2
1

More than 3 years have passed since last update.

railsで.xlsxを生成する

Last updated at Posted at 2020-05-01

概要

xlsxを出力する必要があったため、 caxlsx_rails 使用して.xlsxファイルを生成していく

axlsx_rails renamed to caxlsx_rails

もともとaxlsx_railsという名称のgemだったっぽい

準備

Gemfile
gem 'caxlsx'
gem 'caxlsx_rails'

コントローラーに追加

hoges_controller.rb
...
  def show
    @hoges = Hoge.all
    respond_to do |format|
      format.html
      format.xlsx
    end
  end
...

viewに拡張子が.xlsx.axlsxのテンプレートを作成

下記のようなファイルを作成するだけでxlsm形式のファイルを生成する事が可能。

wb = xlsx_package.workbook
wb.add_worksheet(name: "hoge") do |sheet|
  @hoges.each do |hoge|
    sheet.add_row ["hoge", hoge.hoge]
  end
end

ファイル名を変更したい場合

controllerのformat.xlsx内を変えるだけでいけるっぽい

...
format.xlsx {
  response.headers['Content-Disposition'] = 'attachment; filename="hoge.xlsx"'
}
...

複数シートを作りたい

こんな感じで出来るっぽい

@hoges.each.with_index(1) do |hoge, i|
  wb.add_worksheet(name: "#{i}") do |sheet|
    sheet.add_row ["hoge", hoge.hoge]
  end
end

Ruby Axlsx: How to get values from another worksheet - Stack Overflow

add_worksheetの引数に渡しているnameはそれぞれ別の名前を指定しないと下記のエラーが出るのでファイル毎にそれぞれ違う名前を設定する必要がありそう
There is already a worksheet in this workbook named 'hoge’. Please use a unique name

セル内改行したい

下記設定を追加すればいけそう

...
wb.use_shared_strings = true
...
wrap = wb.styles.add_style alignment: { wrap_text: true }
...
sheet.add_row ["hoge", hoge.hoge], style: wrap
...

実際のコードにするとこんな感じ

wb = xlsx_package.workbook
wb.use_shared_strings = true
@hoges.each.with_index(1) do |hoge, i|
    wrap = wb.styles.add_style alignment: { wrap_text: true }
  wb.add_worksheet(name: "#{i}") do |sheet|
    sheet.add_row ["hoge", hoge.hoge], style: wrap
  end
end
2
1
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
2
1