Dealing with commas in a CSV file

后端 未结 27 2757
傲寒
傲寒 2020-11-21 06:53

I am looking for suggestions on how to handle a csv file that is being created, then uploaded by our customers, and that may have a comma in a value, like a company name.

27条回答
  •  盖世英雄少女心
    2020-11-21 07:21

    For 2017, csv is fully specified - RFC 4180.

    It is a very common specification, and is completely covered by many libraries (example).

    Simply use any easily-available csv library - that is to say RFC 4180.


    There's actually a spec for CSV format and how to handle commas:

    Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.

    http://tools.ietf.org/html/rfc4180

    So, to have values foo and bar,baz, you do this:

    foo,"bar,baz"
    

    Another important requirement to consider (also from the spec):

    If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:

    "aaa","b""bb","ccc"
    

提交回复
热议问题