【问题标题】:How to retrieve cell value with same result as displayed in Excel?如何检索与 Excel 中显示的结果相同的单元格值?
【发布时间】:2015-06-02 23:32:31
【问题描述】:

我有以下代码:

Workbook workbook = WorkbookFactory.create( file );
Sheet sheet = workbook.getSheet( "Sheet1" );
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter formatter = new DataFormatter( true );

int rowNum = 0;
int colNum = 0;
Row row = sheet.getRow( rowNum );
Cell cell = row.getCell( colNum );

double rawCellValue = cell.getNumericCellValue();
System.out.println( "raw value: " + rawCellValue );

String cellValue = formatter.formatCellValue( cell, evaluator );
System.out.println( "formatted: " + cellValue );

这会产生输出:

raw value: 1713.6
formatted: $1,713

当我在 Excel Professional 2010 中打开文件时,值显示为 $1,714

您知道为什么 POI 产生的值与 Excel 不同吗?有没有办法配置 POI 使其返回相同的值(即遵循与 Excel 相同的舍入算法)?

我正在使用带有 xls (Excel 97-2013) 文件的 POI 3.12。

编辑:此单元格的 java 格式为 $#,##0(POI 内部)。以下是 Excel 显示的内容:

编辑 2: 也许这是 Java 的问题,而不是 POI。以下代码:

double number = 1713.6;
System.out.println( "double   : " + number );

DecimalFormat format = new DecimalFormat("#0");

format.setRoundingMode( RoundingMode.HALF_DOWN );
System.out.println( "HALF_DOWN: " + format.format( number ) );

format.setRoundingMode( RoundingMode.HALF_UP );
System.out.println( "HALF_UP  : " + format.format( number ) );

产生结果:

double   : 1713.6
HALF_DOWN: 1714
HALF_UP  : 1713

为什么HALF_DOWN会向上而HALF_UP会向下

【问题讨论】:

  • 格式应该不是问题。它是 Excel 和 POI 中的默认货币格式。我已经尝试过了,无法重现。如果cell.getNumericCellValue()1713.6formatter.formatCellValue( cell, evaluator ) 对我来说是 $1,714A1 中的 Excel 单元格内容是什么?一个公式?哪个?
  • 没有公式。 Excel 中的值正好是 1713.6
  • 最后一次编辑发布为单独的后续question

标签: java excel apache-poi rounding


【解决方案1】:

this answer。看起来这个问题与某个版本的 java 8 中的 rounding bug 有关。这已通过 8u40 (Release Notes) 修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多