blue-sky blue-sky - 1 year ago 77
Java Question

Prevent opencsv from writing quotes to .csv file

I'm populating a file from a resultSet like so :


String[] entries = new String[3];
entries[0] = rs.getString(1);
entries[1] = ",";
entries[2] = rs.getString(2);

println("entries : "+entries);


When I open the excel file the values contain double quotes around them. So test1,test2,test3 when read from the database and written to a .csv file becomes "test1","test2","test3"

How can I write the text to file but not include the quotes ?

When I print the entries to the console the double quotes are not printed so I don't know where they are being added ?

Answer Source

You can use the Constructor as mentioned by @Matten and along with that, use the other writeAll() of CSVWriter.

OpenCSV also provides support to dump data from SQL table directly to CSV. For this we need ResultSet object. Following API can be used to write data to CSV from ResultSet.

java.sql.ResultSet myResultSet = getResultSetFromSomewhere();
writer.writeAll(myResultSet, includeHeaders);

The writeAll(ResultSet, boolean) method is utilized for this. The first argument is the ResultSet which you want to write to CSV file. And the second argument is boolean which represents whether you want to write header columns (table column names) to the file or not.