Character encoding issue exporting rails data to CSV

前端 未结 4 1066
后悔当初
后悔当初 2020-12-03 08:12

I\'m exporting data to a CSV file in rails and in some of my fields, I\'m getting character encoding issues like this when I open in Excel:

didn’t
<         


        
4条回答
  •  被撕碎了的回忆
    2020-12-03 08:53

    The answers above did not work for me on Mac Excel: Using iso-8859-1 would require I replace/remove weird characters, which is not a good enough solution for me, and using BOM with UTF8 worked under Windows but not under Mac Excel.

    What worked for me is the WINDOWS-1252 encoding as suggested by https://stackoverflow.com/a/20194266/226255

    def self.to_csv(options = {})
      (CSV.generate(options) do |csv|
        csv << self.headers
    
        all.each do |e|
          csv << e.values
        end
       end).encode('WINDOWS-1252', :undef => :replace, :replace => '')
    end
    

提交回复
热议问题