xlsxrb 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +43 -0
  3. data/lib/xlsxrb/elements/cell.rb +1 -1
  4. data/lib/xlsxrb/elements/workbook.rb +115 -4
  5. data/lib/xlsxrb/number_formatter.rb +5 -5
  6. data/lib/xlsxrb/ooxml/cfb.rb +61 -25
  7. data/lib/xlsxrb/ooxml/crypto/agile.rb +41 -12
  8. data/lib/xlsxrb/ooxml/reader/listeners/core_listeners.rb +4 -0
  9. data/lib/xlsxrb/ooxml/reader/listeners/feature_listeners.rb +2 -0
  10. data/lib/xlsxrb/ooxml/shared_strings_parser.rb +4 -2
  11. data/lib/xlsxrb/ooxml/utils.rb +4 -3
  12. data/lib/xlsxrb/ooxml/workbook_parser.rb +88 -40
  13. data/lib/xlsxrb/ooxml/workbook_writer.rb +48 -24
  14. data/lib/xlsxrb/ooxml/worksheet_parser.rb +186 -78
  15. data/lib/xlsxrb/ooxml/worksheet_writer.rb +81 -18
  16. data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +1511 -1458
  17. data/lib/xlsxrb/ooxml/writer/features_xml.rb +558 -525
  18. data/lib/xlsxrb/ooxml/writer/styles_xml.rb +272 -280
  19. data/lib/xlsxrb/ooxml/writer.rb +1017 -941
  20. data/lib/xlsxrb/ooxml/xml_builder.rb +48 -16
  21. data/lib/xlsxrb/ooxml/xml_parser.rb +37 -2
  22. data/lib/xlsxrb/ooxml/zip_generator.rb +10 -10
  23. data/lib/xlsxrb/ooxml/zip_reader.rb +19 -6
  24. data/lib/xlsxrb/ooxml/zip_writer.rb +15 -7
  25. data/lib/xlsxrb/stream_row.rb +8 -5
  26. data/lib/xlsxrb/stream_sheet.rb +3 -0
  27. data/lib/xlsxrb/stream_writer.rb +48 -18
  28. data/lib/xlsxrb/style_builder.rb +9 -4
  29. data/lib/xlsxrb/version.rb +1 -1
  30. data/lib/xlsxrb/workbook_builder.rb +14 -8
  31. data/lib/xlsxrb/worksheet_builder.rb +10 -4
  32. data/lib/xlsxrb.rb +415 -418
  33. data/sig/generated/xlsxrb/elements/workbook.rbs +23 -1
  34. data/sig/generated/xlsxrb/ooxml/reader/listeners/core_listeners.rbs +2 -0
  35. data/sig/generated/xlsxrb/ooxml/workbook_parser.rbs +21 -1
  36. data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +20 -2
  37. data/sig/generated/xlsxrb/ooxml/writer/drawing_xml.rbs +162 -47
  38. data/sig/generated/xlsxrb/ooxml/writer/features_xml.rbs +20 -24
  39. data/sig/generated/xlsxrb/ooxml/writer/styles_xml.rbs +20 -20
  40. data/sig/generated/xlsxrb/ooxml/writer.rbs +61 -10
  41. data/sig/generated/xlsxrb/ooxml/xml_builder.rbs +19 -1
  42. data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +21 -0
  43. data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +5 -0
  44. data/sig/generated/xlsxrb/stream_row.rbs +4 -3
  45. data/sig/generated/xlsxrb/style_builder.rbs +5 -5
  46. data/sig/generated/xlsxrb.rbs +41 -20
  47. metadata +1 -1
@@ -10,59 +10,60 @@ module Xlsxrb
10
10
  # : (untyped pivot_table, untyped cache_id) -> untyped
11
11
  def generate_pivot_table_xml(pivot_table, cache_id)
12
12
  data_caption = pivot_table[:data_caption] || (pivot_table[:data_fields].first ? pivot_table[:data_fields].first[:name] : "Values")
13
- pt_attrs = %( xmlns="#{SSML_NS}" name="#{xml_escape(pivot_table[:name])}" cacheId="#{xml_escape(cache_id)}" dataCaption="#{xml_escape(data_caption)}")
14
- pt_attrs << %( grandTotalCaption="#{xml_escape(pivot_table[:grand_total_caption])}") if pivot_table[:grand_total_caption]
15
- pt_attrs << %( errorCaption="#{xml_escape(pivot_table[:error_caption])}") if pivot_table[:error_caption]
16
- pt_attrs << ' showError="1"' if pivot_table[:show_error]
17
- pt_attrs << %( missingCaption="#{xml_escape(pivot_table[:missing_caption])}") if pivot_table[:missing_caption]
18
- pt_attrs << ' showMissing="0"' if pivot_table[:show_missing] == false
19
- pt_attrs << %( tag="#{xml_escape(pivot_table[:tag])}") if pivot_table[:tag]
20
- pt_attrs << %( dataOnRows="1") if pivot_table[:data_on_rows]
21
- pt_attrs << %( dataOnRows="0") unless pivot_table[:data_on_rows]
22
- pt_attrs << %( rowGrandTotals="0") if pivot_table[:row_grand_totals] == false
23
- pt_attrs << %( colGrandTotals="0") if pivot_table[:col_grand_totals] == false
24
- pt_attrs << %( compact="0") if pivot_table[:compact] == false
25
- pt_attrs << %( outline="0") if pivot_table[:outline] == false
26
- pt_attrs << %( outlineData="1") if pivot_table[:outline_data]
27
- pt_attrs << %( compactData="0") if pivot_table[:compact_data] == false
28
- pt_attrs << %( showHeaders="0") if pivot_table[:show_headers] == false
29
- pt_attrs << %( showMultipleLabel="0") if pivot_table[:show_multiple_label] == false
30
- pt_attrs << %( showDataDropDown="0") if pivot_table[:show_data_drop_down] == false
31
- pt_attrs << %( indent="#{xml_escape(pivot_table[:indent])}") if pivot_table[:indent]
32
- pt_attrs << ' published="1"' if pivot_table[:published]
33
- pt_attrs << ' editData="1"' if pivot_table[:edit_data]
34
- pt_attrs << ' disableFieldList="1"' if pivot_table[:disable_field_list]
35
- pt_attrs << ' visualTotals="0"' if pivot_table[:visual_totals] == false
36
- pt_attrs << ' printDrill="1"' if pivot_table[:print_drill]
37
- pt_attrs << %( createdVersion="#{xml_escape(pivot_table[:created_version])}") if pivot_table[:created_version]
38
- pt_attrs << %( updatedVersion="#{xml_escape(pivot_table[:updated_version])}") if pivot_table[:updated_version]
39
- pt_attrs << %( minRefreshableVersion="#{xml_escape(pivot_table[:min_refreshable_version])}") if pivot_table[:min_refreshable_version]
40
13
  anf = pivot_table.fetch(:apply_number_formats, false)
41
14
  abf = pivot_table.fetch(:apply_border_formats, false)
42
15
  aff = pivot_table.fetch(:apply_font_formats, false)
43
16
  apf = pivot_table.fetch(:apply_pattern_formats, false)
44
17
  aaf = pivot_table.fetch(:apply_alignment_formats, false)
45
18
  awf = pivot_table.fetch(:apply_width_height_formats, true)
46
- pt_attrs << %( applyNumberFormats="#{anf ? 1 : 0}")
47
- pt_attrs << %( applyBorderFormats="#{abf ? 1 : 0}")
48
- pt_attrs << %( applyFontFormats="#{aff ? 1 : 0}")
49
- pt_attrs << %( applyPatternFormats="#{apf ? 1 : 0}")
50
- pt_attrs << %( applyAlignmentFormats="#{aaf ? 1 : 0}")
51
- pt_attrs << %( applyWidthHeightFormats="#{awf ? 1 : 0}")
52
- pt_attrs << ' multipleFieldFilters="0"' if pivot_table[:multiple_field_filters] == false
53
- pt_attrs << ' showDrill="0"' if pivot_table[:show_drill] == false
54
- pt_attrs << ' showDataTips="0"' if pivot_table[:show_data_tips] == false
55
- pt_attrs << ' enableDrill="0"' if pivot_table[:enable_drill] == false
56
- pt_attrs << ' showMemberPropertyTips="0"' if pivot_table[:show_member_property_tips] == false
57
- pt_attrs << ' itemPrintTitles="1"' if pivot_table[:item_print_titles]
58
- pt_attrs << ' fieldPrintTitles="1"' if pivot_table[:field_print_titles]
59
- pt_attrs << ' preserveFormatting="0"' if pivot_table[:preserve_formatting] == false
60
- pt_attrs << ' pageOverThenDown="1"' if pivot_table[:page_over_then_down]
61
- pt_attrs << %( pageWrap="#{xml_escape(pivot_table[:page_wrap])}") if pivot_table[:page_wrap]
62
- parts = [
63
- XML_HEADER,
64
- "<pivotTableDefinition#{pt_attrs}>"
65
- ]
19
+
20
+ pt_attrs = {
21
+ xmlns: SSML_NS,
22
+ name: pivot_table[:name] || "",
23
+ cacheId: cache_id || "",
24
+ dataCaption: data_caption || "",
25
+ grandTotalCaption: pivot_table[:grand_total_caption],
26
+ errorCaption: pivot_table[:error_caption],
27
+ showError: pivot_table[:show_error] ? 1 : nil,
28
+ missingCaption: pivot_table[:missing_caption],
29
+ showMissing: pivot_table[:show_missing] == false ? 0 : nil,
30
+ tag: pivot_table[:tag],
31
+ dataOnRows: pivot_table[:data_on_rows] ? 1 : 0,
32
+ rowGrandTotals: pivot_table[:row_grand_totals] == false ? 0 : nil,
33
+ colGrandTotals: pivot_table[:col_grand_totals] == false ? 0 : nil,
34
+ compact: pivot_table[:compact] == false ? 0 : nil,
35
+ outline: pivot_table[:outline] == false ? 0 : nil,
36
+ outlineData: pivot_table[:outline_data] ? 1 : nil,
37
+ compactData: pivot_table[:compact_data] == false ? 0 : nil,
38
+ showHeaders: pivot_table[:show_headers] == false ? 0 : nil,
39
+ showMultipleLabel: pivot_table[:show_multiple_label] == false ? 0 : nil,
40
+ showDataDropDown: pivot_table[:show_data_drop_down] == false ? 0 : nil,
41
+ indent: pivot_table[:indent],
42
+ published: pivot_table[:published] ? 1 : nil,
43
+ editData: pivot_table[:edit_data] ? 1 : nil,
44
+ disableFieldList: pivot_table[:disable_field_list] ? 1 : nil,
45
+ visualTotals: pivot_table[:visual_totals] == false ? 0 : nil,
46
+ printDrill: pivot_table[:print_drill] ? 1 : nil,
47
+ createdVersion: pivot_table[:created_version],
48
+ updatedVersion: pivot_table[:updated_version],
49
+ minRefreshableVersion: pivot_table[:min_refreshable_version],
50
+ applyNumberFormats: anf ? 1 : 0,
51
+ applyBorderFormats: abf ? 1 : 0,
52
+ applyFontFormats: aff ? 1 : 0,
53
+ applyPatternFormats: apf ? 1 : 0,
54
+ applyAlignmentFormats: aaf ? 1 : 0,
55
+ applyWidthHeightFormats: awf ? 1 : 0,
56
+ multipleFieldFilters: pivot_table[:multiple_field_filters] == false ? 0 : nil,
57
+ showDrill: pivot_table[:show_drill] == false ? 0 : nil,
58
+ showDataTips: pivot_table[:show_data_tips] == false ? 0 : nil,
59
+ enableDrill: pivot_table[:enable_drill] == false ? 0 : nil,
60
+ showMemberPropertyTips: pivot_table[:show_member_property_tips] == false ? 0 : nil,
61
+ itemPrintTitles: pivot_table[:item_print_titles] ? 1 : nil,
62
+ fieldPrintTitles: pivot_table[:field_print_titles] ? 1 : nil,
63
+ preserveFormatting: pivot_table[:preserve_formatting] == false ? 0 : nil,
64
+ pageOverThenDown: pivot_table[:page_over_then_down] ? 1 : nil,
65
+ pageWrap: pivot_table[:page_wrap]
66
+ }
66
67
 
