1. 程式人生 > >匯出多級資料到excel並且生成zip壓縮檔案下載

匯出多級資料到excel並且生成zip壓縮檔案下載

為了實現以下如圖的效果

首先:需要的jar包

jxl      生成excel

ant (org.apache.tools.ant) 生成zip壓縮檔案

 

1.建立目錄結構,最後生成壓縮包:

String realPath = request.getServletContext().getRealPath("/");
		  realPath = realPath + "export" + File.separator + "file" + File.separator ;
		  System.out.println(realPath);
		  //TODO 第一部分:地區=========================================================================================================
		  File dq=new File(realPath, "地區");
		  dq.mkdirs();//建立父目錄
		  
		  File province = null;
		  File city = null;
		  File county = null;
		  List<BaseAreaTree> areaList=CacheBaseAreaManager.getTreeByParentCode("-1");
		  List<BaseAreaTree> cityList=null;
		  List<BaseAreaTree> countyList=null;
		  try {
			   for (Iterator iterator = areaList.iterator(); iterator.hasNext();) {
				BaseAreaTree baseAreaTree = (BaseAreaTree) iterator.next();
				province = new File(dq.getPath(),baseAreaTree.getNodeName());
				if(!province.exists()) {
					province.mkdirs();//建立父目錄
				}
				
				
				
				
			}
			
			  
			//TODO 第二部分:學校=========================================================================================================
			  File xx=new File(realPath, "學校");
			  xx.mkdirs();//建立父目錄
			  
			  province = null;
			  city = null;
			  county = null;
			   areaList=CacheBaseAreaManager.getTreeByParentCode("-1");
			   cityList=null;
			   countyList=null;
				  for (Iterator iterator = areaList.iterator(); iterator.hasNext();) {
					BaseAreaTree baseAreaTree = (BaseAreaTree) iterator.next();
					province = new File(xx.getPath(),baseAreaTree.getNodeName());
					if(!province.exists()) {
						province.mkdirs();//建立父目錄
					}
										
					
				}
			  
			  
			  //TODO 完成資料的匯出excel,生成壓縮包============================================================================================================================
			  //注意!:這個zip檔案需要手動生成下,file = new file(".zip")檔案是損壞的,無法識別
			  
			   File zipfile = new File(request.getServletContext().getRealPath("/") + File.separator + "export" + File.separator +  "file.zip");
		        if (!zipfile.exists()) {
		        	zipfile.createNewFile();
		        }
                //建立zip檔案
			        FileOutputStream fOutputStream = new FileOutputStream(zipfile);
			        ZipOutputStream zoutput = new ZipOutputStream(fOutputStream);
			        zoutput.close();
		        
		        File srcdir = new File(request.getServletContext().getRealPath("/") + File.separator + "export" + File.separator + "file");
		        if (!srcdir.exists())  {
		        	System.out.println();
		        }
		        

		        Project prj = new Project();  
		        Zip zip = new Zip();      
		        zip.setProject(prj);  
		        zip.setDestFile(zipfile);  
		        FileSet fileSet = new FileSet();  
		        fileSet.setProject(prj);   
		        fileSet.setDir(srcdir);  
		        //fileSet.setIncludes("**/*.java"); 包括哪些檔案或資料夾 eg:zip.setIncludes("*.java");  
		        //fileSet.setExcludes(...); 排除哪些檔案或資料夾  
		        zip.addFileset(fileSet);            
		        zip.execute();  

			  
			  
		 } catch (Exception e) {
				// TODO: handle exception
			e.printStackTrace();
		}
		  System.out.println("==============================over=================================");
		  
		  

