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
Constructors -
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()Writes this object to the given writer.
-
Constructor Details
-
CsvBuilder
public CsvBuilder()
-
-
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
-
writeTo
Description copied from interface:WritableWrites this object to the given writer.This is used to defer content creation until the point when it is streamed to the output destination. Oftentimes, content will be defined but not necessarily created (as it may be the case with a Closure definition.) In that case, the output is then 'deferred' to the point when it is serialized to the writer. This class may be used whenever an object should be responsible for creating its own textual representation, but creating the entire output as a single String would be inefficient (such as outputting a multi-gigabyte XML document.)
- Specified by:
writeToin interfaceWritable- Parameters:
out- the Writer to which this Writable should output its data.- Returns:
- the Writer that was passed
- Throws:
IOException- if an error occurred while outputting data to the writer
-