1

I'm converting Resultset to CSV using Univocity parser. I want only the user provided fields to be present in the output CSV if the fields are present in the resultset. If the field is not present in the resultset the corresponding column should be blank. I have a restriction of not modifying the SQL query.

I'm using excludeFields() method but it is making the field values blank in the output CSV along with the delimiter.

example:

Name, Age, Email
Joe, 20, joe@example.com

After applying excludeFields("Age"). Since setHeaders() method has some known issues, I'm using my own logic to set headers.

Name, Email
Joe, , joe@example.com

But I want it to be like:

Name, Email
Joe, joe@example.com

Is there any way I can achieve it?

HyperioN
  • 3,433
  • 2
  • 22
  • 36

1 Answers1

1

Currently the writer is controlled by the headers you define. A field selection will simply make the writer print out blanks in the columns that were not selected.

The next version will provide column reordering when writing, which should do what you want. If you can use the 2.5.0-SNAPSHOT it should already work:

ResultSet resultSet = statement.executeQuery("SELECT * FROM users");

CsvWriterSettings csvWriterSettings = new CsvWriterSettings();
csvWriterSettings.excludeFields("Age");
csvWriterSettings.setHeaderWritingEnabled(true);
csvWriterSettings.setColumnReorderingEnabled(true); //this does the trick

CsvRoutines csvRoutines = new CsvRoutines(csvWriterSettings);
csvRoutines.write(resultSet, output);

Hope it helps!

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29
  • thank you for your continuous support. What currently I'm doing as a workaround is to convert the StringWriter to InputStream after writing the resultset to it: csvRoutines.write(resultSet, stringWriter). Feed this InputStream to CsvParser: csvParser.parse(new InputStreamReader(inputStream)), and call csvParserSettings.selectFields("Name", "Email") and again write the output csv using CsvWriter. I'm not sure if it is the only effective approach, but I see there is a lot of time consumed in the process if the resultset is huge. – HyperioN Jun 21 '17 at 08:02
  • when can we expect the 2.5.0 release? Because I don't think it is advisable to use 2.5.0-SNAPSHOT in a production environment. – HyperioN Jun 21 '17 at 08:04
  • Your workaround will work just fine. Version 2.5.0 will be released in a month or so. – Jeronimo Backes Jun 21 '17 at 08:17