POI-XSSF:从公式单元格缓存的值中读取格式化的值

gau*_*430 1 java excel apache-poi xssf

在我的excel工作表中,许多单元格包含公式,当我用Apache POI阅读excel时,我不想重新计算这些公式。

我这样做的方式:

if(cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {

    //System.out.println("Formula is " + cell.getCellFormula());
    switch(cell.getCachedFormulaResultType()) {
        case XSSFCell.CELL_TYPE_NUMERIC:

            System.out.print(cell.getNumericCellValue() +" ");

            break;
        case XSSFCell.CELL_TYPE_STRING:
            System.out.print(cell.getRichStringCellValue()+" ");
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这有助于我获得单元格中的原始值。例如,如果单元格的值为19.5%,这将为我提供0.195456。我想获取格式化的值。

一种获取格式化值的方法是:

DataFormatter formatter = new DataFormatter();

System.out.print(formatter.formatCellValue(cell));
Run Code Online (Sandbox Code Playgroud)

这对于常规单元格效果很好,但是对于具有公式的单元格,它实际上会获取公式字符串并显示它,即,它不会获取缓存的值并对其进行格式化,而只是返回公式字符串。

从CELL_TYPE_FORMULA检索值后,是否可以格式化该值

Syl*_*gat 5

无需使用评估程序就可以直接格式化单元格的缓存值。对于由于第三方插件或单元格公式中不可用的外部数据而导致无法重新计算的值的情况,这很有用。

此代码可用于执行以下操作:

final DataFormatter dataFormatter = new DataFormatter();

final CellStyle cellStyle = cell.getCellStyle();
final String formtatedValue = dataFormatter.formatRawCellContents(cell.getNumericCellValue(), cellStyle.getDataFormat(), cellStyle.getDataFormatString());
System.out.println(formattedValue);
Run Code Online (Sandbox Code Playgroud)

仍然使用格式化程序,但是formatRawCellContents调用了该方法以使用其样式手动格式化单元格缓存的值。