java opencsv 的 writeAll(ResultSet res,Boolean b) 方法在数据周围添加双引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6841622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:32:08  来源:igfitidea点击:

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

javaopencsv

提问by Shamis Shukoor

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

当我使用此函数写入 csv 文件时,所有数据都嵌入在双引号中。

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

有没有办法在没有双引号的情况下写入 csv 文件?

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"

回答by

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

Reference: opencsv CSVWriter JavaDoc

参考:opencsv CSVWriter JavaDoc

回答by user1454926

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

我想通过@user591593 添加到先前的答案(没有足够的点可以添加到评论中) - 在使用 NO_QUOTE_CHARACTER 构造函数时,您应该自己转义这些值。参见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:

此外,最好指定正确的编码,例如 UTF-8,而不是假设系统默认值是正确的:

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));