Getting below error while reading data from a .xlsx
file. I am not able to read data due to this error. Facing the error message "cannot get a numeric value from a text cell".
Here is the code:
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
rowArray[count] = isCellDateFormatted(cell) ? dateFormat.format(cell.getDateCellValue()) : Double.toString(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
rowArray[count] = Boolean.toString(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
rowArray[count] = isCellDateFormatted(cell) ? dateFormat.format(cell.getDateCellValue()) : Double.toString(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
rowArray[count] = cell.getStringCellValue().replace(separatorStr, escapeStr + separatorStr).replace("\n", " ");
break;
default:
rowArray[count] = "";
}
Here is the exception:
java.lang.IllegalStateException: Cannot get a numeric value from a text cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:994)
at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:305)
at org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(DateUtil.java:494)
at cvx.qwer.adfffg.excel.XlsxToCsv.convertToCsv(XlsxToCsv.java:76)
at cvx.qwer.adfffg.excel.XlsxToCsv.main(XlsxToCsv.java:136)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
As of your showed code the rowArray
seems to be a String
array. So the need is to get all cell values as String
representations. Best way to do so is using DataFormatter in combination with FormulaEvaluator :
...
Workbook workbook ...
...
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter formatter = new DataFormatter();
...
Cell cell ...
...
rowArray[count] = formatter.formatCellValue(cell, evaluator);
...
Using this the whole switching the cell types is not necessary. DataFormatter.formatCellValue :
Returns the formatted value of a cell as a String regardless of the cell type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.