首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Apache-POI解析Excel格式到BigDecimal

用Apache-POI解析Excel格式到BigDecimal
EN

Stack Overflow用户
提问于 2018-02-09 08:33:01
回答 1查看 7.8K关注 0票数 5

我想在Apache (XSSF和SAX事件API)的帮助下导入XLSX文件。

因为Excel将数字存储为浮点数,所以在java中有必要将其格式化为它们在Excel中的最初外观。这可以通过读取单元格格式来实现:

代码语言:javascript
复制
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);

上面的代码对我很有用..。但是它给了我一些数字,就像它们最初是在Excel中格式化的,而在德国地区运行Excel。例如,这些数字:

代码语言:javascript
复制
10,30
100.00.00,43

现在,我如何重新格式化这些数字,以便将它们输入Java和?

Apache似乎没有为这种情况提供实用程序类,但是如何在java中处理这些数字呢?

为了让这一切发生,我已经黑进了poi,但没有别的办法吗?

代码语言:javascript
复制
// 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();
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-09 13:03:07

在@AxelRichter的帮助下,下面的解决方案现在解决了我的问题:

代码语言:javascript
复制
// we must use Locale.US, because we want to make sure that the DataFormatter will
// always product "." as decimal-separator and "," as thousands-separator.
this.formatter = new DataFormatter(Locale.US);

// format the floating-point value
String xlsxValue = formatter.formatRawCellContents(
        Double.parseDouble(value),
        formatIndex,
        formatString);

// xlsxValue may contain format-symbols, which we need to remove...
xlsxValue = xlsxValue.replaceAll("[^\\d.]", "");
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48701673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档