How to take data from csv file and save to grails using mysql?

example: I have a CSV file like this

enter image description here

and I want it to be saved in the database .. with loading CSV files.

this is my coding for loading csv file

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

I got confused in groovy .. I tried like this code but didn't succeed.

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

Parsing CSV and exporting to the Mysql database in Grails

how to get data from csv file and save it in mysql database?

+4
source share
2 answers

You need to get an InputStream from the MultipartFile , which you pass as shown in the documentation:

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

Then;

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

You can do it.

  • Grails CSV CSV
plugins {       
      //TODO other plugins          
      compile(":csv:0.3.1") // add this entry in BuildConfig.groovy        
    }

, csv /,

  • /

    //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)
      }
    }
    

    }

0

Source: https://habr.com/ru/post/1523857/


All Articles