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?.
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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.