skip to Main Content

I tried to do an excel data upload into a database using Apache.POI. their function gives me an error like

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: org.apache.poi.xssf.usermodel.XSSFCell cannot be cast to java.lang.Integer

The code segment error occurs in

for (Iterator iterator = dataHolder.iterator(); iterator.hasNext();) {
        List list = (List) iterator.next();
         i++;
        if (i > 0) {  
            ID =  (int) list.get(0);
            Employee_Number = list.get(1).toString();
            FirstName = list.get(2).toString();
            LastName = list.get(3).toString();
            EmailAddress = list.get(4).toString();
            PdfName = list.get(5).toString();
            Sup_EmailAddress = list.get(6).toString();
            PassCode = list.get(7).toString();

can anyone suggest me why getting this kind of error?.

2

Answers


  1. The line ID = (int) list.get(0); throws an error because the data in the cell cannot be converted to an int. Try to save it as a String.

    id = (String) list.get(0);
    

    Or as a long

    id = (long) list.get(0);
    

    Or handle the exception

    try {
      ID = (int) list.get(0);
    } catch (ClassCastException e) {
      // id is not a number
    }
    
    Login or Signup to reply.
  2. According to the official JavaDoc of XSSFCell you can use getNumericCellValue() instead.

    public double getNumericCellValue()

    Get the value of the cell as a number.

    To safely check whether you process an actual number, you can re-write your code fragment as follows:

    import org.apache.poi.ss.usermodel.CellType;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    
    int ID;
    // ... loop here ...
        XSSFCell cell = list.get(0);
        if(CellType.NUMERIC == cell.getCellType()) {
            ID =  new Double(cell.getNumericCellValue()).intValue(); 
        } else {
            // handle this case separately... 
        }
    // end loop
    

    The above code snippet avoids unnecessary casts and/or try and error guessing.

    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search