RailsでExcelを出力する
RailsでExcelを出力するのに、randym/axlsx · GitHub を使ってみました。
ほかにもgemはありますが、
- セルをいろいろ操作したい(装飾とかマージとか)
- 将来的にグラフを出力したいという要望がある
ということで、axlsxを選択しました。
1. gemインストール
Gemfileに以下を追記して、bundle install.
gem 'axlsx'
2. 出力する内容をつくる
axlsx/example.rb at master · randym/axlsx · GitHub を参考に、
地道に1行ずつ作成します。
package = Axlsx::Package.new package.workbook do |wb| # style wb.styles.fonts.first.name = 'MS Pゴシック' defaults = {alignment: {horizontal: :center, vertical: :center}} title = wb.styles.add_style sz: 12, b: true, alignment: { horizontal: :center } bg_yellow = wb.styles.add_style defaults.merge(bg_color: "FFFF00") # 印刷の設定 set_print = {:fit_to_width => 1, :fit_to_height => 1, :orientation => :landscape} wb.add_worksheet(:name => "Test Result", :page_setup => set_print) do |sheet| # 列幅を決める sheet.column_widths 8, 12, 5, 5, 5 # 5行つくる 5.times {sheet.add_row Array.new(5, '')} # A1セルに値とスタイルを設定 sheet.rows[0].cells[0].value = "タイトル" sheet.rows[1].cells[0].style = title # セルごとに設定できるプロパティは以下 # [:value, :type, :font_name, :charset, :family, :b, :i, :strike, :outline, # :shadow, :condense, :extend, :u, :vertAlign, :sz, :color, :scheme] sheet.rows[1].cells[0].value = "下線" sheet.rows[1].cells[0].u = :single sheet.rows[1].cells[0].type = :string # セルを結合する sheet.merge_cells("C2:E2") # こういう指定の仕方もできる sheet["A3:E3"].each.with_index do |cell, i| cell.value = "#{i}" cell.style = bg_yellow end end end
3. xlsxファイルを出力する
send_data package.to_stream.read, filename: "sample.xlsx", type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", disposition: 'attachment'