欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【已解决】使用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” **,影响下载功能。
【未彻底解决该问题】报错仍然没有解决,在研究中,但已经解决无法下载的问题。

报错截图

【已解决】使用easy-poi实现导入excel功能,报错 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();
            }
        }
    }

请看注释"-----重点--------"部分

报错问题未解决,研究中,谢谢

相关标签: Java java