Class: SpreadsheetTemplate::TemplateHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/spreadsheet_template/template_handler.rb

Overview

Template handler for Excel templates

Add rows to your Excel file in the template by manipulating the ‘book’ variable using the Spreadsheet gem methods

sheet = book.create_worksheet sheet.name = “Phenol-Explorer Polyphenol Classes”

# Set style for header sheet.row(0).concat headers format = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10 sheet.row(0).default_format = format row = sheet.row(1) row.push (‘one’, ‘two’, ‘three’)

You can set the default filename for that a browser will use for ‘save as’ by setting @filename instance variable in your controller’s action method e.g.

@filename = 'report.csv'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(template) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/spreadsheet_template/template_handler.rb', line 25

def self.call(template)
  <<-EOV
  begin
    if controller.request.env['HTTP_USER_AGENT'] =~ /msie/i
      controller.response.headers['Pragma'] = 'public'
      controller.response.headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
      controller.response.headers['Content-Disposition'] = "attachment; filename=\#{@filename}"
      controller.response.headers['Expires'] = "0"
    else
      controller.response.headers["Content-Disposition"] = "attachment; filename=\#{@filename}"
      controller.response.headers["Content-Transfer-Encoding"] = "binary"
    end
    controller.response.content_type ||= Mime::XLS

    book = Spreadsheet::Workbook.new
    #{template.source}
    blob = StringIO.new("")
    book.write blob
    blob.string
  rescue Exception => e
    Rails.logger.warn("Exception \#{e} \#{e.message} with class \#{e.class.name} thrown when rendering XLS")
    raise e
  end
  EOV
end

Instance Method Details

#compile(template) ⇒ Object



51
52
53
# File 'lib/spreadsheet_template/template_handler.rb', line 51

def compile(template)
  self.class.call(template)
end