Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java apache POI-获取生成的excel文件的大小_Java_Spring Mvc_Servlets_Apache Poi_Export To Excel - Fatal编程技术网

Java apache POI-获取生成的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{

我正在使用它在SpringMVC应用程序中生成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
,因为我需要生成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的情况下,是否还有其他方法可以做到这一点?