我正在使用 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:
正如您在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();
}
}
导致:
因此,5.2597614320233098E-2
是直接来自 XML
的值。 0.052597614320233098
是 BigDecimal
形式的值。 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/