我在这里看到了很多关于我的问题的答案,但找不到解决方案。我正在读取 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();
}
Run Code Online (Sandbox Code Playgroud)
以下是我在行中发生的异常ps.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)
Run Code Online (Sandbox Code Playgroud)
单元格包含字符串和整数值
1.样本数据:D05(字符串)
2.样本数据:3916(整数)
但在我的表中,我采用 varchar 作为其数据类型
您必须检查返回单元格的类型:
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()))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6159 次 |
| 最近记录: |