首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

Apache POI 讀取 Excel 合併單元格完整解決方案

     編輯:關於C

POI 解析合併儲存格核心邏輯

Excel 中合併儲存格會導致數據只存在於左上角儲存格,其他儲存格為空。需遍歷合併區域判斷當前儲存格是否屬於合併區,若是則取左上角值。

核心代碼實現

1. 獲取所有合併區域

/** 獲取 Sheet 所有合併區域 */
public List getCombineCell(Sheet sheet) {
    List list = new ArrayList<>();
    int count = sheet.getNumMergedRegions();
    for (int i = 0; i < count; i++) {
        list.add(sheet.getMergedRegion(i));
    }
    return list;
}

2. 判斷儲存格是否在合併區並取值

/** 判斷儲存格是否為合併儲存格,是則返回左上角值 */
public String isCombineCell(List mergedList, Cell cell, Sheet sheet) {
    int cellRow = cell.getRowIndex();
    int cellCol = cell.getColumnIndex();

    for (CellRangeAddress ca : mergedList) {
        int firstRow = ca.getFirstRow(), lastRow = ca.getLastRow();
        int firstCol = ca.getFirstColumn(), lastCol = ca.getLastColumn();

        if (cellRow >= firstRow && cellRow <= lastRow &&
            cellCol >= firstCol && cellCol <= lastCol) {
            // 取左上角儲存格值
            Row fRow = sheet.getRow(firstRow);
            Cell fCell = fRow.getCell(firstCol);
            return getCellValue(fCell); // 需自行實現 getCellValue
        }
    }
    return ""; // 非合併區返回空
}

完整解析流程

  1. 讀取 Sheet → getCombineCell() 獲取合併區域列表
  2. 遍歷每行每儲存格 → 調用 isCombineCell() 判斷
  3. 若在合併區 → 取左上角值;否則取儲存格自身值
  4. 處理數據類型轉換(數值、字符串、日期、布爾等)

關鍵注意點

  • 合併區域由 CellRangeAddress 表示,含 firstRow/lastRow/firstColumn/lastColumn
  • 需處理儲存格為 null 的情況(空行/空儲存格)
  • 日期類型需用 DateUtil.isCellDateFormatted() 判斷並格式化
  • 大文件建議使用 SXSSF (流式) 避免 OOM

效果展示

合併儲存格 Excel 示例

擴展建議

可封裝為工具類 ExcelMergeCellReader,提供 readSheet(Sheet) 返回 List>,內部自動處理合併邏輯,業務代碼零侵入。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved