开发自动化测试代码遇Type mismatch错误:CellType无法转为int,求解决方案
解决Type mismatch: cannot convert from CellType to int错误
这个问题我之前帮不少开发者解决过,本质是Apache POI版本更新带来的API变化导致的:在较新的POI版本中,HSSFCell.getCellType()方法不再返回int类型,而是返回CellType枚举类型,所以你直接把它赋值给int变量type就会触发类型不匹配的错误。
这里给你两种可行的解决方案:
方案1:直接使用CellType枚举进行判断(推荐)
这种方式更符合现代Java编码规范,可读性更强,避免使用“魔法数字”带来的维护问题:
public static String cellToString(HSSFCell cell) { Object result; CellType type = cell.getCellType(); switch (type) { case NUMERIC : // Excel中的数值类型 result = cell.getNumericCellValue(); break; case STRING : // Excel中的字符串类型 result = cell.getStringCellValue(); break; default: throw new RuntimeException("不支持该类型单元格"); } return result.toString(); }
方案2:保留int类型判断(兼容旧写法)
如果你习惯用数字判断,可以调用枚举的getCode()方法获取对应的int值:
public static String cellToString(HSSFCell cell) { int type; Object result; type = cell.getCellType().getCode(); switch (type) { case 0 : // 对应CellType.NUMERIC的编码 result = cell.getNumericCellValue(); break; case 1 : // 对应CellType.STRING的编码 result = cell.getStringCellValue(); break; default: throw new RuntimeException("不支持该类型单元格"); } return result.toString(); }
个人更推荐第一种方案,枚举类型的语义更清晰,后续维护起来也更省心,还能避免因为POI版本调整编码值带来的潜在问题。
内容的提问来源于stack exchange,提问作者Excel




