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
@@ -70,7 +70,8 @@ module Xlsxrb
70
70
  else
71
71
  (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size).clamp(1, 100)
72
72
  end
73
- loc_attrs = %(<location ref="#{pivot_table[:dest_ref]}" firstHeaderRow="1" firstDataRow="1" firstDataCol="1")
73
+ loc_attrs = %(<location ref="#{pivot_table[:dest_ref]}" firstHeaderRow="#{pivot_table[:first_header_row] || 1}" ) +
74
+ %(firstDataRow="#{pivot_table[:first_data_row] || 1}" firstDataCol="#{pivot_table[:first_data_col] || 1}")
74
75
  loc_attrs << %( rowPageCount="#{pivot_table[:row_page_count]}") if pivot_table[:row_page_count]
75
76
  loc_attrs << %( colPageCount="#{pivot_table[:col_page_count]}") if pivot_table[:col_page_count]
76
77
  loc_attrs << "/>"
@@ -97,11 +98,18 @@ module Xlsxrb
97
98
  attrs << ' includeNewItemsInFilter="1"' if fa && fa[:include_new_items_in_filter]
98
99
 
99
100
  field_items = pivot_table[:items] && pivot_table[:items][fi]
100
- if field_items
101
+ axis_field = pivot_table[:row_fields].include?(fi) || pivot_table[:col_fields].include?(fi)
102
+ # The default subtotal item goes with the default subtotal; a field with
103
+ # defaultSubtotal="0" must not list it.
104
+ default_subtotal = !(fa && fa[:default_subtotal] == false)
105
+ if field_items || (axis_field && default_subtotal)
106
+ # A row or column field needs an <items> list; without known items it holds only the
107
+ # default subtotal, which Excel fills in when it refreshes the cache on open.
108
+ field_items ||= []
101
109
  parts << "<pivotField#{attrs}>"
102
- parts << %(<items count="#{field_items.size + 1}">)
110
+ parts << %(<items count="#{field_items.size + (default_subtotal ? 1 : 0)}">)
103
111
  field_items.size.times { |ix| parts << %(<item x="#{ix}"/>) }
104
- parts << '<item t="default"/>'
112
+ parts << '<item t="default"/>' if default_subtotal
105
113
  parts << "</items>"
106
114
  parts << "</pivotField>"
107
115
  else
@@ -169,7 +177,9 @@ module Xlsxrb
169
177
  # Parse source ref: "Sheet1!A1:C4" => sheet name + range.
170
178
  source = pivot_table[:source_ref]
171
179
  ws_name_attr = pivot_table[:source_name] ? %( name="#{xml_escape(pivot_table[:source_name])}") : ""
172
- if source.include?("!")
180
+ if source.nil?
181
+ parts << %(<cacheSource type="worksheet"><worksheetSource#{ws_name_attr}/></cacheSource>)
182
+ elsif source.include?("!")
173
183
  sname, srange = source.split("!", 2)
174
184
  sname = sname.delete("'")
175
185
  parts << %(<cacheSource type="worksheet"><worksheetSource ref="#{srange}" sheet="#{xml_escape(sname)}"#{ws_name_attr}/></cacheSource>)
@@ -194,8 +204,8 @@ module Xlsxrb
194
204
  field_items = pivot_table[:items] && pivot_table[:items][fi]
195
205
  if field_items
196
206
  parts << "<cacheField#{cf_attrs}>"
197
- parts << %(<sharedItems count="#{field_items.size}">)
198
- field_items.each { |v| parts << %(<s v="#{xml_escape(v.to_s)}"/>) }
207
+ parts << %(<sharedItems#{shared_items_attrs(field_items)} count="#{field_items.size}">)
208
+ field_items.each { |v| parts << shared_item_xml(v) }
199
209
  parts << "</sharedItems>"
200
210
  parts << "</cacheField>"
201
211
  else
@@ -207,6 +217,33 @@ module Xlsxrb
207
217
  parts.join
208
218
  end
209
219
 
220
+ # Attributes that describe the value types of a cache field's shared items.
221
+ # : (Array[untyped] values) -> String
222
+ def shared_items_attrs(values)
223
+ numbers = values.grep(Numeric)
224
+ strings = values.any? { |v| !v.nil? && !v.is_a?(Numeric) && v != true && v != false }
225
+ attrs = +""
226
+ attrs << ' containsSemiMixedTypes="0"' unless strings || values.include?(nil)
227
+ attrs << ' containsString="0"' unless strings
228
+ attrs << ' containsBlank="1"' if values.include?(nil)
229
+ unless numbers.empty?
230
+ attrs << ' containsNumber="1"'
231
+ attrs << ' containsInteger="1"' if numbers.all? { |n| n.is_a?(Integer) || n == n.to_i }
232
+ attrs << %( minValue="#{numbers.min}" maxValue="#{numbers.max}")
233
+ end
234
+ attrs
235
+ end
236
+
237
+ # : (untyped value) -> String
238
+ def shared_item_xml(value)
239
+ case value
240
+ when nil then "<m/>"
241
+ when true, false then %(<b v="#{value ? 1 : 0}"/>)
242
+ when Numeric then %(<n v="#{value}"/>)
243
+ else %(<s v="#{xml_escape(value.to_s)}"/>)
244
+ end
245
+ end
246
+
210
247
  # : (untyped pivot_table) -> untyped
211
248
  def generate_pivot_cache_records_xml(pivot_table)
212
249
  items = pivot_table[:items]
@@ -315,8 +352,8 @@ module Xlsxrb
315
352
  # : (untyped rich_text) -> untyped
316
353
  def rich_text_xml(rich_text)
317
354
  rich_text.runs.map do |run|
318
- font = run.is_a?(Hash) ? run[:font] : run.font
319
- run_text = run.is_a?(Hash) ? run[:text] : run.text
355
+ font = run.respond_to?(:font) ? run.font : run[:font]
356
+ text = run.respond_to?(:text) ? run.text : run[:text]
320
357
  if font && !font.empty?
321
358
  rpr = +""
322
359
  rpr << "<b/>" if font[:bold]
@@ -338,14 +375,15 @@ module Xlsxrb
338
375
  mapped_va = StyleBuilder::VERT_ALIGN_MAP[va_val.to_sym] || va_val
339
376
  rpr << %(<vertAlign val="#{mapped_va}"/>)
340
377
  end
341
- rpr << %(<sz val="#{font[:sz]}"/>) if font[:sz]
378
+ font_sz = font[:size] || font[:sz]
379
+ rpr << %(<sz val="#{font_sz}"/>) if font_sz
342
380
  rpr << emit_color_xml(font)
343
381
  rpr << %(<rFont val="#{xml_escape(font[:name])}"/>) if font[:name]
344
382
  rpr << %(<family val="#{font[:family]}"/>) if font[:family]
345
383
  rpr << %(<scheme val="#{font[:scheme]}"/>) if font[:scheme]
346
- "<r><rPr>#{rpr}</rPr><t>#{xml_escape(run_text)}</t></r>"
384
+ "<r><rPr>#{rpr}</rPr><t>#{xml_escape(text)}</t></r>"
347
385
  else
348
- "<r><t>#{xml_escape(run_text)}</t></r>"
386
+ "<r><t>#{xml_escape(text)}</t></r>"
349
387
  end
350
388
  end.join
351
389
  end
@@ -372,7 +410,7 @@ module Xlsxrb
372
410
  f_attrs << %( r1="#{value.r1}") if value.r1
373
411
  f_attrs << %( r2="#{value.r2}") if value.r2
374
412
  end
375
- f_attrs << ' ca="1"' if value.calculate_always
413
+ f_attrs << ' ca="1"' if value.calculate_always?
376
414
  f_attrs << ' aca="1"' if value.aca
377
415
  f_attrs << ' bx="1"' if value.bx
378
416
  t_attr = ""
@@ -695,7 +733,8 @@ module Xlsxrb
695
733
  XML_HEADER,
696
734
  %(<Properties xmlns="#{APP_NS}" xmlns:vt="#{VT_NS}">)
697
735
  ]
698
- parts << "<Application>#{xml_escape(@app_properties[:application])}</Application>" if @app_properties[:application]
736
+ app_val = @app_properties[:app_name] || @app_properties[:application]
737
+ parts << "<Application>#{xml_escape(app_val)}</Application>" if app_val
699
738
  parts << "<AppVersion>#{xml_escape(@app_properties[:app_version])}</AppVersion>" if @app_properties[:app_version]
700
739
  if @app_properties[:heading_pairs] && @app_properties[:titles_of_parts]
701
740
  hp = @app_properties[:heading_pairs]
@@ -335,7 +335,7 @@ module Xlsxrb
335
335
  # : (untyped brk, default_max: untyped) -> ::String
336
336
  def emit_brk_xml(brk, default_max:)
337
337
  brk = brk.to_h if brk.is_a?(Elements::MetadataRecord)
338
- if brk.is_a?(Hash) || brk.is_a?(Elements::PageBreak)
338
+ if brk.is_a?(Hash)
339
339
  attrs = %(id="#{brk[:id]}")
340
340
  attrs << %( min="#{brk[:min]}") if brk[:min]
341
341
  attrs << %( max="#{brk.respond_to?(:fetch) ? brk.fetch(:max, default_max) : (brk[:max] || default_max)}")
@@ -563,9 +563,13 @@ module Xlsxrb
563
563
  name = opts[:name]
564
564
  end
565
565
 
566
- font = @fonts[0] ? @fonts[0].dup : { name: "Calibri", sz: 11 }
566
+ font = @fonts[0] ? @fonts[0].dup : { name: "Calibri", sz: 11, size: 11 }
567
567
  font[:name] = (name || opts[:name]).to_s if name || opts[:name]
568
- font[:sz] = size || opts[:size] || opts[:sz] if size || opts[:size] || opts[:sz]
568
+ sz_val = size || opts[:size] || opts[:sz]
569
+ if sz_val
570
+ font[:sz] = sz_val
571
+ font[:size] = sz_val
572
+ end
569
573
  font[:family] = opts[:family] if opts.key?(:family)
570
574
  font[:charset] = opts[:charset] if opts.key?(:charset)
571
575
  font[:scheme] = opts[:scheme].to_s if opts.key?(:scheme)
@@ -577,8 +581,6 @@ module Xlsxrb
577
581
 
578
582
  @fonts[0] = font
579
583
  end
580
- # @deprecated Use {#default_font} instead. Will be removed in 0.2.0.
581
- alias set_default_font default_font
582
584
 
583
585
  # Sets the indexed colors palette (array of ARGB hex strings, e.g. ["FF000000", "FFFFFFFF"]).
584
586
  # rubocop:disable Naming/AccessorMethodName
@@ -742,13 +744,14 @@ module Xlsxrb
742
744
  (@sheet_views[sheet_name] || {}).dup
743
745
  end
744
746
 
745
- # Sets a freeze pane. row: rows to freeze from top, col: columns to freeze from left.
746
- # : (?row: ::Integer, ?col: ::Integer, ?sheet: untyped?) -> untyped
747
- def set_freeze_pane(row: 0, col: 0, sheet: nil)
747
+ # Sets a freeze pane. row: rows to freeze from top, column: columns to freeze from left.
748
+ # : (?row: ::Integer, ?col: ::Integer?, ?column: ::Integer?, ?sheet: untyped?) -> untyped
749
+ def set_freeze_pane(row: 0, col: nil, column: nil, sheet: nil)
748
750
  sheet_name = sheet || @sheet_order.first
749
751
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @freeze_panes.key?(sheet_name)
750
752
 
751
- @freeze_panes[sheet_name] = { row: row, col: col, state: :frozen }
753
+ col_val = column || col || 0
754
+ @freeze_panes[sheet_name] = { row: row, column: col_val, state: :frozen }
752
755
  end
753
756
 
754
757
  # Sets a split pane (non-frozen). x_split/y_split are in 1/20th of a point (twips).
@@ -1671,8 +1674,8 @@ module Xlsxrb
1671
1674
  end
1672
1675
 
1673
1676
  # Adds a comment on a cell.
1674
- # : (untyped cell_address, untyped text, ?author: ::String, ?sheet: untyped?, ?guid: untyped?, ?shape_id: untyped?) -> untyped
1675
- def add_comment(cell_address, text, author: "Author", sheet: nil, guid: nil, shape_id: nil)
1677
+ # : (untyped cell_address, untyped text, ?author: ::String, ?sheet: untyped?, ?guid: untyped?, ?shape_id: untyped?, ?visible: bool, ?anchor: Array[Integer]?) -> untyped
1678
+ def add_comment(cell_address, text, author: "Author", sheet: nil, guid: nil, shape_id: nil, visible: false, anchor: nil)
1676
1679
  validate_cell_address!(cell_address)
1677
1680
  sheet_name = sheet || @sheet_order.first
1678
1681
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @comments_data.key?(sheet_name)
@@ -1680,6 +1683,8 @@ module Xlsxrb
1680
1683
  entry = { ref: cell_address, text: text, author: author }
1681
1684
  entry[:guid] = guid if guid
1682
1685
  entry[:shape_id] = shape_id if shape_id
1686
+ entry[:visible] = true if visible
1687
+ entry[:anchor] = anchor if anchor
1683
1688
  @comments_data[sheet_name] << entry
1684
1689
  end
1685
1690
 
@@ -1766,22 +1771,27 @@ module Xlsxrb
1766
1771
  alias person_list persons
1767
1772
 
1768
1773
  # Adds a pivot table to the given sheet.
1769
- # source_ref: data source range (e.g. "Sheet1!A1:C4").
1770
- # row_fields: array of 0-based field indices for row axis.
1771
- # data_fields: array of { fld:, name:, subtotal: } hashes.
1772
- # col_fields: array of 0-based field indices for column axis.
1774
+ # source_ref: data source range (e.g. "Sheet1!A1:C4"), or nil with source_name: for a table source.
1775
+ # row_fields: array of 0-based field indices, or field names listed in field_names, for row axis.
1776
+ # data_fields: array of { fld:, name:, subtotal: } hashes ({ field: } takes a field name or index
1777
+ # in place of fld:), or field names.
1778
+ # col_fields: array of 0-based field indices, or field names, for column axis.
1773
1779
  # field_names: array of field name strings (for cache definition).
1774
1780
  # items: hash mapping field index to array of item values.
1775
- # : (untyped source_ref, row_fields: untyped, data_fields: untyped, ?col_fields: untyped, ?dest_ref: ::String, ?name: untyped?, ?field_names: untyped?, ?items: untyped?, ?sheet: untyped?, **untyped opts) -> untyped
1776
- def add_pivot_table(source_ref, row_fields:, data_fields:, col_fields: [], dest_ref: "E1", name: nil, field_names: nil, items: nil, sheet: nil, **opts)
1781
+ # : (untyped source_ref, row_fields: untyped, data_fields: untyped, ?col_fields: untyped, ?column_fields: untyped, ?dest_ref: untyped, ?destination: untyped, ?name: untyped?, ?field_names: untyped?, ?items: untyped?, ?sheet: untyped?, **untyped opts) -> untyped
1782
+ def add_pivot_table(source_ref, row_fields:, data_fields:, col_fields: nil, column_fields: nil, dest_ref: nil, destination: nil, name: nil, field_names: nil, items: nil, sheet: nil, **opts)
1777
1783
  sheet_name = sheet || @sheet_order.first
1778
1784
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @pivot_tables_data.key?(sheet_name)
1779
1785
 
1780
1786
  pt_name = name || "PivotTable#{@pivot_tables_data.values.flatten.size + 1}"
1787
+ row_fields = row_fields.map { |f| resolve_pivot_field(f, field_names) }
1788
+ c_fields = (column_fields || col_fields || []).map { |f| resolve_pivot_field(f, field_names) }
1789
+ data_fields = data_fields.map { |df| resolve_pivot_data_field(df, field_names) }
1790
+ target_dest = destination || dest_ref || "E1"
1781
1791
  @pivot_tables_data[sheet_name] << {
1782
1792
  name: pt_name, source_ref: source_ref,
1783
- row_fields: row_fields, col_fields: col_fields,
1784
- data_fields: data_fields, dest_ref: dest_ref,
1793
+ row_fields: row_fields, col_fields: c_fields, column_fields: c_fields,
1794
+ data_fields: data_fields, dest_ref: target_dest, destination: target_dest,
1785
1795
  field_names: field_names, items: items,
1786
1796
  data_caption: opts[:data_caption], data_on_rows: opts[:data_on_rows],
1787
1797
  row_grand_totals: opts[:row_grand_totals], col_grand_totals: opts[:col_grand_totals],
@@ -1798,6 +1808,7 @@ module Xlsxrb
1798
1808
  cache_created_version: opts[:cache_created_version], cache_record_count: opts[:cache_record_count],
1799
1809
  cache_optimize_memory: opts[:cache_optimize_memory],
1800
1810
  row_page_count: opts[:row_page_count], col_page_count: opts[:col_page_count],
1811
+ first_header_row: opts[:first_header_row], first_data_row: opts[:first_data_row], first_data_col: opts[:first_data_col],
1801
1812
  field_attrs: opts[:field_attrs],
1802
1813
  apply_number_formats: opts[:apply_number_formats],
1803
1814
  apply_border_formats: opts[:apply_border_formats],
@@ -1826,6 +1837,35 @@ module Xlsxrb
1826
1837
  }
1827
1838
  end
1828
1839
 
1840
+ # Resolves a pivot table field given as a 0-based index or as a name in field_names.
1841
+ # : (untyped field, untyped field_names) -> Integer
1842
+ def resolve_pivot_field(field, field_names)
1843
+ return field if field.is_a?(Integer)
1844
+ raise ArgumentError, "pivot table field #{field.inspect} is a name; pass field_names: to resolve it" unless field_names
1845
+
1846
+ index = field_names.index(field.to_s)
1847
+ raise ArgumentError, "pivot table field #{field.inspect} is not in field_names #{field_names.inspect}" unless index
1848
+
1849
+ index
1850
+ end
1851
+ private :resolve_pivot_field
1852
+
1853
+ # Normalizes a pivot table data field to a Hash with an Integer fld.
1854
+ # : (untyped data_field, untyped field_names) -> Hash[Symbol, untyped]
1855
+ def resolve_pivot_data_field(data_field, field_names)
1856
+ data_field = { field: data_field } unless data_field.is_a?(Hash)
1857
+ return data_field if data_field[:fld].is_a?(Integer) && !data_field.key?(:field)
1858
+
1859
+ field = data_field.key?(:field) ? data_field[:field] : data_field[:fld]
1860
+ raise ArgumentError, "pivot table data field #{data_field.inspect} needs fld: or field:" if field.nil?
1861
+
1862
+ fld = resolve_pivot_field(field, field_names)
1863
+ subtotal = (data_field[:subtotal] || "sum").to_s
1864
+ caption = data_field[:name] || "#{subtotal[0].upcase}#{subtotal[1..]} of #{field_names ? field_names[fld] : "Field#{fld + 1}"}"
1865
+ data_field.except(:field).merge(fld: fld, name: caption, subtotal: subtotal)
1866
+ end
1867
+ private :resolve_pivot_data_field
1868
+
1829
1869
  # Returns pivot table definitions for the first (or given) sheet.
1830
1870
  # : (?sheet: untyped?) -> untyped
1831
1871
  def pivot_tables(sheet: nil)
@@ -2303,7 +2343,8 @@ module Xlsxrb
2303
2343
  attrs << %(windowHeight="#{@workbook_views[:window_height]}") if @workbook_views[:window_height]
2304
2344
  attrs << %(tabRatio="#{@workbook_views[:tab_ratio]}") if @workbook_views[:tab_ratio]
2305
2345
  attrs << %(firstSheet="#{@workbook_views[:first_sheet]}") if @workbook_views[:first_sheet]
2306
- attrs << %(activeTab="#{@workbook_views[:active_tab]}") if @workbook_views[:active_tab]
2346
+ at = @workbook_views[:active_sheet_index] || @workbook_views[:active_tab]
2347
+ attrs << %(activeTab="#{at}") if at
2307
2348
  afdg = @workbook_views[:auto_filter_date_grouping]
2308
2349
  attrs << %(autoFilterDateGrouping="#{afdg ? 1 : 0}") unless afdg.nil?
2309
2350
  parts << "<bookViews>"
@@ -2543,8 +2584,11 @@ module Xlsxrb
2543
2584
  outline_attrs << %(showOutlineSymbols="#{sos ? 1 : 0}") unless sos.nil?
2544
2585
  sp_children << "<outlinePr #{outline_attrs.join(" ")}/>"
2545
2586
  end
2587
+ psp = sheet_props[:page_setup_properties] || sheet_props[:page_setup_pr]
2546
2588
  ftp = sheet_props[:fit_to_page]
2589
+ ftp = psp[:fit_to_page] if ftp.nil? && psp.is_a?(Hash)
2547
2590
  apb = sheet_props[:auto_page_breaks]
2591
+ apb = psp[:auto_page_breaks] if apb.nil? && psp.is_a?(Hash)
2548
2592
  unless ftp.nil? && apb.nil?
2549
2593
  psp_attrs = []
2550
2594
  psp_attrs << %(fitToPage="#{ftp ? 1 : 0}") unless ftp.nil?
@@ -2614,22 +2658,25 @@ module Xlsxrb
2614
2658
  end
2615
2659
  pane_attrs << %(activePane="#{active_pane}")
2616
2660
  parts << "<pane #{pane_attrs.join(" ")}/>"
2617
- elsif sheet_fp && (sheet_fp[:row].to_i.positive? || sheet_fp[:col].to_i.positive?)
2618
- top_left = "#{index_to_column_letter(sheet_fp[:col].to_i + 1)}#{sheet_fp[:row].to_i + 1}"
2619
- pane_attrs = []
2620
- pane_attrs << %(ySplit="#{sheet_fp[:row]}") if sheet_fp[:row].to_i.positive?
2621
- pane_attrs << %(xSplit="#{sheet_fp[:col]}") if sheet_fp[:col].to_i.positive?
2622
- pane_attrs << %(topLeftCell="#{top_left}")
2623
- active_pane = if sheet_fp[:row].to_i.positive? && sheet_fp[:col].to_i.positive?
2624
- "bottomRight"
2625
- elsif sheet_fp[:row].to_i.positive?
2626
- "bottomLeft"
2627
- else
2628
- "topRight"
2629
- end
2630
- pane_attrs << %(activePane="#{active_pane}")
2631
- pane_attrs << 'state="frozen"'
2632
- parts << "<pane #{pane_attrs.join(" ")}/>"
2661
+ elsif sheet_fp
2662
+ fp_col = sheet_fp[:column] || sheet_fp[:col] || 0
2663
+ if sheet_fp[:row].to_i.positive? || fp_col.to_i.positive?
2664
+ top_left = "#{index_to_column_letter(fp_col.to_i + 1)}#{sheet_fp[:row].to_i + 1}"
2665
+ pane_attrs = []
2666
+ pane_attrs << %(ySplit="#{sheet_fp[:row]}") if sheet_fp[:row].to_i.positive?
2667
+ pane_attrs << %(xSplit="#{fp_col}") if fp_col.to_i.positive?
2668
+ pane_attrs << %(topLeftCell="#{top_left}")
2669
+ active_pane = if sheet_fp[:row].to_i.positive? && fp_col.to_i.positive?
2670
+ "bottomRight"
2671
+ elsif sheet_fp[:row].to_i.positive?
2672
+ "bottomLeft"
2673
+ else
2674
+ "topRight"
2675
+ end
2676
+ pane_attrs << %(activePane="#{active_pane}")
2677
+ pane_attrs << 'state="frozen"'
2678
+ parts << "<pane #{pane_attrs.join(" ")}/>"
2679
+ end
2633
2680
  end
2634
2681
 
2635
2682
  if sheet_sel
@@ -2987,8 +3034,8 @@ module Xlsxrb
2987
3034
  ps_attrs << %(cellComments="#{sheet_ps[:cell_comments]}") if sheet_ps[:cell_comments]
2988
3035
  ps_attrs << %(firstPageNumber="#{sheet_ps[:first_page_number]}") if sheet_ps[:first_page_number] && sheet_ps[:first_page_number].to_i >= 0
2989
3036
  ps_attrs << 'useFirstPageNumber="1"' if sheet_ps[:use_first_page_number]
2990
- ps_attrs << %(horizontalDpi="#{sheet_ps[:horizontal_dpi]}") if sheet_ps[:horizontal_dpi]
2991
- ps_attrs << %(verticalDpi="#{sheet_ps[:vertical_dpi]}") if sheet_ps[:vertical_dpi]
3037
+ ps_attrs << %(horizontalDpi="#{sheet_ps[:horizontal_dpi]}") if sheet_ps[:horizontal_dpi].to_i.positive?
3038
+ ps_attrs << %(verticalDpi="#{sheet_ps[:vertical_dpi]}") if sheet_ps[:vertical_dpi].to_i.positive?
2992
3039
  ps_attrs << %(copies="#{sheet_ps[:copies]}") if sheet_ps[:copies]
2993
3040
  ps_attrs << %(paperHeight="#{sheet_ps[:paper_height]}") if sheet_ps[:paper_height]
2994
3041
  ps_attrs << %(paperWidth="#{sheet_ps[:paper_width]}") if sheet_ps[:paper_width]
@@ -3017,7 +3064,15 @@ module Xlsxrb
3017
3064
 
3018
3065
  # Emit <rowBreaks> if defined.
3019
3066
  unless sheet_rb.empty?
3020
- manual_count = sheet_rb.count { |r| r.is_a?(Hash) || r.respond_to?(:fetch) ? r.fetch(:man, true) : true }
3067
+ manual_count = sheet_rb.count do |r|
3068
+ if r.is_a?(Elements::PageBreak)
3069
+ r.manual?
3070
+ elsif r.is_a?(Hash)
3071
+ r[:man] != false
3072
+ else
3073
+ true
3074
+ end
3075
+ end
3021
3076
  parts << %(<rowBreaks count="#{sheet_rb.size}" manualBreakCount="#{manual_count}">)
3022
3077
  sheet_rb.each { |r| parts << emit_brk_xml(r, default_max: 16_383) }
3023
3078
  parts << "</rowBreaks>"
@@ -3025,7 +3080,15 @@ module Xlsxrb
3025
3080
 
3026
3081
  # Emit <colBreaks> if defined.
3027
3082
  unless sheet_cb.empty?
3028
- manual_count = sheet_cb.count { |c| c.is_a?(Hash) || c.respond_to?(:fetch) ? c.fetch(:man, true) : true }
3083
+ manual_count = sheet_cb.count do |c|
3084
+ if c.is_a?(Elements::PageBreak)
3085
+ c.manual?
3086
+ elsif c.is_a?(Hash)
3087
+ c[:man] != false
3088
+ else
3089
+ true
3090
+ end
3091
+ end
3029
3092
  parts << %(<colBreaks count="#{sheet_cb.size}" manualBreakCount="#{manual_count}">)
3030
3093
  sheet_cb.each { |c| parts << emit_brk_xml(c, default_max: 1_048_575) }
3031
3094
  parts << "</colBreaks>"
@@ -3164,7 +3227,7 @@ module Xlsxrb
3164
3227
  col_attrs = %(id="#{i + 1}" name="#{xml_escape(col_name)}")
3165
3228
  if col.is_a?(Hash) || col.is_a?(Elements::TableColumn)
3166
3229
  calc_formula = col[:calculated_column_formula] || col[:data_formula] || col[:formula]
3167
- tot_formula = col[:totals_row_formula] || col[:total_row_formula] || col[:total_formula]
3230
+ tot_formula = col[:totals_row_formula]
3168
3231
  trf = col[:totals_row_function] || ("custom" if tot_formula)
3169
3232
  col_attrs << %( totalsRowFunction="#{trf}") if trf
3170
3233
  col_attrs << %( totalsRowLabel="#{xml_escape(col[:totals_row_label])}") if col[:totals_row_label]
@@ -3185,7 +3248,8 @@ module Xlsxrb
3185
3248
  end
3186
3249
  end
3187
3250
  parts << "</tableColumns>"
3188
- raw_style = tbl[:style]
3251
+ raw_style = tbl[:style] || tbl[:style_info]
3252
+ raw_style = raw_style.to_h if raw_style.respond_to?(:to_h)
3189
3253
  style = if raw_style.is_a?(Hash)
3190
3254
  raw_style
3191
3255
  elsif raw_style
@@ -17,15 +17,20 @@ begin
17
17
  end
18
18
  end
19
19
  if defined?(REXML::Security)
20
+ # REXML keeps these limits in class variables, which non-main Ractors cannot read.
21
+ # Move them to module instance variables, carrying over the values the application
22
+ # has already set (e.g. 0 to disable entity expansion).
23
+ current_limit = REXML::Security.entity_expansion_limit
24
+ current_text_limit = REXML::Security.entity_expansion_text_limit
20
25
  prev_verbose = $VERBOSE
21
26
  $VERBOSE = nil
22
27
  begin
23
28
  REXML::Security.instance_eval do
24
- @entity_expansion_limit = 10_000
25
- @entity_expansion_text_limit = 10_240
29
+ @entity_expansion_limit = current_limit
30
+ @entity_expansion_text_limit = current_text_limit
26
31
 
27
32
  def self.entity_expansion_limit
28
- @entity_expansion_limit || 10_000
33
+ @entity_expansion_limit
29
34
  end
30
35
 
31
36
  def self.entity_expansion_limit=(val)
@@ -33,7 +38,7 @@ begin
33
38
  end
34
39
 
35
40
  def self.entity_expansion_text_limit
36
- @entity_expansion_text_limit || 10_240
41
+ @entity_expansion_text_limit
37
42
  end
38
43
 
39
44
  def self.entity_expansion_text_limit=(val)
@@ -57,11 +62,79 @@ module Xlsxrb
57
62
  module XmlParser
58
63
  # Parses XML string using SAX2, calling the given listener.
59
64
  def self.parse(xml_string, listener)
60
- parser = REXML::Parsers::SAX2Parser.new(xml_string)
65
+ parser = sax2_parser(xml_string)
61
66
  parser.listen(listener)
62
67
  parser.parse
63
68
  end
64
69
 
70
+ # Returns a SAX2 parser whose listeners receive attribute values with XML entities
71
+ # decoded. REXML's SAX2 parser decodes text but passes attribute values as written, so
72
+ # formatCode="&quot;$&quot;0" would otherwise arrive with the &quot; references.
73
+ #: (String xml_string) -> REXML::Parsers::SAX2Parser
74
+ def self.sax2_parser(xml_string)
75
+ DecodingSAX2Parser.new(xml_string)
76
+ end
77
+
78
+ # SAX2 parser that wraps each listener in an AttributeDecoder.
79
+ class DecodingSAX2Parser < REXML::Parsers::SAX2Parser
80
+ #: (*untyped args) ?{ (*untyped) -> untyped } -> untyped
81
+ def listen(*args, &)
82
+ return super if args.size != 1 || args.first.is_a?(Symbol) || args.first.is_a?(Array) || block_given?
83
+
84
+ super(AttributeDecoder.new(args.first))
85
+ end
86
+ end
87
+
88
+ # Forwards SAX2 events to a listener, decoding entity references in attribute values.
89
+ class AttributeDecoder
90
+ #: (untyped listener) -> void
91
+ def initialize(listener)
92
+ @listener = listener
93
+ end
94
+
95
+ # Plain methods rather than define_method blocks, which Ractors cannot share.
96
+ #: (*untyped args) -> untyped
97
+ def start_document(*args) = @listener.start_document(*args)
98
+ #: (*untyped args) -> untyped
99
+ def end_document(*args) = @listener.end_document(*args)
100
+ #: (*untyped args) -> untyped
101
+ def start_prefix_mapping(*args) = @listener.start_prefix_mapping(*args)
102
+ #: (*untyped args) -> untyped
103
+ def end_prefix_mapping(*args) = @listener.end_prefix_mapping(*args)
104
+ #: (*untyped args) -> untyped
105
+ def end_element(*args) = @listener.end_element(*args)
106
+ #: (*untyped args) -> untyped
107
+ def characters(*args) = @listener.characters(*args)
108
+ #: (*untyped args) -> untyped
109
+ def processing_instruction(*args) = @listener.processing_instruction(*args)
110
+ #: (*untyped args) -> untyped
111
+ def doctype(*args) = @listener.doctype(*args)
112
+ #: (*untyped args) -> untyped
113
+ def attlistdecl(*args) = @listener.attlistdecl(*args)
114
+ #: (*untyped args) -> untyped
115
+ def elementdecl(*args) = @listener.elementdecl(*args)
116
+ #: (*untyped args) -> untyped
117
+ def entitydecl(*args) = @listener.entitydecl(*args)
118
+ #: (*untyped args) -> untyped
119
+ def notationdecl(*args) = @listener.notationdecl(*args)
120
+ #: (*untyped args) -> untyped
121
+ def cdata(*args) = @listener.cdata(*args)
122
+ #: (*untyped args) -> untyped
123
+ def xmldecl(*args) = @listener.xmldecl(*args)
124
+ #: (*untyped args) -> untyped
125
+ def comment(*args) = @listener.comment(*args)
126
+ #: (*untyped args) -> untyped
127
+ def progress(*args) = @listener.progress(*args)
128
+
129
+ #: (String? uri, String local_name, String qname, Hash[String, String] attributes) -> untyped
130
+ def start_element(uri, local_name, qname, attributes)
131
+ if attributes.each_value.any? { |value| value.include?("&") }
132
+ attributes = attributes.transform_values { |value| value.include?("&") ? REXML::Text.unnormalize(value) : value }
133
+ end
134
+ @listener.start_element(uri, local_name, qname, attributes)
135
+ end
136
+ end
137
+
65
138
  # Base listener with unmapped-data collection support.
66
139
  class BaseListener
67
140
  include REXML::SAX2Listener