我需要为电子表格的特定行和列设置一个值,但我在 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)
返回 null
。
您可以使用 MissingCellPolicy
如果 Cell
尚不存在,则确定是否要返回新的 Cell
。 CREATE_NULL_AS_BLANK
值将为您创建一个空白的Cell
(如果它尚不存在)。
关于java - 为什么无法使用 Apache POI 设置行和列的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310388/