为了账号安全,请及时绑定邮箱和手机立即绑定

使用Java从Excel读取数据时如何只提取整数值而不是Double值

使用Java从Excel读取数据时如何只提取整数值而不是Double值

慕姐8265434 2023-04-13 15:17:10
我需要一个代码,它应该从 Excel 中获取数据作为 int 值而不是 String 值。2.0它显示最初保存在工作表中的值2`尝试 1:HSSFCell number = sheet.getRow(1).getCell(26);Integer result =Integer.valueOf(number);                System.out.println(result);尝试 2:int L = Integer.parseInt(getRow(1).getCell(26));Error:The method parseInt(String) in the type Integer is not applicable for the arguments (Cell)代码:System.out.println(+sheet.getRow(1).getCell(26));输出:2.0预期输出:2
查看完整描述

3 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

我推荐以下方式,它不会尝试将 an 转换HSSFCell为Integer/ int:


// get the cell as object (this is NOT a number, instead, it contains one)

HSSFCell numberCell = sheet.getRow(1).getCell(26);

// get the cell value as double (there is no direct integer version)

double cellValue = numberCell.getNumericCellValue();

// cast the value to an int

int number = (int) cellValue;


查看完整回答
反对 回复 2023-04-13
?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

从 Excel 中读取Double值而不是将值显示为2.0后,要将其打印为2 ,您可以使用DecimalFormat 类方法,并且可以使用以下解决方案:


HSSFCell number = sheet.getRow(1).getCell(26);

Double result =Double.valueOf(number);                

DecimalFormat format = new DecimalFormat();

format.setDecimalSeparatorAlwaysShown(false);

System.out.println(format.format(result));

如果您的用例是打印您可以添加的字符串String.valueOf()格式,您可以使用以下解决方案:


HSSFCell number = sheet.getRow(1).getCell(26);

Double result =Double.valueOf(number);                

DecimalFormat format = new DecimalFormat();

format.setDecimalSeparatorAlwaysShown(false);

System.out.println(String.valueOf(format.format(result)));


查看完整回答
反对 回复 2023-04-13
?
慕的地10843

TA贡献1785条经验 获得超8个赞

你可以试试

int L = Integer.parseInt(getRow(1).getCell(26).getStringCellValue());


查看完整回答
反对 回复 2023-04-13
  • 3 回答
  • 0 关注
  • 98 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信