更快的CSV和非拉丁字符

时间:2010-11-09 16:09:16

标签: ruby-on-rails fastercsv

Iv最近编写的代码将帮助我使用带有rails的FasterCSV将SQL数据库导出为CSV。但是,我的数据库的某些部分包含繁体中文字符。当我输出它我得到??????作为CSV文件中的输出。我已经尝试更改$ KCODE ='u',以便FasterCSV使用UTF-8对CSV文件进行编码,但没有运气。转换编码的Iconv也给了我奇怪的结果。这是源代码:

def csv
@lists = Project.find(:all, :order=> (params[:sort] + ' ' + params[:direction]), :conditions =>  ["name LIKE ?", "%#{params[:selection]}%"])

csv_string = FasterCSV.generate do |csv|
  csv << [<bold> "Status","Name","Summary","Description","Creator","Comment","Contact Information","Created Date","Updated Date"]

  @lists.each do |project|
    csv << [project.status, project.name, project.summary, project.description, project.creator, project.statusreason, project.contactinfo, project.created_at, project.updated_at]
  end
end

filename = Time.now.strftime("%Y%m%d") + ".csv"
send_data(csv_string,
  :type => 'text/csv; charset=utf-8; header=present',
  :filename => filename)

谢谢,

1 个答案:

答案 0 :(得分:2)

我不习惯使用中文字符,但您可以尝试在:encoding电话上将generate选项添加到“u”(UTF-8):

...
csv_string = FasterCSV.generate(:encoding => 'u') do |csv|
...

作为旁注,我建议使用named_scopes而不是写这个:

Project.find(:all, :order=> (params[:sort] + ' ' + params[:direction]), :conditions =>  ["name LIKE ?", "%#{params[:selection]}%"])
祝你好运!