使用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
相关产品推荐
相关产品推荐

