5

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.

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.