Search code examples
javaexcelexceptioncelljxl

Exception when reading empty cells from Excel file


When trying to read an Excel sheet I get an exception if some cell is empty:

Cell[] rowCells = sheet.getRow(1);

or

Cell cell = sheet.getCell(0,1);

I always get the same message:

java.lang.ArrayIndexOutOfBoundsException: 1
    at jxl.read.biff.SheetImpl.getCell(SheetImpl.java:356)
    at gui.ReadExcel.read(ReadExcel.java:45)
    at gui.GUIcontroller.chooseSaveFile(GUIcontroller.java:101)

What is the problem? How can I know if the cell is empty, so I won't copy its value?


Solution

  • You can use the getRows or getColumns method to check the bounds of the sheet. The ArrayIndexOutOfBoundsException occurs because you are trying to access a value, which is beyond the range of the farthest cell which is not empty.

    int rows = sheet.getRows();
    int columns = sheet.getColumns();
    int i = 1;
    if(i<rows)
        Cell[] rowCells = sheet.getRow(i);  //Won't throw an Exception
    
    if(i<rows && j<columns)
        Cell cell = sheet.getCell(i,j);