Method: Xls::Selection.parse

Defined in:
lib/xls/selection.rb

.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