2.獲取資料並且生成excel

 try {
					/*String templatePath=url+"excel/"+title+".xls";
					downloadUrl="/excel/"+title+".xls";*/
				    downloadUrl= downloadUrl + File.separator + title+".xls";
					File ff = new File(downloadUrl);
					if(!ff.exists()) {
						ff.createNewFile();
					}
					
					//查詢baseuser的資料
					List baseUserList = baseAreaManager.getBaseUserList(areaId, level, roleCode);
					
					try{
						WorkbookSettings settings = new WorkbookSettings();  
						settings.setWriteAccess(null);
						WritableWorkbook wwb = Workbook.createWorkbook(ff,settings);
						WritableSheet wws = wwb.createSheet(title, 0);
						WritableFont font = new WritableFont(WritableFont.createFont("宋體"), 12,
								WritableFont.NO_BOLD);
						WritableCellFormat cellFormat = new WritableCellFormat(font,NumberFormats.TEXT);
						WritableFont font1 = new WritableFont(WritableFont.createFont("宋體"), 14,
								WritableFont.NO_BOLD);
						WritableCellFormat cellFormat1 = new WritableCellFormat(font1,NumberFormats.TEXT);
						cellFormat.setWrap(true);
						cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
						cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
						cellFormat1.setWrap(true);
						cellFormat1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						cellFormat1.setAlignment(jxl.format.Alignment.CENTRE);
						cellFormat1.setBorder(Border.ALL, BorderLineStyle.THIN);
						Label label = new Label(0, 0, title, cellFormat1);
						wws.addCell(label);
						//設定Excel表頭 
						String[] titles=new String[]{"序號","姓名","賬號"};
						for (int i = 0; i < titles.length; i++) { 
						Label excelTitle = new Label(i, 1, titles[i], cellFormat1); 
						wws.addCell(excelTitle); 
						}
						
						
						/*for (int i = 0; i < users.size(); i++) {
								Object[] baseUser=(Object[])users.get(i);
								wws.setRowView(i+2, 270);
							wws.addCell(new Label(0, i + 2, "a", cellFormat));
							wws.setColumnView(0, 18);  
							wws.addCell(new Label(1, i + 2, "b", cellFormat));
							wws.setColumnView(1, 18); 
						}*/
						Map<String,Object> map = new HashMap<String, Object>();
						for (int i = 0; i < baseUserList.size(); i++) {
							map = (Map<String, Object>) baseUserList.get(i);
							wws.setRowView(i+2, 270);
							wws.addCell(new Label(0, i + 2, String.valueOf(i+1), cellFormat));
							wws.setColumnView(0, 18);  
							wws.addCell(new Label(1, i + 2, (String) map.get("REALNAME"), cellFormat));
							wws.setColumnView(1, 18);  
							wws.addCell(new Label(2, i + 2, (String) map.get("LOGIN_NAME"), cellFormat));
							wws.setColumnView(2, 18); 
						}
						
						wws.mergeCells( 0 , 0 , 2 , 0 );
						wwb.write();
						wwb.close();
					
				    } catch (Exception e) {
						e.printStackTrace();
					}
			 
					
			}catch (java.io.IOException e) {
				 e.printStackTrace();
			}

3.下載檔案:

try {
			
			  response.setContentType("text/html;charset=UTF-8");
		        request.setCharacterEncoding("UTF-8");
		        BufferedInputStream bis = null;
		        BufferedOutputStream bos = null;

		        String downLoadPath = request.getServletContext().getRealPath("/") + File.separator + "export" + File.separator +  "file.zip";

		        long fileLength = new File(downLoadPath).length();

		        response.setContentType("application/octet-stream");
		        response.setHeader("Content-disposition", "attachment; filename="
		                + new String("賬號.zip".getBytes("utf-8"), "ISO8859-1"));
		        response.setHeader("Content-Length", String.valueOf(fileLength));

		        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		        bos = new BufferedOutputStream(response.getOutputStream());
		        byte[] buff = new byte[2048];
		        int bytesRead;
		        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		            bos.write(buff, 0, bytesRead);
		        }
		        bis.close();
		        bos.close();

		  } catch (Exception e) {
				// TODO: handle exception
		}

其中,注意:

1.因為windows和linux平臺的不同,\或者/儘量使用 File.separator 代替

2.不知為何生成.zip檔案使用File file = new File("a.zip")生成的檔案是錯誤的,可以先手動生成一個

 

具體程式碼:

