如何在 DataFormatter 中编辑模式?

How do I edit pattern in DataFormatter?

我想用Java读取Excel中的数据,Excel中单元格的数据有两种类型NUMERICSTRING。所以当我想读取数据为NUMERIC时,它只显示数字101125340004,而不是像这样1.01E+11,因为它是一个电话属性。我的代码工作正常,但对于某些值 (1%) 仍然显示浮点数,但它们实际上是整数,我不知道为什么。

sheet 中的数据 Excel 365

DataFormatter fmt = new DataFormatter();
if (cellType.toString().equals("NUMERIC"))
    companyTel = fmt.formatCellValue(currentRow.getCell(8));
else
    companyTel = currentRow.getCell(8).toString();  

输出仍然是数据库中的浮点数

我使用的 Java Apache POI 版本是 3.17。

请告诉我上面的代码有什么问题或者我该如何解决这个问题?谢谢大家

正如documentation所说:

Internally, formats will be implemented using subclasses of Format such as DecimalFormat and SimpleDateFormat. Therefore the formats used by this class must obey the same pattern rules as these Format subclasses. This means that only legal number pattern characters ("0", "#", ".", "," etc.) may appear in number formats. Other characters can be inserted before or after the number pattern to form a prefix or suffix.

For example the Excel pattern "$#,##0.00 "USD"_);($#,##0.00 "USD")" will be correctly formatted as ",000.00 USD" or "(,000.00 USD)". However the pattern "00-00-00" is incorrectly formatted by DecimalFormat as "000000--". For Excel formats that are not compatible with DecimalFormat, you can provide your own custom Format implementation via DataFormatter.addFormat(String,Format). The following custom formats are already provided by this class:

  • SSN "000-00-0000"
  • Phone Number "(###) ###-####"
  • Zip plus 4 "00000-0000"

您也可以像这样添加自己的格式:

DataFormatter.addFormat(String, Format)

试试这个它可能对你有帮助:-

HSSFCell cellE1 = row1.getCell((short) 4);
cellE1.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
Double e1Val = cellE1.getNumericCellValue();
BigDecimal bd = new BigDecimal(e1Val.toString());
long lonVal = bd.longValue();
System.out.println(lonVal);

Microsoft Excel 在使用单元格编号格式 General 时,将超过 11 位的值转换为科学计数法。因此 842223622111 导致 Excel 单元格中的 8,42224E+11 具有数字格式 General。如果在 Excel 中,单元格应显示 842223622111,则需要一种特殊的数字格式 (0) 而不是 General.

您可以了解 available number formats in Excel for Office 365 以及 General 格式对大数字(12 位或更多位)的特殊行为。

Libreoffice/OpenOffice Calc不会这样做。在数字格式为 General.

的单元格中 842223622111 保留 842223622111

现在,如果 apache poi 得到一个包含 842223622111 且数字格式为 General 的单元格,那么 DataFormatter 将像 Excel 一样格式化.

如果您希望 DataFormatter 将其格式化为 Libreoffice/OpenOffice Calc,那么您可以这样做:

...
DataFormatter fmt = new DataFormatter();
...
fmt.addFormat("General", new java.text.DecimalFormat("#.###############"));
...

使用此方法,无需更改 Excel sheet。但是当然 apache poiDataFormatter 的默认行为被改变了。为避免这种情况,您可以使用数字格式 0 格式化 Excel 中受影响的单元格,即 Number 没有千位分隔符且小数点后位数 = 0.

但是由于您提到此列包含电话号码,最常见的解决方案是使用数字格式 Text (@) 对整个列进行格式化。 "treats the content of a cell as text and displays the content exactly as you type it, even when you type numbers." 所以在应用格式之后,没有任何东西会再改变为科学记数法。