1

I have a module to generate csv file of the model when included.

# app/models/concerns/csv_exportable.rb
module CsvExportable
  extend ActiveSupport::Concern

  included do
    def self.to_csv(options = {})
      CSV.generate(options) do |csv|
        csv << column_names
        all.each do |thismodel|
          csv << thismodel.attributes.values_at(*column_names)
        end
      end
    end
  end
end

and I include the module in models for which I want to generate csv file

# app/models/product.rb
class Reason < ActiveRecord::Base
  include CsvExportable
  .
  .
end

In my controller I do

respond_to do |format|
  format.html
  format.csv { send_data @products.to_csv, filename: 'products.csv' }
end

I want to set the character encoding of generated csv file to Shift_JIS instead of default utf-8. What is the best way to do this ? Thank you

EDIT:

I tried

format.csv { send_data (@products.to_csv).encode("SHIFT-JIS"), filename: 'products.csv' }

now I am getting an error Encoding::ConverterNotFoundError code converter not found (UTF-8 to SHIFT-JIS)

Tony Vincent
  • 13,354
  • 7
  • 49
  • 68
  • **This can solve your problem** [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.](http://stackoverflow.com/a/11451089/4209704) – Pradeep Sapkota Aug 08 '16 at 05:46

2 Answers2

1
format.csv { 
  send_data (@products.to_csv).encode(Encoding::SJIS), 
  filename: 'products.csv', 
  type: 'text/csv; charset=shift_jis'
}

Did the trick

Tony Vincent
  • 13,354
  • 7
  • 49
  • 68
0

You can pass encoding: '<non utf-8 encoding>' option in the options hash you passed to to_csv in CsvExportable so that it will be available for CSV.generate method while generating csv file.

bhanu
  • 2,260
  • 3
  • 24
  • 35