Java apache POI-获取生成的excel文件的大小
我正在使用它在SpringMVC应用程序中生成excel文件。以下是我的春季活动:Java apache POI-获取生成的excel文件的大小,java,spring-mvc,servlets,apache-poi,export-to-excel,Java,Spring Mvc,Servlets,Apache Poi,Export To Excel,我正在使用它在SpringMVC应用程序中生成excel文件。以下是我的春季活动: @RequestMapping(value = "/excel", method = RequestMethod.POST) public void companyExcelExport(@RequestParam String filter, @RequestParam String colNames, HttpServletResponse response) throws IOException{
@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
,因为我需要生成Excel2007格式。但我的问题是XSSFWorkbook
没有getBytes
或getSize
方法。如何计算生成的xlsx文件的大小
编辑:我使用了ByteArrayOutputStream
如下:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(response.getOutputStream());
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
正如@JB Nizet所说:在编写响应之前设置标题 因此,您应该做以下几点:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
response.setHeader("Content-Length", "" + byteArrayOutputStream.size());
workbook.write(response.getOutputStream());
请参考此答案,因为它描述了如何将ByteArrayOutputStream与HSSF工作簿一起使用
希望有帮助 将工作簿写入ByteArrayOutputStream,从中获取大小,然后将字节写入真正的流?我尝试了您的解决方案,但浏览器仍无法显示文件大小。请更新问题,说明如何使用ByteArrayOutputStream在写入响应之前设置标题。并用它来设置。好的,这起作用了。谢谢但是,在没有ByteArrayOutputStream和XSSFWorkbook的情况下,是否还有其他方法可以做到这一点?