CSV-Groovy.csv.groovy 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /*
  2. * Available context bindings:
  3. * COLUMNS List<DataColumn>
  4. * ROWS Iterable<DataRow>
  5. * OUT { append() }
  6. * FORMATTER { format(row, col); formatValue(Object, col) }
  7. * TRANSPOSED Boolean
  8. * plus ALL_COLUMNS, TABLE, DIALECT
  9. *
  10. * where:
  11. * DataRow { rowNumber(); first(); last(); data(): List<Object>; value(column): Object }
  12. * DataColumn { columnNumber(), name() }
  13. */
  14. SEPARATOR = ","
  15. QUOTE = "\""
  16. NEWLINE = System.getProperty("line.separator")
  17. def printRow = { values, valueToString ->
  18. values.eachWithIndex { value, idx ->
  19. def str = valueToString(value)
  20. def q = str.contains(SEPARATOR) || str.contains(QUOTE) || str.contains(NEWLINE)
  21. OUT.append(q ? QUOTE : "")
  22. .append(str.replace(QUOTE, QUOTE + QUOTE))
  23. .append(q ? QUOTE : "")
  24. .append(idx != values.size() - 1 ? SEPARATOR : NEWLINE)
  25. }
  26. }
  27. if (!TRANSPOSED) {
  28. ROWS.each { row -> printRow(COLUMNS, { FORMATTER.format(row, it) }) }
  29. }
  30. else {
  31. def values = COLUMNS.collect { new ArrayList<String>() }
  32. ROWS.each { row -> COLUMNS.eachWithIndex { col, i -> values[i].add(FORMATTER.format(row, col)) } }
  33. values.each { printRow(it, { it }) }
  34. }