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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 126fcecf7b280d0b6b978cfb12151e67da9d54289718f71a0bdd91186cc810d7
4
- data.tar.gz: da5c941c4a66c43c3ab7471d68784549ffcdaaf65ac865449b6d73b30aae0104
3
+ metadata.gz: d7e0f9eb696ffcaeb77f17767a9eb0aa9a70c80e0ca1a20e7d043fab7a89725f
4
+ data.tar.gz: 11884cc0efeedc8745147d5a6baf660662836989f5708c66064353e6fb73b1be
5
5
  SHA512:
6
- metadata.gz: d00259b8db777c33f123b8c9bcc5a3a34121c99c780171aca78c557e08d796fc016d6340cb4ffa551af21447be0bb69dc86a067bc3469422429d65e213441d47
7
- data.tar.gz: a962faf4eb6892ed08135dc0de71451a77661c70c6da688b606eff8ab090ab948362b671277033d0e3f45266f85d4accbe6d3d2bd3f9b191035529c1054118c5
6
+ metadata.gz: 39f84f6fdf218ca637effb2dbe7dfb15626b649f540122fd47452ab58989f3f20818e6d345bcd438f3bc177f8749fa027c7ea50874e0eeb4502f879235870296
7
+ data.tar.gz: d115e40c6f91726b7541be94050c8245b7134182ab433bf49ba47c69ddc6d86539485024ac27cec27a69c4721e58b2ee18f1bfd6a58fdd69a251d3b74a34164d
data/CHANGELOG.md CHANGED
@@ -1,3 +1,46 @@
1
+ ## [0.2.3] - 2026-11-27
2
+
3
+ ### Changed
4
+ - Parse workbook metadata and protection, worksheet metadata, relationship parts, and worksheet drawings in a single XML pass per part in `Xlsxrb.load`, and reuse parsed workbook relationships, worksheet relationships, and threaded-comment person maps instead of re-reading those ZIP entries.
5
+ - Build XML parts in `Ooxml::Writer`, its `DrawingXml`, `FeaturesXml`, and `StylesXml` mixins, and `Ooxml::Crypto::Agile` through `Ooxml::XmlBuilder` ([ADR 0014](docs/adr/0014-build-xml-through-xml-builder.md)), keeping string concatenation only for cell-loop and shared-string hot paths in `Ooxml::WorksheetWriter` and `Ooxml::WorkbookWriter`.
6
+
7
+ ### Fixed
8
+ - Guard against oversized 64-bit stream sizes and truncated DIFAT sectors in `Ooxml::Cfb::Reader` so corrupted CFB containers do not raise `RangeError` or `NoMethodError`.
9
+ - Wrap REXML unknown encoding name and encoding conversion errors as `Xlsxrb::ParseError` in `Ooxml::XmlParser`.
10
+ - Scrub invalid UTF-8 byte sequences in `Ooxml::SharedStringsParser` and `Ooxml::WorksheetParser` before XML entity unescaping and newline normalization.
11
+ - Scrub invalid UTF-8 bytes in ZIP entry names inside `Ooxml::ZipReader` instead of raising `ArgumentError` during case-insensitive catalog lookup.
12
+ - Set the ZIP UTF-8 language encoding flag (general purpose bit 11, `0x0800`) in `Ooxml::ZipWriter` and `Ooxml::ZipGenerator` when writing non-ASCII entry names so external ZIP readers decode UTF-8 filenames instead of treating them as raw bytes.
13
+ - Truncate fractional time portions in `Ooxml::Utils.serial_to_date` so `Cell#to_date` and `StreamRow#values(type_cast: true)` return exact `Date` instances equal to `Date.new(...)` instead of carrying sub-day rational offsets.
14
+ - Pass `date1904: date1904?` from `Elements::Cell#formatted_value` to `NumberFormatter.format` so formatted dates and times on 1904-epoch workbooks do not shift by four years and one day.
15
+ - Apply the current definition of a redefined named column style to `Date` and `Time` cells in `StreamWriter#with_date_style_variants` when the redefined style specifies a number format, matching `WorkbookBuilder`.
16
+ - Parse self-closing `<is/>` elements in inline string cells as empty strings in `Ooxml::WorksheetParser` (`each_row`, `fast_scan_row_values`, and `each_event`) so they match `Ooxml::Reader::WorksheetListener`.
17
+ - Preserve formula attributes (`type`, `ref`, `shared_index`, `calculate_always`, and data-table flags) and expand shared formulas in `Ooxml::WorksheetParser`, `StreamRow`, `Xlsxrb.load`, and `Xlsxrb.read`, and emit self-closing `<f t="shared" si="..."/>` tags for shared formula slaves in `Ooxml::WorksheetWriter`.
18
+ - Enforce `max_uncompressed_size` for stored (`method == 0`) ZIP entries in `Ooxml::ZipReader#read_entry` and `#decompress`, matching `EntryStreamIO`.
19
+ - Skip single-quoted sheet names (`'Q1'!`, `'O''Reilly'!`) and unquoted sheet prefixes before `!` (`S1!`, `Q1!`) in `Xlsxrb.expand_formula` so short or quoted sheet names matching cell-reference patterns are not shifted.
20
+ - Unwrap `<![CDATA[...]]>` sections in `Ooxml::WorksheetParser.normalize_text` and handle SAX2 `cdata` callbacks in `Ooxml::Reader::WorksheetListener` so inline string cells containing CDATA return their text content instead of literal CDATA markers or empty strings.
21
+ - Scrub invalid UTF-8 byte sequences before running the regex fallback in `Ooxml::RelationshipsParser.parse_all` instead of raising `ArgumentError`.
22
+ - Forward `Elements::Row#collapsed?` into row attributes in `Ooxml::WorkbookWriter` so collapsed row outlines built in memory or re-saved via `to_data` emit `collapsed="1"` matching `StreamWriter`.
23
+ - Preserve per-series `:chart_type` values read from combo charts in `Ooxml::Writer::DrawingXml#group_chart_series` so re-saving a loaded workbook keeps `comboChart` series types instead of collapsing them to `barChart`.
24
+ - Emit an empty `<gradientFill/>` element when gradient stops are `nil` or empty in `Ooxml::WorkbookWriter#build_styles_xml` instead of raising `NoMethodError`.
25
+ - Parse `<autoFilter>` inside table XML in `Ooxml::Reader::TableListener` and preserve the presence or absence of table auto-filters when writing loaded workbooks in `Ooxml::WorkbookWriter#build_table_xml`.
26
+ - Emit `colorFilter`, `iconFilter`, `hiddenButton`, `showButton`, `sortMethod`, extra `sortCondition` attributes, and `Elements::SortState#conditions` in `Ooxml::WorksheetWriter#write_auto_filter` and `#write_filter_column` so filter columns and sort states survive `StreamWriter` output and `to_data` re-saves.
27
+ - Preserve `false` boolean values in `Elements::Workbook#initialize`, `WorkbookBuilder#custom_properties`, and `StreamWriter#custom_properties` instead of falling through `v[:value] || v["value"]` to `nil`.
28
+ - Share a single person table across worksheets when writing threaded comments in `Ooxml::WorkbookWriter` and emit `[Content_Types].xml` overrides for `xl/threadedComments/threadedComment*.xml` from the sheet list so multi-sheet threaded comments do not leave dangling `personId` references and `StreamWriter` emits valid content types.
29
+ - Synchronize `_xlnm.Print_Area` and `_xlnm.Print_Titles` defined names and drop stale `unmapped_data` metadata in `Elements::Workbook#with` so edits to worksheet print settings, defined names, or workbook metadata persist across `to_data` and `Xlsxrb.write`.
30
+ - Register inline Hash style definitions passed in `cell_styles` in `StreamWriter#row` (including date and time format variants) so streaming rows apply inline cell styles identically to `WorkbookBuilder`.
31
+ - Deduplicate conditional formatting differential formats (`dxfs`) against `Elements::Styles` in `Ooxml::WorkbookWriter` so identical rules across sheets or repeated writes share a single `dxfId` matching `StreamWriter`.
32
+ - Clear incompatible fill properties in `StyleBuilder` when switching between solid, pattern, and gradient fills so stale gradient or pattern keys do not persist into `styles.xml`.
33
+ - Return an unfrozen empty string from `Ooxml::ZipReader::EntryStreamIO#read(0)` instead of raising `FrozenError` when forcing encoding on a frozen string literal.
34
+ - Number chart parts sequentially across sheets and mixed image/chart drawings in `Ooxml::WorkbookWriter` so workbooks with charts on multiple sheets or alongside images do not emit duplicate `xl/charts/chart1.xml` entries or mismatched `[Content_Types].xml` overrides.
35
+ - Chain multiple directory, FAT, and DIFAT sectors in `Ooxml::Cfb::Writer` so encrypted workbooks and CFB containers larger than 63 KB or holding more than three streams can be read back.
36
+ - Populate `Elements::Column#collapsed?` and `#best_fit?` in `WorksheetBuilder#column`, `Xlsxrb.load`, `StreamSheet#columns`, and `StreamSheet#load`, and forward both flags when writing built workbooks in `Xlsxrb.write`.
37
+ - Preserve existing row or column ranges when `WorksheetBuilder#print_titles` is called with only `rows:` or `columns:`, keep `StreamWriter#print_titles` synchronized after partial updates, and escape single quotes in sheet names when building and parsing `_xlnm.Print_Titles` and `_xlnm.Print_Area` defined names.
38
+ - Return `"Infinity"`, `"-Infinity"`, or `"NaN"` instead of raising `FloatDomainError` when formatting a non-finite `Float` with a `"General"`, empty, `nil`, or over-length format code in `NumberFormatter.format` and `Xlsxrb.format_value`, and preserve the format code's string encoding when splitting format sections.
39
+ - Stop double-escaping chart `frame_macro` attributes, Hash chart title text, DrawingML color `val` attributes, and threaded comment person `displayName`, `userId`, and `providerId` attributes, which escaped values containing `&`, `<`, `>`, or `"` twice.
40
+
41
+ ### Security
42
+ - Escape non-String formula cached values, Hash cell values with an explicit type, VML comment anchors, and app property heading-pair counts when writing them as XML element content.
43
+
1
44
  ## [0.2.2] - 2026-11-23
