Return HSSFWorkbook to client through HttpServletResponse

2.8k views Asked by At

My Excel file seems to be generated but the function doesn't return anything:

@RequestMapping(value = "/excel", method = RequestMethod.POST, consumes = APPLICATION_JSON, produces = "application/vnd.ms-excel")
public void generateExcelExport(@RequestBody String rawContentParameters, final HttpServletRequest request, final HttpServletResponse response) throws FunctionalError, TechnicalError, IOException {        

        for (JsonNode personNode : rootNode) {
            if (personNode instanceof ObjectNode) {
                ObjectNode object = (ObjectNode) personNode;
                object.remove("reportKey");
            }
        }
        rawContentParameters = rootNode.toString();

        ReportParameter reportParameters = new ReportParameter(reportCode);
        HSSFWorkbook workbook = null;

        try {
            workbook = exportExcelService.getFile(reportParameters, rawContentParameters);
        } catch (TechnicalError e1) {
            redirectToErrorPage(request, response, rawContentParameters, Constants.ERR_BAD_REQUEST);
        }
        try {                
            if (workbook != null) {
                workbook.write(response.getOutputStream());     
            }
            response.flushBuffer();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=stuff");
        }
}

What's wrong with it? Even though the return parameter is void, I read that the response should make the download possible.

2

There are 2 answers

3
rangalo On

You are just setting response headers and not sending the response.

Here is a link which sends a any file as response.

http://balusc.blogspot.de/2007/07/fileservlet.html

UPDATE:

Here is how you can write to response directly from HSSWorkbook. So replace the last part with the following.

    HSSFWorkbook wb = getWorkbook(); // I think you already have a workbook
    OutputStream out = response.getOutputStream();
    try {
       wb.write(out);
    }       
    catch (IOException ioe) { 

// handle exception
      }
0
Sviatoslav Fedechko On

method = RequestMethod should be GET.