4

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

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

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

该文件包含表单中的数据

"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"
4

2 回答 2

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

参考:opencsv CSVWriter JavaDoc

于 2011-07-27T08:55:24.507 回答
0

我想通过@user591593 添加到上一个答案(没有足够的分数来添加评论) - 在使用 NO_QUOTE_CHARACTER 构造函数时,您应该自己转义这些值。请参见StringEscapeUtils

此外,最好指定适当的编码,例如 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));
于 2015-03-31T06:56:39.267 回答