我已经使用grails插件成功解析了csv。现在输出如下:
这就是我解析csvFile的方法。我需要将这个csv内容保存到database.How我可以这样做吗?
def upload = {
def f = request.getFile('filecsv')
if (f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
} else {
def file = request.getFile('filecsv')
def singlerow = file.inputStream.toCsvReader(['charset': 'UTF-8', 'separatorChar': '|']).eachLine{
line ->
println "The data are"+line
}
}
}
The data are[test, 2017-08-21, , , 2017-08-21, 100, 8668a73e55e0824c130337d49f0fc746, , Annual, , , , , , , , , , , , , , , , , , , , , test, 1111, test, test, 1901-03-13, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , asd/asd/sad/incentive/20170906/09062017.csv, 2017-09-06, , 4.7, 30430001]
The data are[test, 2017-10-07, , , 2017-08-07, 100, asdasdasdasd, , An, , , , , , , , , , , , , , , , , , , , , test, 1111, test, test, 1900-02-15, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , stat/test/test/incentive/20170906/ 09072017.csv, 2017-09-06, , 4.7, 30430001]
我的域名类:
class Data {
String data1
Date data12
Date data13
Date data14
Date data15
String data16
String data17
String data18
String data19
String data110
String data111
String data112
String data113
String data114
String data115
String data115
String data116
String data117
String data118
String data119
String data120
_____________
__________
___________
} 如何将其保存到此域类的数据库中。
答案 0 :(得分:0)
在不知道其他细节的情况下,我能想到的保存此类域实例的最简单方法是:
static dates = [ 11, 12, 13, 14 ] // positions of fields to be converted to Date
def upload = {
//...
file.inputStream.toCsvReader(['charset': 'UTF-8', 'separatorChar': '|']).eachLine{ line ->
def map = [:]
line.eachWithWithIndex{ d, ix ->
// if( d ) map[ "data${ix+1}" ] = dates.contains( ix ) ? Date.parse( 'yyyy-MM-dd', d ) : d
if( d ) map[ "data${ix+1}" ] = d // if you need no date conversion
}
Data data = new Data( map )
if( !data.save() ) log.warn "save failed: $data.errors"
}
}