3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
50
51
52
53
54
55
|
# File 'lib/controller_extensions/export_to_excel.rb', line 3
def self.included(base)
base.class_eval do
private
require 'spreadsheet'
def export_to_excel_prototype(records, column_names, model_column_names, options)
spreadsheet = StringIO.new
book = create_spreadsheet_for_export(records, column_names, model_column_names, options)
book.write spreadsheet
send_data spreadsheet.string, :filename => (options[:file_name].presence || "export_#{Time.now.to_s.underscore}.xls"), :type => "application/vnd.ms-excel"
end
def create_spreadsheet_for_export(records, column_names, model_column_names, options = {})
book = ::Spreadsheet::Workbook.new sheet = book.create_worksheet :name => (options[:worksheet_name].presence || options[:file_name].presence || 'Excel export') sheet.row(0).concat column_names records.each_with_index do |record, index|
write_record_to_sheet(sheet, record, model_column_names, index + 1) end
book
end
def write_record_to_sheet(sheet, record, model_column_names, row_index)
model_column_names.each_with_index do |name, column_index|
sheet[row_index, column_index] = record.send(name.underscore.to_sym)
end
end
end
end
|