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.



17
18
19
# File 'lib/export_to/base.rb', line 17

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



19
20
21
22
23
24
25
# File 'lib/export_to/base.rb', line 19

def to_csv
  CSV.generate(force_quotes: true) do |csv|
    rows! do |columns, model, x|
      csv << columns
    end
  end
end

#to_xlsObject

舊版 Excel



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/export_to/base.rb', line 54

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

  rows! do |columns, model, x|
    sheet.row(x).concat(columns)
  end

  spreadsheet = StringIO.new
  book.write(spreadsheet)
  spreadsheet.string
end

#to_xlsx(file_path = nil, file_name = nil) ⇒ Object

新版 Excel



28
29
30
31
32
33
34
# File 'lib/export_to/base.rb', line 28

def to_xlsx(file_path=nil, file_name=nil)
  file_path ||= self.class.xlsx_file_path
  file_name ||= self.class.xlsx_file_name
  path = to_xlsx_file(file_path, file_name)
  # TODO: 讀取檔案回傳
  File.open(path, 'rb') { |f| f.read }
end

#to_xlsx_file(file_path = "tmp", file_name = "export") ⇒ Object

新版 Excel (outpuut: path)



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

def to_xlsx_file(file_path="tmp", file_name="export")
  path = "#{file_path}/#{file_name}_#{Time.now.to_i}_#{SecureRandom.hex}.xlsx"
  workbook = FastExcel.open(path, constant_memory: true)
  worksheet = workbook.add_worksheet("Default")

  bold = workbook.bold_cell_format
  worksheet.set_row(0, FastExcel::DEF_COL_WIDTH, bold)

  rows! do |columns, model, x|
    worksheet.write_row(x, columns)
  end

  workbook.close
  path
end