简体   繁体   English

如何获得CSVPrinter引用带空格的字段?

[英]How can I get a CSVPrinter to quote fields with spaces?

I'm using the CSVPrinter class from the Apache Commons in order to output a CSV file. 我正在使用来自Apache Commons的CSVPrinter类 ,以便输出CSV文件。 What I would like to have happen is that if a given field contains any spaces in it, that it gets encapsulated in quotes. 我想发生的是,如果给定的字段中包含任何空格,则将其封装在引号中。 But if it's just a long string of numbers, or a date string, for example, then those do not need to be quoted. 但是,例如,如果它只是一长串数字或日期字符串,则不需要用引号引起来。

Unfortunately the QuoteMode enum seems pretty limited; 不幸的是QuoteMode枚举似乎很有限。 it offers the four following choices: 它提供以下四个选择:

  1. ALL Quotes all fields. ALL引用所有字段。
  2. MINIMAL Quotes fields which contain special characters such as a delimiter, quote character or any of the characters in line separator. MINIMAL引号字段包含特殊字符,例如定界符,引号字符或行分隔符中的任何字符。
  3. NON_NUMERIC Quotes all non-numeric fields. NON_NUMERIC引用所有非数字字段。
  4. NONE Never quotes fields. NONE不引用字段。

The MINIMAL option seems to be the closest to what I want to do here, but since the space character is not part of a line separator, that doesn't work. MINIMAL选项似乎最接近我要在此处执行的操作,但是由于空格字符不是行分隔符的一部分,因此无法正常工作。 Is there any way to configure a CSVPrinter object to quote fields that have spaces in them? 有什么方法可以配置CSVPrinter对象以引用其中包含空格的字段?

CSVPrinter is not that flexible, it is also final so you can't override the printing implementation. CSVPrinter不是那么灵活,它也是final因此您不能覆盖打印实现。

I suggest you find a different csv library or look at the source code of CSVPrinter and implement your own version with your own requirements. 我建议您找到一个不同的csv库或查看CSVPrinter的源代码,并根据自己的要求实现自己的版本。 It is definitely not a requirement of the CSV format to quote strings with whitespace though. 绝对不是CSV格式要求用空格引用字符串。 Any implementation that complies with the format should be able to read strings with whitespace in them (and not quoted). 符合格式的任何实现都应该能够读取字符串中带有空格的字符串(且不加引号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM