[Solution] POI: Cannot get a NUMERIC value from a STRING cell


Exception:
Exception in thread "main"

 java.lang.IllegalStateException: Cannot get a NUMERIC value from a STRING cell

  at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:946)
  at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:260)
  at ExcelReaderPOIExample.main(ExcelReaderPOIExample.java:38)


Solution:

The cells in an Excel Spreadsheet can of various types so its better to either use an if-else or a switch-case to check what kind of value the cell holds before trying to fetch it,

while (cellIterator.hasNext()) {

 Cell cell = cellIterator.next();
   if (cell.getCellType() == CellType.NUMERIC) {
    System.out.print((int) cell.getNumericCellValue() + "\t");
   } else if (cell.getCellType() == CellType.STRING) {
    System.out.print(cell.getNumericCellValue() + "\t");
   } else if(cell.getCellType() == CellType.FORMULA) {
    System.out.print(cell.getCellFormula() + "\t");
   }

}
Solution POI IllegalStateException
Solution POI IllegalStateException


Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.