java - 读取 Excel 数字单元格值,因为它们在 Java 中

标签 java excel apache-poi

当我读取 excel 数字单元格值时,我得到带小数的输出。例如:79 读数为 79.0,0.00 读数为 0.0。我为我的应用程序编写的代码是:

int type = cell.getCellType();
if (type == HSSFCell.CELL_TYPE_NUMERIC)
  System.out.println(cell.getNumericCellValue());

最佳答案

这个问题在 Stack Overflow 上经常出现,因此建议您浏览许多类似的问题以找到答案!

Excel 将文件格式中的几乎所有数字都存储为浮点值,这就是为什么 POI 会为数字单元格返回一个 double 值,因为它确实存在。如果您希望它看起来像在 Excel 中一样,您需要将针对单元格定义的格式设置规则应用于数字。因此,您想做完全相同的事情 as in my answer here .引用:

What you want to do is use the DataFormatter class. You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.

For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.

您需要做的就是:

// Only need one of these
DataFormatter fmt = new DataFormatter();

// Once per cell
String valueAsSeenInExcel = fmt.formatCellValue(cell);

关于java - 读取 Excel 数字单元格值,因为它们在 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16482914/

相关文章:

vba - XMLHTTP 和 ServerXMLHTTP 之间的差异

excel - 当我已经使用 Workbooks.OpenText 打开它时关闭文本文件

java - Apache POI,处理 WorkbookFactory.create() 异常以获得更好的用户体验

java - 包含日期的单元格上的 DataFormatter 呈现两位数年份

Java Apache POI 在单元格中写入 double 值(德语 Excel)

java - 更改折线图Apache POI的颜色

java - JUnit 测试 Hadoop 可写

java - 如何使用 JNI android 获取应用程序构建配置(调试或发布)?

java - 如何更改 XML 文件中的特定行?

java - 在变量上使用多个 String 方法的正确方法是什么?