easypoi导出excel不设置样式_解决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

已标记关键词 清除标记
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页