我有以下方法在我的操作导出到excel的用户列表:
def users_report
@users = Kid.where(confirmation_token: nil).paginate(:page => params[:page], :per_page => 30)
@userxls = Kid.where(confirmation_token: nil)
respond_to do |format|
format.html
format.xls { send_data @userxls.to_csv({col_sep: "t"}) }
end
end
在我的模型中to_csv方法:
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << ["Name", "Surname", "E-mail", "Age", "School", "Class", "Native Language", "Practised Language", "Conversations same Native", "Convserations different Native", "Message same Native", "Message different Native", "Posts", "Clossed/Finished calls", "Missed calls", "Connections per Week", "Nb of foreign friends", "Nb of friends same country", "Activation Date", "Email Parent", "Parent Activated"]
kids = Array.new
all.each do |kid|
if kid.user_role != "admin"
k = Array.new
kid.name = kid.name rescue "No name"
k << kid.name
kid.surname = kid.surname rescue "No surname"
k << kid.surname
kid.email = kid.email rescue "No email"
k << kid.email
k << kid.age rescue "No age"
if !kid.school.nil?
k << kid.school.name
else
k << "No School"
end
if kid.courses.empty?
k << "No Courses"
else
k << kid.courses.first.name
end
if !kid.native_languages.empty?
languages = Array.new
kid.native_languages.each do |lang|
languages << Language.find(lang).name
end
k << languages
else
k << "No native language"
end
if !kid.practice_languages.empty?
languages = Array.new
kid.practice_languages.each do |lang|
languages << Language.find(lang).name
end
k << languages
else
k << "No practise language"
end
k << kid.number_of_native_conversations rescue "0"
k << kid.number_of_foreign_conversations rescue "0"
k << kid.number_of_native_messages rescue "0"
k << kid.number_of_foreign_messages rescue "0"
k << kid.number_of_activity_posts rescue "0"
k << kid.number_of_finished_closed_calls rescue "0"
k << kid.number_of_missed_calls rescue "0"
k << kid.avg_of_connections_week rescue "0"
k << kid.number_of_foreign_friends rescue "0"
k << kid.number_of_friends_same_country rescue "0"
k << kid.confirmed_at.try(:strftime, "%d/%m/%Y") rescue "0"
k << kid.tutor.email rescue "No parent email"
k << kid.tutor.confirmed? rescue "No parent email"
kids << k
end
end
kids.each do |k|
csv << k
end
end
end
但是在我的excel文件中,我得到的名字像Jérôme而不是Jérôme。我试着:
# encoding: utf-8
在我的视图中也尝试了每个字段
.force_encoding("UTF-8")
但是我仍然有这个问题。我真的需要你的帮助。
Thanks in advance
CVS::generate
理解选项:encoding
(参见Ruby API)。
format.xls { send_data @userxls.to_csv({col_sep: "t", encoding: 'UTF-8'}) }
您还可以考虑将表示和业务逻辑分开。我使用csv_builder
,它提供了像user_report.csv.csvbuilder
这样的视图来定义csv输出。
cvs_builder
使用实例变量@encoding
指定输出字符编码。
编辑
看起来,就像你生成的csv已经在UTF-8编码,但你读它,如果它是ISO-8859-1 aka。latin - 1。
您可能想尝试在LATIN-1
中生成csv,因为excel在导入UTF-8 csv文件时存在问题。
根据Ruby或Rails版本,您必须使用ISO-8859-1
而不是LATIN-1
。