I'm using Apache POI and extending Springs AbstractExcelView to create Excel sheets.
public class ExcelSpreadsheetView extends AbstractExcelView {
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//GET POSITIONS TO LOOP THROUGH FROM MODEL
@SuppressWarnings("unchecked")
List<Position> positions = (List<Position>) model.get("positions");
int lastRow = 0;
mySheet = wb.createSheet("SHEET1");
myRow = mySheet.createRow(lastRow);
myCell = myRow.createCell(0);
//loop through positions
for (int p = 0; p < positions.size(); p++) {
myRow = mySheet.createRow(lastRow);
myCell = myRow.createCell(0);
myCell.setCellValue(new HSSFRichTextString(positions.get(p).getPositionName()));
lastRow++;
}
//response stuff goes here, but I shouldnt need it
}
I can successfully create a sheet when I have the following code after all the POI code:
response.setHeader("Content-Disposition", "inline;filename=\"spreadsheet.xls\"");
response.setContentType("APPLICATION/OCTET-STREAM");
OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
Thing is, in none of the examples online do people include the writing out to the OutputStream or setting the ContentType, it seems like the AbstractExcelView handles that.
When I comment out the 6 lines above, it tries to create the file (I can see in console logs that its parsing all the data correctly), but when I go to open the file, Excel fails to open it and displays the following:
"File Error: data may have been lost."
I know my code works as is, I'm just trying to do it the right way and follow what everyone else is doing online. I don't think I have code in the OutputStream or ContentType stuff, but it only works if I do.
Any help much appreciated!