LoginSignup
4
4

More than 5 years have passed since last update.

spreadsheetを使用してmodelの中身をxls形式で出力する

Last updated at Posted at 2013-08-01

概要

コントローラから対象モデルのxlsファイルデータを呼び出して
send_dataを使用してxlsファイルをダウンロード出来るようにします。

application.rb

require 'spreadsheet'
require 'stringio'

Gemfile

gem 'spreadsheet'

hoge_controller.rb

def export_excel
  xls = HogeModel.create_xls
  send_data(xls.string.bytes.to_a.pack("C*"), :filename => 'hoge.xls', :type => 'application/vnd.ms-excel')
end

hoge_model.rb

def self.create_xls
  book = Spreadsheet::Workbook.new
  sheet = book.create_worksheet(:name => 'Sheet1')
  hoge = HogeModel.new
  sheet.row(0).replace hoge.column_names
  hoge.all.each_with_index do |col, count|
    sheet.row(count + 1).replace col.attributes.values
  end
end

不明点(情報求む)

sheetの次row指定に対して追加をするメソッドが見つけられなかったので
each_with_indexでcountを取得して+1しています。

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