[英]Problem in reading Numeric value form Excel file using Apache POI
我有一個數字列,值為 0.142,但轉換為 0.14200000000000002
這是我的代碼,我使用 cell.getNumericCellValue()
case Cell.CELL_TYPE_NUMERIC :
vaTmpVal = String.valueOf(voCel.getNumericCellValue());
浮點數,正如您在以 10 為基數的編號系統(即 0 - 9)中所理解的那樣,無法以二進制(即 0 - 1)准確表示。 因此,大多數情況下,您將看到(從編程語言結構中)是該值的近似值。
在您的情況下,如果您不關心超過千分之一 position 的值的精度,則可以使用DecimalFormat :
import java.text.DecimalFormat;
public class Scratch {
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.000").format(0.142));
}
}
也僅供您參考,在 poi 的錯誤跟蹤器上已經詢問了這個確切的問題,並且已被關閉為“已解決無效”。
此外,作為一個有趣的小實驗來證明上述內容,在 jshell session 中執行以下命令:
% jshell
| Welcome to JShell -- Version 11
| For an introduction type: /help intro
jshell> 0.1*0.1
$1 ==> 0.010000000000000002
你會期望上面的答案只有 0.01; 然而,事實並非如此。
Cell.getNumericCellValue()
獲取與存儲時完全相同的數字單元格值。 但是Excel
始終只使用 15 位有效數字作為數值。 因此,對於Excel
,精確值0.14200000000000002
(具有 17 個有效數字)將為0.142
。
如果需要將所有單元格值作為字符串獲取,則不應通過CellType
獲取單元格值。 相反,您應該使用apache poi
的DataFormatter 。 DataFormatter.formatCellValue
方法通過將所有單元格值格式化為與Excel
相同的類型來獲取所有單元格值作為字符串。 因此,如果Excel
顯示0.142
作為單元格值,那么即使確切的數字單元格值為0.14200000000000002
, DataFormatter
也會得到0.142
。
例子:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.util.Locale;
class GetDataFromExcelUsingDataFormatter {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelExample.xlsx"));
DataFormatter dataFormatter = new DataFormatter();
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
System.out.println(cellValue);
}
}
workbook.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.