java導出excel 瀏覽器直接下載或者或以文件形式導出


 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM