You have to check the presence of that cell. Remember if a row is present doesn't mean that all the cells are present. If that particular cell is not present doing get operations will throw you null pointer error, but create cell will not throw an error because it creates that cell in that particular row. You can do a dot operator on that cell object only if it exists.
For Example:
If the cell at 3rd position is present this will work:
row1.getCell(2).getStringCellValue(); // if the value is of string type
else you have check using if and create that cell if needed.
// This checks if the cell is present or it'll return null if the cell
// is not present (it won't check the value in cell)
if (row1.getCell(2) != null)
{
row1.createCell(2);
}
If that cell is not present and your only objective is to get the value, you can set a default value in your array.
These 2 lines won't work because it'll convert the cell object to string but not the content of it:
lastName = row.getCell(1).toString();
firstName = row.getCell(2).toString();
You have to change it to:
lastName = row.getCell(1).getStringCellValue();
firstName = row.getCell(2).getStringCellValue();
You need not do this when you don't have any value in that cell:
if (row.getCell(2) != null)
{
row.createCell(2);
}
firstName = row.getCell(2).toString();
change this to:
if (row.getCell(2) != null)
{
firstName = row.getCell(2); // your other operations
} else {
firstname = "default value"; // your other operations
}
There's no need of doing a get cell value just when you have created a cell without setting a value.
You have to use row.createCell(2);
only when you are setting a value to the cell. Here you don't have a value in it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…