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>
univocity-parsers does what you want. Try this code:
CsvWriterSettings settings = Csv.writeExcel();
settings.trimValues(false); //values are trimmed by default
settings.setHeaders("Name with designation","Phone","Action","Date");
settings.setHeaderWritingEnabled(true);
StringWriter output = new StringWriter();
CsvWriter writer = new CsvWriter(output, settings);
writer.writeRow("John Doe,Officer"," ","Under investigation","8-Jun-2017");
writer.writeRow("Jack","+123-4567","False Allegation ","4-Jun-2017");
writer.close();
System.out.println(output);
The output will be:
Name with designation,Phone,Action,Date
"John Doe,Officer", ,Under investigation,8-Jun-2017
Jack,+123-4567,False Allegation ,4-Jun-2017
Hope it helps.
Disclaimer: I'm the author of this library. It's open-source and free (Apache 2.0 license)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With