0

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?

1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
OH. Do you mean JExcel or JExcelAPI ?
1

You can also try the JasperReport

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.