java导出多个excel文件并以压缩包的形式下载

需求:用户在前台页面点击批量导出单据,实现下载对应批量单据excel文件压缩包功能

实现思路:先利用java poi工具类包中的Workbook类生成填充excel对象,然后用Workbook中的write方法将excel对象写入到输入流InputStream中,创建压缩文件对象ZipEntry,然后创建ZipOutputStream压缩包输出流对象,因为是要实现前台页面下载功能,所以压缩包流对象要包装response.getOutputStream后台响应输出流,调用ZipOutputStream压缩包流putNextEntry()方法,将文件压缩对象ZipEntry放入到ZipOutputStream压缩包输出流中,然后将excel输入流InputStream写到ZipOutputStream压缩包输出流中,循环进行上述操作,即可实现批量单据excel打包下载

代码部分:

TemplateExportParams params = new TemplateExportParams(templatePath);
//List<File> srcfile = new ArrayList<File>();  //声明一个集合,用来存放多个Excel文件路径及名称
    String filename = (String) mapData.get("filename");
    //生成excel对象
    Workbook workbook = ExcelExportUtil.exportExcel(params, mapData);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    workbook.write(bos);
    byte[] barray = bos.toByteArray();
    InputStream is = new ByteArrayInputStream(barray);
    is.close();
    ZipEntry zipEntry = new ZipEntry(filename);
    Map map = new HashMap();
    map.put("stream",is);
    map.put("zip",zipEntry);
return map;
String pathname=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//File zipfile = new File(pathname);
response.setCharacterEncoding("UTF-8"); // 重点突出
response.setContentType("application/zip");
// 对文件名进行编码处理中文问题
pathname = new String(pathname.getBytes(), StandardCharsets.UTF_8);
//设置前台下载压缩包名
response.setHeader("Content-Disposition", "attachment;filename=" + pathname);
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
byte[] buf = new byte[1024];
try {
    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
    for (int i = 0; i < zipEntry.size(); i++) {
        ZipEntry zipEntryDetail = (ZipEntry)zipEntry.get(i).get("zip");
        InputStream in = (InputStream)zipEntry.get(i).get("stream");
        // Add ZIP entry to output stream.
        out.putNextEntry(zipEntryDetail);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    out.close();

 

 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值