Ruby2xlsx¶ ↑
Export your data to Excel. Provide two ways for export data: template or renderer.
Install¶ ↑
Add gem to your Gemfile:
gem "ruby2xlsx"
Usage¶ ↑
You can use two types: template and renderer.
Renderer¶ ↑
def index @articles = Article.order('id DESC') respond_to do |format| format.html # index.html.erb format.xlsx { render xlsx: @articles } end end
With options:
format.xlsx { render xlsx: @articles, :columns => [:id, :title, :updated_at], :filename => ["articles_", Time.now.to_s, ".xlsx"].join, :worksheet_name => "My articles" }
Template¶ ↑
In controller (app/controllers/articles_controller.rb):
class ArticlesController < ApplicationController respond_to :xlsx, :only => [:index] def index @articles = Article.order('id DESC') @xlsx_filename = "some_file_name" respond_with(@articles) end end
In view (app/views/articles/index.xlsx.xrb):
add_worksheet "Data" bold = add_format(:bold => 1) headings = [ 'Title', 'Views', 'Comments' ] write('A1', headings, bold) @articles.each_with_index do |article, index| row = index + 1 write(row, 0, article.title) write(row, 1, article.views_count) write(row, 2, article.comments_count) end chart4 = add_chart(:name => 'Results Chart', :type => 'Chart::Area') # Configure the series. chart4.add_series( :categories => '=Sheet1!$A$2:$A$7', :values => '=Sheet1!$B$2:$B$7', :name => 'Test data series 1' ) # Add another series. chart4.add_series( :categories => '=Sheet1!$A$2:$A$7', :values => '=Sheet1!$C$2:$C$7', :name => 'Test data series 2' ) # Add some labels. chart4.set_title( :name => 'Results of sample analysis' ) chart4.set_x_axis( :name => 'Sample number' ) chart4.set_y_axis( :name => 'Sample length' )
Dependencies¶ ↑
Other similar gems¶ ↑
This project rocks and uses MIT-LICENSE.