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
@@ -3,6 +3,7 @@
3
3
  # rbs_inline: enabled
4
4
 
5
5
  require_relative "zip_generator"
6
+ require_relative "xml_builder"
6
7
  require_relative "writer/drawing_xml"
7
8
  require_relative "writer/features_xml"
8
9
  require_relative "writer/styles_xml"
@@ -2142,7 +2143,7 @@ module Xlsxrb
2142
2143
 
2143
2144
  private
2144
2145
 
2145
- # : (?::Hash[untyped, untyped] all_entries) -> untyped
2146
+ # : (?::Hash[untyped, untyped] all_entries) -> ::String
2146
2147
  def generate_content_types_xml(all_entries = {})
2147
2148
  defaults = {
2148
2149
  "rels" => "application/vnd.openxmlformats-package.relationships+xml",
@@ -2245,280 +2246,159 @@ module Xlsxrb
2245
2246
  # Merge extra overrides from pass-through.
2246
2247
  overrides.merge!(@extra_ct_overrides) { |_k, generated, _extra| generated }
2247
2248
 
2248
- parts = [XML_HEADER, %(<Types xmlns="#{CT_NS}">)]
2249
- defaults.each { |ext, ct| parts << %(<Default Extension="#{xml_escape(ext)}" ContentType="#{xml_escape(ct)}"/>) }
2250
- overrides.each { |pn, ct| parts << %(<Override PartName="#{xml_escape(pn)}" ContentType="#{xml_escape(ct)}"/>) }
2251
- parts << "</Types>"
2252
- parts.join
2249
+ XmlBuilder.build(declaration: :plain) do |xml|
2250
+ xml.tag("Types", { xmlns: CT_NS }) do
2251
+ defaults.each { |ext, ct| xml.empty_tag("Default", { Extension: ext || "", ContentType: ct || "" }) }
2252
+ overrides.each { |pn, ct| xml.empty_tag("Override", { PartName: pn || "", ContentType: ct || "" }) }
2253
+ end
2254
+ end
2253
2255
  end
2254
2256
 
2255
- # : () -> untyped
2257
+ # : () -> ::String
2256
2258
  def generate_rels_root
2257
2259
  rid_counter = 1
2258
- parts = [
2259
- XML_HEADER,
2260
- %(<Relationships xmlns="#{REL_NS}">),
2261
- %(<Relationship Id="rId#{xml_escape(rid_counter)}" Type="#{DOC_REL_NS}/officeDocument" Target="xl/workbook.xml"/>)
2262
- ]
2263
- unless @core_properties.empty?
2264
- rid_counter += 1
2265
- parts << %(<Relationship Id="rId#{xml_escape(rid_counter)}" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>)
2266
- end
2267
- if @app_properties.any?
2268
- rid_counter += 1
2269
- parts << %(<Relationship Id="rId#{xml_escape(rid_counter)}" Type="#{DOC_REL_NS}/extended-properties" Target="docProps/app.xml"/>)
2270
- end
2271
- unless @custom_properties.empty?
2272
- rid_counter += 1
2273
- parts << %(<Relationship Id="rId#{xml_escape(rid_counter)}" Type="#{DOC_REL_NS}/custom-properties" Target="docProps/custom.xml"/>)
2260
+ XmlBuilder.build(declaration: :plain) do |xml|
2261
+ xml.tag("Relationships", { xmlns: REL_NS }) do
2262
+ xml.empty_tag("Relationship", { Id: "rId#{rid_counter}", Type: "#{DOC_REL_NS}/officeDocument", Target: "xl/workbook.xml" })
2263
+ unless @core_properties.empty?
2264
+ rid_counter += 1
2265
+ xml.empty_tag("Relationship", { Id: "rId#{rid_counter}", Type: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", Target: "docProps/core.xml" })
2266
+ end
2267
+ if @app_properties.any?
2268
+ rid_counter += 1
2269
+ xml.empty_tag("Relationship", { Id: "rId#{rid_counter}", Type: "#{DOC_REL_NS}/extended-properties", Target: "docProps/app.xml" })
2270
+ end
2271
+ unless @custom_properties.empty?
2272
+ rid_counter += 1
2273
+ xml.empty_tag("Relationship", { Id: "rId#{rid_counter}", Type: "#{DOC_REL_NS}/custom-properties", Target: "docProps/custom.xml" })
2274
+ end
2275
+ end
2274
2276
  end
2275
- parts << "</Relationships>"
2276
- parts.join
2277
2277
  end
2278
2278
 
2279
- # : (?::Integer pivot_cache_count) -> untyped
2279
+ # : (?::Integer pivot_cache_count) -> ::String
2280
2280
  def generate_workbook_xml(pivot_cache_count = 0)
2281
- wb_attrs = %(xmlns="#{SSML_NS}" xmlns:r="#{DOC_REL_NS}")
2282
- wb_attrs << %( conformance="#{xml_escape(@workbook_properties[:conformance])}") if @workbook_properties[:conformance]
2283
- parts = [
2284
- XML_HEADER,
2285
- "<workbook #{wb_attrs}>"
2286
- ]
2287
-
2288
- # fileVersion
2289
- unless @file_version.empty?
2290
- fv_attrs = []
2291
- fv_attrs << %(appName="#{xml_escape(@file_version[:app_name])}") if @file_version[:app_name]
2292
- fv_attrs << %(lastEdited="#{xml_escape(@file_version[:last_edited])}") if @file_version[:last_edited]
2293
- fv_attrs << %(lowestEdited="#{xml_escape(@file_version[:lowest_edited])}") if @file_version[:lowest_edited]
2294
- fv_attrs << %(rupBuild="#{xml_escape(@file_version[:rup_build])}") if @file_version[:rup_build]
2295
- fv_attrs << %(codeName="#{xml_escape(@file_version[:code_name])}") if @file_version[:code_name]
2296
- parts << "<fileVersion #{fv_attrs.join(" ")}/>" unless fv_attrs.empty?
2297
- end
2298
-
2299
- # fileSharing
2300
- unless @file_sharing.empty?
2301
- fs_attrs = []
2302
- fs_attrs << 'readOnlyRecommended="1"' if @file_sharing[:read_only_recommended]
2303
- fs_attrs << %(userName="#{xml_escape(@file_sharing[:user_name])}") if @file_sharing[:user_name]
2304
- fs_attrs << %(algorithmName="#{xml_escape(@file_sharing[:algorithm_name])}") if @file_sharing[:algorithm_name]
2305
- fs_attrs << %(hashValue="#{xml_escape(@file_sharing[:hash_value])}") if @file_sharing[:hash_value]
2306
- fs_attrs << %(saltValue="#{xml_escape(@file_sharing[:salt_value])}") if @file_sharing[:salt_value]
2307
- fs_attrs << %(spinCount="#{xml_escape(@file_sharing[:spin_count])}") if @file_sharing[:spin_count]
2308
- parts << "<fileSharing #{fs_attrs.join(" ")}/>" unless fs_attrs.empty?
2309
- end
2310
-
2311
- # workbookPr
2312
- unless @workbook_properties.empty?
2313
- attrs = []
2314
- attrs << %(date1904="#{@workbook_properties[:date1904] ? 1 : 0}") unless @workbook_properties[:date1904].nil?
2315
- attrs << %(dateCompatibility="0") if @workbook_properties[:date_compatibility] == false
2316
- attrs << %(defaultThemeVersion="#{xml_escape(@workbook_properties[:default_theme_version])}") if @workbook_properties[:default_theme_version]
2317
- attrs << %(codeName="#{xml_escape(@workbook_properties[:code_name])}") if @workbook_properties[:code_name]
2318
- attrs << %(filterPrivacy="1") if @workbook_properties[:filter_privacy]
2319
- attrs << %(autoCompressPictures="0") if @workbook_properties[:auto_compress_pictures] == false
2320
- attrs << %(backupFile="1") if @workbook_properties[:backup_file]
2321
- attrs << %(showObjects="#{xml_escape(@workbook_properties[:show_objects])}") if @workbook_properties[:show_objects]
2322
- attrs << %(updateLinks="#{xml_escape(@workbook_properties[:update_links])}") if @workbook_properties[:update_links]
2323
- attrs << %(refreshAllConnections="1") if @workbook_properties[:refresh_all_connections]
2324
- attrs << %(checkCompatibility="1") if @workbook_properties[:check_compatibility]
2325
- attrs << %(hidePivotFieldList="1") if @workbook_properties[:hide_pivot_field_list]
2326
- attrs << %(showBorderUnselectedTables="0") if @workbook_properties[:show_border_unselected_tables] == false
2327
- attrs << %(promptedSolutions="1") if @workbook_properties[:prompted_solutions]
2328
- attrs << %(showInkAnnotation="0") if @workbook_properties[:show_ink_annotation] == false
2329
- attrs << %(saveExternalLinkValues="0") if @workbook_properties[:save_external_link_values] == false
2330
- attrs << %(showPivotChartFilter="1") if @workbook_properties[:show_pivot_chart_filter]
2331
- attrs << %(allowRefreshQuery="1") if @workbook_properties[:allow_refresh_query]
2332
- attrs << %(publishItems="1") if @workbook_properties[:publish_items]
2333
- parts << "<workbookPr #{attrs.join(" ")}/>" unless attrs.empty?
2334
- end
2281
+ XmlBuilder.build(declaration: :plain) do |xml|
2282
+ xml.tag("workbook", { xmlns: SSML_NS, "xmlns:r": DOC_REL_NS, conformance: @workbook_properties[:conformance] }) do
2283
+ write_workbook_file_version_xml(xml)
2284
+ write_workbook_file_sharing_xml(xml)
2285
+ write_workbook_pr_xml(xml)
2286
+ write_workbook_views_xml(xml)
2287
+
2288
+ xml.tag("sheets") do
2289
+ @sheet_order.each_with_index do |name, i|
2290
+ state_attr = case @sheet_states[name]
2291
+ when :hidden then "hidden"
2292
+ when :very_hidden then "veryHidden"
2293
+ end
2294
+ xml.empty_tag("sheet", { name: name || "", sheetId: i + 1, state: state_attr, "r:id": "rId#{i + 1}" })
2295
+ end
2296
+ end
2335
2297
 
2336
- # bookViews/workbookView
2337
- unless @workbook_views.empty?
2338
- attrs = []
2339
- attrs << %(visibility="#{xml_escape(@workbook_views[:visibility])}") if @workbook_views[:visibility]
2340
- attrs << 'minimized="1"' if @workbook_views[:minimized]
2341
- shs = @workbook_views[:show_horizontal_scroll]
2342
- attrs << %(showHorizontalScroll="#{shs ? 1 : 0}") unless shs.nil?
2343
- svs = @workbook_views[:show_vertical_scroll]
2344
- attrs << %(showVerticalScroll="#{svs ? 1 : 0}") unless svs.nil?
2345
- sst = @workbook_views[:show_sheet_tabs]
2346
- attrs << %(showSheetTabs="#{sst ? 1 : 0}") unless sst.nil?
2347
- attrs << %(xWindow="#{xml_escape(@workbook_views[:x_window])}") if @workbook_views[:x_window]
2348
- attrs << %(yWindow="#{xml_escape(@workbook_views[:y_window])}") if @workbook_views[:y_window]
2349
- attrs << %(windowWidth="#{xml_escape(@workbook_views[:window_width])}") if @workbook_views[:window_width]
2350
- attrs << %(windowHeight="#{xml_escape(@workbook_views[:window_height])}") if @workbook_views[:window_height]
2351
- attrs << %(tabRatio="#{xml_escape(@workbook_views[:tab_ratio])}") if @workbook_views[:tab_ratio]
2352
- attrs << %(firstSheet="#{xml_escape(@workbook_views[:first_sheet])}") if @workbook_views[:first_sheet]
2353
- at = @workbook_views[:active_sheet_index] || @workbook_views[:active_tab]
2354
- attrs << %(activeTab="#{xml_escape(at)}") if at
2355
- afdg = @workbook_views[:auto_filter_date_grouping]
2356
- attrs << %(autoFilterDateGrouping="#{afdg ? 1 : 0}") unless afdg.nil?
2357
- parts << "<bookViews>"
2358
- parts << "<workbookView #{attrs.join(" ")}/>" unless attrs.empty?
2359
- parts << "</bookViews>"
2360
- end
2298
+ write_workbook_protection_xml(xml) if @workbook_protection
2361
2299
 
2362
- parts << "<sheets>"
2363
- @sheet_order.each_with_index do |name, i|
2364
- state = @sheet_states[name]
2365
- state_attr = case state
2366
- when :hidden then ' state="hidden"'
2367
- when :very_hidden then ' state="veryHidden"'
2368
- else ""
2369
- end
2370
- parts << %(<sheet name="#{xml_escape(name)}" sheetId="#{i + 1}"#{state_attr} r:id="rId#{i + 1}"/>)
2371
- end
2372
- parts << "</sheets>"
2373
-
2374
- # workbookProtection
2375
- if @workbook_protection
2376
- wp_attrs = []
2377
- wp_attrs << 'lockStructure="1"' if @workbook_protection[:lock_structure]
2378
- wp_attrs << 'lockWindows="1"' if @workbook_protection[:lock_windows]
2379
- wp_attrs << 'lockRevision="1"' if @workbook_protection[:lock_revision]
2380
- if @workbook_protection[:algorithm_name]
2381
- wp_attrs << %(workbookAlgorithmName="#{xml_escape(@workbook_protection[:algorithm_name])}")
2382
- wp_attrs << %(workbookHashValue="#{xml_escape(@workbook_protection[:hash_value])}") if @workbook_protection[:hash_value]
2383
- wp_attrs << %(workbookSaltValue="#{xml_escape(@workbook_protection[:salt_value])}") if @workbook_protection[:salt_value]
2384
- wp_attrs << %(workbookSpinCount="#{xml_escape(@workbook_protection[:spin_count])}") if @workbook_protection[:spin_count]
2385
- elsif @workbook_protection[:password]
2386
- wp_attrs << %(workbookPassword="#{xml_escape(@workbook_protection[:password])}")
2387
- end
2388
- if @workbook_protection[:revisions_algorithm_name]
2389
- wp_attrs << %(revisionsAlgorithmName="#{xml_escape(@workbook_protection[:revisions_algorithm_name])}")
2390
- wp_attrs << %(revisionsHashValue="#{xml_escape(@workbook_protection[:revisions_hash_value])}") if @workbook_protection[:revisions_hash_value]
2391
- wp_attrs << %(revisionsSaltValue="#{xml_escape(@workbook_protection[:revisions_salt_value])}") if @workbook_protection[:revisions_salt_value]
2392
- wp_attrs << %(revisionsSpinCount="#{xml_escape(@workbook_protection[:revisions_spin_count])}") if @workbook_protection[:revisions_spin_count]
2393
- elsif @workbook_protection[:revisions_password]
2394
- wp_attrs << %(revisionsPassword="#{xml_escape(@workbook_protection[:revisions_password])}")
2395
- end
2396
- parts << "<workbookProtection #{wp_attrs.join(" ")}/>" unless wp_attrs.empty?
2397
- end
2300
+ unless @external_links.empty?
2301
+ # rId for external links: after sheets + styles + optional SST + pivot caches
2302
+ el_rid_base = @sheet_order.size + 1 + (@use_shared_strings ? 1 : 0) + 1 + pivot_cache_count
2303
+ xml.tag("externalReferences") do
2304
+ @external_links.each_with_index do |_, idx|
2305
+ xml.empty_tag("externalReference", { "r:id": "rId#{el_rid_base + idx}" })
2306
+ end
2307
+ end
2308
+ end
2398
2309
 
2399
- # externalReferences
2400
- unless @external_links.empty?
2401
- # rId for external links: after sheets + styles + optional SST + pivot caches
2402
- el_rid_base = @sheet_order.size + 1 + (@use_shared_strings ? 1 : 0) + 1 + pivot_cache_count
2403
- parts << "<externalReferences>"
2404
- @external_links.each_with_index do |_, idx|
2405
- parts << %(<externalReference r:id="rId#{xml_escape(el_rid_base + idx)}"/>)
2406
- end
2407
- parts << "</externalReferences>"
2408
- end
2310
+ unless @defined_names.empty?
2311
+ xml.tag("definedNames") do
2312
+ @defined_names.each do |dn|
2313
+ attrs = {
2314
+ name: dn[:name] || "",
2315
+ localSheetId: dn[:local_sheet_id],
2316
+ hidden: (1 if dn[:hidden]),
2317
+ comment: dn[:comment],
2318
+ description: dn[:description],
2319
+ function: (1 if dn[:function]),
2320
+ vbProcedure: (1 if dn[:vb_procedure]),
2321
+ xlm: (1 if dn[:xlm]),
2322
+ shortcutKey: dn[:shortcut_key],
2323
+ publishToServer: (1 if dn[:publish_to_server]),
2324
+ workbookParameter: (1 if dn[:workbook_parameter]),
2325
+ functionGroupId: dn[:function_group_id],
2326
+ customMenu: dn[:custom_menu],
2327
+ help: dn[:help],
2328
+ statusBar: dn[:status_bar]
2329
+ }
2330
+ xml.text_tag("definedName", dn[:value] || "", attrs)
2331
+ end
2332
+ end
2333
+ end
2409
2334
 
2410
- # definedNames
2411
- unless @defined_names.empty?
2412
- parts << "<definedNames>"
2413
- @defined_names.each do |dn|
2414
- attrs = %(name="#{xml_escape(dn[:name])}")
2415
- attrs << %( localSheetId="#{xml_escape(dn[:local_sheet_id])}") if dn[:local_sheet_id]
2416
- attrs << ' hidden="1"' if dn[:hidden]
2417
- attrs << %( comment="#{xml_escape(dn[:comment])}") if dn[:comment]
2418
- attrs << %( description="#{xml_escape(dn[:description])}") if dn[:description]
2419
- attrs << ' function="1"' if dn[:function]
2420
- attrs << ' vbProcedure="1"' if dn[:vb_procedure]
2421
- attrs << ' xlm="1"' if dn[:xlm]
2422
- attrs << %( shortcutKey="#{xml_escape(dn[:shortcut_key])}") if dn[:shortcut_key]
2423
- attrs << ' publishToServer="1"' if dn[:publish_to_server]
2424
- attrs << ' workbookParameter="1"' if dn[:workbook_parameter]
2425
- attrs << %( functionGroupId="#{xml_escape(dn[:function_group_id])}") if dn[:function_group_id]
2426
- attrs << %( customMenu="#{xml_escape(dn[:custom_menu])}") if dn[:custom_menu]
2427
- attrs << %( help="#{xml_escape(dn[:help])}") if dn[:help]
2428
- attrs << %( statusBar="#{xml_escape(dn[:status_bar])}") if dn[:status_bar]
2429
- parts << "<definedName #{attrs}>#{xml_escape(dn[:value])}</definedName>"
2430
- end
2431
- parts << "</definedNames>"
2432
- end
2335
+ write_workbook_calc_pr_xml(xml)
2433
2336
 
2434
- # calcPr
2435
- unless @calc_properties.empty?
2436
- attrs = []
2437
- attrs << %(calcId="#{xml_escape(@calc_properties[:calc_id])}") if @calc_properties[:calc_id]
2438
- attrs << %(calcMode="#{xml_escape(@calc_properties[:calc_mode])}") if @calc_properties[:calc_mode]
2439
- attrs << %(fullCalcOnLoad="#{@calc_properties[:full_calc_on_load] ? 1 : 0}") unless @calc_properties[:full_calc_on_load].nil?
2440
- attrs << %(iterate="#{@calc_properties[:iterate] ? 1 : 0}") unless @calc_properties[:iterate].nil?
2441
- attrs << %(iterateCount="#{xml_escape(@calc_properties[:iterate_count])}") if @calc_properties[:iterate_count]
2442
- attrs << %(iterateDelta="#{xml_escape(@calc_properties[:iterate_delta])}") if @calc_properties[:iterate_delta]
2443
- attrs << %(refMode="#{xml_escape(@calc_properties[:ref_mode])}") if @calc_properties[:ref_mode]
2444
- attrs << %(calcCompleted="#{@calc_properties[:calc_completed] ? 1 : 0}") unless @calc_properties[:calc_completed].nil?
2445
- attrs << %(calcOnSave="#{@calc_properties[:calc_on_save] ? 1 : 0}") unless @calc_properties[:calc_on_save].nil?
2446
- fp = @calc_properties[:full_precision]
2447
- attrs << %(fullPrecision="#{fp ? 1 : 0}") unless fp.nil?
2448
- conc = @calc_properties[:concurrent_calc]
2449
- attrs << %(concurrentCalc="#{conc ? 1 : 0}") unless conc.nil?
2450
- attrs << %(concurrentManualCount="#{xml_escape(@calc_properties[:concurrent_manual_count])}") if @calc_properties[:concurrent_manual_count]
2451
- ffc = @calc_properties[:force_full_calc]
2452
- attrs << %(forceFullCalc="#{ffc ? 1 : 0}") unless ffc.nil?
2453
- parts << "<calcPr #{attrs.join(" ")}/>" unless attrs.empty?
2454
- end
2337
+ if pivot_cache_count.positive?
2338
+ # rId layout: sheets(1..N), styles(N+1), optional SST(N+2), then pivot caches
2339
+ pivot_rid_base = @sheet_order.size + 1 + (@use_shared_strings ? 1 : 0) + 1
2340
+ xml.tag("pivotCaches") do
2341
+ pivot_cache_count.times do |ci|
2342
+ xml.empty_tag("pivotCache", { cacheId: ci + 1, "r:id": "rId#{pivot_rid_base + ci}" })
2343
+ end
2344
+ end
2345
+ end
2455
2346
 
2456
- # pivotCaches (reference from workbook to cache definition rels)
2457
- if pivot_cache_count.positive?
2458
- # rId layout: sheets(1..N), styles(N+1), optional SST(N+2), then pivot caches
2459
- pivot_rid_base = @sheet_order.size + 1 + (@use_shared_strings ? 1 : 0) + 1
2460
- parts << "<pivotCaches>"
2461
- pivot_cache_count.times do |ci|
2462
- parts << %(<pivotCache cacheId="#{xml_escape(ci + 1)}" r:id="rId#{xml_escape(pivot_rid_base + ci)}"/>)
2347
+ unless @file_recovery_properties.empty?
2348
+ frp = @file_recovery_properties
2349
+ frp_attrs = {
2350
+ autoRecover: xml_bool_attr(frp[:auto_recover]),
2351
+ crashSave: xml_bool_attr(frp[:crash_save]),
2352
+ dataExtractLoad: xml_bool_attr(frp[:data_extract_load]),
2353
+ repairLoad: xml_bool_attr(frp[:repair_load])
2354
+ }.compact
2355
+ xml.empty_tag("fileRecoveryPr", frp_attrs) unless frp_attrs.empty?
2356
+ end
2463
2357
  end
2464
- parts << "</pivotCaches>"
2465
2358
  end
2466
-
2467
- # fileRecoveryPr
2468
- unless @file_recovery_properties.empty?
2469
- frp_attrs = []
2470
- ar = @file_recovery_properties[:auto_recover]
2471
- frp_attrs << %(autoRecover="#{ar ? 1 : 0}") unless ar.nil?
2472
- cs = @file_recovery_properties[:crash_save]
2473
- frp_attrs << %(crashSave="#{cs ? 1 : 0}") unless cs.nil?
2474
- del = @file_recovery_properties[:data_extract_load]
2475
- frp_attrs << %(dataExtractLoad="#{del ? 1 : 0}") unless del.nil?
2476
- rl = @file_recovery_properties[:repair_load]
2477
- frp_attrs << %(repairLoad="#{rl ? 1 : 0}") unless rl.nil?
2478
- parts << "<fileRecoveryPr #{frp_attrs.join(" ")}/>" unless frp_attrs.empty?
2479
- end
2480
-
2481
- parts << "</workbook>"
2482
- parts.join
2483
2359
  end
2484
2360
 
2485
- # : (?has_calc_chain: bool) -> untyped
2361
+ # : (?has_calc_chain: bool) -> ::String
2486
2362
  def generate_workbook_rels(has_calc_chain: false)
2487
- parts = [
2488
- XML_HEADER,
2489
- %(<Relationships xmlns="#{REL_NS}">)
2490
- ]
2491
- @sheet_order.each_with_index do |_, i|
2492
- parts << %(<Relationship Id="rId#{i + 1}" Type="#{DOC_REL_NS}/worksheet" Target="worksheets/sheet#{i + 1}.xml"/>)
2493
- end
2494
- next_rid = @sheet_order.size + 1
2495
- parts << %(<Relationship Id="rId#{xml_escape(next_rid)}" Type="#{DOC_REL_NS}/styles" Target="styles.xml"/>)
2496
- next_rid += 1
2497
- if @use_shared_strings
2498
- parts << %(<Relationship Id="rId#{xml_escape(next_rid)}" Type="#{DOC_REL_NS}/sharedStrings" Target="sharedStrings.xml"/>)
2499
- next_rid += 1
2500
- end
2501
- (1..@pivot_cache_count.to_i).each do |c|
2502
- parts << %(<Relationship Id="rId#{xml_escape(next_rid)}" Type="#{DOC_REL_NS}/pivotCacheDefinition" Target="pivotCache/pivotCacheDefinition#{xml_escape(c)}.xml"/>)
2503
- next_rid += 1
2504
- end
2505
- @external_links.each_with_index do |_, idx|
2506
- parts << %(<Relationship Id="rId#{xml_escape(next_rid)}" Type="#{DOC_REL_NS}/externalLink" Target="externalLinks/externalLink#{xml_escape(idx + 1)}.xml"/>)
2507
- next_rid += 1
2508
- end
2509
- if has_calc_chain
2510
- parts << %(<Relationship Id="rId#{xml_escape(next_rid)}" Type="#{DOC_REL_NS}/calcChain" Target="calcChain.xml"/>)
2511
- next_rid += 1
2512
- end
2513
- if @persons_data.any?
2514
- parts << %(<Relationship Id="rId#{xml_escape(next_rid)}" Type="http://schemas.microsoft.com/office/2017/10/relationships/person" Target="persons/person.xml"/>)
2515
- next_rid += 1
2363
+ XmlBuilder.build(declaration: :plain) do |xml|
2364
+ xml.tag("Relationships", { xmlns: REL_NS }) do
2365
+ @sheet_order.each_with_index do |_, i|
2366
+ xml.empty_tag("Relationship", { Id: "rId#{i + 1}", Type: "#{DOC_REL_NS}/worksheet", Target: "worksheets/sheet#{i + 1}.xml" })
2367
+ end
2368
+ next_rid = @sheet_order.size + 1
2369
+ xml.empty_tag("Relationship", { Id: "rId#{next_rid}", Type: "#{DOC_REL_NS}/styles", Target: "styles.xml" })
2370
+ next_rid += 1
2371
+ if @use_shared_strings
2372
+ xml.empty_tag("Relationship", { Id: "rId#{next_rid}", Type: "#{DOC_REL_NS}/sharedStrings", Target: "sharedStrings.xml" })
2373
+ next_rid += 1
2374
+ end
2375
+ (1..@pivot_cache_count.to_i).each do |c|
2376
+ xml.empty_tag("Relationship", { Id: "rId#{next_rid}", Type: "#{DOC_REL_NS}/pivotCacheDefinition", Target: "pivotCache/pivotCacheDefinition#{c}.xml" })
2377
+ next_rid += 1
2378
+ end
2379
+ @external_links.each_with_index do |_, idx|
2380
+ xml.empty_tag("Relationship", { Id: "rId#{next_rid}", Type: "#{DOC_REL_NS}/externalLink", Target: "externalLinks/externalLink#{idx + 1}.xml" })
2381
+ next_rid += 1
2382
+ end
2383
+ if has_calc_chain
2384
+ xml.empty_tag("Relationship", { Id: "rId#{next_rid}", Type: "#{DOC_REL_NS}/calcChain", Target: "calcChain.xml" })
2385
+ next_rid += 1
2386
+ end
2387
+ if @persons_data.any?
2388
+ xml.empty_tag(
2389
+ "Relationship",
2390
+ {
2391
+ Id: "rId#{next_rid}",
2392
+ Type: "http://schemas.microsoft.com/office/2017/10/relationships/person",
2393
+ Target: "persons/person.xml"
2394
+ }
2395
+ )
2396
+ end
2397
+ end
2516
2398
  end
2517
- parts << "</Relationships>"
2518
- parts.join
2519
2399
  end
2520
2400
 
2521
- # : () -> (nil | untyped)
2401
+ # : () -> (nil | ::String)
2522
2402
  def generate_calc_chain_xml
2523
2403
  chain_entries = []
2524
2404
  @sheet_order.each_with_index do |sheet_name, i|
@@ -2528,627 +2408,221 @@ module Xlsxrb
2528
2408
  end
2529
2409
  return nil if chain_entries.empty?
2530
2410
 
2531
- parts = [XML_HEADER, %(<calcChain xmlns="#{SSML_NS}">)]
2532
- chain_entries.each do |entry|
2533
- parts << %(<c r="#{xml_escape(entry[:ref])}" i="#{xml_escape(entry[:sheet_id])}"/>)
2411
+ XmlBuilder.build(declaration: :plain) do |xml|
2412
+ xml.tag("calcChain", { xmlns: SSML_NS }) do
2413
+ chain_entries.each do |entry|
2414
+ xml.empty_tag("c", { r: entry[:ref] || "", i: entry[:sheet_id] || "" })
2415
+ end
2416
+ end
2534
2417
  end
2535
- parts << "</calcChain>"
2536
- parts.join
2537
2418
  end
2538
2419
 
2539
- # : (untyped sheet_cells, untyped sheet_col_widths, untyped sheet_col_attrs, untyped sheet_row_attrs, untyped sheet_auto_filter, untyped sheet_filter_cols, untyped sheet_sort, untyped sheet_merge_cells, untyped sheet_hyperlinks, untyped sheet_cell_styles, untyped sheet_props, untyped sheet_fmt, untyped sheet_sv, untyped sheet_fp, untyped sheet_sel, untyped sheet_po, untyped sheet_pm, untyped sheet_ps, untyped sheet_hf, untyped sheet_rb, untyped sheet_cb, untyped sheet_dv, untyped sheet_cf, ?untyped? sst, ?untyped sheet_tables, ?::Integer hyperlink_count, ?has_drawing: bool, ?has_comments: bool, ?sheet_prot: untyped?, ?vml_rid: untyped?, ?phonetic_pr: untyped?, ?dv_options: ::Hash[untyped, untyped], ?prot_ranges: untyped, ?cell_watches: untyped, ?ignored_errors: untyped, ?data_consol: untyped?, ?sheet_scenarios: untyped?, ?cell_phonetic: ::Hash[untyped, untyped]) -> untyped
2420
+ # : (untyped sheet_cells, untyped sheet_col_widths, untyped sheet_col_attrs, untyped sheet_row_attrs, untyped sheet_auto_filter, untyped sheet_filter_cols, untyped sheet_sort, untyped sheet_merge_cells, untyped sheet_hyperlinks, untyped sheet_cell_styles, untyped sheet_props, untyped sheet_fmt, untyped sheet_sv, untyped sheet_fp, untyped sheet_sel, untyped sheet_po, untyped sheet_pm, untyped sheet_ps, untyped sheet_hf, untyped sheet_rb, untyped sheet_cb, untyped sheet_dv, untyped sheet_cf, ?untyped? sst, ?untyped sheet_tables, ?::Integer hyperlink_count, ?has_drawing: bool, ?has_comments: bool, ?sheet_prot: untyped?, ?vml_rid: untyped?, ?phonetic_pr: untyped?, ?dv_options: ::Hash[untyped, untyped], ?prot_ranges: untyped, ?cell_watches: untyped, ?ignored_errors: untyped, ?data_consol: untyped?, ?sheet_scenarios: untyped?, ?cell_phonetic: ::Hash[untyped, untyped]) -> ::String
2540
2421
  def generate_worksheet_xml(sheet_cells, sheet_col_widths, sheet_col_attrs, sheet_row_attrs, sheet_auto_filter, sheet_filter_cols, sheet_sort, sheet_merge_cells, sheet_hyperlinks, sheet_cell_styles, sheet_props, sheet_fmt, sheet_sv, sheet_fp, sheet_sel, sheet_po, sheet_pm, sheet_ps, sheet_hf, sheet_rb, sheet_cb, sheet_dv, sheet_cf, sst = nil, sheet_tables = [], hyperlink_count = 0, has_drawing: false, has_comments: false, sheet_prot: nil, vml_rid: nil, phonetic_pr: nil, dv_options: {}, prot_ranges: [], cell_watches: [], ignored_errors: [], data_consol: nil, sheet_scenarios: nil, cell_phonetic: {})
2541
2422
  needs_r_ns = !sheet_hyperlinks.empty? || sheet_tables.any? || has_drawing || has_comments
2542
- worksheet_attrs = %(xmlns="#{SSML_NS}")
2543
- worksheet_attrs << %( xmlns:r="#{DOC_REL_NS}") if needs_r_ns
2544
- parts = [
2545
- XML_HEADER,
2546
- "<worksheet #{worksheet_attrs}>"
2547
- ]
2548
-
2549
- # Emit <sheetPr> if sheet properties are defined.
2550
- unless sheet_props.empty?
2551
- sp_attrs = []
2552
- sp_attrs << 'syncHorizontal="1"' if sheet_props[:sync_horizontal]
2553
- sp_attrs << 'syncVertical="1"' if sheet_props[:sync_vertical]
2554
- sp_attrs << %(syncRef="#{xml_escape(sheet_props[:sync_ref])}") if sheet_props[:sync_ref]
2555
- sp_attrs << 'transitionEvaluation="1"' if sheet_props[:transition_evaluation]
2556
- sp_attrs << 'transitionEntry="1"' if sheet_props[:transition_entry]
2557
- sp_attrs << %(codeName="#{xml_escape(sheet_props[:code_name])}") if sheet_props[:code_name]
2558
- sp_attrs << 'filterMode="1"' if sheet_props[:filter_mode]
2559
- sp_attrs << 'published="0"' if sheet_props[:published] == false
2560
- sp_attrs << 'enableFormatConditionsCalculation="0"' if sheet_props[:enable_format_conditions_calculation] == false
2561
- sp_children = []
2562
- tc = sheet_props[:tab_color]
2563
- if tc.is_a?(Hash)
2564
- tc_attrs = []
2565
- tc_attrs << 'auto="1"' if tc[:auto]
2566
- tc_attrs << %(indexed="#{xml_escape(tc[:indexed])}") if tc[:indexed]
2567
- tc_attrs << %(rgb="#{xml_escape(tc[:rgb].to_s.delete_prefix("#"))}") if tc[:rgb]
2568
- tc_attrs << %(theme="#{xml_escape(tc[:theme])}") if tc[:theme]
2569
- tc_attrs << %(tint="#{xml_escape(tc[:tint])}") if tc[:tint]
2570
- sp_children << "<tabColor #{tc_attrs.join(" ")}/>" unless tc_attrs.empty?
2571
- elsif tc
2572
- sp_children << %(<tabColor rgb="#{xml_escape(tc.to_s.delete_prefix("#"))}"/>)
2573
- elsif sheet_props[:tab_color_theme]
2574
- tc_attrs = [%(theme="#{xml_escape(sheet_props[:tab_color_theme])}")]
2575
- tc_attrs << %(tint="#{xml_escape(sheet_props[:tab_color_tint])}") if sheet_props[:tab_color_tint]
2576
- sp_children << "<tabColor #{tc_attrs.join(" ")}/>"
2577
- elsif sheet_props[:tab_color_indexed]
2578
- sp_children << %(<tabColor indexed="#{xml_escape(sheet_props[:tab_color_indexed])}"/>)
2579
- elsif sheet_props[:tab_color_auto]
2580
- sp_children << '<tabColor auto="1"/>'
2581
- end
2582
- sb = sheet_props[:summary_below]
2583
- sr = sheet_props[:summary_right]
2584
- as = sheet_props[:apply_styles]
2585
- sos = sheet_props[:show_outline_symbols]
2586
- unless sb.nil? && sr.nil? && as.nil? && sos.nil?
2587
- outline_attrs = []
2588
- outline_attrs << %(applyStyles="#{as ? 1 : 0}") unless as.nil?
2589
- outline_attrs << %(summaryBelow="#{sb ? 1 : 0}") unless sb.nil?
2590
- outline_attrs << %(summaryRight="#{sr ? 1 : 0}") unless sr.nil?
2591
- outline_attrs << %(showOutlineSymbols="#{sos ? 1 : 0}") unless sos.nil?
2592
- sp_children << "<outlinePr #{outline_attrs.join(" ")}/>"
2593
- end
2594
- psp = sheet_props[:page_setup_properties] || sheet_props[:page_setup_pr]
2595
- ftp = sheet_props[:fit_to_page]
2596
- ftp = psp[:fit_to_page] if ftp.nil? && psp.is_a?(Hash)
2597
- apb = sheet_props[:auto_page_breaks]
2598
- apb = psp[:auto_page_breaks] if apb.nil? && psp.is_a?(Hash)
2599
- unless ftp.nil? && apb.nil?
2600
- psp_attrs = []
2601
- psp_attrs << %(fitToPage="#{ftp ? 1 : 0}") unless ftp.nil?
2602
- psp_attrs << %(autoPageBreaks="#{apb ? 1 : 0}") unless apb.nil?
2603
- sp_children << "<pageSetUpPr #{psp_attrs.join(" ")}/>"
2604
- end
2605
- if !sp_children.empty? || !sp_attrs.empty?
2606
- sp_open = sp_attrs.empty? ? "<sheetPr>" : "<sheetPr #{sp_attrs.join(" ")}>"
2607
- parts << sp_open
2608
- parts.concat(sp_children)
2609
- parts << "</sheetPr>"
2610
- end
2611
- end
2612
-
2613
- # Emit <dimension> computed from cell addresses.
2614
- parts << %(<dimension ref="#{xml_escape(compute_dimension(sheet_cells))}"/>) unless sheet_cells.empty?
2615
-
2616
- # Emit <sheetViews> if sheet view properties, freeze pane, or selection are defined.
2617
- if !sheet_sv.empty? || sheet_fp || sheet_sel
2618
- parts << "<sheetViews>"
2619
- sv_attrs = []
2620
- wp = sheet_sv[:window_protection]
2621
- sv_attrs << %(windowProtection="#{wp ? 1 : 0}") unless wp.nil?
2622
- sf = sheet_sv[:show_formulas]
2623
- sv_attrs << %(showFormulas="#{sf ? 1 : 0}") unless sf.nil?
2624
- sgl = sheet_sv[:show_grid_lines]
2625
- sv_attrs << %(showGridLines="#{sgl ? 1 : 0}") unless sgl.nil?
2626
- srch = sheet_sv[:show_row_col_headers]
2627
- sv_attrs << %(showRowColHeaders="#{srch ? 1 : 0}") unless srch.nil?
2628
- sz = sheet_sv[:show_zeros]
2629
- sv_attrs << %(showZeros="#{sz ? 1 : 0}") unless sz.nil?
2630
- rtl = sheet_sv[:right_to_left]
2631
- sv_attrs << %(rightToLeft="#{rtl ? 1 : 0}") unless rtl.nil?
2632
- sv_attrs << 'tabSelected="1"' if sheet_sv[:tab_selected]
2633
- sr = sheet_sv[:show_ruler]
2634
- sv_attrs << %(showRuler="#{sr ? 1 : 0}") unless sr.nil?
2635
- sos = sheet_sv[:show_outline_symbols]
2636
- sv_attrs << %(showOutlineSymbols="#{sos ? 1 : 0}") unless sos.nil?
2637
- dgc = sheet_sv[:default_grid_color]
2638
- sv_attrs << %(defaultGridColor="#{dgc ? 1 : 0}") unless dgc.nil?
2639
- sws = sheet_sv[:show_white_space]
2640
- sv_attrs << %(showWhiteSpace="#{sws ? 1 : 0}") unless sws.nil?
2641
- sv_attrs << %(view="#{xml_escape(sheet_sv[:view])}") if sheet_sv[:view]
2642
- sv_attrs << %(topLeftCell="#{xml_escape(sheet_sv[:top_left_cell])}") if sheet_sv[:top_left_cell]
2643
- sv_attrs << %(colorId="#{xml_escape(sheet_sv[:color_id])}") if sheet_sv[:color_id]
2644
- zs = sheet_sv[:zoom_scale]
2645
- sv_attrs << %(zoomScale="#{xml_escape(zs)}") if zs
2646
- sv_attrs << %(zoomScaleNormal="#{xml_escape(sheet_sv[:zoom_scale_normal])}") if sheet_sv[:zoom_scale_normal]
2647
- sv_attrs << %(zoomScaleSheetLayoutView="#{xml_escape(sheet_sv[:zoom_scale_sheet_layout_view])}") if sheet_sv[:zoom_scale_sheet_layout_view]
2648
- sv_attrs << %(zoomScalePageLayoutView="#{xml_escape(sheet_sv[:zoom_scale_page_layout_view])}") if sheet_sv[:zoom_scale_page_layout_view]
2649
- sv_attrs << 'workbookViewId="0"'
2650
- parts << "<sheetView #{sv_attrs.join(" ")}>"
2651
-
2652
- if sheet_fp && sheet_fp[:state] == :split
2653
- pane_attrs = []
2654
- pane_attrs << %(xSplit="#{xml_escape(sheet_fp[:x_split])}") if sheet_fp[:x_split].to_i.positive?
2655
- pane_attrs << %(ySplit="#{xml_escape(sheet_fp[:y_split])}") if sheet_fp[:y_split].to_i.positive?
2656
- pane_attrs << %(topLeftCell="#{xml_escape(sheet_fp[:top_left_cell])}") if sheet_fp[:top_left_cell]
2657
- has_x = sheet_fp[:x_split].to_i.positive?
2658
- has_y = sheet_fp[:y_split].to_i.positive?
2659
- active_pane = if has_y && has_x
2660
- "bottomRight"
2661
- elsif has_y
2662
- "bottomLeft"
2663
- else
2664
- "topRight"
2665
- end
2666
- pane_attrs << %(activePane="#{xml_escape(active_pane)}")
2667
- parts << "<pane #{pane_attrs.join(" ")}/>"
2668
- elsif sheet_fp
2669
- fp_col = sheet_fp[:column] || sheet_fp[:col] || 0
2670
- if sheet_fp[:row].to_i.positive? || fp_col.to_i.positive?
2671
- top_left = "#{index_to_column_letter(fp_col.to_i + 1)}#{sheet_fp[:row].to_i + 1}"
2672
- pane_attrs = []
2673
- pane_attrs << %(ySplit="#{xml_escape(sheet_fp[:row])}") if sheet_fp[:row].to_i.positive?
2674
- pane_attrs << %(xSplit="#{xml_escape(fp_col)}") if fp_col.to_i.positive?
2675
- pane_attrs << %(topLeftCell="#{xml_escape(top_left)}")
2676
- active_pane = if sheet_fp[:row].to_i.positive? && fp_col.to_i.positive?
2677
- "bottomRight"
2678
- elsif sheet_fp[:row].to_i.positive?
2679
- "bottomLeft"
2680
- else
2681
- "topRight"
2682
- end
2683
- pane_attrs << %(activePane="#{xml_escape(active_pane)}")
2684
- pane_attrs << 'state="frozen"'
2685
- parts << "<pane #{pane_attrs.join(" ")}/>"
2423
+ XmlBuilder.build(declaration: :plain) do |xml|
2424
+ xml.tag("worksheet", { xmlns: SSML_NS, "xmlns:r": (DOC_REL_NS if needs_r_ns) }) do
2425
+ write_sheet_pr_xml(xml, sheet_props) unless sheet_props.empty?
2426
+ xml.empty_tag("dimension", { ref: compute_dimension(sheet_cells) }) unless sheet_cells.empty?
2427
+ write_sheet_views_xml(xml, sheet_sv, sheet_fp, sheet_sel) if !sheet_sv.empty? || sheet_fp || sheet_sel
2428
+
2429
+ unless sheet_fmt.empty?
2430
+ xml.empty_tag(
2431
+ "sheetFormatPr",
2432
+ {
2433
+ defaultRowHeight: sheet_fmt[:default_row_height],
2434
+ defaultColWidth: sheet_fmt[:default_col_width],
2435
+ baseColWidth: sheet_fmt[:base_col_width],
2436
+ outlineLevelRow: sheet_fmt[:outline_level_row],
2437
+ outlineLevelCol: sheet_fmt[:outline_level_col],
2438
+ customHeight: (1 if sheet_fmt[:custom_height]),
2439
+ zeroHeight: (1 if sheet_fmt[:zero_height]),
2440
+ thickTop: (1 if sheet_fmt[:thick_top]),
2441
+ thickBottom: (1 if sheet_fmt[:thick_bottom])
2442
+ }
2443
+ )
2686
2444
  end
2687
- end
2688
-
2689
- if sheet_sel
2690
- sel_attrs = []
2691
- sel_attrs << %(pane="#{xml_escape(sheet_sel[:pane])}") if sheet_sel[:pane]
2692
- sel_attrs << %(activeCell="#{xml_escape(sheet_sel[:active_cell])}") if sheet_sel[:active_cell]
2693
- sel_attrs << %(activeCellId="#{xml_escape(sheet_sel[:active_cell_id])}") if sheet_sel[:active_cell_id]
2694
- sel_attrs << %(sqref="#{xml_escape(sheet_sel[:sqref])}") if sheet_sel[:sqref]
2695
- parts << "<selection #{sel_attrs.join(" ")}/>"
2696
- end
2697
-
2698
- parts << "</sheetView>"
2699
- parts << "</sheetViews>"
2700
- end
2701
2445
 
2702
- # Emit <sheetFormatPr> if sheet format properties are defined.
2703
- unless sheet_fmt.empty?
2704
- fmt_attrs = []
2705
- fmt_attrs << %(defaultRowHeight="#{xml_escape(sheet_fmt[:default_row_height])}") if sheet_fmt[:default_row_height]
2706
- fmt_attrs << %(defaultColWidth="#{xml_escape(sheet_fmt[:default_col_width])}") if sheet_fmt[:default_col_width]
2707
- fmt_attrs << %(baseColWidth="#{xml_escape(sheet_fmt[:base_col_width])}") if sheet_fmt[:base_col_width]
2708
- fmt_attrs << %(outlineLevelRow="#{xml_escape(sheet_fmt[:outline_level_row])}") if sheet_fmt[:outline_level_row]
2709
- fmt_attrs << %(outlineLevelCol="#{xml_escape(sheet_fmt[:outline_level_col])}") if sheet_fmt[:outline_level_col]
2710
- fmt_attrs << 'customHeight="1"' if sheet_fmt[:custom_height]
2711
- fmt_attrs << 'zeroHeight="1"' if sheet_fmt[:zero_height]
2712
- fmt_attrs << 'thickTop="1"' if sheet_fmt[:thick_top]
2713
- fmt_attrs << 'thickBottom="1"' if sheet_fmt[:thick_bottom]
2714
- parts << "<sheetFormatPr #{fmt_attrs.join(" ")}/>"
2715
- end
2716
-
2717
- # Emit <cols> if column widths or column attributes are defined.
2718
- all_cols = sheet_col_widths.keys | sheet_col_attrs.keys
2719
- unless all_cols.empty?
2720
- parts << "<cols>"
2721
- all_cols.sort_by { |col| column_letter_to_index(col) }.each do |col_letter|
2722
- idx = column_letter_to_index(col_letter)
2723
- width = sheet_col_widths[col_letter]
2724
- ca = sheet_col_attrs[col_letter] || {}
2725
- col_attrs = %(min="#{xml_escape(idx)}" max="#{xml_escape(idx)}")
2726
- col_attrs << %( width="#{xml_escape(width)}" customWidth="1") if width
2727
- col_attrs << ' hidden="1"' if ca[:hidden]
2728
- col_attrs << ' bestFit="1"' if ca[:best_fit]
2729
- col_attrs << %( outlineLevel="#{xml_escape(ca[:outline_level])}") if ca[:outline_level]
2730
- col_attrs << ' collapsed="1"' if ca[:collapsed]
2731
- col_attrs << %( style="#{xml_escape(ca[:style])}") if ca[:style]
2732
- col_attrs << ' phonetic="1"' if ca[:phonetic]
2733
- parts << "<col #{col_attrs}/>"
2734
- end
2735
- parts << "</cols>"
2736
- end
2737
-
2738
- parts << "<sheetData>"
2739
-
2740
- # Group cells by row number.
2741
- cells_by_row = {}
2742
- sheet_cells.each do |address, value|
2743
- row_num = extract_row_number(address)
2744
- col_letter = extract_column_letter(address)
2745
- cells_by_row[row_num] ||= {}
2746
- cells_by_row[row_num][col_letter] = value
2747
- end
2748
-
2749
- # Include rows that have attributes but no cells.
2750
- sheet_row_attrs.each_key { |rn| cells_by_row[rn] ||= {} }
2751
-
2752
- # Emit rows in ascending order.
2753
- cells_by_row.sort.each do |row_num, row_cells|
2754
- attrs = %(r="#{xml_escape(row_num)}")
2755
- ra = sheet_row_attrs[row_num]
2756
- if ra
2757
- attrs << %( ht="#{xml_escape(ra[:height])}" customHeight="1") if ra[:height]
2758
- attrs << ' hidden="1"' if ra[:hidden]
2759
- attrs << %( outlineLevel="#{xml_escape(ra[:outline_level])}") if ra[:outline_level]
2760
- attrs << ' collapsed="1"' if ra[:collapsed]
2761
- attrs << %( s="#{xml_escape(ra[:style])}" customFormat="1") if ra.key?(:style)
2762
- attrs << ' thickTop="1"' if ra[:thick_top]
2763
- attrs << ' thickBot="1"' if ra[:thick_bot]
2764
- attrs << ' ph="1"' if ra[:ph]
2765
- end
2766
- parts << "<row #{attrs}>"
2767
- row_cells.sort_by { |col, _| column_letter_to_index(col) }.each do |col_letter, value|
2768
- cell_ref = "#{col_letter}#{row_num}"
2769
- style_idx = resolve_style_index(sheet_cell_styles[cell_ref])
2770
- parts << cell_xml(cell_ref, value, style_idx, sst, ph: cell_phonetic[cell_ref])
2771
- end
2772
- parts << "</row>"
2773
- end
2774
-
2775
- parts << "</sheetData>"
2776
-
2777
- # Emit <sheetCalcPr> if fullCalcOnLoad is set.
2778
- parts << '<sheetCalcPr fullCalcOnLoad="1"/>' if sheet_props[:full_calc_on_load]
2779
-
2780
- # Emit <sheetProtection> if defined.
2781
- if sheet_prot
2782
- sp_attrs = []
2783
- sp_attrs << 'sheet="1"' if sheet_prot[:sheet] != false
2784
- sp_attrs << 'objects="1"' if sheet_prot[:objects]
2785
- sp_attrs << 'scenarios="1"' if sheet_prot[:scenarios]
2786
- sp_attrs << 'formatCells="0"' if sheet_prot[:format_cells] == false
2787
- sp_attrs << 'formatColumns="0"' if sheet_prot[:format_columns] == false
2788
- sp_attrs << 'formatRows="0"' if sheet_prot[:format_rows] == false
2789
- sp_attrs << 'insertColumns="0"' if sheet_prot[:insert_columns] == false
2790
- sp_attrs << 'insertRows="0"' if sheet_prot[:insert_rows] == false
2791
- sp_attrs << 'insertHyperlinks="0"' if sheet_prot[:insert_hyperlinks] == false
2792
- sp_attrs << 'deleteColumns="0"' if sheet_prot[:delete_columns] == false
2793
- sp_attrs << 'deleteRows="0"' if sheet_prot[:delete_rows] == false
2794
- sp_attrs << 'selectLockedCells="1"' if sheet_prot[:select_locked_cells]
2795
- sp_attrs << 'sort="0"' if sheet_prot[:sort] == false
2796
- sp_attrs << 'autoFilter="0"' if sheet_prot[:auto_filter] == false
2797
- sp_attrs << 'pivotTables="0"' if sheet_prot[:pivot_tables] == false
2798
- sp_attrs << 'selectUnlockedCells="1"' if sheet_prot[:select_unlocked_cells]
2799
- if sheet_prot[:algorithm_name]
2800
- sp_attrs << %(algorithmName="#{xml_escape(sheet_prot[:algorithm_name])}")
2801
- sp_attrs << %(hashValue="#{xml_escape(sheet_prot[:hash_value])}") if sheet_prot[:hash_value]
2802
- sp_attrs << %(saltValue="#{xml_escape(sheet_prot[:salt_value])}") if sheet_prot[:salt_value]
2803
- sp_attrs << %(spinCount="#{xml_escape(sheet_prot[:spin_count])}") if sheet_prot[:spin_count]
2804
- elsif sheet_prot[:password]
2805
- sp_attrs << %(password="#{xml_escape(sheet_prot[:password])}")
2806
- end
2807
- parts << "<sheetProtection #{sp_attrs.join(" ")}/>"
2808
- end
2809
-
2810
- # Emit <protectedRanges> if defined.
2811
- unless prot_ranges.empty?
2812
- parts << "<protectedRanges>"
2813
- prot_ranges.each do |pr|
2814
- pr_attrs = [%(sqref="#{xml_escape(pr[:sqref])}"), %(name="#{xml_escape(pr[:name])}")]
2815
- if pr[:algorithm_name]
2816
- pr_attrs << %(algorithmName="#{xml_escape(pr[:algorithm_name])}")
2817
- pr_attrs << %(hashValue="#{xml_escape(pr[:hash_value])}") if pr[:hash_value]
2818
- pr_attrs << %(saltValue="#{xml_escape(pr[:salt_value])}") if pr[:salt_value]
2819
- pr_attrs << %(spinCount="#{xml_escape(pr[:spin_count])}") if pr[:spin_count]
2820
- end
2821
- sds = pr[:security_descriptors] || []
2822
- if sds.empty?
2823
- parts << "<protectedRange #{pr_attrs.join(" ")}/>"
2824
- else
2825
- parts << "<protectedRange #{pr_attrs.join(" ")}>"
2826
- sds.each { |sd| parts << "<securityDescriptor>#{xml_escape(sd)}</securityDescriptor>" }
2827
- parts << "</protectedRange>"
2446
+ all_cols = sheet_col_widths.keys | sheet_col_attrs.keys
2447
+ unless all_cols.empty?
2448
+ xml.tag("cols") do
2449
+ all_cols.sort_by { |col| column_letter_to_index(col) }.each do |col_letter|
2450
+ idx = column_letter_to_index(col_letter)
2451
+ width = sheet_col_widths[col_letter]
2452
+ ca = sheet_col_attrs[col_letter] || {}
2453
+ xml.empty_tag(
2454
+ "col",
2455
+ {
2456
+ min: idx,
2457
+ max: idx,
2458
+ width: width,
2459
+ customWidth: (1 if width),
2460
+ hidden: (1 if ca[:hidden]),
2461
+ bestFit: (1 if ca[:best_fit]),
2462
+ outlineLevel: ca[:outline_level],
2463
+ collapsed: (1 if ca[:collapsed]),
2464
+ style: ca[:style],
2465
+ phonetic: (1 if ca[:phonetic])
2466
+ }
2467
+ )
2468
+ end
2469
+ end
2828
2470
  end
2829
- end
2830
- parts << "</protectedRanges>"
2831
- end
2832
2471
 
2833
- # Emit <scenarios> if defined.
2834
- if sheet_scenarios
2835
- sc_attrs = []
2836
- sc_attrs << %(current="#{xml_escape(sheet_scenarios[:current])}") if sheet_scenarios[:current]
2837
- sc_attrs << %(show="#{xml_escape(sheet_scenarios[:show])}") if sheet_scenarios[:show]
2838
- sc_attrs << %(sqref="#{xml_escape(sheet_scenarios[:sqref])}") if sheet_scenarios[:sqref]
2839
- items = sheet_scenarios[:scenarios] || []
2840
- sc_attr_str = sc_attrs.empty? ? "" : " #{sc_attrs.join(" ")}"
2841
- parts << "<scenarios#{sc_attr_str}>"
2842
- items.each do |sc|
2843
- s_attrs = [%(name="#{xml_escape(sc[:name])}")]
2844
- s_attrs << 'locked="1"' if sc[:locked]
2845
- s_attrs << 'hidden="1"' if sc[:hidden]
2846
- s_attrs << %(count="#{sc[:input_cells].size}") if sc[:input_cells]&.any?
2847
- s_attrs << %(user="#{xml_escape(sc[:user])}") if sc[:user]
2848
- s_attrs << %(comment="#{xml_escape(sc[:comment])}") if sc[:comment]
2849
- parts << "<scenario #{s_attrs.join(" ")}>"
2850
- (sc[:input_cells] || []).each do |ic|
2851
- ic_attrs = [%(r="#{xml_escape(ic[:r])}"), %(val="#{xml_escape(ic[:val].to_s)}")]
2852
- ic_attrs << 'deleted="1"' if ic[:deleted]
2853
- ic_attrs << 'undone="1"' if ic[:undone]
2854
- ic_attrs << %(numFmtId="#{xml_escape(ic[:num_fmt_id])}") if ic[:num_fmt_id]
2855
- parts << "<inputCells #{ic_attrs.join(" ")}/>"
2856
- end
2857
- parts << "</scenario>"
2858
- end
2859
- parts << "</scenarios>"
2860
- end
2472
+ write_sheet_data_xml(xml, sheet_cells, sheet_row_attrs, sheet_cell_styles, sst, cell_phonetic)
2473
+ xml.empty_tag("sheetCalcPr", { fullCalcOnLoad: 1 }) if sheet_props[:full_calc_on_load]
2474
+ write_sheet_protection_xml(xml, sheet_prot) if sheet_prot
2475
+ write_protected_ranges_xml(xml, prot_ranges) unless prot_ranges.empty?
2476
+ write_scenarios_xml(xml, sheet_scenarios) if sheet_scenarios
2861
2477
 
2862
- # Emit <autoFilter> with optional filterColumns.
2863
- if sheet_auto_filter
2864
- if sheet_filter_cols.empty?
2865
- parts << %(<autoFilter ref="#{xml_escape(sheet_auto_filter)}"/>)
2866
- else
2867
- parts << %(<autoFilter ref="#{xml_escape(sheet_auto_filter)}">)
2868
- sheet_filter_cols.sort.each do |col_id, filter|
2869
- fc_attrs = %( colId="#{xml_escape(col_id)}")
2870
- fc_attrs << ' hiddenButton="1"' if filter[:hidden_button]
2871
- fc_attrs << ' showButton="0"' if filter[:show_button] == false
2872
- parts << "<filterColumn#{fc_attrs}>"
2873
- parts << emit_filter_xml(filter)
2874
- parts << "</filterColumn>"
2478
+ if sheet_auto_filter
2479
+ if sheet_filter_cols.empty?
2480
+ xml.empty_tag("autoFilter", { ref: sheet_auto_filter })
2481
+ else
2482
+ xml.tag("autoFilter", { ref: sheet_auto_filter }) do
2483
+ sheet_filter_cols.sort.each do |col_id, filter|
2484
+ xml.tag(
2485
+ "filterColumn",
2486
+ {
2487
+ colId: col_id,
2488
+ hiddenButton: (1 if filter[:hidden_button]),
2489
+ showButton: (0 if filter[:show_button] == false)
2490
+ }
2491
+ ) do
2492
+ write_filter_xml(xml, filter)
2493
+ end
2494
+ end
2495
+ end
2496
+ end
2875
2497
  end
2876
- parts << "</autoFilter>"
2877
- end
2878
- end
2879
2498
 
2880
- # Emit <sortState> if defined.
2881
- if sheet_sort
2882
- ss_attrs = %( ref="#{xml_escape(sheet_sort[:ref])}")
2883
- ss_attrs << ' columnSort="1"' if sheet_sort[:column_sort]
2884
- ss_attrs << ' caseSensitive="1"' if sheet_sort[:case_sensitive]
2885
- ss_attrs << %( sortMethod="#{xml_escape(sheet_sort[:sort_method])}") if sheet_sort[:sort_method]
2886
- parts << "<sortState#{ss_attrs}>"
2887
- sheet_sort[:sort_conditions].each do |sc|
2888
- sc_attrs = %(ref="#{xml_escape(sc[:ref])}")
2889
- sc_attrs << ' descending="1"' if sc[:descending]
2890
- sc_attrs << %( sortBy="#{xml_escape(sc[:sort_by])}") if sc[:sort_by]
2891
- sc_attrs << %( customList="#{xml_escape(sc[:custom_list])}") if sc[:custom_list]
2892
- sc_attrs << %( dxfId="#{xml_escape(sc[:dxf_id])}") if sc[:dxf_id]
2893
- sc_attrs << %( iconSet="#{xml_escape(sc[:icon_set])}") if sc[:icon_set]
2894
- sc_attrs << %( iconId="#{xml_escape(sc[:icon_id])}") if sc[:icon_id]
2895
- parts << "<sortCondition #{sc_attrs}/>"
2896
- end
2897
- parts << "</sortState>"
2898
- end
2899
-
2900
- # Emit <dataConsolidate> if defined.
2901
- if data_consol
2902
- dc_attrs = []
2903
- dc_attrs << %(function="#{xml_escape(data_consol[:function])}") if data_consol[:function] && data_consol[:function] != "sum"
2904
- dc_attrs << 'startLabels="1"' if data_consol[:start_labels]
2905
- dc_attrs << 'leftLabels="1"' if data_consol[:left_labels]
2906
- dc_attrs << 'topLabels="1"' if data_consol[:top_labels]
2907
- dc_attrs << 'link="1"' if data_consol[:link]
2908
- refs = data_consol[:data_refs] || []
2909
- dc_attr_str = dc_attrs.empty? ? "" : " #{dc_attrs.join(" ")}"
2910
- if refs.empty?
2911
- parts << "<dataConsolidate#{dc_attr_str}/>"
2912
- else
2913
- parts << "<dataConsolidate#{dc_attr_str}>"
2914
- parts << %(<dataRefs count="#{refs.size}">)
2915
- refs.each do |r|
2916
- ref_attrs = []
2917
- ref_attrs << %(ref="#{xml_escape(r[:ref])}") if r[:ref]
2918
- ref_attrs << %(name="#{xml_escape(r[:name])}") if r[:name]
2919
- ref_attrs << %(sheet="#{xml_escape(r[:sheet])}") if r[:sheet]
2920
- parts << "<dataRef #{ref_attrs.join(" ")}/>"
2499
+ if sheet_sort
2500
+ xml.tag(
2501
+ "sortState",
2502
+ {
2503
+ ref: sheet_sort[:ref] || "",
2504
+ columnSort: (1 if sheet_sort[:column_sort]),
2505
+ caseSensitive: (1 if sheet_sort[:case_sensitive]),
2506
+ sortMethod: sheet_sort[:sort_method]
2507
+ }
2508
+ ) do
2509
+ sheet_sort[:sort_conditions].each do |sc|
2510
+ xml.empty_tag(
2511
+ "sortCondition",
2512
+ {
2513
+ ref: sc[:ref] || "",
2514
+ descending: (1 if sc[:descending]),
2515
+ sortBy: sc[:sort_by],
2516
+ customList: sc[:custom_list],
2517
+ dxfId: sc[:dxf_id],
2518
+ iconSet: sc[:icon_set],
2519
+ iconId: sc[:icon_id]
2520
+ }
2521
+ )
2522
+ end
2523
+ end
2921
2524
  end
2922
- parts << "</dataRefs>"
2923
- parts << "</dataConsolidate>"
2924
- end
2925
- end
2926
-
2927
- # Emit <mergeCells> if merge ranges are defined.
2928
- unless sheet_merge_cells.empty?
2929
- parts << %(<mergeCells count="#{sheet_merge_cells.size}">)
2930
- sheet_merge_cells.each { |ref| parts << %(<mergeCell ref="#{xml_escape(ref)}"/>) }
2931
- parts << "</mergeCells>"
2932
- end
2933
2525
 
2934
- # Emit <phoneticPr> if defined.
2935
- if phonetic_pr
2936
- pp_attrs = []
2937
- pp_attrs << %(fontId="#{xml_escape(phonetic_pr[:font_id])}") if phonetic_pr[:font_id]
2938
- pp_attrs << %(type="#{xml_escape(phonetic_pr[:type])}") if phonetic_pr[:type]
2939
- pp_attrs << %(alignment="#{xml_escape(phonetic_pr[:alignment])}") if phonetic_pr[:alignment]
2940
- parts << "<phoneticPr #{pp_attrs.join(" ")}/>"
2941
- end
2526
+ write_data_consolidate_xml(xml, data_consol) if data_consol
2942
2527
 
2943
- # Emit <hyperlinks> if hyperlinks are defined.
2944
- unless sheet_hyperlinks.empty?
2945
- parts << "<hyperlinks>"
2946
- ext_rid = 0
2947
- sheet_hyperlinks.each do |(cell_ref, link)|
2948
- attrs = %(ref="#{xml_escape(cell_ref)}")
2949
- if link[:url]
2950
- ext_rid += 1
2951
- attrs << %( r:id="rId#{xml_escape(ext_rid)}")
2528
+ unless sheet_merge_cells.empty?
2529
+ xml.tag("mergeCells", { count: sheet_merge_cells.size }) do
2530
+ sheet_merge_cells.each { |ref| xml.empty_tag("mergeCell", { ref: ref || "" }) }
2531
+ end
2952
2532
  end
2953
- attrs << %( display="#{xml_escape(link[:display])}") if link[:display]
2954
- attrs << %( tooltip="#{xml_escape(link[:tooltip])}") if link[:tooltip]
2955
- attrs << %( location="#{xml_escape(link[:location])}") if link[:location]
2956
- parts << %(<hyperlink #{attrs}/>)
2957
- end
2958
- parts << "</hyperlinks>"
2959
- end
2960
2533
 
2961
- # Emit <conditionalFormatting> if defined.
2962
- unless sheet_cf.empty?
2963
- sheet_cf.group_by { |cf| cf[:sqref] }.each do |sqref, rules|
2964
- cf_attrs = %( sqref="#{xml_escape(sqref)}")
2965
- cf_attrs << ' pivot="1"' if rules.any? { |r| r[:pivot] }
2966
- parts << "<conditionalFormatting#{cf_attrs}>"
2967
- rules.each do |cf|
2968
- emit_cf_rule(parts, cf)
2534
+ if phonetic_pr
2535
+ xml.empty_tag(
2536
+ "phoneticPr",
2537
+ {
2538
+ fontId: phonetic_pr[:font_id],
2539
+ type: phonetic_pr[:type],
2540
+ alignment: phonetic_pr[:alignment]
2541
+ }
2542
+ )
2969
2543
  end
2970
- parts << "</conditionalFormatting>"
2971
- end
2972
- end
2973
2544
 
2974
- # Emit <dataValidations> if defined.
2975
- unless sheet_dv.empty?
2976
- valid_dv = sheet_dv.reject { |dv| dv[:sqref].nil? || dv[:sqref].to_s.empty? }
2977
- unless valid_dv.empty?
2978
- dv_container_attrs = %( count="#{valid_dv.size}")
2979
- dv_container_attrs << ' disablePrompts="1"' if dv_options[:disable_prompts]
2980
- dv_container_attrs << %( xWindow="#{xml_escape(dv_options[:x_window])}") if dv_options[:x_window]
2981
- dv_container_attrs << %( yWindow="#{xml_escape(dv_options[:y_window])}") if dv_options[:y_window]
2982
- parts << "<dataValidations#{dv_container_attrs}>"
2983
- valid_dv.each do |dv|
2984
- dv_attrs = %(sqref="#{xml_escape(dv[:sqref])}")
2985
- dv_attrs << %( type="#{xml_escape(dv[:type])}") if dv[:type]
2986
- dv_attrs << %( operator="#{xml_escape(dv[:operator])}") if dv[:operator]
2987
- dv_attrs << %( errorStyle="#{xml_escape(dv[:error_style])}") if dv[:error_style]
2988
- dv_attrs << ' allowBlank="1"' if dv[:allow_blank]
2989
- dv_attrs << ' showInputMessage="1"' if dv[:show_input_message]
2990
- dv_attrs << ' showErrorMessage="1"' if dv[:show_error_message]
2991
- dv_attrs << %( errorTitle="#{xml_escape(dv[:error_title])}") if dv[:error_title]
2992
- dv_attrs << %( error="#{xml_escape(dv[:error])}") if dv[:error]
2993
- dv_attrs << %( promptTitle="#{xml_escape(dv[:prompt_title])}") if dv[:prompt_title]
2994
- dv_attrs << %( prompt="#{xml_escape(dv[:prompt])}") if dv[:prompt]
2995
- dv_attrs << ' showDropDown="1"' if dv[:show_drop_down]
2996
- dv_attrs << %( imeMode="#{xml_escape(dv[:ime_mode])}") if dv[:ime_mode]
2997
- if dv[:formula1] || dv[:formula2]
2998
- parts << "<dataValidation #{dv_attrs}>"
2999
- parts << "<formula1>#{xml_escape(dv[:formula1])}</formula1>" if dv[:formula1]
3000
- parts << "<formula2>#{xml_escape(dv[:formula2])}</formula2>" if dv[:formula2]
3001
- parts << "</dataValidation>"
3002
- else
3003
- parts << "<dataValidation #{dv_attrs}/>"
2545
+ unless sheet_hyperlinks.empty?
2546
+ xml.tag("hyperlinks") do
2547
+ ext_rid = 0
2548
+ sheet_hyperlinks.each do |(cell_ref, link)|
2549
+ rid = if link[:url]
2550
+ ext_rid += 1
2551
+ "rId#{ext_rid}"
2552
+ end
2553
+ xml.empty_tag(
2554
+ "hyperlink",
2555
+ {
2556
+ ref: cell_ref || "",
2557
+ "r:id": rid,
2558
+ display: link[:display],
2559
+ tooltip: link[:tooltip],
2560
+ location: link[:location]
2561
+ }
2562
+ )
2563
+ end
3004
2564
  end
3005
2565
  end
3006
- parts << "</dataValidations>"
3007
- end
3008
- end
3009
2566
 
3010
- # Emit <printOptions> if defined.
3011
- unless sheet_po.empty?
3012
- po_attrs = []
3013
- po_attrs << 'gridLines="1"' if sheet_po[:grid_lines]
3014
- po_attrs << 'headings="1"' if sheet_po[:headings]
3015
- po_attrs << 'horizontalCentered="1"' if sheet_po[:horizontal_centered]
3016
- po_attrs << 'verticalCentered="1"' if sheet_po[:vertical_centered]
3017
- po_attrs << 'gridLinesSet="0"' if sheet_po[:grid_lines_set] == false
3018
- parts << "<printOptions #{po_attrs.join(" ")}/>" unless po_attrs.empty?
3019
- end
3020
-
3021
- # Emit <pageMargins> if defined.
3022
- if sheet_pm
3023
- pm_attrs = %w[left right top bottom header footer].filter_map do |k|
3024
- v = sheet_pm[k.to_sym]
3025
- %(#{k}="#{xml_escape(v)}") if v
3026
- end
3027
- parts << "<pageMargins #{pm_attrs.join(" ")}/>" unless pm_attrs.empty?
3028
- end
3029
-
3030
- # Emit <pageSetup> if defined.
3031
- unless sheet_ps.empty?
3032
- ps_attrs = []
3033
- ps_attrs << %(orientation="#{xml_escape(sheet_ps[:orientation])}") if sheet_ps[:orientation]
3034
- ps_attrs << %(paperSize="#{xml_escape(sheet_ps[:paper_size])}") if sheet_ps[:paper_size]
3035
- ps_attrs << %(scale="#{xml_escape(sheet_ps[:scale])}") if sheet_ps[:scale]
3036
- ps_attrs << %(fitToWidth="#{xml_escape(sheet_ps[:fit_to_width])}") if sheet_ps[:fit_to_width]
3037
- ps_attrs << %(fitToHeight="#{xml_escape(sheet_ps[:fit_to_height])}") if sheet_ps[:fit_to_height]
3038
- ps_attrs << %(pageOrder="#{xml_escape(sheet_ps[:page_order])}") if sheet_ps[:page_order]
3039
- ps_attrs << 'blackAndWhite="1"' if sheet_ps[:black_and_white]
3040
- ps_attrs << 'draft="1"' if sheet_ps[:draft]
3041
- ps_attrs << %(cellComments="#{xml_escape(sheet_ps[:cell_comments])}") if sheet_ps[:cell_comments]
3042
- ps_attrs << %(firstPageNumber="#{xml_escape(sheet_ps[:first_page_number])}") if sheet_ps[:first_page_number] && sheet_ps[:first_page_number].to_i >= 0
3043
- ps_attrs << 'useFirstPageNumber="1"' if sheet_ps[:use_first_page_number]
3044
- ps_attrs << %(horizontalDpi="#{xml_escape(sheet_ps[:horizontal_dpi])}") if sheet_ps[:horizontal_dpi].to_i.positive?
3045
- ps_attrs << %(verticalDpi="#{xml_escape(sheet_ps[:vertical_dpi])}") if sheet_ps[:vertical_dpi].to_i.positive?
3046
- ps_attrs << %(copies="#{xml_escape(sheet_ps[:copies])}") if sheet_ps[:copies]
3047
- ps_attrs << %(paperHeight="#{xml_escape(sheet_ps[:paper_height])}") if sheet_ps[:paper_height]
3048
- ps_attrs << %(paperWidth="#{xml_escape(sheet_ps[:paper_width])}") if sheet_ps[:paper_width]
3049
- ps_attrs << %(errors="#{xml_escape(sheet_ps[:errors])}") if sheet_ps[:errors]
3050
- ps_attrs << 'usePrinterDefaults="0"' if sheet_ps[:use_printer_defaults] == false
3051
- parts << "<pageSetup #{ps_attrs.join(" ")}/>" unless ps_attrs.empty?
3052
- end
2567
+ unless sheet_cf.empty?
2568
+ sheet_cf.group_by { |cf| cf[:sqref] }.each do |sqref, rules|
2569
+ xml.tag("conditionalFormatting", { sqref: sqref || "", pivot: (1 if rules.any? { |r| r[:pivot] }) }) do
2570
+ rules.each { |cf| write_cf_rule(xml, cf) }
2571
+ end
2572
+ end
2573
+ end
3053
2574
 
3054
- # Emit <headerFooter> if defined.
3055
- unless sheet_hf.empty?
3056
- hf_attrs = []
3057
- hf_attrs << 'differentFirst="1"' if sheet_hf[:different_first]
3058
- hf_attrs << 'differentOddEven="1"' if sheet_hf[:different_odd_even]
3059
- hf_attrs << 'scaleWithDoc="0"' if sheet_hf[:scale_with_doc] == false
3060
- hf_attrs << 'alignWithMargins="0"' if sheet_hf[:align_with_margins] == false
3061
- hf_tag = hf_attrs.empty? ? "<headerFooter>" : "<headerFooter #{hf_attrs.join(" ")}>"
3062
- parts << hf_tag
3063
- parts << "<oddHeader>#{xml_escape(sheet_hf[:odd_header])}</oddHeader>" if sheet_hf[:odd_header]
3064
- parts << "<oddFooter>#{xml_escape(sheet_hf[:odd_footer])}</oddFooter>" if sheet_hf[:odd_footer]
3065
- parts << "<evenHeader>#{xml_escape(sheet_hf[:even_header])}</evenHeader>" if sheet_hf[:even_header]
3066
- parts << "<evenFooter>#{xml_escape(sheet_hf[:even_footer])}</evenFooter>" if sheet_hf[:even_footer]
3067
- parts << "<firstHeader>#{xml_escape(sheet_hf[:first_header])}</firstHeader>" if sheet_hf[:first_header]
3068
- parts << "<firstFooter>#{xml_escape(sheet_hf[:first_footer])}</firstFooter>" if sheet_hf[:first_footer]
3069
- parts << "</headerFooter>"
3070
- end
2575
+ write_data_validations_xml(xml, sheet_dv, dv_options) unless sheet_dv.empty?
2576
+ write_print_and_page_xml(xml, sheet_po, sheet_pm, sheet_ps, sheet_hf)
2577
+ write_page_breaks_xml(xml, "rowBreaks", sheet_rb, default_max: 16_383) unless sheet_rb.empty?
2578
+ write_page_breaks_xml(xml, "colBreaks", sheet_cb, default_max: 1_048_575) unless sheet_cb.empty?
3071
2579
 
3072
- # Emit <rowBreaks> if defined.
3073
- unless sheet_rb.empty?
3074
- manual_count = sheet_rb.count do |r|
3075
- if r.is_a?(Elements::PageBreak)
3076
- r.manual?
3077
- elsif r.is_a?(Hash)
3078
- r[:man] != false
3079
- else
3080
- true
2580
+ unless cell_watches.empty?
2581
+ xml.tag("cellWatches") do
2582
+ cell_watches.each { |r| xml.empty_tag("cellWatch", { r: r || "" }) }
2583
+ end
3081
2584
  end
3082
- end
3083
- parts << %(<rowBreaks count="#{sheet_rb.size}" manualBreakCount="#{xml_escape(manual_count)}">)
3084
- sheet_rb.each { |r| parts << emit_brk_xml(r, default_max: 16_383) }
3085
- parts << "</rowBreaks>"
3086
- end
3087
2585
 
3088
- # Emit <colBreaks> if defined.
3089
- unless sheet_cb.empty?
3090
- manual_count = sheet_cb.count do |c|
3091
- if c.is_a?(Elements::PageBreak)
3092
- c.manual?
3093
- elsif c.is_a?(Hash)
3094
- c[:man] != false
3095
- else
3096
- true
2586
+ unless ignored_errors.empty?
2587
+ xml.tag("ignoredErrors") do
2588
+ ignored_errors.each do |ie|
2589
+ xml.empty_tag(
2590
+ "ignoredError",
2591
+ {
2592
+ sqref: ie[:sqref] || "",
2593
+ evalError: (1 if ie[:eval_error]),
2594
+ twoDigitTextYear: (1 if ie[:two_digit_text_year]),
2595
+ numberStoredAsText: (1 if ie[:number_stored_as_text]),
2596
+ formula: (1 if ie[:formula]),
2597
+ formulaRange: (1 if ie[:formula_range]),
2598
+ unlockedFormula: (1 if ie[:unlocked_formula]),
2599
+ emptyCellReference: (1 if ie[:empty_cell_reference]),
2600
+ listDataValidation: (1 if ie[:list_data_validation]),
2601
+ calculatedColumn: (1 if ie[:calculated_column])
2602
+ }
2603
+ )
2604
+ end
2605
+ end
3097
2606
  end
3098
- end
3099
- parts << %(<colBreaks count="#{sheet_cb.size}" manualBreakCount="#{xml_escape(manual_count)}">)
3100
- sheet_cb.each { |c| parts << emit_brk_xml(c, default_max: 1_048_575) }
3101
- parts << "</colBreaks>"
3102
- end
3103
2607
 
3104
- # Emit <cellWatches> if defined.
3105
- unless cell_watches.empty?
3106
- parts << "<cellWatches>"
3107
- cell_watches.each { |r| parts << %(<cellWatch r="#{xml_escape(r)}"/>) }
3108
- parts << "</cellWatches>"
3109
- end
2608
+ unless sheet_tables.empty?
2609
+ xml.tag("tableParts", { count: sheet_tables.size }) do
2610
+ sheet_tables.each_with_index do |_tbl, i|
2611
+ rid = hyperlink_count + i + 1
2612
+ xml.empty_tag("tablePart", { "r:id": "rId#{rid}" })
2613
+ end
2614
+ end
2615
+ end
3110
2616
 
3111
- # Emit <ignoredErrors> if defined.
3112
- unless ignored_errors.empty?
3113
- parts << "<ignoredErrors>"
3114
- ignored_errors.each do |ie|
3115
- ie_attrs = %( sqref="#{xml_escape(ie[:sqref])}")
3116
- ie_attrs << ' evalError="1"' if ie[:eval_error]
3117
- ie_attrs << ' twoDigitTextYear="1"' if ie[:two_digit_text_year]
3118
- ie_attrs << ' numberStoredAsText="1"' if ie[:number_stored_as_text]
3119
- ie_attrs << ' formula="1"' if ie[:formula]
3120
- ie_attrs << ' formulaRange="1"' if ie[:formula_range]
3121
- ie_attrs << ' unlockedFormula="1"' if ie[:unlocked_formula]
3122
- ie_attrs << ' emptyCellReference="1"' if ie[:empty_cell_reference]
3123
- ie_attrs << ' listDataValidation="1"' if ie[:list_data_validation]
3124
- ie_attrs << ' calculatedColumn="1"' if ie[:calculated_column]
3125
- parts << "<ignoredError#{ie_attrs}/>"
3126
- end
3127
- parts << "</ignoredErrors>"
3128
- end
2617
+ if has_drawing
2618
+ # The drawing rId is after hyperlinks + tables + comments + vml
2619
+ drawing_rid = hyperlink_count + sheet_tables.size + (has_comments ? 2 : 0) + 1
2620
+ xml.empty_tag("drawing", { "r:id": "rId#{drawing_rid}" })
2621
+ end
3129
2622
 
3130
- # Emit <tableParts> if tables are defined.
3131
- unless sheet_tables.empty?
3132
- parts << %(<tableParts count="#{sheet_tables.size}">)
3133
- sheet_tables.each_with_index do |_tbl, i|
3134
- rid = hyperlink_count + i + 1
3135
- parts << %(<tablePart r:id="rId#{xml_escape(rid)}"/>)
2623
+ xml.empty_tag("legacyDrawing", { "r:id": "rId#{vml_rid}" }) if vml_rid
3136
2624
  end
3137
- parts << "</tableParts>"
3138
2625
  end
3139
-
3140
- # Emit <drawing> reference if images or charts exist.
3141
- if has_drawing
3142
- # The drawing rId is after hyperlinks + tables + comments + vml
3143
- drawing_rid = hyperlink_count + sheet_tables.size + (has_comments ? 2 : 0) + 1
3144
- parts << %(<drawing r:id="rId#{xml_escape(drawing_rid)}"/>)
3145
- end
3146
-
3147
- # Emit <legacyDrawing> reference if comments exist (VML shapes).
3148
- parts << %(<legacyDrawing r:id="rId#{xml_escape(vml_rid)}"/>) if vml_rid
3149
-
3150
- parts << "</worksheet>"
3151
- parts.join
3152
2626
  end
3153
2627
 
3154
2628
  # : () -> ::Array[untyped]
@@ -3174,7 +2648,7 @@ module Xlsxrb
3174
2648
  [rt_sst, str_sst]
3175
2649
  end
3176
2650
 
3177
- # : (untyped sst) -> untyped
2651
+ # : (untyped sst) -> ::String
3178
2652
  def generate_shared_strings_xml(sst)
3179
2653
  rt_sst, str_sst = sst
3180
2654
  total = rt_sst.size + str_sst.size
@@ -3182,79 +2656,25 @@ module Xlsxrb
3182
2656
  rt_sst.each { |rt, idx| entries[idx] = { type: :rt, value: rt } }
3183
2657
  str_sst.each { |str, idx| entries[idx] = { type: :str, value: str } }
3184
2658
 
3185
- parts = [XML_HEADER, %(<sst xmlns="#{SSML_NS}" count="#{xml_escape(total)}" uniqueCount="#{xml_escape(total)}">)]
3186
- entries.each do |entry|
3187
- parts << if entry[:type] == :rt
3188
- "<si>#{rich_text_xml(entry[:value])}</si>"
3189
- else
3190
- "<si><t>#{xml_escape_text(entry[:value])}</t></si>"
3191
- end
2659
+ XmlBuilder.build(declaration: :plain) do |xml|
2660
+ xml.tag("sst", { xmlns: SSML_NS, count: total, uniqueCount: total }) do
2661
+ entries.each do |entry|
2662
+ xml.tag("si") do
2663
+ if entry[:type] == :rt
2664
+ write_rich_text_xml(xml, entry[:value])
2665
+ else
2666
+ xml.tag("t") { xml.xstring_text(entry[:value]) }
2667
+ end
2668
+ end
2669
+ end
2670
+ end
3192
2671
  end
3193
- parts << "</sst>"
3194
- parts.join
3195
2672
  end
3196
2673
 
3197
- # : (untyped tbl) -> untyped
2674
+ # : (untyped tbl) -> ::String
3198
2675
  def generate_table_xml(tbl)
3199
2676
  trc = tbl[:totals_row_count].to_i
3200
- table_attrs = %(xmlns="#{SSML_NS}" id="#{xml_escape(tbl[:id])}" name="#{xml_escape(tbl[:name])}" displayName="#{xml_escape(tbl[:display_name])}" ref="#{xml_escape(tbl[:ref])}")
3201
- table_attrs << %( comment="#{xml_escape(tbl[:comment])}") if tbl[:comment]
3202
2677
  hrc = tbl[:header_row_count]
3203
- table_attrs << %( headerRowCount="#{xml_escape(hrc)}") if hrc && hrc != 1
3204
- table_attrs << ' insertRow="1"' if tbl[:insert_row]
3205
- table_attrs << ' insertRowShift="1"' if tbl[:insert_row_shift]
3206
- table_attrs << %( totalsRowCount="#{xml_escape(trc)}") if trc.positive?
3207
- table_attrs << ' totalsRowShown="0"' if trc.zero?
3208
- table_attrs << ' published="1"' if tbl[:published]
3209
- table_attrs << %( headerRowDxfId="#{xml_escape(tbl[:header_row_dxf_id])}") if tbl[:header_row_dxf_id]
3210
- table_attrs << %( dataDxfId="#{xml_escape(tbl[:data_dxf_id])}") if tbl[:data_dxf_id]
3211
- table_attrs << %( totalsRowDxfId="#{xml_escape(tbl[:totals_row_dxf_id])}") if tbl[:totals_row_dxf_id]
3212
- table_attrs << %( headerRowBorderDxfId="#{xml_escape(tbl[:header_row_border_dxf_id])}") if tbl[:header_row_border_dxf_id]
3213
- table_attrs << %( tableBorderDxfId="#{xml_escape(tbl[:table_border_dxf_id])}") if tbl[:table_border_dxf_id]
3214
- table_attrs << %( totalsRowBorderDxfId="#{xml_escape(tbl[:totals_row_border_dxf_id])}") if tbl[:totals_row_border_dxf_id]
3215
- table_attrs << %( headerRowCellStyle="#{xml_escape(tbl[:header_row_cell_style])}") if tbl[:header_row_cell_style]
3216
- table_attrs << %( totalsRowCellStyle="#{xml_escape(tbl[:totals_row_cell_style])}") if tbl[:totals_row_cell_style]
3217
- table_attrs << %( connectionId="#{xml_escape(tbl[:connection_id])}") if tbl[:connection_id]
3218
- table_attrs << %( tableType="#{xml_escape(tbl[:table_type])}") if tbl[:table_type]
3219
- parts = [
3220
- XML_HEADER,
3221
- "<table #{table_attrs}>"
3222
- ]
3223
- parts << %(<autoFilter ref="#{xml_escape(tbl[:ref])}"/>) unless tbl[:auto_filter] == false
3224
- parts << %(<tableColumns count="#{tbl[:columns].size}">)
3225
- tbl[:columns].each_with_index do |col, i|
3226
- col = col.to_h if col.is_a?(Elements::MetadataRecord)
3227
- col_name = if col.is_a?(Hash)
3228
- col[:name]
3229
- elsif col.is_a?(Elements::TableColumn)
3230
- col.name
3231
- else
3232
- col
3233
- end
3234
- col_attrs = %(id="#{i + 1}" name="#{xml_escape(col_name)}")
3235
- if col.is_a?(Hash) || col.is_a?(Elements::TableColumn)
3236
- calc_formula = col[:calculated_column_formula] || col[:data_formula] || col[:formula]
3237
- tot_formula = col[:totals_row_formula]
3238
- trf = col[:totals_row_function] || ("custom" if tot_formula)
3239
- col_attrs << %( totalsRowFunction="#{xml_escape(trf)}") if trf
3240
- col_attrs << %( totalsRowLabel="#{xml_escape(col[:totals_row_label])}") if col[:totals_row_label]
3241
- col_attrs << %( dataDxfId="#{xml_escape(col[:data_dxf_id])}") if col[:data_dxf_id]
3242
- col_attrs << %( totalsRowDxfId="#{xml_escape(col[:totals_row_dxf_id])}") if col[:totals_row_dxf_id]
3243
- col_attrs << %( headerRowDxfId="#{xml_escape(col[:header_row_dxf_id])}") if col[:header_row_dxf_id]
3244
- col_attrs << %( dataCellStyle="#{xml_escape(col[:data_cell_style])}") if col[:data_cell_style]
3245
- if calc_formula || tot_formula
3246
- parts << "<tableColumn #{col_attrs}>"
3247
- parts << "<calculatedColumnFormula>#{xml_escape(calc_formula.to_s)}</calculatedColumnFormula>" if calc_formula
3248
- parts << "<totalsRowFormula>#{xml_escape(tot_formula.to_s)}</totalsRowFormula>" if tot_formula
3249
- parts << "</tableColumn>"
3250
- else
3251
- parts << "<tableColumn #{col_attrs}/>"
3252
- end
3253
- else
3254
- parts << "<tableColumn #{col_attrs}/>"
3255
- end
3256
- end
3257
- parts << "</tableColumns>"
3258
2678
  raw_style = tbl[:style] || tbl[:style_info]
3259
2679
  raw_style = raw_style.to_h if raw_style.respond_to?(:to_h)
3260
2680
  style = if raw_style.is_a?(Hash)
@@ -3276,34 +2696,103 @@ module Xlsxrb
3276
2696
  end
3277
2697
  show_column_stripes = style.key?(:show_column_stripes) ? style[:show_column_stripes] : tbl[:show_column_stripes]
3278
2698
 
3279
- sfc = show_first_column ? "1" : "0"
3280
- slc = show_last_column ? "1" : "0"
3281
- srs = show_row_stripes ? "1" : "0"
3282
- scs = show_column_stripes ? "1" : "0"
3283
- parts << %(<tableStyleInfo name="#{xml_escape(style_name)}" showFirstColumn="#{xml_escape(sfc)}" showLastColumn="#{xml_escape(slc)}" showRowStripes="#{xml_escape(srs)}" showColumnStripes="#{xml_escape(scs)}"/>)
3284
- parts << "</table>"
3285
- parts.join
2699
+ XmlBuilder.build(declaration: :plain) do |xml|
2700
+ xml.tag(
2701
+ "table",
2702
+ {
2703
+ xmlns: SSML_NS,
2704
+ id: tbl[:id] || "",
2705
+ name: tbl[:name] || "",
2706
+ displayName: tbl[:display_name] || "",
2707
+ ref: tbl[:ref] || "",
2708
+ comment: tbl[:comment],
2709
+ headerRowCount: (hrc if hrc && hrc != 1),
2710
+ insertRow: (1 if tbl[:insert_row]),
2711
+ insertRowShift: (1 if tbl[:insert_row_shift]),
2712
+ totalsRowCount: (trc if trc.positive?),
2713
+ totalsRowShown: (0 if trc.zero?),
2714
+ published: (1 if tbl[:published]),
2715
+ headerRowDxfId: tbl[:header_row_dxf_id],
2716
+ dataDxfId: tbl[:data_dxf_id],
2717
+ totalsRowDxfId: tbl[:totals_row_dxf_id],
2718
+ headerRowBorderDxfId: tbl[:header_row_border_dxf_id],
2719
+ tableBorderDxfId: tbl[:table_border_dxf_id],
2720
+ totalsRowBorderDxfId: tbl[:totals_row_border_dxf_id],
2721
+ headerRowCellStyle: tbl[:header_row_cell_style],
2722
+ totalsRowCellStyle: tbl[:totals_row_cell_style],
2723
+ connectionId: tbl[:connection_id],
2724
+ tableType: tbl[:table_type]
2725
+ }
2726
+ ) do
2727
+ xml.empty_tag("autoFilter", { ref: tbl[:ref] || "" }) unless tbl[:auto_filter] == false
2728
+ xml.tag("tableColumns", { count: tbl[:columns].size }) do
2729
+ tbl[:columns].each_with_index do |col, i|
2730
+ col = col.to_h if col.is_a?(Elements::MetadataRecord)
2731
+ col_name = if col.is_a?(Hash)
2732
+ col[:name]
2733
+ elsif col.is_a?(Elements::TableColumn)
2734
+ col.name
2735
+ else
2736
+ col
2737
+ end
2738
+ if col.is_a?(Hash) || col.is_a?(Elements::TableColumn)
2739
+ calc_formula = col[:calculated_column_formula] || col[:data_formula] || col[:formula]
2740
+ tot_formula = col[:totals_row_formula]
2741
+ trf = col[:totals_row_function] || ("custom" if tot_formula)
2742
+ col_attrs = {
2743
+ id: i + 1,
2744
+ name: col_name || "",
2745
+ totalsRowFunction: trf,
2746
+ totalsRowLabel: col[:totals_row_label],
2747
+ dataDxfId: col[:data_dxf_id],
2748
+ totalsRowDxfId: col[:totals_row_dxf_id],
2749
+ headerRowDxfId: col[:header_row_dxf_id],
2750
+ dataCellStyle: col[:data_cell_style]
2751
+ }
2752
+ if calc_formula || tot_formula
2753
+ xml.tag("tableColumn", col_attrs) do
2754
+ xml.text_tag("calculatedColumnFormula", calc_formula.to_s) if calc_formula
2755
+ xml.text_tag("totalsRowFormula", tot_formula.to_s) if tot_formula
2756
+ end
2757
+ else
2758
+ xml.empty_tag("tableColumn", col_attrs)
2759
+ end
2760
+ else
2761
+ xml.empty_tag("tableColumn", { id: i + 1, name: col_name || "" })
2762
+ end
2763
+ end
2764
+ end
2765
+ xml.empty_tag(
2766
+ "tableStyleInfo",
2767
+ {
2768
+ name: style_name,
2769
+ showFirstColumn: show_first_column ? "1" : "0",
2770
+ showLastColumn: show_last_column ? "1" : "0",
2771
+ showRowStripes: show_row_stripes ? "1" : "0",
2772
+ showColumnStripes: show_column_stripes ? "1" : "0"
2773
+ }
2774
+ )
2775
+ end
2776
+ end
3286
2777
  end
3287
2778
 
3288
- # : (untyped sheet_hyperlinks, ?untyped sheet_tables, ?::Integer table_start_index) -> untyped
2779
+ # : (untyped sheet_hyperlinks, ?untyped sheet_tables, ?::Integer table_start_index) -> ::String
3289
2780
  def generate_worksheet_rels(sheet_hyperlinks, sheet_tables = [], table_start_index = 0)
3290
- parts = [
3291
- XML_HEADER,
3292
- %(<Relationships xmlns="#{REL_NS}">)
3293
- ]
3294
- rid = 0
3295
- sheet_hyperlinks.each do |(_cell_ref, link)|
3296
- next unless link[:url]
3297
-
3298
- rid += 1
3299
- parts << %(<Relationship Id="rId#{xml_escape(rid)}" Type="#{DOC_REL_NS}/hyperlink" Target="#{xml_escape(link[:url])}" TargetMode="External"/>)
3300
- end
3301
- sheet_tables.each_with_index do |_tbl, i|
3302
- rid += 1
3303
- parts << %(<Relationship Id="rId#{xml_escape(rid)}" Type="#{DOC_REL_NS}/table" Target="../tables/table#{xml_escape(table_start_index + i + 1)}.xml"/>)
2781
+ XmlBuilder.build(declaration: :plain) do |xml|
2782
+ xml.tag("Relationships", { xmlns: REL_NS }) do
2783
+ rid = 0
2784
+ sheet_hyperlinks.each do |(_cell_ref, link)|
2785
+ next unless link[:url]
2786
+
2787
+ rid += 1
2788
+ xml.empty_tag("Relationship", { Id: "rId#{rid}", Type: "#{DOC_REL_NS}/hyperlink", Target: link[:url], TargetMode: "External" })
2789
+ end
2790
+ sheet_tables.each_with_index do |_tbl, i|
2791
+ rid += 1
2792
+ xml.empty_tag("Relationship", { Id: "rId#{rid}", Type: "#{DOC_REL_NS}/table", Target: "../tables/table#{table_start_index + i + 1}.xml" })
2793
+ end
2794
+ end
3304
2795
  end
3305
- parts << "</Relationships>"
3306
- parts.join
3307
2796
  end
3308
2797
 
3309
2798
  # : (untyped sheet_name, untyped sheet_tables, untyped table_start_index, untyped drawing_idx, untyped comment_idx, untyped pivot_start, untyped pivot_count, ?untyped? threaded_comment_idx) -> untyped
@@ -3330,15 +2819,602 @@ module Xlsxrb
3330
2819
  rels
3331
2820
  end
3332
2821
 
3333
- # : (untyped rels_data) -> untyped
2822
+ # : (untyped rels_data) -> ::String
3334
2823
  def generate_generic_rels(rels_data)
3335
- parts = [XML_HEADER, %(<Relationships xmlns="#{REL_NS}">)]
3336
- rels_data.each_with_index do |rel, i|
3337
- ext_attr = rel[:external] ? ' TargetMode="External"' : ""
3338
- parts << %(<Relationship Id="rId#{i + 1}" Type="#{xml_escape(rel[:type])}" Target="#{xml_escape(rel[:target])}"#{ext_attr}/>)
2824
+ XmlBuilder.build(declaration: :plain) do |xml|
2825
+ xml.tag("Relationships", { xmlns: REL_NS }) do
2826
+ rels_data.each_with_index do |rel, i|
2827
+ xml.empty_tag(
2828
+ "Relationship",
2829
+ {
2830
+ Id: "rId#{i + 1}",
2831
+ Type: rel[:type] || "",
2832
+ Target: rel[:target] || "",
2833
+ TargetMode: ("External" if rel[:external])
2834
+ }
2835
+ )
2836
+ end
2837
+ end
2838
+ end
2839
+ end
2840
+
2841
+ # : (XmlBuilder xml) -> void
2842
+ def write_workbook_file_version_xml(xml)
2843
+ return if @file_version.empty?
2844
+
2845
+ attrs = {
2846
+ appName: @file_version[:app_name],
2847
+ lastEdited: @file_version[:last_edited],
2848
+ lowestEdited: @file_version[:lowest_edited],
2849
+ rupBuild: @file_version[:rup_build],
2850
+ codeName: @file_version[:code_name]
2851
+ }.compact
2852
+ xml.empty_tag("fileVersion", attrs) unless attrs.empty?
2853
+ end
2854
+
2855
+ # : (XmlBuilder xml) -> void
2856
+ def write_workbook_file_sharing_xml(xml)
2857
+ return if @file_sharing.empty?
2858
+
2859
+ attrs = {
2860
+ readOnlyRecommended: (1 if @file_sharing[:read_only_recommended]),
2861
+ userName: @file_sharing[:user_name],
2862
+ algorithmName: @file_sharing[:algorithm_name],
2863
+ hashValue: @file_sharing[:hash_value],
2864
+ saltValue: @file_sharing[:salt_value],
2865
+ spinCount: @file_sharing[:spin_count]
2866
+ }.compact
2867
+ xml.empty_tag("fileSharing", attrs) unless attrs.empty?
2868
+ end
2869
+
2870
+ # : (XmlBuilder xml) -> void
2871
+ def write_workbook_pr_xml(xml)
2872
+ return if @workbook_properties.empty?
2873
+
2874
+ wp = @workbook_properties
2875
+ attrs = {
2876
+ date1904: xml_bool_attr(wp[:date1904]),
2877
+ dateCompatibility: (0 if wp[:date_compatibility] == false),
2878
+ defaultThemeVersion: wp[:default_theme_version],
2879
+ codeName: wp[:code_name],
2880
+ filterPrivacy: (1 if wp[:filter_privacy]),
2881
+ autoCompressPictures: (0 if wp[:auto_compress_pictures] == false),
2882
+ backupFile: (1 if wp[:backup_file]),
2883
+ showObjects: wp[:show_objects],
2884
+ updateLinks: wp[:update_links],
2885
+ refreshAllConnections: (1 if wp[:refresh_all_connections]),
2886
+ checkCompatibility: (1 if wp[:check_compatibility]),
2887
+ hidePivotFieldList: (1 if wp[:hide_pivot_field_list]),
2888
+ showBorderUnselectedTables: (0 if wp[:show_border_unselected_tables] == false),
2889
+ promptedSolutions: (1 if wp[:prompted_solutions]),
2890
+ showInkAnnotation: (0 if wp[:show_ink_annotation] == false),
2891
+ saveExternalLinkValues: (0 if wp[:save_external_link_values] == false),
2892
+ showPivotChartFilter: (1 if wp[:show_pivot_chart_filter]),
2893
+ allowRefreshQuery: (1 if wp[:allow_refresh_query]),
2894
+ publishItems: (1 if wp[:publish_items])
2895
+ }.compact
2896
+ xml.empty_tag("workbookPr", attrs) unless attrs.empty?
2897
+ end
2898
+
2899
+ # : (XmlBuilder xml) -> void
2900
+ def write_workbook_views_xml(xml)
2901
+ return if @workbook_views.empty?
2902
+
2903
+ wv = @workbook_views
2904
+ attrs = {
2905
+ visibility: wv[:visibility],
2906
+ minimized: (1 if wv[:minimized]),
2907
+ showHorizontalScroll: xml_bool_attr(wv[:show_horizontal_scroll]),
2908
+ showVerticalScroll: xml_bool_attr(wv[:show_vertical_scroll]),
2909
+ showSheetTabs: xml_bool_attr(wv[:show_sheet_tabs]),
2910
+ xWindow: wv[:x_window],
2911
+ yWindow: wv[:y_window],
2912
+ windowWidth: wv[:window_width],
2913
+ windowHeight: wv[:window_height],
2914
+ tabRatio: wv[:tab_ratio],
2915
+ firstSheet: wv[:first_sheet],
2916
+ activeTab: wv[:active_sheet_index] || wv[:active_tab],
2917
+ autoFilterDateGrouping: xml_bool_attr(wv[:auto_filter_date_grouping])
2918
+ }.compact
2919
+ xml.tag("bookViews") do
2920
+ xml.empty_tag("workbookView", attrs) unless attrs.empty?
2921
+ end
2922
+ end
2923
+
2924
+ # : (XmlBuilder xml) -> void
2925
+ def write_workbook_protection_xml(xml)
2926
+ wp = @workbook_protection
2927
+ attrs = {
2928
+ lockStructure: (1 if wp[:lock_structure]),
2929
+ lockWindows: (1 if wp[:lock_windows]),
2930
+ lockRevision: (1 if wp[:lock_revision])
2931
+ }
2932
+ if wp[:algorithm_name]
2933
+ attrs[:workbookAlgorithmName] = wp[:algorithm_name]
2934
+ attrs[:workbookHashValue] = wp[:hash_value]
2935
+ attrs[:workbookSaltValue] = wp[:salt_value]
2936
+ attrs[:workbookSpinCount] = wp[:spin_count]
2937
+ elsif wp[:password]
2938
+ attrs[:workbookPassword] = wp[:password]
2939
+ end
2940
+ if wp[:revisions_algorithm_name]
2941
+ attrs[:revisionsAlgorithmName] = wp[:revisions_algorithm_name]
2942
+ attrs[:revisionsHashValue] = wp[:revisions_hash_value]
2943
+ attrs[:revisionsSaltValue] = wp[:revisions_salt_value]
2944
+ attrs[:revisionsSpinCount] = wp[:revisions_spin_count]
2945
+ elsif wp[:revisions_password]
2946
+ attrs[:revisionsPassword] = wp[:revisions_password]
2947
+ end
2948
+ attrs.compact!
2949
+ xml.empty_tag("workbookProtection", attrs) unless attrs.empty?
2950
+ end
2951
+
2952
+ # : (XmlBuilder xml) -> void
2953
+ def write_workbook_calc_pr_xml(xml)
2954
+ return if @calc_properties.empty?
2955
+
2956
+ cp = @calc_properties
2957
+ attrs = {
2958
+ calcId: cp[:calc_id],
2959
+ calcMode: cp[:calc_mode],
2960
+ fullCalcOnLoad: xml_bool_attr(cp[:full_calc_on_load]),
2961
+ iterate: xml_bool_attr(cp[:iterate]),
2962
+ iterateCount: cp[:iterate_count],
2963
+ iterateDelta: cp[:iterate_delta],
2964
+ refMode: cp[:ref_mode],
2965
+ calcCompleted: xml_bool_attr(cp[:calc_completed]),
2966
+ calcOnSave: xml_bool_attr(cp[:calc_on_save]),
2967
+ fullPrecision: xml_bool_attr(cp[:full_precision]),
2968
+ concurrentCalc: xml_bool_attr(cp[:concurrent_calc]),
2969
+ concurrentManualCount: cp[:concurrent_manual_count],
2970
+ forceFullCalc: xml_bool_attr(cp[:force_full_calc])
2971
+ }.compact
2972
+ xml.empty_tag("calcPr", attrs) unless attrs.empty?
2973
+ end
2974
+
2975
+ # : (XmlBuilder xml, untyped sheet_props) -> void
2976
+ def write_sheet_pr_xml(xml, sheet_props)
2977
+ sp_attrs = {
2978
+ syncHorizontal: (1 if sheet_props[:sync_horizontal]),
2979
+ syncVertical: (1 if sheet_props[:sync_vertical]),
2980
+ syncRef: sheet_props[:sync_ref],
2981
+ transitionEvaluation: (1 if sheet_props[:transition_evaluation]),
2982
+ transitionEntry: (1 if sheet_props[:transition_entry]),
2983
+ codeName: sheet_props[:code_name],
2984
+ filterMode: (1 if sheet_props[:filter_mode]),
2985
+ published: (0 if sheet_props[:published] == false),
2986
+ enableFormatConditionsCalculation: (0 if sheet_props[:enable_format_conditions_calculation] == false)
2987
+ }.compact
2988
+ tab_color_attrs = resolve_tab_color_attrs(sheet_props)
2989
+
2990
+ sb = sheet_props[:summary_below]
2991
+ sr = sheet_props[:summary_right]
2992
+ as = sheet_props[:apply_styles]
2993
+ sos = sheet_props[:show_outline_symbols]
2994
+ has_outline = !(sb.nil? && sr.nil? && as.nil? && sos.nil?)
2995
+
2996
+ psp = sheet_props[:page_setup_properties] || sheet_props[:page_setup_pr]
2997
+ ftp = sheet_props[:fit_to_page]
2998
+ ftp = psp[:fit_to_page] if ftp.nil? && psp.is_a?(Hash)
2999
+ apb = sheet_props[:auto_page_breaks]
3000
+ apb = psp[:auto_page_breaks] if apb.nil? && psp.is_a?(Hash)
3001
+ has_psp = !(ftp.nil? && apb.nil?)
3002
+
3003
+ return if sp_attrs.empty? && tab_color_attrs.nil? && !has_outline && !has_psp
3004
+
3005
+ xml.tag("sheetPr", sp_attrs) do
3006
+ xml.empty_tag("tabColor", tab_color_attrs) if tab_color_attrs
3007
+ if has_outline
3008
+ xml.empty_tag(
3009
+ "outlinePr",
3010
+ {
3011
+ applyStyles: xml_bool_attr(as),
3012
+ summaryBelow: xml_bool_attr(sb),
3013
+ summaryRight: xml_bool_attr(sr),
3014
+ showOutlineSymbols: xml_bool_attr(sos)
3015
+ }
3016
+ )
3017
+ end
3018
+ if has_psp
3019
+ xml.empty_tag(
3020
+ "pageSetUpPr",
3021
+ {
3022
+ fitToPage: xml_bool_attr(ftp),
3023
+ autoPageBreaks: xml_bool_attr(apb)
3024
+ }
3025
+ )
3026
+ end
3027
+ end
3028
+ end
3029
+
3030
+ # : (untyped sheet_props) -> (nil | ::Hash[untyped, untyped])
3031
+ def resolve_tab_color_attrs(sheet_props)
3032
+ tc = sheet_props[:tab_color]
3033
+ if tc.is_a?(Hash)
3034
+ attrs = {
3035
+ auto: (1 if tc[:auto]),
3036
+ indexed: tc[:indexed],
3037
+ rgb: tc[:rgb]&.then { |v| v.to_s.delete_prefix("#") },
3038
+ theme: tc[:theme],
3039
+ tint: tc[:tint]
3040
+ }.compact
3041
+ attrs.empty? ? nil : attrs
3042
+ elsif tc
3043
+ { rgb: tc.to_s.delete_prefix("#") }
3044
+ elsif sheet_props[:tab_color_theme]
3045
+ { theme: sheet_props[:tab_color_theme], tint: sheet_props[:tab_color_tint] }
3046
+ elsif sheet_props[:tab_color_indexed]
3047
+ { indexed: sheet_props[:tab_color_indexed] }
3048
+ elsif sheet_props[:tab_color_auto]
3049
+ { auto: 1 }
3050
+ end
3051
+ end
3052
+
3053
+ # : (XmlBuilder xml, untyped sheet_sv, untyped sheet_fp, untyped sheet_sel) -> void
3054
+ def write_sheet_views_xml(xml, sheet_sv, sheet_fp, sheet_sel)
3055
+ xml.tag("sheetViews") do
3056
+ xml.tag(
3057
+ "sheetView",
3058
+ {
3059
+ windowProtection: xml_bool_attr(sheet_sv[:window_protection]),
3060
+ showFormulas: xml_bool_attr(sheet_sv[:show_formulas]),
3061
+ showGridLines: xml_bool_attr(sheet_sv[:show_grid_lines]),
3062
+ showRowColHeaders: xml_bool_attr(sheet_sv[:show_row_col_headers]),
3063
+ showZeros: xml_bool_attr(sheet_sv[:show_zeros]),
3064
+ rightToLeft: xml_bool_attr(sheet_sv[:right_to_left]),
3065
+ tabSelected: (1 if sheet_sv[:tab_selected]),
3066
+ showRuler: xml_bool_attr(sheet_sv[:show_ruler]),
3067
+ showOutlineSymbols: xml_bool_attr(sheet_sv[:show_outline_symbols]),
3068
+ defaultGridColor: xml_bool_attr(sheet_sv[:default_grid_color]),
3069
+ showWhiteSpace: xml_bool_attr(sheet_sv[:show_white_space]),
3070
+ view: sheet_sv[:view],
3071
+ topLeftCell: sheet_sv[:top_left_cell],
3072
+ colorId: sheet_sv[:color_id],
3073
+ zoomScale: sheet_sv[:zoom_scale],
3074
+ zoomScaleNormal: sheet_sv[:zoom_scale_normal],
3075
+ zoomScaleSheetLayoutView: sheet_sv[:zoom_scale_sheet_layout_view],
3076
+ zoomScalePageLayoutView: sheet_sv[:zoom_scale_page_layout_view],
3077
+ workbookViewId: 0
3078
+ }
3079
+ ) do
3080
+ if sheet_fp && sheet_fp[:state] == :split
3081
+ has_x = sheet_fp[:x_split].to_i.positive?
3082
+ has_y = sheet_fp[:y_split].to_i.positive?
3083
+ active_pane = if has_y && has_x
3084
+ "bottomRight"
3085
+ elsif has_y
3086
+ "bottomLeft"
3087
+ else
3088
+ "topRight"
3089
+ end
3090
+ xml.empty_tag(
3091
+ "pane",
3092
+ {
3093
+ xSplit: (sheet_fp[:x_split] if has_x),
3094
+ ySplit: (sheet_fp[:y_split] if has_y),
3095
+ topLeftCell: sheet_fp[:top_left_cell],
3096
+ activePane: active_pane
3097
+ }
3098
+ )
3099
+ elsif sheet_fp
3100
+ fp_col = sheet_fp[:column] || sheet_fp[:col] || 0
3101
+ if sheet_fp[:row].to_i.positive? || fp_col.to_i.positive?
3102
+ top_left = "#{index_to_column_letter(fp_col.to_i + 1)}#{sheet_fp[:row].to_i + 1}"
3103
+ active_pane = if sheet_fp[:row].to_i.positive? && fp_col.to_i.positive?
3104
+ "bottomRight"
3105
+ elsif sheet_fp[:row].to_i.positive?
3106
+ "bottomLeft"
3107
+ else
3108
+ "topRight"
3109
+ end
3110
+ xml.empty_tag(
3111
+ "pane",
3112
+ {
3113
+ ySplit: (sheet_fp[:row] if sheet_fp[:row].to_i.positive?),
3114
+ xSplit: (fp_col if fp_col.to_i.positive?),
3115
+ topLeftCell: top_left,
3116
+ activePane: active_pane,
3117
+ state: "frozen"
3118
+ }
3119
+ )
3120
+ end
3121
+ end
3122
+
3123
+ if sheet_sel
3124
+ xml.empty_tag(
3125
+ "selection",
3126
+ {
3127
+ pane: sheet_sel[:pane],
3128
+ activeCell: sheet_sel[:active_cell],
3129
+ activeCellId: sheet_sel[:active_cell_id],
3130
+ sqref: sheet_sel[:sqref]
3131
+ }
3132
+ )
3133
+ end
3134
+ end
3135
+ end
3136
+ end
3137
+
3138
+ # : (XmlBuilder xml, untyped sheet_cells, untyped sheet_row_attrs, untyped sheet_cell_styles, untyped? sst, untyped cell_phonetic) -> void
3139
+ def write_sheet_data_xml(xml, sheet_cells, sheet_row_attrs, sheet_cell_styles, sst, cell_phonetic)
3140
+ xml.tag("sheetData") do
3141
+ cells_by_row = {}
3142
+ sheet_cells.each do |address, value|
3143
+ row_num = extract_row_number(address)
3144
+ col_letter = extract_column_letter(address)
3145
+ cells_by_row[row_num] ||= {}
3146
+ cells_by_row[row_num][col_letter] = value
3147
+ end
3148
+
3149
+ sheet_row_attrs.each_key { |rn| cells_by_row[rn] ||= {} }
3150
+
3151
+ cells_by_row.sort.each do |row_num, row_cells|
3152
+ ra = sheet_row_attrs[row_num]
3153
+ row_attrs = { r: row_num }
3154
+ if ra
3155
+ if ra[:height]
3156
+ row_attrs[:ht] = ra[:height]
3157
+ row_attrs[:customHeight] = 1
3158
+ end
3159
+ row_attrs[:hidden] = 1 if ra[:hidden]
3160
+ row_attrs[:outlineLevel] = ra[:outline_level] if ra[:outline_level]
3161
+ row_attrs[:collapsed] = 1 if ra[:collapsed]
3162
+ if ra.key?(:style)
3163
+ row_attrs[:s] = ra[:style] || ""
3164
+ row_attrs[:customFormat] = 1
3165
+ end
3166
+ row_attrs[:thickTop] = 1 if ra[:thick_top]
3167
+ row_attrs[:thickBot] = 1 if ra[:thick_bot]
3168
+ row_attrs[:ph] = 1 if ra[:ph]
3169
+ end
3170
+ xml.tag("row", row_attrs) do
3171
+ row_cells.sort_by { |col, _| column_letter_to_index(col) }.each do |col_letter, value|
3172
+ cell_ref = "#{col_letter}#{row_num}"
3173
+ style_idx = resolve_style_index(sheet_cell_styles[cell_ref])
3174
+ write_cell_xml(xml, cell_ref, value, style_idx, sst, ph: cell_phonetic[cell_ref])
3175
+ end
3176
+ end
3177
+ end
3178
+ end
3179
+ end
3180
+
3181
+ # : (XmlBuilder xml, untyped sheet_prot) -> void
3182
+ def write_sheet_protection_xml(xml, sheet_prot)
3183
+ attrs = {
3184
+ sheet: (1 if sheet_prot[:sheet] != false),
3185
+ objects: (1 if sheet_prot[:objects]),
3186
+ scenarios: (1 if sheet_prot[:scenarios]),
3187
+ formatCells: (0 if sheet_prot[:format_cells] == false),
3188
+ formatColumns: (0 if sheet_prot[:format_columns] == false),
3189
+ formatRows: (0 if sheet_prot[:format_rows] == false),
3190
+ insertColumns: (0 if sheet_prot[:insert_columns] == false),
3191
+ insertRows: (0 if sheet_prot[:insert_rows] == false),
3192
+ insertHyperlinks: (0 if sheet_prot[:insert_hyperlinks] == false),
3193
+ deleteColumns: (0 if sheet_prot[:delete_columns] == false),
3194
+ deleteRows: (0 if sheet_prot[:delete_rows] == false),
3195
+ selectLockedCells: (1 if sheet_prot[:select_locked_cells]),
3196
+ sort: (0 if sheet_prot[:sort] == false),
3197
+ autoFilter: (0 if sheet_prot[:auto_filter] == false),
3198
+ pivotTables: (0 if sheet_prot[:pivot_tables] == false),
3199
+ selectUnlockedCells: (1 if sheet_prot[:select_unlocked_cells])
3200
+ }
3201
+ if sheet_prot[:algorithm_name]
3202
+ attrs[:algorithmName] = sheet_prot[:algorithm_name]
3203
+ attrs[:hashValue] = sheet_prot[:hash_value]
3204
+ attrs[:saltValue] = sheet_prot[:salt_value]
3205
+ attrs[:spinCount] = sheet_prot[:spin_count]
3206
+ elsif sheet_prot[:password]
3207
+ attrs[:password] = sheet_prot[:password]
3208
+ end
3209
+ xml.empty_tag("sheetProtection", attrs)
3210
+ end
3211
+
3212
+ # : (XmlBuilder xml, untyped prot_ranges) -> void
3213
+ def write_protected_ranges_xml(xml, prot_ranges)
3214
+ xml.tag("protectedRanges") do
3215
+ prot_ranges.each do |pr|
3216
+ attrs = { sqref: pr[:sqref] || "", name: pr[:name] || "" }
3217
+ if pr[:algorithm_name]
3218
+ attrs[:algorithmName] = pr[:algorithm_name]
3219
+ attrs[:hashValue] = pr[:hash_value]
3220
+ attrs[:saltValue] = pr[:salt_value]
3221
+ attrs[:spinCount] = pr[:spin_count]
3222
+ end
3223
+ sds = pr[:security_descriptors] || []
3224
+ if sds.empty?
3225
+ xml.empty_tag("protectedRange", attrs)
3226
+ else
3227
+ xml.tag("protectedRange", attrs) do
3228
+ sds.each { |sd| xml.text_tag("securityDescriptor", sd || "") }
3229
+ end
3230
+ end
3231
+ end
3232
+ end
3233
+ end
3234
+
3235
+ # : (XmlBuilder xml, untyped sheet_scenarios) -> void
3236
+ def write_scenarios_xml(xml, sheet_scenarios)
3237
+ xml.tag(
3238
+ "scenarios",
3239
+ {
3240
+ current: sheet_scenarios[:current],
3241
+ show: sheet_scenarios[:show],
3242
+ sqref: sheet_scenarios[:sqref]
3243
+ }
3244
+ ) do
3245
+ (sheet_scenarios[:scenarios] || []).each do |sc|
3246
+ xml.tag(
3247
+ "scenario",
3248
+ {
3249
+ name: sc[:name] || "",
3250
+ locked: (1 if sc[:locked]),
3251
+ hidden: (1 if sc[:hidden]),
3252
+ count: (sc[:input_cells].size if sc[:input_cells]&.any?),
3253
+ user: sc[:user],
3254
+ comment: sc[:comment]
3255
+ }
3256
+ ) do
3257
+ (sc[:input_cells] || []).each do |ic|
3258
+ xml.empty_tag(
3259
+ "inputCells",
3260
+ {
3261
+ r: ic[:r] || "",
3262
+ val: ic[:val].to_s,
3263
+ deleted: (1 if ic[:deleted]),
3264
+ undone: (1 if ic[:undone]),
3265
+ numFmtId: ic[:num_fmt_id]
3266
+ }
3267
+ )
3268
+ end
3269
+ end
3270
+ end
3271
+ end
3272
+ end
3273
+
3274
+ # : (XmlBuilder xml, untyped data_consol) -> void
3275
+ def write_data_consolidate_xml(xml, data_consol)
3276
+ attrs = {
3277
+ function: (data_consol[:function] if data_consol[:function] && data_consol[:function] != "sum"),
3278
+ startLabels: (1 if data_consol[:start_labels]),
3279
+ leftLabels: (1 if data_consol[:left_labels]),
3280
+ topLabels: (1 if data_consol[:top_labels]),
3281
+ link: (1 if data_consol[:link])
3282
+ }
3283
+ refs = data_consol[:data_refs] || []
3284
+ if refs.empty?
3285
+ xml.empty_tag("dataConsolidate", attrs)
3286
+ else
3287
+ xml.tag("dataConsolidate", attrs) do
3288
+ xml.tag("dataRefs", { count: refs.size }) do
3289
+ refs.each do |r|
3290
+ xml.empty_tag("dataRef", { ref: r[:ref], name: r[:name], sheet: r[:sheet] })
3291
+ end
3292
+ end
3293
+ end
3294
+ end
3295
+ end
3296
+
3297
+ # : (XmlBuilder xml, untyped sheet_dv, ::Hash[untyped, untyped] dv_options) -> void
3298
+ def write_data_validations_xml(xml, sheet_dv, dv_options)
3299
+ valid_dv = sheet_dv.reject { |dv| dv[:sqref].nil? || dv[:sqref].to_s.empty? }
3300
+ return if valid_dv.empty?
3301
+
3302
+ xml.tag(
3303
+ "dataValidations",
3304
+ {
3305
+ count: valid_dv.size,
3306
+ disablePrompts: (1 if dv_options[:disable_prompts]),
3307
+ xWindow: dv_options[:x_window],
3308
+ yWindow: dv_options[:y_window]
3309
+ }
3310
+ ) do
3311
+ valid_dv.each do |dv|
3312
+ attrs = {
3313
+ sqref: dv[:sqref] || "",
3314
+ type: dv[:type],
3315
+ operator: dv[:operator],
3316
+ errorStyle: dv[:error_style],
3317
+ allowBlank: (1 if dv[:allow_blank]),
3318
+ showInputMessage: (1 if dv[:show_input_message]),
3319
+ showErrorMessage: (1 if dv[:show_error_message]),
3320
+ errorTitle: dv[:error_title],
3321
+ error: dv[:error],
3322
+ promptTitle: dv[:prompt_title],
3323
+ prompt: dv[:prompt],
3324
+ showDropDown: (1 if dv[:show_drop_down]),
3325
+ imeMode: dv[:ime_mode]
3326
+ }
3327
+ if dv[:formula1] || dv[:formula2]
3328
+ xml.tag("dataValidation", attrs) do
3329
+ xml.text_tag("formula1", dv[:formula1]) if dv[:formula1]
3330
+ xml.text_tag("formula2", dv[:formula2]) if dv[:formula2]
3331
+ end
3332
+ else
3333
+ xml.empty_tag("dataValidation", attrs)
3334
+ end
3335
+ end
3336
+ end
3337
+ end
3338
+
3339
+ # : (XmlBuilder xml, untyped sheet_po, untyped sheet_pm, untyped sheet_ps, untyped sheet_hf) -> void
3340
+ def write_print_and_page_xml(xml, sheet_po, sheet_pm, sheet_ps, sheet_hf)
3341
+ unless sheet_po.empty?
3342
+ po_attrs = {
3343
+ gridLines: (1 if sheet_po[:grid_lines]),
3344
+ headings: (1 if sheet_po[:headings]),
3345
+ horizontalCentered: (1 if sheet_po[:horizontal_centered]),
3346
+ verticalCentered: (1 if sheet_po[:vertical_centered]),
3347
+ gridLinesSet: (0 if sheet_po[:grid_lines_set] == false)
3348
+ }.compact
3349
+ xml.empty_tag("printOptions", po_attrs) unless po_attrs.empty?
3350
+ end
3351
+
3352
+ if sheet_pm
3353
+ pm_attrs = %w[left right top bottom header footer].each_with_object({}) do |k, h|
3354
+ v = sheet_pm[k.to_sym]
3355
+ h[k] = v if v
3356
+ end
3357
+ xml.empty_tag("pageMargins", pm_attrs) unless pm_attrs.empty?
3358
+ end
3359
+
3360
+ unless sheet_ps.empty?
3361
+ ps_attrs = {
3362
+ orientation: sheet_ps[:orientation],
3363
+ paperSize: sheet_ps[:paper_size],
3364
+ scale: sheet_ps[:scale],
3365
+ fitToWidth: sheet_ps[:fit_to_width],
3366
+ fitToHeight: sheet_ps[:fit_to_height],
3367
+ pageOrder: sheet_ps[:page_order],
3368
+ blackAndWhite: (1 if sheet_ps[:black_and_white]),
3369
+ draft: (1 if sheet_ps[:draft]),
3370
+ cellComments: sheet_ps[:cell_comments],
3371
+ firstPageNumber: (sheet_ps[:first_page_number] if sheet_ps[:first_page_number] && sheet_ps[:first_page_number].to_i >= 0),
3372
+ useFirstPageNumber: (1 if sheet_ps[:use_first_page_number]),
3373
+ horizontalDpi: (sheet_ps[:horizontal_dpi] if sheet_ps[:horizontal_dpi].to_i.positive?),
3374
+ verticalDpi: (sheet_ps[:vertical_dpi] if sheet_ps[:vertical_dpi].to_i.positive?),
3375
+ copies: sheet_ps[:copies],
3376
+ paperHeight: sheet_ps[:paper_height],
3377
+ paperWidth: sheet_ps[:paper_width],
3378
+ errors: sheet_ps[:errors],
3379
+ usePrinterDefaults: (0 if sheet_ps[:use_printer_defaults] == false)
3380
+ }.compact
3381
+ xml.empty_tag("pageSetup", ps_attrs) unless ps_attrs.empty?
3382
+ end
3383
+
3384
+ return if sheet_hf.empty?
3385
+
3386
+ xml.tag(
3387
+ "headerFooter",
3388
+ {
3389
+ differentFirst: (1 if sheet_hf[:different_first]),
3390
+ differentOddEven: (1 if sheet_hf[:different_odd_even]),
3391
+ scaleWithDoc: (0 if sheet_hf[:scale_with_doc] == false),
3392
+ alignWithMargins: (0 if sheet_hf[:align_with_margins] == false)
3393
+ }
3394
+ ) do
3395
+ xml.text_tag("oddHeader", sheet_hf[:odd_header]) if sheet_hf[:odd_header]
3396
+ xml.text_tag("oddFooter", sheet_hf[:odd_footer]) if sheet_hf[:odd_footer]
3397
+ xml.text_tag("evenHeader", sheet_hf[:even_header]) if sheet_hf[:even_header]
3398
+ xml.text_tag("evenFooter", sheet_hf[:even_footer]) if sheet_hf[:even_footer]
3399
+ xml.text_tag("firstHeader", sheet_hf[:first_header]) if sheet_hf[:first_header]
3400
+ xml.text_tag("firstFooter", sheet_hf[:first_footer]) if sheet_hf[:first_footer]
3401
+ end
3402
+ end
3403
+
3404
+ # : (XmlBuilder xml, ::String tag, untyped breaks, default_max: ::Integer) -> void
3405
+ def write_page_breaks_xml(xml, tag, breaks, default_max:)
3406
+ manual_count = breaks.count do |brk|
3407
+ if brk.is_a?(Elements::PageBreak)
3408
+ brk.manual?
3409
+ elsif brk.is_a?(Hash)
3410
+ brk[:man] != false
3411
+ else
3412
+ true
3413
+ end
3414
+ end
3415
+ xml.tag(tag, { count: breaks.size, manualBreakCount: manual_count }) do
3416
+ breaks.each { |brk| write_brk_xml(xml, brk, default_max: default_max) }
3339
3417
  end
3340
- parts << "</Relationships>"
3341
- parts.join
3342
3418
  end
3343
3419
 
3344
3420
  # Extracts the row number from a cell address, e.g. 1 from "A1".