Class: Metacrunch::File::XLSXDestination

Inherits:
Object
  • Object
show all
Defined in:
lib/metacrunch/file/xlsx_destination.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  worksheet_title: "My data"
}

Instance Method Summary collapse

Constructor Details

#initialize(filename, columns, options = {}) ⇒ XLSXDestination

Returns a new instance of XLSXDestination.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/metacrunch/file/xlsx_destination.rb', line 11

def initialize(filename, columns, options = {})
  @filename = filename
  @columns = columns
  @options = DEFAULT_OPTIONS.deep_merge(options)

  @package = Axlsx::Package.new
  @workbook = @package.workbook
  @sheet = @workbook.add_worksheet(name: @options[:worksheet_title])

  @sheet.add_row(columns, types: :string)
end

Instance Method Details

#closeObject



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

def close
  # Make the first row a header
  @sheet.sheet_view.pane do |pane|
    pane.top_left_cell = "A2"
    pane.state = :frozen_split
    pane.y_split = 1
    pane.x_split = 0
    pane.active_pane = :bottom_right
  end

  # Add a filter
  @sheet.auto_filter = @sheet.dimension.sqref

  # Generate file
  @package.serialize(@filename)
end

#write(data) ⇒ Object

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/metacrunch/file/xlsx_destination.rb', line 23

def write(data)
  return if data.blank?
  raise ArgumentError, "Data must be an Array" unless data.is_a?(Array)

  if data.first.is_a?(Array)
    data.each do |d|
      @sheet.add_row(d, types: :string)
    end
  else
    @sheet.add_row(data, types: :string)
  end
end