java将多个excel或json文件导出成zip压缩包

一、java导出多个excel压缩成zip包

1.添加依赖

  <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-logging</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
     <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>

2.controller

 /**
     * 导出excel的zip模板
     *
     * @param ids      课程ids
     * @param request  request
     * @param response response
     * @throws IOException io异常
     */
    @GetMapping("exportExcel/{ids}")
    public void exportExcel(@PathVariable @NotBlank(message = "id不能为空") String ids, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams();
        exportParams.setDictHandler(new GlobalExcelDictHandler());
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
        List<EquipmentProduct> equipmentProducts = equipmentProductDao.selectBatchIds(idList);
        List<EquipmentImportExcel> equipmentImportExcels = new ArrayList<>(1);
        EquipmentImportExcel equipmentImportExcel = new EquipmentImportExcel();
        equipmentImportExcels.add(equipmentImportExcel);
        List<InputStream> inputStreams = new ArrayList<>();
        List<String> paths = new ArrayList<>();
        for (EquipmentProduct key : equipmentProducts) {
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, EquipmentImportExcel.class, equipmentImportExcels);
            FileOutputStream fos = new FileOutputStream(path + "/ProductKey_" + key.getProductKey() + ".xlsx");
            workbook.write(fos);
            fos.close();
            inputStreams.add(new FileInputStream(path + "/ProductKey_" + key.getProductKey() + ".xlsx"));
            paths.add("/ProductKey_" + key.getProductKey() + ".xlsx");
        }
        String userAgent = request.getHeader("User-Agent");
        response.setContentType("application/octet-stream;charset=utf-8");
        String fileName = "设备导入模板";
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                //非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
        ZipUtil.zip(response.getOutputStream(), paths.toArray(new String[paths.size()]), inputStreams.toArray(new InputStream[inputStreams.size()]));
        for (EquipmentProduct key : equipmentProducts) {
            File file = new File(path + "/ProductKey_" + key.getProductKey() + ".xlsx");
            if (file.exists()) {
                file.delete();
            }
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

 

二、java导出多个json文件压缩成zip包

/**
     * 导出json的zip模板
     *
     * @param ids      课程ids
     * @param request  request
     * @param response response
     * @throws IOException io异常
     */
    @GetMapping("exportJson/{ids}")
    public void exportJson(@PathVariable @NotBlank(message = "id不能为空") String ids, HttpServletRequest request, HttpServletResponse response) throws IOException {

        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
        List<EquipmentImportJson> equipmentImportJsons = new ArrayList<>(1);
        EquipmentImportJson equipmentImportExcel = new EquipmentImportJson();
        equipmentImportJsons.add(equipmentImportExcel);
        List<EquipmentProduct> equipmentProducts = equipmentProductDao.selectBatchIds(idList);

        List<InputStream> inputStreams = new ArrayList<>();
        List<String> paths = new ArrayList<>();
        for (EquipmentProduct key : equipmentProducts) {
            try {
                String fileName = "ProductKey_"+key.getProductKey()+".json";
                //JsonUtil.exportJson(response, equipmentImportExcels, "/ProductKey_" + key.getProductKey() + ".json");
                String jsonString = JSON.toJSONString(equipmentImportJsons,
                        SerializerFeature.PrettyFormat,
                        SerializerFeature.WriteMapNullValue,
                        SerializerFeature.WriteDateUseDateFormat);

                String fullPath = "/" + fileName;
                File file = new File(fullPath);

                Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
                write.write(jsonString);
                write.flush();
                write.close();

                FileInputStream fis = new FileInputStream(file);
                OutputStream os = new FileOutputStream(path + "/ProductKey_" + key.getProductKey() + ".json");
                byte[] buf = new byte[1024];
                int len = 0;
                while ((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                fis.close();
                os.close();
                inputStreams.add(new FileInputStream(path + "/ProductKey_" + key.getProductKey() + ".json"));
                paths.add("ProductKey_" + key.getProductKey() + ".json");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String userAgent = request.getHeader("User-Agent");
        response.setContentType("application/octet-stream;charset=utf-8");
        String fileName = "设备导入模板";
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                //非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
        ZipUtil.zip(response.getOutputStream(), paths.toArray(new String[paths.size()]), inputStreams.toArray(new InputStream[inputStreams.size()]));
        for (EquipmentProduct key : equipmentProducts) {
            File file = new File(path + "/ProductKey_" + key.getProductKey() + ".json");
            if (file.exists()) {
                file.delete();
            }
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值