【已解决】使用easy-poi实现导入excel功能,报错 getWriter() has already been called for this response] with root cause
程序员文章站
2022-05-01 21:54:37
...
@[TOC]( [已解决]getWriter() has already been called for this response] with root cause)
【已解决】使用easy-poi实现导入excel功能,报错 getWriter() has already been called for this response] with root cause,影响导出excel
在项目中,需要导出查询数据为excel,在本地使用idea测试没有问题。但在测试环境,相同代码,报错** “getWriter() has already been called for this response] with root cause” **,影响下载功能。
【未彻底解决该问题】报错仍然没有解决,在研究中,但已经解决无法下载的问题。
报错截图
分析报错
通过对报错信息的分析,关键就是流信息重复开
解决方法
原来代码
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws Exception {
OutputStream outputStream=null;
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//response.flushBuffer();
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
throw new ServiceException(ResponseEnum.EXCEPTION_FILE_IO);
}finally {
try {
if(outputStream!=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
修改后的代码
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws Exception {
OutputStream outputStream=null;
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//-------------重点------------
response.flushBuffer();
//--------------重点----------
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
throw new ServiceException(ResponseEnum.EXCEPTION_FILE_IO);
}finally {
try {
if(outputStream!=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
请看注释"-----重点--------"部分