通过HttpServletResponse将HSSFWorkbook返回给客户端

时间:2015-06-16 12:36:30

标签: java servlets poi-hssf

我的Excel文件似乎已生成,但该函数未返回任何内容:

@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");
        }
}

它出了什么问题?即使返回参数为void,我也会读到response应该可以下载。

2 个答案:

答案 0 :(得分:0)

您只是设置响应标头而不是发送响应。

这是一个发送任何文件作为响应的链接。

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

更新:

以下是您可以直接从HSSWorkbook写回复的方法。所以用以下内容替换最后一部分。

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

// handle exception
      }

答案 1 :(得分:0)

method = RequestMethod应该是GET。