Character encoding issue exporting rails data to CSV

前端 未结 4 1067
后悔当初
后悔当初 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:42

    This worked for me, with Chinese characters!excel csv fromat (BOM + UTF8)

    def export_csv_excel
      ....
    
      # Add BOM to make excel using utf8 to open csv file
      head = 'EF BB BF'.split(' ').map{|a|a.hex.chr}.join()
    
      csv_str = CSV.generate(csv = head) do |csv|
        csv << [ , , , ...]
        @invoices.each do |invoice|
          csv << [ , , , ...]
        end
      end
    
      send_data csv_str, filename: "Invoices-#{Time.now.strftime("%y%m%d%H%M%S")}.csv", type: "text/csv"
    end
    

    source(Chinese): http://blog.inheart.tw/2013/09/rubyraisl-csv-excel.html

提交回复
热议问题