Reputation: 6454
I want to export data from Rails to Excel in a way which:
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?)
Upvotes: 4
Views: 4631
Reputation: 181
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
Upvotes: 4
Reputation: 1480
Have you tried axlsx? According to the examples section it should work with generic arrays.
Upvotes: 0