poi多文件压缩导出

前言:这里先介绍我今天要做的功能,先查询数据库导出一个excel然后把它和里面记录相关的图片查出来打成一个压缩包在页面!excel里面的一条记录对应一个图片文件夹!

效果:
这里写图片描述

勾选想要导出的数据,点击导出按钮,然后弹出下载的zip文件
这里写图片描述

打开zip压缩包,效果如图:
这里写图片描述

第一步:所需jar
 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>

第二步 :整理需要压缩的数据

  • 导出excel的方式很简单,从数据库查询出来一个map,只需要更改mybatis的
resultType="java.util.HashMap"   

即可。我们在dao层得到一个List<Map<String, Object>> 这样结构
的返回类型! 然后:
Map<String, Object> map = new HashMap<>(); map.put("list", maps);

就是把你得到的返回结果塞入到map里。下面会用到!!

  • 然后我们从数据库查找需要压缩的图片数据,经过遍历处理后我得到了一个嵌套的

    map Map<String,Map<String,Object>> ,对于里层的map,key是图片的名字,value是图片的路径,我这里都是上传到七牛后的网络路径!外层的map是对图片进行的归类,同一保单的图片放一起,key就是保单号!

  • 数据都整理好了接下来就亮出我写的工具类吧—希望大家觉得好用的话给点个赞!!
package com.jy.common.utils.poi;

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 压缩导出
 *
 * @author xiaotian
 * @create 
 */
public class ZipExportUtils {
    /**
     * 导出excel
     *
     * @param params
     * @param bomanPath
     * @param xlsName
     */
    public static void export(Map<String, Object> params,  Map<String,Map<String,Object>> allImage, String bomanPath, String xlsName, HttpServletResponse response) {
        XLSTransformer transformer = new XLSTransformer();
        InputStream is = null;
        try {
            is = new BufferedInputStream(ZipExportUtils.class.getResourceAsStream(bomanPath));
            Workbook workbook = transformer.transformXLS(is, params);
            zipImage(allImage, workbook, xlsName, response, is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件
     *
     * @param
     * @param response
     */
    public static void zipImage( Map<String,Map<String,Object>> allImage, Workbook workbook, String xlsName, HttpServletResponse response, InputStream bookis) {
        setResponseHeader(response, "理赔申请记录");
        HttpURLConnection conn = null;
        ZipOutputStream zos = null;
        InputStream in = null;
        BufferedInputStream bis = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(response.getOutputStream());
            for (String policyNo : allImage.keySet()) {
                Map<String, Object> map = allImage.get(policyNo);
                ZipEntry zip = new ZipEntry("保单_"+policyNo+ "/");
                zos.putNextEntry(zip);
                for (String s : map.keySet()) {
                    String value = (String) map.get(s);
                    URL url = new URL(value);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(6000);
                    in = conn.getInputStream();
                    //创建ZIP实体,并添加进压缩包
                    ZipEntry zipEntry = new ZipEntry( "保单_"+policyNo+"/"+s + ".png");
                    zos.putNextEntry(zipEntry);
                    zip(in, bis, zos);
                }
            }
            //把excel写进压缩文件流
            byte[] bufs = new byte[1024 * 10];
            zos.putNextEntry(new ZipEntry(xlsName + ".xlsx"));
            ByteArrayOutputStream tempos = new ByteArrayOutputStream();
            workbook.write(tempos);
            ByteArrayInputStream swapStream = new ByteArrayInputStream(tempos.toByteArray());
            bis = new BufferedInputStream(swapStream, 1024 * 10);
            int read = 0;
            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                zos.write(bufs, 0, read);
            }
            zos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bookis != null) bookis.close();
                zos.closeEntry();
                if (null != zos) zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读写
     *
     * @return
     * @author
     * @date 2015年7月21日
     */
    public static void zip(InputStream in, BufferedInputStream bis, ZipOutputStream zos) {
        try {
            byte[] bufs = new byte[1024 * 10];
            bis = new BufferedInputStream(in, 1024 * 10);
            int read = 0;
            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                zos.write(bufs, 0, read);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != in) in.close();
                if (null != bis) bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 设置响应头
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            response.reset();// 清空输出流
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("GB2312"), "8859_1")
                    + ".zip");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

这里说明一下这个工具类,入口方法为export,你在controller层调用这个方法的时候,传递的params就是我们要导出excel的map,allImage就是图片数据,bomanPath,是excel模版的路径 .
/excelTemplate/claimExcel.xlsx 这里写图片描述
具体路径看你的项目!这里记得把模版里面填入表达式:
这里写图片描述
xlsName为excel的文件名字,response就是controller层传递过来的输出流用!export方法主要是先生成一个workbook,然后传递下去,把图片和excel压缩到一块。

代码比较简单,这里就不做过多讲解,大家可以根据自己的实际情况的改用!不足的地方也可以留言指出!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章