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
While it is true that it is more usual to write a binary attachment using a servlet rather than a jsp, it is certainly possible to write a binary attachment from a jsp. And the advantage of doing so is that you need not worry about configuring web.xml or reloading your application. That can be an important consideration, depending on your web server environment.
Here is an example jsp that uses poi to send a binary attachment to a browser.
The important trick is to make sure there is only one line with all your imports and other directives prior to the "<%" that begins your code. Otherwise, the jsp may output some initial new lines and corrupt your output.
Also, I suggest you always set the content length. Some browsers will not work correctly if it is not set. That is why I first output my spreadsheet to a byte array, so I could set the length prior to actually sending the data.
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:Now, to download it, invoke the servlet by its URL instead of the JSP file.
if you want to download don,t use hssf workbook it will slower and consume more space use apche poi 3.17 beta-1
For Pdf Use Itext