CSV输出文件的第一个单元格中的字符不正确

时间:2015-12-24 02:52:24

标签: ruby-on-rails csv

当数据库以CSV格式导出时,我将其作为第一个列名称:ÔªøId。不同的计算机和操作系统上的输出相同。其余数据是正确的。数据库在ActivaAdmin,RoR中创建。什么可能导致这个?无需解释我需要Id作为列名。

2 个答案:

答案 0 :(得分:1)

这可能是UTF-8 BOM (Byte Order Mark),(严格来说,UTF-8中不需要字节顺序)。

虽然您显示的字符不同,但文件开头只有3个字节(可能会通过复制/粘贴或读取文件进行转换)。

答案 1 :(得分:0)

:type => 'text/csv; charset=<charset>; header=present'方法中使用send_data

比如,假设你有customer模型,需要导出所有customers然后

  def export_customers
    @customers = Customer.all
    c = CSV.generate_line(["S.No", "Name", "About", "Phone", "Address", "City", "State", "Country"], :col_sep => ', ', :row_sep => "\r\n", :quote_char => '"')
    @customers.each_with_index do |customer, index|
      c += CSV.generate_line([index + 1, customer.name, customer.about, customer.phone, customer.address, customer.city, customer.state, customer.country], :col_sep => ', ', :row_sep => "\r\n", :quote_char => '"')
    end

    send_data(c, :type => 'text/csv; charset=<charset>; header=present', :filename => 'customers.csv')
end
相关问题