gpt4 book ai didi

java - apache POI - 获取生成的 excel 文件的大小

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:16 25 4
gpt4 key购买 nike

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

 @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());

最佳答案

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

所以你应该做的是:

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

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

希望对您有所帮助。

关于java - apache POI - 获取生成的 excel 文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28122474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com