首页 > 解决方案 > 发生“流关闭”异常

问题描述

最近我正在开发一个将数据导出到excel的代码。我使用 apache POI 来开发这个功能。

请考虑以下代码。

public static void prepareDateForCSVGeneration(List<DataList> dataList,HttpServletResponse response)
            throws CashBookingInquiryServiceApplicationException {

         try (ServletOutputStream out = response.getOutputStream()) {
              XSSFWorkbook workbook = new XSSFWorkbook();
              //below method creates headers and rows
              convertToExcel(workbook, dataList);
              response.setContentType("text/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
                workbook.write(out);
                out.flush();
            } catch (IOException exception) {
                System.out.println("Exceptin in excel "+exception.getMessage());
                exception.printStackTrace() ;
            }
    }

一切正常,意味着excel文件下载成功,但之后在控制台中抛出异常:

Exceptin in excel Stream is closed
[err] java.io.IOException: Stream is closed
[err]     at com.ibm.ws.http.channel.internal.outbound.HttpOutputStreamImpl.validate(HttpOutputStreamImpl.java:213)
[err]     at [internal classes]

不知道为什么会这样。

我提到了 [ java IO Exception: Stream Closed

但我没有找到任何具体的解决方案。你能建议做什么吗?提前致谢。

标签: javaspring-mvcioapache-poijava-io

解决方案


推荐阅读