首页 > 解决方案 > 将单元格值导出为字符串的安全方法

问题描述

String使用Apache POI获取单元格值的安全方法是什么?

对于一些非空单元格,我得到以下异常:

com.monitorjbl.xlsx.exceptions.NotSupportedException: null
    at com.monitorjbl.xlsx.impl.StreamingCell.getSheet(StreamingCell.java:330)
    at org.apache.poi.ss.usermodel.DataFormatter.isDate1904(DataFormatter.java:313)
    at org.apache.poi.ss.usermodel.DataFormatter.getFormat(DataFormatter.java:309)
    at org.apache.poi.ss.usermodel.DataFormatter.getFormattedNumberString(DataFormatter.java:868)
    at org.apache.poi.ss.usermodel.DataFormatter.formatCellValue(DataFormatter.java:1021)
    at org.apache.poi.ss.usermodel.DataFormatter.formatCellValue(DataFormatter.java:971)
    at org.apache.poi.ss.usermodel.DataFormatter.formatCellValue(DataFormatter.java:950)
...

我现在使用下面的代码将单元格值提取为文本:

import org.apache.poi.ss.usermodel.*;

private static DataFormatter formatter = new DataFormatter();

private static String formatCellValue(Cell cell) {
    return formatter.formatCellValue(cell);
}

该方法的javadoc说:

无论单元格类型如何,都将单元格的格式化值作为字符串返回。如果无法解析 Excel 格式模式,则单元格值将使用默认格式进行格式化。当传递一个空或空白单元格时,此方法将返回一个空字符串 ("")。不会计算公式类型单元格中的公式。

标签: javaapache-poi

解决方案


解决方案是将检查添加到提到的方法并调用,与在 POI 单元格getStringCellValue()StreamingCell调用它相比,它总是安全的。

private static String formatCellValue(Cell cell) {
    if (cell instanceof com.monitorjbl.xlsx.impl.StreamingCell) {
        return cell.getStringCellValue();
    }

    return formatter.formatCellValue(cell);
}

推荐阅读