Create an excel file for users to download using Apache POI

user571099 picture user571099 · Jun 27, 2012 · Viewed 92.6k times · Source

I'm able to create an excel file using apache poi. however, i want users to be able to download this as a "true" excel file. the effect i want to achieve would be to have a popup box allowing the user to download the file. this is similar to using

<%@ page contentType="application/vnd.ms-excel" pageEncoding="ISO-8859-1"%> 
<%response.setHeader("Content-Disposition", "attachment;filename=myfile.xls"); %>

with one critical exception: i must allow the user to download a proper excel file. i read somewhere the above code simply says to the client that the server is sending an excel file

Answer

BalusC picture BalusC · Jun 27, 2012

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.