67
68
  # Compute field count from source range or explicit field_names.
68
69
  field_count = if pivot_table[:field_names]
@@ -70,251 +71,272 @@ module Xlsxrb
70
71
  else
71
72
  (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size).clamp(1, 100)
72
73
  end
73
- loc_attrs = %(<location ref="#{xml_escape(pivot_table[:dest_ref])}" firstHeaderRow="#{xml_escape(pivot_table[:first_header_row] || 1)}" ) +
74
- %(firstDataRow="#{xml_escape(pivot_table[:first_data_row] || 1)}" firstDataCol="#{xml_escape(pivot_table[:first_data_col] || 1)}")
75
- loc_attrs << %( rowPageCount="#{xml_escape(pivot_table[:row_page_count])}") if pivot_table[:row_page_count]
76
- loc_attrs << %( colPageCount="#{xml_escape(pivot_table[:col_page_count])}") if pivot_table[:col_page_count]
77
- loc_attrs << "/>"
78
- parts << loc_attrs
79
- parts << %(<pivotFields count="#{xml_escape(field_count)}">)
80
- field_count.times do |fi|
81
- attrs = +""
82
- if pivot_table[:row_fields].include?(fi)
83
- attrs << ' axis="axisRow"'
84
- elsif pivot_table[:col_fields].include?(fi)
85
- attrs << ' axis="axisCol"'
86
- end
87
- attrs << ' dataField="1"' if pivot_table[:data_fields].any? { |df| df[:fld] == fi }
88
- fa = pivot_table[:field_attrs] && pivot_table[:field_attrs][fi]
89
- attrs << %( compact="#{fa[:compact] ? "1" : "0"}") if fa && !fa[:compact].nil?
90
- attrs << %( outline="#{fa[:outline] ? "1" : "0"}") if fa && !fa[:outline].nil?
91
- attrs << %( subtotalTop="#{fa[:subtotal_top] ? "1" : "0"}") if fa && !fa[:subtotal_top].nil?
92
- attrs << %( showAll="#{fa && fa[:show_all] == true ? "1" : "0"}")
93
- attrs << %( numFmtId="#{xml_escape(fa[:num_fmt_id])}") if fa && fa[:num_fmt_id]
94
- attrs << %( sortType="#{xml_escape(fa[:sort_type])}") if fa && fa[:sort_type]
95
- attrs << ' defaultSubtotal="0"' if fa && fa[:default_subtotal] == false
96
- attrs << ' insertBlankRow="1"' if fa && fa[:insert_blank_row]
97
- attrs << ' insertPageBreak="1"' if fa && fa[:insert_page_break]
98
- attrs << ' includeNewItemsInFilter="1"' if fa && fa[:include_new_items_in_filter]
99
-
100
- field_items = pivot_table[:items] && pivot_table[:items][fi]
101
- axis_field = pivot_table[:row_fields].include?(fi) || pivot_table[:col_fields].include?(fi)
102
- # The default subtotal item goes with the default subtotal; a field with
103
- # defaultSubtotal="0" must not list it.
104
- default_subtotal = !(fa && fa[:default_subtotal] == false)
105
- if field_items || (axis_field && default_subtotal)
106
- # A row or column field needs an <items> list; without known items it holds only the
107
- # default subtotal, which Excel fills in when it refreshes the cache on open.
108
- field_items ||= []
109
- parts << "<pivotField#{attrs}>"
110
- parts << %(<items count="#{xml_escape(field_items.size + (default_subtotal ? 1 : 0))}">)
111
- field_items.size.times { |ix| parts << %(<item x="#{xml_escape(ix)}"/>) }
112
- parts << '<item t="default"/>' if default_subtotal
113
- parts << "</items>"
114
- parts << "</pivotField>"
115
- else
116
- parts << "<pivotField#{attrs}/>"
117
- end
118
- end
119
- parts << "</pivotFields>"
120
74
 
121
- unless pivot_table[:row_fields].empty?
122
- parts << %(<rowFields count="#{pivot_table[:row_fields].size}">)
123
- pivot_table[:row_fields].each { |f| parts << %(<field x="#{xml_escape(f)}"/>) }
124
- parts << "</rowFields>"
125
- end
75
+ XmlBuilder.build(declaration: :plain) do |xml|
76
+ xml.tag("pivotTableDefinition", pt_attrs) do
77
+ xml.empty_tag("location", {
78
+ ref: pivot_table[:dest_ref] || "",
79
+ firstHeaderRow: pivot_table[:first_header_row] || 1,
80
+ firstDataRow: pivot_table[:first_data_row] || 1,
81
+ firstDataCol: pivot_table[:first_data_col] || 1,
82
+ rowPageCount: pivot_table[:row_page_count],
83
+ colPageCount: pivot_table[:col_page_count]
84
+ })
85
+ xml.tag("pivotFields", { count: field_count }) do
86
+ field_count.times do |fi|
87
+ axis_val = if pivot_table[:row_fields].include?(fi)
88
+ "axisRow"
89
+ elsif pivot_table[:col_fields].include?(fi)
90
+ "axisCol"
91
+ end
92
+ fa = pivot_table[:field_attrs] && pivot_table[:field_attrs][fi]
93
+ pf_attrs = {
94
+ axis: axis_val,
95
+ dataField: pivot_table[:data_fields].any? { |df| df[:fld] == fi } ? 1 : nil,
96
+ compact: xml_bool_attr(fa&.[](:compact)),
97
+ outline: xml_bool_attr(fa&.[](:outline)),
98
+ subtotalTop: xml_bool_attr(fa&.[](:subtotal_top)),
99
+ showAll: fa && fa[:show_all] == true ? "1" : "0",
100
+ numFmtId: fa && fa[:num_fmt_id] ? fa[:num_fmt_id] : nil,
101
+ sortType: fa && fa[:sort_type] ? fa[:sort_type] : nil,
102
+ defaultSubtotal: fa && fa[:default_subtotal] == false ? 0 : nil,
103
+ insertBlankRow: fa && fa[:insert_blank_row] ? 1 : nil,
104
+ insertPageBreak: fa && fa[:insert_page_break] ? 1 : nil,
105
+ includeNewItemsInFilter: fa && fa[:include_new_items_in_filter] ? 1 : nil
106
+ }
107
+ field_items = pivot_table[:items] && pivot_table[:items][fi]
108
+ axis_field = pivot_table[:row_fields].include?(fi) || pivot_table[:col_fields].include?(fi)
109
+ # The default subtotal item goes with the default subtotal; a field with
110
+ # defaultSubtotal="0" must not list it.
111
+ default_subtotal = !(fa && fa[:default_subtotal] == false)
112
+ if field_items || (axis_field && default_subtotal)
113
+ # A row or column field needs an <items> list; without known items it holds only the
114
+ # default subtotal, which Excel fills in when it refreshes the cache on open.
115
+ field_items ||= []
116
+ xml.tag("pivotField", pf_attrs) do
117
+ xml.tag("items", { count: field_items.size + (default_subtotal ? 1 : 0) }) do
118
+ field_items.size.times { |ix| xml.empty_tag("item", { x: ix }) }
119
+ xml.empty_tag("item", { t: "default" }) if default_subtotal
120
+ end
121
+ end
122
+ else
123
+ xml.empty_tag("pivotField", pf_attrs)
124
+ end
125
+ end
126
+ end
126
127
 
