Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Excel document from Spring Controller using Apache POI

I am trying to send a Excel file back to the user. In some way my excel file gets corrupted even if it is empty. When I open the file Excel tells me that the file is corrupt.

If i remove

response.getOutputStream().write(excelService.exportEventsToCSV());

I get an empty excel file.

@RequestMapping(value = "/events/excel", method = RequestMethod.GET)
    public void getEventsAsExcel(HttpServletResponse response) {

        try {

            response.setHeader("Content-disposition", "attachment; filename=test.xls");
            response.getOutputStream().write(excelService.exportEventsToCSV());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

My XML generation is very simple. Just empty document

@Override
public byte[] exportEventsToCSV() {
    try {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet("POI Worksheet");
        HSSFCellStyle cellStyle = workbook.createCellStyle();


        workbook.write(fileOut);

        return workbook.getBytes();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Please any advice. I Was thinking of Springs Excel view but I dont want a view. Just a downloaded file.

like image 962
pethel Avatar asked Dec 16 '22 17:12

pethel


1 Answers

You seem to be doing some very strange things around getting the output out, and I'm fairly sure that workbook.getBytes() isn't returning what you think it is...

I would strongly suggest you change exportEventsToCSV to return the workbook, then you can do the much simpler:

Workbook wb = excelService.exportEventsToCSV();
response.setHeader("Content-disposition", "attachment; filename=test.xls");
wb.write( response.getOutputStream() );

That should work fine and give the end user the kind of thing they were expecting

like image 152
Gagravarr Avatar answered Dec 28 '22 08:12

Gagravarr