xlsxrb 0.2.0 → 0.2.1

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.
@@ -26,18 +26,64 @@ module Xlsxrb
26
26
 
27
27
  INTEGER_STRINGS = (0..65_535).map { |n| -n.to_s }.freeze
28
28
 
29
+ # Matches a value that claims to be a Time through is_a? without being one, such as
30
+ # ActiveSupport::TimeWithZone, which `when Time` does not match. The writers try it
31
+ # after their Time and Date branches, so other values never reach it. Such a value
32
+ # is written as the Time that to_time gives.
33
+ # @api private
34
+ module TimeLike
35
+ #: (untyped value) -> bool
36
+ def self.===(value) = value.is_a?(Time)
37
+
38
+ # A Time with the value's year, month, day, hour, minute, second, and UTC offset,
39
+ # which keeps its wall clock.
40
+ #: (untyped value) -> Time
41
+ def self.to_time(value)
42
+ seconds = value.sec + (value.respond_to?(:subsec) ? value.subsec : 0)
43
+ Time.new(value.year, value.month, value.day, value.hour, value.min, seconds, value.utc_offset)
44
+ end
45
+ end
46
+
29
47
  def initialize(io, date1904: false)
30
48
  @io = io
31
49
  @date1904 = date1904 ? true : false
32
50
  @builder = XmlBuilder.new(@io)
33
51
  @row_buffer = String.new(capacity: 65_536)
52
+ @style_attrs = {} # style id => '" s="<id>' fragment, built once per id
34
53
  @started = false
35
54
  @finished = false
55
+ @column_style_ids = nil # column index => resolved style id, see column_style_ids
56
+ @column_style_ids_map = nil
57
+ @time_like_style_resolver = nil
58
+ @strict_excel_mode = false
59
+ end
60
+
61
+ # Makes the row writers reject text longer than a cell holds (32,767 characters),
62
+ # as the strict Excel mode of the caller asks.
63
+ # @api private
64
+ #: (bool strict) -> void
65
+ def strict_excel_mode=(strict)
66
+ @strict_excel_mode = strict ? true : false
36
67
  end
37
68
 
69
+ # Sets what gives the style id for a Time-like value in a styled cell, so that a
70
+ # style without a number format can be given its date-time variant.
71
+ # @api private
72
+ #: (untyped resolver) -> void
73
+ attr_writer :time_like_style_resolver
74
+
38
75
  def set_column_style(col_index, style_id)
39
76
  @column_styles ||= {}
40
77
  @column_styles[col_index] = style_id
78
+ @column_style_ids = nil
79
+ end
80
+
81
+ # Drops the resolved column style ids, for a caller that changed the style id a
82
+ # name in the style map stands for.
83
+ # @api private
84
+ #: () -> void
85
+ def forget_column_style_ids
86
+ @column_style_ids = nil
41
87
  end
42
88
 
43
89
  # Write the worksheet header. Call once before writing rows.
@@ -108,6 +154,8 @@ module Xlsxrb
108
154
  buf << ' outlineLevel="' << attrs[:outline_level].to_s << '"' if attrs[:outline_level]
109
155
  buf << ">"
110
156
 
157
+ row_style = resolve_style_id(attrs[:style_index], nil)
158
+ style_attrs = @style_attrs
111
159
  cells.each do |cell|
112
160
  if cell.is_a?(Elements::Cell)
113
161
  value = cell.value
@@ -136,41 +184,45 @@ module Xlsxrb
136
184
  end
137
185
 
138
186
  cell_style_id = resolve_style_id(cell_style_id, nil)
139
- col_style = @column_styles && col_idx ? @column_styles[col_idx] : nil
140
- col_style = resolve_style_id(col_style, nil)
141
- row_style = resolve_style_id(attrs[:style_index], nil)
142
- style_id = cell_style_id.nil? ? (row_style || col_style) : cell_style_id
187
+ style_id = cell_style_id.nil? ? (row_style || (@column_styles && col_idx && resolve_style_id(@column_styles[col_idx], nil))) : cell_style_id
143
188
  style_id = nil unless style_id.is_a?(Integer)
