java 防止 opencsv 将引号写入 .csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15366954/
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
Prevent opencsv from writing quotes to .csv file
提问by blue-sky
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"
当我打开 excel 文件时,值在它们周围包含双引号。所以 test1,test2,test3 从数据库中读取并写入 .csv 文件时变为 "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 ?
当我将条目打印到控制台时,没有打印双引号,所以我不知道它们被添加到哪里?
采纳答案by SudoRahul
You can use the Constructor
as mentioned by @Matten and along with that, use the other writeAll()of CSVWriter
.
您可以使用Constructor
通过@Matten而且随着该提到的,使用其他writeAll()的CSVWriter
。
OpenCSValso provides support to dump data from SQL table directly to CSV. For this we need ResultSet object. Following APIcan be used to write data to CSV from ResultSet.
OpenCSV还支持将数据从 SQL 表直接转储到 CSV。为此,我们需要 ResultSet 对象。以下API可用于将数据从 ResultSet 写入 CSV。
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 CSVfile. And the second argument is boolean
which represents whether you want to write header columns (table column names) to the file or not.
该writeAll(ResultSet, boolean)
方法用于此。第一个参数是ResultSet
您要写入CSV文件的参数。第二个参数boolean
表示是否要将标题列(表列名称)写入文件。
回答by obsessiveCookie
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:
只是为了扩展 Matten 的答案,使用 CSVWriter 中的内置字符来指定quotechar
. 因此,您的编写器将如下所示:
CSVWriter writer = new CSVWriter(new FileWriter(fileName), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
回答by vegemite4me
Update(16-Oct-2019): This is now possible with later versions of OpenCSV. Please see Sikor's answer.
更新(2019 年 10 月 16 日):现在可以使用更高版本的 OpenCSV。请参阅Sikor 的回答。
TL;DRYou cannot do it with OpenCSV v2.3. But you can with Commons CSV.
TL;DR你不能用 OpenCSV v2.3 做到这一点。但是您可以使用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.
OpenCSV (v2.3) 似乎没有提供在不需要时关闭引号的安全方法。对于没有分隔符或行结束符的值,通常不需要引号。
Using NO_QUOTE_CHARACTER
as some have suggested:
使用NO_QUOTE_CHARACTER
一些建议:
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 incorrectCSV representation as:
产生不正确的CSV 表示为:
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:
我没有使用Commons CSV,但它似乎提供了这种能力,通过QuoteMode.MINIMAL
它执行以下操作:
Quotes fields which contain special characters such as a delimiter, quote character or any of the characters in line separator.
引用字段包含特殊字符,例如分隔符、引号字符或行分隔符中的任何字符。
回答by Sahil Sancheti
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,它遵循与 CSVReader 相同的语义。例如,要编写一个制表符分隔的文件:
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).
如果您更喜欢使用自己的引号字符,则可以使用构造函数的三个 arg 版本,它接受一个引号字符(或随意传入 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.
您还可以自定义生成文件中使用的行终止符(这在您从 Linux Web 应用程序导出到 Windows 客户端时很方便)。为此有一个构造函数参数。
回答by Sikor
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.
由于当有人查找 OpenCSV 和引号问题时,这个问题首先出现在 google 结果中,因此我将在此处添加较新的解决方案。
I'm using version 4.6 and it is indeed possible to skip the quotes, while keeping quotes in entires that contain separator char.
我使用的是 4.6 版,确实可以跳过引号,同时保留包含分隔符字符的整体引号。
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:
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
.
正如您在上面看到的,我使用分号作为分隔符并且我没有更改quotechar。只需将 更改withApplyQuotesToAll
为false
。
This produces the following result:
这会产生以下结果:
SAMPLE1COLNAME;SAMPLE2COLNAME
sdf1;sdf2
hgh1;"hgh2;hghgh2"
回答by user1454926
see thislink on how to use NO_QUOTE_CHARACTER constructor and proper encoding when writing out to a file:
请参阅此链接,了解在写入文件时如何使用 NO_QUOTE_CHARACTER 构造函数和正确编码:
回答by Matten
The constructor code of the writerallows you to give an escape character (quotechar
):
编写器的构造函数代码允许您提供转义字符 ( 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)