Class: Xlsxrb::Ooxml::WorkbookWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/xlsxrb/ooxml/workbook_writer.rb,
sig/generated/xlsxrb/ooxml/workbook_writer.rbs

Overview

Orchestrates writing a complete XLSX workbook. Generates all required OpenXML parts and assembles them into a ZIP.

Defined Under Namespace

Classes: ZipEntryIO

Constant Summary collapse

SSML_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/spreadsheetml/2006/main"
REL_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/package/2006/relationships"
CT_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/package/2006/content-types"
DOC_REL =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/officeDocument/2006/relationships"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sheets:, shared_strings: [], shared_strings_index: nil, styles: nil, defined_names: nil, core_properties: nil, app_properties: nil, custom_properties: nil, workbook_protection: nil, workbook_properties: nil) ⇒ WorkbookWriter

Returns a new instance of WorkbookWriter.

Parameters:

  • sheets: (Object)
  • shared_strings: (Object) (defaults to: [])
  • shared_strings_index: (Object) (defaults to: nil)
  • styles: (Object) (defaults to: nil)
  • defined_names: (Object) (defaults to: nil)
  • core_properties: (Object) (defaults to: nil)
  • app_properties: (Object) (defaults to: nil)
  • custom_properties: (Object) (defaults to: nil)
  • workbook_protection: (Object) (defaults to: nil)
  • workbook_properties: (Object) (defaults to: nil)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 45

def initialize(sheets:, shared_strings: [], shared_strings_index: nil, styles: nil,
               defined_names: nil, core_properties: nil, app_properties: nil,
               custom_properties: nil, workbook_protection: nil, workbook_properties: nil)
  @sheets = sheets
  @shared_strings = shared_strings
  @shared_strings_index = shared_strings_index
  @styles = styles || {}
  @defined_names = defined_names || []
  @core_properties = core_properties || {}
  @app_properties = app_properties || {}
  @custom_properties = custom_properties || []
  @workbook_protection = workbook_protection
  @workbook_properties = workbook_properties || { update_links: "never" }
  @drawing_count = 0
  @chart_count = 0
  @comment_count = 0
  @table_count = 0
  @pivot_cache_count = 0
  @pivot_table_count = 0
end

Class Method Details

.write(target, sheets:, shared_strings: [], shared_strings_index: nil, styles: nil, defined_names: nil, core_properties: nil, app_properties: nil, custom_properties: nil, workbook_protection: nil, workbook_properties: nil) ⇒ Object

Parameters:

  • target (Object)
  • sheets: (Object)
  • shared_strings: (Object) (defaults to: [])
  • shared_strings_index: (Object) (defaults to: nil)
  • styles: (Object) (defaults to: nil)
  • defined_names: (Object) (defaults to: nil)
  • core_properties: (Object) (defaults to: nil)
  • app_properties: (Object) (defaults to: nil)
  • custom_properties: (Object) (defaults to: nil)
  • workbook_protection: (Object) (defaults to: nil)
  • workbook_properties: (Object) (defaults to: nil)

Returns:

  • (Object)


33
34
35
36
37
38
39
40
41
42
43
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 33

def self.write(target, sheets:, shared_strings: [], shared_strings_index: nil, styles: nil,
               defined_names: nil, core_properties: nil, app_properties: nil,
               custom_properties: nil, workbook_protection: nil, workbook_properties: nil)
  Xlsxrb.in_span("Ooxml::WorkbookWriter.write") do
    writer = new(sheets: sheets, shared_strings: shared_strings, shared_strings_index: shared_strings_index, styles: styles,
                 defined_names: defined_names, core_properties: core_properties,
                 app_properties: app_properties, custom_properties: custom_properties,
                 workbook_protection: workbook_protection, workbook_properties: workbook_properties)
    writer.write_to(target)
  end
end

Instance Method Details

#build_app_properties_xmlObject

Returns:

  • (Object)


969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 969

def build_app_properties_xml
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("Properties", {
               xmlns: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
               "xmlns:vt": "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"
             })
  b.tag("Application") { |_| b.text(@app_properties[:application]) } if @app_properties[:application]
  b.tag("Company") { |_| b.text(@app_properties[:company]) } if @app_properties[:company]
  b.tag("Manager") { |_| b.text(@app_properties[:manager]) } if @app_properties[:manager]
  b.close_tag("Properties")
  io.string
end

#build_content_typesObject

Returns:

  • (Object)


311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 311

