Groovy load .csv files

前端 未结 6 625
孤城傲影
孤城傲影 2020-12-23 20:01

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 .

6条回答
  •  無奈伤痛
    2020-12-23 20:59

    With Apache Commons-CSV

    @Grab('org.apache.commons:commons-csv:1.2')
    import org.apache.commons.csv.CSVParser
    import static org.apache.commons.csv.CSVFormat.*
    
    import java.nio.file.Paths
    
    Paths.get('countryInfo.txt').withReader { reader ->
        CSVParser csv = new CSVParser(reader, DEFAULT.withHeader())
    
        for (record in csv.iterator()) {
            println record.dump()
        }
    }
    

    Commons-CSV has nice API and I recommend that.


    With GroovyCSV:

    @Grab('com.xlson.groovycsv:groovycsv:0.2')
    import com.xlson.groovycsv.CsvParser
    
    def csv = '''Name,Lastname
    Mark,Andersson
    Pete,Hansen'''
    
    def data = new CsvParser().parse(csv)
    for(line in data) {
        println "$line.Name $line.Lastname"
    }
    

    (Taken from it's samples)


    Last resort: Regular expression.

    Here's how I parsed a file that might contain a quoted escaped string in it's fourth column:

        File detailedStatsFile = new File("stats.csv");
        detailedStatsFile.eachLine { line, number ->
            // Number Of Executions, Total Milliseconds, Milliseconds per execution, "Type"
            def match = line =~ /([^,]*?),\s*([^,]*?),\s*([^,]*?),\s*(?:([^",]+)|(?:"((?:[^\\"]++(?:\\")?)++)"))$/; //"
    
            if (!match.matches())
                continue;
    
            def numberOfExecs = Integer.valueOf(match.group(1));
            def totalMillis = Integer.valueOf(match.group(2));
            def detailedStatName = match.group(4);
            if (detailedStatName == null)
                detailedStatName = match.group(5).replaceAll('\\"','"');
    

提交回复
热议问题