我有关于导出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")
但我仍然有这个问题。我真的需要帮助。
提前致谢
答案 0 :(得分:1)
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
。