def build_content_types
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("Types", { xmlns: CT_NS })
  b.empty_tag("Default", { Extension: "rels", ContentType: "application/vnd.openxmlformats-package.relationships+xml" })
  b.empty_tag("Default", { Extension: "xml", ContentType: "application/xml" })
  b.empty_tag("Default", { Extension: "vml", ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing" })
  b.empty_tag("Override", { PartName: "/xl/workbook.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" })
  b.empty_tag("Override", { PartName: "/xl/styles.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" })
  b.empty_tag("Override", { PartName: "/xl/sharedStrings.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" }) unless @shared_strings.empty?

  # Document properties
  b.empty_tag("Override", { PartName: "/docProps/core.xml", ContentType: "application/vnd.openxmlformats-package.core-properties+xml" }) unless @core_properties.empty?
  b.empty_tag("Override", { PartName: "/docProps/app.xml", ContentType: "application/vnd.openxmlformats-officedocument.extended-properties+xml" }) unless @app_properties.empty?
  b.empty_tag("Override", { PartName: "/docProps/custom.xml", ContentType: "application/vnd.openxmlformats-officedocument.custom-properties+xml" }) unless @custom_properties.empty?

  drawing_count = 0
  chart_count = 0
  comment_count = 0
  table_count = 0
  pivot_cache_count = 0
  pivot_table_count = 0
  image_exts = {}
  @sheets.each_with_index do |sheet, idx|
    b.empty_tag("Override", { PartName: "/xl/worksheets/sheet#{idx + 1}.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" })

    sheet_images = sheet[:images] || []
    sheet_charts = sheet[:charts] || []
    sheet_shapes = sheet[:shapes] || []
    sheet_comments = sheet[:comments] || []
    sheet_tables = sheet[:tables] || []
    has_drawing = sheet_images.any? || sheet_charts.any? || sheet_shapes.any?

    if has_drawing
      drawing_count += 1
      b.empty_tag("Override", { PartName: "/xl/drawings/drawing#{drawing_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.drawing+xml" })
      sheet_charts.each do |_chart|
        chart_count += 1
        b.empty_tag("Override", { PartName: "/xl/charts/chart#{chart_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.drawingml.chart+xml" })
      end
      sheet_images.each do |img|
        ext = img[:ext] || "png"
        next if image_exts[ext]

        mime = case ext
               when "png" then "image/png"
               when "jpg", "jpeg" then "image/jpeg"
               when "gif" then "image/gif"
               when "bmp" then "image/bmp"
               when "emf" then "image/x-emf"
               when "wmf" then "image/x-wmf"
               else "application/octet-stream"
               end
        b.empty_tag("Default", { Extension: ext, ContentType: mime })
        image_exts[ext] = true
      end
    end

    if sheet_comments.any?
      comment_count += 1
      b.empty_tag("Override", { PartName: "/xl/comments#{comment_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml" })
    end

    sheet_tables.each do |_tbl|
      table_count += 1
      b.empty_tag("Override", { PartName: "/xl/tables/table#{table_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml" })
    end

    sheet_pivots = sheet[:pivot_tables] || []
    sheet_pivots.each do |_pt|
      pivot_cache_count += 1
      pivot_table_count += 1
      b.empty_tag("Override", { PartName: "/xl/pivotCache/pivotCacheDefinition#{pivot_cache_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml" })
      b.empty_tag("Override", { PartName: "/xl/pivotCache/pivotCacheRecords#{pivot_cache_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml" })
      b.empty_tag("Override", { PartName: "/xl/pivotTables/pivotTable#{pivot_table_count}.xml", ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml" })
    end
  end

  b.close_tag("Types")
  io.string
end

#build_core_properties_xmlObject

Returns:

  • (Object)


947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 947

def build_core_properties_xml
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("cp:coreProperties", {
               "xmlns:cp": "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
               "xmlns:dc": "http://purl.org/dc/elements/1.1/",
               "xmlns:dcterms": "http://purl.org/dc/terms/",
               "xmlns:dcmitype": "http://purl.org/dc/dcmitype/",
               "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
             })
  b.tag("dc:title") { |_| b.text(@core_properties[:title]) } if @core_properties[:title]
  b.tag("dc:subject") { |_| b.text(@core_properties[:subject]) } if @core_properties[:subject]
  b.tag("dc:creator") { |_| b.text(@core_properties[:creator]) } if @core_properties[:creator]
  b.tag("cp:keywords") { |_| b.text(@core_properties[:keywords]) } if @core_properties[:keywords]
  b.tag("dc:description") { |_| b.text(@core_properties[:description]) } if @core_properties[:description]
  b.tag("cp:lastModifiedBy") { |_| b.text(@core_properties[:last_modified_by]) } if @core_properties[:last_modified_by]
  b.tag("cp:category") { |_| b.text(@core_properties[:category]) } if @core_properties[:category]
  b.close_tag("cp:coreProperties")
  io.string
end

#build_custom_properties_xmlObject

Returns:

  • (Object)


984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 984

def build_custom_properties_xml
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("Properties", {
               xmlns: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
               "xmlns:vt": "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"
             })
  @custom_properties.each_with_index do |prop, idx|
    b.open_tag("property", { fmtid: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", pid: (idx + 2).to_s, name: prop[:name] })
    case prop[:type]
    when :number
      b.tag("vt:i4") { |_| b.text(prop[:value].to_s) }
    when :bool
      b.tag("vt:bool") { |_| b.text(prop[:value] ? "true" : "false") }
    when :date
      b.tag("vt:filetime") { |_| b.text(prop[:value].to_s) }
    else
      b.tag("vt:lpwstr") { |_| b.text(prop[:value].to_s) }
    end
    b.close_tag("property")
  end
  b.close_tag("Properties")
  io.string
end

#build_root_relsObject

Returns:

  • (Object)


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 394

def build_root_rels
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("Relationships", { xmlns: REL_NS })
  b.empty_tag("Relationship", {
                Id: "rId1",
                Type: "#{DOC_REL}/officeDocument",
                Target: "xl/workbook.xml"
              })
  rid = 1
  unless @core_properties.empty?
    rid += 1
    b.empty_tag("Relationship", {
                  Id: "rId#{rid}",
                  Type: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
                  Target: "docProps/core.xml"
                })
  end
  unless @app_properties.empty?
    rid += 1
    b.empty_tag("Relationship", {
                  Id: "rId#{rid}",
                  Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",
                  Target: "docProps/app.xml"
                })
  end
  unless @custom_properties.empty?
    rid += 1
    b.empty_tag("Relationship", {
                  Id: "rId#{rid}",
                  Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties",
                  Target: "docProps/custom.xml"
                })
  end
  b.close_tag("Relationships")
  io.string
end

#build_shared_strings_xmlObject

Returns:

  • (Object)


768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 768

def build_shared_strings_xml
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("sst", {
               xmlns: SSML_NS,
               count: @shared_strings.size.to_s,
               uniqueCount: @shared_strings.size.to_s
             })
  @shared_strings.each do |str|
    if str.is_a?(Xlsxrb::Elements::RichText)
      b.open_tag("si")
      str.runs.each do |run|
        font = run[:font]
        if font && !font.empty?
          b.open_tag("r")
          b.open_tag("rPr")
          b.empty_tag("b") if font[:bold]
          b.empty_tag("i") if font[:italic]
          b.empty_tag("strike") if font[:strike]
          if font[:underline]
            if font[:underline] == true
              b.empty_tag("u")
            else
              b.empty_tag("u", { val: font[:underline] })
            end
          end
          b.empty_tag("vertAlign", { val: font[:vert_align] }) if font[:vert_align]
          b.empty_tag("sz", { val: font[:sz].to_s }) if font[:sz]
          if font[:color]
            b.empty_tag("color", { rgb: font[:color] })
          elsif font[:theme]
            tc_attrs = { theme: font[:theme].to_s }
            tc_attrs[:tint] = font[:tint].to_s if font[:tint]
            b.empty_tag("color", tc_attrs)
          end
          b.empty_tag("rFont", { val: font[:name] }) if font[:name]
          b.empty_tag("family", { val: font[:family].to_s }) if font[:family]
          b.empty_tag("scheme", { val: font[:scheme] }) if font[:scheme]
          b.close_tag("rPr")
          b.tag("t") { |_| b.text(run[:text]) }
          b.close_tag("r")
        else
          b.tag("r") { |_| b.tag("t") { |_| b.text(run[:text]) } }
        end
      end
      b.close_tag("si")
    else
      b.tag("si") { |_| b.tag("t") { |_| b.text(str.to_s) } }
    end
  end
  b.close_tag("sst")
  io.string
end

#build_sheet_rels_from_list(rels) ⇒ Object

Parameters:

  • rels (Object)

Returns:

  • (Object)


297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 297

def build_sheet_rels_from_list(rels)
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("Relationships", { xmlns: REL_NS })
  rels.each do |rel|
    attrs = { Id: rel[:id], Type: rel[:type], Target: rel[:target] }
    attrs[:TargetMode] = rel[:target_mode] if rel[:target_mode]
    b.empty_tag("Relationship", attrs)
  end
  b.close_tag("Relationships")
  io.string
end

#build_styles_xmlObject

Returns:

  • (Object)


540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 540

def build_styles_xml
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("styleSheet", { xmlns: SSML_NS })

  # Fonts
  fonts = @styles&.dig(:fonts) || []
  fonts = [{}] if fonts.empty? # At least one default font
  b.tag("fonts", { count: fonts.size.to_s }) do |_|
    fonts.each do |font_props|
      b.tag("font") do |_|
        b.empty_tag("sz", { val: (font_props[:sz] || 11).to_s }) if font_props[:sz] || fonts == [{}]
        b.empty_tag("b") if font_props[:bold]
        b.empty_tag("i") if font_props[:italic]
        b.empty_tag("strike") if font_props[:strike]
        if font_props[:underline]
          b.empty_tag("u", font_props[:underline] == "single" ? {} : { val: font_props[:underline] })
        end
        b.empty_tag("color", { rgb: font_props[:color] }) if font_props[:color]
        b.empty_tag("name", { val: font_props[:name] || "Calibri" })
      end
    end
  end

  # Fills
  fills = @styles&.dig(:fills) || []
  fills = [{ pattern: "none" }, { pattern: "gray125" }] if fills.empty?
  b.tag("fills", { count: fills.size.to_s }) do |_|
    fills.each do |fill_props|
      b.tag("fill") do |_|
        if fill_props[:gradient]
          b.open_tag("gradientFill", { type: fill_props[:gradient][:type], degree: fill_props[:gradient][:degree]&.to_s }.compact)
          fill_props[:gradient][:stops].each do |stop|
            b.tag("stop", { position: stop[:position].to_s }) do |_|
              b.empty_tag("color", { rgb: stop[:color] })
            end
          end
          b.close_tag("gradientFill")
        else
          b.tag("patternFill", { patternType: fill_props[:pattern] || "none" }) do |_|
            b.empty_tag("fgColor", { rgb: fill_props[:fg_color] }) if fill_props[:fg_color]
            b.empty_tag("bgColor", { rgb: fill_props[:bg_color] }) if fill_props[:bg_color]
          end
        end
      end
    end
  end

  # Borders
  borders = @styles&.dig(:borders) || []
  borders = [{}] if borders.empty?
  b.tag("borders", { count: borders.size.to_s }) do |_|
    borders.each do |border_props|
      border_attrs = {}
      border_attrs[:diagonalUp] = "1" if border_props[:diagonal_up]
      border_attrs[:diagonalDown] = "1" if border_props[:diagonal_down]
      b.tag("border", border_attrs) do |_|
        %i[left right top bottom diagonal].each do |side|
          side_data = border_props[side]
          if side_data
            b.tag(side.to_s, { style: side_data[:style] }) do |_|
              b.empty_tag("color", { rgb: side_data[:color] }) if side_data[:color]
            end
          else
            b.empty_tag(side.to_s)
          end
        end
      end
    end
  end

  # cellStyleXfs
  b.tag("cellStyleXfs", { count: "1" }) do |_|
    b.empty_tag("xf", { numFmtId: "0", fontId: "0", fillId: "0", borderId: "0" })
  end

  # Number formats
  num_fmts = @styles&.dig(:num_fmts) || []
  unless num_fmts.empty?
    b.tag("numFmts", { count: num_fmts.size.to_s }) do |_|
      num_fmts.each do |nf|
        b.empty_tag("numFmt", { numFmtId: nf[:num_fmt_id].to_s, formatCode: nf[:format_code] }) if nf.is_a?(Hash)
      end
    end
  end

  # Cell XFs (formatting)
  xf_entries = @styles&.dig(:xf_entries) || []
  xf_count = [xf_entries.size, 1].max
  b.tag("cellXfs", { count: xf_count.to_s }) do |_|
    xf_entries.each do |xf|
      attrs = {
        numFmtId: (xf[:num_fmt_id] || 0).to_s,
        fontId: (xf[:font_id] || 0).to_s,
        fillId: (xf[:fill_id] || 0).to_s,
        borderId: (xf[:border_id] || 0).to_s
      }
      attrs[:xfId] = xf[:xf_id].to_s if xf[:xf_id]
      attrs[:applyNumberFormat] = "1" if xf[:num_fmt_id]&.to_i&.positive?
      attrs[:applyFont] = "1" if xf[:font_id]&.to_i&.positive?
      attrs[:applyFill] = "1" if xf[:fill_id]&.to_i&.positive?
      attrs[:applyBorder] = "1" if xf[:border_id]&.to_i&.positive?
      attrs[:applyAlignment] = "1" if xf[:alignment]
      attrs[:applyProtection] = "1" if xf[:protection]

      if xf[:alignment] || xf[:protection]
        b.tag("xf", attrs) do |_|
          if xf[:alignment]
            align_attrs = {}
            align_attrs[:horizontal] = xf[:alignment][:horizontal] if xf[:alignment][:horizontal]
            align_attrs[:vertical] = xf[:alignment][:vertical] if xf[:alignment][:vertical]
            align_attrs[:wrapText] = "1" if xf[:alignment][:wrap_text]
            align_attrs[:textRotation] = xf[:alignment][:text_rotation].to_s if xf[:alignment][:text_rotation]
            align_attrs[:indent] = xf[:alignment][:indent].to_s if xf[:alignment][:indent]
            align_attrs[:relativeIndent] = xf[:alignment][:relative_indent].to_s if xf[:alignment][:relative_indent]
            align_attrs[:shrinkToFit] = "1" if xf[:alignment][:shrink_to_fit]
            align_attrs[:readingOrder] = xf[:alignment][:reading_order].to_s if xf[:alignment][:reading_order]
            align_attrs[:justifyLastLine] = "1" if xf[:alignment][:justify_last_line]
            b.empty_tag("alignment", align_attrs)
          end
          if xf[:protection]
            prot_attrs = {}
            prot_attrs[:locked] = xf[:protection][:locked] ? "1" : "0" unless xf[:protection][:locked].nil?
            prot_attrs[:hidden] = xf[:protection][:hidden] ? "1" : "0" unless xf[:protection][:hidden].nil?
            b.empty_tag("protection", prot_attrs)
          end
        end
      else
        b.empty_tag("xf", attrs)
      end
    end
    # Add default if empty
    b.empty_tag("xf", { numFmtId: "0", fontId: "0", fillId: "0", borderId: "0" }) if xf_entries.empty?
  end

  # Differential formats (for conditional formatting)
  dxfs = @styles&.dig(:dxfs) || []
  unless dxfs.empty?
    b.tag("dxfs", { count: dxfs.size.to_s }) do |_|
      dxfs.each do |dxf|
        b.tag("dxf") do |_|
          write_dxf_font(b, dxf[:font]) if dxf[:font]
          if dxf[:num_fmt]
            nf = dxf[:num_fmt]
            b.empty_tag("numFmt", { numFmtId: nf[:num_fmt_id].to_s, formatCode: nf[:format_code].to_s })
          end
          write_dxf_fill(b, dxf[:fill]) if dxf[:fill]
        end
      end
    end
  end

  b.close_tag("styleSheet")
  io.string
end

#build_table_xml(tbl, table_id) ⇒ Object

Parameters:

  • tbl (Object)
  • table_id (Object)

Returns:

  • (Object)


885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 885

def build_table_xml(tbl, table_id)
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  tbl_name = tbl[:name] || "Table#{table_id}"
  t_attrs = {
    xmlns: SSML_NS,
    id: table_id.to_s,
    name: tbl_name,
    displayName: tbl[:display_name] || tbl_name,
    ref: tbl[:ref]
  }
  t_attrs[:totalsRowCount] = tbl[:totals_row_count].to_s if tbl[:totals_row_count]&.positive?
  b.open_tag("table", t_attrs)

  # Auto filter for the table range
  b.empty_tag("autoFilter", { ref: tbl[:ref] })

  # Table columns
  columns = tbl[:columns] || []
  b.open_tag("tableColumns", { count: columns.size.to_s })
  columns.each_with_index do |col_name, ci|
    b.empty_tag("tableColumn", { id: (ci + 1).to_s, name: col_name })
  end
  b.close_tag("tableColumns")

  # Table style. Accepts either:
  # - style: "TableStyleMedium9"
  # - style: { name:, show_* }
  # and also show_* values at the table root for Facade compatibility.
  raw_style = tbl[:style]
  style = if raw_style.is_a?(Hash)
            raw_style
          elsif raw_style
            { name: raw_style.to_s }
          else
            {}
          end

  style_attrs = { name: style[:name] || "TableStyleMedium2" }

  show_first_column = style.key?(:show_first_column) ? style[:show_first_column] : tbl[:show_first_column]
  show_last_column = style.key?(:show_last_column) ? style[:show_last_column] : tbl[:show_last_column]
  show_row_stripes = if style.key?(:show_row_stripes)
                       style[:show_row_stripes]
                     elsif tbl.key?(:show_row_stripes)
                       tbl[:show_row_stripes]
                     else
                       true
                     end
  show_column_stripes = style.key?(:show_column_stripes) ? style[:show_column_stripes] : tbl[:show_column_stripes]

  style_attrs[:showFirstColumn] = show_first_column ? "1" : "0" unless show_first_column.nil?
  style_attrs[:showLastColumn] = show_last_column ? "1" : "0" unless show_last_column.nil?
  style_attrs[:showRowStripes] = show_row_stripes ? "1" : "0"
  style_attrs[:showColumnStripes] = show_column_stripes ? "1" : "0" unless show_column_stripes.nil?
  b.empty_tag("tableStyleInfo", style_attrs)

  b.close_tag("table")
  io.string
end

#build_workbook_relsObject

Returns:

  • (Object)


498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 498

def build_workbook_rels
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("Relationships", { xmlns: REL_NS })
  @sheets.each_with_index do |_sheet, idx|
    b.empty_tag("Relationship", {
                  Id: "rId#{idx + 1}",
                  Type: "#{DOC_REL}/worksheet",
                  Target: "worksheets/sheet#{idx + 1}.xml"
                })
  end
  rid = @sheets.size + 1
  b.empty_tag("Relationship", {
                Id: "rId#{rid}",
                Type: "#{DOC_REL}/styles",
                Target: "styles.xml"
              })
  unless @shared_strings.empty?
    rid += 1
    b.empty_tag("Relationship", {
                  Id: "rId#{rid}",
                  Type: "#{DOC_REL}/sharedStrings",
                  Target: "sharedStrings.xml"
                })
  end

  # Pivot cache relationships
  total_pivots = @sheets.sum { |s| (s[:pivot_tables] || []).size }
  total_pivots.times do |i|
    rid += 1
    b.empty_tag("Relationship", {
                  Id: "rId#{rid}",
                  Type: "#{DOC_REL}/pivotCacheDefinition",
                  Target: "pivotCache/pivotCacheDefinition#{i + 1}.xml"
                })
  end

  b.close_tag("Relationships")
  io.string
end

#build_workbook_xmlObject

Returns:

  • (Object)


433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 433

def build_workbook_xml
  io = StringIO.new
  b = XmlBuilder.new(io)
  b.declaration
  b.open_tag("workbook", {
               xmlns: SSML_NS,
               "xmlns:r": DOC_REL
             })

  # Workbook properties
  if @workbook_properties && !@workbook_properties.empty?
    attrs = {}
    attrs[:date1904] = "1" if @workbook_properties[:date1904]
    attrs[:updateLinks] = @workbook_properties[:update_links] if @workbook_properties[:update_links]
    b.empty_tag("workbookPr", attrs) unless attrs.empty?
  end

  # Workbook protection
  if @workbook_protection
    wp_attrs = {}
    wp_attrs[:lockStructure] = "1" if @workbook_protection[:lock_structure]
    wp_attrs[:lockWindows] = "1" if @workbook_protection[:lock_windows]
    wp_attrs[:workbookPassword] = @workbook_protection[:password] if @workbook_protection[:password]
    b.empty_tag("workbookProtection", wp_attrs) unless wp_attrs.empty?
  end

  b.open_tag("sheets")
  @sheets.each_with_index do |sheet, idx|
    b.empty_tag("sheet", {
                  name: sheet[:name],
                  sheetId: (idx + 1).to_s,
                  "r:id": "rId#{idx + 1}"
                })
  end
  b.close_tag("sheets")

  # Defined names
  unless @defined_names.empty?
    b.open_tag("definedNames")
    @defined_names.each do |dn|
      dn_attrs = { name: dn[:name] }
      dn_attrs[:localSheetId] = dn[:local_sheet_id].to_s if dn[:local_sheet_id]
      dn_attrs[:hidden] = "1" if dn[:hidden]
      b.tag("definedName", dn_attrs) { |_| b.text(dn[:value]) }
    end
    b.close_tag("definedNames")
  end

  # Pivot caches
  total_pivots = @sheets.sum { |s| (s[:pivot_tables] || []).size }
  if total_pivots.positive?
    # rId for pivot caches starts after sheets + styles + sharedStrings
    # In build_workbook_rels: sheets(1..N), styles(N+1), sharedStrings(N+2 if present)
    pivot_rid_base = @sheets.size + 1 + (@shared_strings.empty? ? 0 : 1)
    b.open_tag("pivotCaches")
    total_pivots.times do |i|
      b.empty_tag("pivotCache", { cacheId: (i + 1).to_s, "r:id": "rId#{pivot_rid_base + i + 1}" })
    end
    b.close_tag("pivotCaches")
  end

  b.close_tag("workbook")
  io.string
end

#extract_dxf_from_rule!(rule) ⇒ Object

Parameters:

  • rule (Object)

Returns:

  • (Object)


722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 722

def extract_dxf_from_rule!(rule)
  font = {}
  font[:color] = rule.delete(:font_color) if rule.key?(:font_color)
  font[:bold] = rule.delete(:bold) if rule.key?(:bold)
  font[:italic] = rule.delete(:italic) if rule.key?(:italic)
  font[:underline] = rule.delete(:underline) if rule.key?(:underline)

  fill = {}
  if rule.key?(:fill_color)
    fill[:pattern] = "solid"
    fill[:fg_color] = rule.delete(:fill_color)
  end

  dxf = {}
  dxf[:font] = font unless font.empty?
  dxf[:fill] = fill unless fill.empty?
  dxf.empty? ? nil : dxf
end

#preprocess_conditional_formats!Object

Returns:

  • (Object)


697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 697

def preprocess_conditional_formats!
  @styles[:dxfs] ||= []

  @sheets.each do |sheet|
    rules = sheet[:conditional_formats]
    next if rules.nil? || rules.empty?

    sheet[:conditional_formats] = rules.map do |rule|
      next rule if rule[:format_id]

      normalized = rule.dup
      dxf = normalized.delete(:dxf) || extract_dxf_from_rule!(normalized)
      next normalized unless dxf

      dxf_id = @styles[:dxfs].index(dxf)
      unless dxf_id
        @styles[:dxfs] << dxf
        dxf_id = @styles[:dxfs].size - 1
      end
      normalized[:format_id] = dxf_id
      normalized
    end
  end
end

#write_dxf_fill(builder, fill) ⇒ Object

Parameters:

  • builder (Object)
  • fill (Object)

Returns:

  • (Object)


758
759
760
761
762
763
764
765
766
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 758

def write_dxf_fill(builder, fill)
  builder.tag("fill") do |_|
    pattern = fill[:pattern] || "solid"
    builder.tag("patternFill", { patternType: pattern }) do |_|
      builder.empty_tag("fgColor", { rgb: fill[:fg_color] }) if fill[:fg_color]
      builder.empty_tag("bgColor", { rgb: fill[:bg_color] }) if fill[:bg_color]
    end
  end
end

#write_dxf_font(builder, font) ⇒ Object

Parameters:

  • builder (Object)
  • font (Object)

Returns:

  • (Object)


741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 741

def write_dxf_font(builder, font)
  builder.tag("font") do |_|
    builder.empty_tag("b") if font[:bold]
    builder.empty_tag("i") if font[:italic]
    if font[:underline]
      if font[:underline] == true
        builder.empty_tag("u")
      else
        builder.empty_tag("u", { val: font[:underline] })
      end
    end
    builder.empty_tag("color", { rgb: font[:color] }) if font[:color]
    builder.empty_tag("name", { val: font[:name] }) if font[:name]
    builder.empty_tag("sz", { val: font[:sz].to_s }) if font[:sz]
  end
end

#write_to(target) ⇒ Object

Parameters:

  • target (Object)

Returns:

  • (Object)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 66

def write_to(target)
  preprocess_conditional_formats!

  ZipWriter.open(target) do |zip|
    zip.add_entry("[Content_Types].xml", build_content_types)
    zip.add_entry("_rels/.rels", build_root_rels)
    zip.add_entry("xl/workbook.xml", build_workbook_xml)
    zip.add_entry("xl/_rels/workbook.xml.rels", build_workbook_rels)
    zip.add_entry("xl/styles.xml", build_styles_xml)
    zip.add_entry("xl/sharedStrings.xml", build_shared_strings_xml) unless @shared_strings.empty?

    # Document properties
    zip.add_entry("docProps/core.xml", build_core_properties_xml) unless @core_properties.empty?
    zip.add_entry("docProps/app.xml", build_app_properties_xml) unless @app_properties.empty?
    zip.add_entry("docProps/custom.xml", build_custom_properties_xml) unless @custom_properties.empty?

    @sheets.each_with_index do |sheet, idx|
      sheet_images = sheet[:images] || []
      sheet_charts = sheet[:charts] || []
      sheet_shapes = sheet[:shapes] || []
      sheet_comments = sheet[:comments] || []
      sheet_tables = sheet[:tables] || []
      sheet_hyperlinks = sheet[:hyperlinks] || []
      has_drawing = sheet_images.any? || sheet_charts.any? || sheet_shapes.any?
      has_comments = sheet_comments.any?

      # Track relationship IDs for this sheet
      sheet_rels = []
      drawing_rid = nil
      vml_rid = nil
      table_start_rid = nil
      hyperlink_rels = []

      # Drawing relationships (images, charts, shapes)
      if has_drawing
        @drawing_count += 1
        drawing_rid_num = sheet_rels.size + 1
        sheet_rels << { id: "rId#{drawing_rid_num}", type: "#{DOC_REL}/drawing", target: "../drawings/drawing#{@drawing_count}.xml" }
        drawing_rid = "rId#{drawing_rid_num}"

        drawing_rels_data = []
        drawing_parts = []

        chart_writer = Xlsxrb::Ooxml::Writer.new
        chart_writer.add_sheet(sheet[:name]) unless sheet[:name] == "Sheet1"

        # Populate sheet data in chart_writer for chart cache resolution
        (sheet[:rows] || []).each do |row|
          cells = row.is_a?(Hash) ? row[:cells] : row.cells
          (cells || []).each do |cell|
            ref = cell.is_a?(Hash) ? cell[:ref] : cell.ref
            value = cell.is_a?(Hash) ? cell[:value] : cell.value
            chart_writer.set_cell(ref, value, sheet: sheet[:name])
          end
        end
        sheet[:cells]&.each do |ref, value|
          chart_writer.set_cell(ref, value, sheet: sheet[:name])
        end

        sheet_images.each do |img|
          media_idx = @drawing_count # simplified
          media_path = "xl/media/image#{media_idx}.#{img[:ext] || "png"}"
          zip.add_binary_entry(media_path, img[:file_data])
          drawing_rels_data << { type: :image, target: "../media/image#{media_idx}.#{img[:ext] || "png"}" }
          drawing_parts << { kind: :pic, img: img, rid_index: drawing_rels_data.size }
        end

        sheet_charts.each do |chart_options|
          chart_writer.add_chart(**chart_options)
        end

        processed_charts = chart_writer.charts
        processed_charts.each do |chart|
          @chart_count += 1
          chart_path = "xl/charts/chart#{@chart_count}.xml"
          zip.add_entry(chart_path, chart_writer.send(:generate_chart_xml, chart))
          drawing_rels_data << { type: :chart, target: "../charts/chart#{@chart_count}.xml" }
          drawing_parts << { kind: :chart, chart: chart, rid_index: drawing_rels_data.size }
        end

        sheet_shapes.each_with_index do |shape, si|
          drawing_parts << { kind: :sp, shape: shape, id: drawing_parts.size + si + 2 }
        end

        drawing_xml = chart_writer.send(:generate_drawing_xml, drawing_parts)
        zip.add_entry("xl/drawings/drawing#{@drawing_count}.xml", drawing_xml)
        unless drawing_rels_data.empty?
          drawing_rels_xml = chart_writer.send(:generate_drawing_rels, drawing_rels_data)
          zip.add_entry("xl/drawings/_rels/drawing#{@drawing_count}.xml.rels", drawing_rels_xml)
        end
      end

      # Comment relationships
      if has_comments
        @comment_count += 1
        comment_rid_num = sheet_rels.size + 1
        sheet_rels << { id: "rId#{comment_rid_num}", type: "#{DOC_REL}/comments", target: "../comments#{@comment_count}.xml" }
        vml_rid_num = sheet_rels.size + 1
        sheet_rels << { id: "rId#{vml_rid_num}", type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing", target: "../drawings/vmlDrawing#{@comment_count}.vml" }
        vml_rid = "rId#{vml_rid_num}"

        # Generate comments XML using Writer's method
        comment_writer = Xlsxrb::Ooxml::Writer.new
        sheet_comments.each do |c|
          comment_writer.add_comment(c[:cell], c[:text], author: c[:author] || "Author")
        end
        zip.add_entry("xl/comments#{@comment_count}.xml", comment_writer.send(:generate_comments_xml, comment_writer.comments))
        zip.add_entry("xl/drawings/vmlDrawing#{@comment_count}.vml", comment_writer.send(:generate_vml_drawing_xml, comment_writer.comments))
      end

      # Hyperlink relationships (external URLs need rels)
      sheet_hyperlinks.each_with_index do |link, _hi|
        next unless link[:url]

        h_rid_num = sheet_rels.size + 1
        sheet_rels << { id: "rId#{h_rid_num}", type: "#{DOC_REL}/hyperlink", target: link[:url], target_mode: "External" }
        hyperlink_rels << h_rid_num
      end
      # Assign rIds to hyperlinks
      h_rid_idx = 0
      enriched_hyperlinks = sheet_hyperlinks.map do |link|
        if link[:url]
          rid = hyperlink_rels[h_rid_idx]
          h_rid_idx += 1
          link.merge(_rid: rid)
        else
          link
        end
      end

      # Table relationships
      unless sheet_tables.empty?
        table_start_rid = sheet_rels.size + 1
        sheet_tables.each_with_index do |_tbl, _ti|
          @table_count += 1
          t_rid_num = sheet_rels.size + 1
          sheet_rels << { id: "rId#{t_rid_num}", type: "#{DOC_REL}/table", target: "../tables/table#{@table_count}.xml" }
        end
      end

      # Pivot table relationships
      sheet_pivot_tables = sheet[:pivot_tables] || []
      pivot_table_start_cache = @pivot_cache_count
      unless sheet_pivot_tables.empty?
        pivot_writer = Xlsxrb::Ooxml::Writer.new
        pivot_writer.add_sheet(sheet[:name])
        sheet_pivot_tables.each do |pt|
          pivot_writer.add_pivot_table(
            pt[:source_ref],
            row_fields: pt[:row_fields],
            data_fields: pt[:data_fields],
            col_fields: pt[:col_fields] || [],
            dest_ref: pt[:dest_ref] || "E1",
            name: pt[:name],
            field_names: pt[:field_names],
            items: pt[:items],
            sheet: sheet[:name]
          )

          @pivot_cache_count += 1
          @pivot_table_count += 1

          pt_rid_num = sheet_rels.size + 1
          sheet_rels << { id: "rId#{pt_rid_num}", type: "#{DOC_REL}/pivotTable", target: "../pivotTables/pivotTable#{@pivot_table_count}.xml" }
        end

        # Generate pivot table XML files
        pivot_data = pivot_writer.pivot_tables(sheet: sheet[:name])
        pivot_data.each_with_index do |pt_data, pi|
          cache_idx = pivot_table_start_cache + pi + 1
          pt_idx = pivot_table_start_cache + pi + 1
          zip.add_entry("xl/pivotCache/pivotCacheDefinition#{cache_idx}.xml",
                        pivot_writer.send(:generate_pivot_cache_definition_xml, pt_data, cache_idx))
          zip.add_entry("xl/pivotCache/pivotCacheRecords#{cache_idx}.xml",
                        pivot_writer.send(:generate_pivot_cache_records_xml, pt_data))
          zip.add_entry("xl/pivotTables/pivotTable#{pt_idx}.xml",
                        pivot_writer.send(:generate_pivot_table_xml, pt_data, cache_idx))
          zip.add_entry("xl/pivotCache/_rels/pivotCacheDefinition#{cache_idx}.xml.rels",
                        pivot_writer.send(:generate_pivot_cache_rels, cache_idx))
          zip.add_entry("xl/pivotTables/_rels/pivotTable#{pt_idx}.xml.rels",
                        pivot_writer.send(:generate_pivot_table_rels, cache_idx))
        end
      end

      # Build worksheet rels if any
      zip.add_entry("xl/worksheets/_rels/sheet#{idx + 1}.xml.rels", build_sheet_rels_from_list(sheet_rels)) unless sheet_rels.empty?

      # Generate table XML files
      table_id_base = @table_count - sheet_tables.size
      sheet_tables.each_with_index do |tbl, ti|
        tbl_id = table_id_base + ti + 1
        zip.add_entry("xl/tables/table#{tbl_id}.xml", build_table_xml(tbl, tbl_id))
      end

      # Build the worksheet XML with all metadata
      zip.start_entry("xl/worksheets/sheet#{idx + 1}.xml")
      write_worksheet_xml(
        ZipEntryIO.new(zip),
        sheet,
        drawing_rid: drawing_rid,
        sheet_protection: sheet[:sheet_protection],
        auto_filter: sheet[:auto_filter],
        filter_columns: sheet[:filter_columns],
        sort_state: sheet[:sort_state],
        merge_cells: sheet[:merge_cells],
        conditional_formats: sheet[:conditional_formats],
        data_validations: sheet[:data_validations],
        hyperlinks: enriched_hyperlinks.empty? ? nil : enriched_hyperlinks,
        print_options: sheet[:print_options],
        page_margins: sheet[:page_margins],
        page_setup: sheet[:page_setup],
        header_footer: sheet[:header_footer],
        row_breaks: sheet[:row_breaks],
        col_breaks: sheet[:col_breaks],
        freeze_pane: sheet[:freeze_pane],
        split_pane: sheet[:split_pane],
        selection: sheet[:selection],
        sheet_view: sheet[:sheet_view],
        sheet_properties: sheet[:sheet_properties],
        tables: sheet_tables,
        table_start_rid: table_start_rid,
        legacy_drawing_rid: vml_rid,
        sparkline_groups: sheet[:sparkline_groups]
      )
      zip.finish_entry
    end
  end
end

#write_worksheet_xml(io, sheet, drawing_rid: nil, sheet_protection: nil, auto_filter: nil, filter_columns: nil, sort_state: nil, merge_cells: nil, conditional_formats: nil, data_validations: nil, hyperlinks: nil, print_options: nil, page_margins: nil, page_setup: nil, header_footer: nil, row_breaks: nil, col_breaks: nil, freeze_pane: nil, split_pane: nil, selection: nil, sheet_view: nil, sheet_properties: nil, tables: nil, table_start_rid: nil, legacy_drawing_rid: nil, sparkline_groups: nil) ⇒ Object

Parameters:

  • io (Object)
  • sheet (Object)
  • drawing_rid: (Object) (defaults to: nil)
  • sheet_protection: (Object) (defaults to: nil)
  • auto_filter: (Object) (defaults to: nil)
  • filter_columns: (Object) (defaults to: nil)
  • sort_state: (Object) (defaults to: nil)
  • merge_cells: (Object) (defaults to: nil)
  • conditional_formats: (Object) (defaults to: nil)
  • data_validations: (Object) (defaults to: nil)
  • hyperlinks: (Object) (defaults to: nil)
  • print_options: (Object) (defaults to: nil)
  • page_margins: (Object) (defaults to: nil)
  • page_setup: (Object) (defaults to: nil)
  • header_footer: (Object) (defaults to: nil)
  • row_breaks: (Object) (defaults to: nil)
  • col_breaks: (Object) (defaults to: nil)
  • freeze_pane: (Object) (defaults to: nil)
  • split_pane: (Object) (defaults to: nil)
  • selection: (Object) (defaults to: nil)
  • sheet_view: (Object) (defaults to: nil)
  • sheet_properties: (Object) (defaults to: nil)
  • tables: (Object) (defaults to: nil)
  • table_start_rid: (Object) (defaults to: nil)
  • legacy_drawing_rid: (Object) (defaults to: nil)
  • sparkline_groups: (Object) (defaults to: nil)

Returns:

  • (Object)


823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'lib/xlsxrb/ooxml/workbook_writer.rb', line 823

def write_worksheet_xml(io, sheet, drawing_rid: nil, sheet_protection: nil,
                        auto_filter: nil, filter_columns: nil, sort_state: nil,
                        merge_cells: nil, conditional_formats: nil,
                        data_validations: nil, hyperlinks: nil,
                        print_options: nil, page_margins: nil, page_setup: nil,
                        header_footer: nil, row_breaks: nil, col_breaks: nil,
                        freeze_pane: nil, split_pane: nil, selection: nil,
                        sheet_view: nil, sheet_properties: nil,
                        tables: nil, table_start_rid: nil,
                        legacy_drawing_rid: nil, sparkline_groups: nil)
  ws = WorksheetWriter.new(io)
  ws.start(
    columns: sheet[:columns] || [],
    sheet_properties: sheet_properties,
    freeze_pane: freeze_pane,
    split_pane: split_pane,
    selection: selection,
    sheet_view: sheet_view
  )
  if sheet[:rows_tmp_path]
    File.open(sheet[:rows_tmp_path], "rb") do |f|
      while (chunk = f.read(16_384))
        io.write(chunk)
      end
    end
  else
    (sheet[:rows] || []).each do |row|
      if row.is_a?(Hash)
        ws.write_row(row[:index], row[:cells], attrs: row[:attrs] || {}, unmapped: row[:unmapped] || [], sst_index: @shared_strings_index)
      else
        attrs = {}
        attrs[:height] = row.height if row.height
        attrs[:hidden] = true if row.hidden
        attrs[:custom_height] = true if row.custom_height
        attrs[:outline_level] = row.outline_level if row.outline_level
        ws.write_row(row.index, row.cells, attrs: attrs, unmapped: row.unmapped_data || [], sst_index: @shared_strings_index)
      end
    end
  end
  ws.finish(
    drawing_rid: drawing_rid,
    sheet_protection: sheet_protection,
    auto_filter: auto_filter,
    filter_columns: filter_columns,
    sort_state: sort_state,
    merge_cells: merge_cells,
    conditional_formats: conditional_formats,
    data_validations: data_validations,
    hyperlinks: hyperlinks,
    print_options: print_options,
    page_margins: page_margins,
    page_setup: page_setup,
    header_footer: header_footer,
    row_breaks: row_breaks,
    col_breaks: col_breaks,
    tables: tables,
    table_start_rid: table_start_rid,
    legacy_drawing_rid: legacy_drawing_rid,
    sparkline_groups: sparkline_groups
  )
end