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
@@ -342,7 +342,7 @@ module Xlsxrb
342
342
  v_tag_end_str = "</#{prefix}v>"
343
343
  v_tag_end_len = v_tag_end_str.bytesize
344
344
 
345
- is_tag_start_str = "<#{prefix}is>"
345
+ is_tag_start_str = "<#{prefix}is"
346
346
  is_tag_start_len = is_tag_start_str.bytesize
347
347
  is_tag_end_str = "</#{prefix}is>"
348
348
  is_tag_end_len = is_tag_end_str.bytesize
@@ -437,11 +437,22 @@ module Xlsxrb
437
437
  else
438
438
  cpos = tag_pos + 2
439
439
  end
440
- elsif xml.byteslice(tag_pos, is_tag_start_len) == is_tag_start_str
441
- is_end = xml.index(is_tag_end_str, tag_pos + is_tag_start_len)
442
- if is_end && is_end <= c_end
443
- inline_str = extract_inline_text(xml, tag_pos + is_tag_start_len, is_end)
444
- cpos = is_end + is_tag_end_len
440
+ elsif xml.byteslice(tag_pos, is_tag_start_len) == is_tag_start_str &&
441
+ TAG_DELIM_BYTES.include?(xml.getbyte(tag_pos + is_tag_start_len))
442
+ is_tag_end = xml.index(">", tag_pos + is_tag_start_len)
443
+ if is_tag_end && is_tag_end < c_end
444
+ if xml.getbyte(is_tag_end - 1) == 47
445
+ inline_str = +""
446
+ cpos = is_tag_end + 1
447
+ else
448
+ is_end = xml.index(is_tag_end_str, is_tag_end + 1)
449
+ if is_end && is_end <= c_end
450
+ inline_str = extract_inline_text(xml, is_tag_end + 1, is_end)
451
+ cpos = is_end + is_tag_end_len
452
+ else
453
+ cpos = is_tag_end + 1
454
+ end
455
+ end
445
456
  else
446
457
  cpos = tag_pos + is_tag_start_len
447
458
  end
@@ -545,7 +556,10 @@ module Xlsxrb
545
556
  # copying. Only for Strings the caller has just created (e.g. regex captures).
546
557
  #: (String? str) -> String?
547
558
  def self.utf8!(str)
548
- str&.force_encoding(Encoding::UTF_8)
559
+ return nil unless str
560
+
561
+ str.force_encoding(Encoding::UTF_8)
562
+ str.valid_encoding? ? str : str.scrub
549
563
  end
550
564
 
551
565
  # Resolves a cell value from its type attribute and parsed XML content (<v> or <is>).
@@ -637,11 +651,40 @@ module Xlsxrb
637
651
 
638
652
  #: (String str) -> String
639
653
  def self.normalize_text(str)
640
- s = decode_xml_entities(str)
654
+ utf8 = str.encoding == Encoding::BINARY ? str.dup.force_encoding(Encoding::UTF_8) : str
655
+ utf8 = utf8.scrub unless utf8.valid_encoding?
656
+ s = utf8.include?("<![CDATA[") ? decode_text_with_cdata(utf8) : decode_xml_entities(utf8)
641
657
  s = s.gsub("\r\n", "\n").tr("\r", "\n") if s.include?("\r")
642
- s.encoding == Encoding::BINARY ? s.dup.force_encoding(Encoding::UTF_8) : s
658
+ s
643
659
  end
644
660
 
661
+ #: (String str) -> String
662
+ def self.decode_text_with_cdata(str)
663
+ utf8 = str.encoding == Encoding::BINARY ? str.dup.force_encoding(Encoding::UTF_8) : str
664
+ out = +""
665
+ pos = 0
666
+ len = utf8.length
667
+ while pos < len
668
+ c_start = utf8.index("<![CDATA[", pos)
669
+ unless c_start
670
+ out << decode_xml_entities(utf8[pos..] || "")
671
+ break
672
+ end
673
+ out << decode_xml_entities(utf8[pos...c_start] || "") if c_start > pos
674
+ body_start = c_start + 9
675
+ c_end = utf8.index("]]>", body_start)
676
+ unless c_end
677
+ out << decode_xml_entities(utf8[c_start..] || "")
678
+ break
679
+ end
680
+ out << (utf8[body_start...c_end] || "")
681
+ pos = c_end + 3
682
+ end
683
+ out
684
+ end
685
+
686
+ private_class_method :decode_text_with_cdata
687
+
645
688
  # Parses <cols> section for column definitions.
646
689
  class ColumnsListener
647
690
  include REXML::SAX2Listener
@@ -666,6 +709,8 @@ module Xlsxrb
666
709
  width: attrs["width"]&.to_f,
667
710
  hidden: attrs["hidden"] == "1" || (attrs["hidden"]&.casecmp?("true") || false),
668
711
  custom_width: attrs["customWidth"] == "1" || (attrs["customWidth"]&.casecmp?("true") || false),
