user2809386
user2809386

Reputation:

how to take data from csv file and save into grails with mysql?

example : i have a CSV file like this

enter image description here

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

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'])}"'/>

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

Parse CSV and export into Mysql database in Grails

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

Upvotes: 4

Views: 6710

Answers (2)

Motilal
Motilal

Reputation: 276

You could do this way.

  1. use the Grails CSV plugin to upload and parse the CSV files
plugins {       
      //TODO other plugins          
      compile(":csv:0.3.1") // add this entry in BuildConfig.groovy        
    }

make sure you have the csv data in controller/service and here you go

  1. in controller/service use below logic

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

    }

Upvotes: 0

tim_yates
tim_yates

Reputation: 171114

You need to get the InputStream from the MultipartFile you are passed 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()}")
    }
}

Upvotes: 7

Related Questions