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

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)


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!