Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including double quotes while writing CSV using apache commons in java

I am using apache commons CSV to write csv files. I want to stick to this library. While I am writing a csv file, in the first column of generated file, it contains double quotes as quote character and other columns are generated as expected.

I really want to get rid of double quotes here. Please find below code for the same.

CSVFormat format = CSVFormat.DEFAULT;
FileWriter fw = new FileWriter("Temp.csv");
CSVPrinter printer = new CSVPrinter(fw, format);

String[] temp = new String[4];

for(int i=0; i<4; i++) {
    if(i==1)
        temp[0] = "#";
    else
        temp[0] = "";
    temp[1] = "hello" + (i+1);
    temp[2] = "";
    temp[3] = "test";

    Object[] temp1 = temp[]
    printer.printRecord(temp1);
}

fw.close();
printer.close();

Temp.csv

"",hello1,,test
"#",hello2,,test
"",hello3,,test
"",hello4,,test

I don't want a quote character at the beginning of every row. I just want an empty string without quotes, same as in column 3. Can anyone help?

like image 844
Harshit Avatar asked Jul 06 '15 23:07

Harshit


People also ask

What is Apache Commons CSV?

The Apache Commons CSV library is the Apache Software Foundation's version of a Java CSV parser. According to the project summary, it attempts to "provide a simple interface for reading and writing CSV files of various types".

What is quoting in CSV?

So quote characters are used in CSV files when the text within a field also includes a comma and could be confused as being the reserved comma delimiter for the next field. Quote characters indicate the start and end of a block of text where any comma characters can be ignored.


1 Answers

Mentioned in lars issue tracking, try to set the CSVFormat to the following,

final CSVFormat csvFileFormat = CSVFormat.DEFAULT.withEscape('\\').withQuoteMode(QuoteMode.NONE);

like image 64
t3po7re5 Avatar answered Sep 30 '22 20:09

t3po7re5