xlsxrb 0.1.18 → 0.2.0

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 (75) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +163 -0
  3. data/README.md +34 -11
  4. data/lib/ruby_lsp/xlsxrb/completion_listener.rb +410 -80
  5. data/lib/xlsxrb/chart_builder.rb +251 -386
  6. data/lib/xlsxrb/dsl_helpers.rb +120 -67
  7. data/lib/xlsxrb/elements/cell.rb +37 -157
  8. data/lib/xlsxrb/elements/column.rb +11 -19
  9. data/lib/xlsxrb/elements/coordinate_access.rb +15 -86
  10. data/lib/xlsxrb/elements/image.rb +5 -72
  11. data/lib/xlsxrb/elements/metadata.rb +463 -817
  12. data/lib/xlsxrb/elements/row.rb +27 -145
  13. data/lib/xlsxrb/elements/styles.rb +30 -88
  14. data/lib/xlsxrb/elements/types.rb +6 -99
  15. data/lib/xlsxrb/elements/workbook.rb +19 -126
  16. data/lib/xlsxrb/elements/worksheet.rb +43 -314
  17. data/lib/xlsxrb/ooxml/reader/listeners/core_listeners.rb +4 -1
  18. data/lib/xlsxrb/ooxml/reader/listeners/drawing_listeners.rb +7 -7
  19. data/lib/xlsxrb/ooxml/reader/listeners/feature_listeners.rb +32 -17
  20. data/lib/xlsxrb/ooxml/reader.rb +49 -51
  21. data/lib/xlsxrb/ooxml/styles_parser.rb +26 -2
  22. data/lib/xlsxrb/ooxml/utils.rb +2 -2
  23. data/lib/xlsxrb/ooxml/workbook_parser.rb +0 -1
  24. data/lib/xlsxrb/ooxml/workbook_writer.rb +172 -93
  25. data/lib/xlsxrb/ooxml/worksheet_parser.rb +61 -29
  26. data/lib/xlsxrb/ooxml/worksheet_writer.rb +65 -47
  27. data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +28 -11
  28. data/lib/xlsxrb/ooxml/writer/features_xml.rb +53 -14
  29. data/lib/xlsxrb/ooxml/writer/styles_xml.rb +1 -1
  30. data/lib/xlsxrb/ooxml/writer.rb +105 -41
  31. data/lib/xlsxrb/ooxml/xml_parser.rb +78 -5
  32. data/lib/xlsxrb/ooxml/zip_reader.rb +65 -15
  33. data/lib/xlsxrb/ooxml/zip_writer.rb +119 -30
  34. data/lib/xlsxrb/stream_row.rb +12 -116
  35. data/lib/xlsxrb/stream_sheet.rb +14 -261
  36. data/lib/xlsxrb/stream_writer.rb +623 -1476
  37. data/lib/xlsxrb/style_builder.rb +376 -593
  38. data/lib/xlsxrb/version.rb +1 -1
  39. data/lib/xlsxrb/workbook_builder.rb +192 -226
  40. data/lib/xlsxrb/worksheet_builder.rb +456 -1324
  41. data/lib/xlsxrb.rb +266 -1083
  42. data/sig/generated/xlsxrb/chart_builder.rbs +202 -205
  43. data/sig/generated/xlsxrb/dsl_helpers.rbs +64 -16
  44. data/sig/generated/xlsxrb/elements/cell.rbs +12 -76
  45. data/sig/generated/xlsxrb/elements/column.rbs +0 -7
  46. data/sig/generated/xlsxrb/elements/coordinate_access.rbs +5 -41
  47. data/sig/generated/xlsxrb/elements/image.rbs +3 -29
  48. data/sig/generated/xlsxrb/elements/metadata.rbs +138 -151
  49. data/sig/generated/xlsxrb/elements/row.rbs +10 -53
  50. data/sig/generated/xlsxrb/elements/styles.rbs +1 -39
  51. data/sig/generated/xlsxrb/elements/workbook.rbs +14 -78
  52. data/sig/generated/xlsxrb/elements/worksheet.rbs +5 -121
  53. data/sig/generated/xlsxrb/ooxml/reader/listeners/feature_listeners.rbs +0 -4
  54. data/sig/generated/xlsxrb/ooxml/reader.rbs +0 -3
  55. data/sig/generated/xlsxrb/ooxml/styles_parser.rbs +1 -1
  56. data/sig/generated/xlsxrb/ooxml/utils.rbs +3 -3
  57. data/sig/generated/xlsxrb/ooxml/workbook_writer.rbs +12 -0
  58. data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +16 -0
  59. data/sig/generated/xlsxrb/ooxml/worksheet_writer.rbs +5 -3
  60. data/sig/generated/xlsxrb/ooxml/writer/features_xml.rbs +7 -0
  61. data/sig/generated/xlsxrb/ooxml/writer.rbs +20 -14
  62. data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +70 -0
  63. data/sig/generated/xlsxrb/ooxml/zip_reader.rbs +22 -7
  64. data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +26 -1
  65. data/sig/generated/xlsxrb/stream_row.rbs +7 -42
  66. data/sig/generated/xlsxrb/stream_sheet.rbs +1 -158
  67. data/sig/generated/xlsxrb/stream_writer.rbs +457 -976
  68. data/sig/generated/xlsxrb/style_builder.rbs +206 -242
  69. data/sig/generated/xlsxrb/workbook_builder.rbs +84 -132
  70. data/sig/generated/xlsxrb/worksheet_builder.rbs +309 -685
  71. data/sig/generated/xlsxrb.rbs +43 -190
  72. data/sig/rexml.rbs +8 -0
  73. metadata +3 -5
  74. data/lib/xlsxrb/utils.rb +0 -251
  75. data/sig/generated/xlsxrb/utils.rbs +0 -200
