9

When exporting csv in Rails 4.2 app, there are ascii code in the csv output for Chinese characters (UTF8):

中åˆåŒç†Šå·¥ç­‰ç”¨é¤

We tried options in send_data without luck:

send_data @payment_requests.to_csv, :type => 'text/csv; charset=utf-8; header=present'

And:

send_data @payment_requests.to_csv.force_encoding("UTF-8")

In model, there is forced encoding utf8:

# encoding: utf-8

But it does not work. There are online posts talking about use gem iconv. However iconv depends on the platform's ruby version. Is there cleaner solution to fix the ascii in Rails 4.2 csv exporting?

user938363
  • 9,990
  • 38
  • 137
  • 303

4 Answers4

6

If @payment_requests.to_csv includes ASCII text, then you should use encode method:

@payment_requests.to_csv.encode("UTF-8")

or

@payment_requests.to_csv.force_encoding("ASCII").encode("UTF-8")

depending on which internal encoding @payment_requests.to_csv has.

1

You can try:

@payment_requests.to_csv.force_encoding("ISO-8859-1")
dx7
  • 804
  • 5
  • 11
1

for Chinese characters

CSV.generate(options) do |csv|
  csv << column_names
  all.each do |product|
    csv << product.attributes.values_at(*column_names)
  end
end.encode('gb2312', :invalid => :replace, :undef => :replace, :replace => "?")
Alan Wang
  • 552
  • 6
  • 15
0

This is what worked for me:

head = 'EF BB BF'.split(' ').map{|a|a.hex.chr}.join()

csv_str = CSV.generate(csv = head) do |csv|
  csv << [ , , , ...]
  @elements.each do |element|
    csv << [ , , , ...]
  end
end
Kryptman
  • 996
  • 9
  • 14