Pls help: 2 issues on downloading excel file thru servlet
When I wrote a servlet to generate and export a excel report, I encountered 2 problems.
The fisrt is the downloaded file is named by the url and in html format, but not I indicated filename in the code by setting the reponse header.
The second, if I delay to save the downloaded file for a long time(e.g. 2 hours) after the browser's prompt, the saving action will be failed because the browser cache for the downloaded file has been losed.
The following is my code. Who can help me? Thanks!
String filename= "Report.xls";
response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+filename);
wwb = Workbook.createWorkbook(response.getOutputStream());
//write report data into wwb
wwb.write();
wwb.close();
[856 byte] By [
teozhanga] at [2007-10-2 17:05:14]

Sorry.
As you see, I have indicated Report.xls as the file name, but when Internet Explorer prompt me to Open/Save the downloaded file, its name is changed into DownloadServlet.html. Save DownloadServlet.html and open it with Microsoft Excel, you can find its data is correct. How can I automatically save the file as Report.xls?
Hi,
I had similar problems a while ago. This is a copy&paste from my code that works just fine. I hope it helps.
Nick
ByteArrayOutputStream out = new ByteArrayOutputStream();
workSheet.write (out);
try
{
ServletOutputStream sos = response.getOutputStream();
response.setContentType ("application/octet-stream");
response.setContentLength (out.size());
response.setHeader ("Content-Disposition", "inline; filename=\"Report.xls\"");
ByteArrayInputStream in = new ByteArrayInputStream (out.toByteArray());
byte [] buffer = new byte [4 * 1024]; // 4KB buffer is enough
int read = 0;
while ( (read = in.read(buffer)) != -1) {
sos.write(buffer, 0, read);
}
in.close();
sos.flush();
sos.close();
}
catch (Exception e) {
e.printStackTrace();
}
> The second, if I delay to save the downloaded file
> for a long time(e.g. 2 hours) after the browser's
> prompt, the saving action will be failed because the
> browser cache for the downloaded file has been
> losed.
My guess is that it fails because the HTTPSession & the HttpServletResponse have both expired. Usually the default session timeout is set to 30 minutes. You can easily change that value, depending on the container you're using.
Honestly, I don't see why someone would wait 2 hours to click on "Save as".. :-)
Nick