@@ -8,7 +8,7 @@ require_relative "../elements/styles"
8
8
  module Xlsxrb
9
9
  module Ooxml
10
10
  # SAX-based parser for xl/styles.xml.
11
- # Returns an Elements::Styles (Hash) with :num_fmts, :fonts, :fills, :borders, :cell_xfs, :cell_style_xfs.
11
+ # Returns an Elements::Styles (Hash) with :num_fmts, :fonts, :fills, :borders, :cell_xfs, :cell_style_xfs, :cell_styles.
12
12
  class StylesParser
13
13
  #: (String? xml_string) -> Elements::Styles
14
14
  def self.parse(xml_string)
@@ -35,12 +35,14 @@ module Xlsxrb
35
35
  borders: [],
36
36
  cell_xfs: [],
37
37
  cell_style_xfs: [],
38
+ cell_styles: [],
38
39
  dxfs: []
39
40
  }
40
41
  @context = []
41
42
  @current_font = nil
42
43
  @current_fill = nil
43
44
  @current_fill_pattern = nil
45
+ @current_gradient_stop = nil
44
46
  @current_border = nil
45
47
  @current_border_side = nil
46
48
  @current_xf = nil
@@ -92,10 +94,22 @@ module Xlsxrb
92
94
  handle_color(attrs)
93
95
  when "name"
94
96
  @current_font[:name] = attrs["val"] if @current_font
97
+ when "family"
98
+ @current_font[:family] = attrs["val"].to_i if @current_font && attrs["val"]
99
+ when "scheme"
100
+ @current_font[:scheme] = attrs["val"] if @current_font && attrs["val"]
95
101
  when "fill"
96
102
  @current_fill = {} if parent_context?("fills") || (@current_dxf && parent_context?("dxf"))
97
103
  when "patternFill"
98
104
  @current_fill_pattern = attrs["patternType"] if @current_fill
105
+ when "gradientFill"
106
+ if @current_fill
107
+ gradient = { type: attrs["type"], degree: attrs["degree"]&.to_f }
108
+ %w[left right top bottom].each { |side| gradient[side.to_sym] = attrs[side].to_f if attrs[side] }
109
+ @current_fill[:gradient] = gradient.compact.merge(stops: [])
110
+ end
111
+ when "stop"
112
+ @current_gradient_stop = { position: attrs["position"].to_f } if @current_fill&.dig(:gradient)
99
113
  when "fgColor", "bgColor"
100
114
  handle_fill_color(localname, attrs) if @current_fill
101
115
  when "border"
@@ -110,6 +124,8 @@ module Xlsxrb
110
124
  @in_cell_xfs = true
111
125
  when "cellStyleXfs"
112
126
  @in_cell_style_xfs = true
127
+ when "cellStyle"
128
+ @result[:cell_styles] << { name: attrs["name"], xf_id: attrs["xfId"]&.to_i, builtin_id: attrs["builtinId"]&.to_i }.compact
113
129
  when "xf"
114
130
  handle_xf(attrs)
115
131
  when "alignment"
@@ -130,6 +146,11 @@ module Xlsxrb
130
146
  end
131
147
  @current_font = nil
132
148
  end
149
+ when "stop"
150
+ if @current_gradient_stop
151
+ @current_fill[:gradient][:stops] << @current_gradient_stop if @current_fill&.dig(:gradient)
152
+ @current_gradient_stop = nil
153
+ end
133
154
  when "fill"
134
155
  if @current_fill
135
156
  if @current_fill_pattern
@@ -181,7 +202,10 @@ module Xlsxrb
181
202
  end
182
203
 
183
204
  def handle_color(attrs)
184
- if @current_font
205
+ if @current_gradient_stop
206
+ color = extract_color(attrs)
207
+ @current_gradient_stop[:color] = color unless color.empty?
208
+ elsif @current_font
185
209
  color = extract_color(attrs)
186
210
  @current_font[:color] = color unless color.empty?
187
211
  elsif @current_border && @current_border_side
@@ -113,8 +113,8 @@ module Xlsxrb
113
113
  end
114
114
  end
115
115
 
116
- # Converts a Time to a fractional Excel serial number (1900 or 1904 system).
117
- #: (Time time, ?date1904: bool) -> Float
116
+ # Converts a Time or DateTime to a fractional Excel serial number (1900 or 1904 system).
117
+ #: (Time | DateTime time, ?date1904: bool) -> Float
118
118
  def datetime_to_serial(time, date1904: false)
119
119
  date = time.to_date
120
120
  day_serial = date_to_serial(date, date1904: date1904)
@@ -56,7 +56,6 @@ module Xlsxrb
56
56
  case localname
57
57
  when "sheet"
58
58
  name_attr = attrs["name"]
59
- name_attr = REXML::Text.unnormalize(name_attr) if name_attr
60
59
  raw_state = attrs["state"]
61
60
  state_sym = case raw_state
62
61
  when "hidden" then :hidden
@@ -33,7 +33,7 @@ module Xlsxrb
33
33
  def self.write(target, sheets:, shared_strings: [], shared_strings_index: nil, styles: nil,
34
34
  defined_names: nil, core_properties: nil, app_properties: nil,
35
35
  custom_properties: nil, workbook_protection: nil, workbook_properties: nil,
36
- compression_level: Zlib::DEFAULT_COMPRESSION)
36
+ compression_level: DEFAULT_COMPRESSION_LEVEL)
37
37
  writer = new(sheets: sheets, shared_strings: shared_strings, shared_strings_index: shared_strings_index, styles: styles,
38
38
  defined_names: defined_names, core_properties: core_properties,
39
39
  app_properties: app_properties, custom_properties: custom_properties,
@@ -45,7 +45,7 @@ module Xlsxrb
45
45
  def initialize(sheets:, shared_strings: [], shared_strings_index: nil, styles: nil,
46
46
  defined_names: nil, core_properties: nil, app_properties: nil,
47
47
  custom_properties: nil, workbook_protection: nil, workbook_properties: nil,
48
- compression_level: Zlib::DEFAULT_COMPRESSION)
48
+ compression_level: DEFAULT_COMPRESSION_LEVEL)
49
49
  @sheets = sheets
50
50
  @shared_strings = shared_strings || []
51
51
  @shared_strings_index = shared_strings_index
@@ -56,7 +56,7 @@ module Xlsxrb
56
56
  @custom_properties = custom_properties || []
57
57
  @workbook_protection = workbook_protection.is_a?(Elements::MetadataRecord) ? workbook_protection.to_h : workbook_protection
58
58
  @workbook_properties = workbook_properties.is_a?(Elements::MetadataRecord) ? workbook_properties.to_h : (workbook_properties || { update_links: "never" })
59
- @compression_level = compression_level || Zlib::DEFAULT_COMPRESSION
59
+ @compression_level = compression_level || DEFAULT_COMPRESSION_LEVEL
60
60
  @drawing_count = 0
61
61
  @chart_count = 0
62
62
  @comment_count = 0
@@ -68,6 +68,8 @@ module Xlsxrb
68
68
  end
69
69
 
70
70
  def write_to(target)
71
+ raise ArgumentError, "Workbook must contain at least one sheet (Excel limitation)" if @sheets.empty?
72
+
71
73
  preprocess_conditional_formats!
72
74
 
73
75
  active_tab_idx = resolve_active_tab_index
@@ -79,10 +81,11 @@ module Xlsxrb
79
81
  sheet_tables = sheet[:tables] || []
80
82
 
81
83
  sv = sheet[:sheet_view]
84
+ sv = sv.to_h if sv && !sv.is_a?(Hash)
82
85
  if idx == effective_active_idx
83
86
  sv = (sv || {}).merge(tab_selected: true)
84
87
  elsif sv&.key?(:tab_selected)
85
- sv = sv.is_a?(Hash) ? sv.dup : sv.to_h
88
+ sv = sv.dup
86
89
  sv.delete(:tab_selected)
87
90
  end
88
91
 
@@ -106,7 +109,6 @@ module Xlsxrb
106
109
  header_footer: sheet[:header_footer],
107
110
  row_breaks: sheet[:row_breaks],
108
111
  column_breaks: sheet[:column_breaks],
109
- col_breaks: sheet[:col_breaks] || sheet[:column_breaks],
110
112
  freeze_pane: sheet[:freeze_pane],
111
113
  split_pane: sheet[:split_pane],
112
114
  selection: sheet[:selection],
@@ -221,12 +223,8 @@ module Xlsxrb
221
223
  bg_data = File.binread(bg_data)
222
224
  else
223
225
  bg_ext = if bg_img.is_a?(Hash)
224
- (bg_img[:extension] || bg_img[:ext] || (bg_img[:path] && File.extname(bg_img[:path]).delete_prefix(".")) || (bg_img[:filename] && File.extname(bg_img[:filename]).delete_prefix(".")) || "png").to_s.downcase
225
- elsif bg_img.respond_to?(:extension) && bg_img.extension
226
- bg_img.extension.to_s.downcase
227
- elsif bg_img.respond_to?(:path) && bg_img.path
228
- File.extname(bg_img.path).delete_prefix(".").downcase
229
- elsif bg_img.respond_to?(:filename) && bg_img.filename
226
+ (bg_img[:ext] || (bg_img[:filename] && File.extname(bg_img[:filename]).delete_prefix(".")) || "png").to_s.downcase
227
+ elsif bg_img.respond_to?(:filename)
230
228
  File.extname(bg_img.filename).delete_prefix(".").downcase
231
229
  else
232
230
  "png"
@@ -255,6 +253,7 @@ module Xlsxrb
255
253
 
256
254
  def write_auxiliary_parts(zip)
257
255
  drawing_idx = 0
256
+ media_idx = 0
258
257
  comment_idx = 0
259
258
  tc_idx = 0
260
259
  table_idx = 0
@@ -292,9 +291,11 @@ module Xlsxrb
292
291
  end
293
292
 
294
293
  sheet_images.each do |img|
