问题
I am getting a null pointer error everytime I ran my code (below) and it points to the line specified with two asterisk.
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");
}
}
}
}
I am a new to apache poi and am just trying to write data to a blank cell in a 2nd excel sheet (Sheet2). Did I do something wrong here?
回答1:
Unfortunately, the cell is currently null
not a blank cell. Placing data on the specified sheet makes it blank. You might want to create the cell first then check if it is a blank
cell rather than null
.
**XSSFCell cell = row.createCell(1);
if (cell == Cell.CELL_TYPE_BLANK){
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Apple");
}
回答2:
This would led to incompatible types.
Instead do this:
if (cell.getCellType() == Cell.CELL_TYPE_BLANK){
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Apple");
}
来源:https://stackoverflow.com/questions/14227108/getting-null-pointer-exception-in-creating-cell-in-apache-poi