712
+ best_fit: attrs["bestFit"] == "1" || (attrs["bestFit"]&.casecmp?("true") || false),
713
+ collapsed: attrs["collapsed"] == "1" || (attrs["collapsed"]&.casecmp?("true") || false),
669
714
  outline_level: attrs["outlineLevel"]&.to_i,
670
715
  style_index: attrs["style"]&.to_i
671
716
  }
@@ -708,6 +753,7 @@ module Xlsxrb
708
753
 
709
754
  pos = sd_open_end + 1
710
755
  last_row_index = -1
756
+ shared_formulas = xml.include?('t="shared"') || xml.include?("t='shared'") ? {} : nil
711
757
 
712
758
  while pos < sd_end
713
759
  row_start = xml.index(row_start_pattern, pos)
@@ -786,6 +832,11 @@ module Xlsxrb
786
832
  row_end = xml.index(row_end_tag, tag_end + 1)
787
833
  break unless row_end
788
834
 
835
+ if shared_formulas
836
+ shared_pos = xml.byteindex("shared", tag_end + 1)
837
+ record_shared_masters(xml, tag_end + 1, row_end, shared_formulas, row_index) if shared_pos && shared_pos < row_end
838
+ end
839
+
789
840
  row_obj = StreamRow.fast_create(
790
841
  row_index,
791
842
  xml,
@@ -801,7 +852,8 @@ module Xlsxrb
801
852
  styles,
802
853
  date1904,
803
854
  attrs[:collapsed] || false,
804
- pad_empty_cells
855
+ pad_empty_cells,
856
+ shared_formulas
805
857
  )
806
858
  block.call(row_obj)
807
859
 
@@ -828,6 +880,7 @@ module Xlsxrb
828
880
  row_end_len = 6
829
881
  sd_end_tag = "</sheetData>"
830
882
  last_row_index = -1
883
+ shared_formulas = nil
831
884
  # SECURITY NOTE: The buffer is searched again each time a chunk is added. These hold
832
885
  # how far the previous searches got without a match, so that a row or a stretch of
833
886
  # other markup spanning many chunks is searched once, not once per chunk.
@@ -987,6 +1040,10 @@ module Xlsxrb
987
1040
  end
988
1041
 
989
1042
  cells_xml = buffer.byteslice(tag_end + 1, row_end - (tag_end + 1))
1043
+ if cells_xml.include?('t="shared"') || cells_xml.include?("t='shared'")
1044
+ shared_formulas ||= {}
1045
+ record_shared_masters(cells_xml, 0, cells_xml.bytesize, shared_formulas, row_index)
1046
+ end
990
1047
  row_obj = StreamRow.fast_create(
991
1048
  row_index,
992
1049
  cells_xml,
@@ -1002,7 +1059,8 @@ module Xlsxrb
1002
1059
  styles,
1003
1060
  date1904,
1004
1061
  attrs[:collapsed] || false,
1005
- pad_empty_cells
1062
+ pad_empty_cells,
1063
+ shared_formulas
1006
1064
  )
1007
1065
  block.call(row_obj)
1008
1066
 
@@ -1063,18 +1121,21 @@ module Xlsxrb
1063
1121
  [COL_LETTERS[idx], idx]
1064
1122
  end.freeze
1065
1123
 
1124
+ FORMULA_TYPE_MAP = { "shared" => :shared, "array" => :array, "dataTable" => :data_table }.freeze
1125
+ private_constant :FORMULA_TYPE_MAP
1126
+
1066
1127
  # Captures r, s, and t directly when they appear in the order Excel and xlsxrb write them
1067
1128
  # (groups 1 to 3). Any other attribute set or order falls back to capturing the raw
