读取Excel单元格的数字值,因为它们是在Java中 [英] Read Excel Numeric cell values as they are in Java
问题描述
当我读的Excel单元格的数字值,我得到带有小数的输出。例如:79阅读为79.0,0.00阅读0.0。我的应用程序的code我写的是:
int型的= cell.getCellType();
如果(类型== HSSFCell.CELL_TYPE_NUMERIC)
的System.out.println(cell.getNumericCellValue());
这个问题出现在堆栈溢出了很多,所以你会得到很好的建议,以期待通过许多类似的,看看那里的答案!
Excel存储几乎是在文件格式为浮点值,这是所有的数字为什么POI会给你回一个双对数字小区因为这是什么真的存在。如果你希望它看起来像它在Excel中那样,你需要申请对细胞数定义的格式规则。因此,你想要做同样的事情在我的答案这里。引用:
您想要做的是使用 DataFormatter类。你通过这一个单元格,并会尽力回报你什么包含Excel中会告诉你该小区的字符串。如果你传递一个字符串单元格,你会得到的字符串返回。如果你传递一个数字细胞与应用格式规则,它会格式化基于它们的数量,并给你的字符串返回。
有关你的情况,我会假设数字单元应用了一个整数格式规则。如果你问DataFormatter格式化这些细胞,它会给你回在它的整数字符串的字符串。
块引用>所有你需要做的是:
//只需要其中的一个
DataFormatter FMT =新DataFormatter();//每一次细胞
字符串valueAsSeenInExcel = fmt.formatCellValue(单元);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());
解决方案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 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:
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.
All you need to do is:
// Only need one of these DataFormatter fmt = new DataFormatter(); // Once per cell String valueAsSeenInExcel = fmt.formatCellValue(cell);
这篇关于读取Excel单元格的数字值,因为它们是在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!