Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy load .csv files

Tags:

import

csv

groovy

How to read and import .csv file in groovy on grails. I have .csv file with data and
need to import in to db using user interface .

like image 234
Srinath Avatar asked Apr 12 '10 10:04

Srinath


People also ask

How read and write csv file in Java?

You can Download OpenCSV Jar and include in your project class path. CSVReader – This class provides the operations to read the CSV file as a list of String array. CSVWriter – This class allows us to write the data to a CSV file.


2 Answers

There are as always different possibilities to work with CSV files in Groovy.

As Groovy is fully interoperable with Java, you can use one of the existing CSV libararies, e.g. OpenCSV.

Depending on the complexity of the CSV file you are using, you can also use the standard file/string handling possibilities of Groovy:

def sql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb",   "user", "pswd", "com.mysql.jdbc.Driver") def people = sql.dataSet("PERSON") new File("users.csv").splitEachLine(",") {fields ->   people.add(     first_name: fields[0],     last_name: fields[1],     email: fields[2]   ) } 

EDIT: Kelly Robinson just wrote a nice blog post about the different possibilities that are available to work with CSV files in Groovy.

EDIT #2: As Leonard Axelsson recently released version 1.0 of his GroovyCVS library, I thought I should definitely add this to the list of options.

like image 173
Christoph Metzendorf Avatar answered Nov 04 '22 02:11

Christoph Metzendorf


Using xlson's GroovyCSV:

@Grab('com.xlson.groovycsv:groovycsv:1.3') import static com.xlson.groovycsv.CsvParser.parseCsv  for(line in parseCsv(new FileReader('countries.csv'), separator: ';')) {     println "Country=$line.COUNTRY, Capital=$line.CAPITAL" } 

The field names are taken from the header of the CSV file.
If the CSV file has no header, you can specify the field names programmatically.

like image 21
Nicolas Raoul Avatar answered Nov 04 '22 00:11

Nicolas Raoul