[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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap