Class CSVFormat

java.lang.Object
org.apache.commons.csv.CSVFormat
All Implemented Interfaces:
Serializable

public final class CSVFormat extends Object implements Serializable
Specifies the format of a CSV file for parsing and writing.

Using predefined formats

You can use one of the predefined formats:

For example:

 CSVParser parser = CSVFormat.EXCEL.parse(reader);
 

The CSVParser provides static methods to parse other input types, for example:

 CSVParser parser = CSVParser.parse(file, StandardCharsets.US_ASCII, CSVFormat.EXCEL);
 

Defining formats

You can extend a format by calling the set methods. For example:


 CSVFormat.EXCEL.builder().setNullString("N/A").setIgnoreSurroundingSpaces(true).get();
 

Defining column names

To define the column names you want to use to access records, write:


 CSVFormat.EXCEL.builder().setHeader("Col1", "Col2", "Col3").get();
 

Calling CSVFormat.Builder.setHeader(String...) lets you use the given names to address values in a CSVRecord, and assumes that your CSV source does not contain a first record that also defines column names. If it does, then you are overriding this metadata with your names and you should skip the first record by calling CSVFormat.Builder.setSkipHeaderRecord(boolean) with true.

Parsing

You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write:


 Reader in = ...;
 CSVFormat.EXCEL.builder().setHeader("Col1", "Col2", "Col3").get().parse(in);
 

For other input types, like resources, files, and URLs, use the static methods on CSVParser.

Referencing columns safely

If your source contains a header record, you can simplify your code and safely reference columns, by using CSVFormat.Builder.setHeader(String...) with no arguments:

 CSVFormat.EXCEL.builder().setHeader().get();
 

This causes the parser to read the first record and use its values as column names. Then, call one of the CSVRecord get method that takes a String column name argument:


 String value = record.get("Col1");
 

This makes your code impervious to changes in column order in the CSV file.

Serialization

This class implements the Serializable interface with the following caveats:

  • This class will no longer implement Serializable in 2.0.
  • Serialization is not supported from one version to the next.

The serialVersionUID values are:

  • Version 1.10.0: 2L
  • Version 1.9.0 through 1.0: 1L

Notes

This class is immutable.

Not all settings are used for both parsing and writing.

See Also: