blue-sky
blue-sky

Reputation: 53806

Prevent opencsv from writing quotes to .csv file

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

      while(rs.next()){

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

          println("entries : "+entries);
          writer.writeNext(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 ?

Upvotes: 13

Views: 29105

Answers (10)

supernova
supernova

Reputation: 2070

A long time and many working answers, but as of 2021 and v5 the cleanest solution in my eyes is using the builder with defined constants. This allows you more control on the CsvWriter than with a fixed constructor.

import static com.opencsv.ICSVWriter.*;

CSVWriterBuilder builder = new CSVWriterBuilder(new FileWriter("yourfile.csv"));
ICSVWriter csvWriter = builder
      .withQuoteChar(NO_QUOTE_CHARACTER)
      .build();
csvWriter.writeAll(rs, true);

Upvotes: -1

elkoo
elkoo

Reputation: 762

Use this pattern to prevent from double quotes (checked on 5.3 version)

CSVWriter writer = new CSVWriter(new FileWriter(filename), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

Upvotes: -1

夢のの夢
夢のの夢

Reputation: 5816

Here is what works for me since version 5.x

import static com.opencsv.ICSVParser.*;

...
new CSVWriter(writer, DEFAULT_SEPARATOR, NO_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END)

Upvotes: -1

Krystian Sikora
Krystian Sikora

Reputation: 12268

Since this question pops up at the first place in google results when someone looks for OpenCSV and quotes issue, I'm going to add the newer solution here.

I'm using version 4.6 and it is indeed possible to skip the quotes, while keeping quotes in entires that contain separator char.

Sample code:

List<SomeCsvEntryTO> csvEntries = new ArrayList<>();
csvEntries.add(new SomeCsvEntryTO("sdf1", "sdf2"));
csvEntries.add(new SomeCsvEntryTO("hgh1", "hgh2;hghgh2"));

Writer writer = new FileWriter(filePath);
StatefulBeanToCsv<SomeCsvEntryTO> csvWriter = new StatefulBeanToCsvBuilder<SomeCsvEntryTO>(writer)
        .withSeparator(';')
        .withApplyQuotesToAll(false)
        .build();
csvWriter.write(csvEntries);
writer.close();

SomeCsvEntryTO:

public class SomeCsvEntryTO{

   @CsvBindByName(column = "sample1colname")
   private String sample1;

   @CsvBindByName(column = "sample2colname")
   private String sample2;
}

As you can see above, I am using semicolon as a separator and I do not change the quotechar. Just change the withApplyQuotesToAll to false.

This produces the following result:

SAMPLE1COLNAME;SAMPLE2COLNAME
sdf1;sdf2
hgh1;"hgh2;hghgh2"

Upvotes: 8

vegemite4me
vegemite4me

Reputation: 6856

Update (16-Oct-2019): This is now possible with later versions of OpenCSV. Please see Sikor's answer.


TL;DR You cannot do it with OpenCSV v2.3. But you can with Commons CSV.

OpenCSV (v2.3) does not seem to provide a safe way of turning off quotes when they are not required. Quotes usually are not required for values that do no have the separator character or line end character in them.

Using NO_QUOTE_CHARACTER as some have suggested:

CSVWriter writer = new CSVWriter(new FileWriter("data.csv"), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
String[] someData = new String[] {"Black and white", "Red, yellow and blue"};
writer.writeNext(someData);

produces the incorrect CSV representation as:

Black and white,Red, yellow and blue

A more valid representation of this data, which uses quotes only when required would be:

Black and white,"Red, yellow and blue"

I have not used Commons CSV, but it appears to provide this ability via QuoteMode.MINIMAL which does the following:

Quotes fields which contain special characters such as a delimiter, quote character or any of the characters in line separator.

Upvotes: 4

Sahil Sancheti
Sahil Sancheti

Reputation: 39

Yes. There is a CSVWriter in the same package that follows the same semantics as the CSVReader. For example, to write a tab separated file:

CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
// feed in your array (or convert your data to an array)
String[] entries = "first#second#third".split("#");
writer.writeNext(entries);
writer.close();

If you'd prefer to use your own quote characters, you may use the three arg version of the constructor, which takes a quote character (or feel free to pass in CSVWriter.NO_QUOTE_CHARACTER).

You can also customise the line terminators used in the generated file (which is handy when you're exporting from your Linux web application to Windows clients). There is a constructor argument for this purpose.

Upvotes: 2

user1454926
user1454926

Reputation: 199

see this link on how to use NO_QUOTE_CHARACTER constructor and proper encoding when writing out to a file:

https://stackoverflow.com/a/29362439/1454926

Upvotes: 0

obsessiveCookie
obsessiveCookie

Reputation: 1138

Just to extend on Matten's answer, use the built-in characters in the CSVWriter to specify the quotechar. So your writer would look like the following:

CSVWriter writer = new CSVWriter(new FileWriter(fileName), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

Upvotes: 25

Rahul
Rahul

Reputation: 45060

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.

Upvotes: -2

Matten
Matten

Reputation: 17621

The constructor code of the writer allows you to give an escape character (quotechar):

CSVWriter(Writer writer, char separator, char quotechar)

If this is the wrong one, there is another constructor with escape character :-)

CSVWriter(Writer writer, char separator, char quotechar, char escapechar)

Upvotes: 0

Related Questions