user3548398
user3548398

Reputation: 61

Rails to excel with associations

i'am new on rails , i've spent my day looking for solution to export my data into excel file.

I've tryed to_xls, simple_xlxs and other gems, also i've tryed to render xml template , but i've no success.

So i have associations between 2 models:

Call model:

class Call < ActiveRecord::Base
  belongs_to :number
  has_many :results
end

and my result model:

class Result < ActiveRecord::Base
  belongs_to :call
end

So i need to genrate excel tables with my OWN headers in table calle'd as i want. And also i wan't that in this excel file will be columns from my associeted model

What can i do? Thanks

Upvotes: 0

Views: 167

Answers (1)

fgc29
fgc29

Reputation: 36

# install in a gem file or in the terminal to test
# gem install spreadsheet


require 'spreadsheet'

Spreadsheet.client_encoding = 'UTF-8'

book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => 'test'

money_format = Spreadsheet::Format.new :number_format => "#,##0.00 [$€-407]"
date_format = Spreadsheet::Format.new :number_format => 'MM.DD.YYYY'

# set default column formats
sheet1.column(1).default_format = money_format
sheet1.column(2).default_format = date_format

# depending on your data you obviously have to create a loop that fits  the format of your data
sheet1.row(0).push "just text", 5.98, DateTime.now

book.write 'sample.xls'

The above code example writes the data to columns you create. You can have your info in csv style. So if you're returning objects you can just get values for each object and join the array with ',' separation and loop through.

Upvotes: 2

Related Questions