java.lang.IllegalStateException:无法从文本单元格获取数字值

我在这里看到很多关于我的问题的答案,但是找不到解决办法。 我正在阅读一个Excel文件,并存储在MySQL数据库。 这是我的代码

Sheet mySheet = wb.getSheetAt(0); for (Row row : mySheet) { int columnNumber = mySheet.getFirstRowNum(); Cell c = row.getCell(columnNumber); String sql = "insert into medtest(FMCODE,FLAG,MCODE,EMPNO,NAME,ADDRESS1,ADDRESS2,ADDRESS3,BALANCE,HOSPITAL_O,HOSPITAL_I,NURSING,GENERAL,PRIVATE,SPLCODE,BKCD,ACCOUNT_NO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement ps = (PreparedStatement) con .prepareStatement(sql); ps.setString(1, row.getCell(0).getStringCellValue()); ps.setString(2, row.getCell(1).getStringCellValue()); ps.setInt(3, (int) row.getCell(2).getNumericCellValue()); if (c != null) { if (c.getCellType() == Cell.CELL_TYPE_STRING) ps.setString(4, row.getCell(3).getStringCellValue()); else if(c.getCellType() == Cell.CELL_TYPE_NUMERIC) ps.setInt(4, (int) row.getCell(3).getNumericCellValue()); } ps.setString(5, row.getCell(4).getStringCellValue()); ps.setString(6, row.getCell(5).getStringCellValue()); ps.setString(7, row.getCell(6).getStringCellValue()); ps.setString(8, row.getCell(7).getStringCellValue()); ps.setFloat(9, (float) row.getCell(8).getNumericCellValue()); ps.setFloat(10, (float) row.getCell(9).getNumericCellValue()); ps.setFloat(11, (float) row.getCell(10).getNumericCellValue()); ps.setFloat(12, (float) row.getCell(11).getNumericCellValue()); ps.setFloat(13, (float) row.getCell(12).getNumericCellValue()); ps.setFloat(14, (float) row.getCell(13).getNumericCellValue()); ps.setString(15, row.getCell(14).getStringCellValue()); ps.setString(16, row.getCell(15).getStringCellValue()); ps.setString(17, row.getCell(16).getStringCellValue()); ps.executeUpdate(); } 

下面是我在ps.setString(4, row.getCell(3).getStringCellValue());发生的exceptionps.setString(4, row.getCell(3).getStringCellValue());

 java.lang.IllegalStateException: Cannot get a text value from a numeric cell at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:643) at org.apache.poi.hssf.usermodel.HSSFCell.getRichStringCellValue(HSSFCell.java:720) at org.apache.poi.hssf.usermodel.HSSFCell.getStringCellValue(HSSFCell.java:703) at org.stc.action.DataImport.doGet(DataImport.java:94) at org.stc.action.DataImport.doPost(DataImport.java:70) 

该单元格包含string和整数值

1.样品数据:D05(string)

2.样品数据:3916(整数)

但在我的表中,我已经把varchar作为它的数据types

你必须检查返回的单元格的types:

 if (row.getCell(3).getCellType() == Cell.CELL_TYPE_STRING) ps.setString(4, row.getCell(3).getStringCellValue()); else ps.setString(4, String.valueOf(row.getCell(3).getNumericCellValue())) 

写一个帮助器方法,我有类似的问题,有时即使你期望string(或int cell),如果它们是空的,它们是不同的types:

 if (cell.getCellType() == Cell.CELL_TYPE_STRING) { //process string value } else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { //process numeric value } else { }