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

从Excel读取邮编至Selenium脚本报错:Cannot get a STRING from NUMERIC cell

解决Selenium读取Excel邮编时的IllegalStateException错误

这个错误的根源非常明确:你尝试用getStringCellValue()读取一个数字类型的单元格,但该单元格里的邮编(V9G1Y3)本应被当作文本处理。Excel常会自动把含数字的内容识别为数字类型(哪怕内容里包含字母),或是你手动设置了单元格格式为数字,导致POI无法直接用字符串方法读取,从而抛出类型不匹配的异常。

下面给你几个可行的解决方案,按推荐程度排序:

方案1:使用DataFormatter统一读取为字符串(最推荐)

Apache POI提供的DataFormatter类可以根据单元格的格式返回对应的字符串,不管单元格原本是数字、文本还是其他类型,完美适配这种场景。

修改你的代码如下:

import org.apache.poi.ss.usermodel.DataFormatter;

// 初始化DataFormatter实例
DataFormatter formatter = new DataFormatter();
Cell cell = sheet.getRow(i).getCell(3);
// 统一将单元格内容转为字符串格式
String postalCodeValue = formatter.formatCellValue(cell);
driver.findElement(postalCode).sendKeys(postalCodeValue);

方案2:手动判断单元格类型并处理

如果你不想引入额外类,可以手动检查单元格类型,根据不同类型做读取逻辑:

Cell cell = sheet.getRow(i).getCell(3);
String postalCodeValue;

if (cell.getCellType() == CellType.STRING) {
    postalCodeValue = cell.getStringCellValue();
} else if (cell.getCellType() == CellType.NUMERIC) {
    // 邮编一般为整数格式,转字符串时直接取整即可
    postalCodeValue = String.valueOf((long) cell.getNumericCellValue());
} else {
    // 处理空白、公式等其他特殊类型
    postalCodeValue = "";
}

driver.findElement(postalCode).sendKeys(postalCodeValue);

方案3:修改Excel单元格格式为文本

从源头解决问题:打开你的Excel文件,选中邮编所在列,设置单元格格式为文本,之后重新输入或粘贴邮编内容。这样POI读取时会直接识别为字符串类型,原代码无需修改。

注意:如果已经输入内容后才修改格式,需要双击单元格并回车,让格式设置生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:36:14