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

使用Selenium读取Excel日期,解析字符串转整数报错:For input string: "5"求助

解决Selenium读取Excel日期解析整数失败问题

错误排查

报错For input string: "5"的核心原因是:你读取到的cellValue并非纯"5-Feb-2000",而是包含首尾双引号的完整字符串(即实际值为"\"5-Feb-2000\"")。此时用split("-")[0]得到的不是纯数字"5",而是带前引号的"\"5",自然无法被Integer.parseInt解析为整数。

解决方案

方案1:先去除字符串首尾的双引号

在拆分前先清理掉cellValue中的首尾引号,再执行拆分和解析操作:

// 去除首尾双引号
String cleanedCellValue = cellValue.replaceAll("^\"|\"$", "");
// 拆分日期部分
String day = cleanedCellValue.split("-")[0];
int intDay = Integer.parseInt(day);

// 同理解析年份
String year = cleanedCellValue.split("-")[2];
int intYear = Integer.parseInt(year);

如果确定首尾一定有引号,也可以用substring直接截取:

String cleanedCellValue = cellValue.substring(1, cellValue.length() - 1);

方案2:直接读取Excel日期格式单元格(更可靠)

如果Excel中的单元格是日期格式而非文本格式,建议直接用POI的日期API读取,避免字符串拆分的麻烦:

// 假设cell是你获取到的Excel单元格对象
if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
    Date date = cell.getDateCellValue();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int intDay = cal.get(Calendar.DAY_OF_MONTH);
    int intYear = cal.get(Calendar.YEAR);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:53:11