【问题标题】:apache POI - get size of generated excel fileapache POI - 获取生成的excel文件的大小
【发布时间】:2015-03-23 05:37:05
【问题描述】:

我正在使用Apache POI 在我的 spring mvc 应用程序中生成 excel 文件。这是我的春季行动:

 @RequestMapping(value = "/excel", method = RequestMethod.POST)
public void companyExcelExport(@RequestParam String filter, @RequestParam String colNames, HttpServletResponse response) throws IOException{
    XSSFWorkbook workbook = new XSSFWorkbook();
    //code for generate excel file
    //....

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
    workbook.write(response.getOutputStream());

    response.setHeader("Content-Length", "" + /* How can i access workbook size here*/);
}

我使用了XSSFWorkbook,因为我需要生成 Excel 2007 格式。但我的问题是XSSFWorkbook 没有getBytesgetSize 方法。如何计算生成的 xlsx 文件的大小?

编辑:我在这里使用了ByteArrayOutputStream

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(response.getOutputStream()); 
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());

【问题讨论】:

  • 将工作簿写入 ByteArrayOutputStream,从中获取大小,然后将字节写入真实流?
  • 我尝试了您的解决方案,但浏览器仍然不显示文件大小。
  • 请更新问题,说明您如何使用 ByteArrayOutputStream
  • 在写响应之前设置标题。并使用setContentLength()进行设置。

标签: java spring-mvc servlets apache-poi export-to-excel


【解决方案1】:

正如@JB Nizet 所说:在编写响应之前设置标题。

所以你应该做的是:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
workbook.write(response.getOutputStream()); 

请参考这个答案here,因为它描述了如何将 ByteArrayOutputStream 与 HSSFWorkbook 一起使用。

希望对您有所帮助。

【讨论】:

  • 好的,这行得通。谢谢。但是,如果没有 ByteArrayOutputStream 和 XSSFWorkbook ,有没有办法做到这一点?
猜你喜欢
  • 2019-02-02
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
相关资源
最近更新 更多