Create an excel file for users to download using Apache POI

Do the job in a normal servlet instead of a JSP file. A JSP file is meant for dynamically generating HTML code and is using a character writer for that instead of a binary output stream and would thus only corrupt your POI-generated Excel file which is in essence a binary stream.

So, basically all you need to do in the doGet() method of the servlet is the following:

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=filename.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
// ...
// Now populate workbook the usual way.
// ...
workbook.write(response.getOutputStream()); // Write workbook to response.
workbook.close();

Now, to download it, invoke the servlet by its URL instead of the JSP file.

Leave a Comment