Excelizer
Excelizer handles Excel files generation for your Rails models with the Spreadsheet gem, using an API similar to the awesome active_model_serializers.
Installation
Add this line to your application's Gemfile:
gem 'excelizer'And then execute:
$ bundleOr install it yourself as:
$ gem install excelizerYou will need to add this line to the config/initializers/mime_types.rb file:
Mime::Type.register "application/vnd.ms-excel", :xlsUsage
You should create a downloaders folder inside the app folder. You can define a downloader like this
class UserDownloader < Excelizer::Base
attribute :name
attribute :last_name
attribute :email
attribute :token
endIt's possible to redefine the attributes using the object reference
class UserDownloader < Excelizer::Base
attribute :token
def token
object.token + rand(100)
end
endOr even create new attributes by defining them as methods:
class UserDownloader < Excelizer::Base
attribute :full_name
def full_name
"#{object.name} #{object.last_name}"
end
endAnd you can redefine the object variable by calling the instance method:
class UserDownloader < Excelizer::Base
instance :user
attribute :full_name
def full_name
"#{user.name} #{user.last_name}"
end
endYou can redefine the column name by passing the header option:
class UserDownloader < Excelizer::Base
attribute :full_name, header: "Nombre Completo"
endNow that we have a downloader, how do we actually use it? If you want to learn how to use it along ActiveAdmin, skip to the next section, if you just want to use the raw output, you can do this:
output = UserDownloader.new(User.all).downloadYou can optionally pass a collection as a parameter for scoped results:
output = UserDownloader.new(User.where(name: "Jaime")).downloadActiveAdmin
The recommended way to use this gem along ActiveAdmin is using an action_item and a collection_action. Future releases won't need this ;)
ActiveAdmin.register User do
collection_action :download_xls do
send_data UserDownloader.new(User.all).download,
type: 'application/vnd.ms-excel',
filename: "user_report.xls"
end
action_item only: [:index] do
link_to "Download Excel", download_xls_admin_users_path
end
endContributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
Changelog
- 1.0.0 Introduces brand new API
- 0.2.0 Fix custom header bug
- 0.1.0 Custom header support
- 0.0.9 Adds support for Rails 4
- 0.0.8 Safer attribute initialization
- 0.0.7 First release
License
This project is released under the MIT license.