简体   繁体   English

读取CSV文件并使用Grails / Groovy将结果放入地图中

[英]Read CSV file and put result in a map using Grails / Groovy

Im using the code below to read a csv file and would like to put result in a map 我使用下面的代码来读取csv文件,并希望将结果放在地图中

def fileName = 'C:/temp/exampleCSV.csv'
        def reader = new CSVReader(new FileReader(new File(fileName)))
        def header = reader.readNext()
        def rows = reader.readAll().collect { row ->
            (0..(row.size()-1)).collectEntries { [header[it], row[it]] }
        }

CSV: CSV:

name;cuInfo;service;startDate;appId
Apple;T12;3;14-02-16 10:00;G12351
Apple;T13;3;14-01-16 13:00;G12352
Google;T14;9;10-01-16 11:20;G12301
Microsoft;T15;10;26-02-16 10:20;G12999

But the code above give me the output: 但上面的代码给了我输出:

  [
        [name;cuInfo;service;startDate;appId:Apple;T12;3;14-02-16 10:00;G12351], 
        [name;cuInfo;service;startDate;appId:Apple;T13;3;14-01-16 13:00;G12352], 
        [name;cuInfo;service;startDate;appId:Google;T14;9;10-01-16 11:20;G12301], 
        [name;cuInfo;service;startDate;appId:Microsoft;T15;10;26-02-16 10:20;G12999]
    ]

I would like to get this structure as the map below? 我想把这个结构作为下面的地图?

[
        [name:"Apple", cuInfo:"T12",service:"3",startDate:"14-01-16 13:22",appId:"G12355"],
        [name:"Apple",cuInfo:"T13",service:"3",startDate:"12-02-16 13:00",appId:"G12356"],
        [name:"Google",cuInfo:"T14",service:"9",startDate:"10-01-16 11:20",appId:"G12300"], 
        [name:"Microsoft",cuInfo:"T15",service:"10",startDate:"26-02-16 10:20",appId:"G12999"]  
    ]

To get the data from the CSV file into the same structure (a list of Maps) as the query output, you can do this: 要将CSV文件中的数据作为查询输出提供到相同的结构(地图列表)中,您可以执行以下操作:

def reader = new CSVReader(new FileReader(new File(fileName)))
def output = reader.collect { it[0].split(';') }.with { rows ->
    def header = rows.head()
    def dataRows = rows.tail()

    dataRows.collect { row ->
        [header, row].transpose().collectEntries()
    }
}

The CSV rows are split into columns, the header and the remaining rows are gathered, and then they are transformed. CSV行被分成列,标题和剩余的行被收集,然后它们被转换。

The transpose() creates a structure like this for each data row: transpose()为每个数据行创建一个这样的结构:

[[name, Apple], [cuInfo, T12], [service, 3], [startDate, 14-02-16 10:00], [appId, G12351]]

And collectEntries() turns this into a Map : collectEntries()将其转换为Map

[name:Apple, cuInfo:T12, service:3, startDate:14-02-16 10:00, appId:G12351]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM