Friday, August 8, 2008

JSP: Save As Pop Up in JSP Another way

Place the following code segment in your scriptlet tag of JSP page.

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=abc.xls");
ServletOutputStream so = response.getOutputStream();
String filename = "c:\\reports\myreport.xls";
String mimetype = "application/vnd.ms-excel";
ByteArrayOutputStream output = new ByteArrayOutputStream();
InputStream in = new BufferedInputStream(new FileInputStream(filename));
byte bytebuff[] = new byte[500];
for(int lengthread = 0; (lengthread = in.read(bytebuff)) != -1;){
output.write(bytebuff, 0, lengthread);
}
byte data[] = output.toByteArray();
response.setContentType(mimetype);
so.write(data);
in.close();
so.close();


WHERE:


abc.xls
is the file name that will automatically appear in the file Name box of SaveAs Pop Up.

and

filename
is the actual file path on your server machine. It may be outside of your WEB-INF directory.

No comments: