【问题标题】:how to take data from csv file and save into grails with mysql?如何从 csv 文件中获取数据并使用 mysql 保存到 grails 中?
【发布时间】:2014-02-17 23:19:22
【问题描述】:

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

我希望它保存到数据库中..上传 CSV 文件。

这是我上传 CSV 文件的编码

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

我在 groovy 中感到困惑..我尝试过这样的代码,但没有成功。

    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()}")
}

Parse CSV and export into Mysql database in Grails

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

【问题讨论】:

  • grails.org/plugin/excel-import 可能值得一看
  • 另外,"...but not success" 是什么意思?你收到错误了吗?
  • 我已经编辑了我的帖子,我无法获取此路径 "" 但如果 new File('C:\\user \\desktop\\book1.csv').splitEachLine(',') {fields ->

标签: mysql grails csv groovy


【解决方案1】:

你需要从MultipartFile获取InputStream你通过as shown in the documentation:

<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()}")
    }
}

【讨论】:

  • 2014-01-27 16:44:54,047 [http-8080-4] 错误错误。GrailsExceptionResolver - 没有方法签名:org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile()适用于参数类型:(java.lang.String) 值:[filecsv] 可能的解决方案:getXML()、getAt(java.lang.String)、getAt(java.lang.String)、getLocale()、getJSON() , getHeader(java.lang.String) groovy.lang.MissingMethodException: 没有方法签名: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile()
  • 你在 GSP 中使用 uploadForm 是吗?
  • 只有这个在 g:form
  • 我的意思是我的答案的顶部......它需要在上传表单或多部分表单中
【解决方案2】:

你可以这样做。

  1. 使用 Grails CSV 插件上传和解析 CSV 文件
plugins {       
      //TODO other plugins          
      compile(":csv:0.3.1") // add this entry in BuildConfig.groovy        
    }

确保您在控制器/服务中有 csv 数据,然后就可以了

  1. 在控制器/服务中使用以下逻辑

    //Read the CSV file data excluding the header    
    filecsv.inputStream.toCsvReader(['skipLines':1]).eachLine { tokens ->    
    //parse the csv columns
    def name= tokens[0].trim()
    def class= tokens[1].trim()
    def age = tokens[2].trim()
    def phone = tokens[3].trim()
    
    //assign the csv column values to domain object
    City city = new City() // this is your domain/table that you used to insert csv data   
    city.name = name
    city.class = class
    city.age = age
    if(!city.save(validate: true)){
      city.errors.each {
      log.debug(it)
      }
    }
    

    }

【讨论】:

  • 目前的问题不是解析 CSV,而是在控制器中获取多部分表单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 2018-05-17
  • 2020-10-11
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多