我尝试使用Apache.POI将Excel数据上传到数据库中。他们的功能给我一个错误
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: org.apache.poi.xssf.usermodel.XSSFCell cannot be cast to java.lang.Integer
代码段错误发生在
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();
任何人都可以建议我为什么会出现这种错误?
根据official JavaDoc of XSSFCell,您可以使用getNumericCellValue()
代替。
public double getNumericCellValue()
获取单元格的值作为数字。
要安全地检查是否处理实际数字,可以按如下方式重新编写代码片段:
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
上面的代码片段避免了不必要的强制转换和/或尝试和错误猜测。
希望能帮助到你。
行ID = (int) list.get(0);
抛出错误,因为单元格中的数据无法转换为int。尝试将其保存为String。
id = (String) list.get(0);
或者很长
id = (long) list.get(0);
或处理异常
try {
ID = (int) list.get(0);
} catch (ClassCastException e) {
// id is not a number
}