javaダイナミックに複数のエクセルファイルを作成し、zipパッケージにしてユーザーにダウンロードします。

8291 ワード

最近のプロジェクトの中でこのような需要があります。つまり、ページ上の複数の記録を選択して、一つの記録ごとにエクセルを作成して、選択記録で生成されたエクセルをすべてzipパッケージに包装してユーザーにダウンロードします。
バックグラウンドコード:

/**
	 *     Excel
	 * @return
	 * @throws DBException
	 */
	@SuppressWarnings("unchecked")
	public String batchExport() throws DBException{
		
		@SuppressWarnings("unused")
		List<String> chkList = this.checkValueToList();//       
		List<File> srcfile=new ArrayList<File>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHSS");
        String path = sdf.format(new Date());
        
        String serverPath = request.getSession().getServletContext().getRealPath("/");
        //          
        File file = new File(serverPath+path);
        if(!file.exists()){
        	file.mkdir();
        }

		for (int i = 0; i < chkList.size(); i++ ){
			String t[] = chkList.get(i).split("\\|");
			LhjcOrgSelfQuery lhjcunioncheckquery = new LhjcOrgSelfQuery();
			lhjcunioncheckquery.setChnoticeId(t[0]);
			lhjcunioncheckquery.setOrgId(t[1]);
			lhjcunioncheckquery.setSelfChTempId(t[2]);
			List<Map<String,String>> reportViews=commonService.getObjectPages("ExportLhjcunioncheckresultReportView", lhjcunioncheckquery);
			String orgName = (String)commonService.get2Object("getUnioncheckOrgName", t[1]);
			//  excel   
			String templateName = nyear+"               -"+(orgName==null?"    ":orgName);
			
			/**      */
			String[] headArray = new String[]{"  ","     ","          ","    ","          ","        ","  ","  "};
			
			/**       */
			String[] fieldArray = new String[]{"CHECKITEMCODE","CHITEMNAME","CHCONTENT","REPORTTYPE","QUESTDESC","CHITEMDESC","REPORTWEIGHT","UNIONSCORE"};
			
			ExportUtils exportUtils = new ExportUtils();
			exportUtils.setTitle(templateName);
			exportUtils.setHead(templateName);
			exportUtils.setHeadArray(headArray);
			exportUtils.setFieldArray(fieldArray);
			try {
				HttpServletResponse response = ServletActionContext.getResponse();
				
				SimpleDateFormat sfm = new SimpleDateFormat("yyyy-MM-dd");
				String filename = templateName + "_" + sfm.format(new Date());
				
				String encodedfileName = new String(filename.getBytes(), "GBK");
				//      excel             
				FileOutputStream out = new FileOutputStream(serverPath+path+"\\"+encodedfileName+".xls");
				
				if(fileType.indexOf(",") != -1){
					fileType = StringUtils.substringBefore(fileType, ",");
				}
				response.setHeader("Content-Disposition", " filename=\"" + encodedfileName + "." + fileType + "\"");
				
				//  excel
				if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
					exportUtils.exportExcel(reportViews,fileType,out);
				} else if("doc".equals(fileType) || "docx".equals(fileType)){
					exportUtils.exportWord(reportViews, fileType, out);
				} else if("pdf".equals(fileType)){
					exportUtils.exportPdf(reportViews, out);
				} 
				
				srcfile.add(new File(serverPath+path+"\\"+encodedfileName+".xls"));
				
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		//       Excel      zip 
		File zipfile = new File(serverPath+path+".zip");
		this.zipFiles(srcfile, zipfile);
		//          
		this.downFile(ServletActionContext.getResponse(),serverPath, path+".zip");
		return null;
	}


	/**
	 *    Excel   zip  
	 * @param srcfile
	 * @param zipfile
	 */
	public void zipFiles(List<File> srcfile, File zipfile) {  
        byte[] buf = new byte[1024];  
        try {  
            // Create the ZIP file  
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));  
            // Compress the files  
            for (int i = 0; i < srcfile.size(); i++) {  
                File file = srcfile.get(i);  
                FileInputStream in = new FileInputStream(file);  
                // Add ZIP entry to output stream.  
                out.putNextEntry(new ZipEntry(file.getName()));  
                // Transfer bytes from the file to the ZIP file  
                int len;  
                while ((len = in.read(buf)) > 0) {  
                    out.write(buf, 0, len);  
                }  
                // Complete the entry  
                out.closeEntry();  
                in.close();  
            }  
            // Complete the ZIP file  
            out.close(); 
        } catch (IOException e) {  
           e.printStackTrace();
        }  
    }  


	public void downFile(HttpServletResponse response,String serverPath, String str) {  
        try {  
            String path = serverPath + str;  
            File file = new File(path);  
            if (file.exists()) {  
                InputStream ins = new FileInputStream(path);  
                BufferedInputStream bins = new BufferedInputStream(ins);//          
                OutputStream outs = response.getOutputStream();//       IO   
                BufferedOutputStream bouts = new BufferedOutputStream(outs);  
                response.setContentType("application/x-download");//   response       
                response.setHeader(  
                        "Content-disposition",  
                        "attachment;filename="  
                                + URLEncoder.encode(str, "GBK"));//         
                int bytesRead = 0;  
                byte[] buffer = new byte[8192];  
                 //            
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {  
                   bouts.write(buffer, 0, bytesRead);  
               }  
               bouts.flush();//        flush()    
                ins.close();  
                bins.close();  
                outs.close();  
                bouts.close();  
            } else {  
                response.sendRedirect("../error.jsp");  
            }  
        } catch (IOException e) {  
        	e.printStackTrace();
        }  
    }
ページの呼び出し:

<script language="javascript">
       <!-- 

//    Excel
       function batchExport(){
       		var chkbox = $("input[type='checkbox'][name='chk'][checked]");
			if(chkbox.length == 0){
				alert('            !');
				return;
			}
			$("#exportLoading").html('<img src="${ctx}/images/loading.gif"/>');
			
			var checkboxvalue = '';
			chkbox.each(function(){
				checkboxvalue += $(this).val()+",";
			});
			
			var nyear = document.getElementById('nyear').value;
			
			if(checkboxvalue != null && checkboxvalue.length > 0){
				
				checkboxvalue = checkboxvalue.substring(0,checkboxvalue.length-1);
				$('#checkboxvalue').val(checkboxvalue);
				
				var form = document.forms[0];
				form.action="${ctx}/core/lhjc/lhjccheckjd/batchExport.action?fileType=xls&chvalue="+checkboxvalue+"&nyear="+nyear;
			    form.submit();
			    $("#exportLoading").empty();
			}
			
       }
		
		-->
		</script>