apache POI - 获取生成的 excel 文件的大小 [英] apache POI - get size of generated excel file
问题描述
我正在使用 Apache POI 在我的 spring mvc 应用程序中生成 excel 文件.这是我的春季行动:
I'm using Apache POI for generating excel file in my spring mvc application. here is my spring action:
@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
没有 getBytes
或 getSize
方法.如何计算生成的 xlsx 文件的大小?
I used XSSFWorkbook
because i need to generate Excel 2007 format. but my problem is XSSFWorkbook
does not have getBytes
or getSize
method. How can i calculate size of generated xlsx file?
我在这里使用了 ByteArrayOutputStream
:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(response.getOutputStream());
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
推荐答案
正如@JB Nizet 所说:在编写响应之前设置标题.
As @JB Nizet said : set the Header before writing the response .
所以你应该做的是:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
workbook.write(response.getOutputStream());
请参考这个答案这里,因为它描述了如何将 ByteArrayOutputStream 与 HSSFWorkbook 一起使用.
and please refer to this answer here , as it describes how to use the ByteArrayOutputStream with the HSSFWorkbook .
希望有所帮助.
这篇关于apache POI - 获取生成的 excel 文件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!