We can use servlet to export information in excel format. The code for this purpose may be as below:
String folder = "/excels/";
Three parameters have been sent using request as per requirement.fileNameToShow contains the value for the name of the file to save in client side
String fileNameToShow=request.getParameter("fileName");String dbName=request.getParameter("dbName");
String query=request.getParameter("query");
String file_name = folder;
System.out.println("Report Name: " + file_name);
try {
ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] bytes = null;
try {
ExcelHelper exlHelper = new ExcelHelper();
bytes = exlHelper.createExcell(getServletConfig().getServletContext().getRealPath(file_name), query, dbName);
response.setHeader("Content-Disposition", "inline;filename="+fileNameToShow+".xls");
response.setContentType("application/vnd.ms-excel");
response.setContentLength(bytes.length);
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();
mailMessage = mailMessage + ". REPORT produced successfully";
} catch (Exception e) {
// display stack trace in the browser
logger.error(e);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
response.setContentType("text/plain");
response.getOutputStream().print("Could not display report temporarily...");
//response.getOutputStream().print(stringWriter.toString());
mailMessage = mailMessage + ".ERROR catched when creating report.";
}
} catch (Exception e) {
System.out.println(e.getMessage());
logger.error(e);
} finally {
logger.info(mailMessage);
}
Expecting your kind suggestion for moderation of the code.