You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache POI的CellReference读取两行单元格数据解决取值报错问题

问题原因

你当前代码仅初始化了第3行的Row对象,读取B4单元格时依然使用第3行的row实例调用getCell方法,无法获取到第4行的单元格数据,因此触发报错。另外原代码的校验逻辑存在错误:校验单元格引用对象不为空没有实际意义,需要校验实际读取到的单元格对象是否为空。

修正方案

  1. 单独声明第4行的Row对象,通过B4的单元格引用获取对应行
  2. 调整B4单元格的读取逻辑,使用第4行的Row实例获取单元格
  3. 修正校验判断逻辑,补充空值防护避免空指针异常
  4. 增加工作簿关闭逻辑,避免资源泄漏

修正后完整代码

private boolean validaLinha(InputStream arquivoCancelamento) throws IOException{
        XSSFWorkbook wb = new XSSFWorkbook(arquivoCancelamento);
        wb.setForceFormulaRecalculation(true);
        Sheet sheet = wb.getSheetAt(0);
        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
        String celulaB3 = "Número do Cartão ";
        String celulaC3 = "Número Pedido";
        String celulaD3 = "Motivo de Cancelamento";
        String celulaE3 = "Observação";
        String celulaB4 = "";
        boolean val = false;

        CellReference cellReferenceB3 = new CellReference("B3");
        CellReference cellReferenceC3 = new CellReference("C3");
        CellReference cellReferenceD3 = new CellReference("D3");
        CellReference cellReferenceE3 = new CellReference("E3");
        CellReference cellReferenceB4 = new CellReference("B4");

        // 分别获取第3行、第4行的Row对象
        Row row3 = sheet.getRow(cellReferenceC3.getRow());
        Row row4 = sheet.getRow(cellReferenceB4.getRow());

        // 读取第3行单元格,增加空行防护
        Cell cellB3 = row3 != null ? row3.getCell(cellReferenceB3.getCol()) : null;
        Cell cellC3 = row3 != null ? row3.getCell(cellReferenceC3.getCol()) : null;
        Cell cellD3 = row3 != null ? row3.getCell(cellReferenceD3.getCol()) : null;
        Cell cellE3 = row3 != null ? row3.getCell(cellReferenceE3.getCol()) : null;
        // 读取第4行B4单元格
        Cell cellB4 = row4 != null ? row4.getCell(cellReferenceB4.getCol()) : null;


        if ((cellB3!=null && celulaB3.equals(cellB3.getStringCellValue() ))
                &&  (cellC3!=null && celulaC3.equals(cellC3.getStringCellValue() ))
                && (cellD3!=null && celulaD3.equals(cellD3.getStringCellValue() ))
                && (cellE3!=null && celulaE3.equals(cellE3.getStringCellValue() ))
                && (cellB4!=null)
                // 此处可补充B4单元格的自定义校验逻辑
                ){
            val = true;
            // 校验通过后的业务逻辑
        }
        // 关闭工作簿释放资源
        wb.close();
        return val;
}

内容的提问来源于stack exchange,提问作者johny campos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 13:39:02