java 動態生成多個excel檔案打成zip包供使用者下載

NO IMAGE

最近專案中有這樣的需求:就是選擇頁面上的多條記錄,每一條記錄生成一個excel,然後把所有選擇記錄生成的excel打包成zip包供使用者下載。 

後臺程式碼:

  1. /** 
  2.      * 批量匯出Excel 
  3.      * @return 
  4.      * @throws DBException 
  5.      */  
  6.     @SuppressWarnings(“unchecked”)  
  7.     public String batchExport() throws DBException{  
  8.           
  9.         @SuppressWarnings(“unused”)  
  10.         List<String> chkList = this.checkValueToList();//獲取核取方塊的值  
  11.         List<File> srcfile=new ArrayList<File>();  
  12.           
  13.         SimpleDateFormat sdf = new SimpleDateFormat(“yyyyMMddHHSS”);  
  14.         String path = sdf.format(new Date());  
  15.           
  16.         String serverPath = request.getSession().getServletContext().getRealPath(“/”);  
  17.         //在伺服器端建立資料夾  
  18.         File file = new File(serverPath path);  
  19.         if(!file.exists()){  
  20.             file.mkdir();  
  21.         }  
  22.   
  23.         for (int i = 0; i < chkList.size(); i  ){  
  24.             String t[] = chkList.get(i).split(“\\|”);  
  25.             LhjcOrgSelfQuery lhjcunioncheckquery = new LhjcOrgSelfQuery();  
  26.             lhjcunioncheckquery.setChnoticeId(t[0]);  
  27.             lhjcunioncheckquery.setOrgId(t[1]);  
  28.             lhjcunioncheckquery.setSelfChTempId(t[2]);  
  29.             List<Map<String,String>> reportViews=commonService.getObjectPages(“ExportLhjcunioncheckresultReportView”, lhjcunioncheckquery);  
  30.             String orgName = (String)commonService.get2Object(“getUnioncheckOrgName”, t[1]);  
  31.             //生成excel的名字  
  32.             String templateName = nyear “深圳市黨政機關資訊保安檢查結果-” (orgName==null?”未知單位”:orgName);  
  33.               
  34.             /** 表頭陣列 */  
  35.             String[] headArray = new String[]{“編碼”,”檢查項名稱”,”   檢查內容   “,”考核型別”,”   檢查結果   “,”   備註   “,”權重”,”得分”};  
  36.               
  37.             /** 欄位名陣列 */  
  38.             String[] fieldArray = new String[]{“CHECKITEMCODE”,”CHITEMNAME”,”CHCONTENT”,”REPORTTYPE”,”QUESTDESC”,”CHITEMDESC”,”REPORTWEIGHT”,”UNIONSCORE”};  
  39.               
  40.             ExportUtils exportUtils = new ExportUtils();  
  41.             exportUtils.setTitle(templateName);  
  42.             exportUtils.setHead(templateName);  
  43.             exportUtils.setHeadArray(headArray);  
  44.             exportUtils.setFieldArray(fieldArray);  
  45.             try {  
  46.                 HttpServletResponse response = ServletActionContext.getResponse();  
  47.                   
  48.                 SimpleDateFormat sfm = new SimpleDateFormat(“yyyy-MM-dd”);  
  49.                 String filename = templateName   “_”   sfm.format(new Date());  
  50.                   
  51.                 String encodedfileName = new String(filename.getBytes(), “GBK”);  
  52.                 //將生成的多個excel放到伺服器的指定的資料夾中  
  53.                 FileOutputStream out = new FileOutputStream(serverPath path “\\” encodedfileName “.xls”);  
  54.                   
  55.                 if(fileType.indexOf(“,”) != -1){  
  56.                     fileType = StringUtils.substringBefore(fileType, “,”);  
  57.                 }  
  58.                 response.setHeader(“Content-Disposition”, ” filename=\””   encodedfileName   “.”   fileType   “\””);  
  59.                   
  60.                 //匯出excel  
  61.                 if (“xls”.equals(fileType) || “xlsx”.equals(fileType)) {  
  62.                     exportUtils.exportExcel(reportViews,fileType,out);  
  63.                 } else if(“doc”.equals(fileType) || “docx”.equals(fileType)){  
  64.                     exportUtils.exportWord(reportViews, fileType, out);  
  65.                 } else if(“pdf”.equals(fileType)){  
  66.                     exportUtils.exportPdf(reportViews, out);  
  67.                 }   
  68.                   
  69.                 srcfile.add(new File(serverPath path “\\” encodedfileName “.xls”));  
  70.                   
  71.             } catch (Exception e) {  
  72.                 e.printStackTrace();  
  73.             }   
  74.         }  
  75.         //將伺服器上存放Excel的資料夾打成zip包  
  76.         File zipfile = new File(serverPath path “.zip”);  
  77.         this.zipFiles(srcfile, zipfile);  
  78.         //彈出下載框供使用者下載  
  79.         this.downFile(ServletActionContext.getResponse(),serverPath, path “.zip”);  
  80.         return null;  
  81.     }  
  82.   
  83.   
  84.     /** 
  85.      * 將多個Excel打包成zip檔案 
  86.      * @param srcfile 
  87.      * @param zipfile 
  88.      */  
  89.     public void zipFiles(List<File> srcfile, File zipfile) {    
  90.         byte[] buf = new byte[1024];    
  91.         try {    
  92.             // Create the ZIP file    
  93.             ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));    
  94.             // Compress the files    
  95.             for (int i = 0; i < srcfile.size(); i ) {    
  96.                 File file = srcfile.get(i);    
  97.                 FileInputStream in = new FileInputStream(file);    
  98.                 // Add ZIP entry to output stream.    
  99.                 out.putNextEntry(new ZipEntry(file.getName()));    
  100.                 // Transfer bytes from the file to the ZIP file    
  101.                 int len;    
  102.                 while ((len = in.read(buf)) > 0) {    
  103.                     out.write(buf, 0, len);    
  104.                 }    
  105.                 // Complete the entry    
  106.                 out.closeEntry();    
  107.                 in.close();    
  108.             }    
  109.             // Complete the ZIP file    
  110.             out.close();   
  111.         } catch (IOException e) {    
  112.            e.printStackTrace();  
  113.         }    
  114.     }    
  115.   
  116.   
  117.     public void downFile(HttpServletResponse response,String serverPath, String str) {    
  118.         try {    
  119.             String path = serverPath   str;    
  120.             File file = new File(path);    
  121.             if (file.exists()) {    
  122.                 InputStream ins = new FileInputStream(path);    
  123.                 BufferedInputStream bins = new BufferedInputStream(ins);// 放到緩衝流裡面    
  124.                 OutputStream outs = response.getOutputStream();// 獲取檔案輸出IO流    
  125.                 BufferedOutputStream bouts = new BufferedOutputStream(outs);    
  126.                 response.setContentType(“application/x-download”);// 設定response內容的型別    
  127.                 response.setHeader(    
  128.                         “Content-disposition”,    
  129.                         “attachment;filename=”    
  130.                                   URLEncoder.encode(str, “GBK”));// 設定頭部資訊    
  131.                 int bytesRead = 0;    
  132.                 byte[] buffer = new byte[8192];    
  133.                  //開始向網路傳輸檔案流    
  134.                 while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {    
  135.                    bouts.write(buffer, 0, bytesRead);    
  136.                }    
  137.                bouts.flush();// 這裡一定要呼叫flush()方法    
  138.                 ins.close();    
  139.                 bins.close();    
  140.                 outs.close();    
  141.                 bouts.close();    
  142.             } else {    
  143.                 response.sendRedirect(“../error.jsp”);    
  144.             }    
  145.         } catch (IOException e) {    
  146.             e.printStackTrace();  
  147.         }    
  148.     }  