1068
- # attribute string (group 4, or group 8 for a self-closing cell) for ATTR_* lookups.
1069
- CELL_FAST_RE = %r{<(?:[a-zA-Z0-9_]+:)?c(?:\s+r="([A-Za-z0-9]+)"(?:\s+s="(\d+)")?(?:\s+t="([a-zA-Z]+)")?\s*|\b([^>]*(?<!/)))>\s*(?:<(?:[a-zA-Z0-9_]+:)?f\b[^>]*?(?:/>|>([^<]*)</(?:[a-zA-Z0-9_]+:)?f>)\s*)?(?:<(?:[a-zA-Z0-9_]+:)?v>([^<]*)</(?:[a-zA-Z0-9_]+:)?v>\s*)?(?:<(?:[a-zA-Z0-9_]+:)?is>(.*?)</(?:[a-zA-Z0-9_]+:)?is>\s*)?.*?</(?:[a-zA-Z0-9_]+:)?c>|<(?:[a-zA-Z0-9_]+:)?c\b([^>]*)/?>}m
1070
- CELL_GENERIC_RE = %r{<(?:[a-zA-Z0-9_]+:)?c\b([^>]*?)(?:>\s*(?:<(?:[a-zA-Z0-9_]+:)?f\b[^>]*?(?:/>|>([^<]*)</(?:[a-zA-Z0-9_]+:)?f>)\s*)?(?:<(?:[a-zA-Z0-9_]+:)?v>([^<]*)</(?:[a-zA-Z0-9_]+:)?v>\s*)?(?:<(?:[a-zA-Z0-9_]+:)?is>(.*?)</(?:[a-zA-Z0-9_]+:)?is>\s*)?.*?</(?:[a-zA-Z0-9_]+:)?c>|/>)}m
1129
+ # attribute string (group 4, or group 9 for a self-closing cell) for ATTR_* lookups.
1130
+ CELL_FAST_RE = %r{<(?:[a-zA-Z0-9_]+:)?c(?:\s+r="([A-Za-z0-9]+)"(?:\s+s="(\d+)")?(?:\s+t="([a-zA-Z]+)")?\s*|\b([^>]*(?<!/)))>\s*(?:<(?:[a-zA-Z0-9_]+:)?f(?:\s+([^>]*?))?(?:/>|>([^<]*)</(?:[a-zA-Z0-9_]+:)?f>)\s*)?(?:<(?:[a-zA-Z0-9_]+:)?v>([^<]*)</(?:[a-zA-Z0-9_]+:)?v>\s*)?(?:<(?:[a-zA-Z0-9_]+:)?is\s*((?=/)|>.*?(?=</(?:[a-zA-Z0-9_]+:)?is>))(?:/>|</(?:[a-zA-Z0-9_]+:)?is>)\s*)?.*?</(?:[a-zA-Z0-9_]+:)?c>|<(?:[a-zA-Z0-9_]+:)?c\b([^>]*)/?>}m
1131
+ CELL_GENERIC_RE = %r{<(?:[a-zA-Z0-9_]+:)?c\b([^>]*?)(?:>\s*(?:<(?:[a-zA-Z0-9_]+:)?f(?:\s+([^>]*?))?(?:/>|>([^<]*)</(?:[a-zA-Z0-9_]+:)?f>)\s*)?(?:<(?:[a-zA-Z0-9_]+:)?v>([^<]*)</(?:[a-zA-Z0-9_]+:)?v>\s*)?(?:<(?:[a-zA-Z0-9_]+:)?is\s*((?=/)|>.*?(?=</(?:[a-zA-Z0-9_]+:)?is>))(?:/>|</(?:[a-zA-Z0-9_]+:)?is>)\s*)?.*?</(?:[a-zA-Z0-9_]+:)?c>|/>)}m
1071
1132
  ATTR_R = /\br="([A-Za-z0-9]+)"/
1072
1133
  ATTR_T = /\bt="([a-zA-Z]+)"/
1073
1134
  ATTR_S = /\bs="(\d+)"/
1074
1135
 
1075
1136
  CELL_CLOSE_RE = %r{</(?:[a-zA-Z0-9_]+:)?c>}
1076
1137
  UNCLOSED_CELL_RE = %r{<(?:[a-zA-Z0-9_]+:)?c(?:\s[^>]*)?(?<!/)>}
1077
- INLINE_STRING_OPEN_RE = /<(?:[a-zA-Z0-9_]+:)?is[\s>]/
1138
+ INLINE_STRING_OPEN_RE = %r{<(?:[a-zA-Z0-9_]+:)?is(?:\s[^>]*)?(?<!/)>}
1078
1139
  INLINE_STRING_CLOSE_RE = %r{</(?:[a-zA-Z0-9_]+:)?is>}
1079
1140
  private_constant :CELL_CLOSE_RE, :UNCLOSED_CELL_RE, :INLINE_STRING_OPEN_RE, :INLINE_STRING_CLOSE_RE
1080
1141
 
@@ -1120,8 +1181,93 @@ module Xlsxrb
1120
1181
  cells
1121
1182
  end
1122
1183
 
