如何从csv文件中获取数据并使用mysql保存到grails? [英] how to take data from csv file and save into grails with mysql?

查看:182
本文介绍了如何从csv文件中获取数据并使用mysql保存到grails?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:
i有一个这样的CSV文件

example : i have a CSV file like this

我希望将其保存到database..with上传CSV文件。

and i want it save in to database..with upload the CSV's files.

这是我上传CSV文件的编码

this is my coding for upload CSV file

<input type="file" name="filecsv"/>
<input type="button" class="upload" value="Upload 
             onclick='location.href ="${createLink(url: [action: 'upload'])}"'/>

我在groovy..i中混淆尝试像这样的代码,但不成功。 >

i confuse in groovy..i tried like this code but not success.

    def upload = {
        println params.filecsv
    new File('filecsv').splitEachLine(',') {fields ->
    def city = new City(
        city: fields[0].trim(),
        description: fields[1].trim()
    )

    if (city.hasErrors() || city.save(flush: true) == null) {
        log.error("Could not import domainObject  ${city.errors}")
    }

    log.debug("Importing domainObject  ${city.toString()}")
}

解析CSV并导出到Grails中的Mysql数据库

如何从文件CSV获取数据并将其保存到数据库mysql?

how to get data from file CSV and save it into database mysql?

推荐答案

您需要从 MultipartFile 如文档中所示:

<g:uploadForm action="upload">
    <input type="file" name="filecsv" />
    <input type="submit" />
</g:uploadForm>

然后;

def upload = {
    request.getFile( 'filecsv' )
          .inputStream
          .splitEachLine(',') { fields ->
        def city = new City( city: fields[0].trim(),
                             description: fields[1].trim() )

        if (city.hasErrors() || city.save(flush: true) == null) {
            log.error("Could not import domainObject  ${city.errors}")
        }

        log.debug("Importing domainObject  ${city.toString()}")
    }
}

这篇关于如何从csv文件中获取数据并使用mysql保存到grails?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