导出多级数据到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
		}
	  }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值