144
189
 
145
190
  raise ArgumentError, "Non-finite Float #{value} is not supported in XLSX" if value.is_a?(Float) && !value.finite?
146
191
 
147
- # Fast path for common unstyled cells
148
- if !formula && !style_id && !cell_type_val
192
+ # Fast path for common cells, styled or not
193
+ if !formula && !cell_type_val
194
+ # '" s="<id>' to append after the cell reference, or "" for an unstyled cell
195
+ s_attr = style_id ? (style_attrs[style_id] ||= -%(" s="#{style_id})) : ""
149
196
  case value
150
197
  when Integer, Float
151
- buf << '<c r="' << col_ref << '"><v>' << value.to_s << "</v></c>"
198
+ buf << '<c r="' << col_ref << s_attr << '"><v>' << value.to_s << "</v></c>"
152
199
  next
153
200
  when String
154
201
  if sst_index && (idx = sst_index[value])
155
- buf << '<c r="' << col_ref << '" t="s"><v>' << idx.to_s << "</v></c>"
202
+ buf << '<c r="' << col_ref << s_attr << '" t="s"><v>' << idx.to_s << "</v></c>"
156
203
  next
157
204
  end
158
205
  when true
159
- buf << '<c r="' << col_ref << '" t="b"><v>1</v></c>'
206
+ buf << '<c r="' << col_ref << s_attr << '" t="b"><v>1</v></c>'
160
207
  next
161
208
  when false
162
- buf << '<c r="' << col_ref << '" t="b"><v>0</v></c>'
209
+ buf << '<c r="' << col_ref << s_attr << '" t="b"><v>0</v></c>'
163
210
  next
164
211
  when nil
165
- buf << '<c r="' << col_ref << '"/>'
212
+ # An empty cell keeps only its own style, not the row or column style.
213
+ if cell_style_id.is_a?(Integer)
214
+ buf << '<c r="' << col_ref << '" s="' << cell_style_id.to_s << '"/>'
215
+ else
216
+ buf << '<c r="' << col_ref << '"/>'
217
+ end
166
218
  next
167
219
  when DateTime
168
220
  serial = Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: @date1904)
169
- buf << '<c r="' << col_ref << '"><v>' << serial.to_s << "</v></c>"
221
+ buf << '<c r="' << col_ref << s_attr << '"><v>' << serial.to_s << "</v></c>"
170
222
  next
171
223
  when Date
172
224
  serial = Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: @date1904)
173
- buf << '<c r="' << col_ref << '"><v>' << serial.to_s << "</v></c>"
225
+ buf << '<c r="' << col_ref << s_attr << '"><v>' << serial.to_s << "</v></c>"
174
226
  next
175
227
  end
176
228
  end
@@ -259,6 +311,8 @@ module Xlsxrb
259
311
  xml_val = Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: @date1904)
260
312
  when Date
261
313
  xml_val = Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: @date1904)
314
+ when TimeLike # after Date, so Date values skip TimeLike.===
315
+ xml_val = Xlsxrb::Ooxml::Utils.datetime_to_serial(TimeLike.to_time(value), date1904: @date1904)
262
316
  when BigDecimal
263
317
  xml_val = value.to_s("F")
264
318
  when Xlsxrb::Elements::CellError
@@ -275,7 +329,7 @@ module Xlsxrb
275
329
  if xml_val.is_a?(Xlsxrb::Elements::RichText)
276
330
  write_inline_rich_text(buf, xml_val)
277
331
  else
278
- buf << "><is><t>" << escape_xml(xml_val.to_s) << "</t></is></c>"
332
+ buf << "><is><t>" << escape_text(xml_val.to_s) << "</t></is></c>"
279
333
  end
280
334
  elsif formula_expr || (formula_type && formula_type.to_sym == :shared && !formula_si.nil?)
