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?
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.
You can also try the JasperReport
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
精彩评论