您好,我正在使用Ruby on Rails进行CSV生成。在我们的应用程序中,我们计划采用多语言(I18n),但是当在Windows Excel的CSV文件中查看I18n内容时遇到了问题。
在Linux(Ubuntu)和Mac上没有问题。
我们发现Windows Excel需要重新导入数据才能查看实际数据。在导入时,我们将获得更多选择字符集的选项。
但是这不能为每个用户提供教育,因此我们正在寻找的解决方案是通过双击打开文件。
然后,我们在Windows Excel中识别了通过打开模式和BOM显示数据的方法,借助于aghuddleston的gist。附加在参考资料中。
I18n内容示例
在Mac和Linux中
瑞典语:Förnamn
英语:First name
在Windows中
瑞典语:Förnamn
英语:First name
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
需要注意的重要事项是打开模式和bom
open_mode = "w+:UTF-16LE:UTF-8"
bom = "\xEF\xBB\xBF"
在写CSV之前插入BOM
f.write bom
f.write(csv_file)
Windows和Mac
文件可以通过双击直接打开。
Linux(ubuntu)
在打开文件时会提示选择分隔符选项,选择“TAB”![enter image description here](https://istack.dev59.com/KC1Zz.webp)
\t
作为分隔符。适用于英文和非英文Excel设定。可以直接按Ctrl-S
进行保存,无需选择文件格式等操作。可以保留Unicode字符。 - Sebastian