简体   繁体   English

从 xlsx 文件获取数据时无法从文本单元格获取数值

[英]Cannot get a numeric value from a text cell while getting data from xlsx file

Getting below error while reading data from a .xlsx file..xlsx文件读取数据时出现以下错误。 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.根据您显示的代码, rowArray似乎是一个String数组。 So the need is to get all cell values as String representations.所以需要将所有单元格值作为String表示。 Best way to do so is using DataFormatter in combination with FormulaEvaluator :最好的方法是将DataFormatterFormulaEvaluator结合使用:

...
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 : DataFormatter.formatCellValue :

Returns the formatted value of a cell as a String regardless of the cell type.无论单元格类型如何,都将单元格的格式化值作为字符串返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM