读取Excel数值单元格值,因为它们在Java中 [英] Read Excel Numeric cell values as they are in Java

查看:456
本文介绍了读取Excel数值单元格值,因为它们在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I am reading excel numeric cell values, i am getting the output with decimals. eg: 79 is reading as 79.0, 0.00 reading as 0.0. The code for my application I have written is:

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


推荐答案

这个问题在Stack Overflow上出现了很多你会很乐意看看很多类似的东西,看看答案!

This question comes up a lot on Stack Overflow, so you'd be well advised to look through many of the similar ones to see there answers!

Excel将文件格式中几乎所有的数字都存储为浮点值,这就是为什么POI会给你一个数字单元格的双倍,因为这是真正的。如果您希望在Excel中看起来像这样,您需要将针对单元格定义的格式规则应用于数字。因此,您希望完成同样的事情,如我在这里的答案。引用:

Excel stores almost all numbers in the file format as floating point values, which is why POI will give you back a double for a numeric cell as that's what was really there. If you want it to look like it does in Excel, you need to apply the formatting rules defined against the cell to the number. Thus, you want to do exactly the same thing as in my answer here. To quote:


你想做的是使用 DataFormatter类。你传递一个单元格,它最好返回一个包含Excel将显示给该单元格的字符串。如果你传递一个字符串单元格,你会得到字符串。如果你传递一个格式化规则应用的数字单元格,它将根据它们格式化数字,并给你字符串。

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.

对于你的情况,我会假设数字单元格应用了整数格式规则。如果您要求DataFormatter格式化这些单元格,那么它将返回一个带有整数字符串的字符串。

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

这篇关于读取Excel数值单元格值,因为它们在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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