Workbook library does not read the cell value if the cell is empty

Sangamesh picture Sangamesh · Jul 5, 2013 · Viewed 8.7k times · Source

Hi I am reading Excel file from java using jxl workbook library.Below is the code.

Workbook wb = Workbook.getWorkbook(new File(destFile));

String line = "";                   // available
for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {

  Sheet sheet = wb.getSheet(sheetNo);
  System.out.println("Sheet Name is:\t" + sheet.getName());
  if(sheet.getName().trim().equals("Store List")){
    int columns = sheet.getColumns();
    int rows = sheet.getRows();
    String data;

    for (int row = 0; row < rows; row++) {      
      for (int col = 1; col < columns; col++) {
        data = sheet.getCell(col, row).getContents();
        line = line + data + "#";
      }
       line += "#&#";
    }
    System.out.println("Entire line is" + line);
  }
}

The above code reads row&column data from the excel file and passes it to the service method for further processing.

When I traverse it line-by-line for the empty cell, the Java code throws IndexOutOfBoundException. Please find the java code below which throws exception.

for(int elementCount=4;elementCount<elements.length;elementCount++) {
  String strquantity =      rowValues[elementCount];
  int quantity=0;
  if(strquantity.equals("")){
    quantity = 0;
  } else {
    quantity = Integer.parseInt(strquantity);
    System.out.println("Quantity value is:\t" + quantity);
  }
}

As you the above code exception is thrown at line 2.

I believe that cause is due to workbook library.

Answer

Sangamesh picture Sangamesh · Jul 5, 2013

After doing some rnd i got the solution,If it is empty cell will get the 0 or null value from jxl API. As in my code i was looking for empty string

 if(strquantity.equals("")){
       quantity = 0;
    }

now the code changed to below one

if(strquantity.equals(null) || strquantity.equals("0")){
      quantity = 0;
   }