Class: Xls::Columnizer

Inherits:
Object
  • Object
show all
Defined in:
lib/xls/columnizer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Columnizer

Constructor



9
10
11
# File 'lib/xls/columnizer.rb', line 9

def initialize(options={})
  self.fixed_columns = options[:fixed_columns] || []
end

Instance Attribute Details

#fixed_columnsObject

A list of names of the columns that should stay fixed.



21
22
23
# File 'lib/xls/columnizer.rb', line 21

def fixed_columns
  @fixed_columns
end

Instance Method Details

#process(input) ⇒ Workbook

Converts the columns on the worksheets of the input workbook from n-column tables to 2-column tables.

Parameters:

  • input (Workbook)

    The input workbook.

Returns:

  • (Workbook)

    The columnized workbook.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/xls/columnizer.rb', line 36

def process(input)
  output = Spreadsheet::Workbook.new()
  
  (0...input.sheet_count).each do |input_sheet_index|
    input_sheet = input.worksheet(input_sheet_index)
    output_sheet = output.create_worksheet()
    output_index = 1

    # Process headers.
    input_headers = input_sheet.row(0).map { |cell| cell.to_s }
    output_sheet.row(0).replace(fixed_columns.clone.concat(['KEY', 'VALUE']))

    # Process data.
    column_range = (0...input_headers.length)
    input_sheet.each(1) do |input_row|
      # Determine fixed column values.
      fixed_column_values = fixed_columns.map { '' }
      column_range.each do |index|
        fixed_column_index = fixed_columns.index(input_headers[index])
        fixed_column_values[fixed_column_index] = input_row[index] unless fixed_column_index.nil?
      end
      
      # Write key/value data.
      column_range.each do |index|
        next if fixed_columns.index(input_headers[index])
        output_row = output_sheet.row(output_index)
        output_row.replace(fixed_column_values)

        # Write header and data.
        output_row.push(input_headers[index])
        output_row.push(input_row[index])

        output_index = output_index + 1
      end
    end

  end
  
  return output
end