281
335
  f_attrs = +""
@@ -301,7 +355,7 @@ module Xlsxrb
301
355
  else
302
356
  v_str = xml_val.to_s
303
357
  v_str = v_str.dup.force_encoding(Encoding::UTF_8) if v_str.encoding == Encoding::BINARY
304
- v_str = escape_xml(v_str) if type == "str" || xml_val.is_a?(String)
358
+ v_str = escape_text(v_str) if type == "str" || xml_val.is_a?(String)
305
359
  buf << "<v>" << v_str << "</v></c>"
306
360
  end
307
361
  else
@@ -348,7 +402,7 @@ module Xlsxrb
348
402
 
349
403
  buf << '<c r="' << col_ref << row_num_str << '"><v>' << value.to_s << "</v></c>"
350
404
  when String
351
- raise ArgumentError, "Cell text length #{value.length} exceeds Excel limit of 32,767 characters" if @strict_excel_mode && value.length > 32_767
405
+ DslHelpers.check_cell_text_length!(value) if @strict_excel_mode && value.bytesize > DslHelpers::MAX_CELL_TEXT_LENGTH
352
406
 
353
407
  if sst_index
354
408
  idx = (sst_index[value] ||= begin
@@ -358,7 +412,7 @@ module Xlsxrb
358
412
  idx_str = idx < 65_536 ? INTEGER_STRINGS[idx] : idx.to_s
359
413
  buf << '<c r="' << col_ref << row_num_str << '" t="s"><v>' << idx_str << "</v></c>"
360
414
  else
361
- buf << '<c r="' << col_ref << row_num_str << '" t="inlineStr"><is><t>' << escape_xml(value) << "</t></is></c>"
415
+ buf << '<c r="' << col_ref << row_num_str << '" t="inlineStr"><is><t>' << escape_text(value) << "</t></is></c>"
362
416
  end
363
417
  when true
364
418
  buf << '<c r="' << col_ref << row_num_str << '" t="b"><v>1</v></c>'
@@ -378,6 +432,13 @@ module Xlsxrb
378
432
  else
379
433
  "<c r=\"#{col_ref}#{row_num_str}\"><v>#{Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: @date1904)}</v></c>"
380
434
  end
435
+ when TimeLike # after Date, so Date values skip TimeLike.===
436
+ time_style_id = style_map ? style_map["__xlsxrb_time"] : nil
437
+ buf << if time_style_id
438
+ "<c r=\"#{col_ref}#{row_num_str}\" s=\"#{time_style_id}\"><v>#{Xlsxrb::Ooxml::Utils.datetime_to_serial(TimeLike.to_time(value), date1904: @date1904)}</v></c>"
439
+ else
440
+ "<c r=\"#{col_ref}#{row_num_str}\"><v>#{Xlsxrb::Ooxml::Utils.datetime_to_serial(TimeLike.to_time(value), date1904: @date1904)}</v></c>"
441
+ end
381
442
  when Xlsxrb::Elements::Formula
382
443
  raise ArgumentError, "Non-finite Float #{value.cached_value} is not supported in XLSX" if value.cached_value.is_a?(Float) && !value.cached_value.finite?
383
444
 
@@ -482,7 +543,7 @@ module Xlsxrb
482
543
  buf << '<c r="' << col_ref << row_num_str << '" t="inlineStr"'
483
544
  write_inline_rich_text(buf, value)
484
545
  else
485
- buf << "<c r=\"#{col_ref}#{row_num_str}\" t=\"inlineStr\"><is><t>#{escape_xml(value.to_s)}</t></is></c>"
546
+ buf << "<c r=\"#{col_ref}#{row_num_str}\" t=\"inlineStr\"><is><t>#{escape_text(value.to_s)}</t></is></c>"
486
547
  end
487
548
  end
488
549
  end
@@ -521,215 +582,7 @@ module Xlsxrb
521
582
  max_len = [max_len, styles_len].max
522
583
  end
523
584
 
524
- col_index = 0
525
- while col_index < max_len
526
- value = col_index < values.length ? values[col_index] : nil
527
- cell_style_id = single_style_id
528
- if is_styles_collection
529
- style_name = if styles.is_a?(Array)
530
- col_index < styles.length ? styles[col_index] : nil
531
- else
532
- styles[col_index]
533
- end
534
- cell_style_id = resolve_style_id(style_name, style_map)
535
- end
536
-
537
- if cell_style_id.nil?
538
- col_style = @column_styles ? @column_styles[col_index] : nil
539
- col_style_id = resolve_style_id(col_style, style_map)
540
- style_id = row_style_id || col_style_id
541
- else
542
- style_id = cell_style_id
543
- end
544
-
545
- col_ref = COLUMN_LETTERS[col_index] || column_letter(col_index)
546
-
547
- if value.nil?
548
- buf << '<c r="' << col_ref << row_num_str << '" s="' << cell_style_id.to_s << '"/>' if cell_style_id
549
- col_index += 1
550
- next
551
- end
552
-
553
- raise ArgumentError, "Non-finite Float #{value} is not supported in XLSX" if value.is_a?(Float) && !value.finite?
554
-
555
- # Fast path: unstyled numbers, booleans, and simple strings (majority of cells)
556
- if style_id.nil? && !value.is_a?(Xlsxrb::Elements::Formula) && !value.is_a?(Hash)
557
- case value
558
- when Integer
559
- val_str = INTEGER_STRINGS[value] || value.to_s
560
- buf << '<c r="' << col_ref << row_num_str << '"><v>' << val_str << "</v></c>"
561
- col_index += 1
562
- next
563
- when Float
564
- buf << '<c r="' << col_ref << row_num_str << '"><v>' << value.to_s << "</v></c>"
565
- col_index += 1
566
- next
567
- when String
568
- if sst_index
569
- idx = sst_index[value]
570
- unless idx
571
- sst << value
572
- idx = sst.size - 1
573
- sst_index[value] = idx
574
- end
575
- idx_str = INTEGER_STRINGS[idx] || idx.to_s
576
- buf << '<c r="' << col_ref << row_num_str << '" t="s"><v>' << idx_str << "</v></c>"
577
- else
578
- buf << '<c r="' << col_ref << row_num_str << '" t="inlineStr"><is><t>' << escape_xml(value) << "</t></is></c>"
579
- end
580
- col_index += 1
581
- next
582
- when true
583
- buf << '<c r="' << col_ref << row_num_str << '" t="b"><v>1</v></c>'
584
- col_index += 1
585
- next
586
- when false
587
- buf << '<c r="' << col_ref << row_num_str << '" t="b"><v>0</v></c>'
588
- col_index += 1
589
- next
590
- when Time, DateTime
591
- buf << '<c r="' << col_ref << row_num_str << '"><v>' << Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: @date1904).to_s << "</v></c>"
592
- col_index += 1
593
- next
594
- when Date
595
- buf << '<c r="' << col_ref << row_num_str << '"><v>' << Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: @date1904).to_s << "</v></c>"
596
- col_index += 1
597
- next
598
- end
599
- end
600
-
601
- # General path: styled, formula, rich text, or complex cell
602
- formula_expr = nil
603
- formula_ca = false
604
- formula_type = nil
605
- formula_ref = nil
606
- formula_si = nil
607
- xml_val = value
608
- type = nil
609
-
610
- case value
611
- when Xlsxrb::Elements::Formula
612
- formula_expr = value.expression
613
- formula_ca = value.calculate_always?
614
- formula_type = value.type
615
- formula_ref = value.ref
616
- formula_si = value.shared_index
617
- xml_val = value.cached_value
618
- case value.cached_value
619
- when String
620
- type = "str"
621
- when true
622
- type = "b"
623
- xml_val = "1"
624
- when false
625
- type = "b"
626
- xml_val = "0"
627
- when Xlsxrb::Elements::CellError
628
- type = "e"
629
- xml_val = value.cached_value.code
630
- end
631
- when Hash
632
- if value.key?(:formula)
633
- formula_expr = value[:formula] || value[:expression]
634
- formula_ca = value[:calculate_always] || false
635
- formula_type = value[:type]
636
- formula_ref = value[:ref]
637
- formula_si = value[:si] || value[:shared_index]
638
- xml_val = if value.key?(:value)
639
- value[:value]
640
- elsif value.key?(:cached_value)
641
- value[:cached_value]
642
- end
643
- case xml_val
644
- when String
645
- type = "str"
646
- when true
647
- type = "b"
648
- xml_val = "1"
649
- when false
650
- type = "b"
651
- xml_val = "0"
652
- when Xlsxrb::Elements::CellError
653
- type = "e"
654
- xml_val = xml_val.code
655
- end
656
- end
657
- when String, Xlsxrb::Elements::RichText
658
- if sst_index
659
- idx = sst_index[value]
660
- unless idx
661
- sst << value
662
- idx = sst.size - 1
663
- sst_index[value] = idx
664
- end
665
- xml_val = idx
666
- type = "s"
667
- else
668
- xml_val = value
669
- type = "inlineStr"
670
- end
671
- when true
672
- xml_val = "1"
673
- type = "b"
674
- when false
675
- xml_val = "0"
676
- type = "b"
677
- when Time, DateTime
678
- xml_val = Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: @date1904)
679
- when Date
680
- xml_val = Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: @date1904)
681
- when BigDecimal
682
- xml_val = value.to_s("F")
683
- when Xlsxrb::Elements::CellError
684
- xml_val = value.code
685
- type = "e"
686
- end
687
-
688
- raise ArgumentError, "Non-finite Float #{xml_val} is not supported in XLSX" if xml_val.is_a?(Float) && !xml_val.finite?
689
-
690
- formula_expr = formula_expr[1..] if formula_expr&.start_with?("=")
691
-
692
- buf << '<c r="' << col_ref << row_num_str << '"'
693
- buf << ' s="' << style_id.to_s << '"' if style_id
694
- buf << ' t="' << type << '"' if type
695
- if formula_expr || (formula_type && formula_type.to_sym == :shared && !formula_si.nil?)
696
- f_attrs = +""
697
- if formula_type
698
- case formula_type.to_sym
699
- when :array
700
- f_attrs << ' t="array"'
701
- f_attrs << %( ref="#{formula_ref}") if formula_ref
702
- when :shared
703
- f_attrs << ' t="shared"'
704
- f_attrs << %( si="#{formula_si}") if formula_si
705
- f_attrs << %( ref="#{formula_ref}") if formula_ref
706
- end
707
- end
708
- f_attrs << ' ca="1"' if formula_ca
709
- if formula_expr && !formula_expr.empty?
710
- buf << "><f#{f_attrs}>" << escape_xml(formula_expr) << "</f>"
711
- else
712
- buf << "><f#{f_attrs}/>"
713
- end
714
- if xml_val.nil?
715
- buf << "<v>0</v></c>"
716
- else
717
- v_str = xml_val.to_s
718
- v_str = escape_xml(v_str) if type == "str" || xml_val.is_a?(String)
719
- buf << "<v>" << v_str << "</v></c>"
720
- end
721
- elsif type == "inlineStr"
722
- if xml_val.is_a?(Xlsxrb::Elements::RichText)
723
- write_inline_rich_text(buf, xml_val)
724
- else
725
- buf << "><is><t>" << escape_xml(xml_val.to_s) << "</t></is></c>"
726
- end
727
- else
728
- buf << "><v>" << xml_val.to_s << "</v></c>"
729
- end
730
-
731
- col_index += 1
732
- end
585
+ write_styled_cells(buf, values, max_len, row_num_str, styles, is_styles_collection, single_style_id, row_style_id, style_map, sst, sst_index)
733
586
 
