Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.2 - how to fix ascii code in CSV exporting without gem 'iconv'?

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?

like image 241
user938363 Avatar asked Apr 21 '15 00:04

user938363


2 Answers

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.

like image 84
Dieter Pisarewski Avatar answered Oct 08 '22 23:10

Dieter Pisarewski


You can try:

@payment_requests.to_csv.force_encoding("ISO-8859-1")
like image 33
dx7 Avatar answered Oct 09 '22 00:10

dx7