summaryrefslogtreecommitdiffhomepage
path: root/lib/axlsx/workbook/worksheet/pivot_table_cache_definition.rb
blob: 3a6053e9f61294f7ea0b79806bc4b0eb9e34285b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

module Axlsx
  # Table
  # @note Worksheet#add_pivot_table is the recommended way to create tables for your worksheets.
  # @see README for examples
  class PivotTableCacheDefinition
    include Axlsx::OptionsParser

    # Creates a new PivotTable object
    # @param [String] pivot_table The pivot table this cache definition is in
    def initialize(pivot_table)
      @pivot_table = pivot_table
    end

    # # The reference to the pivot table data
    # # @return [PivotTable]
    attr_reader :pivot_table

    # The index of this chart in the workbooks charts collection
    # @return [Integer]
    def index
      pivot_table.sheet.workbook.pivot_tables.index(pivot_table)
    end

    # The part name for this table
    # @return [String]
    def pn
      format(PIVOT_TABLE_CACHE_DEFINITION_PN, index + 1)
    end

    # The identifier for this cache
    # @return [Integer]
    def cache_id
      index + 1
    end

    # The relationship id for this pivot table cache definition.
    # @see Relationship#Id
    # @return [String]
    def rId
      pivot_table.relationships.for(self).Id
    end

    # Serializes the object
    # @param [String] str
    # @return [String]
    def to_xml_string(str = +'')
      str << '<?xml version="1.0" encoding="UTF-8"?>'
      str << '<pivotCacheDefinition xmlns="' << XML_NS << '" xmlns:r="' << XML_NS_R << '" invalid="1" refreshOnLoad="1" recordCount="0">'
      str << '<cacheSource type="worksheet">'
      str << '<worksheetSource ref="' << pivot_table.range << '" sheet="' << pivot_table.data_sheet.name << '"/>'
      str << '</cacheSource>'
      str << '<cacheFields count="' << pivot_table.header_cells_count.to_s << '">'
      pivot_table.header_cells.each do |cell|
        str << '<cacheField name="' << cell.clean_value << '" numFmtId="0">'
        str <<     '<sharedItems count="0">'
        str <<     '</sharedItems>'
        str << '</cacheField>'
      end
      str << '</cacheFields>'
      str << '</pivotCacheDefinition>'
    end
  end
end