0

I am facing a problem caused by quotation mark, while trying to insert data into csv file. I have two elements: 20" and BI. After running through this sentence:

writers[k].write("\"" + tablelist.get(k).get(i)[j] + "\",");

They would be presented as :

"20",","BI"

In the csv file, it would be presented in a cell as 20",BI" rather than two separate elements.

Could anyone give me suggestions how to solve this problem?

WangMango
  • 35
  • 5

3 Answers3

4

Ugh... use opencsv, do not, under any circumstances, attempt to parse or write CSV yourself. There are just too many edge cases, that are addressed. If you want to append, first read the CSV in, then add your string array to the list, and write it out. There are other CSV libraries for Java that work in similar ways.

hd1
  • 33,938
  • 5
  • 80
  • 91
  • I don't know anything about Maven or pom files. Is there documentation for how to build opencsv.jar? – Daniel May 10 '14 at 14:45
  • 1
    http://maven.apache.org/run-maven/index.html#Quick_Start first hit on Google... – hd1 May 10 '14 at 14:54
2

Use a different quote character then ". You can configure what character is to be treated as the quote when opening the csv file.

Instead of this

writers[k].write("\"" + tablelist.get(k).get(i)[j] + "\",");

Add a quote character and then choose one you are not likely to get in your data like this

String quote = "|";
writers[k].write(quote + tablelist.get(k).get(i)[j] + quote +",");

Then when you open this (depending on program) you can configure it so that | is used as the quote

In Libre Office it should ask you when you double click on the csv file

In MS Excel (depending on version) you open excel then import from text then it should give you the option to choose then.

Java Devil
  • 10,629
  • 7
  • 33
  • 48
  • 1
    What if the quote cannot be changed? It is in the file I need to parse and I cannot change them every time they appear – WangMango Oct 10 '13 at 22:28
  • Why would the quote not be able to be changed? you just change them in your line of code....`writers[k].write("\"" + tablelist.get(k).get(i)[j] + "\",");` – Java Devil Oct 10 '13 at 22:38
1

RFC 4180 Common Format and MIME Type for Comma-Separated Values (CSV) Files

Section 2.7:

If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:

   "aaa","b""bb","ccc"

But as others have mentioned, it would be better to use a library that handles these details for you.

Community
  • 1
  • 1
dnault
  • 8,340
  • 1
  • 34
  • 53