简体   繁体   中英

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. 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; it offers the four following choices:

  1. ALL Quotes all fields.
  2. MINIMAL Quotes fields which contain special characters such as a delimiter, quote character or any of the characters in line separator.
  3. NON_NUMERIC Quotes all non-numeric fields.
  4. NONE Never quotes fields.

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. Is there any way to configure a CSVPrinter object to quote fields that have spaces in them?

CSVPrinter is not that flexible, it is also final so you can't override the printing implementation.

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. It is definitely not a requirement of the CSV format to quote strings with whitespace though. Any implementation that complies with the format should be able to read strings with whitespace in them (and not quoted).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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