我从 .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 DataFormatter
的 formatCellValue(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/