Home » excel » Read value in Excel in Java, problems Windows vs Linux

Read value in Excel in Java, problems Windows vs Linux

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have app with Java in Springboot, I read the value numeric from cell 3123456,89, We are using in Excel the format the money European -> . Thousand and , decimals.

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

I read the cell as a String.

Then I parse this String to Double ->

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

I need this parse because We are insert numerics in format European but Java is format American ( , Thousand and . decimals)

This process IS CORRECT WITH WINDOWS.

Now I upload my app a Linux, I have any problems…

Now I get this value -> 3,123,456,89 , If I use replace -> "Error multiple points" If i wish replace , I lose part decimal…

I use apache.poi for read the Excels.

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

Finally In linux I have problems with this code, that, in windows is correct. thanks.

How to&Answers:

Seems your problem results from the fact, that in your Linux system Java uses a different default Locale than in your Windows system.

You can construct the DataFormatter having a special Locale. If that is Locale.US, then the whole replacement will not be necessary as the stringValue will be formatted for that Locale.US. Then you can use java.text.NumberFormat of the same locale to get the Number out of the string.

...
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
}
...

Another approach is getting the cell value as numeric value instead of as formatted string.

For apache poi 3.15 this would be like:

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

See also https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents.