使用POI获取excel单元格的实际单元格值而不定义数据类型 [英] Get actual cell value of excel cell with POI without defining a datatype

查看:58
本文介绍了使用POI获取excel单元格的实际单元格值而不定义数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I catch my cells from an .xls file like this:

cell.getStringCellValue();

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

But since some of the cells are numeric, I have to do this instead:

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

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

since it's getting a double and then converts it to a string this results in some unwanted operations like:

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

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

How do I solve this and get the actual cell value instead of some converted numbers? Also, all of the cells are defined as default in excel

推荐答案

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

You can use Apache POI DataFormatter's formatCellValue(Cell cell) method as it returns the formatted value of a cell as a String regardless of the cell type.

根据DataFormatter doc -

DataFormatter 包含格式化存储在一个细胞.这对于报告和 GUI 演示很有用需要完全按照 Excel 中显示的方式显示数据.支持的格式包括货币、SSN、百分比、小数、日期、电话号码、邮政编码等

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);

这篇关于使用POI获取excel单元格的实际单元格值而不定义数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