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

来源:互联网 发布:淘宝女装精修图教程 编辑:程序博客网 时间:2024/06/10 08:37
  1. 参考文献:http://blog.csdn.net/youyou_yo/article/details/52180937

  2. /** 
  3.      * 批量导出Excel 
  4.      * @return 
  5.      * @throws DBException 
  6.      */  
  7.     @SuppressWarnings("unchecked")  
  8.     public String batchExport() throws DBException{  
  9.           
  10.         @SuppressWarnings("unused")  
  11.         List<String> chkList = this.checkValueToList();//获取复选框的值  
  12.         List<File> srcfile=new ArrayList<File>();  
  13.           
  14.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHSS");  
  15.         String path = sdf.format(new Date());  
  16.           
  17.         String serverPath = request.getSession().getServletContext().getRealPath("/");  
  18.         //在服务器端创建文件夹  
  19.         File file = new File(serverPath+path);  
  20.         if(!file.exists()){  
  21.             file.mkdir();  
  22.         }  
  23.   
  24.         for (int i = 0; i < chkList.size(); i++ ){  
  25.             String t[] = chkList.get(i).split("\\|");  
  26.             LhjcOrgSelfQuery lhjcunioncheckquery = new LhjcOrgSelfQuery();  
  27.             lhjcunioncheckquery.setChnoticeId(t[0]);  
  28.             lhjcunioncheckquery.setOrgId(t[1]);  
  29.             lhjcunioncheckquery.setSelfChTempId(t[2]);  
  30.             List<Map<String,String>> reportViews=commonService.getObjectPages("ExportLhjcunioncheckresultReportView", lhjcunioncheckquery);  
  31.             String orgName = (String)commonService.get2Object("getUnioncheckOrgName", t[1]);  
  32.             //生成excel的名字  
  33.             String templateName = nyear+"深圳市党政机关信息安全检查结果-"+(orgName==null?"未知单位":orgName);  
  34.               
  35.             /** 表头数组 */  
  36.             String[] headArray = new String[]{"编码","检查项名称","   检查内容   ","考核类型","   检查结果   ","   备注   ","权重","得分"};  
  37.               
  38.             /** 字段名数组 */  
  39.             String[] fieldArray = new String[]{"CHECKITEMCODE","CHITEMNAME","CHCONTENT","REPORTTYPE","QUESTDESC","CHITEMDESC","REPORTWEIGHT","UNIONSCORE"};  
  40.               
  41.             ExportUtils exportUtils = new ExportUtils();  
  42.             exportUtils.setTitle(templateName);  
  43.             exportUtils.setHead(templateName);  
  44.             exportUtils.setHeadArray(headArray);  
  45.             exportUtils.setFieldArray(fieldArray);  
  46.             try {  
  47.                 HttpServletResponse response = ServletActionContext.getResponse();  
  48.                   
  49.                 SimpleDateFormat sfm = new SimpleDateFormat("yyyy-MM-dd");  
  50.                 String filename = templateName + "_" + sfm.format(new Date());  
  51.                   
  52.                 String encodedfileName = new String(filename.getBytes(), "GBK");  
  53.                 //将生成的多个excel放到服务器的指定的文件夹中  
  54.                 FileOutputStream out = new FileOutputStream(serverPath+path+"\\"+encodedfileName+".xls");  
  55.                   
  56.                 if(fileType.indexOf(",") != -1){  
  57.                     fileType = StringUtils.substringBefore(fileType, ",");  
  58.                 }  
  59.                 response.setHeader("Content-Disposition"" filename=\"" + encodedfileName + "." + fileType + "\"");  
  60.                   
  61.                 //导出excel  
  62.                 if ("xls".equals(fileType) || "xlsx".equals(fileType)) {  
  63.                     exportUtils.exportExcel(reportViews,fileType,out);  
  64.                 } else if("doc".equals(fileType) || "docx".equals(fileType)){  
  65.                     exportUtils.exportWord(reportViews, fileType, out);  
  66.                 } else if("pdf".equals(fileType)){  
  67.                     exportUtils.exportPdf(reportViews, out);  
  68.                 }   
  69.                   
  70.                 srcfile.add(new File(serverPath+path+"\\"+encodedfileName+".xls"));  
  71.                   
  72.             } catch (Exception e) {  
  73.                 e.printStackTrace();  
  74.             }   
  75.         }  
  76.         //将服务器上存放Excel的文件夹打成zip包  
  77.         File zipfile = new File(serverPath+path+".zip");  
  78.         this.zipFiles(srcfile, zipfile);  
  79.         //弹出下载框供用户下载  
  80.         this.downFile(ServletActionContext.getResponse(),serverPath, path+".zip");  
  81.         return null;  
  82.     }  
  83.   
  84.   
  85.     /** 
  86.      * 将多个Excel打包成zip文件 
  87.      * @param srcfile 
  88.      * @param zipfile 
  89.      */  
  90.     public void zipFiles(List<File> srcfile, File zipfile) {    
  91.         byte[] buf = new byte[1024];    
  92.         try {    
  93.             // Create the ZIP file    
  94.             ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));    
  95.             // Compress the files    
  96.             for (int i = 0; i < srcfile.size(); i++) {    
  97.                 File file = srcfile.get(i);    
  98.                 FileInputStream in = new FileInputStream(file);    
  99.                 // Add ZIP entry to output stream.    
  100.                 out.putNextEntry(new ZipEntry(file.getName()));    
  101.                 // Transfer bytes from the file to the ZIP file    
  102.                 int len;    
  103.                 while ((len = in.read(buf)) > 0) {    
  104.                     out.write(buf, 0, len);    
  105.                 }    
  106.                 // Complete the entry    
  107.                 out.closeEntry();    
  108.                 in.close();    
  109.             }    
  110.             // Complete the ZIP file    
  111.             out.close();   
  112.         } catch (IOException e) {    
  113.            e.printStackTrace();  
  114.         }    
  115.     }    
  116.   
  117.   
  118.     public void downFile(HttpServletResponse response,String serverPath, String str) {    
  119.         try {    
  120.             String path = serverPath + str;    
  121.             File file = new File(path);    
  122.             if (file.exists()) {    
  123.                 InputStream ins = new FileInputStream(path);    
  124.                 BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面    
  125.                 OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
  126.                 BufferedOutputStream bouts = new BufferedOutputStream(outs);    
  127.                 response.setContentType("application/x-download");// 设置response内容的类型    
  128.                 response.setHeader(    
  129.                         "Content-disposition",    
  130.                         "attachment;filename="    
  131.                                 + URLEncoder.encode(str, "GBK"));// 设置头部信息    
  132.                 int bytesRead = 0;    
  133.                 byte[] buffer = new byte[8192];    
  134.                  //开始向网络传输文件流    
  135.                 while ((bytesRead = bins.read(buffer, 08192)) != -1) {    
  136.                    bouts.write(buffer, 0, bytesRead);    
  137.                }    
  138.                bouts.flush();// 这里一定要调用flush()方法    
  139.                 ins.close();    
  140.                 bins.close();    
  141.                 outs.close();    
  142.                 bouts.close();    
  143.             } else {    
  144.                 response.sendRedirect("../error.jsp");    
  145.             }    
  146.         } catch (IOException e) {    
  147.             e.printStackTrace();  
  148.         }    
  149.     }  
页面调用:

  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>  
阅读全文
1 0
原创粉丝点击