java - 为什么无法使用 Apache POI 设置行和列的值?

标签 java excel 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");

我正在尝试设置该单元格 enter image description here

最佳答案

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

Cell 似乎不存在。 row.getCell(j) 返回 null

您可以使用 MissingCellPolicy如果 Cell 尚不存在,则确定是否要返回新的 CellCREATE_NULL_AS_BLANK 值将为您创建一个空白的Cell(如果它尚不存在)。

关于java - 为什么无法使用 Apache POI 设置行和列的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310388/

相关文章:

java - Java 控制台应用程序中使用 Windows "cls"命令清屏

java - 将 JInternalFrame 添加到持有 JScrollPane 的 JTabbedPane 中,持有 JPanel 宽度的 Gridbaglayout

java - 为什么原始数组不允许添加到 GSON 中的 JSON 结构

android - 方法错误太多

java - XSSFWorksheet 代码中未检测到空白

java - 计算数据透视表中具有相同列索引的列

java - 按对象内部的值过滤 RecyclerView

excel - 从文本中导入最多 n 行

performance - VBA代码运行两个循环非常慢

java - POI - 处理 HH :MM:SS. sss 格式的数据