2
45
 
3
46
  ### Added
@@ -375,7 +375,7 @@ module Xlsxrb
375
375
  def formatted_value(custom_format_code = nil)
376
376
  return nil if value.nil?
377
377
 
378
- NumberFormatter.format(value, custom_format_code || format_code)
378
+ NumberFormatter.format(value, custom_format_code || format_code, date1904: date1904?)
379
379
  end
380
380
 
381
381
  # Returns the classified format category for this cell (:date, :datetime, :time, :number, :text, :general, or nil).
@@ -12,11 +12,15 @@ module Xlsxrb
12
12
  # workbook.each { |s| puts s.name }
13
13
  #
14
14
  # @api public
15
- # rubocop:disable Style/DataInheritance -- Required as class syntax for mutant subject matcher
15
+ # Class syntax is required for the mutant subject matcher.
16
16
  class Workbook < Data.define(:sheets, :shared_strings, :styles, :unmapped_data, :errors, :defined_names, :workbook_properties, :core_properties, :app_properties, :workbook_protection, :custom_properties)
17
- # rubocop:enable Style/DataInheritance
18
17
  [Enumerable].each { |m| include m }
19
18
 
19
+ STALE_UNMAPPED_KEYS = %i[
20
+ defined_names workbook_properties core_properties app_properties workbook_protection custom_properties
21
+ ].freeze
22
+ private_constant :STALE_UNMAPPED_KEYS
23
+
20
24
  # @param sheets [Array<Elements::Worksheet>] Worksheets in the workbook.
