views:

380

answers:

3

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  A: 

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.

Brian Agnew
thanks! it's just what i've wanted
michal
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.
Ravi Wallau
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 ?
Brian Agnew
+1  A: 

You can also try the JasperReport

Steve Zhang
+1  A: 

As an alternative to using a library to generate an Excel file (in which case I would recommend looking at JExcel), you can generate a CSV file, if you have Excel installed it probably will use it to open this type of file.

CSV = Comma Separated Values

Ravi Wallau