18
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで出力したcsvファイルをexcelで開いても文字化けしない方法

Last updated at Posted at 2019-03-05

発生事象

RailsアプリケーションでCSV出力をしたファイルをExcelで開くと文字化ける。
理由はExcelがUTF-8のファイルをSJISで開こうとしてしまうため。

文字a化け.rb
def to_csv
  csv_column_name = %w(id 名前 メール)
  CSV.generate do |csv|
    csv << csv_column_name
    all.each do |user|
      csv << user.csv_column_values
    end
  end
end

方法1 BOM付きUTF-8でcsv出力する

bom付きにするとexcelがUTF-8で開く。
UTF-8のファイルをUTF-8として開くから文字化けない。

bom+utf8の方法.rb
def to_csv
  bom = "\uFEFF"
  csv_column_name = %w(id 名前 メール)
  CSV.generate(bom) do |csv|
    csv << csv_column_name
    all.each do |user|
      csv << user.csv_column_values
    end
  end
end
この部分.rb
bom = "\uFEFF"
この部分.rb
CSV.generate(bom) do |csv|

方法2 SJISにエンコードして出力する

sjisの方法.rb
def to_csv
  csv_column_name = %w(id 名前 メール)
  CSV.generate(encoding: Encoding::SJIS, row_sep: "\r\n", force_quotes: true) do |csv|
    csv << csv_column_name
    all.each do |user|
      csv << user.csv_column_values
    end
  end
end
この部分.rb
CSV.generate(encoding: Encoding::SJIS, row_sep: "\r\n", force_quotes: true) do |csv|

参考

https://qiita.com/wada811/items/8b73f633f77c0466e9da
https://qiita.com/ngron/items/60915083cb2bc3622c79

18
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?