困扰无数人的 POI 读取合并单元格内容难题,终于有解了

POI读取合并单元格内容

产品们想到的excel真是千奇百怪,这次又遇到一个读取包含合并单元格的excel文件,一开始直接读取,直接报空了,没办法,只能对于这些列进行判断是否为合并单元格

java 复制代码
private boolean isMergedRegion(Sheet sheet, int row, int column) {
    int sheetMergeCount = sheet.getNumMergedRegions();
    for (int i = 0; i < sheetMergeCount; i++) {
        CellRangeAddress range = sheet.getMergedRegion(i);
        int firstColumn = range.getFirstColumn();
        int lastColumn = range.getLastColumn();
        int firstRow = range.getFirstRow();
        int lastRow = range.getLastRow();
        if (row >= firstRow && row <= lastRow) {
            if (column >= firstColumn && column <= lastColumn) {
                return true;
            }
        }
    }
    return false;
}

如果是合并单元格的话,使用单独的方法来进行读取

java 复制代码
public String getMergedRegionValue(Sheet sheet, int row, int column) {
    int sheetMergeCount = sheet.getNumMergedRegions();
    for (int i = 0; i < sheetMergeCount; i++) {
        CellRangeAddress ca = sheet.getMergedRegion(i);
        int firstColumn = ca.getFirstColumn();
        int lastColumn = ca.getLastColumn();
        int firstRow = ca.getFirstRow();
        int lastRow = ca.getLastRow();
        if (row >= firstRow && row <= lastRow) {
            if (column >= firstColumn && column <= lastColumn) {
                Row fRow = sheet.getRow(firstRow);
                Cell fCell = fRow.getCell(firstColumn,Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                return fCell.toString();
            }
        }
    }

    return null;
}

参考文献

相关推荐
七牛开发者9 小时前
如何从零开发一个工业级的 SKILL
人工智能·程序员·agent
CSDN不脱发的程序猿12 小时前
如何让Skill同时跑在Cursor、Codex和Claude Code 里?
程序员
多租户观察室18 小时前
信通院标准体系2.0深度解读:低代码管理平台进入“精品竞争”时代
前端·低代码·程序员
修己xj1 天前
一个西瓜背后的思考:当爹后才明白的事
程序员
程序员cxuan2 天前
还在用 xigh 拉满跑?大错特错
人工智能·后端·程序员
阿里嘎多学长2 天前
2026-05-28 GitHub 热点项目精选
开发语言·程序员·github·代码托管
TigerOne2 天前
第9章 工具调用循环——Agent的行动闭环
人工智能·程序员
程序员cxuan2 天前
这个插件,直接让 Java 小白秒变资深开发
人工智能·后端·程序员
CodeSheep2 天前
苦撑13年,创始人离职出走,拉勾终究还是倒下了…
前端·后端·程序员
程序员cxuan2 天前
Claude Opus 4.8 来了,我感觉更像 4.7 满血版
人工智能·后端·程序员