excel打包成zip提供使用者下載 要用到ant.jar ant.jar
/** * zip下載 @author yzh * @return * @throws Exception */ public String downzip() throws Exception { this.checkYM(); Common c = new Common(); HttpServletResponse response = ServletActionContext.getResponse(); List<Company> companyList = new ArrayList<Company>();//公司列表 Company company = (Company) session.get("company");// 取得目前使用者的公司對象 if (company.getMonadmin().equals(1)) {// 如果使用者所屬的公司為管理公司 companyList = this.unitService.findMonCompany();// 取得所有受管理的公司列表 if (this.companyid == null) {// 頁面請求的公司id如果為空白,則查詢目前使用者所屬公司 this.companyid = companyList.get(0).getUnitid(); } } if(!companyList.isEmpty()){ List<String> namelist = new ArrayList<String>(); List<byte[]> bytelist = new ArrayList<byte[]>(); for (Company company1 : companyList) { List<Object> list = getCollectExcelBytes(company1);//取得byte[]資料與檔案名稱的方法 String basename = (String) list.get(0); byte[] buf = (byte[]) list.get(1); namelist.add(basename); bytelist.add(buf); } String filename = "所有公司_合約額及收款情況"+ "_" + year + "年" + month + "月_" + c.getStrDate(); getZip(filename,namelist,bytelist,response);//zip打包處理的方法 } return null; } /** * @author yzh * 取得 合約及收款報表 byte[]數組及檔案名稱 */ private List<Object> getCollectExcelBytes(Company company) throws Exception { List<Object> list = new ArrayList<Object>(); this.checkYM();//年月驗證類,略 Common c = new Common();//時間處理類,略 String filename = "合約額及收款情況_" + company.getNameshort() + "_" + year + "年" + month + "月_" + c.getStrDate()+".xls"; ByteArrayOutputStream os = new ByteArrayOutputStream();// 取得輸出資料流 WritableWorkbook wbook = collectService.exportCollectExcel( company.getUnitid(), this.year, this.month, os);//取得excel 對象方法,略 wbook.write(); // 寫入檔案 wbook.close(); list.add(filename); list.add(os.toByteArray()); return list; } /** * @author yzh 取得動態取得zip檔案 * @param filename zip檔案初始名 * @param list 要打包檔案名稱集合 * @param tytess 要打包檔案byte[]數組集合 * @param response HttpServletResponse * @throws Exception */ public void getZip(String filename,List<String> list,List<byte[]> tytess,HttpServletResponse response) throws Exception { byte[] buffer = new byte[1024]; filename = new String(filename.getBytes(),"iso8859-1"); // 清空response response.reset(); // 設定response的Header response.setHeader("Content-disposition", "attachment; filename=" + filename + ".zip");// 設定輸出檔案頭 /*使用ant.jar中的org.apache.tools.zip.*; 不要使用java.util.zip.*; 避免中文亂碼問題 主要原因是因為java.util.zip使用編碼和WinZip和WinRar使用的不同, 解壓後,使用java.util.zip.*有中文的話會出現亂碼 */ ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); for (int j = 0; j < list.size(); j++) { String name = list.get(j); byte[] bytes = tytess.get(j); if(name!=null && bytes!=null){//非空 InputStream fis = new ByteArrayInputStream(bytes); out.putNextEntry(new ZipEntry(name.toString())); int len; while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); out.closeEntry(); fis.close(); } } out.flush(); out.close(); }