1184
+ # Parses a `<f ...>` element with attributes into an `Elements::Formula`,
1185
+ # registering or expanding shared formulas when `shared_formulas` is present.
1186
+ #: (String f_attrs, String? raw_f, String? cell_ref, Hash[Integer, Hash[Symbol, untyped]]? shared_formulas) -> Elements::Formula?
1187
+ def self.build_formula_from_attrs(f_attrs, raw_f, cell_ref, shared_formulas)
1188
+ attrs_padded = " #{f_attrs}"
1189
+ raw_type = tag_attr(attrs_padded, ' t="') || tag_attr(attrs_padded, " t='")
1190
+ f_type = raw_type ? FORMULA_TYPE_MAP[raw_type] : nil
1191
+ f_ref = decoded_attr(attrs_padded, ' ref="')
1192
+ si_str = tag_attr(attrs_padded, ' si="') || tag_attr(attrs_padded, " si='")
1193
+ f_si = si_str&.to_i
1194
+ expr = raw_f ? normalize_text(utf8!(strip_ws(raw_f))) : +""
1195
+ if f_type == :shared && f_si && shared_formulas
1196
+ if !expr.empty?
1197
+ shared_formulas[f_si] = { ref: cell_ref, expression: expr }
1198
+ elsif (master = shared_formulas[f_si]) && cell_ref
1199
+ expr = Xlsxrb.expand_formula(master[:expression], from_ref: master[:ref], to_ref: cell_ref) || ""
1200
+ end
1201
+ end
1202
+ return nil if expr.empty? && f_type.nil?
1203
+
1204
+ Elements::Formula.new(
1205
+ expression: expr,
1206
+ type: f_type,
1207
+ ref: f_ref,
1208
+ shared_index: f_si,
1209
+ calculate_always: (true if f_attrs.include?('ca="1"') || f_attrs.include?('ca="true"')),
1210
+ aca: (true if f_attrs.include?('aca="1"') || f_attrs.include?('aca="true"')),
1211
+ bx: (true if f_attrs.include?('bx="1"') || f_attrs.include?('bx="true"')),
1212
+ dt2d: (true if f_attrs.include?('dt2D="1"') || f_attrs.include?('dt2D="true"')),
1213
+ dtr: (true if f_attrs.include?('dtr="1"') || f_attrs.include?('dtr="true"')),
1214
+ r1: decoded_attr(attrs_padded, ' r1="'),
1215
+ r2: decoded_attr(attrs_padded, ' r2="')
1216
+ )
1217
+ end
1218
+
1219
+ private_class_method :build_formula_from_attrs
1220
+
1221
+ # Records shared formula masters from a row slice before yielding StreamRow
1222
+ # so forward-iterated or skipped rows still populate shared masters for later slaves.
1223
+ #: (String xml, Integer from, Integer to, Hash[Integer, Hash[Symbol, untyped]] shared_formulas, Integer row_idx) -> void
1224
+ def self.record_shared_masters(xml, from, to, shared_formulas, row_idx)
1225
+ chunk = scrub_row(xml.byteslice(from, to - from))
1226
+ col_idx = 0
1227
+ matched_any = false
1228
+ chunk.scan(CELL_FAST_RE) do |r, _s, _t, attrs_str, f_attrs, f, _v, _is, self_attrs|
1229
+ matched_any = true
1230
+ r ||= (attrs_str || self_attrs || "")[ATTR_R, 1]
1231
+ c_idx = resolve_cell_col_index(r, col_idx)
1232
+ col_idx = c_idx + 1
1233
+ next unless f_attrs && f && !f.empty? && (f_attrs.include?('t="shared"') || f_attrs.include?("t='shared'"))
1234
+
1235
+ build_formula_from_attrs(f_attrs, f, r || "#{COL_LETTERS[c_idx]}#{row_idx + 1}", shared_formulas)
1236
+ end
1237
+ return if matched_any
1238
+
1239
+ col_idx = 0
1240
+ chunk.scan(CELL_GENERIC_RE) do |attrs, f_attrs, f, _v, _is|
1241
+ r = attrs[ATTR_R, 1]
1242
+ c_idx = resolve_cell_col_index(r, col_idx)
1243
+ col_idx = c_idx + 1
1244
+ next unless f_attrs && f && !f.empty? && (f_attrs.include?('t="shared"') || f_attrs.include?("t='shared'"))
1245
+
1246
+ build_formula_from_attrs(f_attrs, f, r || "#{COL_LETTERS[c_idx]}#{row_idx + 1}", shared_formulas)
1247
+ end
1248
+ end
1249
+
1250
+ private_class_method :record_shared_masters
1251
+
1252
+ #: (String? ref, Integer col_idx) -> Integer
1253
+ def self.resolve_cell_col_index(ref, col_idx)
1254
+ return col_idx unless ref
1255
+
1256
+ expected_letter = COL_LETTERS[col_idx]
1257
+ if expected_letter && ref.start_with?(expected_letter) && (digit = ref.getbyte(expected_letter.bytesize)) && digit >= 48 && digit <= 57
1258
+ col_idx
1259
+ else
1260
+ c_len = 0
1261
+ c_len += 1 while (b = ref.getbyte(c_len)) && (b.between?(65, 90) || b.between?(97, 122))
1262
+ col_letters = ref.byteslice(0, c_len).upcase
1263
+ COL_MAP[col_letters] || col_idx
1264
+ end
1265
+ end
1266
+
1267
+ private_class_method :resolve_cell_col_index
1268
+
1123
1269
  # rubocop:disable Style/OptionalBooleanParameter
1124
- def self.fast_scan_cells_direct(xml, from, to, shared_strings, row_source, _prefix = "", styles = nil, date1904 = false, &)
1270
+ def self.fast_scan_cells_direct(xml, from, to, shared_strings, row_source, _prefix = "", styles = nil, date1904 = false, shared_formulas = nil, &)
1125
1271
  # rubocop:enable Style/OptionalBooleanParameter
1126
1272
  chunk = scrub_row(xml.byteslice(from, to - from))
1127
1273
  verify_cells_closed!(chunk)
@@ -1129,7 +1275,7 @@ module Xlsxrb
1129
1275
  col_idx = 0
1130
1276
  matched_any = false
1131
1277
 
1132
- chunk.scan(CELL_FAST_RE) do |r, s, t, attrs_str, f, v, is, self_attrs|
1278
+ chunk.scan(CELL_FAST_RE) do |r, s, t, attrs_str, f_attrs, f, v, is, self_attrs|
1133
1279
  matched_any = true
1134
1280
  unless r
1135
1281
  raw_attrs = attrs_str || self_attrs || ""