127
- unless pivot_table[:col_fields].empty?
128
- parts << %(<colFields count="#{pivot_table[:col_fields].size}">)
129
- pivot_table[:col_fields].each { |f| parts << %(<field x="#{xml_escape(f)}"/>) }
130
- parts << "</colFields>"
131
- end
128
+ unless pivot_table[:row_fields].empty?
129
+ xml.tag("rowFields", { count: pivot_table[:row_fields].size }) do
130
+ pivot_table[:row_fields].each { |f| xml.empty_tag("field", { x: f || "" }) }
131
+ end
132
+ end
132
133
 
133
- unless pivot_table[:data_fields].empty?
134
- parts << %(<dataFields count="#{pivot_table[:data_fields].size}">)
135
- pivot_table[:data_fields].each do |df|
136
- df_attrs = %( name="#{xml_escape(df[:name])}" fld="#{xml_escape(df[:fld])}" subtotal="#{xml_escape(df[:subtotal] || "sum")}")
137
- df_attrs << %( showDataAs="#{xml_escape(df[:show_data_as])}") if df[:show_data_as]
138
- df_attrs << %( baseField="#{xml_escape(df[:base_field])}") if df[:base_field]
139
- df_attrs << %( baseItem="#{xml_escape(df[:base_item])}") if df[:base_item]
140
- df_attrs << %( numFmtId="#{xml_escape(df[:num_fmt_id])}") if df[:num_fmt_id]
141
- parts << "<dataField#{df_attrs}/>"
142
- end
143
- parts << "</dataFields>"
144
- end
134
+ unless pivot_table[:col_fields].empty?
135
+ xml.tag("colFields", { count: pivot_table[:col_fields].size }) do
136
+ pivot_table[:col_fields].each { |f| xml.empty_tag("field", { x: f || "" }) }
137
+ end
138
+ end
145
139
 
146
- if pivot_table[:pivot_table_style]
147
- psi = pivot_table[:pivot_table_style]
148
- psi_attrs = +""
149
- psi_attrs << %( name="#{xml_escape(psi[:name])}") if psi[:name]
150
- psi_attrs << %( showRowHeaders="#{psi[:show_row_headers] ? "1" : "0"}") unless psi[:show_row_headers].nil?
151
- psi_attrs << %( showColHeaders="#{psi[:show_col_headers] ? "1" : "0"}") unless psi[:show_col_headers].nil?
152
- psi_attrs << %( showRowStripes="#{psi[:show_row_stripes] ? "1" : "0"}") unless psi[:show_row_stripes].nil?
153
- psi_attrs << %( showColStripes="#{psi[:show_col_stripes] ? "1" : "0"}") unless psi[:show_col_stripes].nil?
154
- psi_attrs << %( showLastColumn="#{psi[:show_last_column] ? "1" : "0"}") unless psi[:show_last_column].nil?
155
- parts << "<pivotTableStyleInfo#{psi_attrs}/>"
156
- end
140
+ unless pivot_table[:data_fields].empty?
141
+ xml.tag("dataFields", { count: pivot_table[:data_fields].size }) do
142
+ pivot_table[:data_fields].each do |df|
143
+ xml.empty_tag("dataField", {
144
+ name: df[:name] || "",
145
+ fld: df[:fld] || "",
146
+ subtotal: df[:subtotal] || "sum",
147
+ showDataAs: df[:show_data_as],
148
+ baseField: df[:base_field],
149
+ baseItem: df[:base_item],
150
+ numFmtId: df[:num_fmt_id]
151
+ })
152
+ end
153
+ end
154
+ end
157
155
 
158
- parts << "</pivotTableDefinition>"
159
- parts.join
156
+ if (psi = pivot_table[:pivot_table_style])
157
+ xml.empty_tag("pivotTableStyleInfo", {
158
+ name: psi[:name],
159
+ showRowHeaders: xml_bool_attr(psi[:show_row_headers]),
160
+ showColHeaders: xml_bool_attr(psi[:show_col_headers]),
161
+ showRowStripes: xml_bool_attr(psi[:show_row_stripes]),
162
+ showColStripes: xml_bool_attr(psi[:show_col_stripes]),
163
+ showLastColumn: xml_bool_attr(psi[:show_last_column])
164
+ })
165
+ end
166
+ end
167
+ end
160
168
  end
161
169
 
162
170
  # : (untyped pivot_table, untyped _cache_id) -> untyped
163
171
  def generate_pivot_cache_definition_xml(pivot_table, _cache_id)
