java - excel中的数字单元格值读取异常,小数点后附加额外数字

标签 java excel apache-poi numeric

请在下面找到代码片段。该实现读取 Excel 工作表中特定列的单元格值。

诸如 459000.00 之类的数值被代码读取为 459000.00000000006。它对于少数数字来说工作正常,但对于某些数字来说却失败了。

 try
                {
                String AmountColumn="C";
                File FS = new File(FileLocation);
                FileInputStream FileStream = new FileInputStream(FS);
                XSSFWorkbook FileWorkbook = new XSSFWorkbook(FileStream);
                Sheet FileWorksheet = FileWorkbook.getSheetAt(0);
                double[] AmountArray = new double[FileWorksheet.getPhysicalNumberOfRows() - 1];
                Iterator<Row> iterator2 = FileWorksheet.iterator();
                int i2 = 0;

                while (iterator2.hasNext())
                {
                if (i2 == 0)
                {
                iterator2.next();
                }
                else
                {
                AmountArray[i2 - 1] = iterator2.next().getCell(CellReference.convertColStringToIndex(AmountColumn)).getNumericCellValue();
                System.out.println("Amount is: " + AmountArray[i2 - 1]);
                }
                i2++;
                }
                Amount = AmountArray;
                }
                catch (Exception e)
                {
                e.printStackTrace();
                }

最佳答案

Excel 比 Java 对结果进行更多舍入。存储的真实值可能是 459000.00000000006,但显示为 459000.0

如果我在 Excel 中输入 459000.00000000006 ,它会显示 459000

一个简单的解决方案是对您获得的名称进行一点四舍五入。

例如四舍五入到小数点后 6 位

/**
 * Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it
 * might be rounded up or down. This is a pragmatic choice for performance reasons as it is
 * assumed you are not working on the edge of the precision of double.
 *
 * @param d value to round
 * @return rounded value
 */
public static double round6(double d) {
    final double factor = 1e6;
    return d > WHOLE_NUMBER / factor || d < -WHOLE_NUMBER / factor ? d :
            (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}

https://github.com/OpenHFT/Chronicle-Core/blob/master/src/main/java/net/openhft/chronicle/core/Maths.java#L121

关于java - excel中的数字单元格值读取异常,小数点后附加额外数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158233/

相关文章:

java - 为什么 Java 接口(interface)在文档中有描述

java - Exception.getMessage() 为空

java - Apache-POI : How to set background color of a cell when creating spreadsheet?

带有正则表达式的 Java String.split()

java - Android - 如何找出当前线程的创建位置?

excel - VBA在工作表的给定范围内保护和取消保护

Perl Excel 解析器截断列

excel - VBA VLookUp-不起作用,但没有错误

java - 我得到的是公式而不是单元格内容

java - 如何使用 Apache POI 通过 Google App Engine 读取电子表格?