Skip to content

Instantly share code, notes, and snippets.

@nathancolgate
Forked from ream88/excel_template_handler.rb
Last active November 18, 2018 15:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nathancolgate/5468947 to your computer and use it in GitHub Desktop.
Save nathancolgate/5468947 to your computer and use it in GitHub Desktop.
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
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
Copy link
Author

@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