当前位置: 首页 > news >正文

java8循环解压zip文件---实现Excel文件数据追加

java8循环追加Excel数据


实际遇到问题:定期获取zip文件,zip文件内有几个固定模板的Excel文件,有的Excel文件可能还包含多个sheet。
有段时间一次性获取到好几个zip包,需要将这些包都解压,并且按照不同的文件名、sheet进行数据整合到一个sheet-Excel中。

![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/2f20c7a800c645f19d2f5e7d8d2edf01.png
在这里插入图片描述

可以在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.xmlbeans</groupId>
    <artifactId>xmlbeans</artifactId>
    <version>5.1.1</version>
</dependency>

import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Collections;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipExcelMerger {

    public static void main(String[] args) {
        // 原始zip文件路径
        String zipDirectory = "path/to/zip/files";
        // 解压zip文件至新的路径
        String outputDirectory = "path/to/output";

        File dir = new File(zipDirectory);
        File[] zipFiles = dir.listFiles((d, name) -> name.endsWith(".zip"));

        if (zipFiles != null) {
            // 升序
            Collections.sort(Arrays.asList(zipDirectory));
            for (File zipFile : zipFiles) {
                unzipAndMerge(zipFile, outputDirectory);
            }
        }
    }

    private static void unzipAndMerge(File zipFile, String outputDirectory) {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (!entry.isDirectory() && (entry.getName().endsWith(".xls") || entry.getName().endsWith(".xlsx"))) {
                    File outputFile = new File(outputDirectory, entry.getName());
                    byte[] buffer = new byte[1024];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        baos.write(buffer, 0, len);
                    }
                    baos.close();

                    if (outputFile.exists()) {
                        mergeExcelFiles(outputFile, new ByteArrayInputStream(baos.toByteArray()));
                    } else {
                        saveToFile(outputFile, new ByteArrayInputStream(baos.toByteArray()));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	private static void mergeExcelFiles(File existingFile, InputStream newFileStream) {
        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = File.createTempFile("temp", ".xlsx");
            Files.copy(existingFile.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            // 读取临时文件
            Workbook existingWorkbook;
            try (InputStream is = new FileInputStream(tempFile)) {
                existingWorkbook = WorkbookFactory.create(is);
            }

            // 读取新文件
            try (Workbook newWorkbook = createWorkbook(newFileStream, existingFile.getName())) {
                for (int i = 0; i < newWorkbook.getNumberOfSheets(); i++) {
                    Sheet newSheet = newWorkbook.getSheetAt(i);
                    Sheet existingSheet = existingWorkbook.getSheet(newSheet.getSheetName());

                    if (existingSheet != null) {
                        for (int j = 1; j <= newSheet.getLastRowNum(); j++) {
                            Row newRow = newSheet.getRow(j);
                            if (newRow != null) {
                                Row existingRow = existingSheet.createRow(existingSheet.getLastRowNum() + 1);
                                copyRow(newRow, existingRow);
                            }
                        }
                    }
                }
            }

            // 将合并后的内容写回临时文件
            try (OutputStream os = new FileOutputStream(tempFile)) {
                existingWorkbook.write(os);
            }

            // 用临时文件替换原文件
            Files.move(tempFile.toPath(), existingFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

	private static Workbook createWorkbook(InputStream inputStream, String fileName) throws IOException {
        if (fileName.endsWith(".xlsx")) {
            return WorkbookFactory.create(inputStream);
        } else if (fileName.endsWith(".xls")) {
            return WorkbookFactory.create(inputStream);
        } else {
            throw new IllegalArgumentException("Unsupported file format: " + fileName);
        }
    }

    private static void saveToFile(File file, InputStream inputStream) {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	private static void copyRow(Row sourceRow, Row targetRow) {
        for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
            Cell sourceCell = sourceRow.getCell(i);
            if (sourceCell != null) {
                Cell targetCell = targetRow.createCell(i);
                targetCell.setCellValue(sourceCell.toString());
            }
        }
    }
}

相关文章:

  • 慧通测控汽车智能座舱测试技术
  • k8s基础知识总结node+pod(上)
  • CSS语言的双向链表
  • 4、pytest常用插件
  • word中指定页面开始添加页码
  • Python(4)Python函数编程性能优化全指南:从基础语法到并发调优
  • Java设计模式之访问者模式
  • 计算机网络 - OSI 七层模型
  • 笔记:分享如何使用github静态页面搭建个人页面
  • 【2025】基于springboot+uniapp的企业培训打卡小程序设计与实现(源码、万字文档、图文修改、调试答疑)
  • 专访成都昭音科技Jackal:AI内容营销助力中企走向全球
  • 鸿蒙学习笔记(2)-国际化配置、ArkTS简述
  • 【Javaweb】b站黑马视频学习笔记(导览)
  • 多模态大模型Qwen 和 Qwen2 的模型结构、训练方式与数据处理对比分析
  • 安卓应用兼容新方案:Android Translation Layer(ATL)
  • 抽奖的诱惑系统注册与登录功能测试报告
  • 机器学习都有哪些算法?
  • 大模型技术在商品归一和商品预测中的应用
  • 5.5 位运算专题:LeetCode 面试题 17.19. 消失的两个数字
  • 重庆邮电大学笔试F021 考纲解析
  • C919上海虹桥-深圳航线开通,东航今年计划再接收10架C919
  • 商务部:对原产于美国、欧盟、台湾地区和日本的进口共聚聚甲醛征收反倾销税
  • 菲律宾中期选举结果揭晓,马科斯与杜特尔特家族重回“权力的游戏”
  • 穆迪下调美国主权信用评级
  • 朝鲜称将在各领域采取反制措施,应对美国敌对挑衅
  • 以军证实空袭也门多个港口