40
39

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.

RubyでMac版ExcelでインポートできるCSVデータを作成する

Last updated at Posted at 2012-12-26

Mac版ExcelはBOM付きUTF-16LEでないと正常にインポートできません。

以下Railsのコントローラーからの抜粋。
ポイントは、BOMのバイト列を force_encoding("UTF-16LE") しているところです。
こうしないと、output(UTF-16LE)と連結する際にエラーが出ます(ソースコードがUTF-8だとBOMのバイト列も当然UTF-8文字列とみなされるので)。

format.csv {
  header = "ID,氏名,住所,年齢,電話番号\r\n"
  CSV.generate(output = header) do |csv|
    @users.each do |user|
      csv << [user.id, user.name, user.address, user.age, user.tel]
    end
  end
  
  bom = "\xFE\xFF".force_encoding("UTF-16LE")
  
  send_data(bom + output.encode("UTF-16LE"),
    :type => 'text/csv',
    :filename => "your_file_name.csv")
}
40
39
2

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
40
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?