mardi 24 juin 2014

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


Vote count:

0




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



  • Text values are surrounded by " quotes (as they should be, because they might contain the delimiter character , comma).

  • 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:



"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 ""!



asked 2 mins ago






Aucun commentaire:

Enregistrer un commentaire