21
25
  # @param shared_strings [Array<String>] Shared strings table.
22
26
  # @param styles [Elements::Styles, Hash] Styles definition.
@@ -68,7 +72,7 @@ module Xlsxrb
68
72
  if v.is_a?(Elements::CustomProperty)
69
73
  v
70
74
  elsif v.is_a?(Hash)
71
- Elements::CustomProperty.new(name: (v[:name] || v["name"] || k).to_s, value: v[:value] || v["value"], type: v[:type] || v["type"])
75
+ Elements::CustomProperty.new(name: (v[:name] || v["name"] || k).to_s, value: v.key?(:value) ? v[:value] : v["value"], type: v[:type] || v["type"])
72
76
  else
73
77
  Elements::CustomProperty.new(name: k.to_s, value: v)
74
78
  end
@@ -76,7 +80,7 @@ module Xlsxrb
76
80
  elsif raw_custom.is_a?(Array)
77
81
  raw_custom.map do |v|
78
82
  if v.is_a?(Hash)
79
- Elements::CustomProperty.new(name: (v[:name] || v["name"]).to_s, value: v[:value] || v["value"], type: v[:type] || v["type"])
83
+ Elements::CustomProperty.new(name: (v[:name] || v["name"]).to_s, value: v.key?(:value) ? v[:value] : v["value"], type: v[:type] || v["type"])
80
84
  else
81
85
  v
82
86
  end
@@ -325,6 +329,30 @@ module Xlsxrb
325
329
  Xlsxrb.write(self, shared_strings: shared_strings, compression_level: compression_level, **options)
326
330
  end
327
331
 
332
+ # Returns a new Workbook with attributes replaced, clearing stale unmapped/facade metadata
333
+ # and keeping sheet-scoped print defined names synchronized when sheets change.
334
+ #
335
+ # @param changes [Hash]
336
+ # @return [Elements::Workbook]
337
+ # @api public
338
+ #: (**untyped) -> Elements::Workbook
339
+ def with(**changes)
340
+ return self if changes.empty?
341
+
342
+ updated = changes.dup
343
+ if updated.key?(:sheets) && !updated.key?(:defined_names) && updated[:sheets].is_a?(Array)
344
+ synced = sync_sheet_print_defined_names(updated[:sheets])
345
+ updated[:defined_names] = synced if synced
346
+ end
347
+
348
+ unless updated.key?(:unmapped_data)
349
+ cleaned = strip_stale_unmapped_data(updated)
350
+ updated[:unmapped_data] = cleaned if cleaned
351
+ end
352
+
353
+ super(**updated)
354
+ end
355
+
328
356
  # Validates workbook structure according to OOXML specifications.
