writer.groovy 880 Bytes
Newer Older
Andrey Vetlugin's avatar
Andrey Vetlugin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#!/usr/bin/env groovy

String escape(String unescaped) {
    if (!unescaped) {
        return '""'
    }
    return '"' + unescaped.replaceAll(~/"/, '""') + '"'
}

assert escape('asdf') == '"asdf"'
assert escape('as"df') == '"as""df"'
assert escape(null) == '""'

def writeToCsv(List<Map<String, String>> inputMap) {
    // print headers
    Set<String> headers = []
    inputMap.each {
        it.each { k, v ->
            headers.add(k)
        }
    }
    println headers.collect {
        escape(it)
    }.join(",")

    // print values as CSV
    inputMap.each { Map<String, String> lineMap ->
        println headers.collect { String key ->
            escape(lineMap[key])
        }.join(',')
    }
}

List<Map<String, String>> inputMap = [
        [name: 'Andrey', email: 'andrey@cc.de'],
        [name: 'Sems', email: 'sems@cc.de', company: 'cc']
]
writeToCsv(inputMap)