Class: Axlsx::SortState

Inherits:
Object
  • Object
show all
Defined in:
lib/axlsx/workbook/worksheet/auto_filter/sort_state.rb

Overview

This class performs sorting on a range in a worksheet

Instance Method Summary collapse

Constructor Details

#initialize(auto_filter) ⇒ SortState

creates a new SortState object

Parameters:

  • auto_filter (AutoFilter)

    the auto_filter that this sort_state belongs to



10
11
12
# File 'lib/axlsx/workbook/worksheet/auto_filter/sort_state.rb', line 10

def initialize(auto_filter)
  @auto_filter = auto_filter
end

Instance Method Details

#add_sort_condition(column_index:, order: :asc, custom_list: []) ⇒ SortCondition

Adds a SortCondition to the sort_state. This is the recommended way to add conditions to it. It requires a column_index for the sorting, descending and the custom order are optional.

Parameters:

  • column_index (Integer)

    Zero-based index indicating the AutoFilter column to which the sorting should be applied to

  • order (Symbol) (defaults to: :asc)

    The order the column should be sorted on, can only be :asc or :desc

  • custom_list (Array) (defaults to: [])

    An array containing a custom sorting list in order.

Returns:



26
27
28
29
# File 'lib/axlsx/workbook/worksheet/auto_filter/sort_state.rb', line 26

def add_sort_condition(column_index:, order: :asc, custom_list: [])
  sort_conditions << SortCondition.new(column_index: column_index, order: order, custom_list: custom_list)
  sort_conditions.last
end

#increment_cell_value(str) ⇒ Object

method to increment the String representing the first cell of the range of the autofilter by 1 row for the sortCondition xml string



33
34
35
36
37
38
39
40
# File 'lib/axlsx/workbook/worksheet/auto_filter/sort_state.rb', line 33

def increment_cell_value(str)
  letter = str[/[A-Za-z]+/]
  number = str[/\d+/].to_i

  incremented_number = number + 1

  "#{letter}#{incremented_number}"
end

#sort_conditionsSimpleTypedList

A collection of SortConditions for this sort_state

Returns:

  • (SimpleTypedList)


16
17
18
# File 'lib/axlsx/workbook/worksheet/auto_filter/sort_state.rb', line 16

def sort_conditions
  @sort_conditions ||= SimpleTypedList.new SortCondition
end

#to_xml_string(str = +'')) ⇒ String

serialize the object

Returns:

  • (String)


44
45
46
47
48
49
50
51
52
53
54
# File 'lib/axlsx/workbook/worksheet/auto_filter/sort_state.rb', line 44

def to_xml_string(str = +'')
  return if sort_conditions.empty?

  ref = @auto_filter.range
  first_cell, last_cell = ref.split(':')
  ref = "#{increment_cell_value(first_cell)}:#{last_cell}"

  str << "<sortState xmlns:xlrd2='http://schemas.microsoft.com/office/spreadsheetml/2017/richdata2' ref='#{ref}'>"
  sort_conditions.each { |sort_condition| sort_condition.to_xml_string(str, ref) }
  str << "</sortState>"
end