
升级 Apache POI 的 jar 包后,旧的 HSSFCell.CELL_TYPE_* 常量不可用,相关代码会编译报错。本文说明原因和替换方法。
错误原因
jar 包版本更新,官方改动。
解决方法
- 导入CellType包:import org.apache.poi.ss.usermodel.CellType
- 使用CellType.STRING代替HSSFCell.CELL_TYPE_STRING
修改后的代码
if(cell==null||cell.getCellType()==CellType.BLANK){value="null";}else {//判断数据类型switch (cell.getCellType()) {case FORMULA:value = "" + cell.getCellFormula();break;case NUMERIC:value = "" + cell.getNumericCellValue();break;case STRING:value = cell.getStringCellValue();break;default:break;}}修改前的代码(对照)
if(cell==null||cell.equals("")||cell.getCellType()==HSSFCell.CELL_TYPE_BLANK){value="null";}else {//判断数据类型switch (cell.getCellType()) {case HSSFCell.CELL_TYPE_FORMULA:value = "" + cell.getCellFormula();break;case HSSFCell.CELL_TYPE_NUMERIC:value = "" + cell.getNumericCellValue();break;case HSSFCell.CELL_TYPE_STRING:value = cell.getStringCellValue();break;default:break;}}小结
核心改动就是把 HSSFCell.CELL_TYPE_* 换成 CellType.*,并导入 org.apache.poi.ss.usermodel.CellType。getCellType() 的返回值也随之从 int 常量变为 CellType 枚举,switch 的 case 标签相应去掉 HSSFCell.CELL_TYPE_ 前缀。