295
- media_path = "xl/media/image#{drawing_idx}.#{img[:ext] || "png"}"
296
- zip.add_binary_entry(media_path, img[:file_data])
297
- drawing_rels_data << { type: :image, target: "../media/image#{drawing_idx}.#{img[:ext] || "png"}" }
294
+ # One media file per image: a sheet can hold several.
295
+ media_idx += 1
296
+ media_name = "image#{media_idx}.#{img[:ext] || "png"}"
297
+ zip.add_binary_entry("xl/media/#{media_name}", img[:file_data])
298
+ drawing_rels_data << { type: :image, target: "../media/#{media_name}" }
298
299
  drawing_parts << { kind: :pic, img: img, rid_index: drawing_rels_data.size }
299
300
  end
300
301
 
@@ -327,7 +328,8 @@ module Xlsxrb
327
328
  comment_writer = Xlsxrb::Ooxml::Writer.new
328
329
  sheet_comments.each do |c|
329
330
  c = c.to_h if c.is_a?(Elements::MetadataRecord)
330
- comment_writer.add_comment(c[:cell] || c[:ref], c[:text], author: c[:author] || "Author")
331
+ comment_writer.add_comment(c[:cell] || c[:ref], c[:text], author: c[:author] || "Author", visible: c[:visible] == true,
332
+ anchor: c[:anchor])
331
333
  end
332
334
  zip.add_entry("xl/comments#{comment_idx}.xml", comment_writer.send(:generate_comments_xml, comment_writer.comments))
333
335
  zip.add_entry("xl/drawings/vmlDrawing#{comment_idx}.vml", comment_writer.send(:generate_vml_drawing_xml, comment_writer.comments))
@@ -343,10 +345,10 @@ module Xlsxrb
343
345
  c[:cell] || c[:ref],
344
346
  c[:text],
345
347
  author: c[:author] || "Author",
346
- timestamp: c[:timestamp] || c[:dt],
348
+ timestamp: c[:timestamp] || c[:dt] || c[:created_at],
347
349
  id: c[:id],
348
350
  parent_id: c[:parent_id],
349
- done: c[:done],
351
+ done: c.key?(:done) ? c[:done] : c[:resolved],
350
352
  user_id: c[:user_id],
351
353
  provider_id: c[:provider_id]
352
354
  )
@@ -364,23 +366,15 @@ module Xlsxrb
364
366
 
365
367
  sheet_pivot_tables = sheet[:pivot_tables] || []
366
368
  unless sheet_pivot_tables.empty?
369
+ # The writer only collects the definitions here, so its default sheet holds them
370
+ # whatever the worksheet is called; source ranges name their own sheet.
367
371
  pivot_writer = Xlsxrb::Ooxml::Writer.new
368
- pivot_writer.add_sheet(sheet[:name])
369
372
  sheet_pivot_tables.each do |pt|
370
- pivot_writer.add_pivot_table(
371
- pt[:source_ref],
372
- row_fields: pt[:row_fields],
373
- data_fields: pt[:data_fields],
374
- col_fields: pt[:col_fields] || [],
375
- dest_ref: pt[:dest_ref] || "E1",
376
- name: pt[:name],
377
- field_names: pt[:field_names],
378
- items: pt[:items],
379
- sheet: sheet[:name]
380
- )
373
+ source_ref, args = pivot_table_arguments(pt)
374
+ pivot_writer.add_pivot_table(source_ref, **args)
381
375
  end
382
376
 
383
- pivot_data = pivot_writer.pivot_tables(sheet: sheet[:name])
377
+ pivot_data = pivot_writer.pivot_tables
384
378
  pivot_data.each do |pt_data|
385
379
  pivot_cache_idx += 1
386
380
  pivot_table_idx += 1
@@ -430,6 +424,51 @@ module Xlsxrb
430
424
 
431
425
  private
432
426
 
