Back

CSV文件下载,用excel打开会出现的乱码问题的解决办法

发布时间: 2015-08-27 22:57:00

CSV下载时,如果使用官方文档的说明,下载后的文件用excel打开时, 会产生乱码.

问题的根源有两点:

1. 文件需要指定好 encoding,

2. windows 与 mac下的 csv的分隔符是不一样的. 我服了...

  require 'csv'
  def download_csv
    filename = "机型名单"
    options = client_is_mac? ? { :col_sep => ";" } : {}
    file = CSV.generate(options) do |csv|
      csv << ["品牌", "机型名称", "UA里的机型名称", "价格"]
      CellPhone.all.each do |cell_phone|
        csv << [cell_phone.brand, cell_phone.name, cell_phone.ua_name, cell_phone.price]
      end
    end
    send_data file.encode("gbk", "utf-8"), :type => 'text/csv; charset=gbk; header=present', :disposition => "attachment;filename=#{filename}.csv"
  end

Back