Class: Xls::Selection

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

Defined Under Namespace

Classes: SelectionFormatError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(columns, rows) ⇒ Selection

Constructor



70
71
72
73
# File 'lib/xls/selection.rb', line 70

def initialize(columns, rows)
  self.columns = columns
  self.rows = rows
end

Instance Attribute Details

#columnsObject

A range of column indices that the selection covers.



86
87
88
# File 'lib/xls/selection.rb', line 86

def columns
  @columns
end

#rowsObject

A range of row indices that the selection covers.



83
84
85
# File 'lib/xls/selection.rb', line 83

def rows
  @rows
end

Class Method Details

.col_to_index(letters) ⇒ Object

Converts column letters to integer indices.



55
56
57
58
59
60
61
# File 'lib/xls/selection.rb', line 55

def self.col_to_index(letters)
  value = 0
  letters.upcase.split('').each_with_index do |letter, index|
    value = value + ((letter.ord - "A".ord) * (26 ** index))
  end
  return value
end

.parse(str) ⇒ Selection

Parses an Excel style [COLUMN]:[COLUMN] format into a selection.

Parameters:

  • str (String)

    The Excel-style selection.

Returns:

Raises:



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
# File 'lib/xls/selection.rb', line 24

def self.parse(str)
  m, tl_col, tl_row, br_col, br_row = *str.to_s.match(/^([A-Z]+)?(\d+)?(?::([A-Z]+)?(\d+)?)?$/)
  raise SelectionFormatError.new("Invalid selection: #{str}") if m.nil?
  
  # Default bottom-right for single cell selection.
  br_col = tl_col if br_col.nil?
  br_row = tl_row if br_row.nil?
  
  # Convert column letters to numbers.
  columns = nil
  if !tl_col.nil? && !br_col.nil?
    tl_col = col_to_index(tl_col)
    br_col = col_to_index(br_col)
    tl_col, br_col = [tl_col, br_col].min, [tl_col, br_col].max
    columns = (tl_col..br_col)
  end
  
  # Convert rows to zero-based indices.
  rows = nil
  if !tl_row.nil? && !br_row.nil?
    tl_row = tl_row.to_i - 1
    br_row = br_row.to_i - 1
    tl_row, br_row = [tl_row, br_row].min, [tl_row, br_row].max
    rows = (tl_row..br_row)
  end
  
  # Return a selection object.
  return Xls::Selection.new(columns, rows)
end

Instance Method Details

#indicesObject

An array of indicies (top-level column, top-left row, bottom-right column, bottom-right row).



90
91
92
93
94
95
96
97
# File 'lib/xls/selection.rb', line 90

def indices
  return [
    columns.nil? ? nil : columns.begin,
    rows.nil? ? nil : rows.begin,
    columns.nil? ? nil : columns.end,
    rows.nil? ? nil : rows.end
  ]
end