java 动态生成多个excel文件打成zip包供用户下载

最近项目中有这样的需求:就是选择页面上的多条记录,每一条记录生成一个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, 08192)) != -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>  

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值