Ruby: How to generate CSV files that has Excel-friendly encoding

后端 未结 4 1062
暗喜
暗喜 2020-12-30 03:01

I am generating CSV files that needs to be opened and reviewed in Excel once they have been generated. It seems that Excel requires a different encoding than UTF-8.

4条回答
  •  清歌不尽
    2020-12-30 03:35

    Excel understands UTF-8 CSV if it has BOM. That can be done like:

    Use CSV.generate

    # the argument of CSV.generate is default string
    csv_string = CSV.generate("\uFEFF") do |csv|
      csv << ["Text a", "Text b", "Text æ", "Text ø", "Text å"]
    end
    

    Use CSV.open

    filename = "/tmp/example.csv"
    
    # Default output encoding is UTF-8
    CSV.open(filename, "w") do |csv|
      csv.to_io.write "\uFEFF" # use CSV#to_io to write BOM directly 
      csv << ["Text a", "Text b", "Text æ", "Text ø", "Text å"]
    end
    

提交回复
热议问题