427
+ PIVOT_CACHE_OPTIONS = {
428
+ save_data: :cache_save_data, enable_refresh: :cache_enable_refresh, refreshed_by: :cache_refreshed_by,
429
+ refreshed_version: :cache_refreshed_version, created_version: :cache_created_version,
430
+ optimize_memory: :cache_optimize_memory
431
+ }.freeze
432
+ private_constant :PIVOT_CACHE_OPTIONS
433
+
434
+ # Returns the source and keyword arguments of Writer#add_pivot_table for a pivot table hash,
435
+ # as the builders create it or as Xlsxrb.load reads it (with the source, field names, and
436
+ # shared items in :cache, and pivot field attributes in :fields).
437
+ #: (Hash[Symbol, untyped] pivot_table) -> [String?, Hash[Symbol, untyped]]
438
+ def pivot_table_arguments(pivot_table)
439
+ cache = pivot_table[:cache] || {}
440
+ cache_fields = cache[:fields] || []
441
+ source_ref = pivot_table[:source_ref]
442
+ if source_ref.nil? && cache[:source_ref]
443
+ source_ref = cache[:source_sheet] ? "#{DslHelpers.quote_sheet_name(cache[:source_sheet])}!#{cache[:source_ref]}" : cache[:source_ref]
444
+ end
445
+ field_names = pivot_table[:field_names] || (cache_fields.map { |f| f[:name] } unless cache_fields.empty?)
446
+ items = pivot_table[:items]
447
+ if items.nil? && cache_fields.any? { |f| f[:shared_items] }
448
+ items = cache_fields.each_with_index.filter_map { |f, i| [i, f[:shared_items]] if f[:shared_items] }.to_h
449
+ end
450
+ field_attrs = pivot_table[:field_attrs]
451
+ if field_attrs.nil? && pivot_table[:fields]
452
+ field_attrs = pivot_table[:fields].each_with_index.map do |f, i|
453
+ cf = cache_fields[i] || {}
454
+ f.except(:items).merge(cache_num_fmt_id: cf[:num_fmt_id], cache_caption: cf[:caption], cache_formula: cf[:formula]).compact
455
+ end
456
+ end
457
+ options = pivot_table.except(:source_ref, :row_fields, :data_fields, :column_fields, :col_fields, :destination, :dest_ref, :ref,
458
+ :field_names, :items, :field_attrs, :fields, :cache, :cache_id, :sheet)
459
+ # Page fields of a loaded pivot table are not written, so neither are their counts.
460
+ options = options.except(:row_page_count, :col_page_count, :column_page_count) if pivot_table[:fields]
461
+ PIVOT_CACHE_OPTIONS.each { |key, option| options[option] = cache[key] if !cache[key].nil? && !options.key?(option) }
462
+ options[:source_name] ||= cache[:source_name] if cache[:source_name]
463
+ args = options.merge(
464
+ row_fields: pivot_table[:row_fields] || [], data_fields: pivot_table[:data_fields] || [],
465
+ column_fields: pivot_table[:column_fields] || pivot_table[:col_fields] || [],
466
+ destination: pivot_table[:destination] || pivot_table[:dest_ref] || pivot_table[:ref] || "E1",
467
+ field_names: field_names, items: items, field_attrs: field_attrs
468
+ )
469
+ [source_ref, args]
470
+ end
471
+
433
472
  def build_sheet_rels_from_list(rels)
434
473
  io = StringIO.new
435
474
  b = XmlBuilder.new(io)
@@ -609,9 +648,25 @@ module Xlsxrb
609
648
  # Workbook protection
610
649
  if @workbook_protection
611
650
  wp_attrs = {}
612
- wp_attrs[:lockStructure] = "1" if @workbook_protection[:lock_structure]
613
- wp_attrs[:lockWindows] = "1" if @workbook_protection[:lock_windows]
614
- wp_attrs[:workbookPassword] = @workbook_protection[:password] if @workbook_protection[:password]
651
+ wp = @workbook_protection
652
+ legacy_password = wp[:workbook_password] || wp[:password]
653
+ wp_attrs[:workbookPassword] = legacy_password.to_s if legacy_password
654
+ wp_attrs[:lockStructure] = "1" if wp[:lock_structure]
655
+ wp_attrs[:lockWindows] = "1" if wp[:lock_windows]
656
+ wp_attrs[:lockRevision] = "1" if wp[:lock_revision]
657
+ wp_attrs[:revisionsPassword] = wp[:revisions_password].to_s if wp[:revisions_password]
658
+ if wp[:algorithm_name]
659
+ wp_attrs[:workbookAlgorithmName] = wp[:algorithm_name].to_s
660
+ wp_attrs[:workbookHashValue] = wp[:hash_value].to_s if wp[:hash_value]
661
+ wp_attrs[:workbookSaltValue] = wp[:salt_value].to_s if wp[:salt_value]
662
+ wp_attrs[:workbookSpinCount] = wp[:spin_count].to_s if wp[:spin_count]
663
+ end
664
+ if wp[:revisions_algorithm_name]
665
+ wp_attrs[:revisionsAlgorithmName] = wp[:revisions_algorithm_name].to_s
666
+ wp_attrs[:revisionsHashValue] = wp[:revisions_hash_value].to_s if wp[:revisions_hash_value]
667
+ wp_attrs[:revisionsSaltValue] = wp[:revisions_salt_value].to_s if wp[:revisions_salt_value]
668
+ wp_attrs[:revisionsSpinCount] = wp[:revisions_spin_count].to_s if wp[:revisions_spin_count]
669
+ end
615
670
  b.empty_tag("workbookProtection", wp_attrs) unless wp_attrs.empty?
616
671
  end
617
672
 
@@ -621,7 +676,7 @@ module Xlsxrb
621
676
  show_sheet_tabs = @workbook_properties&.[](:show_sheet_tabs)
622
677
  tab_ratio = @workbook_properties&.[](:tab_ratio)
623
678
 
624
- emit_active_tab = !(@workbook_properties&.[](:active_sheet) || @workbook_properties&.[](:active_tab)).nil? || active_tab_idx&.positive?
679
+ emit_active_tab = !(@workbook_properties&.[](:active_sheet_index) || @workbook_properties&.[](:active_sheet) || @workbook_properties&.[](:active_tab)).nil? || active_tab_idx&.positive?
625
680
 
626
681
  has_book_views = emit_active_tab || first_sheet_idx || !show_sheet_tabs.nil? || tab_ratio
627
682
  if has_book_views
@@ -751,8 +806,6 @@ module Xlsxrb
751
806
  # Number formats
752
807
  raw_num_fmts = if @styles.respond_to?(:number_formats)
753
808
  @styles.number_formats
754
- elsif @styles.respond_to?(:num_fmts)
755
- @styles.num_fmts
756
809
  else
757
810
  @styles&.dig(:num_fmts) || []
758
811
  end
