JavaWeb导出Excel问题小计
注意,要在写入response.getOutputStream()输出流前设置response相关配置,否则无法写入response配置
进入如response.setHeader源码,可知当response的outputstream有数据后便不可以设置response其他配置
正确代码,可如下
@RequestMapping("/export") public void export(HttpServletResponse response) throws Exception { ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); String fileName = excelService.exportExcel(outputStream); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//一定在response设置后再写入数据 response.getOutputStream().write(outputStream.toByteArray()); System.out.println("导出成功"); }