Package groovy.csv
Class CsvBuilder
java.lang.Object
groovy.csv.CsvBuilder
- All Implemented Interfaces:
Writable
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,30')
- Since:
- 6.0.0
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a builder that uses comma-separated columns and double quotes for field escaping. -
Method Summary
Modifier and TypeMethodDescriptioncall(Collection<? extends Map<String, ?>> data) Build CSV from a collection of maps.setQuoteChar(char quoteChar) Set the quote character (default: double-quote).setSeparator(char separator) Set the column separator character (default: comma).static StringtoCsv(Collection<? extends Map<String, ?>> data) Convert a collection of maps to CSV.static <T> StringtoCsv(Collection<T> data, Class<T> type) Convert a collection of typed objects to CSV using Jackson databinding.toString()Returns the CSV content built so far, or an empty string if no data has been written yet.Writes the current CSV content to the supplied writer.
-
Constructor Details
-
CsvBuilder
public CsvBuilder()Creates a builder that uses comma-separated columns and double quotes for field escaping.
-
-
Method Details
-
setSeparator
Set the column separator character (default: comma).- Parameters:
separator- the separator character- Returns:
- this builder for chaining
-
setQuoteChar
Set the quote character (default: double-quote).- Parameters:
quoteChar- the quote character- Returns:
- this builder for chaining
-
toCsv
Convert a collection of maps to CSV. The keys of the first map are used as column headers.- Parameters:
data- the collection of maps- Returns:
- the CSV string
-
toCsv
Convert a collection of typed objects to CSV using Jackson databinding. Supports@JsonPropertyand@JsonFormatannotations.- Type Parameters:
T- the object type- Parameters:
data- the collection of objectstype- the object type (used to derive the schema)- Returns:
- the CSV string
-
call
Build CSV from a collection of maps.- Parameters:
data- the collection of maps- Returns:
- this builder
-
toString
Returns the CSV content built so far, or an empty string if no data has been written yet. -
writeTo
Writes the current CSV content to the supplied writer.- Specified by:
writeToin interfaceWritable- Parameters:
out- the destination writer- Returns:
- the writer passed in
- Throws:
IOException- if the writer cannot be written to
-