@@ -810,7 +863,7 @@ module Xlsxrb
810
863
  b.empty_tag("vertAlign", { val: mapped_va })
811
864
  end
812
865
  sz_val = font_props[:size] || font_props[:sz]
813
- b.empty_tag("sz", { val: (sz_val || 11).to_s }) if sz_val || (fonts.first.is_a?(Hash) && fonts == [{}])
866
+ b.empty_tag("sz", { val: (sz_val || 11).to_s }) if sz_val || fonts == [{}]
814
867
  color_attrs = color_tag_attrs(font_props[:color] || (font_props.key?(:rgb) || font_props.key?(:theme) || font_props.key?(:indexed) ? font_props : nil))
815
868
  b.empty_tag("color", color_attrs) if color_attrs
816
869
  b.empty_tag("name", { val: font_props[:name] || "Calibri" })
@@ -833,7 +886,9 @@ module Xlsxrb
833
886
  fill_props = fill_props.to_h if fill_props.is_a?(Elements::MetadataRecord)
834
887
  b.tag("fill") do |_|
835
888
  if fill_props[:gradient]
836
- b.open_tag("gradientFill", { type: fill_props[:gradient][:type], degree: fill_props[:gradient][:degree]&.to_s }.compact)
889
+ gradient = fill_props[:gradient]
890
+ b.open_tag("gradientFill", { type: gradient[:type], degree: gradient[:degree]&.to_s, left: gradient[:left]&.to_s,
891
+ right: gradient[:right]&.to_s, top: gradient[:top]&.to_s, bottom: gradient[:bottom]&.to_s }.compact)
837
892
  fill_props[:gradient][:stops].each do |stop|
838
893
  b.tag("stop", { position: stop[:position].to_s }) do |_|
839
894
  c_attrs = color_tag_attrs(stop[:color] || stop)
@@ -842,7 +897,8 @@ module Xlsxrb
842
897
  end
843
898
  b.close_tag("gradientFill")
844
899
  else
845
- b.tag("patternFill", { patternType: fill_props[:pattern] || "none" }) do |_|
900
+ # Elements::Fill names the pattern :pattern_type; StyleBuilder fills use :pattern.
901
+ b.tag("patternFill", { patternType: fill_props[:pattern_type] || fill_props[:pattern] || "none" }) do |_|
846
902
  fg_attrs = color_tag_attrs(fill_props[:fg_color] || (fill_props[:fg_color_theme] ? { theme: fill_props[:fg_color_theme], tint: fill_props[:fg_color_tint] } : nil) || (fill_props[:fg_color_indexed] ? { indexed: fill_props[:fg_color_indexed] } : nil))
847
903
  b.empty_tag("fgColor", fg_attrs) if fg_attrs
848
904
 
@@ -883,9 +939,16 @@ module Xlsxrb
883
939
  end
884
940
  end
885
941
 
886
- # cellStyleXfs
887
- b.tag("cellStyleXfs", { count: "1" }) do |_|
888
- b.empty_tag("xf", { numFmtId: "0", fontId: "0", fillId: "0", borderId: "0" })
942
+ # cellStyleXfs: the base formats that cellXfs and named cell styles refer to by xfId.
943
+ style_xfs = if @styles.respond_to?(:cell_style_xfs)
944
+ @styles.cell_style_xfs
945
+ else
946
+ @styles&.dig(:cell_style_xfs) || []
947
+ end
948
+ style_xf_count = [style_xfs.size, 1].max
949
+ b.tag("cellStyleXfs", { count: style_xf_count.to_s }) do |_|
950
+ style_xfs.each { |xf| write_xf(b, xf, style_xf_count: nil) }
951
+ b.empty_tag("xf", { numFmtId: "0", fontId: "0", fillId: "0", borderId: "0" }) if style_xfs.empty?
889
952
  end
890
953
 
891
954
  # Cell XFs (formatting)
@@ -896,52 +959,27 @@ module Xlsxrb
896
959
  end
897
960
  xf_count = [xf_entries.size, 1].max
898
961
  b.tag("cellXfs", { count: xf_count.to_s }) do |_|