頁面呼叫:

  1. <script language=”javascript”>  
  2.        <!–   
  3.   
  4. //批量匯出Excel  
  5.        function batchExport(){  
  6.             var chkbox = $(“input[type=’checkbox’][name=’chk’][checked]”);  
  7.             if(chkbox.length == 0){  
  8.                 alert(‘請選擇一條或多條記錄操作!’);  
  9.                 return;  
  10.             }  
  11.             $(“#exportLoading”).html(‘<img src=”${ctx}/images/loading.gif”/>’);  
  12.               
  13.             var checkboxvalue = ”;  
  14.             chkbox.each(function(){  
  15.                 checkboxvalue  = $(this).val() “,”;  
  16.             });  
  17.               
  18.             var nyear = document.getElementById(‘nyear’).value;  
  19.               
  20.             if(checkboxvalue != null && checkboxvalue.length > 0){  
  21.                   
  22.                 checkboxvalue = checkboxvalue.substring(0,checkboxvalue.length-1);  
  23.                 $(‘#checkboxvalue’).val(checkboxvalue);  
  24.                   
  25.                 var form = document.forms[0];  
  26.                 form.action=”${ctx}/core/lhjc/lhjccheckjd/batchExport.action?fileType=xls&chvalue=” checkboxvalue “&nyear=” nyear;  
  27.                 form.submit();  
  28.                 $(“#exportLoading”).empty();  
  29.             }  
  30.               
  31.        }  
  32.           
  33.         –>  
  34.         </script>