329
357
  #
330
358
  # @param sheets [Array<Elements::Worksheet>]
@@ -344,6 +372,89 @@ module Xlsxrb
344
372
  end
345
373
  errs
346
374
  end
375
+
376
+ private
377
+
378
+ #: (Hash[Symbol, untyped] updated) -> Hash[untyped, untyped]?
379
+ def strip_stale_unmapped_data(updated)
380
+ return nil unless unmapped_data.is_a?(Hash)
381
+
382
+ changed_keys = STALE_UNMAPPED_KEYS.select { |k| updated.key?(k) }
383
+ return nil if changed_keys.empty?
384
+
385
+ facade = unmapped_data[:facade]
386
+ has_facade = facade.is_a?(Hash)
387
+ stale_top = changed_keys.any? { |k| unmapped_data.key?(k) }
388
+ stale_facade = has_facade && changed_keys.any? { |k| facade.key?(k) }
389
+ return nil unless stale_top || stale_facade
390
+
391
+ cleaned = unmapped_data.dup
392
+ if stale_facade
393
+ cleaned_facade = facade.dup
394
+ changed_keys.each { |k| cleaned_facade.delete(k) }
395
+ cleaned[:facade] = cleaned_facade
396
+ end
397
+ changed_keys.each { |k| cleaned.delete(k) } if stale_top
398
+ cleaned
399
+ end
400
+
401
+ #: (Array[untyped] new_sheets) -> Array[Elements::DefinedName]?
402
+ def sync_sheet_print_defined_names(new_sheets)
403
+ dns = nil #: Array[Elements::DefinedName]?
404
+ if new_sheets.size < sheets.size
405
+ dns = defined_names.dup
406
+ dns.reject! do |dn|
407
+ %w[_xlnm.Print_Area _xlnm.Print_Titles].include?(dn.name) &&
408
+ !dn.local_sheet_id.nil? && dn.local_sheet_id >= new_sheets.size
409
+ end
410
+ end
411
+
412
+ new_sheets.each_with_index do |new_ws, idx|
413
+ old_ws = sheets[idx]
414
+ new_name = new_ws.name || "Sheet#{idx + 1}"
415
+ old_name = old_ws&.name
416
+ renamed = !old_ws.nil? && new_name != old_name
417
+
418
+ if new_ws.print_area != old_ws&.print_area || (renamed && !new_ws.print_area.nil?)
419
+ dns ||= defined_names.dup
420
+ dns.reject! { |dn| matches_sheet_print_dn?(dn, "_xlnm.Print_Area", idx, old_name, new_name) }
421
+ if new_ws.print_area
422
+ quoted = DslHelpers.quote_sheet_name(new_name)
423
+ val = new_ws.print_area.split(",").map { |part| "#{quoted}!#{DslHelpers.absolute_range(part.strip)}" }.join(",")
424
+ dns << Elements::DefinedName.new(name: "_xlnm.Print_Area", value: val, local_sheet_id: idx)
425
+ end
426
+ end
427
+
428
+ next unless new_ws.print_titles != old_ws&.print_titles || (renamed && !new_ws.print_titles.nil?)
429
+
430
+ dns ||= defined_names.dup
431
+ dns.reject! { |dn| matches_sheet_print_dn?(dn, "_xlnm.Print_Titles", idx, old_name, new_name) }
432
+ next unless new_ws.print_titles
433
+
434
+ pt = new_ws.print_titles
435
+ quoted = DslHelpers.quote_sheet_name(new_name)
436
+ parts = [] #: Array[String]
437
+ parts << "#{quoted}!$#{pt.columns.sub(":", ":$")}" if pt.columns
438
+ parts << "#{quoted}!$#{pt.rows.sub(":", ":$")}" if pt.rows
439
+ dns << Elements::DefinedName.new(name: "_xlnm.Print_Titles", value: parts.join(","), local_sheet_id: idx) unless parts.empty?
440
+ end
441
+
442
+ return nil if dns.nil? || dns == defined_names
443
+
444
+ dns
445
+ end
446
+
447
+ #: (Elements::DefinedName defined_name_entry, String target_name, Integer idx, String? old_name, String new_name) -> bool
448
+ def matches_sheet_print_dn?(defined_name_entry, target_name, idx, old_name, new_name)
449
+ return false unless defined_name_entry.name == target_name
450
+ return true if !defined_name_entry.local_sheet_id.nil? && defined_name_entry.local_sheet_id == idx
451
+ return true if defined_name_entry.local_sheet_name && [old_name, new_name].include?(defined_name_entry.local_sheet_name)
452
+ return false unless defined_name_entry.local_sheet_id.nil? && defined_name_entry.value
453
+
454
+ [old_name, new_name].compact.uniq.any? do |sname|
455
+ defined_name_entry.value.start_with?("#{DslHelpers.quote_sheet_name(sname)}!", "#{sname}!")
456
+ end
457
+ end
347
458
  end
