Class: ExportTo::Base

Inherits:
Struct
  • Object
show all
Defined in:
lib/export_to/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#objectObject

Returns the value of attribute object.



11
12
13
# File 'lib/export_to/base.rb', line 11

def object
  @object
end

#recordsObject

Returns the value of attribute records

Returns:

  • (Object)

    the current value of records



2
3
4
# File 'lib/export_to/base.rb', line 2

def records
  @records
end

Instance Method Details

#to_csvObject



13
14
15
16
17
18
19
# File 'lib/export_to/base.rb', line 13

def to_csv
  CSV.generate do |csv|
    each do |columns, order, i|
      csv << columns
    end
  end
end

#to_xlsObject

舊版 Excel



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/export_to/base.rb', line 41

def to_xls
  book = Spreadsheet::Workbook.new
  sheet = book.create_worksheet

  each do |columns, order, x|
    sheet.row(x).concat(columns)
  end
  spreadsheet = StringIO.new
  book.write(spreadsheet)
  spreadsheet.string
end

#to_xlsxObject

新版 Excel



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/export_to/base.rb', line 22

def to_xlsx
  io = StringIO.new
  book = WriteXLSX.new(io)
  sheet = book.add_worksheet

  # 表格頭 (粗體紅字)
  format_head = book.add_format.tap { |f| f.set_bold }.tap { |f| f.set_color('red') }

  each do |columns, order, x|
    columns.each_with_index do |column, y|
      sheet.write(x, y, column, format_head)
    end
  end

  book.close
  io.string
end