I am trying to read an Excel file with Apache POI. My goal is to get the cells 2 & 3 from every row and place them into an array. In some rows cell number 3 is empty (I am not talking about EMPTY, NULL or BLANK). Just empty if you check them in Excel.
Some of those empty cells (not all) cause the NullPonterException: Exception in thread "main" java.lang.NullPointerException. It happens when trying to get the cell value or the cell type. I have the impression that there is no cell at that location.
At the same time if I do row.createCell(2).setCellType(1);
for that specific row the program continues until next cell of this type. That is the only workaround (that I could find) to continue reading cells from next rows.
Could you please help me understand how to identify these cells (with code) and put my workaround in place so I can continue reading till the end of the file?
This is the code:
static ArrayList<String> getFirstFile() throws IOException
{
FileInputStream fileIn = null;
ArrayList <String> namesFirstFile = new ArrayList <String>();
String folderPath = "C:";
String indivList1 = "filename.xls";
fileIn = new FileInputStream(folderPath+indivList1);
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
int rowNumber = 6; //skipping the first 6 rows as irrelevant
HSSFRow row = sheet.getRow(rowNumber);
String firstName = "";
String lastName = "";
while(row.getCell(0).getCellType() == 0) {
lastName = row.getCell(1).toString();
firstName = row.getCell(2).toString();
namesFirstFile.add((rowNumber-6), (lastName + " " + firstName));
rowNumber++;
row = sheet.getRow(rowNumber);
}
}
See Question&Answers more detail:os