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
就像这里:
I used ByteArrayOutputStream
like here:
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屋!