您的位置:首页 > 编程语言 > Java开发

java excel打包成zip 导入zip先解压

2018-01-11 10:45 796 查看
话不多说,先讲需求,再上代码。

需求1:数据库查询出数据 导出并封装成excel  再打包成zip 并下载下来 

代码:1):数据查出来不说了。

    2):封装成excel 

    3):将excel打包成zip

    4):下载

    5)   :下载完成后删除文件夹以及文件  我把它放在了第四步里面

备注:需要导入的包没贴出来 具体需要哪些包写的时候有提示

   

      public void  exportExcel(){
String path = request.getSession().getServletContext().getRealPath("/ExcelData");
File file = new File(path);  
if(!file.exists()){  
file.mkdirs();  
}  
2)this.service.exportExcel(this.getRequest(),this.getResponse(),path);
try {
/*********将excel打包成zip**********/
3)this.service.craeteZipPath(path);

       /*******下载zip*******/
        4) service.downLoadExcelZip(getResponse(),getRequest(),path);
} catch (IOException e) {
e.printStackTrace();
}
}

public Map exportExcel(String startDate,String serialNo,String plugName,
HttpServletRequest request, HttpServletResponse response,String path){
/*********按条件查询数据**********/
List<Map> personals = // 这里是查数据的方法
try{
WritableWorkbook book = Workbook.createWorkbook(new File(path+"/"+"excelData"+".xls"));
       WritableCellFormat normalFormat = new WritableCellFormat(
            new WritableFont(WritableFont.createFont("宋体"), 10,
         
      WritableFont.NO_BOLD, false,
         
      UnderlineStyle.NO_UNDERLINE));
        /**设置表头*/
        normalFormat.setBackground(jxl.format.Colour.GREY_25_PERCENT);
      normalFormat.setBorder(Border.ALL, BorderLineStyle.THICK,
          jxl.format.Colour.BLACK);
      normalFormat.setAlignment(Alignment.CENTRE);
      normalFormat.setWrap(true);
      WritableSheet sheet = book.createSheet("导出数据" , 0 );
      int j=0;
      List<String> list = new ArrayList();
      for (Map map : personals) {
      for(Object key :map.keySet()){
      sheet.addCell(new Label( j , 0 , key+"", normalFormat ));
      list.add(String.valueOf(key));
      j++;
      }
      break;

        WritableCellFormat cellFormat = new WritableCellFormat(
             
new WritableFont(WritableFont.createFont("宋体"), 10,
                WritableFont.NO_BOLD, false,
                UnderlineStyle.NO_UNDERLINE));
        cellFormat.setBackground(jxl.format.Colour.WHITE);
        cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,
        jxl.format.Colour.BLACK);
        cellFormat.setAlignment(Alignment.RIGHT);
        WritableCellFormat format = new WritableCellFormat(
             
new WritableFont(WritableFont.createFont("宋体"), 10,
           
      WritableFont.NO_BOLD, false,
           
      UnderlineStyle.NO_UNDERLINE));
        format.setBackground(jxl.format.Colour.WHITE);
        format.setBorder(Border.ALL, BorderLineStyle.THIN,
          jxl.format.Colour.BLACK);
        format.setAlignment(Alignment.CENTRE);
        format.setVerticalAlignment(VerticalAlignment.CENTRE);
        format.setWrap(true);
        int row = 1;
        try {
  for (Map map : personals) { 
  j=0;
 for(String key : list){ 
   sheet.addCell(new Label(j, row, String.valueOf(map.get(key)), format));
           j++;
 }  
 row++;
        }
} catch (Exception e) {
e.printStackTrace();
}
        book.write();                                                                                                                                                 
        book.close();
}catch (Exception e) {
        e.printStackTrace();
    }
return null;
}

       /**
* 生成zip文件  zip文件名字是ExcelDataZip.zip
* @param path
* @throws IOException
*/
public String craeteZipPath(String path) throws IOException{  

        ZipOutputStream zipOutputStream = null;  

        File file = new File(path+"ExcelDataZip"+".zip");  

        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

        File[] files = new File(path).listFiles();  

        FileInputStream fileInputStream = null;  

        byte[] buf = new byte[1024];  

        int len = 0;  

        if(files!=null && files.length > 0){  

            for(File excelFile:files){
       String fileName = excelFile.getName();  
       fileInputStream = new FileInputStream(excelFile);  
       //放入压缩zip包中;  
    zipOutputStream.putNextEntry(new ZipEntry(fileName));  
           while((len=fileInputStream.read(buf)) >0){  
           
zipOutputStream.write(buf, 0, len);  
           }  
       zipOutputStream.closeEntry();  
       if(fileInputStream != null){  
           fileInputStream.close();  
       }  

            }

        }

        if(zipOutputStream !=null){  

            zipOutputStream.close();  

        }  

        return null;

    } 

   /**

     * 下载excelDataZip

     * @param response

     * @param request

     * @return

     */

    public String downLoadExcelZip(HttpServletResponse response,HttpServletRequest request,String path) {  

        String fileName = "excelDataZip.zip";  

        String realPath=path+"excelDataZip.zip";

        try {  

            File file = new File(realPath); 

            File file2 = new File(path); 

            response.setCharacterEncoding("UTF-8");  

            response.setHeader("Content-Disposition",  

                    "attachment; filename=" + new String(fileName.getBytes("ISO8859-1"), "UTF-8"));  

            response.setContentLength((int) file.length());  

            response.setContentType("application/zip");

            FileInputStream fis = new FileInputStream(file);  

            BufferedInputStream buff = new BufferedInputStream(fis);  

            byte[] b = new byte[1024];

            long k = 0;

            OutputStream myout = response.getOutputStream();

            // 开始循环下载  

            while (k < file.length()) {  

                int j = buff.read(b, 0, 1024);  

                k += j;  

                myout.write(b, 0, j);  

            }  

            myout.flush();  

            buff.close();  

            file.delete();

            deleteFile(file2);//删除新建的文件夹

        } catch (Exception e) {  

            System.out.println(e);  

        }  

        return null;  

    } 

   /**

     * 递归删除文件夹  

     * @param file

     */

    public void deleteFile(File file) {  

       if(file.exists()){

          if(file.isFile()){//判断是否是文件  

              file.delete();

          }else if(file.isDirectory()){//否则如果它是一个目录  

              File[] files = file.listFiles();//声明目录下所有的文件 files[];  

       for(int i = 0;i < files.length;i ++){//遍历目录下所有的文件  

          this.deleteFile(files[i]);//把每个文件用这个方法进行迭代  

       }  

          file.delete();//删除文件夹  

      }  

      }else{  

        System.out.println("所删除的文件不存在");  

      }  

    }

//最后贴一个 解压zip的

/**
* 解压zip
* @param zipFile 解压的zip文件
* @param descDir  目标地址
*/
public String zipToExcel(File zipFile,String descDir)throws IOException{
String fileName="";
    File pathFile = new File(descDir);
    if(!pathFile.exists()){
       pathFile.mkdirs();
     }
   //解压zip文件中有中文目录或者中文文件
   ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
   for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
     ZipEntry entry = (ZipEntry)entries.nextElement();
     String zipEntryName = entry.getName();
     fileName = zipEntryName;
     InputStream in = zip.getInputStream(entry);
     String outPath = descDir+"/"+zipEntryName;
     OutputStream out = new FileOutputStream(outPath);
     byte[] buf1 = new byte[1024];
     int len;
     while((len=in.read(buf1))>0){
     out.write(buf1,0,len); 
     }
     in.close();
     out.close();
   }
System.out.println("******************解压完毕********************");
return fileName;

  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel java zip