Write CSV with text in quotes, but numerical values without quotes

Jean-François Corbett picture Jean-François Corbett · Jun 24, 2014 · Viewed 7k times · Source

Using OpenCSV, I'm trying to write a CSV file in which

  • Text values are surrounded by " quotes.
  • Numerical values are not surrounded by quotes (because they should be treated as numbers, not as strings, by the program that will eventually read the CSV file).

Example desired output:

Format required by the program that will read the CSV file:

"Header 1","Header 2","Header 3"
123.4,234.6,999.8
456456.32,1222.4,2222.2

Attempted solution:

My best attempt so far is:

CSVWriter csvWriter = new CSVWriter(new FileWriter(csvFile),',','\0');

where the quote char is set to '\0' i.e. the empty char (and the delimiter is left to be , as usual).

This puts no quotes around any values. To make up for the lack of " quotes around the text values, I "manually" prepend and append a litteral quote "\"" to each text value (this is quite manageable, because my headers are really only the only things that have text in them).

    for (int i=0;i<headers.length;++i) {
        headers[i] = "\"" + headers[i] + "\"";
    }

Actual output:

I really thought this would nail it, but the output looks like this:

""Header 1"",""Header 2"",""Header 3""
123.4,234.6,999.8
456456.32,1222.4,2222.2

Text values are enclosed in double quotes ""!

  • Why?
  • How do I fix this?

Answer

Duncan Jones picture Duncan Jones · Jun 24, 2014

You could specify the escape character to be '\0', which would stop OpenCSV from escaping your existing quotes:

CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(System.out),
        ',', '\0', '\0');
csvWriter.writeNext(new String[] { "\"Header 1\"", "\"Header 2\"",
        "\"Header 3\"" });
csvWriter.writeNext(new String[] { "123.4", "234.6", "999.8" });
csvWriter.close();

Output:

"Header 1","Header 2","Header 3"
123.4,234.6,999.8

Of course, you are swiftly reaching the stage where OpenCSV is doing nothing for you. If you handle all escaping and all quoting, then OpenCSV is just joining string arrays with commas.

It may be sensible to abandon the library and just write that small amount of code yourself - it will avoid confusion for future maintainers who think "Hmmm, this is mighty odd CSV data we're producing here!".