@@ -1139,19 +1285,7 @@ module Xlsxrb
1139
1285
  end
1140
1286
  style_idx = s&.to_i
1141
1287
  ref = r
1142
- c_idx = if ref
1143
- expected_letter = COL_LETTERS[col_idx]
1144
- if expected_letter && ref.start_with?(expected_letter) && (digit = ref.getbyte(expected_letter.bytesize)) && digit >= 48 && digit <= 57
1145
- col_idx
1146
- else
1147
- c_len = 0
1148
- c_len += 1 while (b = ref.getbyte(c_len)) && (b.between?(65, 90) || b.between?(97, 122))
1149
- col_letters = ref.byteslice(0, c_len).upcase
1150
- COL_MAP[col_letters] || col_idx
1151
- end
1152
- else
1153
- col_idx
1154
- end
1288
+ c_idx = resolve_cell_col_index(ref, col_idx)
1155
1289
  col_idx = c_idx + 1
1156
1290
  v = utf8!(strip_ws(v)) if v
1157
1291
  f = utf8!(strip_ws(f)) if f
@@ -1164,34 +1298,27 @@ module Xlsxrb
1164
1298
  normalize_text(v)
1165
1299
  end
1166
1300
 
1167
- formula_expr = f ? normalize_text(f) : nil
1168
- formula_expr = nil if formula_expr && formula_expr.empty?
1301
+ formula_val = if f_attrs
1302
+ cell_ref = ref || "#{COL_LETTERS[c_idx]}#{row_idx + 1}"
1303
+ build_formula_from_attrs(f_attrs, f, cell_ref, shared_formulas)
1304
+ elsif f
1305
+ expr = normalize_text(f)
1306
+ expr.empty? ? nil : expr
1307
+ end
1169
1308
  fmt_code = NumberFormatter.format_code_for(style_idx, styles) if styles && style_idx
1170
- cell = Elements::Cell.fast_create(row_idx, c_idx, val, style_idx, formula_expr, raw_val, fmt_code, date1904)
1309
+ cell = Elements::Cell.fast_create(row_idx, c_idx, val, style_idx, formula_val, raw_val, fmt_code, date1904)
1171
1310
  yield cell
1172
1311
  end
1173
1312
 
1174
1313
  return if matched_any || (!chunk.include?("<c") && !chunk.include?(":c"))
1175
1314
 
1176
1315
  # Fallback for non-standard attribute ordering
1177
- chunk.scan(CELL_GENERIC_RE) do |attrs, f, v, is|
1316
+ chunk.scan(CELL_GENERIC_RE) do |attrs, f_attrs, f, v, is|
1178
1317
  r = attrs[ATTR_R, 1]
1179
1318
  t = attrs[ATTR_T, 1]
1180
1319
  s = attrs[ATTR_S, 1]
1181
1320
 
1182
- c_idx = if r
1183
- expected_letter = COL_LETTERS[col_idx]
1184
- if expected_letter && r.start_with?(expected_letter) && (digit = r.getbyte(expected_letter.bytesize)) && digit >= 48 && digit <= 57
1185
- col_idx
1186
- else
1187
- c_len = 0
1188
- c_len += 1 while (b = r.getbyte(c_len)) && (b.between?(65, 90) || b.between?(97, 122))
1189
- col_letters = r.byteslice(0, c_len).upcase
1190
- COL_MAP[col_letters] || col_idx
1191
- end
1192
- else
1193
- col_idx
1194
- end
1321
+ c_idx = resolve_cell_col_index(r, col_idx)
1195
1322
  col_idx = c_idx + 1
1196
1323
  v = utf8!(strip_ws(v)) if v
1197
1324
  f = utf8!(strip_ws(f)) if f
@@ -1205,10 +1332,15 @@ module Xlsxrb
1205
1332
  end
1206
1333
 
1207
1334
  style_idx = s&.to_i
1208
- formula_expr = f ? normalize_text(f) : nil
1209
- formula_expr = nil if formula_expr && formula_expr.empty?
1335
+ formula_val = if f_attrs
1336
+ cell_ref = r || "#{COL_LETTERS[c_idx]}#{row_idx + 1}"
1337
+ build_formula_from_attrs(f_attrs, f, cell_ref, shared_formulas)
1338
+ elsif f
1339
+ expr = normalize_text(f)
1340
+ expr.empty? ? nil : expr
1341
+ end
1210
1342
  fmt_code = NumberFormatter.format_code_for(style_idx, styles) if styles && style_idx
1211
- cell = Elements::Cell.fast_create(row_idx, c_idx, val, style_idx, formula_expr, raw_val, fmt_code, date1904)
1343
+ cell = Elements::Cell.fast_create(row_idx, c_idx, val, style_idx, formula_val, raw_val, fmt_code, date1904)
1212
1344
  yield cell
1213
1345
  end
1214
1346
  end
@@ -1226,7 +1358,7 @@ module Xlsxrb
1226
1358
  matched_any = false
1227
1359
  row_values = []
1228
1360
 
