从数据库中导出csv数据,并压缩成zip下载

直接上代码:

 // 导出多个工作组的csv
    public ActionForward ExportAllDataToCsv(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                HttpServletResponse response){
        String batchNo=request.getSession().getAttribute("batchNo").toString();

        List pcParams = paichanDataManager.getListByBatchNo(batchNo);
        List<String> fileNames=new ArrayList<String>();
        String Date=new SimpleDateFormat("yyyyMMddHHmm").format(new Date());//文件名時間戳
        String zipName="paichan-"+Date;
        File tempFile = null;
        
        for(int i=0;i<pcParams.size();i++){
            ICsvMapWriter writer = null;
            PaichanParam pcparam = (PaichanParam)pcParams.get(i);
            
            fileNames.add(pcparam.getWrkgrpCode());
            Map param=new HashMap();
            param.put("iv_version_id", pcparam.getVersionId());
            param.put("iv_factory_id", pcparam.getFactoryId());
            param.put("iv_dept", pcparam.getDeptCode());
            param.put("iv_wrkgrp", pcparam.getWrkgrpCode());
            List results = paichanDataManager.queryDataByExcel(param);
            String[] listCols = param.get("o_title").toString().split(",");
            String[] listFlds = param.get("o_title_field").toString().split(",");
            
            //String  fullName = request.getRealPath("upload")+File.separator+pcparam.getWrkgrpCode()+".csv";   //指定导出的文件目录
            String userName=getUserName(request);
            File file = new File("/tmp/upload/"+userName);  
            if(!file.exists()){
                file.mkdirs();
            }
           
            String  fullName ="/tmp/upload/"+userName+File.separator+pcparam.getWrkgrpCode()+".csv";
            try {
                tempFile = new File(fullName);  
               
                OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fullName),Charset.forName("GBK"));
                
                writer = new CsvMapWriter(out,CsvPreference.EXCEL_PREFERENCE);
                writer.writeHeader(listCols);
                for(int j=0;j<results.size();j++){
                    Map<String, Object> values=(Map<String, Object>)results.get(j);
                    for(int k=0;k<listFlds.length;k++){
                        Object val=values.get(listFlds[k]);
                        if (val instanceof java.sql.Timestamp) {
                            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            val = f.format(val);
                            values.put(listFlds[k], val);
                        }
                    }
                    writer.write(values, listFlds);
   
                }
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        //如果文件不為空
        if(!fileNames.isEmpty())
        zipCsv(request,response,fileNames,zipName);
       
        
        return null;
    }



public static void zipCsv(HttpServletRequest request, HttpServletResponse response, List<String> filename,String zipName){
        ZipOutputStream zos = null;
        InputStream  fis = null;
        try{
            //如果不以压缩包的形式导出,下面的代码就完全没有必要要了。上面的部分,系统会以CSV格式导出到本地。
             response.setContentType("application/zip");
             response.reset();
             response.setCharacterEncoding("GBK");
             response.setHeader("Content-Disposition","attachment; filename=" + new String(zipName.getBytes("GBK"),"ISO8859-1")+".zip" );
             //文件压缩
             int leng=0;
             String userName = (String) request.getSession().getAttribute("User");
             zos = new ZipOutputStream(response.getOutputStream());   
             //zos =new ZipOutputStream(new File("/tmp/upload/"+zipName+".zip"));
             //zos.setEncoding("GBK");
             File delFile = null;
             //获取用户名称
             
       for(int l = 0;l<filename.size();l++){  
             // fis = new  FileInputStream(request.getRealPath("upload/")+File.separator+filename.get(l) + ".csv");
          
           fis = new  FileInputStream("/tmp/upload/"+userName+File.separator+filename.get(l)+".csv");
           
              ZipEntry z1 = new ZipEntry(filename.get(l)+".csv");
              
              //z1.setUnixMode(644);//linux 下设置,防止乱码
             // zos.setComment(zipName);
              zos.putNextEntry(z1);
              byte[] b = new byte[1024];
             while((leng = fis.read(b))!=-1){
                 zos.write(b,0,leng);
                 }
            
             fis.close();
         }
             zos.close();
             File file = new File("/tmp/upload/"+userName);  
             if (file.exists()) {
                 // 为文件时调用删除文件方法  
               for(int l = 0;l<filename.size();l++){
               delFile = new File("/tmp/upload/"+userName+File.separator+filename.get(l) + ".csv");
               delFile.delete();
           }
                 file.delete();
             }
    }  catch(Exception e){
        e.printStackTrace();
    }
        finally {
            if(zos!=null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                zos = null;
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fis = null;
            }
          }
        
        }



注释:这里压缩文件用的是java.util.zip包,而没有openzip.jar,openzipjar包在linux环境上一直压缩的是空压缩包,倘若有人遇到这样的问题,请改用java自带的zip压缩

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值