繁体   English   中英

在 Java 中读取 Excel 中的值,问题 Windows 与 ZEDC9F0A5A5D577978368E373647

[英]Read value in Excel in Java, problems Windows vs Linux

我在 Springboot 中有带有 Java 的应用程序,我从单元格3123456,89中读取数值数字,我们在 Excel 中使用货币格式为欧洲 -> . 千和,小数。

String stringValue = new DataFormatter().formatCellValue(cell);

我将单元格读取为字符串。

然后我将此字符串解析为 Double ->

Double.parseDouble(stringValue .replaceAll("\\.", "").replaceAll(",", "."));

我需要这个解析,因为我们以欧洲格式插入数字,但 Java 是美国格式( ,千和.小数)

这个过程对于 WINDOWS 是正确的。

现在我上传我的应用程序 Linux,我有任何问题......

现在我得到这个值 -> 3,123,456,89 ,如果我使用替换 -> "Error multiple points"如果我希望替换,我会丢失部分小数...

我使用 apache.poi 来读取 Excel。

  <!-- EXCELS -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.15</version>
    </dependency>

最后在 linux 我有这个代码的问题,在 windows 是正确的。 谢谢。

似乎您的问题源于这样一个事实,即在您的Linux系统Java使用与Windows系统不同的默认Locale

您可以构造具有特殊LocaleDataFormatter 如果那是Locale.US ,则不需要整个替换,因为stringValue将针对该Locale.US进行格式化。 然后您可以使用相同语言环境的java.text.NumberFormat从字符串中获取Number

...
DataFormatter dataFormatter = new DataFormatter(java.util.Locale.US);
java.text.NumberFormat numberFormat = java.text.NumberFormat.getInstance(java.util.Locale.US);
String stringValue = dataFormatter.formatCellValue(cell);
Double doubleValue = null;
try {
 doubleValue = numberFormat.parse(stringValue).doubleValue();
} catch (Exception ex) {
 //do nothing
}
...

另一种方法是将单元格值作为数值而不是格式化字符串。

对于apache poi 3.15这将是这样的:

...
if (cell.getCellTypeEnum() == CellType.NUMERIC) {
 Double doubleValue = cell.getNumericCellValue();
}
...

另见https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM