Rails: Export arbitrary array to Excel using to_xls gem
export-to-excel, ruby-on-rails
Solution
This should work for arbitrary Arrays and for ActiveRecord objects. Apparently, the to_xls gem supports all the customisation via the :columns and :headers parameters.
require 'bundler/setup'
require 'to_xls'
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def name
"#{first_name} #{last_name}"
end
end
array = [Person.new("Andrzej", "Krzywda"), Person.new("Derek", "Hill")]
File.open("output.xls", "w") do |f|
f.write(
array.to_xls(
:columns => [:first_name, :last_name, :name],
:headers => ["First name", "Last name", "name"]
)
)
end
Problem
I want to export data from Rails to Excel in a way which: - supports special characters (é, ô, ü etc.) - works in all versions of Excel 2007+ - allows me to add calculated columns before export I'm thinking about using the to_xls gem, but can't get it to work on arbitrary arrays (only Active Record objects). The docs say the gem is only slightly oriented towards exporting Active Record sets, and that it's designed to transform arrays into Excel so it must be possible. I think the issue is that it requires each object in the array to respond to .attributes. I tried the approach of adding a virtual attribute to the Active Record model the export is based on but it seems that this doesn't show up when .attributes is called. How could I get this working? (Or can you suggest an alternative way to achieve these goals?)