Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example demonstrating the use of writeexcel gem in rails 3.2
# config/initializers/mime_types.rb
Mime::Type.register "application/vnd.ms-excel", :xls
# app/controllers/reports_controller.rb
class ReportsController < ApplicationController
def show
@report = Report.find(params[:id])
respond_to do |format|
format.html
format.xls { render :template => 'reports/show.xls.writeexcel'}
end
end
end
# app/views/reports/show.xls.writeexcel
# Add worksheet(s)
worksheet = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
# Add and define a format
format = workbook.add_format
format.set_bold
format.set_color('red')
format.set_align('right')
# write a formatted and unformatted string.
worksheet.write(1, 1, 'Hi Excel.', format) # cell B2
worksheet.write(2, 1, 'Hi Excel.') # cell B3
# write a number and formula using A1 notation
worksheet.write('B4', 3.14159)
worksheet.write('B5', '=SIN(B4/4)')
worksheet.write('B5', @report.number_of_widgets)
# config/initializers/writeexcel_template_handler.rb
class ActionView::Template
module Handlers
class WriteExcelTemplateHandler
def call(template)
%{
Tempfile.open('writeexcel').tap do |tmp|
WriteExcel.new(tmp.path).tap do |workbook|
#{template.source}
end.close
end.tap(&:rewind).read
}
end
end
end
register_template_handler(:writeexcel, Handlers::WriteExcelTemplateHandler.new)
end
@Trehana

This comment has been minimized.

Copy link

Trehana commented Jul 23, 2014

hi, I would like to know how can we embed data from a model in writeexcel file.
Thanks,

@nathancolgate

This comment has been minimized.

Copy link
Owner Author

nathancolgate commented Dec 3, 2014

@Trehana I updated the view to include some data from the model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.