ruby csv文件编码为utf-8,但是windows excel无法识别

时间:2016-01-07 12:18:11

标签: ruby utf-8

在ruby中,我在打开文件时生成CSV文件,我将其称为UTF-8编码。下面给出了代码。在linux和mac中它工作正常,但在Windows中,当我试图打开csv文件时,excel不能识别为UTF-8。我能做什么,以便Windows将其识别为UTF-8编码。     CSV.open(File.join(Rails.public_path,"/csv_uploads/#{csv_name}.csv"),“w:UTF-8”)。

我甚至手动将文件中的项目编码为UTF-8。

`result[2].encode('UTF-8')`.

1 个答案:

答案 0 :(得分:0)

虽然编写本身需要使用open_mode和bom。

这里要注意的重要事项是开放模式和Bom

open_mode =“ w +:UTF-16LE:UTF-8”

bom =“ \ xEF \ xBB \ xBF”

在编写CSV插入BOM表之前

f.write bom

f.write(csv_file)

示例I18n内容

在Mac和Linux中

瑞典语:弗南姆 英语:名字

在Windows中

瑞典语:Förnamn 英语:名字

示例代码:

def user_information_report(report_file_path, user_id)
    user = User.find(user_id)
    I18n.locale = user.current_lang
    open_mode = "w+:UTF-16LE:UTF-8"
    bom = "\xEF\xBB\xBF"
    body user, open_mode, bom
  end

def headers
    headers = [
        "ID", "SDN ID",
        I18n.t('sys_first_name'), I18n.t('sys_last_name'), I18n.t('sys_dob'),
        I18n.t('sys_gender'), I18n.t('sys_email'), I18n.t('sys_address'),
        I18n.t('sys_city'), I18n.t('sys_state'), I18n.t('sys_zip'),
        I18n.t('sys_phone_number')
    ]
  end

def body tenant, open_mode, bom
    File.open(report_file_path, open_mode) do |f|
      csv_file = CSV.generate(col_sep: "\t") do |csv|
        csv << headers
        tenant.patients.find_each(batch_size: 10) do |patient|
          csv <<  [
              patient.id, patient.patientid,
              patient.first_name, patient.last_name, "#{patient.dob}",
              "#{translate_gender(patient.gender)}", patient.email, "#{patient.address_1.to_s} #{patient.address_2.to_s}",
              "#{patient.city}", "#{patient.state}",  "#{patient.zip}",
              "#{patient.phone_number}"
          ]
        end
      end
      f.write bom
      f.write(csv_file)
    end
  end

Windows和Mac

可以通过双击直接打开文件。

Linux(ubuntu)

打开文件时,请询问分隔符选项->选择“ TAB”

相关问题