How to make an excel file (and txt file) filled with data from a table on the html page in a servlet and send it to a browser?
3 Answers
Firstly you need to generate the actual content (e.g. an Excel file). Apache POI can generate Excel spreadsheets easily. Alternatively you can simply generate a .csv file.
Secondly you need to return it with the correct content type. See this Javaworld tip for more info. Briefly, you set the content type on the response thus.
// MIME type for Excel res.setContentType( "application/vnd.ms-excel" ); will set an Excel MIME type. text/csv would work if you generate a CSV file.
You may also want to set the filename for downloading.
res.setHeader("Content-disposition", "attachment; filename=Example.xls" ); uses the content-disposition header to achieve this.
3 Comments
Ravi Wallau
I have both POI and it had two problems - it was slow to open a big file (20 MB) and it could not evaluate NPV. I decided to try JExcel, and it was really fast, REALLY fast, the model to read the cells was way easier to use than one in POI, and it could do NPV. I always tend to thing that Apache stuff is always best than the "one guy doing something", but on this case I think it was the opposite.
Brian Agnew
Interesting. Don't forget I'm talking about creating files (although one of my methods for file creation in POI is to load/modify an existing file). I will check out JExcel, though.
Brian Agnew
OH. Do you mean JExcel or JExcelAPI ?