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();

 

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读