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

当使用Apache POI库读取Excel文件中的数值单元格时,发现数字被以浮点数形式输出,例如79显示为79.0,0.00显示为0.0。解决办法是应用单元格的格式规则来格式化数值。通过使用DataFormatter类,可以获取与Excel中显示相同的字符串。DataFormatter会根据单元格的格式规则将数字转换为字符串,对于带有整数格式的数值单元格,它会返回整数字符串。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值