java - 使用 POI 获取 Excel 单元格的实际单元格值,无需定义数据类型

标签 java excel apache apache-poi

我从 .xls 文件中捕获我的单元格,如下所示:

cell.getStringCellValue();

但是由于某些单元格是数字,我必须这样做:

                try
                {
                    cells[colIx] = cell.getStringCellValue();
                } catch (IllegalStateException e)
                {
                    cells[colIx] = String.valueOf(cell.getNumericCellValue());
                }

因为它得到一个 double 值,然后将其转换为字符串,这会导致一些不需要的操作,例如:

  • 1 转换为 1.0(不是一个大问题)
  • 16711680 转换为 1.671168E7

如何解决这个问题并获取实际的单元格值而不是一些转换后的数字?此外,所有单元格都在 Excel 中定义为默认值

最佳答案

您可以使用 Apache POI DataFormatterformatCellValue(Cell cell) 方法,因为无论单元格类型如何,它都会以字符串形式返回单元格的格式化值。

根据DataFormatter文档-

DataFormatter contains methods for formatting the value stored in an Cell. This can be useful for reports and GUI presentations when you need to display data exactly as it appears in Excel. Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.

示例代码

DataFormatter dataFormatter= new DataFormatter();

// Inside loop
String cellValueStr = dataFormatter.formatCellValue(cell);

关于java - 使用 POI 获取 Excel 单元格的实际单元格值,无需定义数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953678/

相关文章:

java - 如何在managedBean之间传递参数

excel - 如何设置直方图x轴的最大和最小比例?

django - Apache SSL 请求证书

java - ClassDefNotFoundException 即使类是由类加载器加载的(服务器上安装了多个应用程序)

java - 如何到达在 Java 中实现 Runnable 的对象的方法?

java - FetchType.LAZY 在 OpenJPA 中获取 null

excel - 使用 Right()、Len() 和 Find() 输出公式时出现 VLOOKUP 错误

从 Excel VBA 运行 R,无需 RExcel

android - 如何使用 gradle 将 org.apache.commons.lang3 添加到 Android Studio

.net - 在 Ubuntu 和 Certbot 上使用 SSL 的 Blazor