LoginSignup
10
9

More than 5 years have passed since last update.

RailsでExcelファイルを出力する

Posted at

今回はAxlsx_railsというgemを使います。
ボタンを押したらダウンロード出来るとこまでやります。

環境

・ruby 2.3
・Rails 5.1

準備

gemを追加

Gemfile
gem 'rubyzip', '>= 1.2.1'
gem 'axlsx', git: 'https://github.com/randym/axlsx.git', ref: '776037c0fc799bb09da8c9ea47980bd3bf296874'
gem 'axlsx_rails'

Mime::Typeを追加

config/initializers/mine_types.rb
Mime::Type.unregister :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx

任意のアクションに対して下記のコードを追加(model名は適当です)

app/assets/products_controller.rb
class ProductsController < ApplicationController

def index
  @products = Product.all
  respond_to do |format|
    format.html
    format.xlsx {
      response.headers['Content-Disposition'] = 'attachment; filename="Product.xlsx"'
    }
  end
end

テンプレートの作成

出力するファイルのデザインや、要素を書き込んでいきます。

Axlsx_railsはAxlsxというgemに依存しているのでAxlsxのサンプルがそのまま使えます。
Axlsx サンプルコード

それでは実際に作っていきます。

実装

app/views/productsフォルダにテンプレートファイルを作成します。

ファイル名には規則があります。
action名.xlsx.axlsx

今回はindex.xlsx.axlsxになります。
もし、actionがcreateだとしたら
create.xlsx.axlsxというファイル名になります。

app/views/products/index.xlsx.axlsx
wb = xlsx_package.workbook
wb.styles do |style|
  highlight_cell = style.add_style(bg_color: "EFC376")

  wb.add_worksheet(name: "Products") do |sheet|
    @products.each do |product|
     sheet.add_row [product.title, product.price], style: [nil, highlight_cell]
    end
  end
end

次にダウンロードボタンを追加します。

app/views/products/index.html.erb
<%= link_to 'Download spreadsheet', product_path(format: :xlsx), data: {turbolinks: false} %>

これでExcelファイルをダウンロードできるようになりました。

参考サイト

Generate Excel Spreadsheets with Rails and the Axlsx Gem
【Rails】Rubyテンプレートで axlsx を出力する方法
axlsx_rails を用いて Excel のスプレッドシートを生成する
RailsでExcelを扱うGemまとめ

10
9
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
10
9