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

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

问题描述

  cell.getStringCellValue(); 

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

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

因为它是一个双倍,然后将其转换为一个字符串,这导致一些




  • 1转换为1.0(不是那个大问题)

  • 16711680转换为1.671168E7



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

解决方案

可以使用Apache POI DataFormatter formatCellValue(单元格单元格)方法,因为它将字符串的格式化值作为字符串返回,而不管单元格类型。



根据 DataFormatter doc -


DataFormatter包含用于格式化存储在
单元格中的值的方法。当
需要完全按照Excel中显示的数据显示数据时,这可能对报表和GUI表示很有用。支持的格式
包括货币,SSN,百分比,小数,日期,电话号码,
邮政编码等。


示例代码

  DataFormatter dataFormatter = new DataFormatter(); 

//内循环
String cellValueStr = dataFormatter.formatCellValue(cell);


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

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

  • 1 converts into 1.0 (not that kind of a big problem)
  • 16711680 converts to 1.671168E7

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

解决方案

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.

According to DataFormatter doc -

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.

Sample code

DataFormatter dataFormatter= new DataFormatter();

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

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

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