Builds CSV output from collections of maps or typed objects. Example with maps: def data = [[name: 'Alice', age: 30], [name: 'Bob', age: 25]] def csv = groovy.csv.CsvBuilder.toCsv(data) assert csv.contains('name,age') assert csv.contains('Alice,
| 42 | * @since 6.0.0 |
| 43 | */ |
| 44 | @Incubating |
| 45 | public class CsvBuilder implements Writable { |
| 46 | private final CsvMapper mapper; |
| 47 | private char separator = ','; |
| 48 | private char quoteChar = '"'; |
| 49 | private String content; |
| 50 | |
| 51 | /** |
| 52 | * Creates a builder that uses comma-separated columns and double quotes |
| 53 | * for field escaping. |
| 54 | */ |
| 55 | public CsvBuilder() { |
| 56 | this.mapper = CsvSlurper.mapper(); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Set the column separator character (default: comma). |
| 61 | * |
| 62 | * @param separator the separator character |
| 63 | * @return this builder for chaining |
| 64 | */ |
| 65 | public CsvBuilder setSeparator(char separator) { |
| 66 | this.separator = separator; |
| 67 | return this; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Set the quote character (default: double-quote). |
| 72 | * |
| 73 | * @param quoteChar the quote character |
| 74 | * @return this builder for chaining |
| 75 | */ |
| 76 | public CsvBuilder setQuoteChar(char quoteChar) { |
| 77 | this.quoteChar = quoteChar; |
| 78 | return this; |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Convert a collection of maps to CSV. |
| 83 | * The keys of the first map are used as column headers. |
| 84 | * |
| 85 | * @param data the collection of maps |
| 86 | * @return the CSV string |
| 87 | */ |
| 88 | public static String toCsv(Collection<? extends Map<String, ?>> data) { |
| 89 | if (data == null || data.isEmpty()) { |
| 90 | return ""; |
| 91 | } |
| 92 | CsvMapper csvMapper = CsvSlurper.mapper(); |
| 93 | Map<String, ?> first = data.iterator().next(); |
| 94 | CsvSchema.Builder schemaBuilder = CsvSchema.builder(); |
| 95 | for (String key : first.keySet()) { |
| 96 | schemaBuilder.addColumn(key); |
| 97 | } |
| 98 | CsvSchema schema = schemaBuilder.build().withHeader(); |
| 99 | try { |
| 100 | return csvMapper.writer(schema).writeValueAsString(data); |
| 101 | } catch (IOException e) { |
nothing calls this directly
no outgoing calls
no test coverage detected