Groovy 当遇到字母数字值时,脚本无法从 NUMERIC 单元格异常中获取 STRING 值

Groovy script not getting STRING value from a NUMERIC cell exception when alpha numeric value encounter

我正在尝试使用 Groovy 脚本读取 Soap Ui 中的 excel 数据。一切看起来都很好,除非脚本尝试获取 excell 单元格数据然后抛出异常。我不确定如何结合使用以下两项:

log.info cell.getNumericCellValue()
log.info cell.getStringCellValue()

我的 Excel 数据是这样的:

Column1  Column2

USA         1
CANADA      2
FRANCE      3

以下是我的代码:

import org.apache.poi.xssf.usermodel.*


def fs = new FileInputStream("C:\File\Book2.xlsx")
def wb = new XSSFWorkbook(fs)
def ws = wb.getSheet("Sheet1")
def r = ws.getPhysicalNumberOfRows()


for(def i=0; i<r; i++){

    def row = ws.getRow(i)
    def c = row.getPhysicalNumberOfCells()

    for (def j=0; j<c; j++) {

        def cell = row.getCell(j)

         log.info cell.getStringCellValue()
    }
}

当我 运行 上面的代码时,当我的 excel 包含一列具有 Alpha 值而另一列具有数值时,我得到以下异常:

java.lang.illegalStateException:Cannot get a STRING value from a NUMERIC cell

当我将 log.info cell.getStringCellValue() 更新为 log.info cell.getNumericCellValue() 时,它会抛出以下异常:

 java.lang.illegalStateException:Cannot get a NUMERIC value from a STRING cell

我做了一些研究,发现这是我们解析值的方式:

我只是在下面的代码中将 cell.getStringCellValue() 替换为 cell.toString(),异常问题已解决。

更新后的代码如下:

import org.apache.poi.xssf.usermodel.*


def fs = new FileInputStream("C:\File\Book2.xlsx")
def wb = new XSSFWorkbook(fs)
def ws = wb.getSheet("Sheet1")
def r = ws.getPhysicalNumberOfRows()


for(def i=0; i<r; i++){

    def row = ws.getRow(i)
    def c = row.getPhysicalNumberOfCells()

    for (def j=0; j<c; j++) {

        def cell = row.getCell(j)

         log.info cell.toString()
    }
}