为什么不能使用 Apache POI 为行和列设置值?

Why can't set a value for a row and column with the Apache POI?

我需要为电子表格的特定行和列设置一个值,但在 i = 1 之前我得到一个空指针 。我试过更改代码,但此错误不断发生,我不知道为什么。
有人知道为什么会发生这种情况吗?

我的代码

public Workbook build(Planilha planilha) {
    File file = new File(TEMPLATE_PATH);
    if (!file.exists()) {
        Log.error(this, String.format("File %s not exists.", file.getAbsolutePath()));
        throw new NotFoundException("File not exists.");
    }

    Workbook wb = null;
    try (FileInputStream fs = new FileInputStream(file)) {
        wb = new XSSFWorkbook(fs);
        wb = writeMetadatas(planilha, wb);

        Map<String, Integer> header = getHeader(wb);
        Sheet sheet = wb.getSheetAt(0);
        Row row;
        Cell cell;
        for (int i = 0; i <= 10; i++) {
            row = sheet.getRow(i);
            for (int j = 0; j <= 10; j++) {
                cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
                if (cell.getColumnIndex() == 0 && row.getRowNum() == 7) {
                    cell.setCellValue("teste");
                }
            }

        }

    } catch (Exception e) {
        Log.error(this, "Erro: Planilha não existe", e);
        System.err.print("Erro");
    }


    String tmpDir = System.getProperty("java.io.tmpdir");
    File f = FileUtil.file(PATH, System.currentTimeMillis() + ".xlsx");
    try {
        FileOutputStream fout = new FileOutputStream(f);
        wb.write(fout);
        fout.flush();
        fout.close();
    } catch (Exception e) {
        Log.error(this, "Erro ao abrir arquivo p escrever.");
    }
    return wb;
}

**NullPointer 发生在 cell.setCellValue("teste");

我正在尝试设置那个单元格

首先,您可以测试行号是否是 for 循环之外的某个数字,该循环遍历一行中的单元格。将 if 拉到 j for 循环之外。

看起来 Cell 不存在。 row.getCell(j) 是 returning null.

如果 Cell 不存在,您可以使用 MissingCellPolicy 来确定是否要 return 一个新的 Cell。如果 CREATE_NULL_AS_BLANK 值不存在,将为您创建一个空白 Cell