300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > easypoi导出excel不设置样式_解决EasyPoi导出excel文件后打开提示格式错误的问题

easypoi导出excel不设置样式_解决EasyPoi导出excel文件后打开提示格式错误的问题

时间:2021-01-21 17:44:50

相关推荐

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。