348
459
  end
349
460
  end
@@ -38,11 +38,11 @@ module Xlsxrb
38
38
  return "" if value.nil?
39
39
  return value.code.to_s if value.respond_to?(:code)
40
40
  return value ? "TRUE" : "FALSE" if [true, false].include?(value)
41
+ # Infinity and NaN, from values such as 1e999, have no date or digits to format.
42
+ return value.to_s if value.is_a?(Float) && !value.finite?
41
43
 
42
44
  code = format_code.to_s.strip
43
45
  return default_format(value) if code.empty? || code.casecmp("general").zero? || code.length > MAX_FORMAT_CODE_LENGTH
44
- # Infinity and NaN, from values such as 1e999, have no date or digits to format.
45
- return value.to_s if value.is_a?(Float) && !value.finite?
46
46
 
47
47
  return format_datetime(value, code) if value.is_a?(Date) || value.is_a?(DateTime) || value.is_a?(Time)
48
48
 
@@ -275,7 +275,7 @@ module Xlsxrb
275
275
  private
276
276
 
277
277
  def default_format(value)
278
- if value.is_a?(Float)
278
+ if value.is_a?(Float) && value.finite?
279
279
  value == value.to_i ? value.to_i.to_s : value.to_s
280
280
  else
281
281
  value.to_s
@@ -284,7 +284,7 @@ module Xlsxrb
284
284
 
285
285
  def split_sections(code)
286
286
  sections = []
287
- current = String.new
287
+ current = String.new(encoding: code.encoding)
288
288
  in_quotes = false
289
289
  code.each_char do |ch|
290
290
  if ch == "\""
@@ -292,7 +292,7 @@ module Xlsxrb
292
292
  current << ch
293
293
  elsif ch == ";" && !in_quotes
294
294
  sections << current
295
- current = String.new
295
+ current = String.new(encoding: code.encoding)
296
296
  else
297
297
  current << ch
298
298
  end
@@ -155,10 +155,15 @@ module Xlsxrb
155
155
 
156
156
  visited[curr] = true
157
157
  sec_data = read_sector(curr)
158
+ break if sec_data.empty?
159
+
158
160
  entries_per_sec = (@sector_size / 4) - 1
159
- entries = sec_data[0, entries_per_sec * 4].unpack("V*")
161
+ entries = (sec_data[0, entries_per_sec * 4] || "".b).unpack("V*")
160
162
  @difat_sectors.concat(entries)
161
- curr = sec_data[entries_per_sec * 4, 4].unpack1("V")
163
+ next_bytes = sec_data[entries_per_sec * 4, 4]
164
+ break if next_bytes.nil? || next_bytes.bytesize < 4
165
+
166
+ curr = next_bytes.unpack1("V")
162
167
  end
163
168
  end
164
169
 
@@ -244,9 +249,9 @@ module Xlsxrb
244
249
  end
245
250
 
246
251
  def read_regular_stream_data(start_sector, total_size)
247
- return "".b if [ENDOFCHAIN, FREESECT].include?(start_sector) || total_size.zero?
252
+ return "".b if [ENDOFCHAIN, FREESECT].include?(start_sector) || total_size <= 0
248
253
 
249
- result = +""
254
+ result = +"".b
250
255
  curr = start_sector
251
256
  visited = {}
252
257
  while curr != ENDOFCHAIN && curr != FREESECT && curr < @fat.size
@@ -258,13 +263,13 @@ module Xlsxrb
258
263
 
259
264
  curr = @fat[curr]
260
265
  end
261
- result[0, total_size] || "".b
266
+ result.bytesize > total_size ? (result.byteslice(0, total_size) || "".b) : result
262
267
  end
263
268
 
264
269
  def read_mini_stream_data(start_mini_sector, total_size)
265
- return "".b if [ENDOFCHAIN, FREESECT].include?(start_mini_sector) || total_size.zero?
270
+ return "".b if [ENDOFCHAIN, FREESECT].include?(start_mini_sector) || total_size <= 0
266
271
 
267
- result = +""
272
+ result = +"".b
268
273
  curr = start_mini_sector
269
274
  visited = {}
270
275
  while curr != ENDOFCHAIN && curr != FREESECT && curr < @minifat.size
