You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Excel读取数据转Java对象时出现NumberFormatException错误

解决Java读取Excel字符串值时的NumberFormatException(输入字符串为"447475.0")

问题出在你读取的Excel单元格值虽然显示为整数,但实际被转成了带.0的字符串,而Long.parseLong()只能解析纯整数格式的字符串,因此触发异常。下面是几种可行的解决方法:

方法1:先清理字符串再转换

直接去掉字符串末尾的.0后缀,再进行Long转换:

String cellValue = getCellValue(row.getCell(positionMap.get(columnName)));
// 移除末尾的.0
String integerStr = cellValue.replaceAll("\\.0$", "");
Long targetLong = Long.parseLong(integerStr);

如果需要兼容更多小数场景(比如偶尔出现非.0的小数),可以用BigDecimal处理,确保转换安全:

String cellValue = getCellValue(row.getCell(positionMap.get(columnName)));
BigDecimal bd = new BigDecimal(cellValue);
// 确认是整数时用longValueExact(),非整数会抛异常;允许取整用longValue()
Long targetLong = bd.longValueExact();

方法2:从读取源头优化(针对Apache POI等Excel库)

如果使用Apache POI读取Excel,直接根据单元格类型处理,避免不必要的字符串转换:

Cell cell = row.getCell(positionMap.get(columnName));
Long targetLong = null;
if (cell != null) {
    switch (cell.getCellType()) {
        case NUMERIC:
            // 单元格是数值类型,直接取整转换
            targetLong = (long) cell.getNumericCellValue();
            break;
        case STRING:
            String cellStr = cell.getStringCellValue().trim();
            // 处理字符串格式的数值
            if (cellStr.contains(".")) {
                cellStr = cellStr.split("\\.")[0];
            }
            targetLong = Long.parseLong(cellStr);
            break;
        // 按需处理其他类型(如公式、空白等)
    }
}

注意事项

如果业务场景中Excel单元格可能存在非整数值(比如447475.5),需要提前明确处理规则:是抛出异常提示数据错误,还是直接截断小数部分,避免出现不符合预期的转换结果。

内容的提问来源于stack exchange,提问作者user3123934

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:35:03