在Apache POI中创建单元格时获取空指针exception
每次运行我的代码时,我都会收到一个空指针错误(下图),它指向用两个星号指定的行。
public void writeSomething(XSSFWorkbook wb){ for (String elem: listOfSheetNames){ if (elem.equals("Sheet2")){ sheet = wb.getSheet(elem); //sheet is of type XSSFSheet XSSFRow row = sheet.getRow(0); **XSSFCell cell = row.getCell(1); if (cell == null){ cell = row.createCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue("Apple"); } } } }
我是apache poi的新手,我只是想把数据写入第二张excel表(Sheet2)中的空白单元格。 我在这里做错了吗?
不幸的是,该单元格当前为null
而不是空白单元格。 将数据放在指定的工作表上会使其变为空白。 您可能希望先创建单元格,然后检查它是否为blank
单元格而不是null
单元格。
**XSSFCell cell = row.createCell(1); if (cell == Cell.CELL_TYPE_BLANK){ cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue("Apple"); }
这将导致不兼容的类型。
而是这样做:
if (cell.getCellType() == Cell.CELL_TYPE_BLANK){ cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue("Apple"); }