1229
- chunk.scan(CELL_FAST_RE) do |r, s_val, t, attrs_str, _f, v, is, self_attrs|
1361
+ chunk.scan(CELL_FAST_RE) do |r, s_val, t, attrs_str, _f_attrs, _f, v, is, self_attrs|
1230
1362
  matched_any = true
1231
1363
  unless r
1232
1364
  raw_attrs = attrs_str || self_attrs || ""
@@ -1235,19 +1367,7 @@ module Xlsxrb
1235
1367
  t = raw_attrs.include?('t="') ? raw_attrs[ATTR_T, 1] : nil
1236
1368
  end
1237
1369
  ref = r
1238
- c_idx = if ref
1239
- expected_letter = COL_LETTERS[col_idx]
1240
- if expected_letter && ref.start_with?(expected_letter) && (digit = ref.getbyte(expected_letter.bytesize)) && digit >= 48 && digit <= 57
1241
- col_idx
1242
- else
1243
- c_len = 0
1244
- c_len += 1 while (b = ref.getbyte(c_len)) && (b.between?(65, 90) || b.between?(97, 122))
1245
- col_letters = ref.byteslice(0, c_len).upcase
1246
- COL_MAP[col_letters] || col_idx
1247
- end
1248
- else
1249
- col_idx
1250
- end
1370
+ c_idx = resolve_cell_col_index(ref, col_idx)
1251
1371
  col_idx = c_idx + 1
1252
1372
  v = v.strip if v
1253
1373
 
@@ -1273,24 +1393,12 @@ module Xlsxrb
1273
1393
  return row_values if matched_any || (!chunk.include?("<c") && !chunk.include?(":c"))
1274
1394
 
1275
1395
  # Fallback for non-standard attribute ordering
1276
- chunk.scan(CELL_GENERIC_RE) do |attrs, _f, v, is|
1396
+ chunk.scan(CELL_GENERIC_RE) do |attrs, _f_attrs, _f, v, is|
1277
1397
  r = attrs[ATTR_R, 1]
1278
1398
  t = attrs[ATTR_T, 1]
1279
1399
  s = attrs[ATTR_S, 1]
1280
1400
 
1281
- c_idx = if r
1282
- expected_letter = COL_LETTERS[col_idx]
1283
- if expected_letter && r.start_with?(expected_letter) && (digit = r.getbyte(expected_letter.bytesize)) && digit >= 48 && digit <= 57
1284
- col_idx
1285
- else
1286
- c_len = 0
1287
- c_len += 1 while (b = r.getbyte(c_len)) && (b.between?(65, 90) || b.between?(97, 122))
1288
- col_letters = r.byteslice(0, c_len).upcase
1289
- COL_MAP[col_letters] || col_idx
1290
- end
1291
- else
1292
- col_idx
1293
- end
1401
+ c_idx = resolve_cell_col_index(r, col_idx)
1294
1402
  col_idx = c_idx + 1
1295
1403
  v = v.strip if v
1296
1404
 
@@ -349,7 +349,7 @@ module Xlsxrb
349
349
  end
350
350
  end
351
351
  f_attrs << ' ca="1"' if formula_ca
352
- if formula_expr && !formula_expr.empty?
352
+ if formula_expr && !formula_expr.empty? && !(formula_type&.to_sym == :shared && formula_ref.nil?)
353
353
  buf << "><f#{f_attrs}>" << escape_xml(formula_expr) << "</f>"
354
354
  else
355
355
  buf << "><f#{f_attrs}/>"
@@ -359,12 +359,25 @@ module Xlsxrb
359
359
  else
360
360
  v_str = xml_val.to_s
361
361
  v_str = v_str.dup.force_encoding(Encoding::UTF_8) if v_str.encoding == Encoding::BINARY
362
- v_str = escape_text(v_str) if type == "str" || xml_val.is_a?(String)
362
+ v_str = if type == "str" || (type != "e" && xml_val.is_a?(String))
363
+ escape_text(v_str)
364
+ elsif xml_val.is_a?(Numeric)
365
+ v_str
366
+ else
367
+ escape_xml(v_str)
368
+ end
363
369
  buf << "<v>" << v_str << "</v></c>"
364
370
  end
365
371
  else
366
372
  v_str = xml_val.to_s
367
373
  v_str = v_str.dup.force_encoding(Encoding::UTF_8) if v_str.encoding == Encoding::BINARY
374
+ v_str = if type == "str"
375
+ escape_text(v_str)
376
+ elsif xml_val.is_a?(Numeric) || xml_val.is_a?(BigDecimal)
377
+ v_str
378
+ else
379
+ escape_xml(v_str)
380
+ end
368
381
  buf << "><v>" << v_str << "</v></c>"
369
382
  end
370
383
  end
@@ -471,13 +484,13 @@ module Xlsxrb
471
484
  v_val = "0"
472
485
  when Xlsxrb::Elements::CellError
473
486
  c_type = ' t="e"'
474
- v_val = value.cached_value.code
487
+ v_val = escape_xml(value.cached_value.code)
475
488
  when nil
476
489
  v_val = 0
477
490
  else
478
- v_val = value.cached_value.is_a?(String) ? escape_xml(value.cached_value) : value.cached_value
491
+ v_val = value.cached_value.is_a?(Numeric) ? value.cached_value : escape_xml(value.cached_value)
479
492
  end
480
- f_tag = if formula_expr && !formula_expr.empty?
493
+ f_tag = if formula_expr && !formula_expr.empty? && !(value.type&.to_sym == :shared && value.ref.nil?)
481
494
  "<f#{f_attrs}>#{escape_xml(formula_expr)}</f>"
482
495
  else
483
496
  "<f#{f_attrs}/>"
@@ -523,8 +536,8 @@ module Xlsxrb
523
536
  c_type = ' t="e"'
524
537
  xml_val = xml_val.code
525
538
  end
526
- xml_val = escape_xml(xml_val) if xml_val.is_a?(String)
527
- f_tag = if formula_expr && !formula_expr.empty?
539
+ xml_val = escape_xml(xml_val) unless xml_val.is_a?(Numeric)
540
+ f_tag = if formula_expr && !formula_expr.empty? && !(f_type&.to_sym == :shared && value[:ref].nil?)
528
541
  "<f#{f_attrs}>#{escape_xml(formula_expr)}</f>"
529
542
  else
530
543
  "<f#{f_attrs}/>"
@@ -532,7 +545,7 @@ module Xlsxrb
532
545
  buf << "<c r=\"#{col_ref}#{row_num_str}\"#{c_type}>#{f_tag}<v>#{xml_val}</v></c>"
533
546
  end
534
547
  when Xlsxrb::Elements::CellError
535
- buf << "<c r=\"#{col_ref}#{row_num_str}\" t=\"e\"><v>#{value.code}</v></c>"
548
+ buf << "<c r=\"#{col_ref}#{row_num_str}\" t=\"e\"><v>#{escape_xml(value.code)}</v></c>"
536
549
  when BigDecimal
537
550
  buf << "<c r=\"#{col_ref}#{row_num_str}\"><v>#{value.to_s("F")}</v></c>"
538
551
  else
@@ -837,7 +850,7 @@ module Xlsxrb
837
850
  end
838
851
  end
839
852
  f_attrs << ' ca="1"' if formula_ca
840
- if formula_expr && !formula_expr.empty?
853
+ if formula_expr && !formula_expr.empty? && !(formula_type&.to_sym == :shared && formula_ref.nil?)
841
854
  buf << "><f#{f_attrs}>" << escape_xml(formula_expr) << "</f>"
842
855
  else
843
856
  buf << "><f#{f_attrs}/>"
@@ -846,7 +859,14 @@ module Xlsxrb
846
859
  buf << "<v>0</v></c>"
847
860
  else
848
861
  v_str = xml_val.to_s
849
- v_str = escape_text(v_str) if type == "str" || xml_val.is_a?(String)
862
+ v_str = v_str.dup.force_encoding(Encoding::UTF_8) if v_str.encoding == Encoding::BINARY
863
+ v_str = if type == "str" || (type != "e" && xml_val.is_a?(String))
864
+ escape_text(v_str)
865
+ elsif xml_val.is_a?(Numeric)
866
+ v_str
867
+ else
868
+ escape_xml(v_str)
869
+ end
850
870
  buf << "<v>" << v_str << "</v></c>"
851
871
  end
852
872
  elsif type == "inlineStr"
@@ -856,7 +876,10 @@ module Xlsxrb
856
876
  buf << "><is><t>" << escape_text(xml_val.to_s) << "</t></is></c>"
857
877
  end
858
878
  else
859
- buf << "><v>" << xml_val.to_s << "</v></c>"
879
+ v_str = xml_val.to_s
880
+ v_str = v_str.dup.force_encoding(Encoding::UTF_8) if v_str.encoding == Encoding::BINARY
881
+ v_str = escape_xml(v_str) unless xml_val.is_a?(Numeric) || xml_val.is_a?(BigDecimal)
882
+ buf << "><v>" << v_str << "</v></c>"
860
883
  end
861
884
  end
862
885
 
@@ -1103,10 +1126,16 @@ module Xlsxrb
1103
1126
  ss_attrs = { ref: sort_state[:ref] }
1104
1127
  ss_attrs[:columnSort] = "1" if sort_state[:column_sort]
1105
1128
  ss_attrs[:caseSensitive] = "1" if sort_state[:case_sensitive]
1129
+ ss_attrs[:sortMethod] = sort_state[:sort_method].to_s if sort_state[:sort_method]
1106
1130
  @builder.open_tag("sortState", ss_attrs)
1107
- (sort_state[:sort_conditions] || []).each do |sc|
1131
+ (sort_state[:sort_conditions] || sort_state[:conditions] || []).each do |sc|
1108
1132
  sc_attrs = { ref: sc[:ref] }
1109
1133
  sc_attrs[:descending] = "1" if sc[:descending]
1134
+ sc_attrs[:sortBy] = sc[:sort_by].to_s if sc[:sort_by]
1135
+ sc_attrs[:customList] = sc[:custom_list].to_s if sc[:custom_list]
1136
+ sc_attrs[:dxfId] = sc[:dxf_id].to_s unless sc[:dxf_id].nil?
1137
+ sc_attrs[:iconSet] = sc[:icon_set].to_s if sc[:icon_set]
1138
+ sc_attrs[:iconId] = sc[:icon_id].to_s unless sc[:icon_id].nil?
1110
1139
  @builder.empty_tag("sortCondition", sc_attrs)
1111
1140
  end
1112
1141
  @builder.close_tag("sortState")
@@ -1118,16 +1147,34 @@ module Xlsxrb
1118
1147
  end
1119
1148
 
1120
1149
  def write_filter_column(col_id, filter)
1121
- @builder.open_tag("filterColumn", { colId: col_id.to_s })
1150
+ fc_attrs = { colId: col_id.to_s }
1151
+ fc_attrs[:hiddenButton] = "1" if filter[:hidden] || filter[:hidden_button]
1152
+ fc_attrs[:showButton] = "0" if filter[:show_button] == false
1153
+ @builder.open_tag("filterColumn", fc_attrs)
1122
1154
  case filter[:type]
1123
1155
  when :filters
1124
1156
  f_attrs = {}
1125
1157
  f_attrs[:blank] = "1" if filter[:blank]
1126
- @builder.open_tag("filters", f_attrs)
1127
- (filter[:values] || []).each do |val|
1128
- @builder.empty_tag("filter", { val: val.to_s })
1158
+ f_attrs[:calendarType] = filter[:calendar_type].to_s if filter[:calendar_type]
1159
+ values = filter[:values] || []
1160
+ date_items = filter[:date_group_items] || []
1161
+ if values.any? || date_items.any?
1162
+ @builder.open_tag("filters", f_attrs)
1163
+ values.each { |val| @builder.empty_tag("filter", { val: val.to_s }) }
1164
+ date_items.each do |dg|
1165
+ dg_attrs = { dateTimeGrouping: dg[:date_time_grouping].to_s }
1166
+ dg_attrs[:year] = dg[:year].to_s if dg[:year]
1167
+ dg_attrs[:month] = dg[:month].to_s if dg[:month]
1168
+ dg_attrs[:day] = dg[:day].to_s if dg[:day]
1169
+ dg_attrs[:hour] = dg[:hour].to_s if dg[:hour]
1170
+ dg_attrs[:minute] = dg[:minute].to_s if dg[:minute]
1171
+ dg_attrs[:second] = dg[:second].to_s if dg[:second]
1172
+ @builder.empty_tag("dateGroupItem", dg_attrs)
1173
+ end
1174
+ @builder.close_tag("filters")
1175
+ else
1176
+ @builder.empty_tag("filters", f_attrs)
1129
1177
  end
1130
- @builder.close_tag("filters")
1131
1178
  when :custom
1132
1179
  if filter[:filters]
1133
1180
  c_attrs = {}
@@ -1142,13 +1189,29 @@ module Xlsxrb
1142
1189
  end
1143
1190
  @builder.close_tag("customFilters")
1144
1191
  when :dynamic
1145
- @builder.empty_tag("dynamicFilter", { type: filter[:dynamic_type] })
1192
+ d_attrs = { type: filter[:dynamic_type].to_s }
1193
+ d_attrs[:val] = filter[:val].to_s unless filter[:val].nil?
1194
+ d_attrs[:valIso] = filter[:val_iso].to_s if filter[:val_iso]
1195
+ d_attrs[:maxVal] = filter[:max_val].to_s unless filter[:max_val].nil?
1196
+ d_attrs[:maxValIso] = filter[:max_val_iso].to_s if filter[:max_val_iso]
1197
+ @builder.empty_tag("dynamicFilter", d_attrs)
1146
1198
  when :top10
1147
1199
  t_attrs = {}
1148
1200
  t_attrs[:top] = filter[:top] ? "1" : "0" unless filter[:top].nil?
1149
1201
  t_attrs[:percent] = filter[:percent] ? "1" : "0" unless filter[:percent].nil?
1150
1202
  t_attrs[:val] = filter[:val].to_s if filter[:val]
1203
+ t_attrs[:filterVal] = filter[:filter_val].to_s unless filter[:filter_val].nil?
1151
1204
  @builder.empty_tag("top10", t_attrs)
1205
+ when :color_filter
1206
+ cf_attrs = {}
1207
+ cf_attrs[:dxfId] = filter[:dxf_id].to_s unless filter[:dxf_id].nil?
1208
+ cf_attrs[:cellColor] = "0" if filter[:cell_color] == false
1209
+ @builder.empty_tag("colorFilter", cf_attrs)
1210
+ when :icon_filter
1211
+ ic_attrs = {}
1212
+ ic_attrs[:iconSet] = filter[:icon_set].to_s if filter[:icon_set]
1213
+ ic_attrs[:iconId] = filter[:icon_id].to_s unless filter[:icon_id].nil?
1214
+ @builder.empty_tag("iconFilter", ic_attrs)
1152
1215
  end
1153
1216
  @builder.close_tag("filterColumn")
1154
1217
  end