我的域模型
package sample
class Person {
String lastName
String firstName
Date dateOfBirth
int numberOfChildren
static constraints = {
}
}
我的 Controller
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'。
最佳答案
在某些情况下,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
}
}
为了更好地了解哪个字段验证失败,请编写正确的字段验证错误消息。