LoginSignup
11
11

More than 5 years have passed since last update.

RailでCSVエクスポートする

Last updated at Posted at 2015-08-03

毎度実装する度に、文字化けやらなんやらで調べることが多いのでまとめておきます。

環境

  • ruby 2.1.0
  • Ruby on Rails 4.2.0

実装

Controller

ControllerではCSVにて出力したいデータを取得する処理を書きます。
今回は例として、ユーザーデータが入ったUser model(name: string, phone_number: string)の中身を全部出力するコードを書いていきます。

users_controller.rb
class UsersController < ApplicationController

  def csv_download
    @users = User.all
    # ファイル名を指定するために以下の1行を追加しておく
    send_data render_to_string, filename: 'users.csv', type: :csv
  end

end

View

次にControllerから取得したデータをCSVで出力するためのViewを作っていきます。

csv_download.csv.ruby
# 以下2のモジュールを使用
require 'csv'
require 'nkf'

# 1行目に表示する項目を設定
items = %w(No 名前 電話番号 登録日時)

csv_str = CSV.generate do |csv|
  csv << items
  i = 1
  @users.each_with_index(1) do |user, i|
    csv << [
      i,
      user.name,
      user.phone_number
      user.created_at.strftime("%Y-%m-%d %H:%M:%S")
    ]
  end
end

# 文字化けを防止するためにNKFで文字コード変換
NKF::nkf('--sjis -Lw', csv_str)

以上で実装は完了です。あとはダウンロードをリンクを該当のページに作るだけでCSVをダウンロードすることができます。

参考

11
11
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
11
11