We’re going to export data to Excel from our RoR application, in about five lines of code. There’re many options available out there and it’s all pretty confusing. People try to export CSV and XML formats.
Here’s how we do it, and so should you.
Just Do It!
Use spreadsheet 0.6.5.8 with this monkey-patch added as initializers/spreadsheet_encodings.rb and to_xls 1.0 from my to-xls-on-models branch.
Register the Excel MIME type in config/initializers/mime_types.rb.
Add a as_xls method to any model that you want to export that contains the fields of interest. Here’s what I added to app/models/user.rb.
You can also simply call as_json inside as_xls. Note that currently only top-level keys are exported.
Add support for the .XLS format in any controller out of which you want to export Excel files. Here’s what I added to app/controllers/users_controller.rb.
Add a link on the users view. Here’s what I added to app/views/users.html.haml. The parameter merging lets you reuse whatever parameters were passed in the page.
We added some styles, so here’s what the export button looks like next to another one.
You get real XLS documents, book & al.
We can write a spec for this controller too.
Links
- spreadsheet gem home, rubygems and patch for frozen hash in encoding
- to_xls home and rubygems and my pull request to to_xls with as_xls support
- plataforma’s blog post on the topic that helped me steer in the right direction
- spreadsheet_encodings.rb monkey patch
- original to_csv that inspired to_xls
- an alternative using rxsl templates