734
587
  buf << "</row>"
735
588
  return unless buf.bytesize >= 32_768
@@ -795,8 +648,218 @@ module Xlsxrb
795
648
 
796
649
  private
797
650
 
651
+ # Writes the cells of a row that has cell styles, row attributes, or column styles.
652
+ # It is not inlined in write_row_values because YJIT ran the same loop there about
653
+ # 1.6 times slower, after the row attribute handling.
654
+ def write_styled_cells(buf, values, max_len, row_num_str, styles, is_styles_collection, single_style_id, row_style_id, style_map, sst, sst_index)
655
+ style_attrs = @style_attrs
656
+ column_ids = @column_styles && column_style_ids(style_map)
657
+ col_index = 0
658
+ while col_index < max_len
659
+ # Indexing past the end of values or styles (Array or Hash) yields nil.
660
+ value = values[col_index]
661
+ cell_style_id = is_styles_collection ? resolve_style_id(styles[col_index], style_map) : single_style_id
662
+ style_id = cell_style_id || row_style_id || (column_ids && column_ids[col_index])
663
+ col_ref = COLUMN_LETTERS[col_index] || column_letter(col_index)
664
+ col_index += 1
665
+
666
+ if value.nil?
667
+ buf << '<c r="' << col_ref << row_num_str << '" s="' << cell_style_id.to_s << '"/>' if cell_style_id
668
+ next
669
+ end
670
+
671
+ # '" s="<id>' to append after the cell reference, or "" for an unstyled cell
672
+ s_attr = style_id ? (style_attrs[style_id] ||= -%(" s="#{style_id})) : ""
673
+ case value
674
+ when Integer
675
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '"><v>' << (value >= 0 && value < 65_536 ? INTEGER_STRINGS[value] : value.to_s) << "</v></c>"
676
+ when Float
677
+ raise ArgumentError, "Non-finite Float #{value} is not supported in XLSX" unless value.finite?
678
+
679
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '"><v>' << value.to_s << "</v></c>"
680
+ when String
681
+ DslHelpers.check_cell_text_length!(value) if @strict_excel_mode && value.bytesize > DslHelpers::MAX_CELL_TEXT_LENGTH
682
+
683
+ if sst_index
684
+ idx = sst_index[value]
685
+ unless idx
686
+ sst << value
687
+ idx = sst.size - 1
688
+ sst_index[value] = idx
689
+ end
690
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '" t="s"><v>' << (INTEGER_STRINGS[idx] || idx.to_s) << "</v></c>"
691
+ else
692
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '" t="inlineStr"><is><t>' << escape_text(value) << "</t></is></c>"
693
+ end
694
+ when true
695
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '" t="b"><v>1</v></c>'
696
+ when false
697
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '" t="b"><v>0</v></c>'
698
+ when Time, DateTime
699
+ if style_id.nil? && style_map && (time_style_id = style_map["__xlsxrb_time"])
700
+ s_attr = style_attrs[time_style_id] ||= -%(" s="#{time_style_id})
701
+ end
702
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '"><v>' << Xlsxrb::Ooxml::Utils.datetime_to_serial(value, date1904: @date1904).to_s << "</v></c>"
703
+ when Date
704
+ if style_id.nil? && style_map && (date_style_id = style_map["__xlsxrb_date"])
705
+ s_attr = style_attrs[date_style_id] ||= -%(" s="#{date_style_id})
706
+ end
707
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '"><v>' << Xlsxrb::Ooxml::Utils.date_to_serial(value, date1904: @date1904).to_s << "</v></c>"
708
+ when TimeLike
709
+ if style_id.nil?
710
+ time_style_id = style_map && style_map["__xlsxrb_time"]
711
+ elsif @time_like_style_resolver
712
+ time_style_id = @time_like_style_resolver.call(style_id)
713
+ end
714
+ s_attr = style_attrs[time_style_id] ||= -%(" s="#{time_style_id}) if time_style_id
715
+ buf << '<c r="' << col_ref << row_num_str << s_attr << '"><v>' << Xlsxrb::Ooxml::Utils.datetime_to_serial(TimeLike.to_time(value), date1904: @date1904).to_s << "</v></c>"
716
+ else
717
+ write_complex_cell(buf, col_ref, row_num_str, value, style_id, sst, sst_index)
718
+ end
719
+ end
720
+ end
721
+
722
+ # The style id of each column style, indexed by column, resolved once instead of
723
+ # for every cell. It is resolved again when the style map is another Hash, or after
724
+ # set_column_style or forget_column_style_ids.
725
+ #: (Hash[untyped, Integer]? style_map) -> Array[Integer?]
726
+ def column_style_ids(style_map)
727
+ ids = @column_style_ids
728
+ return ids if ids && @column_style_ids_map.equal?(style_map)
729
+
730
+ ids = []
731
+ @column_styles&.each { |col_index, style| ids[col_index] = resolve_style_id(style, style_map) }
732
+ @column_style_ids_map = style_map
733
+ @column_style_ids = ids
734
+ end
735
+
736
+ # Writes a cell for write_styled_cells whose value is a formula, rich text, BigDecimal,
737
+ # cell error, or another value that write_styled_cells does not write itself.
738
+ def write_complex_cell(buf, col_ref, row_num_str, value, style_id, sst, sst_index)
739
+ formula_expr = nil
740
+ formula_ca = false
741
+ formula_type = nil
742
+ formula_ref = nil
743
+ formula_si = nil
744
+ xml_val = value
745
+ type = nil
746
+
747
+ case value
748
+ when Xlsxrb::Elements::Formula
749
+ formula_expr = value.expression
750
+ formula_ca = value.calculate_always?
751
+ formula_type = value.type
752
+ formula_ref = value.ref
753
+ formula_si = value.shared_index
754
+ xml_val = value.cached_value
755
+ case value.cached_value
756
+ when String
757
+ type = "str"
758
+ when true
759
+ type = "b"
760
+ xml_val = "1"
761
+ when false
762
+ type = "b"
763
+ xml_val = "0"
764
+ when Xlsxrb::Elements::CellError
765
+ type = "e"
766
+ xml_val = value.cached_value.code
767
+ end
768
+ when Hash
769
+ if value.key?(:formula)
770
+ formula_expr = value[:formula] || value[:expression]
771
+ formula_ca = value[:calculate_always] || false
772
+ formula_type = value[:type]
773
+ formula_ref = value[:ref]
774
+ formula_si = value[:si] || value[:shared_index]
775
+ xml_val = if value.key?(:value)
776
+ value[:value]
777
+ elsif value.key?(:cached_value)
778
+ value[:cached_value]
779
+ end
780
+ case xml_val
781
+ when String
782
+ type = "str"
783
+ when true
784
+ type = "b"
785
+ xml_val = "1"
786
+ when false
787
+ type = "b"
788
+ xml_val = "0"
789
+ when Xlsxrb::Elements::CellError
790
+ type = "e"
791
+ xml_val = xml_val.code
792
+ end
793
+ end
794
+ when Xlsxrb::Elements::RichText
795
+ if sst_index
796
+ idx = sst_index[value]
797
+ unless idx
798
+ sst << value
799
+ idx = sst.size - 1
800
+ sst_index[value] = idx
801
+ end
802
+ xml_val = idx
803
+ type = "s"
804
+ else
805
+ xml_val = value
806
+ type = "inlineStr"
807
+ end
808
+ when BigDecimal
809
+ xml_val = value.to_s("F")
810
+ when Xlsxrb::Elements::CellError
811
+ xml_val = value.code
812
+ type = "e"
813
+ end
814
+
815
+ raise ArgumentError, "Non-finite Float #{xml_val} is not supported in XLSX" if xml_val.is_a?(Float) && !xml_val.finite?
816
+
817
+ formula_expr = formula_expr[1..] if formula_expr&.start_with?("=")
818
+
819
+ buf << '<c r="' << col_ref << row_num_str << '"'
820
+ buf << ' s="' << style_id.to_s << '"' if style_id
821
+ buf << ' t="' << type << '"' if type
822
+ if formula_expr || (formula_type && formula_type.to_sym == :shared && !formula_si.nil?)
823
+ f_attrs = +""
824
+ if formula_type
825
+ case formula_type.to_sym
826
+ when :array
827
+ f_attrs << ' t="array"'
828
+ f_attrs << %( ref="#{formula_ref}") if formula_ref
829
+ when :shared
830
+ f_attrs << ' t="shared"'
831
+ f_attrs << %( si="#{formula_si}") if formula_si
832
+ f_attrs << %( ref="#{formula_ref}") if formula_ref
833
+ end
834
+ end
835
+ f_attrs << ' ca="1"' if formula_ca
836
+ if formula_expr && !formula_expr.empty?
837
+ buf << "><f#{f_attrs}>" << escape_xml(formula_expr) << "</f>"
838
+ else
839
+ buf << "><f#{f_attrs}/>"
840
+ end
841
+ if xml_val.nil?
842
+ buf << "<v>0</v></c>"
843
+ else
844
+ v_str = xml_val.to_s
845
+ v_str = escape_text(v_str) if type == "str" || xml_val.is_a?(String)
846
+ buf << "<v>" << v_str << "</v></c>"
847
+ end
848
+ elsif type == "inlineStr"
849
+ if xml_val.is_a?(Xlsxrb::Elements::RichText)
850
+ write_inline_rich_text(buf, xml_val)
851
+ else
852
+ buf << "><is><t>" << escape_text(xml_val.to_s) << "</t></is></c>"
853
+ end
854
+ else
855
+ buf << "><v>" << xml_val.to_s << "</v></c>"
856
+ end
857
+ end
858
+
798
859
  def resolve_style_id(style, style_map)
799
860
  return nil if style.nil?
861
+ # Without names to look up, an index is the style id.
862
+ return style if style_map.nil? && style.is_a?(Integer)
800
863
 
801
864
  if style_map
802
865
  mapped = style_map[style] || style_map[style.to_s]
@@ -1750,7 +1813,7 @@ module Xlsxrb
1750
1813
  else
1751
1814
  buf << "<r><t>"
1752
1815
  end
1753
- buf << escape_xml(text.to_s) << "</t></r>"
1816
+ buf << escape_text(text.to_s) << "</t></r>"
1754
1817
  end
1755
1818
  buf << "</is></c>"
1756
1819
  end
@@ -1766,6 +1829,17 @@ module Xlsxrb
1766
1829
  str = str.gsub(INVALID_XML_CHARS_RE, "") if str.match?(INVALID_XML_CHARS_RE)
1767
1830
  str.match?(ESCAPE_RE) ? str.gsub(ESCAPE_RE, ESCAPE_MAP) : str
1768
1831
  end
1832
+
1833
+ # Escapes cell text: encodes it as ST_Xstring (XmlBuilder.encode_xstring), so that
1834
+ # text that looks like _xHHHH_ and characters XML 1.0 cannot hold are read back as
1835
+ # written, then escapes the XML special characters.
1836
+ def escape_text(value)
1837
+ str = value.to_s
1838
+ str = str.dup.force_encoding(Encoding::UTF_8) if str.encoding == Encoding::BINARY
1839
+ # Most text has neither; the checks cost less than encode_xstring's own.
1840
+ str = XmlBuilder.encode_xstring(str) if str.include?("_x") || str.match?(INVALID_XML_CHARS_RE)
1841
+ str.match?(ESCAPE_RE) ? str.gsub(ESCAPE_RE, ESCAPE_MAP) : str
1842
+ end
1769
1843
  end
1770
1844
  end
1771
1845
  end