899
- xf_entries.each do |xf|
900
- xf = xf.to_h if xf.is_a?(Elements::MetadataRecord)
901
- attrs = {
902
- numFmtId: (xf[:num_fmt_id] || 0).to_s,
903
- fontId: (xf[:font_id] || 0).to_s,
904
- fillId: (xf[:fill_id] || 0).to_s,
905
- borderId: (xf[:border_id] || 0).to_s
906
- }
907
- attrs[:xfId] = xf[:xf_id].to_s if xf[:xf_id]
908
- attrs[:applyNumberFormat] = "1" if xf[:num_fmt_id]&.to_i&.positive?
909
- attrs[:applyFont] = "1" if xf[:font_id]&.to_i&.positive?
910
- attrs[:applyFill] = "1" if xf[:fill_id]&.to_i&.positive?
911
- attrs[:applyBorder] = "1" if xf[:border_id]&.to_i&.positive?
912
- attrs[:applyAlignment] = "1" if xf[:alignment]
913
- attrs[:applyProtection] = "1" if xf[:protection]
914
-
915
- if xf[:alignment] || xf[:protection]
916
- b.tag("xf", attrs) do |_|
917
- if xf[:alignment]
918
- align_attrs = {}
919
- align_attrs[:horizontal] = xf[:alignment][:horizontal] if xf[:alignment][:horizontal]
920
- align_attrs[:vertical] = xf[:alignment][:vertical] if xf[:alignment][:vertical]
921
- align_attrs[:wrapText] = "1" if xf[:alignment][:wrap_text]
922
- align_attrs[:textRotation] = xf[:alignment][:text_rotation].to_s if xf[:alignment][:text_rotation]
923
- align_attrs[:indent] = xf[:alignment][:indent].to_s if xf[:alignment][:indent]
924
- align_attrs[:relativeIndent] = xf[:alignment][:relative_indent].to_s if xf[:alignment][:relative_indent]
925
- align_attrs[:shrinkToFit] = "1" if xf[:alignment][:shrink_to_fit]
926
- align_attrs[:readingOrder] = xf[:alignment][:reading_order].to_s if xf[:alignment][:reading_order]
927
- align_attrs[:justifyLastLine] = "1" if xf[:alignment][:justify_last_line]
928
- b.empty_tag("alignment", align_attrs)
929
- end
930
- if xf[:protection]
931
- prot_attrs = {}
932
- prot_attrs[:locked] = xf[:protection][:locked] ? "1" : "0" unless xf[:protection][:locked].nil?
933
- prot_attrs[:hidden] = xf[:protection][:hidden] ? "1" : "0" unless xf[:protection][:hidden].nil?
934
- b.empty_tag("protection", prot_attrs)
935
- end
936
- end
937
- else
938
- b.empty_tag("xf", attrs)
939
- end
940
- end
962
+ xf_entries.each { |xf| write_xf(b, xf, style_xf_count: style_xf_count) }
941
963
  # Add default if empty
942
964
  b.empty_tag("xf", { numFmtId: "0", fontId: "0", fillId: "0", borderId: "0" }) if xf_entries.empty?
943
965
  end
944
966
 
967
+ # Named cell styles, such as Normal and Heading 1, kept from a loaded workbook.
968
+ cell_styles = if @styles.respond_to?(:cell_styles)
969
+ @styles.cell_styles
970
+ else
971
+ @styles&.dig(:cell_styles) || []
972
+ end
973
+ cell_styles = cell_styles.map { |cs| cs.is_a?(Elements::MetadataRecord) ? cs.to_h : cs }
974
+ .select { |cs| cs[:name] && cs[:xf_id].to_i < style_xf_count }
975
+ unless cell_styles.empty?
976
+ b.tag("cellStyles", { count: cell_styles.size.to_s }) do |_|
977
+ cell_styles.each do |cs|
978
+ b.empty_tag("cellStyle", { name: cs[:name], xfId: cs[:xf_id].to_i.to_s, builtinId: cs[:builtin_id]&.to_s }.compact)
979
+ end
980
+ end
981
+ end
982
+
945
983
  # Differential formats (for conditional formatting)
946
984
  dxfs = if @styles.respond_to?(:dxfs)
947
985
  @styles.dxfs
@@ -994,7 +1032,6 @@ module Xlsxrb
994
1032
  end
995
1033
  end
996
1034
  normalized[:dxf_id] = dxf_id
997
- normalized[:format_id] = dxf_id
998
1035
  normalized
999
1036
  end
1000
1037
  end
@@ -1004,6 +1041,48 @@ module Xlsxrb
1004
1041
  DslHelpers.extract_dxf_from_rule!(rule)
1005
1042
  end
1006
1043
 
1044
+ # Writes one <xf> of cellXfs, or of cellStyleXfs when style_xf_count is nil. An xfId that
1045
+ # points past the written cellStyleXfs is dropped, so it falls back to the first entry.
1046
+ def write_xf(builder, format, style_xf_count:)
1047
+ format = format.to_h if format.is_a?(Elements::MetadataRecord)
1048
+ attrs = {
1049
+ numFmtId: (format[:num_fmt_id] || 0).to_s,
1050
+ fontId: (format[:font_id] || 0).to_s,
1051
+ fillId: (format[:fill_id] || 0).to_s,
1052
+ borderId: (format[:border_id] || 0).to_s
1053
+ }
1054
+ attrs[:xfId] = format[:xf_id].to_s if style_xf_count && format[:xf_id] && format[:xf_id].to_i < style_xf_count
1055
+ attrs[:applyNumberFormat] = "1" if format[:num_fmt_id]&.to_i&.positive?
1056
+ attrs[:applyFont] = "1" if format[:font_id]&.to_i&.positive?
1057
+ attrs[:applyFill] = "1" if format[:fill_id]&.to_i&.positive?
1058
+ attrs[:applyBorder] = "1" if format[:border_id]&.to_i&.positive?
1059
+ attrs[:applyAlignment] = "1" if format[:alignment]
1060
+ attrs[:applyProtection] = "1" if format[:protection]
1061
+ return builder.empty_tag("xf", attrs) unless format[:alignment] || format[:protection]
1062
+
1063
+ builder.tag("xf", attrs) do |_|
1064
+ if format[:alignment]
1065
+ align_attrs = {}
1066
+ align_attrs[:horizontal] = format[:alignment][:horizontal] if format[:alignment][:horizontal]
1067
+ align_attrs[:vertical] = format[:alignment][:vertical] if format[:alignment][:vertical]
1068
+ align_attrs[:wrapText] = "1" if format[:alignment][:wrap_text]
1069
+ align_attrs[:textRotation] = format[:alignment][:text_rotation].to_s if format[:alignment][:text_rotation]
1070
+ align_attrs[:indent] = format[:alignment][:indent].to_s if format[:alignment][:indent]
1071
+ align_attrs[:relativeIndent] = format[:alignment][:relative_indent].to_s if format[:alignment][:relative_indent]
1072
+ align_attrs[:shrinkToFit] = "1" if format[:alignment][:shrink_to_fit]
1073
+ align_attrs[:readingOrder] = format[:alignment][:reading_order].to_s if format[:alignment][:reading_order]
1074
+ align_attrs[:justifyLastLine] = "1" if format[:alignment][:justify_last_line]
1075
+ builder.empty_tag("alignment", align_attrs)
1076
+ end
1077
+ if format[:protection]
1078
+ prot_attrs = {}
1079
+ prot_attrs[:locked] = format[:protection][:locked] ? "1" : "0" unless format[:protection][:locked].nil?
1080
+ prot_attrs[:hidden] = format[:protection][:hidden] ? "1" : "0" unless format[:protection][:hidden].nil?
1081
+ builder.empty_tag("protection", prot_attrs)
1082
+ end
1083
+ end
1084
+ end
1085
+
1007
1086
  def write_dxf_font(builder, font)
