2015-02-23 36 views
2

我推一些字符串到CSV文件:生成CSV文件時避免雙引號混淆?

csv_string = CSV.generate({col_sep: ";", row_sep: "\n"}) do |csv| 
    csv << ["101-41", "Sparri, \"Violet\" (rod) (1 bunt á 10 stk.)"] 
end 

當CSV文件最終生成一個常規Excel安裝顯然會正確顯示的內容,而是通過純文本編輯器仔細一看(如Sublime文本)顯示雙引號引起混淆:

10-41;"Sparri, ""Violet"" (rod) (1 bunt á 10 stk.)" 

我該如何避免這種情況?在推送到CSV文件之前,我應該將雙引號轉換爲不同的內容嗎?

回答

2

這是正確的,雙引號是逃脫與另一個雙引號。從RFC 4180

如果雙引號用於封裝領域,那麼場內出現一個雙引號 必須由具有 另一雙引號之前它被轉義。例如:

"aaa","b""bb","ccc" 
+0

狀態OK,所以我應該乾脆把它保留原樣? – ChristofferJoergensen 2015-02-23 08:17:09

+0

@ChristofferJoergensen是的,我會保持原樣。使用不同的'quote_char'可能會導致Excel出現問題。 – Stefan 2015-02-23 08:34:05

+0

的確如此。 +1 – 2015-02-23 08:41:43

0

CSV沒有官方標準,奇怪的,因爲它是。 還有的RFC 4180 guidelines大約雙引號

5. Each field may or may not be enclosed in double quotes (however 
     some programs, such as Microsoft Excel, do not use double quotes 
     at all). If fields are not enclosed with double quotes, then 
     double quotes may not appear inside the fields. For example: 

     "aaa","bbb","ccc" CRLF 
     zzz,yyy,xxx 

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

     "aaa","b CRLF 
     bb","ccc" CRLF 
     zzz,yyy,xxx 

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

所以您的格式是正確的,aslong爲Excel顯示文件正確,我不會介意的雙「雙引號」