@@ -277,7 +282,7 @@ module Xlsxrb
277
282
 
278
283
  curr = @minifat[curr]
279
284
  end
280
- result[0, total_size] || "".b
285
+ result.bytesize > total_size ? (result.byteslice(0, total_size) || "".b) : result
281
286
  end
282
287
  end
283
288
 
@@ -399,30 +404,61 @@ module Xlsxrb
399
404
  sector_chains << [first_minifat_sec, num_minifat_sec]
400
405
  end
401
406
 
402
- # 4. Directory sector
407
+ # 4. Directory sectors (4 entries * 128 bytes = 512 bytes per sector)
403
408
  dir_sector_id = allocated_sectors.size
404
- dir_sector_bytes = +""
405
- dir_entries.each do |e|
406
- dir_sector_bytes << serialize_dir_entry(e)
409
+ num_dir_sec = dir_entries.size / 4
410
+ num_dir_sec.times do |d_idx|
411
+ chunk = +""
412
+ 4.times do |e_idx|
413
+ chunk << serialize_dir_entry(dir_entries[(d_idx * 4) + e_idx])
414
+ end
415
+ allocated_sectors << chunk
416
+ end
417
+ sector_chains << [dir_sector_id, num_dir_sec]
418
+
419
+ # 5. FAT and DIFAT sectors
420
+ entries_per_fat_sec = sector_size / 4
421
+ difat_entries_per_sec = entries_per_fat_sec - 1
422
+ base_sectors = allocated_sectors.size
423
+ num_fat_sec = 1
424
+ num_difat_sec = 0
425
+ loop do
426
+ needed_difat = num_fat_sec > 109 ? ((num_fat_sec - 109 + difat_entries_per_sec - 1) / difat_entries_per_sec) : 0
427
+ total_sectors = base_sectors + num_fat_sec + needed_difat
428
+ needed_fat = (total_sectors + entries_per_fat_sec - 1) / entries_per_fat_sec
429
+ break if needed_fat == num_fat_sec && needed_difat == num_difat_sec
430
+
431
+ num_fat_sec = needed_fat
432
+ num_difat_sec = needed_difat
407
433
  end
408
- allocated_sectors << dir_sector_bytes
409
434
 
410
- # 5. FAT sector
411
- fat_sector_id = allocated_sectors.size
412
- fat = Array.new(fat_sector_id + 1, FREESECT)
435
+ first_fat_sec_id = allocated_sectors.size
436
+ fat_sector_ids = Array.new(num_fat_sec) { |i| first_fat_sec_id + i }
437
+ first_difat_sec = num_difat_sec.positive? ? (first_fat_sec_id + num_fat_sec) : ENDOFCHAIN
413
438
 
414
- # Populate regular sector chains in FAT
439
+ fat = Array.new(num_fat_sec * entries_per_fat_sec, FREESECT)
415
440
  sector_chains.each do |start_sec, num_sec|
416
441
  num_sec.times do |s_idx|
417
442
  fat[start_sec + s_idx] = s_idx == num_sec - 1 ? ENDOFCHAIN : (start_sec + s_idx + 1)
418
443
  end
419
444
  end
445
+ fat_sector_ids.each { |sec_id| fat[sec_id] = FATSECT }
446
+ num_difat_sec.times { |d_idx| fat[first_difat_sec + d_idx] = DIFATSECT }
420
447
 
421
- fat[dir_sector_id] = ENDOFCHAIN
422
- fat[fat_sector_id] = FATSECT
448
+ fat_bytes = fat.pack("V*")
449
+ num_fat_sec.times do |f_idx|
450
+ allocated_sectors << fat_bytes[f_idx * sector_size, sector_size]
451
+ end
423
452
 
424
- fat_bytes = fat.pack("V*").ljust(sector_size, 255.chr(Encoding::BINARY))
425
- allocated_sectors << fat_bytes
453
+ if num_difat_sec.positive?
454
+ overflow_fat_ids = fat_sector_ids[109..] || []
455
+ num_difat_sec.times do |d_idx|
456
+ slice = overflow_fat_ids[d_idx * difat_entries_per_sec, difat_entries_per_sec] || []
457
+ padded = slice + Array.new(difat_entries_per_sec - slice.size, FREESECT)
458
+ next_difat = d_idx == num_difat_sec - 1 ? ENDOFCHAIN : (first_difat_sec + d_idx + 1)
459
+ allocated_sectors << (padded + [next_difat]).pack("V128")
460
+ end
461
+ end
426
462
 
427
463
  # Build Header (512 bytes)
428
464
  header = +""
@@ -434,18 +470,18 @@ module Xlsxrb
434
470
  header << [6].pack("v") # 0x20 Mini sector shift (64 bytes)
