为什么不能使用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");

我试图设置这个单元格 在这里输入图像说明

首先,您可以testing行号是否在for循环之外的特定数字,该循环遍历一行中的单元格。 拉if你的j循环之外。

它看起来像Cell不存在。 row.getCell(j)返回null

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