writeAll(ResultSet res,Boolean b) method of opencsv adds double quotes around data

时光毁灭记忆、已成空白 提交于 2019-12-19 03:43:06

问题


When I use this function to write to a csv file all the data is embedded in double quotes.

Is there a way to write to csv file without the double quotes?

CSVWriter writer = new CSVWriter(new FileWriter(table+".csv"), '\t');
            writer.writeAll(rset, true);
            writer.close();

the file contains data in the form

"EMPNO" "ENAME" "JOB"   "MGR"   "HIREDATE"  "SAL"   "COMM"  "DEPTNO"    "TAG"   "LOOKUP"
"7369"  "SMITH" "CLERK" "7902"  "17-Dec-1980"   "800"   "2" "20"    "E" "1"
"7499"  "ALLEN" "SALESMAN"  "7698"  "20-Feb-1981"   "1600"  "2" "30"    "E" "2"
"7521"  "WARD"  "SALESMAN"  "7698"  "22-Feb-1981"   "1250"  "2" "30"    "E" "3"
"7566"  "JONES" "MANAGER"   "7839"  "02-Apr-1981"   "2975"  "2" "20"    "E" "2"

回答1:


CSVWriter writer = new CSVWriter(new FileWriter(table+".csv"), '\t', CSVWriter.NO_QUOTE_CHARACTER);
            writer.writeAll(rset, true);
            writer.close();

Reference: opencsv CSVWriter JavaDoc




回答2:


I'd like to add to the previous answer (don't have enough points to just add to comments) by @user591593 - while using the NO_QUOTE_CHARACTER constructor, you should escape the values yourself. See StringEscapeUtils

More over, it's best to specify a proper encoding, such as UTF-8, instead of assuming that the system default is the correct one:

CSVWriter writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), '\t', CSVWriter.NO_QUOTE_CHARACTER);

String s = "some fun \t string with \" double quotes and \n new lines";

writer.writeNext(StringEscapeUtils.escapeCsv(s));


来源:https://stackoverflow.com/questions/6841622/writeallresultset-res-boolean-b-method-of-opencsv-adds-double-quotes-around-da

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!