435
471
  header << ("\x00".b * 6) # 0x22 Reserved
436
472
  header << [0].pack("V") # 0x28 Number of Directory sectors (0 for v3)
437
- header << [1].pack("V") # 0x2C Number of FAT sectors (1)
473
+ header << [num_fat_sec].pack("V") # 0x2C Number of FAT sectors
438
474
  header << [dir_sector_id].pack("V") # 0x30 First Directory sector
439
475
  header << [0].pack("V") # 0x34 Transaction signature
440
476
  header << [MINI_STREAM_CUTOFF].pack("V") # 0x38 Mini stream cutoff size (4096)
441
477
  header << [first_minifat_sec].pack("V") # 0x3C First Mini FAT sector
442
478
  header << [num_minifat_sec].pack("V") # 0x40 Number of Mini FAT sectors
443
- header << [ENDOFCHAIN].pack("V") # 0x44 First DIFAT sector
444
- header << [0].pack("V") # 0x48 Number of DIFAT sectors
479
+ header << [first_difat_sec].pack("V") # 0x44 First DIFAT sector
480
+ header << [num_difat_sec].pack("V") # 0x48 Number of DIFAT sectors
445
481
 
446
482
  # DIFAT array (109 entries * 4 bytes = 436 bytes)
447
483
  difat = Array.new(109, FREESECT)
448
- difat[0] = fat_sector_id
484
+ [num_fat_sec, 109].min.times { |i| difat[i] = fat_sector_ids[i] }
449
485
  header << difat.pack("V109")
450
486
 
451
487
  raise "Header size mismatch" unless header.bytesize == 512
@@ -5,6 +5,7 @@
5
5
  require "openssl"
6
6
  require "rexml/document"
7
7
  require "securerandom"
8
+ require_relative "../xml_builder"
8
9
 
9
10
  module Xlsxrb
10
11
  module Ooxml
@@ -144,18 +145,46 @@ module Xlsxrb
144
145
  encrypted_hmac_val = aes_encrypt(cipher_name, package_key, digest.digest(key_data_salt + BLOCK_KEY_INTEGRITY_VALUE), hmac_value)
145
146
 
146
147
  # Build EncryptionInfo XML
147
- xml = <<~XML
148
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
149
- <encryption xmlns="http://schemas.microsoft.com/office/2006/encryption" xmlns:p="http://schemas.microsoft.com/office/2006/keyEncryptor/password" xmlns:c="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate">
150
- <keyData saltSize="#{key_data_salt.bytesize}" blockSize="#{block_size}" keyBits="#{key_bits}" hashSize="#{hash_size}" cipherAlgorithm="#{cipher_algorithm}" cipherChaining="#{cipher_chaining}" hashAlgorithm="#{hash_algorithm}" saltValue="#{[key_data_salt].pack("m0")}"/>
151
- <dataIntegrity encryptedHmacKey="#{[encrypted_hmac_key].pack("m0")}" encryptedHmacValue="#{[encrypted_hmac_val].pack("m0")}"/>
152
- <keyEncryptors>
153
- <keyEncryptor uri="http://schemas.microsoft.com/office/2006/keyEncryptor/password">
154
- <p:encryptedKey spinCount="#{spin_count}" saltSize="#{encryptor_salt.bytesize}" blockSize="#{block_size}" keyBits="#{key_bits}" hashSize="#{hash_size}" cipherAlgorithm="#{cipher_algorithm}" cipherChaining="#{cipher_chaining}" hashAlgorithm="#{hash_algorithm}" saltValue="#{[encryptor_salt].pack("m0")}" encryptedVerifierHashInput="#{[encrypted_verifier_input].pack("m0")}" encryptedVerifierHashValue="#{[encrypted_verifier_val].pack("m0")}" encryptedKeyValue="#{[encrypted_key_value].pack("m0")}"/>
155
- </keyEncryptor>
156
- </keyEncryptors>
157
- </encryption>
158
- XML
148
+ xml = XmlBuilder.build(declaration: :standalone) do |b|
149
+ b.tag("encryption", {
150
+ xmlns: "http://schemas.microsoft.com/office/2006/encryption",
151
+ "xmlns:p": "http://schemas.microsoft.com/office/2006/keyEncryptor/password",
152
+ "xmlns:c": "http://schemas.microsoft.com/office/2006/keyEncryptor/certificate"
153
+ }) do
154
+ b.empty_tag("keyData", {
155
+ saltSize: key_data_salt.bytesize,
156
+ blockSize: block_size,
157
+ keyBits: key_bits,
158
+ hashSize: hash_size,
159
+ cipherAlgorithm: cipher_algorithm,
160
+ cipherChaining: cipher_chaining,
161
+ hashAlgorithm: hash_algorithm,
162
+ saltValue: [key_data_salt].pack("m0")
163
+ })
164
+ b.empty_tag("dataIntegrity", {
165
+ encryptedHmacKey: [encrypted_hmac_key].pack("m0"),
166
+ encryptedHmacValue: [encrypted_hmac_val].pack("m0")
167
+ })
168
+ b.tag("keyEncryptors") do
169
+ b.tag("keyEncryptor", { uri: "http://schemas.microsoft.com/office/2006/keyEncryptor/password" }) do
170
+ b.empty_tag("p:encryptedKey", {
171
+ spinCount: spin_count,
172
+ saltSize: encryptor_salt.bytesize,
173
+ blockSize: block_size,
174
+ keyBits: key_bits,
175
+ hashSize: hash_size,
176
+ cipherAlgorithm: cipher_algorithm,
177
+ cipherChaining: cipher_chaining,
178
+ hashAlgorithm: hash_algorithm,
179
+ saltValue: [encryptor_salt].pack("m0"),
180
+ encryptedVerifierHashInput: [encrypted_verifier_input].pack("m0"),
181
+ encryptedVerifierHashValue: [encrypted_verifier_val].pack("m0"),
182
+ encryptedKeyValue: [encrypted_key_value].pack("m0")
183
+ })
184
+ end
185
+ end
186
+ end
187
+ end
159
188
 
