无法将对象 'jxl.biff.EmptyCell@47821b4b' 与 class 'jxl.biff.EmptyCell' 转换为 class 'jxl.DateCell'

Cannot cast object 'jxl.biff.EmptyCell@47821b4b' with class 'jxl.biff.EmptyCell' to class 'jxl.DateCell'

我的域模型

package sample

class Person {

String lastName
String firstName
Date dateOfBirth
int numberOfChildren
static constraints = {
}
} 

我的控制器

package sample

/*imported libraries.*/

import jxl.DateCell
import jxl.LabelCell
import jxl.NumberCell
import jxl.Sheet
import jxl.Workbook

class PersonController {
private final static int COLUMN_LAST_NAME = 0
private final static int COLUMN_FIRST_NAME = 1
private final static int COLUMN_DATE_OF_BIRTH = 2
private final static int COLUMN_NUMBER_OF_CHILDREN = 3

 def index() {
    redirect(action: "list", params: params)
}

def list(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    [personInstanceList: Person.list(params), personInstanceTotal: Person.count()]
}

def upload() { }


    def doUpload() {
    def file = request.getFile('file')
    Workbook workbook = Workbook.getWorkbook(file.getInputStream());
    Sheet sheet = workbook.getSheet(0);

    // skip first row (row 0) by starting from 1
    for (int row = 1; row < sheet.getRows(); row++) {
        LabelCell lastName = sheet.getCell(COLUMN_LAST_NAME, row)
        LabelCell firstName = sheet.getCell(COLUMN_FIRST_NAME, row)
        DateCell dateOfBirth = sheet.getCell(COLUMN_DATE_OF_BIRTH, row)
        NumberCell numberOfChildren = sheet.getCell(COLUMN_NUMBER_OF_CHILDREN, row)

        new Person(lastName:lastName.string , firstName:firstName.string ,
                dateOfBirth:dateOfBirth.date, numberOfChildren:numberOfChildren.value).save()

    }
    redirect (action:'list')
}


} 

我想从我的 grails 数据库中的 .xls 文件加载数据问题是 xls 文件加载数据没有保存,我收到以下错误。 无法将对象 'jxl.biff.EmptyCell@47821b4b' 与 class 'jxl.biff.EmptyCell' 转换为 class 'jxl.DateCell'.

看起来,在某些情况下,dateOfBirth没有任何价值。在这些情况下,空值无法转换为日期。这就是抛出 can not cast class 'jxl.biff.EmptyCell' to class 'jxl.DateCell' 的原因。

确保在 dataOfBirth 单元格为空时将 dateOfBirth 设置为 null。如果你对 dateOfBirth 字段有限制,它会自动抛出一个 exception

constraints 表示 Person class 中的所有属性都是必需的。显然 Excel sheet 中有空字段导致整个过程停止。如果您仍然喜欢忽略那些具有空字段的行并仍然处理好的行,您可以执行以下一项或两项操作:

检查每个字段是否为空并调用继续处理下一行。这是我的建议。

AND/OR

用 try/catch:

在循环内换行
    for (int row = 1; row < sheet.getRows(); row++) {
        try{
                LabelCell lastName = sheet.getCell(COLUMN_LAST_NAME, row)
                LabelCell firstName = sheet.getCell(COLUMN_FIRST_NAME, row)
                DateCell dateOfBirth = sheet.getCell(COLUMN_DATE_OF_BIRTH, row)
                NumberCell numberOfChildren = sheet.getCell(COLUMN_NUMBER_OF_CHILDREN, row)
new Person(lastName:lastName.string , firstName:firstName.string ,
                        dateOfBirth:dateOfBirth.date, numberOfChildren:numberOfChildren.value).save(failOnError: true)
        }catch(e){
          // log the error and the row number so that you know which row failed
        }

    }

为了更好地了解哪个字段验证失败,请编写正确的字段验证错误消息。