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

后端 未结 4 1059
暗喜
暗喜 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:36

    You should switch the encoding to ISO-8859-1 as following:

    CSV.generate(encoding: 'ISO-8859-1') { |csv|  csv << ["Text á", "Text é", "Text æ"] }
    

    For your context, you can do this:

    config = {
      col_sep: ';',
      row_sep: ';',
      encoding: 'ISO-8859-1'
    }
    
    CSV.generate(config) { |csv|  csv << ["Text á", "Text é", "Text æ"] }
    

    I had the same issue and that encoding fixed.

提交回复
热议问题