使用 Apache POI 实现 Excel 单元格合并

在日常工作中,Excel 是一个不可或缺的工具,尤其是在处理大量数据时。为了提升数据的可读性和美观性,我们经常需要对 Excel 中的单元格进行合并操作。本文将介绍如何使用 Apache POI 库在 Java 中实现 Excel 单元格的合并,并提供一个现成的工具类供大家使用。

工具类介绍

我们提供了一个名为 ExcelMergeUtility 的工具类,它可以帮助你轻松地合并 Excel 中的单元格。该类支持纵向合并(按行合并)和横向合并(按列合并),并且可以指定需要合并的列。

工具类代码

java 复制代码
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Component
public class ExcelMergeUtility {

    /**
     * 合并Excel中内容相同的单元格
     *
     * @param workbook       工作簿
     * @param sheetName      工作表名称
     * @param columnsToMerge 需要合并的列索引列表
     * @param isRowMerge     是否按行合并(纵向合并)
     * @param isColumnMerge  是否按列合并(横向合并)
     */
    public void mergeCells(Workbook workbook, String sheetName, List<Integer> columnsToMerge,
                           boolean isRowMerge, boolean isColumnMerge) {
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            throw new IllegalArgumentException("工作表 " + sheetName + " 不存在");
        }

        // 记录第一列的合并行数
        int firstColMergeEndRow = 0;

        for (int colIndex : columnsToMerge) {
            for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row currentRow = sheet.getRow(rowIndex);
                if (currentRow == null) continue;

                Cell currentCell = currentRow.getCell(colIndex);
                if (currentCell == null) continue;

                String currentValue = currentCell.getStringCellValue();

                if (isRowMerge) {
                    // 纵向合并
                    int mergeStartRow = rowIndex;
                    while (rowIndex + 1 <= sheet.getLastRowNum()) {
                        Row nextRow = sheet.getRow(rowIndex + 1);
                        if (nextRow == null) break;

                        Cell nextCell = nextRow.getCell(colIndex);
                        if (nextCell == null || !nextCell.getStringCellValue().equals(currentValue)) break;

                        // 如果当前列不是第一列,且合并行数超过前一列的合并行数,则停止合并
                        if (colIndex > 0 && rowIndex + 1 > getMergeEndRow(sheet, mergeStartRow, colIndex - 1)) break;

                        // 如果合并行数超过第一列的合并行数,则停止合并
                        if (colIndex > 0 && rowIndex + 1 > firstColMergeEndRow) break;

                        rowIndex++;
                    }
                    if (mergeStartRow != rowIndex) {
                        sheet.addMergedRegion(new CellRangeAddress(mergeStartRow, rowIndex, colIndex, colIndex));
                    }

                    // 如果是第一列,记录合并的最后一行
                    if (colIndex == 0) {
                        firstColMergeEndRow = rowIndex;
                    }
                }

                if (isColumnMerge) {
                    // 横向合并
                    int mergeStartCol = colIndex;
                    while (colIndex + 1 < currentRow.getLastCellNum()) {
                        Cell nextCell = currentRow.getCell(colIndex + 1);
                        if (nextCell == null || !nextCell.getStringCellValue().equals(currentValue)) break;

                        colIndex++;
                    }
                    if (mergeStartCol != colIndex) {
                        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, mergeStartCol, colIndex));
                    }
                }
            }
        }
    }

    /**
     * 获取指定单元格的合并的最后一行
     *
     * @param sheet     工作表
     * @param rowIndex  行索引
     * @param colIndex  列索引
     * @return 合并的最后一行
     */
      private int getMergeEndRow(Sheet sheet, int rowIndex, int colIndex) {
        int numMergedRegions = sheet.getNumMergedRegions();
        for (int i = 0; i < numMergedRegions; i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
            if (mergedRegion.isInRange(rowIndex, colIndex)) {
                return mergedRegion.getLastRow();
            }
        }
//        for (CellRangeAddress mergedRegion : sheet.getMergedRegions()) {
//            if (mergedRegion.isInRange(rowIndex, colIndex)) {
//                return mergedRegion.getLastRow();
//            }
//        }
        return rowIndex; // 如果没有合并,则返回当前行
    }

    /**
     * 示例:生成Excel并合并单元格
     */
    public void generateAndMergeExcel(String filePath, String sheetName, List<Integer> columnsToMerge,
                                      boolean isRowMerge, boolean isColumnMerge) throws IOException {
        // 打开现有的Excel文件
        Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));

        // 合并单元格
        mergeCells(workbook, sheetName, columnsToMerge, isRowMerge, isColumnMerge);

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }

        workbook.close();
    }
}

调用示例

java 复制代码
List<Integer> columnsToMerge = Arrays.asList(0, 1, 2, 3, 4, 5); // 合并第1列和第2列
boolean isRowMerge = true; // 启用纵向合并
boolean isColumnMerge = false; // 禁用横向合并

excelMergeUtility.generateAndMergeExcel("C:\\Users\\xxxx\\Downloads\\汇总记录2025-03-04%2B10_38_30.xls", "汇总", columnsToMerge, isRowMerge, isColumnMerge);

依赖配置

为了使用这个工具类,你需要在你的项目中添加 Apache POI 的依赖:

xml 复制代码
<!-- Apache POI 核心库 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- Apache POI OOXML 库,用于处理 .xlsx 文件 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>


总结

通过 ExcelMergeUtility 工具类,你可以轻松地实现 Excel 单元格的合并操作。无论是纵向合并还是横向合并,该工具类都能满足你的需求。希望本文对你有所帮助,欢迎在评论区分享你的使用体验和问题。

相关推荐
海兰1 小时前
【Kafka进阶4】KRaft 完全指南:Apache Kafka 摆脱 ZooKeeper 的架构
zookeeper·kafka·apache
2601_967019511 小时前
如何选择合适的SSL证书类型?
apache
AI导出鸭1 小时前
怎么让文心做表格?AI导出鸭苹果版将文心输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格
人工智能·chatgpt·word·excel·ai导出鸭
admin00511 小时前
Excel记账和财务软件记账哪个好?效率与准确率真实对比
excel·excel记账·财务软件记账·小微企业记账
Python私教18 小时前
Excel 和群聊什么时候该升级成管理系统?7 个判断信号
excel·管理系统·权限设计
鲲穹AI种草19 小时前
表格数据处理怎么选?多款 Excel 工具能力客观记录
excel·表格数据处理
AI英德西牛仔20 小时前
Claude导出word指令的PC端最优解:AI导出鸭电脑版底层逻辑全拆解
人工智能·word·excel·deepseek·ai导出鸭
toooooop821 小时前
踩坑:PHP7.2导出Excel正常,升级7.3文件损坏需修复
android·excel
AI英德西牛仔21 小时前
Gemini 导出 word 指令 时代,PC 端 AI 工作流的最后一块拼图:AI 导出鸭电脑版深度拆解
人工智能·word·excel·deepseek·ai导出鸭
AI导出鸭1 天前
怎么让Grok做表格?AI导出鸭苹果版通过专属解析引擎,将Grok输出的管道表格智能还原为二维结构,一键导出Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