報錯: java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell
阿新 • • 發佈:2022-05-30
報錯如下:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:1050) at org.apache.poi.xssf.usermodel.XSSFCell.getRichStringCellValue(XSSFCell.java:404) at org.apache.poi.xssf.usermodel.XSSFCell.getRichStringCellValue(XSSFCell.java:70) at com.jawasoft.testDemo.ExcelUtil.readExcel(ExcelUtil.java:81) at com.jawasoft.testDemo.ExcelUtil.readExcelToObj(ExcelUtil.java:46) at com.jawasoft.testDemo.ExcelUtil.main(ExcelUtil.java:29)
報錯原因:在讀取cell單元格字串時,有number型別的資料,因此需要把它轉化為純String型別,這樣就不會報錯了。
報錯的程式碼:
returnStr = cell.getRichStringCellValue().getString();
或者如下程式碼
//獲取單元格資料 String cellValue = cell.getStringCellValue();
解決辦法:在讀取excel單元格資料轉化之前設定單元格型別為String
程式碼如下:
//設定單元格型別
cell.setCellType(CellType.STRING);
returnStr = cell.getRichStringCellValue().getString();