/**
	   * 生成每個地區的樹狀路徑,並且生成zip檔案
	   */
	  public String exportArea(){
		  String realPath = request.getServletContext().getRealPath("/");
		  realPath = realPath + "export" + File.separator + "file" + File.separator ;
		  System.out.println(realPath);
		  //TODO 第一部分:地區=========================================================================================================
		  File dq=new File(realPath, "地區");
		  dq.mkdirs();//建立父目錄
		  
		  File province = null;
		  File city = null;
		  File county = null;
		  List<BaseAreaTree> areaList=CacheBaseAreaManager.getTreeByParentCode("-1");
		  List<BaseAreaTree> cityList=null;
		  List<BaseAreaTree> countyList=null;
		  try {
			   for (Iterator iterator = areaList.iterator(); iterator.hasNext();) {
				BaseAreaTree baseAreaTree = (BaseAreaTree) iterator.next();
				province = new File(dq.getPath(),baseAreaTree.getNodeName());
				if(!province.exists()) {
					province.mkdirs();//建立父目錄
				}
				if(baseAreaTree.getNodeCode().length() == 3){
					//if("北京市".equals(baseAreaTree.getNodeName())){

					//說明是省
					//TODO 建立管理員
						exportBaseUser(baseAreaTree.getNodeName()+"管理員", province.getPath(), "role.areaManager",baseAreaTree.getId(),1);
						exportBaseUser(baseAreaTree.getNodeName()+"稽核員", province.getPath(), "role.areaAuditor",baseAreaTree.getId(),1);
						exportBaseUser(baseAreaTree.getNodeName()+"視察員", province.getPath(), "role.areaObserve",baseAreaTree.getId(),1);
					
					
					cityList = CacheBaseAreaManager.getTreeByParentCode(baseAreaTree.getNodeCode());
					for (Iterator iterator2 = cityList.iterator(); iterator2
							.hasNext();) {
						BaseAreaTree baseAreaTree2 = (BaseAreaTree) iterator2.next();
						city = new File(province.getPath(),baseAreaTree2.getNodeName());
						if(!city.exists()) {
							city.mkdirs();//建立父目錄
						}
						
						if(baseAreaTree2 != null && baseAreaTree2.getNodeCode().length() == 6){
							
								//說明是市
								
								//TODO 建立管理員
							exportBaseUser(baseAreaTree2.getNodeName()+"管理員", city.getPath(), "role.areaManager",baseAreaTree2.getId(),2);
							exportBaseUser(baseAreaTree2.getNodeName()+"稽核員", city.getPath(), "role.areaAuditor",baseAreaTree2.getId(),2);
							exportBaseUser(baseAreaTree2.getNodeName()+"視察員", city.getPath(), "role.areaObserve",baseAreaTree2.getId(),2);
							
								countyList = CacheBaseAreaManager.getTreeByParentCode(baseAreaTree2.getNodeCode());
								if(countyList != null && countyList.size() > 0){
									
										for (Iterator iterator3 = countyList.iterator(); iterator3
												.hasNext();) {
											BaseAreaTree baseAreaTree3 = (BaseAreaTree) iterator3.next();
											county = new File(city.getPath(),baseAreaTree3.getNodeName());
											county.mkdirs();//建立縣一級
											if(!county.exists()) {
												county.mkdirs();//建立父目錄
											}
											
											//TODO 建立管理員
											exportBaseUser(baseAreaTree3.getNodeName()+"管理員", county.getPath(), "role.areaManager",baseAreaTree3.getId(),3);
											exportBaseUser(baseAreaTree3.getNodeName()+"稽核員", county.getPath(), "role.areaAuditor",baseAreaTree3.getId(),3);
											exportBaseUser(baseAreaTree3.getNodeName()+"視察員", county.getPath(), "role.areaObserve",baseAreaTree3.getId(),3);
											
										}
									
								}
						
						}
						
						
					}
					
				}
				//}//////
				
				
				
			}
			
			  
			//TODO 第二部分:學校=========================================================================================================
			  File xx=new File(realPath, "學校");
			  xx.mkdirs();//建立父目錄
			  
			  province = null;
			  city = null;
			  county = null;
			   areaList=CacheBaseAreaManager.getTreeByParentCode("-1");
			   cityList=null;
			   countyList=null;
				  for (Iterator iterator = areaList.iterator(); iterator.hasNext();) {
					BaseAreaTree baseAreaTree = (BaseAreaTree) iterator.next();
					province = new File(xx.getPath(),baseAreaTree.getNodeName());
					if(!province.exists()) {
						province.mkdirs();//建立父目錄
					}
					if(baseAreaTree.getNodeCode().length() == 3){
						//if("北京市".equals(baseAreaTree.getNodeName())){

						//說明是省
						//TODO 建立管理員
							exportBaseUser(baseAreaTree.getNodeName()+"管理員", province.getPath(), "role.schoolManager",baseAreaTree.getId(),1);
						
						
						cityList = CacheBaseAreaManager.getTreeByParentCode(baseAreaTree.getNodeCode());
						for (Iterator iterator2 = cityList.iterator(); iterator2
								.hasNext();) {
							BaseAreaTree baseAreaTree2 = (BaseAreaTree) iterator2.next();
							city = new File(province.getPath(),baseAreaTree2.getNodeName());
							if(!city.exists()) {
								city.mkdirs();//建立父目錄
							}
							
							if(baseAreaTree2 != null && baseAreaTree2.getNodeCode().length() == 6){
								
									//說明是市
									
									//TODO 建立管理員
								exportBaseUser(baseAreaTree2.getNodeName()+"管理員", city.getPath(), "role.schoolManager",baseAreaTree2.getId(),2);
								
									countyList = CacheBaseAreaManager.getTreeByParentCode(baseAreaTree2.getNodeCode());
									if(countyList != null && countyList.size() > 0){
										
											for (Iterator iterator3 = countyList.iterator(); iterator3
													.hasNext();) {
												BaseAreaTree baseAreaTree3 = (BaseAreaTree) iterator3.next();
												county = new File(city.getPath(),baseAreaTree3.getNodeName());
												county.mkdirs();//建立縣一級
												if(!county.exists()) {
													county.mkdirs();//建立父目錄
												}
												
												//TODO 建立管理員
												exportBaseUser(baseAreaTree3.getNodeName()+"管理員", county.getPath(), "role.schoolManager",baseAreaTree3.getId(),3);
												
											}
										
									}
								
							}
							
							
						}
						
					}
					//}//
					
					
				}
			  
			  
			  //TODO 完成資料的匯出excel,生成壓縮包============================================================================================================================
			  //注意!:這個zip檔案需要手動生成下,file = new file(".zip")檔案是損壞的,無法識別
			  
			   File zipfile = new File(request.getServletContext().getRealPath("/") + File.separator + "export" + File.separator +  "file.zip");
		        if (!zipfile.exists()) {
		        	zipfile.createNewFile();
		        }
                //建立zip檔案
			        FileOutputStream fOutputStream = new FileOutputStream(zipfile);
			        ZipOutputStream zoutput = new ZipOutputStream(fOutputStream);
			        zoutput.close();
		        
		        File srcdir = new File(request.getServletContext().getRealPath("/") + File.separator + "export" + File.separator + "file");
		        if (!srcdir.exists())  {
		        	System.out.println();
		        }
		        

		        Project prj = new Project();  
		        Zip zip = new Zip();      
		        zip.setProject(prj);  
		        zip.setDestFile(zipfile);  
		        FileSet fileSet = new FileSet();  
		        fileSet.setProject(prj);   
		        fileSet.setDir(srcdir);  
		        //fileSet.setIncludes("**/*.java"); 包括哪些檔案或資料夾 eg:zip.setIncludes("*.java");  
		        //fileSet.setExcludes(...); 排除哪些檔案或資料夾  
		        zip.addFileset(fileSet);            
		        zip.execute();  

			  
			  
		 } catch (Exception e) {
				// TODO: handle exception
			e.printStackTrace();
		}
		  System.out.println("==============================over=================================");
		  
		  //下載zip檔案
		  fileDownBaseUser();
		  return null;
	  }
	  
	  /**
	   * 資料寫入excel
	   * @param title
	   * @param downloadUrl
	   * @param roleCode
	   * @param areaId
	   * @param level
	   */
	  public void exportBaseUser(String title,String downloadUrl,String roleCode,String areaId,Integer level){
			 try {
					/*String templatePath=url+"excel/"+title+".xls";
					downloadUrl="/excel/"+title+".xls";*/
				    downloadUrl= downloadUrl + File.separator + title+".xls";
					File ff = new File(downloadUrl);
					if(!ff.exists()) {
						ff.createNewFile();
					}
					
					//查詢baseuser的資料
					List baseUserList = baseAreaManager.getBaseUserList(areaId, level, roleCode);
					
					try{
						WorkbookSettings settings = new WorkbookSettings();  
						settings.setWriteAccess(null);
						WritableWorkbook wwb = Workbook.createWorkbook(ff,settings);
						WritableSheet wws = wwb.createSheet(title, 0);
						WritableFont font = new WritableFont(WritableFont.createFont("宋體"), 12,
								WritableFont.NO_BOLD);
						WritableCellFormat cellFormat = new WritableCellFormat(font,NumberFormats.TEXT);
						WritableFont font1 = new WritableFont(WritableFont.createFont("宋體"), 14,
								WritableFont.NO_BOLD);
						WritableCellFormat cellFormat1 = new WritableCellFormat(font1,NumberFormats.TEXT);
						cellFormat.setWrap(true);
						cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
						cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
						cellFormat1.setWrap(true);
						cellFormat1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						cellFormat1.setAlignment(jxl.format.Alignment.CENTRE);
						cellFormat1.setBorder(Border.ALL, BorderLineStyle.THIN);
						Label label = new Label(0, 0, title, cellFormat1);
						wws.addCell(label);
						//設定Excel表頭 
						String[] titles=new String[]{"序號","姓名","賬號"};
						for (int i = 0; i < titles.length; i++) { 
						Label excelTitle = new Label(i, 1, titles[i], cellFormat1); 
						wws.addCell(excelTitle); 
						}
						
						
						/*for (int i = 0; i < users.size(); i++) {
								Object[] baseUser=(Object[])users.get(i);
								wws.setRowView(i+2, 270);
							wws.addCell(new Label(0, i + 2, "a", cellFormat));
							wws.setColumnView(0, 18);  
							wws.addCell(new Label(1, i + 2, "b", cellFormat));
							wws.setColumnView(1, 18); 
						}*/
						Map<String,Object> map = new HashMap<String, Object>();
						for (int i = 0; i < baseUserList.size(); i++) {
							map = (Map<String, Object>) baseUserList.get(i);
							wws.setRowView(i+2, 270);
							wws.addCell(new Label(0, i + 2, String.valueOf(i+1), cellFormat));
							wws.setColumnView(0, 18);  
							wws.addCell(new Label(1, i + 2, (String) map.get("REALNAME"), cellFormat));
							wws.setColumnView(1, 18);  
							wws.addCell(new Label(2, i + 2, (String) map.get("LOGIN_NAME"), cellFormat));
							wws.setColumnView(2, 18); 
						}
						
						wws.mergeCells( 0 , 0 , 2 , 0 );
						wwb.write();
						wwb.close();
					
				    } catch (Exception e) {
						e.printStackTrace();
					}
			 
					
			}catch (java.io.IOException e) {
				 e.printStackTrace();
			}
	 }
	  
	  /**
	   * 檔案的下載
	   */
	  public void fileDownBaseUser(){
		  try {
			
			  response.setContentType("text/html;charset=UTF-8");
		        request.setCharacterEncoding("UTF-8");
		        BufferedInputStream bis = null;
		        BufferedOutputStream bos = null;

		        String downLoadPath = request.getServletContext().getRealPath("/") + File.separator + "export" + File.separator +  "file.zip";

		        long fileLength = new File(downLoadPath).length();

		        response.setContentType("application/octet-stream");
		        response.setHeader("Content-disposition", "attachment; filename="
		                + new String("賬號.zip".getBytes("utf-8"), "ISO8859-1"));
		        response.setHeader("Content-Length", String.valueOf(fileLength));

		        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		        bos = new BufferedOutputStream(response.getOutputStream());
		        byte[] buff = new byte[2048];
		        int bytesRead;
		        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		            bos.write(buff, 0, bytesRead);
		        }
		        bis.close();
		        bos.close();

		  } catch (Exception e) {
				// TODO: handle exception
		}
	  }