rails Excel出力

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます
Gemインストール
gem 'rubyzip', '>= 1.2.1'
gem 'axlsx', git: 'https://github.com/randym/axlsx.git', ref: '776037c0fc799bb09da8c9ea47980bd3bf296874'
gem 'axlsx_rails'

設定ファイルの作成
vim config/initializers/mine_types.rb
Mime::Type.unregister :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx

controllerの作成
  def action
    @project = Project.find(1)
    @action_histories = ActionHistory.where(project_id: @project.id)

    respond_to do |format|
      format.html
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="Action.xlsx"'
      }
    end
  end


view
wb = xlsx_package.workbook
wb.styles do |style|
  highlight_cell = style.add_style(bg_color: "EFC376")

  wb.add_worksheet(name: "Action") do |sheet|
  sheet.add_row ['UID', 'action', '日時']
    @action_histories.each do |action|
     sheet.add_row [action.user_key, action.action_id, action.created_at], style: [nil, highlight_cell]
    end
  end
end

以下のようなURLで確認
"http://hogehoge.jp/output/action.xlsx

[参考]
Back