开发者

FasterCSV and Non-Latin Characters

开发者 https://www.devze.com 2023-01-24 09:20 出处:网络
Iv recently written code that will help me export an SQL database into CSV using FasterCSV with rails. However some parts of my database contain Traditional Chinese Characters. When I export it i\'m g

Iv recently written code that will help me export an SQL database into CSV using FasterCSV with rails. However some parts of my database contain Traditional Chinese Characters. When I export it i'm getting ?????? as the output in the CSV file. Iv already tried changing the $KCODE = 'u' so that FasterCSV uses UTF-8 to encode the CSV file, but no luck. Iconv to convert the encoding is giving me strange results as well. Here is the source code:

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; head开发者_C百科er=present',
  :filename => filename)

end

Thanks,


I'm not used to work with chinese characters, but you can try adding the :encoding option to 'u' (UTF-8) on the generate call:

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

As a side note, I'd recommend using named_scopes instead of writing this:

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

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消