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

如何解决Scala代码中CELL_TYPE_NUMERIC不属于Cell对象的报错?

解决Apache POI中CELL_TYPE_NUMERIC不是Cell对象成员的错误

这个报错的根源很明确——你用的是Apache POI 4.0及以上版本,这个版本已经彻底移除了Cell类里的CELL_TYPE_NUMERIC、CELL_TYPE_STRING这类常量,它们被迁移到类型更安全的CellType枚举类中了。

具体修改步骤:

  • 把匹配语句里的Cell.CELL_TYPE_NUMERIC替换成CellType.NUMERIC,Cell.CELL_TYPE_STRING替换成CellType.STRING
  • 优化myChoice的类型声明,直接用CellType代替Any,让代码更严谨

修改后的完整代码:

import java.io.File
import java.io.FileInputStream
import org.apache.poi.ss.usermodel.{Cell, CellType, Row}
import org.apache.poi.xssf.usermodel.{XSSFRow, XSSFSheet, XSSFWorkbook}

object Excel_read_switch_Scala {
  var row: XSSFRow = null

  @throws[Exception]
  def main(args: Array[String]): Unit = {
    val fis = new FileInputStream(new File("D:\\MyFirstExcel.xlsx"))
    val workbook = new XSSFWorkbook(fis)
    val spreadsheet = workbook.getSheetAt(0)
    val rowIterator = spreadsheet.iterator

    while (rowIterator.hasNext) {
      row = rowIterator.next.asInstanceOf[XSSFRow]
      val cellIterator = row.cellIterator

      while (cellIterator.hasNext()) {
        val cell = cellIterator.next
        // 直接声明为CellType类型,无需Any
        val myChoice: CellType = cell.getCellType
        myChoice match {
          // 使用CellType枚举的成员
          case CellType.NUMERIC => System.out.print(cell.getNumericCellValue + " \t\t ")
          case CellType.STRING => System.out.print(cell.getStringCellValue + " \t\t ")
        }
      }
      System.out.println()
    }
    fis.close()
  }
}

补充说明:

在POI 3.x版本中,我们确实是用Cell.CELL_TYPE_*这类int常量来判断单元格类型,但从POI 4.0开始,官方为了类型安全,把这些常量重构为CellType枚举,原来的常量先被标记为废弃,最终在更高版本中被完全移除。所以如果你是从旧版本代码迁移过来,就会遇到这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:23:42