I am using the Apache poi api for java to write into an existing sheet in an excel workbook. My problem is that in the worksheet that I am trying to edit, if any of the cell in the row is not null i.e. has some some sort of value in it, then the program runs fine and edits any any particular cell in that row. For example if the cell in my worksheet (1,1) contains a value then the program will have no problem editing other cells of the same row say (1,5) or (1,12) and so on. But if my entire row is empty i.e. all the cells contain null then the code throws a nullpointer exception which I cannot figure out how to remove. Here is the write method I used for my project to write a particular cell in my excel class.
public void write(int row, int column, String label) {
try {
InputStream inp = new FileInputStream(filePath);
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row sheetRow = sheet.getRow(row);
Cell cell = sheetRow.getCell(column);
//String cellContents = cell.getStringCellValue();
// //Modify the cellContents here
// // Write the output to a file
if (cell == null) {
cell = sheetRow.createCell(column);
cell.setCellType(Cell.CELL_TYPE_STRING);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(label);
FileOutputStream fileOut = new FileOutputStream(filePath);
wb.write(fileOut);
fileOut.close();
} catch (IOException ex) {
Logger.getLogger(ExcelManipulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(ExcelManipulator.class.getName()).log(Level.SEVERE, null, ex);
}
}
The exception that java throws on editing a cell in an untouched i.e. a null row is :
Exception in thread "main" java.lang.NullPointerException
at seleniumtest.ExcelManipulator.write(ExcelManipulator.java:76)
at seleniumtest.SeleniumTest.main(SeleniumTest.java:28)
Java Result: 1
Can anybody help me get rid of this so that my code also writes a cell even if the whole row is null? Thanks