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

时间:2016-03-07 11:56:22

标签: java csv grails groovy

我使用下面的代码来读取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:

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

但上面的代码给出了输出:

  [
        [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]
    ]

我想将此结构作为下图?

[
        [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"]  
    ]

1 个答案:

答案 0 :(得分:3)

要将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()
    }
}

将CSV行拆分为列,收集标题和其余行,然后对其进行转换。

transpose()为每个数据行创建一个这样的结构:

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

collectEntries()将其转换为Map

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