Wednesday, January 15, 2014

csv-2-List for groovycsv

@Grab('com.xlson.groovycsv:groovycsv:1.0')
import com.xlson.groovycsv.CsvParser
 
// a normally parsed csv can only be searched through ONCE
// this is used to create a "re-searchable" object (List of Maps)
List csv2List( String filePath, boolean shouldTrim = true ) {
    new File( filePath ).withReader { r ->
        new CsvParser().parse( r ).with { csv ->
            return csv.collect { line ->
                line.columns.collectEntries { c, v ->
                    [ c, (shouldTrim ? line[ c ].trim() : line[ c ]) ]
                }
            }
        }
    }
}

No comments:

Post a Comment