Character encoding issue exporting rails data to CSV

When Excel opens the CSV file it just assumes an “iso-8859-1” character encoding. I guess it doesn’t even know about the encoding information you send along within your HTTP reply. That’s why setting this to UTF-8 doesn’t work.

So in order to export your CSV file for Excel in Rails you could do this:

send_data Iconv.conv('iso-8859-1//IGNORE', 'utf-8', csv_data),
  :type => 'text/csv; charset=iso-8859-1; header=present',
  :disposition => "attachment; filename=#{filename}.csv"

This re-encodes your UTF-8 data string (that’s the Rails default) to ISO-8859 and sends it. Along goes the information that this reply is actually ISO-8859-1 encoded (which won’t make a difference for Excel but is technically correct if you should open it in a browser etc.).

Leave a Comment