zoukankan      html  css  js  c++  java
  • 解决EasyPoi导出excel文件后打开提示格式错误的问题

    excel文件下载成功后打开文件遇到错误

     之前的下载代码:

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
            try {
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                workbook.write(response.getOutputStream());
            } catch (IOException e) {
                try {
                    throw new Exception(e.getMessage());
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    

    改正后的下载代码:

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
            try (OutputStream out = response.getOutputStream())
            {
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                workbook.write(baos);
                response.setHeader("Content-Length", String.valueOf(baos.size()));
                out.write( baos.toByteArray() );
            } catch (IOException e) {
                try {
                    throw new Exception(e.getMessage());
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    

    原因:Debug发现请求头的Content-Length,在未设置的情况在是-1,下载时需重新定义Content-Length

  • 相关阅读:
    超级小白使用pip安装第三方库的正确姿势
    selenium+python自动化测试--解决无法启动IE浏览器及报错问题
    microsoft edge浏览器安装驱动
    超详细MySQL安装及基本使用教程
    Navicat15最新版本破解 亲测可用!!!
    Ubuntu 16.04安装JMeter测试工具
    JMeter_Ubuntu上安装jmeter
    韩国vps推荐-kdatacenter
    全栈之js入门篇
    Web前端之CSS_day5
  • 原文地址:https://www.cnblogs.com/lpq21314/p/13501436.html
Copyright © 2011-2022 走看看