0

I have written below mentioned snippet of code for reading excel file and this is working fine for non empty excel file but for excel file it is throwing NULLPOINTEREXCEPTION.

    ArrayList<String> dataList = new ArrayList<String>();
    XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
    int rowNum = xssfSheet.getLastRowNum() + 1;
    int startRow = 0, startCol = 0, colNum;
    for (int r = startRow; r < rowNum; r++) {
        XSSFRow row = xssfSheet.getRow(r);
        colNum = xssfSheet.getRow(r).getLastCellNum();
        String data = "";
        for (int c = startCol; c < colNum; c++) {
            XSSFCell cell = row.getCell(c,XSSFRow.CREATE_NULL_AS_BLANK);
            data += cell.toString() + ", ";
        }
        dataList.add(data);
    }
    closeFile();

I'm getting exception in this line for an empty file: colNum = xssfSheet.getRow(r).getLastCellNum(); The issue is getLastCellNum() return value as 0 for no record as well as for one record. So while retrieving getLastCellNum() i'm getting null pointer exception.

AMAN KUMAR
  • 277
  • 1
  • 6
  • 19

1 Answers1

0

You should use rowIterator() and cellIterator() to iterate over rows and columns.

XSSFRow row; 
XSSFCell cell;
Iterator rows = sheet.rowIterator();
    while (rows.hasNext()){
        row=(XSSFRow) rows.next();
        Iterator cells = row.cellIterator();
        while (cells.hasNext())
        {
            cell=(XSSFCell) cells.next();
            cIndex=cell.getColumnIndex();
            data += cell.toString() + ", ";
        }
         dataList.add(data);
    }
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18