I am using Apache Commons CSV lib to write CSV files.
The sample provided to me had a strange pattern.
Sample output expected:
As can be seen, the Name with designation column can have values with comma. So they needs to be quoted. However there are values where there are empty spaces, such as, phone no, which can be only empty space, or the Action column, where values can contain empty space (middle or end).
Now when I write the CSV using apache commons library, I used the following CSVFormat with the CSVPrinter class.
CSVFormat.EXCEL.withQuoteMode(QuoteMode.MINIMAL));
This configuration gave the closest output as like the sample. However, the Empty space or the values with the trailing spaces, that is, even when there is no comma, also gets quoted.
My Output:
What I need is, when there is only space or space at end, and the value does not have comma, the Quotes will not be there.
Is there any configuration in Apache Commons that I am missing? Or is there any other CSV library with a format that gives this output?
You can use super-csv. That follows the RFC-4180
CsvListWriter c = new CsvListWriter(new PrintWriter(System.out), CsvPreference.STANDARD_PREFERENCE);
c.write(Lists.newArrayList(" Aa", " ", " John \"Doe\"", "Comma,", "test "));
c.flush();
c.close();
Writes:
Aa, ," John ""Doe""","Comma,",test
Maven depencency:
<!-- https://mvnrepository.com/artifact/net.sf.supercsv/super-csv -->
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>