I am trying to return an Excel sheet from my struts2 action class.
I am not sure what result-type should I be using? Has anyone tried to return an excel from strut
If you need to dynamically generate an Excel file using POI/HSSF and return in Struts 2,
JSP
Click to Download
Action Method
@Action(value = "DownloadExcel")
public void download() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String filename = "report.xlsx"; // or any other filename strategy
String mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
String characterEncoding = response.getCharacterEncoding();
if (characterEncoding != null) {
mimeType += "; charset=" + characterEncoding;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.getSheetAt(0);
// Fill out workbook as necessary... (simple example)
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("test");
//...
ServletOutputStream out = null;
try {
out = response.getOutputStream();
workbook.write(out);
workbook.close();
} catch (IOException e) {
log.error("Failed to write into response - fileName=" + filename + ", mimeType=" + mimeType, e);
}
finally {
if (out != null) {
out.flush();
out.close();
}
}
}