困扰无数人的 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;
}

参考文献

相关推荐
陈随易12 小时前
VSCode的Copilot扩展支持接入DeepSeek,Kimi了!
前端·后端·程序员
七十二時44621 小时前
什么是VibeCoding
程序员
AskHarries1 天前
Canvas / Artifact:把结果变成可查看、可交互的产物
程序员
爱勇宝2 天前
鸿蒙生态的下半场:开发者不只要能开发,还要能赚钱
android·前端·程序员
程序员cxuan2 天前
DeepSeek 杀入多模态,识图功能正式上线!
人工智能·后端·程序员
文心快码BaiduComate2 天前
Comate 搭载GLM-5.2:百万上下文,稳定支撑长程任务
前端·程序员·开源
程序员cxuan2 天前
分享一下我最近常用的 10 个 Codex 小技巧。
人工智能·后端·程序员
Moonbit2 天前
MoonBit ×CCF开源创新大赛 倒计时24天!快来提交你的作品
程序员·编程语言
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
demo007x3 天前
Docling 文档转换以及技术架构分析
前端·后端·程序员