160
189
  # EncryptionInfo stream header: versionMajor=4, versionMinor=4, flags=0x40
161
190
  info_stream = [4, 4, 0x40].pack("vvV") + xml.b
@@ -280,6 +280,10 @@ module Xlsxrb
280
280
  @formula_buffer << text if @inside_formula
281
281
  end
282
282
 
283
+ def cdata(content)
284
+ characters(content)
285
+ end
286
+
283
287
  def end_element(_uri, local_name, qname)
284
288
  name = element_name(local_name, qname)
285
289
 
@@ -1382,6 +1382,8 @@ module Xlsxrb
1382
1382
  cid = attributes["connectionId"]
1383
1383
  @table[:connection_id] = cid.to_i if cid
1384
1384
  @table[:table_type] = attributes["tableType"] if attributes["tableType"]
1385
+ when "autoFilter"
1386
+ @table[:auto_filter] = { ref: attributes["ref"] } if @table && attributes["ref"]
1385
1387
  when "tableColumn"
1386
1388
  col = { name: attributes["name"] }
1387
1389
  trf = attributes["totalsRowFunction"]
@@ -122,7 +122,8 @@ module Xlsxrb
122
122
  # Multiple <t> tags (rich text runs)
123
123
  str = extract_multi_t(xml, si_open_end + 1, si_end, t_start_pattern, t_start_len, t_end_tag, t_end_len, rph_start_pattern, rph_end_tag, rph_end_len, has_rph: has_rph)
124
124
  else
125
- raw_str = xml.byteslice(t_open_end + 1, t_end - t_open_end - 1).force_encoding("UTF-8")
125
+ raw_str = xml.byteslice(t_open_end + 1, t_end - t_open_end - 1).force_encoding(Encoding::UTF_8)
126
+ raw_str = raw_str.scrub unless raw_str.valid_encoding?
126
127
  str = XmlBuilder.unescape(raw_str)
127
128
  end
128
129
  else
@@ -199,7 +200,8 @@ module Xlsxrb
199
200
  t_end = xml.index(t_end_tag, t_open_end + 1)
200
201
  break unless t_end && t_end <= to
201
202
 
202
- raw_chunk = xml.byteslice(t_open_end + 1, t_end - t_open_end - 1).force_encoding("UTF-8")
203
+ raw_chunk = xml.byteslice(t_open_end + 1, t_end - t_open_end - 1).force_encoding(Encoding::UTF_8)
204
+ raw_chunk = raw_chunk.scrub unless raw_chunk.valid_encoding?
203
205
  buf << XmlBuilder.unescape(raw_chunk)
204
206
  pos = t_end + t_end_len
205
207
  end
@@ -117,12 +117,13 @@ module Xlsxrb
117
117
  raise ArgumentError, "Excel serial date must be non-negative" if serial.negative?
118
118
  raise ArgumentError, "Excel serial date exceeds maximum supported date (9999-12-31)" if serial >= max_serial + 1
119
119
 
120
+ days = serial.div(1)
120
121
  if date1904
121
- EPOCH_1904 + serial
122
+ EPOCH_1904 + days
122
123
  else
123
124
  # Adjust for Lotus 1-2-3 bug.
124
- serial -= 1 if serial > 60
125
- EPOCH_1900 + serial
125
+ days -= 1 if days > 60
126
+ EPOCH_1900 + days
126
127
  end
127
128
  end
128
129