无法投射物品' jxl.biff.EmptyCell@47821b4b'与班级' jxl.biff.EmptyCell'上课' jxl.DateCell'

时间:2016-02-21 14:29:11

标签: grails xls grails-controller jxl grails-2.4

我的域名模型

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文件加载数据没有保存,我得到以下错误。     无法投射物品&#39; jxl.biff.EmptyCell@47821b4b'与班级&#39; jxl.biff.EmptyCell&#39;上课&#39; jxl.DateCell&#39;。

1 个答案:

答案 0 :(得分:0)

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

dateOfBirth单元格为空时,请确保将null设置为dataOfBirth。如果您对dateOfBirth字段有约束,它将自动抛出exception

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

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

和/或

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

    }

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