Exception in thread “main” java.lang.IllegalStateE

2019-09-03 04:41发布

问题:

I have written code as below to fetch value from Excel.

String CID = s1.getRow(i).getCell(0).getStringCellValue();

but in excel, 1st cell is a numeric value, but in above code I am trying to fetch String cell value. thats why I am getting error as :

Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric cell

Can anyone please provide a solution for this. how to fetch the numeric value from excel?

回答1:

getCellType() for any cell gives you the type of the cell.The types are:

Cell.CELL_TYPE_BLANK
Cell.CELL_TYPE_NUMERIC
Cell.CELL_TYPE_STRING
Cell.CELL_TYPE_FORMULA
Cell.CELL_TYPE_BOOLEAN
Cell.CELL_TYPE_ERROR

It is better to use a switch statement and collect the correct type of cell value. There exists getNumericCellValue() and getStringCellValue() functions but it is safer with types.



回答2:

I'm not sure, but I think that exists getNumericalCellValue() or getIntegerCellValue() which returns what you want.



回答3:

Add apostrophe as prefix to that number in cell, automatically it will be converted as text. it had worked for me



回答4:

Check the cell type first and then get its value.

           row.getCell(index).getCellType();
Number ==> row.getCell(index).getNumericCellValue();
String ==> row.getCell(index).getStringCellValue();


回答5:

You should use it =>

String CID = new BigDecimal(s1.getRow(i).getCell(0).getNumericCellValue()).toString();