-
-
Save nathancolgate/5468947 to your computer and use it in GitHub Desktop.
Example demonstrating the use of writeexcel gem in rails 3.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/mime_types.rb | |
Mime::Type.register "application/vnd.ms-excel", :xls |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi, I would like to know how can we embed data from a model in writeexcel file.
Thanks,