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