164
- pcd_attrs = %( xmlns="#{SSML_NS}" xmlns:r="#{DOC_REL_NS}" r:id="rId1" refreshOnLoad="1")
165
- pcd_attrs << ' saveData="0"' if pivot_table[:cache_save_data] == false
166
- pcd_attrs << ' enableRefresh="0"' if pivot_table[:cache_enable_refresh] == false
167
- pcd_attrs << %( refreshedBy="#{xml_escape(pivot_table[:cache_refreshed_by])}") if pivot_table[:cache_refreshed_by]
168
- pcd_attrs << %( refreshedVersion="#{xml_escape(pivot_table[:cache_refreshed_version])}") if pivot_table[:cache_refreshed_version]
169
- pcd_attrs << %( createdVersion="#{xml_escape(pivot_table[:cache_created_version])}") if pivot_table[:cache_created_version]
170
- pcd_attrs << %( recordCount="#{xml_escape(pivot_table[:cache_record_count])}") if pivot_table[:cache_record_count]
171
- pcd_attrs << ' optimizeMemory="1"' if pivot_table[:cache_optimize_memory]
172
- parts = [
173
- XML_HEADER,
174
- "<pivotCacheDefinition#{pcd_attrs}>"
175
- ]
176
-
177
- # Parse source ref: "Sheet1!A1:C4" => sheet name + range.
178
- source = pivot_table[:source_ref]
179
- ws_name_attr = pivot_table[:source_name] ? %( name="#{xml_escape(pivot_table[:source_name])}") : ""
180
- if source.nil?
181
- parts << %(<cacheSource type="worksheet"><worksheetSource#{ws_name_attr}/></cacheSource>)
182
- elsif source.include?("!")
183
- sname, srange = source.split("!", 2)
184
- sname = sname.delete("'")
185
- parts << %(<cacheSource type="worksheet"><worksheetSource ref="#{xml_escape(srange)}" sheet="#{xml_escape(sname)}"#{ws_name_attr}/></cacheSource>)
186
- else
187
- parts << %(<cacheSource type="worksheet"><worksheetSource ref="#{xml_escape(source)}"#{ws_name_attr}/></cacheSource>)
188
- end
172
+ pcd_attrs = {
173
+ xmlns: SSML_NS,
174
+ "xmlns:r": DOC_REL_NS,
175
+ "r:id": "rId1",
176
+ refreshOnLoad: 1,
177
+ saveData: pivot_table[:cache_save_data] == false ? 0 : nil,
178
+ enableRefresh: pivot_table[:cache_enable_refresh] == false ? 0 : nil,
179
+ refreshedBy: pivot_table[:cache_refreshed_by],
180
+ refreshedVersion: pivot_table[:cache_refreshed_version],
181
+ createdVersion: pivot_table[:cache_created_version],
182
+ recordCount: pivot_table[:cache_record_count],
183
+ optimizeMemory: pivot_table[:cache_optimize_memory] ? 1 : nil
184
+ }
185
+
186
+ XmlBuilder.build(declaration: :plain) do |xml|
187
+ xml.tag("pivotCacheDefinition", pcd_attrs) do
188
+ # Parse source ref: "Sheet1!A1:C4" => sheet name + range.
189
+ source = pivot_table[:source_ref]
190
+ ws_attrs = {}
191
+ if source&.include?("!")
192
+ sname, srange = source.split("!", 2)
193
+ ws_attrs[:ref] = srange
194
+ ws_attrs[:sheet] = sname.delete("'")
195
+ elsif !source.nil?
196
+ ws_attrs[:ref] = source
197
+ end
198
+ ws_attrs[:name] = pivot_table[:source_name] if pivot_table[:source_name]
199
+ xml.tag("cacheSource", { type: "worksheet" }) do
200
+ xml.empty_tag("worksheetSource", ws_attrs)
201
+ end
189
202
 
190
- field_count = pivot_table[:field_names] ? pivot_table[:field_names].size : (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size)
191
- parts << %(<cacheFields count="#{xml_escape(field_count)}">)
192
- field_count.times do |fi|
193
- fname = if pivot_table[:field_names] && pivot_table[:field_names][fi]
194
- pivot_table[:field_names][fi]
203
+ field_count = pivot_table[:field_names] ? pivot_table[:field_names].size : (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size)
204
+ xml.tag("cacheFields", { count: field_count }) do
205
+ field_count.times do |fi|
206
+ fname = if pivot_table[:field_names] && pivot_table[:field_names][fi]
207
+ pivot_table[:field_names][fi]
208
+ else
209
+ df = pivot_table[:data_fields].find { |d| d[:fld] == fi }
210
+ df ? df[:name] : "Field#{fi + 1}"
211
+ end
212
+ fa = pivot_table[:field_attrs] && pivot_table[:field_attrs][fi]
213
+ cf_attrs = {
214
+ name: fname || "",
215
+ numFmtId: (fa && fa[:cache_num_fmt_id]) || 0,
216
+ caption: fa && fa[:cache_caption] ? fa[:cache_caption] : nil,
217
+ formula: fa && fa[:cache_formula] ? fa[:cache_formula] : nil
218
+ }
219
+ field_items = pivot_table[:items] && pivot_table[:items][fi]
220
+ xml.tag("cacheField", cf_attrs) do
221
+ if field_items
222
+ write_shared_items_xml(xml, field_items)
195
223
  else
196
- df = pivot_table[:data_fields].find { |d| d[:fld] == fi }
197
- df ? df[:name] : "Field#{fi + 1}"
224
+ xml.empty_tag("sharedItems")
198
225
  end
199
- fa = pivot_table[:field_attrs] && pivot_table[:field_attrs][fi]
200
- cf_num_fmt = (fa && fa[:cache_num_fmt_id]) || 0
201
- cf_attrs = %( name="#{xml_escape(fname)}" numFmtId="#{xml_escape(cf_num_fmt)}")
202
- cf_attrs << %( caption="#{xml_escape(fa[:cache_caption])}") if fa && fa[:cache_caption]
203
- cf_attrs << %( formula="#{xml_escape(fa[:cache_formula])}") if fa && fa[:cache_formula]
204
- field_items = pivot_table[:items] && pivot_table[:items][fi]
205
- if field_items
206
- parts << "<cacheField#{cf_attrs}>"
207
- parts << %(<sharedItems#{shared_items_attrs(field_items)} count="#{field_items.size}">)
208
- field_items.each { |v| parts << shared_item_xml(v) }
209
- parts << "</sharedItems>"
210
- parts << "</cacheField>"
211
- else
212
- parts << "<cacheField#{cf_attrs}><sharedItems/></cacheField>"
226
+ end
227
+ end
228
+ end
213
229
  end
214
230
  end
215
- parts << "</cacheFields>"
216
- parts << "</pivotCacheDefinition>"
217
- parts.join
218
231
  end
219
232
 
220
- # Attributes that describe the value types of a cache field's shared items.
221
- # : (Array[untyped] values) -> String
222
- def shared_items_attrs(values)
233
+ # Writes <sharedItems> and its typed children for a cache field.
234
+ # : (XmlBuilder xml, Array[untyped] values) -> void
235
+ def write_shared_items_xml(xml, values)
223
236
  numbers = values.grep(Numeric)
224
237
  strings = values.any? { |v| !v.nil? && !v.is_a?(Numeric) && v != true && v != false }
225
- attrs = +""
226
- attrs << ' containsSemiMixedTypes="0"' unless strings || values.include?(nil)
227
- attrs << ' containsString="0"' unless strings
228
- attrs << ' containsBlank="1"' if values.include?(nil)
229
- unless numbers.empty?
230
- attrs << ' containsNumber="1"'
231
- attrs << ' containsInteger="1"' if numbers.all? { |n| n.is_a?(Integer) || n == n.to_i }
232
- attrs << %( minValue="#{xml_escape(numbers.min)}" maxValue="#{xml_escape(numbers.max)}")
233
- end
234
- attrs
235
- end
236
-
237
- # : (untyped value) -> String
238
- def shared_item_xml(value)
239
- case value
240
- when nil then "<m/>"
241
- when true, false then %(<b v="#{value ? 1 : 0}"/>)
242
- when Numeric then %(<n v="#{xml_escape(value)}"/>)
243
- else %(<s v="#{xml_escape(value.to_s)}"/>)
238
+ attrs = {
239
+ containsSemiMixedTypes: strings || values.include?(nil) ? nil : 0,
240
+ containsString: strings ? nil : 0,
241
+ containsBlank: values.include?(nil) ? 1 : nil,
242
+ containsNumber: numbers.empty? ? nil : 1,
243
+ containsInteger: !numbers.empty? && numbers.all? { |n| n.is_a?(Integer) || n == n.to_i } ? 1 : nil,
244
+ minValue: numbers.empty? ? nil : numbers.min,
245
+ maxValue: numbers.empty? ? nil : numbers.max,
246
+ count: values.size
247
+ }
248
+ xml.tag("sharedItems", attrs) do
249
+ values.each do |value|
250
+ case value
251
+ when nil then xml.empty_tag("m")
252
+ when true, false then xml.empty_tag("b", { v: value ? 1 : 0 })
253
+ when Numeric then xml.empty_tag("n", { v: value })
254
+ else xml.empty_tag("s", { v: value.to_s })
255
+ end
256
+ end
244
257
  end
245
258
  end
246
259
 
247
260
  # : (untyped pivot_table) -> untyped
248
261
  def generate_pivot_cache_records_xml(pivot_table)
249
262
  items = pivot_table[:items]
250
- if items&.values&.any? { |v| v && !v.empty? }
251
- max_len = items.values.map { |v| v ? v.size : 0 }.max
252
- parts = [XML_HEADER, %(<pivotCacheRecords xmlns="#{SSML_NS}" count="#{xml_escape(max_len)}">)]
253
- max_len.times do |ri|
254
- parts << "<r>"
263
+ XmlBuilder.build(declaration: :plain) do |xml|
264
+ if items&.values&.any? { |v| v && !v.empty? }
265
+ max_len = items.values.map { |v| v ? v.size : 0 }.max
255
266
  field_count = pivot_table[:field_names] ? pivot_table[:field_names].size : (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size)
256
- field_count.times do |fi|
257
- field_items = items[fi]
258
- parts << if field_items
259
- %(<x v="#{xml_escape(ri < field_items.size ? ri : 0)}"/>)
260
- else
261
- %(<n v="0"/>)
262
- end
267
+ xml.tag("pivotCacheRecords", { xmlns: SSML_NS, count: max_len }) do
268
+ max_len.times do |ri|
269
+ xml.tag("r") do
270
+ field_count.times do |fi|
271
+ field_items = items[fi]
272
+ if field_items
273
+ xml.empty_tag("x", { v: ri < field_items.size ? ri : 0 })
274
+ else
275
+ xml.empty_tag("n", { v: 0 })
276
+ end
277
+ end
278
+ end
279
+ end
263
280
  end
264
- parts << "</r>"
281
+ else
282
+ xml.empty_tag("pivotCacheRecords", { xmlns: SSML_NS, count: 0 })
265
283
  end
266
- parts << "</pivotCacheRecords>"
267
- parts.join
268
- else
269
- [XML_HEADER, %(<pivotCacheRecords xmlns="#{SSML_NS}" count="0"/>)].join
270
284
  end
271
285
  end
272
286
 
273
287
  # : (untyped cache_id) -> untyped
274
288
  def generate_pivot_cache_rels(cache_id)
275
- [
276
- XML_HEADER,
277
- %(<Relationships xmlns="#{REL_NS}">),
278
- %(<Relationship Id="rId1" Type="#{DOC_REL_NS}/pivotCacheRecords" Target="pivotCacheRecords#{xml_escape(cache_id)}.xml"/>),
279
- "</Relationships>"
280
- ].join
289
+ XmlBuilder.build(declaration: :plain) do |xml|
290
+ xml.tag("Relationships", { xmlns: REL_NS }) do
291
+ xml.empty_tag("Relationship", {
292
+ Id: "rId1",
293
+ Type: "#{DOC_REL_NS}/pivotCacheRecords",
294
+ Target: "pivotCacheRecords#{cache_id}.xml"
295
+ })
296
+ end
297
+ end
281
298
  end
282
299
 
283
300
  # : (untyped cache_id) -> untyped
284
301
  def generate_pivot_table_rels(cache_id)
285
- [
286
- XML_HEADER,
287
- %(<Relationships xmlns="#{REL_NS}">),
288
- %(<Relationship Id="rId1" Type="#{DOC_REL_NS}/pivotCacheDefinition" Target="../pivotCache/pivotCacheDefinition#{xml_escape(cache_id)}.xml"/>),
289
- "</Relationships>"
290
- ].join
302
+ XmlBuilder.build(declaration: :plain) do |xml|
303
+ xml.tag("Relationships", { xmlns: REL_NS }) do
304
+ xml.empty_tag("Relationship", {
305
+ Id: "rId1",
306
+ Type: "#{DOC_REL_NS}/pivotCacheDefinition",
307
+ Target: "../pivotCache/pivotCacheDefinition#{cache_id}.xml"
308
+ })
309
+ end
310
+ end
291
311
  end
292
312
 
293
313
  # : (untyped ext_link) -> untyped
294
314
  def generate_external_link_xml(ext_link)
295
- parts = [
296
- XML_HEADER,
297
- %(<externalLink xmlns="#{SSML_NS}" xmlns:r="#{DOC_REL_NS}">),
298
- '<externalBook r:id="rId1">'
299
- ]
300
- unless ext_link[:sheet_names].empty?
301
- parts << "<sheetNames>"
302
- ext_link[:sheet_names].each { |sn| parts << %(<sheetName val="#{xml_escape(sn)}"/>) }
303
- parts << "</sheetNames>"
315
+ XmlBuilder.build(declaration: :plain) do |xml|
316
+ xml.tag("externalLink", { xmlns: SSML_NS, "xmlns:r": DOC_REL_NS }) do
317
+ xml.tag("externalBook", { "r:id": "rId1" }) do
318
+ unless ext_link[:sheet_names].empty?
319
+ xml.tag("sheetNames") do
320
+ ext_link[:sheet_names].each { |sn| xml.empty_tag("sheetName", { val: sn || "" }) }
321
+ end
322
+ end
323
+ end
324
+ end
304
325
  end
305
- parts << "</externalBook>"
306
- parts << "</externalLink>"
307
- parts.join
308
326
  end
309
327
 
310
328
  # : (untyped ext_link) -> untyped
311
329
  def generate_external_link_rels(ext_link)
312
- [
313
- XML_HEADER,
314
- %(<Relationships xmlns="#{REL_NS}">),
315
- %(<Relationship Id="rId1" Type="#{DOC_REL_NS}/externalLinkPath" Target="#{xml_escape(ext_link[:target])}" TargetMode="External"/>),
316
- "</Relationships>"
317
- ].join
330
+ XmlBuilder.build(declaration: :plain) do |xml|
331
+ xml.tag("Relationships", { xmlns: REL_NS }) do
332
+ xml.empty_tag("Relationship", {
333
+ Id: "rId1",
334
+ Type: "#{DOC_REL_NS}/externalLinkPath",
335
+ Target: ext_link[:target] || "",
336
+ TargetMode: "External"
337
+ })
338
+ end
339
+ end
318
340
  end
319
341
 
320
342
  # : (untyped ct_xml) -> untyped
@@ -327,149 +349,142 @@ module Xlsxrb
327
349
  end
328
350
  end
329
351
 
330
- # : (untyped element, untyped opts) -> ("" | ::String)
331
- def build_line_end_xml(element, opts)
332
- return "" unless opts
352
+ # : (XmlBuilder xml, untyped element, untyped opts) -> void
353
+ def write_line_end_xml(xml, element, opts)
354
+ return unless opts
333
355
 
334
- attrs = +""
335
- attrs << %( type="#{xml_escape(opts[:type])}") if opts[:type]
336
- attrs << %( w="#{xml_escape(opts[:w])}") if opts[:w]
337
- attrs << %( len="#{xml_escape(opts[:len])}") if opts[:len]
338
- "<a:#{element}#{attrs}/>"
356
+ xml.empty_tag("a:#{element}", {
357
+ type: opts[:type],
358
+ w: opts[:w],
359
+ len: opts[:len]
360
+ })
339
361
  end
340
362
 
341
- # : (untyped value) -> untyped
342
- # Escapes cell text: ST_Xstring (XmlBuilder.encode_xstring), then XML.
343
- def xml_escape_text(value)
344
- str = value.to_s
345
- str = str.dup.force_encoding(Encoding::UTF_8) if str.encoding == Encoding::BINARY
346
- xml_escape(XmlBuilder.encode_xstring(str))
347
- end
348
-
349
- def xml_escape(value)
350
- value.to_s
351
- .gsub(/[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/, "")
352
- .gsub("&", "&amp;")
353
- .gsub("<", "&lt;")
354
- .gsub(">", "&gt;")
355
- .gsub('"', "&quot;")
356
- .gsub("'", "&apos;")
357
- end
358
-
359
- # : (untyped rich_text) -> untyped
360
- def rich_text_xml(rich_text)
361
- rich_text.runs.map do |run|
363
+ # : (XmlBuilder xml, untyped rich_text) -> void
364
+ def write_rich_text_xml(xml, rich_text)
365
+ rich_text.runs.each do |run|
362
366
  font = run.respond_to?(:font) ? run.font : run[:font]
363
367
  text = run.respond_to?(:text) ? run.text : run[:text]
364
- if font && !font.empty?
365
- rpr = +""
366
- rpr << "<b/>" if font[:bold]
367
- rpr << "<i/>" if font[:italic]
368
- rpr << "<strike/>" if font[:strike]
369
- if font[:underline]
370
- u_val = font[:underline]
371
- if u_val == true || u_val.to_s == "single"
372
- rpr << "<u/>"
373
- else
374
- mapped_u = StyleBuilder::UNDERLINE_MAP[u_val.to_sym] || u_val
375
- rpr << %(<u val="#{xml_escape(mapped_u)}"/>)
368
+ xml.tag("r") do
369
+ if font && !font.empty?
370
+ xml.tag("rPr") do
371
+ xml.empty_tag("b") if font[:bold]
372
+ xml.empty_tag("i") if font[:italic]
373
+ xml.empty_tag("strike") if font[:strike]
374
+ if font[:underline]
375
+ u_val = font[:underline]
376
+ if u_val == true || u_val.to_s == "single"
377
+ xml.empty_tag("u")
378
+ else
379
+ mapped_u = StyleBuilder::UNDERLINE_MAP[u_val.to_sym] || u_val
380
+ xml.empty_tag("u", { val: mapped_u })
381
+ end
382
+ end
383
+ va_val = font[:vert_align] || font[:vertical_align]
384
+ va_val ||= "superscript" if font[:superscript]
385
+ va_val ||= "subscript" if font[:subscript]
386
+ if va_val
387
+ mapped_va = StyleBuilder::VERT_ALIGN_MAP[va_val.to_sym] || va_val
388
+ xml.empty_tag("vertAlign", { val: mapped_va })
389
+ end
390
+ font_sz = font[:size] || font[:sz]
391
+ xml.empty_tag("sz", { val: font_sz }) if font_sz
392
+ write_color_xml(xml, font)
393
+ xml.empty_tag("rFont", { val: font[:name] }) if font[:name]
394
+ xml.empty_tag("family", { val: font[:family] }) if font[:family]
395
+ xml.empty_tag("scheme", { val: font[:scheme] }) if font[:scheme]
376
396
  end
377
397
  end
378
- va_val = font[:vert_align] || font[:vertical_align]
379
- va_val ||= "superscript" if font[:superscript]
380
- va_val ||= "subscript" if font[:subscript]
381
- if va_val
382
- mapped_va = StyleBuilder::VERT_ALIGN_MAP[va_val.to_sym] || va_val
383
- rpr << %(<vertAlign val="#{xml_escape(mapped_va)}"/>)
384
- end
385
- font_sz = font[:size] || font[:sz]
386
- rpr << %(<sz val="#{xml_escape(font_sz)}"/>) if font_sz
387
- rpr << emit_color_xml(font)
388
- rpr << %(<rFont val="#{xml_escape(font[:name])}"/>) if font[:name]
389
- rpr << %(<family val="#{xml_escape(font[:family])}"/>) if font[:family]
390
- rpr << %(<scheme val="#{xml_escape(font[:scheme])}"/>) if font[:scheme]
391
- "<r><rPr>#{rpr}</rPr><t>#{xml_escape_text(text)}</t></r>"
392
- else
393
- "<r><t>#{xml_escape_text(text)}</t></r>"
398
+ xml.tag("t") { xml.xstring_text(text) }
394
399
  end
395
- end.join
400
+ end
396
401
  end
397
402
 
398
- # : (untyped cell_ref, untyped value, untyped style_idx, ?untyped? sst, ?ph: untyped?) -> untyped
399
- def cell_xml(cell_ref, value, style_idx, sst = nil, ph: nil) # rubocop:disable Naming/MethodParameterName
400
- s_attr = style_idx ? %( s="#{xml_escape(style_idx)}") : ""
401
- ph_attr = ph ? ' ph="1"' : ""
403
+ # : (XmlBuilder xml, untyped cell_ref, untyped value, untyped style_idx, ?untyped? sst, ?ph: untyped?) -> void
404
+ def write_cell_xml(xml, cell_ref, value, style_idx, sst = nil, ph: nil) # rubocop:disable Naming/MethodParameterName
405
+ ph_val = ph ? 1 : nil
402
406
  case value
403
407
  when Xlsxrb::Elements::CellError
404
- %(<c r="#{xml_escape(cell_ref)}" t="e"#{s_attr}#{ph_attr}><v>#{xml_escape(value.code)}</v></c>)
405
- when Xlsxrb::Elements::Formula
406
- f_attrs = +""
407
- case value.type
408
- when :shared
409
- f_attrs << %( t="shared" si="#{xml_escape(value.shared_index)}")
410
- f_attrs << %( ref="#{xml_escape(value.ref)}") if value.ref
411
- when :array
412
- f_attrs << %( t="array" ref="#{xml_escape(value.ref)}") if value.ref
413
- when :data_table
414
- f_attrs << ' t="dataTable"'
415
- f_attrs << ' dt2D="1"' if value.dt2d
416
- f_attrs << ' dtr="1"' if value.dtr
417
- f_attrs << %( r1="#{xml_escape(value.r1)}") if value.r1
418
- f_attrs << %( r2="#{xml_escape(value.r2)}") if value.r2
408
+ xml.tag("c", { r: cell_ref || "", t: "e", s: style_idx, ph: ph_val }) do
409
+ xml.text_tag("v", value.code)
419
410
  end
420
- f_attrs << ' ca="1"' if value.calculate_always?
421
- f_attrs << ' aca="1"' if value.aca
422
- f_attrs << ' bx="1"' if value.bx
423
- t_attr = ""
411
+ when Xlsxrb::Elements::Formula
412
+ f_attrs = case value.type
413
+ when :shared
414
+ { t: "shared", si: value.shared_index || "", ref: value.ref }
415
+ when :array
416
+ value.ref ? { t: "array", ref: value.ref } : {}
417
+ when :data_table
418
+ {
419
+ t: "dataTable",
420
+ dt2D: value.dt2d ? 1 : nil,
421
+ dtr: value.dtr ? 1 : nil,
422
+ r1: value.r1,
423
+ r2: value.r2
424
+ }
425
+ else
426
+ {}
427
+ end
428
+ f_attrs[:ca] = 1 if value.calculate_always?
429
+ f_attrs[:aca] = 1 if value.aca
430
+ f_attrs[:bx] = 1 if value.bx
431
+ t_val = nil
424
432
  cached_val_str = value.cached_value.to_s
425
433
  case value.cached_value
426
434
  when String
427
- t_attr = ' t="str"'
435
+ t_val = "str"
428
436
  when true
429
- t_attr = ' t="b"'
437
+ t_val = "b"
430
438
  cached_val_str = "1"
431
439
  when false
432
- t_attr = ' t="b"'
440
+ t_val = "b"
433
441
  cached_val_str = "0"
434
442
  end
435
- f_tag = if value.expression && !value.expression.empty?
436
- "<f#{f_attrs}>#{xml_escape(value.expression)}</f>"
437
- else
438
- "<f#{f_attrs}/>"
439
- end
440
- parts = %(<c r="#{xml_escape(cell_ref)}"#{t_attr}#{s_attr}#{ph_attr}>#{f_tag})
441
- parts << "<v>#{xml_escape_text(cached_val_str)}</v>" unless value.cached_value.nil?
442
- parts << "</c>"
443
- parts
443
+ xml.tag("c", { r: cell_ref || "", t: t_val, s: style_idx, ph: ph_val }) do
444
+ if value.expression && !value.expression.empty?
445
+ xml.text_tag("f", value.expression, f_attrs)
446
+ else
447
+ xml.empty_tag("f", f_attrs)
448
+ end
449
+ xml.tag("v") { xml.xstring_text(cached_val_str) } unless value.cached_value.nil?
450
+ end
444
451
  when Xlsxrb::Elements::RichText
445
452
  if sst
446
453
  rt_sst, = sst
447
- idx = rt_sst[value]
448
- %(<c r="#{xml_escape(cell_ref)}" t="s"#{s_attr}#{ph_attr}><v>#{idx}</v></c>)
454
+ xml.tag("c", { r: cell_ref || "", t: "s", s: style_idx, ph: ph_val }) do
455
+ xml.text_tag("v", rt_sst[value])
456
+ end
449
457
  else
450
- %(<c r="#{xml_escape(cell_ref)}" t="inlineStr"#{s_attr}#{ph_attr}><is>#{rich_text_xml(value)}</is></c>)
458
+ xml.tag("c", { r: cell_ref || "", t: "inlineStr", s: style_idx, ph: ph_val }) do
459
+ xml.tag("is") { write_rich_text_xml(xml, value) }
460
+ end
451
461
  end
452
462
  when true, false
453
- %(<c r="#{xml_escape(cell_ref)}" t="b"#{s_attr}#{ph_attr}><v>#{value ? 1 : 0}</v></c>)
463
+ xml.tag("c", { r: cell_ref || "", t: "b", s: style_idx, ph: ph_val }) do
464
+ xml.text_tag("v", value ? 1 : 0)
465
+ end
454
466
  when Time
455
467
  date1904 = @workbook_properties&.[](:date1904) ? true : false
456
468
  serial = Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: date1904)
457
- dt_attr = s_attr.empty? && (dt_style = resolve_style_index(datetime_num_fmt_id)) ? %( s="#{xml_escape(dt_style)}") : s_attr
458
- %(<c r="#{xml_escape(cell_ref)}"#{dt_attr}#{ph_attr}><v>#{serial}</v></c>)
469
+ s_val = style_idx || resolve_style_index(datetime_num_fmt_id)
470
+ xml.tag("c", { r: cell_ref || "", s: s_val, ph: ph_val }) { xml.text_tag("v", serial) }
459
471
  when Date
460
472
  date1904 = @workbook_properties&.[](:date1904) ? true : false
461
473
  serial = Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: date1904)
462
- ds_attr = s_attr.empty? && (date_style = resolve_style_index(date_num_fmt_id)) ? %( s="#{xml_escape(date_style)}") : s_attr
463
- %(<c r="#{xml_escape(cell_ref)}"#{ds_attr}#{ph_attr}><v>#{serial}</v></c>)
474
+ s_val = style_idx || resolve_style_index(date_num_fmt_id)
475
+ xml.tag("c", { r: cell_ref || "", s: s_val, ph: ph_val }) { xml.text_tag("v", serial) }
464
476
  when Numeric
465
- %(<c r="#{xml_escape(cell_ref)}"#{s_attr}#{ph_attr}><v>#{value}</v></c>)
477
+ xml.tag("c", { r: cell_ref || "", s: style_idx, ph: ph_val }) { xml.text_tag("v", value) }
466
478
  else
467
479
  if sst
468
480
  _, str_sst = sst
469
- idx = str_sst[value.to_s]
470
- %(<c r="#{xml_escape(cell_ref)}" t="s"#{s_attr}#{ph_attr}><v>#{idx}</v></c>)
481
+ xml.tag("c", { r: cell_ref || "", t: "s", s: style_idx, ph: ph_val }) do
482
+ xml.text_tag("v", str_sst[value.to_s])
483
+ end
471
484
  else
472
- %(<c r="#{xml_escape(cell_ref)}" t="inlineStr"#{s_attr}#{ph_attr}><is><t>#{xml_escape_text(value)}</t></is></c>)
485
+ xml.tag("c", { r: cell_ref || "", t: "inlineStr", s: style_idx, ph: ph_val }) do
486
+ xml.tag("is") { xml.tag("t") { xml.xstring_text(value) } }
487
+ end
473
488
  end
474
489
  end
475
490
  end
@@ -512,71 +527,76 @@ module Xlsxrb
512
527
  @xf_index_map[num_fmt_id]
513
528
  end
514
529
 
515
- # : (untyped filter) -> untyped
516
- def emit_filter_xml(filter)
530
+ # : (XmlBuilder xml, untyped filter) -> void
531
+ def write_filter_xml(xml, filter)
517
532
  case filter[:type]
518
533
  when :filters
519
- attrs = filter[:blank] ? +' blank="1"' : +""
520
- attrs << %( calendarType="#{xml_escape(filter[:calendar_type])}") if filter[:calendar_type]
534
+ attrs = {
535
+ blank: filter[:blank] ? 1 : nil,
536
+ calendarType: filter[:calendar_type]
537
+ }
521
538
  has_values = filter[:values]&.any?
522
539
  has_date_groups = filter[:date_group_items]&.any?
523
540
  if has_values || has_date_groups
524
- parts = ["<filters#{attrs}>"]
525
- filter[:values]&.each { |v| parts << %(<filter val="#{xml_escape(v)}"/>) }
526
- filter[:date_group_items]&.each do |dg|
527
- dg_attrs = %(dateTimeGrouping="#{xml_escape(dg[:date_time_grouping])}")
528
- dg_attrs << %( year="#{xml_escape(dg[:year])}") if dg[:year]
529
- dg_attrs << %( month="#{xml_escape(dg[:month])}") if dg[:month]
530
- dg_attrs << %( day="#{xml_escape(dg[:day])}") if dg[:day]
531
- dg_attrs << %( hour="#{xml_escape(dg[:hour])}") if dg[:hour]
532
- dg_attrs << %( minute="#{xml_escape(dg[:minute])}") if dg[:minute]
533
- dg_attrs << %( second="#{xml_escape(dg[:second])}") if dg[:second]
534
- parts << "<dateGroupItem #{dg_attrs}/>"
541
+ xml.tag("filters", attrs) do
542
+ filter[:values]&.each { |v| xml.empty_tag("filter", { val: v || "" }) }
543
+ filter[:date_group_items]&.each do |dg|
544
+ xml.empty_tag("dateGroupItem", {
545
+ dateTimeGrouping: dg[:date_time_grouping] || "",
546
+ year: dg[:year],
547
+ month: dg[:month],
548
+ day: dg[:day],
549
+ hour: dg[:hour],
550
+ minute: dg[:minute],
551
+ second: dg[:second]
552
+ })
553
+ end
535
554
  end
536
- parts << "</filters>"
537
- parts.join
538
555
  else
539
- "<filters#{attrs}/>"
556
+ xml.empty_tag("filters", attrs)
540
557
  end
541
558
  when :custom
542
559
  if filter[:filters]
543
- and_attr = filter[:and] ? ' and="1"' : ""
544
- parts = ["<customFilters#{and_attr}>"]
545
- filter[:filters].each do |cf|
546
- parts << %(<customFilter operator="#{xml_escape(cf[:operator])}" val="#{xml_escape(cf[:val])}"/>)
560
+ xml.tag("customFilters", { and: filter[:and] ? 1 : nil }) do
561
+ filter[:filters].each do |cf|
562
+ xml.empty_tag("customFilter", { operator: cf[:operator] || "", val: cf[:val] || "" })
563
+ end
547
564
  end
548
- parts << "</customFilters>"
549
- parts.join
550
565
  else
551
- %(<customFilters><customFilter operator="#{xml_escape(filter[:operator])}" val="#{xml_escape(filter[:val])}"/></customFilters>)
566
+ xml.tag("customFilters") do
567
+ xml.empty_tag("customFilter", { operator: filter[:operator] || "", val: filter[:val] || "" })
568
+ end
552
569
  end
553
570
  when :dynamic
554
- dyn_attrs = %( type="#{xml_escape(filter[:dynamic_type])}")
555
- dyn_attrs << %( val="#{xml_escape(filter[:val])}") if filter[:val]
556
- dyn_attrs << %( valIso="#{xml_escape(filter[:val_iso])}") if filter[:val_iso]
557
- dyn_attrs << %( maxVal="#{xml_escape(filter[:max_val])}") if filter[:max_val]
558
- dyn_attrs << %( maxValIso="#{xml_escape(filter[:max_val_iso])}") if filter[:max_val_iso]
559
- "<dynamicFilter#{dyn_attrs}/>"
571
+ xml.empty_tag("dynamicFilter", {
572
+ type: filter[:dynamic_type] || "",
573
+ val: filter[:val],
574
+ valIso: filter[:val_iso],
575
+ maxVal: filter[:max_val],
576
+ maxValIso: filter[:max_val_iso]
577
+ })
560
578
  when :top10
561
- top_attr = filter[:top] ? ' top="1"' : ""
562
- pct_attr = filter[:percent] ? ' percent="1"' : ""
563
- fv_attr = filter[:filter_val] ? %( filterVal="#{xml_escape(filter[:filter_val])}") : ""
564
- %(<top10#{top_attr}#{pct_attr} val="#{xml_escape(filter[:val])}"#{fv_attr}/>)
579
+ xml.empty_tag("top10", {
580
+ top: filter[:top] ? 1 : nil,
581
+ percent: filter[:percent] ? 1 : nil,
582
+ val: filter[:val] || "",
583
+ filterVal: filter[:filter_val]
584
+ })
565
585
  when :color_filter
566
- cf_attrs = %(dxfId="#{xml_escape(filter[:dxf_id])}")
567
- cf_attrs << ' cellColor="0"' if filter[:cell_color] == false
568
- %(<colorFilter #{cf_attrs}/>)
586
+ xml.empty_tag("colorFilter", {
587
+ dxfId: filter[:dxf_id] || "",
588
+ cellColor: filter[:cell_color] == false ? 0 : nil
589
+ })
569
590
  when :icon_filter
570
- if_attrs = %(iconSet="#{xml_escape(filter[:icon_set])}")
571
- if_attrs << %( iconId="#{xml_escape(filter[:icon_id])}") if filter[:icon_id]
572
- %(<iconFilter #{if_attrs}/>)
573
- else
574
- ""
591
+ xml.empty_tag("iconFilter", {
592
+ iconSet: filter[:icon_set] || "",
593
+ iconId: filter[:icon_id]
594
+ })
575
595
  end
576
596
  end
577
597
 
578
- # : (untyped parts, untyped rule) -> untyped
579
- def emit_cf_rule(parts, rule)
598
+ # : (XmlBuilder xml, untyped rule) -> void
599
+ def write_cf_rule(xml, rule)
580
600
  type = rule[:type]
581
601
  if type.is_a?(String) || type.is_a?(Symbol)
582
602
  t_str = type.to_s
@@ -586,24 +606,26 @@ module Xlsxrb
586
606
  type = snake if CF_TYPE_MAP.key?(snake)
587
607
  end
588
608
  rule_type = CF_TYPE_MAP[type] || type.to_s
589
- rule_attrs = %(type="#{xml_escape(rule_type)}")
590
- rule_attrs << %( priority="#{xml_escape(rule[:priority])}") if rule[:priority]
591
- rule_attrs << %( operator="#{xml_escape(rule[:operator])}") if rule[:operator]
592
609
  did = rule[:dxf_id] || rule[:format_id]
593
- rule_attrs << %( dxfId="#{xml_escape(did)}") if did
594
- rule_attrs << %( stopIfTrue="1") if rule[:stop_if_true]
595
- rule_attrs << %( aboveAverage="0") if rule[:above_average] == false
596
- rule_attrs << %( equalAverage="1") if rule[:equal_average]
597
- rule_attrs << %( rank="#{xml_escape(rule[:rank])}") if rule[:rank]
598
- rule_attrs << %( percent="1") if rule[:percent]
599
- rule_attrs << %( bottom="1") if rule[:bottom]
600
- rule_attrs << %( text="#{xml_escape(rule[:text])}") if rule[:text]
601
- if rule[:time_period]
602
- tp = rule[:time_period]
603
- tp_str = DslHelpers::CF_TIME_PERIODS[tp.to_sym] || tp.to_s
604
- rule_attrs << %( timePeriod="#{xml_escape(tp_str)}")
605
- end
606
- rule_attrs << %( stdDev="#{xml_escape(rule[:std_dev])}") if rule[:std_dev]
610
+ tp_str = if rule[:time_period]
611
+ tp = rule[:time_period]
612
+ DslHelpers::CF_TIME_PERIODS[tp.to_sym] || tp.to_s
613
+ end
614
+ rule_attrs = {
615
+ type: rule_type,
616
+ priority: rule[:priority],
617
+ operator: rule[:operator],
618
+ dxfId: did,
619
+ stopIfTrue: rule[:stop_if_true] ? 1 : nil,
620
+ aboveAverage: rule[:above_average] == false ? 0 : nil,
621
+ equalAverage: rule[:equal_average] ? 1 : nil,
622
+ rank: rule[:rank],
623
+ percent: rule[:percent] ? 1 : nil,
624
+ bottom: rule[:bottom] ? 1 : nil,
625
+ text: rule[:text],
626
+ timePeriod: tp_str,
627
+ stdDev: rule[:std_dev]
628
+ }
607
629
 
608
630
  case type
609
631
  when :cell_is, :expression, :above_average, :top10, :duplicate_values, :unique_values,
@@ -611,71 +633,74 @@ module Xlsxrb
611
633
  :contains_blanks, :not_contains_blanks, :contains_errors, :not_contains_errors, :time_period
612
634
  formulas = rule[:formulas] || [rule[:formula]].compact
613
635
  if formulas.empty?
614
- parts << "<cfRule #{rule_attrs}/>"
636
+ xml.empty_tag("cfRule", rule_attrs)
615
637
  else
616
- parts << "<cfRule #{rule_attrs}>"
617
- formulas.each { |f| parts << "<formula>#{xml_escape(f)}</formula>" }
618
- parts << "</cfRule>"
638
+ xml.tag("cfRule", rule_attrs) do
639
+ formulas.each { |f| xml.text_tag("formula", f) }
640
+ end
619
641
  end
620
642
  when :color_scale
621
643
  cs = rule[:color_scale]
622
- parts << "<cfRule #{rule_attrs}>"
623
- parts << "<colorScale>"
624
- cs[:cfvo]&.each do |cfvo|
625
- cfvo_attrs = %(type="#{xml_escape(cfvo[:type])}")
626
- cfvo_attrs << %( val="#{xml_escape(cfvo[:val])}") if cfvo[:val]
627
- cfvo_attrs << ' gte="0"' if cfvo[:gte] == false
628
- parts << "<cfvo #{cfvo_attrs}/>"
644
+ xml.tag("cfRule", rule_attrs) do
645
+ xml.tag("colorScale") do
646
+ cs[:cfvo]&.each do |cfvo|
647
+ xml.empty_tag("cfvo", {
648
+ type: cfvo[:type] || "",
649
+ val: cfvo[:val],
650
+ gte: cfvo[:gte] == false ? 0 : nil
651
+ })
652
+ end
653
+ cs[:colors]&.each { |c| write_cf_color_xml(xml, c) }
654
+ end
629
655
  end
630
- cs[:colors]&.each { |c| parts << emit_cf_color_xml(c) }
631
- parts << "</colorScale>"
632
- parts << "</cfRule>"
633
656
  when :data_bar
634
657
  db = rule[:data_bar]
635
- parts << "<cfRule #{rule_attrs}>"
636
- db_attrs = +""
637
- db_attrs << %( minLength="#{xml_escape(db[:min_length])}") if db[:min_length]
638
- db_attrs << %( maxLength="#{xml_escape(db[:max_length])}") if db[:max_length]
639
- db_attrs << %( showValue="#{db[:show_value] ? 1 : 0}") unless db[:show_value].nil?
640
- parts << "<dataBar#{db_attrs}>"
641
- db[:cfvo]&.each do |cfvo|
642
- cfvo_attrs = %(type="#{xml_escape(cfvo[:type])}")
643
- cfvo_attrs << %( val="#{xml_escape(cfvo[:val])}") if cfvo[:val]
644
- cfvo_attrs << ' gte="0"' if cfvo[:gte] == false
645
- parts << "<cfvo #{cfvo_attrs}/>"
658
+ xml.tag("cfRule", rule_attrs) do
659
+ xml.tag("dataBar", {
660
+ minLength: db[:min_length],
661
+ maxLength: db[:max_length],
662
+ showValue: xml_bool_attr(db[:show_value])
663
+ }) do
664
+ db[:cfvo]&.each do |cfvo|
665
+ xml.empty_tag("cfvo", {
666
+ type: cfvo[:type] || "",
667
+ val: cfvo[:val],
668
+ gte: cfvo[:gte] == false ? 0 : nil
669
+ })
670
+ end
671
+ write_cf_color_xml(xml, db[:color]) if db[:color]
672
+ end
646
673
  end
647
- parts << emit_cf_color_xml(db[:color]) if db[:color]
648
- parts << "</dataBar>"
649
- parts << "</cfRule>"
650
674
  when :icon_set
651
675
  is = rule[:icon_set]
652
- parts << "<cfRule #{rule_attrs}>"
653
- is_attrs = +""
654
- is_attrs << %( iconSet="#{xml_escape(is[:icon_set])}") if is[:icon_set]
655
- is_attrs << %( reverse="#{is[:reverse] ? 1 : 0}") unless is[:reverse].nil?
656
- is_attrs << %( percent="#{is[:percent] ? 1 : 0}") unless is[:percent].nil?
657
- is_attrs << %( showValue="#{is[:show_value] ? 1 : 0}") unless is[:show_value].nil?
658
- parts << "<iconSet#{is_attrs}>"
659
- is[:cfvo]&.each do |cfvo|
660
- cfvo_attrs = %(type="#{xml_escape(cfvo[:type])}")
661
- cfvo_attrs << %( val="#{xml_escape(cfvo[:val])}") if cfvo[:val]
662
- cfvo_attrs << ' gte="0"' if cfvo[:gte] == false
663
- parts << "<cfvo #{cfvo_attrs}/>"
676
+ xml.tag("cfRule", rule_attrs) do
677
+ xml.tag("iconSet", {
678
+ iconSet: is[:icon_set],
679
+ reverse: xml_bool_attr(is[:reverse]),
680
+ percent: xml_bool_attr(is[:percent]),
681
+ showValue: xml_bool_attr(is[:show_value])
682
+ }) do
683
+ is[:cfvo]&.each do |cfvo|
684
+ xml.empty_tag("cfvo", {
685
+ type: cfvo[:type] || "",
686
+ val: cfvo[:val],
687
+ gte: cfvo[:gte] == false ? 0 : nil
688
+ })
689
+ end
690
+ end
664
691
  end
665
- parts << "</iconSet>"
666
- parts << "</cfRule>"
667
692
  else
668
- parts << "<cfRule #{rule_attrs}/>"
693
+ xml.empty_tag("cfRule", rule_attrs)
669
694
  end
670
695
  end
671
696
 
672
697
  # Emits a <color> element for CF rules, accepting either a plain RGB string or a hash.
673
- # : (untyped color) -> (untyped | ::String)
674
- def emit_cf_color_xml(color)
698
+ # : (XmlBuilder xml, untyped color) -> void
699
+ def write_cf_color_xml(xml, color)
675
700
  if color.is_a?(Hash)
676
- emit_color_xml(color)
701
+ write_color_xml(xml, color)
677
702
  else
678
- %(<color rgb="#{xml_escape(color)}"/>)
703
+ xml.empty_tag("color", { rgb: color || "" })
679
704
  end
680
705
  end
681
706
 
@@ -714,63 +739,60 @@ module Xlsxrb
714
739
 
715
740
  # : () -> untyped
716
741
  def generate_core_properties_xml
717
- parts = [
718
- XML_HEADER,
719
- %(<cp:coreProperties xmlns:cp="#{CP_NS}" xmlns:dc="#{DC_NS}" xmlns:dcterms="#{DCTERMS_NS}" xmlns:xsi="#{XSI_NS}">)
720
- ]
721
- parts << "<dc:title>#{xml_escape(@core_properties[:title])}</dc:title>" if @core_properties[:title]
722
- parts << "<dc:subject>#{xml_escape(@core_properties[:subject])}</dc:subject>" if @core_properties[:subject]
723
- parts << "<dc:creator>#{xml_escape(@core_properties[:creator])}</dc:creator>" if @core_properties[:creator]
724
- parts << "<cp:keywords>#{xml_escape(@core_properties[:keywords])}</cp:keywords>" if @core_properties[:keywords]
725
- parts << "<dc:description>#{xml_escape(@core_properties[:description])}</dc:description>" if @core_properties[:description]
726
- parts << "<cp:lastModifiedBy>#{xml_escape(@core_properties[:last_modified_by])}</cp:lastModifiedBy>" if @core_properties[:last_modified_by]
727
- parts << "<cp:revision>#{xml_escape(@core_properties[:revision])}</cp:revision>" if @core_properties[:revision]
728
- parts << %(<dcterms:created xsi:type="dcterms:W3CDTF">#{xml_escape(@core_properties[:created])}</dcterms:created>) if @core_properties[:created]
729
- parts << %(<dcterms:modified xsi:type="dcterms:W3CDTF">#{xml_escape(@core_properties[:modified])}</dcterms:modified>) if @core_properties[:modified]
730
- parts << "<cp:category>#{xml_escape(@core_properties[:category])}</cp:category>" if @core_properties[:category]
731
- parts << "<cp:contentStatus>#{xml_escape(@core_properties[:content_status])}</cp:contentStatus>" if @core_properties[:content_status]
732
- parts << "<dc:language>#{xml_escape(@core_properties[:language])}</dc:language>" if @core_properties[:language]
733
- parts << "</cp:coreProperties>"
734
- parts.join
742
+ XmlBuilder.build(declaration: :plain) do |xml|
743
+ xml.tag("cp:coreProperties", {
744
+ "xmlns:cp": CP_NS,
745
+ "xmlns:dc": DC_NS,
746
+ "xmlns:dcterms": DCTERMS_NS,
747
+ "xmlns:xsi": XSI_NS
748
+ }) do
749
+ xml.text_tag("dc:title", @core_properties[:title]) if @core_properties[:title]
750
+ xml.text_tag("dc:subject", @core_properties[:subject]) if @core_properties[:subject]
751
+ xml.text_tag("dc:creator", @core_properties[:creator]) if @core_properties[:creator]
752
+ xml.text_tag("cp:keywords", @core_properties[:keywords]) if @core_properties[:keywords]
753
+ xml.text_tag("dc:description", @core_properties[:description]) if @core_properties[:description]
754
+ xml.text_tag("cp:lastModifiedBy", @core_properties[:last_modified_by]) if @core_properties[:last_modified_by]
755
+ xml.text_tag("cp:revision", @core_properties[:revision]) if @core_properties[:revision]
756
+ xml.text_tag("dcterms:created", @core_properties[:created], { "xsi:type": "dcterms:W3CDTF" }) if @core_properties[:created]
757
+ xml.text_tag("dcterms:modified", @core_properties[:modified], { "xsi:type": "dcterms:W3CDTF" }) if @core_properties[:modified]
758
+ xml.text_tag("cp:category", @core_properties[:category]) if @core_properties[:category]
759
+ xml.text_tag("cp:contentStatus", @core_properties[:content_status]) if @core_properties[:content_status]
760
+ xml.text_tag("dc:language", @core_properties[:language]) if @core_properties[:language]
761
+ end
762
+ end
735
763
  end
736
764
 
737
765
  # : () -> untyped
738
766
  def generate_app_properties_xml
739
- parts = [
740
- XML_HEADER,
741
- %(<Properties xmlns="#{APP_NS}" xmlns:vt="#{VT_NS}">)
742
- ]
743
767
  app_val = @app_properties[:app_name] || @app_properties[:application]
744
- parts << "<Application>#{xml_escape(app_val)}</Application>" if app_val
745
- parts << "<AppVersion>#{xml_escape(@app_properties[:app_version])}</AppVersion>" if @app_properties[:app_version]
746
- if @app_properties[:heading_pairs] && @app_properties[:titles_of_parts]
747
- hp = @app_properties[:heading_pairs]
748
- tp = @app_properties[:titles_of_parts]
749
- parts << "<HeadingPairs>"
750
- parts << %(<vt:vector size="#{xml_escape(hp.size * 2)}" baseType="variant">)
751
- hp.each do |label, count|
752
- parts << "<vt:variant><vt:lpstr>#{xml_escape(label)}</vt:lpstr></vt:variant>"
753
- parts << "<vt:variant><vt:i4>#{count}</vt:i4></vt:variant>"
768
+ XmlBuilder.build(declaration: :plain) do |xml|
769
+ xml.tag("Properties", { xmlns: APP_NS, "xmlns:vt": VT_NS }) do
770
+ xml.text_tag("Application", app_val) if app_val
771
+ xml.text_tag("AppVersion", @app_properties[:app_version]) if @app_properties[:app_version]
772
+ if @app_properties[:heading_pairs] && @app_properties[:titles_of_parts]
773
+ hp = @app_properties[:heading_pairs]
774
+ tp = @app_properties[:titles_of_parts]
775
+ xml.tag("HeadingPairs") do
776
+ xml.tag("vt:vector", { size: hp.size * 2, baseType: "variant" }) do
777
+ hp.each do |label, count|
778
+ xml.tag("vt:variant") { xml.text_tag("vt:lpstr", label) }
779
+ xml.tag("vt:variant") { xml.text_tag("vt:i4", count) }
780
+ end
781
+ end
782
+ end
783
+ xml.tag("TitlesOfParts") do
784
+ xml.tag("vt:vector", { size: tp.size, baseType: "lpstr" }) do
785
+ tp.each { |t| xml.text_tag("vt:lpstr", t) }
786
+ end
787
+ end
788
+ end
754
789
  end
755
- parts << "</vt:vector>"
756
- parts << "</HeadingPairs>"
757
- parts << "<TitlesOfParts>"
758
- parts << %(<vt:vector size="#{tp.size}" baseType="lpstr">)
759
- tp.each { |t| parts << "<vt:lpstr>#{xml_escape(t)}</vt:lpstr>" }
760
- parts << "</vt:vector>"
761
- parts << "</TitlesOfParts>"
762
790
  end
763
- parts << "</Properties>"
764
- parts.join
765
791
  end
766
792
 
767
793
  # : () -> untyped
768
794
  def generate_custom_properties_xml
769
795
  custom_ns = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
770
- parts = [
771
- XML_HEADER,
772
- %(<Properties xmlns="#{xml_escape(custom_ns)}" xmlns:vt="#{VT_NS}">)
773
- ]
774
796
  list = if @custom_properties.is_a?(Hash)
775
797
  @custom_properties.map do |name, val|
776
798
  if val.is_a?(Elements::CustomProperty) || (val.respond_to?(:name) && val.respond_to?(:value))
@@ -790,26 +812,37 @@ module Xlsxrb
790
812
  end
791
813
  end
792
814
  end
793
- list.each_with_index do |prop, idx|
794
- fmtid = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
795
- pid = idx + 2 # pids start at 2
796
- parts << %(<property fmtid="#{xml_escape(fmtid)}" pid="#{xml_escape(pid)}" name="#{xml_escape(prop[:name])}">)
797
- parts << case prop[:type]
798
- when :number, :int, :i4
799
- "<vt:i4>#{xml_escape(prop[:value])}</vt:i4>"
800
- when :float, :r8
801
- "<vt:r8>#{xml_escape(prop[:value])}</vt:r8>"
802
- when :bool, :boolean
803
- "<vt:bool>#{prop[:value] ? "true" : "false"}</vt:bool>"
804
- when :date, :filetime
805
- "<vt:filetime>#{xml_escape(prop[:value])}</vt:filetime>"
806
- else
807
- "<vt:lpwstr>#{xml_escape(prop[:value].to_s)}</vt:lpwstr>"
808
- end
809
- parts << "</property>"
815
+
816
+ XmlBuilder.build(declaration: :plain) do |xml|
817
+ xml.tag("Properties", { xmlns: custom_ns, "xmlns:vt": VT_NS }) do
818
+ list.each_with_index do |prop, idx|
819
+ fmtid = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
820
+ xml.tag("property", { fmtid: fmtid, pid: idx + 2, name: prop[:name] || "" }) do
821
+ case prop[:type]
822
+ when :number, :int, :i4
823
+ xml.text_tag("vt:i4", prop[:value])
824
+ when :float, :r8
825
+ xml.text_tag("vt:r8", prop[:value])
826
+ when :bool, :boolean
827
+ xml.text_tag("vt:bool", prop[:value] ? "true" : "false")
828
+ when :date, :filetime
829
+ xml.text_tag("vt:filetime", prop[:value])
830
+ else
831
+ xml.text_tag("vt:lpwstr", prop[:value])
832
+ end
833
+ end
834
+ end
835
+ end
810
836
  end
811
- parts << "</Properties>"
812
- parts.join
837
+ end
838
+
839
+ private
840
+
841
+ # : (untyped val) -> (nil | ::Integer)
842
+ def xml_bool_attr(val)
843
+ return nil if val.nil?
844
+
845
+ val ? 1 : 0
813
846
  end
814
847
  end
815
848
  end