I want to Import an XLSX-File with Help of Apache-POI (XSSF and SAX Event API).
Because Excel stores numbers as floating-point numbers it is necessary in java to format them back to the way they originally look in Excel. This is possible by reading the cell-format:
String cellStyle = sheetReader.getAttributeValue(null, "s");
if (cellStyle != null) {
// save the format of the cell for later use.
int styleIndex = Integer.parseInt(cellStyle);
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
formatIndex = style.getDataFormat();
formatString = style.getDataFormatString();
if (formatString == null) {
// formatString could not be found, so it must be a builtin format.
formatString = BuiltinFormats.getBuiltinFormat(formatIndex);
}
}
...
// format the floating-point value
String xlsxValue = formatter.formatRawCellContents(
Double.parseDouble(value),
formatIndex,
formatString);
The above code does work well for me... but it gives me the numbers like they are originally formatted in Excel while running Excel in Germany Locale. Example for such numbers:
10,30
100.00.00,43
Now how can i reformat those numbers so that they can be fed to Java Double and Java BigDecimal?
Apache-POI seemingly does not provide Utility-Classes for this case, but how can the numbers be processed in java then?
I have hacked my way into poi to make this happen like this, but is there no other way?
// hack apache-poi classes that are private, so we can retrieve the 'format'
// which helps us to transform the formated value to the expected java-format
CellStyle style = new CellStyleHack(formatIndex, formatString);
Cell cell = new CellHack(Double.parseDouble(xlsxValue), style);
java.text.Format format = formatter.createFormat(cell);
if (format instanceof DecimalFormat) {
DecimalFormat decimalFormat = ((DecimalFormat) format);
char dSep = decimalFormat.getDecimalFormatSymbols().getDecimalSeparator();
char gSep = decimalFormat.getDecimalFormatSymbols().getGroupingSeparator();
String cSymbol = decimalFormat.getDecimalFormatSymbols().getCurrencySymbol();
// java always expects '.' as decimal seperator for BigDecimal and Double.
xlsxValue = xlsxValue.replace("" + gSep, "");
xlsxValue = xlsxValue.replace(dSep, '.');
if (cSymbol != null) {
xlsxValue = xlsxValue.replace(cSymbol, "").trim();
}
}
Locale.US? Or setting LocaleUtil.setUserLocale toLocale.USbefore using theDataFormatter?formatter = new DataFormatter(Locale.US). And i have tryed using theformatRawCellContents--> With value: "1333", format-string: "#,##0" result: "1,333". With value: "1", format-string: "0.00", result: "1.00". So it really does change something, but it still produces "," in result. But thanks this helps. It would be a solution if with Locale.US it would never produce a comma.