Reputation: 175
i have table like the following
now, i want to export this to excel, so i can open it in ms excel
Upvotes: 0
Views: 3173
Reputation: 1397
Ruby 1.9 has a built in CSV library with very similar API as the FasterCSV gem (actually the gem got integrated into Ruby!).
Upvotes: 0
Reputation: 17587
You can use FasterCSV gem.
You can either use to_csv
method.
def index
@records = ....
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @records }
format.csv { @records.to_csv }
end
end
or customize the output and use send_data
method in the controller.
format.csv do
csv_string = FasterCSV.generate do |csv|
# header row
csv << ["id", "Column1", "Column1"]
# data rows
@records.each do |r|
csv << [r.id, r.column1, r.column2]
end
# send it to the browser
send_data csv_string,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=records.csv"
end
Upvotes: 3
Reputation: 18775
I would advice to use Spreadsheet which is mature. I'm using it with Rails 3 with no problems.
The overall process would be:
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => 'Customers'
sheet.row(0).concat %w{Name Country Acknowlegement}
book.write '/path/to/output/excel-file.xls'
Upvotes: 1