Monday, July 15, 2013

Output XLS file to servlet output stream using JExcelAPI

Here's a quick way (although not the best one) to stream an Excel file generated by JExcelAPI (http://jexcelapi.sourceforge.net/). I'm using the servlet output stream in this case.

HttpServletResponse response = getContext().getResponse();

ServletOutputStream sos = response.getOutputStream();

WritableWorkbook workbook = Workbook.createWorkbook(sos);
WritableSheet sheet = workbook.createSheet("Report", 0);
sheet.addCell(new Label(1, 1, "asdfasdfasdf"));

response.setContentType("application/vnd.ms-excel");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "inline; filename=report-.xls");

workbook.write();
workbook.close();
sos.close();

No comments: