我正在使用Apache POI检索单元格double值:
1.以openxml格式存储的单元格的实际值为“ 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:
如您在5.25976143202331%
中看到的A1
。它是德语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个)。%
值的例外是因为%
中的Excel
格式不仅是格式,而且是值的更改。 1
= 100%
。因此,如果将100%
放在Excel
单元格中,则会存储值1
。如果将10%
放在Excel
单元格中,则会存储值0.1
。关于java - excel单元格值精度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44216409/