java - Excel单元格值精度

标签 java excel apache apache-poi aspose

我正在使用 Apache POI 检索单元格 double 值:

1.openxml格式存储的cell实际值为“5.259761432023309”, 2.同一单元格的格式化显示值为“5.26%”。 3.然而,MS Excel公式栏上显示的值为“5.25976143202331%”

使用 Apache POI,我能够检索:

值1,使用cell.getNumericValue();

我也可以检索 值 2,使用 DataFormatter df = new DataFormatter();String asItLooksInExcel = df.formatCellValue(cell);

但是,我无法检索值 3,即编辑栏上显示的值,请建议检索相同值的方法。

最佳答案

我无法证实您的观察结果。

如果我有以下 Excel:

enter image description here

正如您在A1中看到的5.25976143202331%。它是德语 Excel,因此小数点分隔符是逗号。但这并不重要。

XML 是:

<sheetData>
 <row r="1" spans="1:1" x14ac:dyDescent="0.25">
  <c r="A1" s="1">
   <v>5.2597614320233098E-2</v>
  </c>
 </row>
</sheetData>

以及以下代码

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

import org.apache.poi.ss.format.CellNumberFormatter;

import java.io.*;

import java.math.BigDecimal;
import java.util.Locale;

class ExcelProcentValuePrecision {

 public static void main(String[] args) throws Exception{

  InputStream inp = new FileInputStream("ExcelProcentValuePrecision.xlsx");
  Workbook workbook = WorkbookFactory.create(inp);

  Cell cell = workbook.getSheetAt(0).getRow(0).getCell(0);

  String s = ((XSSFCell)cell).getCTCell().getV();
  System.out.println(s);

  BigDecimal bd = new BigDecimal(s);
  System.out.println(bd);

  double d = cell.getNumericCellValue();
  System.out.println(d);

  Locale.setDefault(Locale.US);

  DataFormatter dataformatter = new DataFormatter();
  s = dataformatter.formatCellValue(cell);
  System.out.println(s);

  CellNumberFormatter formatter = new CellNumberFormatter("#.#################%");
  s = formatter.format(cell.getNumericCellValue());
  System.out.println(s);

  workbook.close();

 }
}

导致:

enter image description here

因此,5.2597614320233098E-2 是直接来自 XML 的值。 0.052597614320233098BigDecimal 形式的值。 0.0525976143202331 是根据 IEEE floating point 的浮点 double 值。 5.26%Excel 中显示的格式化值。

5.25976143202331%Excel 编辑栏中显示的值。百分比值是一种特殊情况,因为 Excel 在公式栏中也显示 % 格式,但具有完整的有效数字(最多 15 位)。

% 值的异常(exception)是因为 Excel 中的 % 格式化不仅是格式化,而且还更改了值。 1 = 100%。因此,如果您将 100% 放入 Excel 单元格中,则会存储值 1。如果将 10% 放入 Excel 单元格中,则会存储值 0.1

关于java - Excel单元格值精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44216409/

相关文章:

java - 从 Singleton 触发 GWT SimpleEventBus 事件时出现 Nullpointer [Umbrella]Exception

excel - 代码执行被中断

c# - 包含来自 SSRS 报告的多个工作表的 Excel 文件

java - Luke - 当前位置没有有效的目录

java - 为不带参数的 boolean 方法编写 Junit 测试

java - 如何在 PDF 输出的同一行上显示 Excel 文件中两个不同大小的数组?

java - 使用 VSCode 发送电子邮件(spring-boot-starter-email)

excel - 在 Excel 中过滤大型列表的最佳方法是什么?

linux - 在 Ubuntu 14.04 上安装 ColdFusion 9,运行连接器向导时出错

php - .htaccess – 重写对index.php的所有请求,除了某些目录中的文件