0

我的领域模型

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”的对象“jxl.biff.EmptyCell@47821b4b”转换为类“jxl.DateCell”。

4

1 回答 1

0

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

当单元格为空时,请确保设置dateOfBirth为。如果您对字段有限制,它将自动抛出一个. nulldataOfBirthdateOfBirthexception

constraints意味着Person类中的所有属性都是必需的。显然,Excel 工作表中有空白字段会导致整个过程停止。如果您仍然想忽略那些带有空字段的行并仍然处理好的行,您可以执行以下一项或两项操作:

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

和/或

用 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
        }

    }

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

于 2016-02-21T15:02:50.200 回答