1 /** 2 * excel表格直接下载 3 */ 4 public static void exportExcelByDownload(HSSFWorkbook wb,HttpServletResponse httpServletResponse,String fileName) throws Exception { 5 //响应类型为application/octet- stream情况下使用了这个头信息的话,那就意味着不想直接显示内容 6 httpServletResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); 7 8 //attachment为以附件方式下载 9 httpServletResponse.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode( 10 fileName + ".xls", 11 "utf-8")); 12 /** 13 * 代码里面使用Content-Disposition来确保浏览器弹出下载对话框的时候。 14 * response.addHeader("Content-Disposition","attachment");一定要确保没有做过关于禁止浏览器缓存的操作 15 */ 16 httpServletResponse.setHeader("Cache-Control", "No-cache"); 17 httpServletResponse.flushBuffer(); 18 19 wb.write(httpServletResponse.getOutputStream()); 20 wb.close(); 21 } 22 23 /** 24 * excel以文件的形式导出 25 * @throws Exception 26 */ 27 public static void exportExcelByFile(HSSFWorkbook wb,String fileName,String path) throws Exception{ 28 29 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 30 wb.write(stream); 31 FileOutputStream outputStream = new FileOutputStream(path + fileName); 32 outputStream.write(stream.toByteArray()); 33 stream.close(); 34 outputStream.close(); 35 36 }
原文地址:https://www.cnblogs.com/wang-yaz/p/10785647.html
时间: 2024-11-29 06:01:12