1008
1087
  font = font.to_h if font.is_a?(Elements::MetadataRecord)
1009
1088
  builder.tag("font") do |_|
@@ -1031,11 +1110,12 @@ module Xlsxrb
1031
1110
  mapped_va = StyleBuilder::VERT_ALIGN_MAP[va_val.to_sym] || va_val.to_s
1032
1111
  builder.empty_tag("vertAlign", { val: mapped_va })
1033
1112
  end
1113
+ # sz, color, and name follow vertAlign in this order, as in CT_Font and Excel's output.
1114
+ sz_val = font[:sz] || font[:size]
1115
+ builder.empty_tag("sz", { val: sz_val.to_s }) if sz_val
1034
1116
  color_attrs = color_tag_attrs(font[:color] || font)
1035
1117
  builder.empty_tag("color", color_attrs) if color_attrs
1036
1118
  builder.empty_tag("name", { val: font[:name] }) if font[:name]
1037
- sz_val = font[:sz] || font[:size]
1038
- builder.empty_tag("sz", { val: sz_val.to_s }) if sz_val
1039
1119
  end
1040
1120
  end
1041
1121
 
@@ -1190,8 +1270,8 @@ module Xlsxrb
1190
1270
  if str.is_a?(Xlsxrb::Elements::RichText)
1191
1271
  buf << "<si>"
1192
1272
  str.runs.each do |run|
1193
- font = run.is_a?(Hash) ? run[:font] : run.font
1194
- run_text = run.is_a?(Hash) ? run[:text] : run.text
1273
+ font = run.respond_to?(:font) ? run.font : run[:font]
1274
+ text = run.respond_to?(:text) ? run.text : run[:text]
1195
1275
  if font && !font.empty?
1196
1276
  buf << "<r><rPr>"
1197
1277
  buf << "<b/>" if font[:bold]
@@ -1226,7 +1306,7 @@ module Xlsxrb
1226
1306
  else
1227
1307
  buf << "<r><t>"
1228
1308
  end
1229
- buf << escape_xml(run_text.to_s) << "</t></r>"
1309
+ buf << escape_xml(text.to_s) << "</t></r>"
1230
1310
  end
1231
1311
  buf << "</si>"
1232
1312
  else
@@ -1307,7 +1387,6 @@ module Xlsxrb
1307
1387
  header_footer: header_footer,
1308
1388
  row_breaks: row_breaks,
1309
1389
  col_breaks: col_breaks || column_breaks,
1310
- column_breaks: column_breaks || col_breaks,
1311
1390
  cell_watches: cell_watches,
1312
1391
  ignored_errors: ignored_errors,
1313
1392
  tables: tables,
@@ -1355,7 +1434,7 @@ module Xlsxrb
1355
1434
  tot_formula = nil
1356
1435
  if col.is_a?(Hash) || col.is_a?(Elements::TableColumn)
1357
1436
  calc_formula = col[:calculated_column_formula] || col[:data_formula] || col[:formula]
1358
- tot_formula = col[:totals_row_formula] || col[:total_row_formula] || col[:total_formula]
1437
+ tot_formula = col[:totals_row_formula]
1359
1438
  trf = col[:totals_row_function] || ("custom" if tot_formula)
1360
1439
  col_attrs[:totalsRowFunction] = trf.to_s if trf
1361
1440
  col_attrs[:totalsRowLabel] = col[:totals_row_label].to_s if col[:totals_row_label]
@@ -1509,7 +1588,7 @@ module Xlsxrb
1509
1588
  end
1510
1589
 
1511
1590
  def resolve_active_tab_index
1512
- active_tab = @workbook_properties&.[](:active_sheet) || @workbook_properties&.[](:active_tab)
1591
+ active_tab = @workbook_properties&.[](:active_sheet_index) || @workbook_properties&.[](:active_sheet) || @workbook_properties&.[](:active_tab)
1513
1592
  if active_tab.nil?
1514
1593
  first_vis_idx = @sheets.find_index do |s|
1515
1594
  state = s.respond_to?(:state) ? s.state : s[:state]