Java POI-XSSF:从公式单元格缓存值读取格式化值
在我的excel工作表中,许多单元格都包含公式,我不想在使用ApachePOI读取excel时重新计算这些公式 我这样做的方式:Java POI-XSSF:从公式单元格缓存值读取格式化值,java,excel,apache-poi,xssf,Java,Excel,Apache Poi,Xssf,在我的excel工作表中,许多单元格都包含公式,我不想在使用ApachePOI读取excel时重新计算这些公式 我这样做的方式: if(cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) { //System.out.println("Formula is " + cell.getCellFormula()); switch(cell.getCachedFormulaResultType()) { case XSS
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;
}
}
这有助于我获取单元格中的原始值。
例如,如果单元格的值为19.5%,则表示为0.195456。
我想得到格式化的值
获取格式化值的一种方法是:
DataFormatter formatter = new DataFormatter();
System.out.print(formatter.formatCellValue(cell));
这适用于常规单元格,但对于包含公式的单元格,它实际上会获取公式字符串并显示它,也就是说,它不会获取缓存值并对其进行格式化,而只是返回公式字符串
是否有一种方法可以在从单元格\u TYPE\u FORMULA检索值后格式化该值如果在调用
formatCellValue
时传入FormulaEvaluator
,即
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
System.out.print(formatter.formatCellValue(cell, evaluator));
可以直接格式化单元格的缓存值,而无需使用计算器。当由于第三方插件或单元格公式中的外部数据不可用而无法重新计算值时,此功能非常有用 此代码可用于执行以下操作:
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);
格式化程序仍在使用,但调用方法
formatRawCellContents
以手动格式化单元格缓存值及其样式。实际上,公式来自第三方插件,我不打算使用,我只需要正确格式化缓存值