Class: Xlsxrb::Ooxml::Writer

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

Overview

Writes spreadsheet data into an XLSX file.

Constant Summary collapse

XML_HEADER =

Returns:

  • (::String)
%(<?xml version="1.0" encoding="UTF-8"?>)
CT_NS =

Returns:

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

Returns:

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

Returns:

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

Returns:

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

Returns:

  • (::String)
"http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
DC_NS =

Returns:

  • (::String)
"http://purl.org/dc/elements/1.1/"
DCTERMS_NS =

Returns:

  • (::String)
"http://purl.org/dc/terms/"
XSI_NS =

Returns:

  • (::String)
"http://www.w3.org/2001/XMLSchema-instance"
APP_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"
VT_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"
CELL_ADDRESS_PATTERN =

Returns:

  • (::Regexp)
/\A([A-Z]{1,3})(\d+)\z/
MAX_ROW =

Returns:

  • (::Integer)
1_048_576
MAX_COLUMN_INDEX =

XFD

Returns:

  • (::Integer)
16_384
CF_TYPE_MAP =

Returns:

  • (Object)
{
  cell_is: "cellIs",
  expression: "expression",
  color_scale: "colorScale",
  data_bar: "dataBar",
  icon_set: "iconSet",
  above_average: "aboveAverage",
  top10: "top10",
  duplicate_values: "duplicateValues",
  unique_values: "uniqueValues",
  contains_text: "containsText",
  not_contains_text: "notContainsText",
  begins_with: "beginsWith",
  ends_with: "endsWith",
  contains_blanks: "containsBlanks",
  not_contains_blanks: "notContainsBlanks",
  time_period: "timePeriod"
}.freeze
XDR_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
A_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/drawingml/2006/main"
C_NS =

Returns:

  • (::String)
"http://schemas.openxmlformats.org/drawingml/2006/chart"
CHART_TYPE_MAP =

Returns:

  • (Object)
{
  bar: "barChart", line: "lineChart", pie: "pieChart",
  area: "areaChart", scatter: "scatterChart", doughnut: "doughnutChart",
  radar: "radarChart", bar3d: "bar3DChart", line3d: "line3DChart",
  pie3d: "pie3DChart", area3d: "area3DChart", surface: "surfaceChart",
  surface3d: "surface3DChart",
  stock: "stockChart", bubble: "bubbleChart",
  of_pie: "ofPieChart"
}.freeze
NO_AXIS_CHARTS =

Returns:

  • (Object)
%w[pieChart doughnutChart pie3DChart ofPieChart].freeze
THREE_AXIS_CHARTS =

Returns:

  • (Object)
%w[surface3DChart].freeze
GROUPING_CHARTS =

Returns:

  • (Object)
%w[barChart lineChart areaChart bar3DChart line3DChart area3DChart].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeObject

: () -> void



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
# File 'lib/xlsxrb/ooxml/writer.rb', line 31

def initialize
  @sheets = { "Sheet1" => {} }
  @column_widths = { "Sheet1" => {} }
  @column_attrs = { "Sheet1" => {} }
  @row_attrs = { "Sheet1" => {} }
  @merge_cells = { "Sheet1" => [] }
  @hyperlinks = { "Sheet1" => {} }
  @cell_styles = { "Sheet1" => {} }
  @cell_phonetic = { "Sheet1" => {} }
  @auto_filters = { "Sheet1" => nil }
  @filter_columns = { "Sheet1" => {} }
  @sort_state = { "Sheet1" => nil }
  @num_fmts = []
  @fonts = [{ sz: 11, name: "Calibri" }]
  @fills = [{ pattern: "none" }, { pattern: "gray125" }]
  @borders = [{ left: nil, right: nil, top: nil, bottom: nil }]
  @xf_entries = [{ num_fmt_id: 0, font_id: 0, fill_id: 0, border_id: 0 }]
  @cell_style_xfs = [{ num_fmt_id: 0, font_id: 0, fill_id: 0, border_id: 0 }]
  @cell_style_names = [{ name: "Normal", xf_id: 0, builtin_id: 0 }]
  @dxfs = []
  @indexed_colors = []
  @mru_colors = []
  @table_styles = {}
  @sheet_order = ["Sheet1"]
  @core_properties = {}
  @app_properties = {}
  @custom_properties = []
  @file_version = {}
  @file_sharing = {}
  @workbook_properties = {}
  @workbook_views = {}
  @calc_properties = {}
  @file_recovery_properties = {}
  @sheet_states = {}
  @defined_names = []
  @sheet_properties = { "Sheet1" => {} }
  @phonetic_properties = { "Sheet1" => nil }
  @sheet_formats = { "Sheet1" => {} }
  @sheet_views = { "Sheet1" => {} }
  @freeze_panes = { "Sheet1" => nil }
  @selections = { "Sheet1" => nil }
  @print_options = { "Sheet1" => {} }
  @page_margins = { "Sheet1" => nil }
  @page_setup = { "Sheet1" => {} }
  @header_footer = { "Sheet1" => {} }
  @row_breaks = { "Sheet1" => [] }
  @col_breaks = { "Sheet1" => [] }
  @data_validations = { "Sheet1" => [] }
  @data_validations_options = { "Sheet1" => {} }
  @conditional_formats = { "Sheet1" => [] }
  @tables = { "Sheet1" => [] }
  @cell_watches = { "Sheet1" => [] }
  @ignored_errors = { "Sheet1" => [] }
  @data_consolidate = { "Sheet1" => nil }
  @scenarios = { "Sheet1" => nil }
  @use_shared_strings = true
  @images = { "Sheet1" => [] }
  @charts_data = { "Sheet1" => [] }
  @shapes_data = { "Sheet1" => [] }
  @comments_data = { "Sheet1" => [] }
  @pivot_tables_data = { "Sheet1" => [] }
  @extra_entries = {}
  @extra_ct_defaults = {}
  @extra_ct_overrides = {}
  @preserve_macros = false
  @sheet_protection = { "Sheet1" => nil }
  @protected_ranges = { "Sheet1" => [] }
  @workbook_protection = nil
  @external_links = []
end

Instance Attribute Details

#bordersObject (readonly)

Returns the value of attribute borders.

Returns:

  • (Object)


28
29
30
# File 'lib/xlsxrb/ooxml/writer.rb', line 28

def borders
  @borders
end

#fillsObject (readonly)

Returns the value of attribute fills.

Returns:

  • (Object)


28
29
30
# File 'lib/xlsxrb/ooxml/writer.rb', line 28

def fills
  @fills
end

#fontsObject (readonly)

Returns the value of attribute fonts.

Returns:

  • (Object)


28
29
30
# File 'lib/xlsxrb/ooxml/writer.rb', line 28

def fonts
  @fonts
end

#num_fmtsObject (readonly)

Returns the value of attribute num_fmts.

Returns:

  • (Object)


28
29
30
# File 'lib/xlsxrb/ooxml/writer.rb', line 28

def num_fmts
  @num_fmts
end

#sheet_orderObject (readonly)

Returns ordered sheet names. : untyped

Returns:

  • (Object)


1183
1184
1185
# File 'lib/xlsxrb/ooxml/writer.rb', line 1183

def sheet_order
  @sheet_order
end

#xf_entriesObject (readonly)

Returns the value of attribute xf_entries.

Returns:

  • (Object)


28
29
30
# File 'lib/xlsxrb/ooxml/writer.rb', line 28

def xf_entries
  @xf_entries
end

Instance Method Details

#absolute_cell(cell_ref) ⇒ Object

Converts "A1" to "$A$1". : (untyped cell_ref) -> ::String

Parameters:

  • cell_ref (Object)

Returns:

  • (Object)


5654
5655
5656
5657
5658
5659
# File 'lib/xlsxrb/ooxml/writer.rb', line 5654

def absolute_cell(cell_ref)
  m = cell_ref.match(/\A([A-Z]+)(\d+)\z/)
  raise ArgumentError, "invalid cell reference: #{cell_ref}" unless m

  "$#{m[1]}$#{m[2]}"
end

#absolute_range(range) ⇒ Object

Converts a range like "A1:D20" to absolute "$A$1:$D$20". : (untyped range) -> untyped

Parameters:

  • range (Object)

Returns:

  • (Object)


5648
5649
5650
# File 'lib/xlsxrb/ooxml/writer.rb', line 5648

def absolute_range(range)
  range.split(":").map { |part| absolute_cell(part) }.join(":")
end

#add_border(**opts) ⇒ Object

Registers a border and returns its border_id. Opts: left, right, top, bottom (each a hash with :style and optional :color). : (**untyped opts) -> untyped

Parameters:

  • opts (Object)

Returns:

  • (Object)


449
450
451
452
453
454
455
# File 'lib/xlsxrb/ooxml/writer.rb', line 449

def add_border(**opts)
  existing = @borders.index(opts)
  return existing if existing

  @borders << opts
  @borders.size - 1
end

#add_cell_style(**opts) ⇒ Object

Registers a cell style (xf entry) and returns its index for use with set_cell_style. Opts: font_id, fill_id, border_id, num_fmt_id, alignment (hash with horizontal, vertical, wrap_text, text_rotation, indent, shrink_to_fit). : (**untyped opts) -> untyped

Parameters:

  • opts (Object)

Returns:

  • (Object)


460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/xlsxrb/ooxml/writer.rb', line 460

def add_cell_style(**opts)
  entry = {
    num_fmt_id: opts[:num_fmt_id] || 0,
    font_id: opts[:font_id] || 0,
    fill_id: opts[:fill_id] || 0,
    border_id: opts[:border_id] || 0,
    xf_id: opts[:xf_id] || 0
  }
  entry[:alignment] = opts[:alignment] if opts[:alignment]
  entry[:protection] = opts[:protection] if opts[:protection]
  entry[:quote_prefix] = true if opts[:quote_prefix]
  entry[:pivot_button] = true if opts[:pivot_button]
  existing = @xf_entries.index(entry)
  return existing if existing

  @xf_entries << entry
  @xf_entries.size - 1
end

#add_cell_watch(cell_ref, sheet: nil) ⇒ Object

Adds a cell watch to the given sheet. : (untyped cell_ref, ?sheet: untyped?) -> untyped

Parameters:

  • cell_ref (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1101
1102
1103
1104
1105
1106
# File 'lib/xlsxrb/ooxml/writer.rb', line 1101

def add_cell_watch(cell_ref, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)

  @cell_watches[sheet_name] << cell_ref
end

#add_chart(type: :bar, title: nil, title_overlay: nil, title_font: nil, title_fill_color: nil, title_no_fill: nil, title_line_color: nil, title_line_width: nil, title_line_dash: nil, title_rotation: nil, auto_title_deleted: nil, cat_ref: nil, val_ref: nil, series: nil, legend: nil, data_labels: nil, cat_axis_title: nil, val_axis_title: nil, cat_axis_title_font: nil, cat_axis_title_fill: nil, cat_axis_title_no_fill: nil, cat_axis_title_line_color: nil, cat_axis_title_line_width: nil, cat_axis_title_line_dash: nil, cat_axis_title_rotation: nil, val_axis_title_font: nil, val_axis_title_fill: nil, val_axis_title_no_fill: nil, val_axis_title_line_color: nil, val_axis_title_line_width: nil, val_axis_title_line_dash: nil, val_axis_title_rotation: nil, cat_axis_tick_lbl_pos: nil, val_axis_tick_lbl_pos: nil, cat_axis_major_gridlines: nil, val_axis_major_gridlines: nil, cat_axis_minor_gridlines: nil, val_axis_minor_gridlines: nil, cat_axis_delete: nil, val_axis_delete: nil, cat_axis_orientation: nil, val_axis_orientation: nil, cat_axis_num_fmt: nil, val_axis_num_fmt: nil, cat_axis_major_tick_mark: nil, cat_axis_minor_tick_mark: nil, val_axis_major_tick_mark: nil, val_axis_minor_tick_mark: nil, cat_axis_crosses: nil, val_axis_crosses: nil, cat_axis_crosses_at: nil, val_axis_crosses_at: nil, cat_axis_tick_lbl_skip: nil, cat_axis_tick_mark_skip: nil, cat_axis_lbl_offset: nil, cat_axis_auto: nil, cat_axis_lbl_algn: nil, cat_axis_no_multi_lvl_lbl: nil, val_axis_cross_between: nil, val_axis_major_unit: nil, val_axis_minor_unit: nil, cat_axis_scaling_max: nil, cat_axis_scaling_min: nil, val_axis_scaling_max: nil, val_axis_scaling_min: nil, cat_axis_log_base: nil, val_axis_log_base: nil, val_axis_disp_units: nil, gap_width: nil, gap_depth: nil, overlap: nil, first_slice_ang: nil, hole_size: nil, smooth: nil, marker: nil, scatter_style: nil, radar_style: nil, bar_shape: nil, bubble_3d: nil, bubble_scale: nil, show_neg_bubbles: nil, size_represents: nil, wireframe: nil, grouping: nil, bar_dir: nil, vary_colors: nil, style: nil, rounded_corners: nil, view_3d: nil, cat_axis_pos: nil, val_axis_pos: nil, name: nil, description: nil, frame_title: nil, frame_hidden: nil, frame_macro: nil, frame_no_grp: nil, from_col: 0, from_row: 0, to_col: 10, to_row: 15, from_col_off: nil, from_row_off: nil, to_col_off: nil, to_row_off: nil, edit_as: nil, published: nil, locks_with_sheet: nil, prints_with_sheet: nil, plot_vis_only: nil, disp_blanks_as: nil, show_d_lbls_over_max: nil, data_table: nil, plot_area_fill: nil, plot_area_no_fill: nil, plot_area_line_color: nil, plot_area_line_width: nil, plot_area_line_dash: nil, plot_area_layout: nil, floor: nil, side_wall: nil, back_wall: nil, drop_lines: nil, hi_low_lines: nil, ser_lines: nil, up_down_bars: nil, band_fmts: nil, of_pie_type: nil, split_type: nil, split_pos: nil, cust_split: nil, second_pie_size: nil, cat_axis_label_rotation: nil, val_axis_label_rotation: nil, cat_axis_font: nil, val_axis_font: nil, cat_axis_line_color: nil, cat_axis_line_width: nil, cat_axis_line_dash: nil, val_axis_line_color: nil, val_axis_line_width: nil, val_axis_line_dash: nil, cat_axis_fill: nil, cat_axis_no_fill: nil, val_axis_fill: nil, val_axis_no_fill: nil, cat_axis_type: nil, cat_axis_base_time_unit: nil, cat_axis_major_time_unit: nil, cat_axis_minor_time_unit: nil, cat_axis_major_unit: nil, cat_axis_minor_unit: nil, chart_fill: nil, chart_no_fill: nil, chart_line_color: nil, chart_line_width: nil, chart_line_dash: nil, protection: nil, print_settings: nil, chart_font: nil, sheet: nil) ⇒ Object

Adds a chart to the given sheet. type: :bar, :line, :pie. title: chart title string. data_ref: e.g. "Sheet1!$A$1:$B$4". cat_ref/val_ref for explicit series. : (?type: ::Symbol, ?title: untyped?, ?title_overlay: untyped?, ?title_font: untyped?, ?title_fill_color: untyped?, ?title_no_fill: untyped?, ?title_line_color: untyped?, ?title_line_width: untyped?, ?title_line_dash: untyped?, ?title_rotation: untyped?, ?auto_title_deleted: untyped?, ?cat_ref: untyped?, ?val_ref: untyped?, ?series: untyped?, ?legend: untyped?, ?data_labels: untyped?, ?cat_axis_title: untyped?, ?val_axis_title: untyped?, ?cat_axis_title_font: untyped?, ?cat_axis_title_fill: untyped?, ?cat_axis_title_no_fill: untyped?, ?cat_axis_title_line_color: untyped?, ?cat_axis_title_line_width: untyped?, ?cat_axis_title_line_dash: untyped?, ?cat_axis_title_rotation: untyped?, ?val_axis_title_font: untyped?, ?val_axis_title_fill: untyped?, ?val_axis_title_no_fill: untyped?, ?val_axis_title_line_color: untyped?, ?val_axis_title_line_width: untyped?, ?val_axis_title_line_dash: untyped?, ?val_axis_title_rotation: untyped?, ?cat_axis_tick_lbl_pos: untyped?, ?val_axis_tick_lbl_pos: untyped?, ?cat_axis_major_gridlines: untyped?, ?val_axis_major_gridlines: untyped?, ?cat_axis_minor_gridlines: untyped?, ?val_axis_minor_gridlines: untyped?, ?cat_axis_delete: untyped?, ?val_axis_delete: untyped?, ?cat_axis_orientation: untyped?, ?val_axis_orientation: untyped?, ?cat_axis_num_fmt: untyped?, ?val_axis_num_fmt: untyped?, ?cat_axis_major_tick_mark: untyped?, ?cat_axis_minor_tick_mark: untyped?, ?val_axis_major_tick_mark: untyped?, ?val_axis_minor_tick_mark: untyped?, ?cat_axis_crosses: untyped?, ?val_axis_crosses: untyped?, ?cat_axis_crosses_at: untyped?, ?val_axis_crosses_at: untyped?, ?cat_axis_tick_lbl_skip: untyped?, ?cat_axis_tick_mark_skip: untyped?, ?cat_axis_lbl_offset: untyped?, ?cat_axis_auto: untyped?, ?cat_axis_lbl_algn: untyped?, ?cat_axis_no_multi_lvl_lbl: untyped?, ?val_axis_cross_between: untyped?, ?val_axis_major_unit: untyped?, ?val_axis_minor_unit: untyped?, ?cat_axis_scaling_max: untyped?, ?cat_axis_scaling_min: untyped?, ?val_axis_scaling_max: untyped?, ?val_axis_scaling_min: untyped?, ?cat_axis_log_base: untyped?, ?val_axis_log_base: untyped?, ?val_axis_disp_units: untyped?, ?gap_width: untyped?, ?gap_depth: untyped?, ?overlap: untyped?, ?first_slice_ang: untyped?, ?hole_size: untyped?, ?smooth: untyped?, ?marker: untyped?, ?scatter_style: untyped?, ?radar_style: untyped?, ?bar_shape: untyped?, ?bubble_3d: untyped?, ?bubble_scale: untyped?, ?show_neg_bubbles: untyped?, ?size_represents: untyped?, ?wireframe: untyped?, ?grouping: untyped?, ?bar_dir: untyped?, ?vary_colors: untyped?, ?style: untyped?, ?rounded_corners: untyped?, ?view_3d: untyped?, ?cat_axis_pos: untyped?, ?val_axis_pos: untyped?, ?name: untyped?, ?description: untyped?, ?frame_title: untyped?, ?frame_hidden: untyped?, ?frame_macro: untyped?, ?frame_no_grp: untyped?, ?from_col: ::Integer, ?from_row: ::Integer, ?to_col: ::Integer, ?to_row: ::Integer, ?from_col_off: untyped?, ?from_row_off: untyped?, ?to_col_off: untyped?, ?to_row_off: untyped?, ?edit_as: untyped?, ?published: untyped?, ?locks_with_sheet: untyped?, ?prints_with_sheet: untyped?, ?plot_vis_only: untyped?, ?disp_blanks_as: untyped?, ?show_d_lbls_over_max: untyped?, ?data_table: untyped?, ?plot_area_fill: untyped?, ?plot_area_no_fill: untyped?, ?plot_area_line_color: untyped?, ?plot_area_line_width: untyped?, ?plot_area_line_dash: untyped?, ?plot_area_layout: untyped?, ?floor: untyped?, ?side_wall: untyped?, ?back_wall: untyped?, ?drop_lines: untyped?, ?hi_low_lines: untyped?, ?ser_lines: untyped?, ?up_down_bars: untyped?, ?band_fmts: untyped?, ?of_pie_type: untyped?, ?split_type: untyped?, ?split_pos: untyped?, ?cust_split: untyped?, ?second_pie_size: untyped?, ?cat_axis_label_rotation: untyped?, ?val_axis_label_rotation: untyped?, ?cat_axis_font: untyped?, ?val_axis_font: untyped?, ?cat_axis_line_color: untyped?, ?cat_axis_line_width: untyped?, ?cat_axis_line_dash: untyped?, ?val_axis_line_color: untyped?, ?val_axis_line_width: untyped?, ?val_axis_line_dash: untyped?, ?cat_axis_fill: untyped?, ?cat_axis_no_fill: untyped?, ?val_axis_fill: untyped?, ?val_axis_no_fill: untyped?, ?cat_axis_type: untyped?, ?cat_axis_base_time_unit: untyped?, ?cat_axis_major_time_unit: untyped?, ?cat_axis_minor_time_unit: untyped?, ?cat_axis_major_unit: untyped?, ?cat_axis_minor_unit: untyped?, ?chart_fill: untyped?, ?chart_no_fill: untyped?, ?chart_line_color: untyped?, ?chart_line_width: untyped?, ?chart_line_dash: untyped?, ?protection: untyped?, ?print_settings: untyped?, ?chart_font: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • type: (Object) (defaults to: :bar)
  • title: (Object) (defaults to: nil)
  • title_overlay: (Object) (defaults to: nil)
  • title_font: (Object) (defaults to: nil)
  • title_fill_color: (Object) (defaults to: nil)
  • title_no_fill: (Object) (defaults to: nil)
  • title_line_color: (Object) (defaults to: nil)
  • title_line_width: (Object) (defaults to: nil)
  • title_line_dash: (Object) (defaults to: nil)
  • title_rotation: (Object) (defaults to: nil)
  • auto_title_deleted: (Object) (defaults to: nil)
  • cat_ref: (Object) (defaults to: nil)
  • val_ref: (Object) (defaults to: nil)
  • series: (Object) (defaults to: nil)
  • legend: (Object) (defaults to: nil)
  • data_labels: (Object) (defaults to: nil)
  • cat_axis_title: (Object) (defaults to: nil)
  • val_axis_title: (Object) (defaults to: nil)
  • cat_axis_title_font: (Object) (defaults to: nil)
  • cat_axis_title_fill: (Object) (defaults to: nil)
  • cat_axis_title_no_fill: (Object) (defaults to: nil)
  • cat_axis_title_line_color: (Object) (defaults to: nil)
  • cat_axis_title_line_width: (Object) (defaults to: nil)
  • cat_axis_title_line_dash: (Object) (defaults to: nil)
  • cat_axis_title_rotation: (Object) (defaults to: nil)
  • val_axis_title_font: (Object) (defaults to: nil)
  • val_axis_title_fill: (Object) (defaults to: nil)
  • val_axis_title_no_fill: (Object) (defaults to: nil)
  • val_axis_title_line_color: (Object) (defaults to: nil)
  • val_axis_title_line_width: (Object) (defaults to: nil)
  • val_axis_title_line_dash: (Object) (defaults to: nil)
  • val_axis_title_rotation: (Object) (defaults to: nil)
  • cat_axis_tick_lbl_pos: (Object) (defaults to: nil)
  • val_axis_tick_lbl_pos: (Object) (defaults to: nil)
  • cat_axis_major_gridlines: (Object) (defaults to: nil)
  • val_axis_major_gridlines: (Object) (defaults to: nil)
  • cat_axis_minor_gridlines: (Object) (defaults to: nil)
  • val_axis_minor_gridlines: (Object) (defaults to: nil)
  • cat_axis_delete: (Object) (defaults to: nil)
  • val_axis_delete: (Object) (defaults to: nil)
  • cat_axis_orientation: (Object) (defaults to: nil)
  • val_axis_orientation: (Object) (defaults to: nil)
  • cat_axis_num_fmt: (Object) (defaults to: nil)
  • val_axis_num_fmt: (Object) (defaults to: nil)
  • cat_axis_major_tick_mark: (Object) (defaults to: nil)
  • cat_axis_minor_tick_mark: (Object) (defaults to: nil)
  • val_axis_major_tick_mark: (Object) (defaults to: nil)
  • val_axis_minor_tick_mark: (Object) (defaults to: nil)
  • cat_axis_crosses: (Object) (defaults to: nil)
  • val_axis_crosses: (Object) (defaults to: nil)
  • cat_axis_crosses_at: (Object) (defaults to: nil)
  • val_axis_crosses_at: (Object) (defaults to: nil)
  • cat_axis_tick_lbl_skip: (Object) (defaults to: nil)
  • cat_axis_tick_mark_skip: (Object) (defaults to: nil)
  • cat_axis_lbl_offset: (Object) (defaults to: nil)
  • cat_axis_auto: (Object) (defaults to: nil)
  • cat_axis_lbl_algn: (Object) (defaults to: nil)
  • cat_axis_no_multi_lvl_lbl: (Object) (defaults to: nil)
  • val_axis_cross_between: (Object) (defaults to: nil)
  • val_axis_major_unit: (Object) (defaults to: nil)
  • val_axis_minor_unit: (Object) (defaults to: nil)
  • cat_axis_scaling_max: (Object) (defaults to: nil)
  • cat_axis_scaling_min: (Object) (defaults to: nil)
  • val_axis_scaling_max: (Object) (defaults to: nil)
  • val_axis_scaling_min: (Object) (defaults to: nil)
  • cat_axis_log_base: (Object) (defaults to: nil)
  • val_axis_log_base: (Object) (defaults to: nil)
  • val_axis_disp_units: (Object) (defaults to: nil)
  • gap_width: (Object) (defaults to: nil)
  • gap_depth: (Object) (defaults to: nil)
  • overlap: (Object) (defaults to: nil)
  • first_slice_ang: (Object) (defaults to: nil)
  • hole_size: (Object) (defaults to: nil)
  • smooth: (Object) (defaults to: nil)
  • marker: (Object) (defaults to: nil)
  • scatter_style: (Object) (defaults to: nil)
  • radar_style: (Object) (defaults to: nil)
  • bar_shape: (Object) (defaults to: nil)
  • bubble_3d: (Object) (defaults to: nil)
  • bubble_scale: (Object) (defaults to: nil)
  • show_neg_bubbles: (Object) (defaults to: nil)
  • size_represents: (Object) (defaults to: nil)
  • wireframe: (Object) (defaults to: nil)
  • grouping: (Object) (defaults to: nil)
  • bar_dir: (Object) (defaults to: nil)
  • vary_colors: (Object) (defaults to: nil)
  • style: (Object) (defaults to: nil)
  • rounded_corners: (Object) (defaults to: nil)
  • view_3d: (Object) (defaults to: nil)
  • cat_axis_pos: (Object) (defaults to: nil)
  • val_axis_pos: (Object) (defaults to: nil)
  • name: (Object) (defaults to: nil)
  • description: (Object) (defaults to: nil)
  • frame_title: (Object) (defaults to: nil)
  • frame_hidden: (Object) (defaults to: nil)
  • frame_macro: (Object) (defaults to: nil)
  • frame_no_grp: (Object) (defaults to: nil)
  • from_col: (Object) (defaults to: 0)
  • from_row: (Object) (defaults to: 0)
  • to_col: (Object) (defaults to: 10)
  • to_row: (Object) (defaults to: 15)
  • from_col_off: (Object) (defaults to: nil)
  • from_row_off: (Object) (defaults to: nil)
  • to_col_off: (Object) (defaults to: nil)
  • to_row_off: (Object) (defaults to: nil)
  • edit_as: (Object) (defaults to: nil)
  • published: (Object) (defaults to: nil)
  • locks_with_sheet: (Object) (defaults to: nil)
  • prints_with_sheet: (Object) (defaults to: nil)
  • plot_vis_only: (Object) (defaults to: nil)
  • disp_blanks_as: (Object) (defaults to: nil)
  • show_d_lbls_over_max: (Object) (defaults to: nil)
  • data_table: (Object) (defaults to: nil)
  • plot_area_fill: (Object) (defaults to: nil)
  • plot_area_no_fill: (Object) (defaults to: nil)
  • plot_area_line_color: (Object) (defaults to: nil)
  • plot_area_line_width: (Object) (defaults to: nil)
  • plot_area_line_dash: (Object) (defaults to: nil)
  • plot_area_layout: (Object) (defaults to: nil)
  • floor: (Object) (defaults to: nil)
  • side_wall: (Object) (defaults to: nil)
  • back_wall: (Object) (defaults to: nil)
  • drop_lines: (Object) (defaults to: nil)
  • hi_low_lines: (Object) (defaults to: nil)
  • ser_lines: (Object) (defaults to: nil)
  • up_down_bars: (Object) (defaults to: nil)
  • band_fmts: (Object) (defaults to: nil)
  • of_pie_type: (Object) (defaults to: nil)
  • split_type: (Object) (defaults to: nil)
  • split_pos: (Object) (defaults to: nil)
  • cust_split: (Object) (defaults to: nil)
  • second_pie_size: (Object) (defaults to: nil)
  • cat_axis_label_rotation: (Object) (defaults to: nil)
  • val_axis_label_rotation: (Object) (defaults to: nil)
  • cat_axis_font: (Object) (defaults to: nil)
  • val_axis_font: (Object) (defaults to: nil)
  • cat_axis_line_color: (Object) (defaults to: nil)
  • cat_axis_line_width: (Object) (defaults to: nil)
  • cat_axis_line_dash: (Object) (defaults to: nil)
  • val_axis_line_color: (Object) (defaults to: nil)
  • val_axis_line_width: (Object) (defaults to: nil)
  • val_axis_line_dash: (Object) (defaults to: nil)
  • cat_axis_fill: (Object) (defaults to: nil)
  • cat_axis_no_fill: (Object) (defaults to: nil)
  • val_axis_fill: (Object) (defaults to: nil)
  • val_axis_no_fill: (Object) (defaults to: nil)
  • cat_axis_type: (Object) (defaults to: nil)
  • cat_axis_base_time_unit: (Object) (defaults to: nil)
  • cat_axis_major_time_unit: (Object) (defaults to: nil)
  • cat_axis_minor_time_unit: (Object) (defaults to: nil)
  • cat_axis_major_unit: (Object) (defaults to: nil)
  • cat_axis_minor_unit: (Object) (defaults to: nil)
  • chart_fill: (Object) (defaults to: nil)
  • chart_no_fill: (Object) (defaults to: nil)
  • chart_line_color: (Object) (defaults to: nil)
  • chart_line_width: (Object) (defaults to: nil)
  • chart_line_dash: (Object) (defaults to: nil)
  • protection: (Object) (defaults to: nil)
  • print_settings: (Object) (defaults to: nil)
  • chart_font: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
# File 'lib/xlsxrb/ooxml/writer.rb', line 1260

def add_chart(type: :bar, title: nil, title_overlay: nil, title_font: nil, title_fill_color: nil, title_no_fill: nil, title_line_color: nil, title_line_width: nil, title_line_dash: nil, title_rotation: nil, auto_title_deleted: nil, cat_ref: nil, val_ref: nil, series: nil, legend: nil, data_labels: nil, cat_axis_title: nil, val_axis_title: nil, cat_axis_title_font: nil, cat_axis_title_fill: nil, cat_axis_title_no_fill: nil, cat_axis_title_line_color: nil, cat_axis_title_line_width: nil, cat_axis_title_line_dash: nil, cat_axis_title_rotation: nil, val_axis_title_font: nil, val_axis_title_fill: nil, val_axis_title_no_fill: nil, val_axis_title_line_color: nil, val_axis_title_line_width: nil, val_axis_title_line_dash: nil, val_axis_title_rotation: nil, cat_axis_tick_lbl_pos: nil, val_axis_tick_lbl_pos: nil, cat_axis_major_gridlines: nil, val_axis_major_gridlines: nil, cat_axis_minor_gridlines: nil, val_axis_minor_gridlines: nil, cat_axis_delete: nil, val_axis_delete: nil, cat_axis_orientation: nil, val_axis_orientation: nil, cat_axis_num_fmt: nil, val_axis_num_fmt: nil, cat_axis_major_tick_mark: nil, cat_axis_minor_tick_mark: nil, val_axis_major_tick_mark: nil, val_axis_minor_tick_mark: nil, cat_axis_crosses: nil, val_axis_crosses: nil, cat_axis_crosses_at: nil, val_axis_crosses_at: nil, cat_axis_tick_lbl_skip: nil, cat_axis_tick_mark_skip: nil, cat_axis_lbl_offset: nil, cat_axis_auto: nil, cat_axis_lbl_algn: nil, cat_axis_no_multi_lvl_lbl: nil, val_axis_cross_between: nil, val_axis_major_unit: nil, val_axis_minor_unit: nil, cat_axis_scaling_max: nil, cat_axis_scaling_min: nil, val_axis_scaling_max: nil, val_axis_scaling_min: nil, cat_axis_log_base: nil, val_axis_log_base: nil, val_axis_disp_units: nil, gap_width: nil, gap_depth: nil, overlap: nil, first_slice_ang: nil, hole_size: nil, smooth: nil, marker: nil, scatter_style: nil, radar_style: nil, bar_shape: nil, bubble_3d: nil, bubble_scale: nil, show_neg_bubbles: nil, size_represents: nil, wireframe: nil, grouping: nil, bar_dir: nil, vary_colors: nil, style: nil, rounded_corners: nil, view_3d: nil, cat_axis_pos: nil, val_axis_pos: nil, name: nil, description: nil, frame_title: nil, frame_hidden: nil, frame_macro: nil, frame_no_grp: nil, from_col: 0, from_row: 0, to_col: 10, to_row: 15, from_col_off: nil, from_row_off: nil, to_col_off: nil, to_row_off: nil, edit_as: nil, published: nil, locks_with_sheet: nil, prints_with_sheet: nil, plot_vis_only: nil, disp_blanks_as: nil, show_d_lbls_over_max: nil, data_table: nil, plot_area_fill: nil, plot_area_no_fill: nil, plot_area_line_color: nil, plot_area_line_width: nil, plot_area_line_dash: nil, plot_area_layout: nil, floor: nil, side_wall: nil, back_wall: nil, drop_lines: nil, hi_low_lines: nil, ser_lines: nil, up_down_bars: nil, band_fmts: nil, of_pie_type: nil, split_type: nil, split_pos: nil, cust_split: nil, second_pie_size: nil, cat_axis_label_rotation: nil, val_axis_label_rotation: nil, cat_axis_font: nil, val_axis_font: nil, cat_axis_line_color: nil, cat_axis_line_width: nil, cat_axis_line_dash: nil, val_axis_line_color: nil, val_axis_line_width: nil, val_axis_line_dash: nil, cat_axis_fill: nil, cat_axis_no_fill: nil, val_axis_fill: nil, val_axis_no_fill: nil, cat_axis_type: nil, cat_axis_base_time_unit: nil, cat_axis_major_time_unit: nil, cat_axis_minor_time_unit: nil, cat_axis_major_unit: nil, cat_axis_minor_unit: nil, chart_fill: nil, chart_no_fill: nil, chart_line_color: nil, chart_line_width: nil, chart_line_dash: nil, protection: nil, print_settings: nil, chart_font: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @charts_data.key?(sheet_name)

  chart = { type: type, title: title,
            from_col: from_col, from_row: from_row,
            to_col: to_col, to_row: to_row }
  chart[:from_col_off] = from_col_off if from_col_off
  chart[:from_row_off] = from_row_off if from_row_off
  chart[:to_col_off] = to_col_off if to_col_off
  chart[:to_row_off] = to_row_off if to_row_off
  chart[:series] = (series || [{ cat_ref: cat_ref, val_ref: val_ref }])
  chart[:auto_title_deleted] = auto_title_deleted unless auto_title_deleted.nil?
  chart[:title_overlay] = title_overlay unless title_overlay.nil?
  chart[:title_font] = title_font if title_font
  chart[:title_fill_color] = title_fill_color if title_fill_color
  chart[:title_no_fill] = title_no_fill unless title_no_fill.nil?
  chart[:title_line_color] = title_line_color if title_line_color
  chart[:title_line_width] = title_line_width if title_line_width
  chart[:title_line_dash] = title_line_dash if title_line_dash
  chart[:title_rotation] = title_rotation if title_rotation
  chart[:legend] = legend if legend
  chart[:data_labels] = data_labels if data_labels
  chart[:cat_axis_title] = cat_axis_title if cat_axis_title
  chart[:val_axis_title] = val_axis_title if val_axis_title
  chart[:cat_axis_title_font] = cat_axis_title_font if cat_axis_title_font
  chart[:cat_axis_title_fill] = cat_axis_title_fill if cat_axis_title_fill
  chart[:cat_axis_title_no_fill] = cat_axis_title_no_fill unless cat_axis_title_no_fill.nil?
  chart[:cat_axis_title_line_color] = cat_axis_title_line_color if cat_axis_title_line_color
  chart[:cat_axis_title_line_width] = cat_axis_title_line_width if cat_axis_title_line_width
  chart[:cat_axis_title_line_dash] = cat_axis_title_line_dash if cat_axis_title_line_dash
  chart[:cat_axis_title_rotation] = cat_axis_title_rotation if cat_axis_title_rotation
  chart[:val_axis_title_font] = val_axis_title_font if val_axis_title_font
  chart[:val_axis_title_fill] = val_axis_title_fill if val_axis_title_fill
  chart[:val_axis_title_no_fill] = val_axis_title_no_fill unless val_axis_title_no_fill.nil?
  chart[:val_axis_title_line_color] = val_axis_title_line_color if val_axis_title_line_color
  chart[:val_axis_title_line_width] = val_axis_title_line_width if val_axis_title_line_width
  chart[:val_axis_title_line_dash] = val_axis_title_line_dash if val_axis_title_line_dash
  chart[:val_axis_title_rotation] = val_axis_title_rotation if val_axis_title_rotation
  chart[:cat_axis_tick_lbl_pos] = cat_axis_tick_lbl_pos if cat_axis_tick_lbl_pos
  chart[:val_axis_tick_lbl_pos] = val_axis_tick_lbl_pos if val_axis_tick_lbl_pos
  chart[:cat_axis_major_gridlines] = cat_axis_major_gridlines unless cat_axis_major_gridlines.nil?
  chart[:val_axis_major_gridlines] = val_axis_major_gridlines unless val_axis_major_gridlines.nil?
  chart[:cat_axis_minor_gridlines] = cat_axis_minor_gridlines unless cat_axis_minor_gridlines.nil?
  chart[:val_axis_minor_gridlines] = val_axis_minor_gridlines unless val_axis_minor_gridlines.nil?
  chart[:cat_axis_delete] = cat_axis_delete unless cat_axis_delete.nil?
  chart[:val_axis_delete] = val_axis_delete unless val_axis_delete.nil?
  chart[:cat_axis_orientation] = cat_axis_orientation if cat_axis_orientation
  chart[:val_axis_orientation] = val_axis_orientation if val_axis_orientation
  chart[:cat_axis_num_fmt] = cat_axis_num_fmt if cat_axis_num_fmt
  chart[:val_axis_num_fmt] = val_axis_num_fmt if val_axis_num_fmt
  chart[:cat_axis_major_tick_mark] = cat_axis_major_tick_mark if cat_axis_major_tick_mark
  chart[:cat_axis_minor_tick_mark] = cat_axis_minor_tick_mark if cat_axis_minor_tick_mark
  chart[:val_axis_major_tick_mark] = val_axis_major_tick_mark if val_axis_major_tick_mark
  chart[:val_axis_minor_tick_mark] = val_axis_minor_tick_mark if val_axis_minor_tick_mark
  chart[:cat_axis_crosses] = cat_axis_crosses if cat_axis_crosses
  chart[:val_axis_crosses] = val_axis_crosses if val_axis_crosses
  chart[:cat_axis_crosses_at] = cat_axis_crosses_at if cat_axis_crosses_at
  chart[:val_axis_crosses_at] = val_axis_crosses_at if val_axis_crosses_at
  chart[:cat_axis_tick_lbl_skip] = cat_axis_tick_lbl_skip if cat_axis_tick_lbl_skip
  chart[:cat_axis_tick_mark_skip] = cat_axis_tick_mark_skip if cat_axis_tick_mark_skip
  chart[:cat_axis_lbl_offset] = cat_axis_lbl_offset if cat_axis_lbl_offset
  chart[:cat_axis_auto] = cat_axis_auto unless cat_axis_auto.nil?
  chart[:cat_axis_lbl_algn] = cat_axis_lbl_algn if cat_axis_lbl_algn
  chart[:cat_axis_no_multi_lvl_lbl] = cat_axis_no_multi_lvl_lbl unless cat_axis_no_multi_lvl_lbl.nil?
  chart[:val_axis_cross_between] = val_axis_cross_between if val_axis_cross_between
  chart[:val_axis_major_unit] = val_axis_major_unit if val_axis_major_unit
  chart[:val_axis_minor_unit] = val_axis_minor_unit if val_axis_minor_unit
  chart[:cat_axis_scaling_max] = cat_axis_scaling_max if cat_axis_scaling_max
  chart[:cat_axis_scaling_min] = cat_axis_scaling_min if cat_axis_scaling_min
  chart[:val_axis_scaling_max] = val_axis_scaling_max if val_axis_scaling_max
  chart[:val_axis_scaling_min] = val_axis_scaling_min if val_axis_scaling_min
  chart[:cat_axis_log_base] = cat_axis_log_base if cat_axis_log_base
  chart[:val_axis_log_base] = val_axis_log_base if val_axis_log_base
  chart[:val_axis_disp_units] = val_axis_disp_units if val_axis_disp_units
  chart[:first_slice_ang] = first_slice_ang if first_slice_ang
  chart[:hole_size] = hole_size if hole_size
  chart[:smooth] = smooth unless smooth.nil?
  chart[:marker] = marker unless marker.nil?
  chart[:scatter_style] = scatter_style if scatter_style
  chart[:radar_style] = radar_style if radar_style
  chart[:cat_axis_pos] = cat_axis_pos if cat_axis_pos
  chart[:val_axis_pos] = val_axis_pos if val_axis_pos
  chart[:gap_width] = gap_width if gap_width
  chart[:gap_depth] = gap_depth if gap_depth
  chart[:bar_shape] = bar_shape if bar_shape
  chart[:bubble_3d] = bubble_3d unless bubble_3d.nil?
  chart[:bubble_scale] = bubble_scale if bubble_scale
  chart[:show_neg_bubbles] = show_neg_bubbles unless show_neg_bubbles.nil?
  chart[:size_represents] = size_represents if size_represents
  chart[:overlap] = overlap if overlap
  chart[:grouping] = grouping if grouping
  chart[:bar_dir] = bar_dir if bar_dir
  chart[:vary_colors] = vary_colors unless vary_colors.nil?
  chart[:wireframe] = wireframe unless wireframe.nil?
  chart[:band_fmts] = band_fmts if band_fmts
  chart[:of_pie_type] = of_pie_type if of_pie_type
  chart[:split_type] = split_type if split_type
  chart[:split_pos] = split_pos if split_pos
  chart[:cust_split] = cust_split if cust_split
  chart[:second_pie_size] = second_pie_size if second_pie_size
  chart[:style] = style if style
  chart[:rounded_corners] = rounded_corners unless rounded_corners.nil?
  chart[:view_3d] = view_3d if view_3d
  chart[:floor] = floor if floor
  chart[:side_wall] = side_wall if side_wall
  chart[:back_wall] = back_wall if back_wall
  chart[:name] = name if name
  chart[:description] = description if description
  chart[:frame_title] = frame_title if frame_title
  chart[:frame_hidden] = frame_hidden unless frame_hidden.nil?
  chart[:frame_macro] = frame_macro if frame_macro
  chart[:frame_no_grp] = frame_no_grp unless frame_no_grp.nil?
  chart[:edit_as] = edit_as if edit_as
  chart[:published] = published unless published.nil?
  chart[:locks_with_sheet] = locks_with_sheet unless locks_with_sheet.nil?
  chart[:prints_with_sheet] = prints_with_sheet unless prints_with_sheet.nil?
  chart[:plot_vis_only] = plot_vis_only unless plot_vis_only.nil?
  chart[:disp_blanks_as] = disp_blanks_as if disp_blanks_as
  chart[:show_d_lbls_over_max] = show_d_lbls_over_max unless show_d_lbls_over_max.nil?
  chart[:data_table] = data_table if data_table
  chart[:plot_area_fill] = plot_area_fill if plot_area_fill
  chart[:plot_area_no_fill] = plot_area_no_fill unless plot_area_no_fill.nil?
  chart[:plot_area_line_color] = plot_area_line_color if plot_area_line_color
  chart[:plot_area_line_width] = plot_area_line_width if plot_area_line_width
  chart[:plot_area_line_dash] = plot_area_line_dash if plot_area_line_dash
  chart[:plot_area_layout] = plot_area_layout if plot_area_layout
  chart[:drop_lines] = drop_lines unless drop_lines.nil?
  chart[:hi_low_lines] = hi_low_lines unless hi_low_lines.nil?
  chart[:ser_lines] = ser_lines unless ser_lines.nil?
  chart[:up_down_bars] = up_down_bars if up_down_bars
  chart[:cat_axis_label_rotation] = cat_axis_label_rotation if cat_axis_label_rotation
  chart[:val_axis_label_rotation] = val_axis_label_rotation if val_axis_label_rotation
  chart[:cat_axis_font] = cat_axis_font if cat_axis_font
  chart[:val_axis_font] = val_axis_font if val_axis_font
  chart[:cat_axis_line_color] = cat_axis_line_color if cat_axis_line_color
  chart[:cat_axis_line_width] = cat_axis_line_width if cat_axis_line_width
  chart[:cat_axis_line_dash] = cat_axis_line_dash if cat_axis_line_dash
  chart[:val_axis_line_color] = val_axis_line_color if val_axis_line_color
  chart[:val_axis_line_width] = val_axis_line_width if val_axis_line_width
  chart[:val_axis_line_dash] = val_axis_line_dash if val_axis_line_dash
  chart[:cat_axis_fill] = cat_axis_fill if cat_axis_fill
  chart[:cat_axis_no_fill] = cat_axis_no_fill unless cat_axis_no_fill.nil?
  chart[:val_axis_fill] = val_axis_fill if val_axis_fill
  chart[:val_axis_no_fill] = val_axis_no_fill unless val_axis_no_fill.nil?
  chart[:cat_axis_type] = cat_axis_type if cat_axis_type
  chart[:cat_axis_base_time_unit] = cat_axis_base_time_unit if cat_axis_base_time_unit
  chart[:cat_axis_major_time_unit] = cat_axis_major_time_unit if cat_axis_major_time_unit
  chart[:cat_axis_minor_time_unit] = cat_axis_minor_time_unit if cat_axis_minor_time_unit
  chart[:cat_axis_major_unit] = cat_axis_major_unit if cat_axis_major_unit
  chart[:cat_axis_minor_unit] = cat_axis_minor_unit if cat_axis_minor_unit
  chart[:chart_fill] = chart_fill if chart_fill
  chart[:chart_no_fill] = chart_no_fill unless chart_no_fill.nil?
  chart[:chart_line_color] = chart_line_color if chart_line_color
  chart[:chart_line_width] = chart_line_width if chart_line_width
  chart[:chart_line_dash] = chart_line_dash if chart_line_dash
  chart[:protection] = protection if protection
  chart[:print_settings] = print_settings if print_settings
  chart[:chart_font] = chart_font if chart_font
  @charts_data[sheet_name] << chart
end

#add_col_break(col_index, sheet: nil) ⇒ Object

Adds a column break (page break before a given column index, 1-based). : (untyped col_index, ?sheet: untyped?) -> untyped

Parameters:

  • col_index (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


820
821
822
823
824
825
# File 'lib/xlsxrb/ooxml/writer.rb', line 820

def add_col_break(col_index, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @col_breaks.key?(sheet_name)

  @col_breaks[sheet_name] << col_index
end

#add_comment(cell_address, text, author: "Author", sheet: nil, guid: nil, shape_id: nil) ⇒ Object

Adds a comment on a cell. : (untyped cell_address, untyped text, ?author: ::String, ?sheet: untyped?, ?guid: untyped?, ?shape_id: untyped?) -> untyped

Parameters:

  • cell_address (Object)
  • text (Object)
  • author: (Object) (defaults to: "Author")
  • sheet: (Object) (defaults to: nil)
  • guid: (Object) (defaults to: nil)
  • shape_id: (Object) (defaults to: nil)

Returns:

  • (Object)


1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
# File 'lib/xlsxrb/ooxml/writer.rb', line 1534

def add_comment(cell_address, text, author: "Author", sheet: nil, guid: nil, shape_id: nil)
  validate_cell_address!(cell_address)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @comments_data.key?(sheet_name)

  entry = { ref: cell_address, text: text, author: author }
  entry[:guid] = guid if guid
  entry[:shape_id] = shape_id if shape_id
  @comments_data[sheet_name] << entry
end

#add_conditional_format(sqref, sheet: nil, **opts) ⇒ Object

Adds a conditional formatting rule to the specified range. Options: type (:cell_is, :expression, :color_scale, :data_bar, :icon_set), operator, priority, formula/formulas, format_id, color_scale, data_bar, icon_set. : (untyped sqref, ?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sqref (Object)
  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


866
867
868
869
870
871
# File 'lib/xlsxrb/ooxml/writer.rb', line 866

def add_conditional_format(sqref, sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @conditional_formats.key?(sheet_name)

  @conditional_formats[sheet_name] << opts.merge(sqref: sqref)
end

#add_data_validation(sqref, sheet: nil, **opts) ⇒ Object

Adds a data validation rule. sqref: cell range (e.g. "A1:A100") Options: type:, operator:, formula1:, formula2:, allow_blank:, show_input_message:, show_error_message:, error_style:, error_title:, error:, prompt_title:, prompt: : (untyped sqref, ?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sqref (Object)
  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


839
840
841
842
843
844
# File 'lib/xlsxrb/ooxml/writer.rb', line 839

def add_data_validation(sqref, sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @data_validations.key?(sheet_name)

  @data_validations[sheet_name] << opts.merge(sqref: sqref)
end

#add_defined_name(name, value, sheet: nil, hidden: false, **opts) ⇒ Object

Adds a defined name. Options: sheet: (local scope), hidden: true, value: (formula or constant). : (untyped name, untyped value, ?sheet: untyped?, ?hidden: bool, **untyped opts) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)
  • hidden: (Object) (defaults to: false)
  • opts (Object)

Returns:

  • (Object)


934
935
936
937
938
939
940
941
942
943
944
945
946
947
# File 'lib/xlsxrb/ooxml/writer.rb', line 934

def add_defined_name(name, value, sheet: nil, hidden: false, **opts)
  entry = { name: name, value: value, hidden: hidden }
  %i[comment description function vb_procedure xlm shortcut_key publish_to_server workbook_parameter
     function_group_id custom_menu help status_bar].each do |key|
    entry[key] = opts[key] if opts.key?(key)
  end
  if sheet
    idx = @sheet_order.index(sheet)
    raise ArgumentError, "unknown sheet: #{sheet}" unless idx

    entry[:local_sheet_id] = idx
  end
  @defined_names << entry
end

#add_dxf(**opts) ⇒ Object

Registers a differential format (dxf) for conditional formatting. Returns dxf_id. Opts: font (hash), fill (hash), border (hash), num_fmt (hash). : (**untyped opts) -> untyped

Parameters:

  • opts (Object)

Returns:

  • (Object)


519
520
521
522
# File 'lib/xlsxrb/ooxml/writer.rb', line 519

def add_dxf(**opts)
  @dxfs << opts
  @dxfs.size - 1
end

Adds an external link reference to another workbook. target: path or URI to the external workbook (e.g. "Book2.xlsx"). sheet_names: array of sheet name strings in the external workbook. : (target: untyped, ?sheet_names: untyped) -> untyped

Parameters:

  • target: (Object)
  • sheet_names: (Object) (defaults to: [])

Returns:

  • (Object)


1624
1625
1626
# File 'lib/xlsxrb/ooxml/writer.rb', line 1624

def add_external_link(target:, sheet_names: [])
  @external_links << { target: target, sheet_names: sheet_names }
end

#add_fill(**opts) ⇒ Object

Registers a fill and returns its fill_id. Opts: pattern, fg_color, bg_color. : (**untyped opts) -> untyped

Parameters:

  • opts (Object)

Returns:

  • (Object)


438
439
440
441
442
443
444
# File 'lib/xlsxrb/ooxml/writer.rb', line 438

def add_fill(**opts)
  existing = @fills.index(opts)
  return existing if existing

  @fills << opts
  @fills.size - 1
end

#add_filter_column(col_id, filter, sheet: nil) ⇒ Object

Adds a filter column to the autoFilter. col_id: 0-based column index within the autoFilter range. filter: hash describing the filter, e.g. { type: :filters, values: ["A", "B"] } { type: :filters, blank: true } { type: :custom, operator: "greaterThan", val: "100" } { type: :custom, filters: [{ operator: "greaterThan", val: "10" }, { operator: "lessThan", val: "100" }], and: true } { type: :dynamic, dynamic_type: "today" } { type: :top10, top: true, percent: false, val: 10 } : (untyped col_id, untyped filter, ?sheet: untyped?) -> untyped

Parameters:

  • col_id (Object)
  • filter (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


370
371
372
373
374
375
# File 'lib/xlsxrb/ooxml/writer.rb', line 370

def add_filter_column(col_id, filter, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @filter_columns.key?(sheet_name)

  @filter_columns[sheet_name][col_id] = filter
end

#add_font(**opts) ⇒ Object

Registers a font and returns its font_id. Opts: bold, italic, sz, color, name. : (**untyped opts) -> untyped

Parameters:

  • opts (Object)

Returns:

  • (Object)


428
429
430
431
432
433
434
# File 'lib/xlsxrb/ooxml/writer.rb', line 428

def add_font(**opts)
  existing = @fonts.index(opts)
  return existing if existing

  @fonts << opts
  @fonts.size - 1
end

#add_ignored_error(sheet: nil, **opts) ⇒ Object

Adds an ignored error entry for the given sheet. Options: sqref:, eval_error:, two_digit_text_year:, number_stored_as_text:, formula:, formula_range:, unlocked_formula:, empty_cell_reference:, list_data_validation:, calculated_column: : (?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


1119
1120
1121
1122
1123
1124
1125
# File 'lib/xlsxrb/ooxml/writer.rb', line 1119

def add_ignored_error(sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)
  raise ArgumentError, "sqref is required" unless opts[:sqref]

  @ignored_errors[sheet_name] << opts
end

#add_named_cell_style(name:, num_fmt_id: 0, font_id: 0, fill_id: 0, border_id: 0, builtin_id: nil, i_level: nil, hidden: nil, custom_builtin: nil) ⇒ Object

Registers a base style definition (cellStyleXf) and a named cellStyle. Returns the xfId for the new base style. : (name: untyped, ?num_fmt_id: ::Integer, ?font_id: ::Integer, ?fill_id: ::Integer, ?border_id: ::Integer, ?builtin_id: untyped?, ?i_level: untyped?, ?hidden: untyped?, ?custom_builtin: untyped?) -> untyped

Parameters:

  • name: (Object)
  • num_fmt_id: (Object) (defaults to: 0)
  • font_id: (Object) (defaults to: 0)
  • fill_id: (Object) (defaults to: 0)
  • border_id: (Object) (defaults to: 0)
  • builtin_id: (Object) (defaults to: nil)
  • i_level: (Object) (defaults to: nil)
  • hidden: (Object) (defaults to: nil)
  • custom_builtin: (Object) (defaults to: nil)

Returns:

  • (Object)


482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/xlsxrb/ooxml/writer.rb', line 482

def add_named_cell_style(name:, num_fmt_id: 0, font_id: 0, fill_id: 0, border_id: 0, builtin_id: nil,
                         i_level: nil, hidden: nil, custom_builtin: nil)
  entry = { num_fmt_id: num_fmt_id, font_id: font_id, fill_id: fill_id, border_id: border_id }
  @cell_style_xfs << entry
  xf_id = @cell_style_xfs.size - 1
  cs = { name: name, xf_id: xf_id }
  cs[:builtin_id] = builtin_id if builtin_id
  cs[:i_level] = i_level if i_level
  cs[:hidden] = true if hidden
  cs[:custom_builtin] = true if custom_builtin
  @cell_style_names << cs
  xf_id
end

#add_number_format(format_code) ⇒ Object

Registers a custom number format and returns its numFmtId (starting at 164). : (untyped format_code) -> untyped

Parameters:

  • format_code (Object)

Returns:

  • (Object)


407
408
409
410
411
412
413
414
# File 'lib/xlsxrb/ooxml/writer.rb', line 407

def add_number_format(format_code)
  existing = @num_fmts.find { |nf| nf[:format_code] == format_code }
  return existing[:num_fmt_id] if existing

  num_fmt_id = 164 + @num_fmts.size
  @num_fmts << { num_fmt_id: num_fmt_id, format_code: format_code }
  num_fmt_id
end

#add_pivot_table(source_ref, row_fields:, data_fields:, col_fields: [], dest_ref: "E1", name: nil, field_names: nil, items: nil, sheet: nil, **opts) ⇒ Object

Adds a pivot table to the given sheet. source_ref: data source range (e.g. "Sheet1!A1:C4"). row_fields: array of 0-based field indices for row axis. data_fields: array of { fld:, name:, subtotal: } hashes. col_fields: array of 0-based field indices for column axis. field_names: array of field name strings (for cache definition). items: hash mapping field index to array of item values. : (untyped source_ref, row_fields: untyped, data_fields: untyped, ?col_fields: untyped, ?dest_ref: ::String, ?name: untyped?, ?field_names: untyped?, ?items: untyped?, ?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • source_ref (Object)
  • row_fields: (Object)
  • data_fields: (Object)
  • col_fields: (Object) (defaults to: [])
  • dest_ref: (Object) (defaults to: "E1")
  • name: (Object) (defaults to: nil)
  • field_names: (Object) (defaults to: nil)
  • items: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
# File 'lib/xlsxrb/ooxml/writer.rb', line 1560

def add_pivot_table(source_ref, row_fields:, data_fields:, col_fields: [], dest_ref: "E1", name: nil, field_names: nil, items: nil, sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @pivot_tables_data.key?(sheet_name)

  pt_name = name || "PivotTable#{@pivot_tables_data.values.flatten.size + 1}"
  @pivot_tables_data[sheet_name] << {
    name: pt_name, source_ref: source_ref,
    row_fields: row_fields, col_fields: col_fields,
    data_fields: data_fields, dest_ref: dest_ref,
    field_names: field_names, items: items,
    data_caption: opts[:data_caption], data_on_rows: opts[:data_on_rows],
    row_grand_totals: opts[:row_grand_totals], col_grand_totals: opts[:col_grand_totals],
    compact: opts[:compact], outline: opts[:outline], show_headers: opts[:show_headers],
    source_name: opts[:source_name],
    grand_total_caption: opts[:grand_total_caption], error_caption: opts[:error_caption],
    show_error: opts[:show_error], missing_caption: opts[:missing_caption],
    show_missing: opts[:show_missing], tag: opts[:tag], indent: opts[:indent],
    published: opts[:published], created_version: opts[:created_version],
    updated_version: opts[:updated_version], min_refreshable_version: opts[:min_refreshable_version],
    pivot_table_style: opts[:pivot_table_style],
    cache_save_data: opts[:cache_save_data], cache_enable_refresh: opts[:cache_enable_refresh],
    cache_refreshed_by: opts[:cache_refreshed_by], cache_refreshed_version: opts[:cache_refreshed_version],
    cache_created_version: opts[:cache_created_version], cache_record_count: opts[:cache_record_count],
    cache_optimize_memory: opts[:cache_optimize_memory],
    row_page_count: opts[:row_page_count], col_page_count: opts[:col_page_count],
    field_attrs: opts[:field_attrs],
    apply_number_formats: opts[:apply_number_formats],
    apply_border_formats: opts[:apply_border_formats],
    apply_font_formats: opts[:apply_font_formats],
    apply_pattern_formats: opts[:apply_pattern_formats],
    apply_alignment_formats: opts[:apply_alignment_formats],
    apply_width_height_formats: opts[:apply_width_height_formats],
    multiple_field_filters: opts[:multiple_field_filters],
    show_drill: opts[:show_drill],
    show_data_tips: opts[:show_data_tips],
    enable_drill: opts[:enable_drill],
    show_member_property_tips: opts[:show_member_property_tips],
    item_print_titles: opts[:item_print_titles],
    field_print_titles: opts[:field_print_titles],
    preserve_formatting: opts[:preserve_formatting],
    page_over_then_down: opts[:page_over_then_down],
    page_wrap: opts[:page_wrap],
    compact_data: opts[:compact_data],
    outline_data: opts[:outline_data],
    show_multiple_label: opts[:show_multiple_label],
    show_data_drop_down: opts[:show_data_drop_down],
    edit_data: opts[:edit_data],
    disable_field_list: opts[:disable_field_list],
    visual_totals: opts[:visual_totals],
    print_drill: opts[:print_drill]
  }
end

#add_protected_range(sheet: nil, **opts) ⇒ Object

Adds a protected range to the given sheet. Required: name:, sqref: Optional: algorithm_name:, hash_value:, salt_value:, spin_count:, security_descriptors: [] : (?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


1083
1084
1085
1086
1087
1088
1089
1090
# File 'lib/xlsxrb/ooxml/writer.rb', line 1083

def add_protected_range(sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)
  raise ArgumentError, "name is required" unless opts[:name]
  raise ArgumentError, "sqref is required" unless opts[:sqref]

  @protected_ranges[sheet_name] << opts
end

#add_raw_entry(path, content, content_type: nil) ⇒ Object

Adds a raw ZIP entry to be included in the output (for pass-through retention). : (untyped path, untyped content, ?content_type: untyped?) -> (nil | untyped)

Parameters:

  • path (Object)
  • content (Object)
  • content_type: (Object) (defaults to: nil)

Returns:

  • (Object)


1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'lib/xlsxrb/ooxml/writer.rb', line 1187

def add_raw_entry(path, content, content_type: nil)
  @extra_entries[path] = content
  return unless content_type

  ext = File.extname(path).delete(".")
  if ext.empty? || path.include?("/")
    @extra_ct_overrides["/#{path}"] = content_type
  else
    @extra_ct_defaults[ext] = content_type
  end
end

#add_row_break(row_num, sheet: nil) ⇒ Object

Adds a row break (page break before a given row number). : (untyped row_num, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


804
805
806
807
808
809
# File 'lib/xlsxrb/ooxml/writer.rb', line 804

def add_row_break(row_num, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_breaks.key?(sheet_name)

  @row_breaks[sheet_name] << row_num
end

#add_shape(preset: "rect", text: nil, name: nil, description: nil, title: nil, hidden: nil, macro: nil, textlink: nil, f_locks_text: nil, no_grp: nil, no_rot: nil, fill_color: nil, fill_alpha: nil, fill_color_transforms: nil, no_fill: nil, gradient_fill: nil, pattern_fill: nil, line_color: nil, line_alpha: nil, line_color_transforms: nil, line_width: nil, no_line: nil, line_dash: nil, line_custom_dash: nil, line_cap: nil, line_align: nil, line_compound: nil, line_join: nil, line_miter_limit: nil, head_end: nil, tail_end: nil, rotation: nil, text_wrap: nil, text_anchor: nil, text_vert_overflow: nil, text_horz_overflow: nil, text_spc_first_last_para: nil, text_num_col: nil, text_spc_col: nil, text_rtl_col: nil, text_from_word_art: nil, text_upright: nil, text_compat_ln_spc: nil, text_force_aa: nil, text_warp: nil, text_vertical: nil, text_insets: nil, text_rot: nil, adjust_values: nil, text_font: nil, text_end_para_rpr: nil, text_def_rpr: nil, text_align: nil, text_font_align: nil, text_def_tab_sz: nil, text_indent: nil, text_anchor_ctr: nil, text_spacing: nil, text_rtl: nil, text_ea_ln_brk: nil, text_latin_ln_brk: nil, text_hanging_punct: nil, text_tab_stops: nil, text_bullet: nil, text_level: nil, text_paragraphs: nil, autofit: nil, outer_shadow: nil, inner_shadow: nil, glow: nil, soft_edge: nil, reflection: nil, blur: nil, from_col: 0, from_row: 0, to_col: 5, to_row: 5, from_col_off: nil, from_row_off: nil, to_col_off: nil, to_row_off: nil, edit_as: nil, published: nil, locks_with_sheet: nil, prints_with_sheet: nil, sheet: nil) ⇒ Object

Adds a shape to the given sheet. preset: preset geometry name (e.g. "rect", "ellipse", "roundRect"). text: optional text body string. from_col/from_row/to_col/to_row: anchor coordinates. : (?preset: ::String, ?text: untyped?, ?name: untyped?, ?description: untyped?, ?title: untyped?, ?hidden: untyped?, ?macro: untyped?, ?textlink: untyped?, ?f_locks_text: untyped?, ?no_grp: untyped?, ?no_rot: untyped?, ?fill_color: untyped?, ?fill_alpha: untyped?, ?fill_color_transforms: untyped?, ?no_fill: untyped?, ?gradient_fill: untyped?, ?pattern_fill: untyped?, ?line_color: untyped?, ?line_alpha: untyped?, ?line_color_transforms: untyped?, ?line_width: untyped?, ?no_line: untyped?, ?line_dash: untyped?, ?line_custom_dash: untyped?, ?line_cap: untyped?, ?line_align: untyped?, ?line_compound: untyped?, ?line_join: untyped?, ?line_miter_limit: untyped?, ?head_end: untyped?, ?tail_end: untyped?, ?rotation: untyped?, ?text_wrap: untyped?, ?text_anchor: untyped?, ?text_vert_overflow: untyped?, ?text_horz_overflow: untyped?, ?text_spc_first_last_para: untyped?, ?text_num_col: untyped?, ?text_spc_col: untyped?, ?text_rtl_col: untyped?, ?text_from_word_art: untyped?, ?text_upright: untyped?, ?text_compat_ln_spc: untyped?, ?text_force_aa: untyped?, ?text_warp: untyped?, ?text_vertical: untyped?, ?text_insets: untyped?, ?text_rot: untyped?, ?adjust_values: untyped?, ?text_font: untyped?, ?text_end_para_rpr: untyped?, ?text_def_rpr: untyped?, ?text_align: untyped?, ?text_font_align: untyped?, ?text_def_tab_sz: untyped?, ?text_indent: untyped?, ?text_anchor_ctr: untyped?, ?text_spacing: untyped?, ?text_rtl: untyped?, ?text_ea_ln_brk: untyped?, ?text_latin_ln_brk: untyped?, ?text_hanging_punct: untyped?, ?text_tab_stops: untyped?, ?text_bullet: untyped?, ?text_level: untyped?, ?text_paragraphs: untyped?, ?autofit: untyped?, ?outer_shadow: untyped?, ?inner_shadow: untyped?, ?glow: untyped?, ?soft_edge: untyped?, ?reflection: untyped?, ?blur: untyped?, ?from_col: ::Integer, ?from_row: ::Integer, ?to_col: ::Integer, ?to_row: ::Integer, ?from_col_off: untyped?, ?from_row_off: untyped?, ?to_col_off: untyped?, ?to_row_off: untyped?, ?edit_as: untyped?, ?published: untyped?, ?locks_with_sheet: untyped?, ?prints_with_sheet: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • preset: (Object) (defaults to: "rect")
  • text: (Object) (defaults to: nil)
  • name: (Object) (defaults to: nil)
  • description: (Object) (defaults to: nil)
  • title: (Object) (defaults to: nil)
  • hidden: (Object) (defaults to: nil)
  • macro: (Object) (defaults to: nil)
  • textlink: (Object) (defaults to: nil)
  • f_locks_text: (Object) (defaults to: nil)
  • no_grp: (Object) (defaults to: nil)
  • no_rot: (Object) (defaults to: nil)
  • fill_color: (Object) (defaults to: nil)
  • fill_alpha: (Object) (defaults to: nil)
  • fill_color_transforms: (Object) (defaults to: nil)
  • no_fill: (Object) (defaults to: nil)
  • gradient_fill: (Object) (defaults to: nil)
  • pattern_fill: (Object) (defaults to: nil)
  • line_color: (Object) (defaults to: nil)
  • line_alpha: (Object) (defaults to: nil)
  • line_color_transforms: (Object) (defaults to: nil)
  • line_width: (Object) (defaults to: nil)
  • no_line: (Object) (defaults to: nil)
  • line_dash: (Object) (defaults to: nil)
  • line_custom_dash: (Object) (defaults to: nil)
  • line_cap: (Object) (defaults to: nil)
  • line_align: (Object) (defaults to: nil)
  • line_compound: (Object) (defaults to: nil)
  • line_join: (Object) (defaults to: nil)
  • line_miter_limit: (Object) (defaults to: nil)
  • head_end: (Object) (defaults to: nil)
  • tail_end: (Object) (defaults to: nil)
  • rotation: (Object) (defaults to: nil)
  • text_wrap: (Object) (defaults to: nil)
  • text_anchor: (Object) (defaults to: nil)
  • text_vert_overflow: (Object) (defaults to: nil)
  • text_horz_overflow: (Object) (defaults to: nil)
  • text_spc_first_last_para: (Object) (defaults to: nil)
  • text_num_col: (Object) (defaults to: nil)
  • text_spc_col: (Object) (defaults to: nil)
  • text_rtl_col: (Object) (defaults to: nil)
  • text_from_word_art: (Object) (defaults to: nil)
  • text_upright: (Object) (defaults to: nil)
  • text_compat_ln_spc: (Object) (defaults to: nil)
  • text_force_aa: (Object) (defaults to: nil)
  • text_warp: (Object) (defaults to: nil)
  • text_vertical: (Object) (defaults to: nil)
  • text_insets: (Object) (defaults to: nil)
  • text_rot: (Object) (defaults to: nil)
  • adjust_values: (Object) (defaults to: nil)
  • text_font: (Object) (defaults to: nil)
  • text_end_para_rpr: (Object) (defaults to: nil)
  • text_def_rpr: (Object) (defaults to: nil)
  • text_align: (Object) (defaults to: nil)
  • text_font_align: (Object) (defaults to: nil)
  • text_def_tab_sz: (Object) (defaults to: nil)
  • text_indent: (Object) (defaults to: nil)
  • text_anchor_ctr: (Object) (defaults to: nil)
  • text_spacing: (Object) (defaults to: nil)
  • text_rtl: (Object) (defaults to: nil)
  • text_ea_ln_brk: (Object) (defaults to: nil)
  • text_latin_ln_brk: (Object) (defaults to: nil)
  • text_hanging_punct: (Object) (defaults to: nil)
  • text_tab_stops: (Object) (defaults to: nil)
  • text_bullet: (Object) (defaults to: nil)
  • text_level: (Object) (defaults to: nil)
  • text_paragraphs: (Object) (defaults to: nil)
  • autofit: (Object) (defaults to: nil)
  • outer_shadow: (Object) (defaults to: nil)
  • inner_shadow: (Object) (defaults to: nil)
  • glow: (Object) (defaults to: nil)
  • soft_edge: (Object) (defaults to: nil)
  • reflection: (Object) (defaults to: nil)
  • blur: (Object) (defaults to: nil)
  • from_col: (Object) (defaults to: 0)
  • from_row: (Object) (defaults to: 0)
  • to_col: (Object) (defaults to: 5)
  • to_row: (Object) (defaults to: 5)
  • from_col_off: (Object) (defaults to: nil)
  • from_row_off: (Object) (defaults to: nil)
  • to_col_off: (Object) (defaults to: nil)
  • to_row_off: (Object) (defaults to: nil)
  • edit_as: (Object) (defaults to: nil)
  • published: (Object) (defaults to: nil)
  • locks_with_sheet: (Object) (defaults to: nil)
  • prints_with_sheet: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
# File 'lib/xlsxrb/ooxml/writer.rb', line 1434

def add_shape(preset: "rect", text: nil, name: nil, description: nil, title: nil, hidden: nil, macro: nil, textlink: nil, f_locks_text: nil, no_grp: nil, no_rot: nil, fill_color: nil, fill_alpha: nil, fill_color_transforms: nil, no_fill: nil, gradient_fill: nil, pattern_fill: nil, line_color: nil, line_alpha: nil, line_color_transforms: nil, line_width: nil, no_line: nil, line_dash: nil, line_custom_dash: nil, line_cap: nil, line_align: nil, line_compound: nil, line_join: nil, line_miter_limit: nil, head_end: nil, tail_end: nil, rotation: nil, text_wrap: nil, text_anchor: nil, text_vert_overflow: nil, text_horz_overflow: nil, text_spc_first_last_para: nil, text_num_col: nil, text_spc_col: nil, text_rtl_col: nil, text_from_word_art: nil, text_upright: nil, text_compat_ln_spc: nil, text_force_aa: nil, text_warp: nil, text_vertical: nil, text_insets: nil, text_rot: nil, adjust_values: nil, text_font: nil, text_end_para_rpr: nil, text_def_rpr: nil, text_align: nil, text_font_align: nil, text_def_tab_sz: nil, text_indent: nil, text_anchor_ctr: nil, text_spacing: nil, text_rtl: nil, text_ea_ln_brk: nil, text_latin_ln_brk: nil, text_hanging_punct: nil, text_tab_stops: nil, text_bullet: nil, text_level: nil, text_paragraphs: nil, autofit: nil, outer_shadow: nil, inner_shadow: nil, glow: nil, soft_edge: nil, reflection: nil, blur: nil, from_col: 0, from_row: 0, to_col: 5, to_row: 5, from_col_off: nil, from_row_off: nil, to_col_off: nil, to_row_off: nil, edit_as: nil, published: nil, locks_with_sheet: nil, prints_with_sheet: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @shapes_data.key?(sheet_name)

  shape_name = name || "Shape #{@shapes_data[sheet_name].size + 1}"
  shape = {
    preset: preset, text: text, name: shape_name,
    from_col: from_col, from_row: from_row,
    to_col: to_col, to_row: to_row
  }
  shape[:from_col_off] = from_col_off if from_col_off
  shape[:from_row_off] = from_row_off if from_row_off
  shape[:to_col_off] = to_col_off if to_col_off
  shape[:to_row_off] = to_row_off if to_row_off
  shape[:description] = description if description
  shape[:title] = title if title
  shape[:hidden] = hidden unless hidden.nil?
  shape[:macro] = macro if macro
  shape[:textlink] = textlink if textlink
  shape[:f_locks_text] = f_locks_text unless f_locks_text.nil?
  shape[:no_grp] = no_grp unless no_grp.nil?
  shape[:no_rot] = no_rot unless no_rot.nil?
  shape[:fill_color] = fill_color if fill_color
  shape[:fill_alpha] = fill_alpha if fill_alpha
  shape[:fill_color_transforms] = fill_color_transforms if fill_color_transforms
  shape[:no_fill] = no_fill unless no_fill.nil?
  shape[:line_color] = line_color if line_color
  shape[:line_alpha] = line_alpha if line_alpha
  shape[:line_color_transforms] = line_color_transforms if line_color_transforms
  shape[:line_width] = line_width if line_width
  shape[:line_dash] = line_dash if line_dash
  shape[:line_custom_dash] = line_custom_dash if line_custom_dash
  shape[:line_cap] = line_cap if line_cap
  shape[:line_align] = line_align if line_align
  shape[:line_compound] = line_compound if line_compound
  shape[:line_join] = line_join if line_join
  shape[:line_miter_limit] = line_miter_limit if line_miter_limit
  shape[:head_end] = head_end if head_end
  shape[:tail_end] = tail_end if tail_end
  shape[:no_line] = no_line unless no_line.nil?
  shape[:text_wrap] = text_wrap if text_wrap
  shape[:text_anchor] = text_anchor if text_anchor
  shape[:text_vert_overflow] = text_vert_overflow if text_vert_overflow
  shape[:text_horz_overflow] = text_horz_overflow if text_horz_overflow
  shape[:text_spc_first_last_para] = text_spc_first_last_para unless text_spc_first_last_para.nil?
  shape[:text_num_col] = text_num_col if text_num_col
  shape[:text_spc_col] = text_spc_col if text_spc_col
  shape[:text_rtl_col] = text_rtl_col unless text_rtl_col.nil?
  shape[:text_from_word_art] = text_from_word_art unless text_from_word_art.nil?
  shape[:text_upright] = text_upright unless text_upright.nil?
  shape[:text_compat_ln_spc] = text_compat_ln_spc unless text_compat_ln_spc.nil?
  shape[:text_force_aa] = text_force_aa unless text_force_aa.nil?
  shape[:text_warp] = text_warp if text_warp
  shape[:text_vertical] = text_vertical if text_vertical
  shape[:text_insets] = text_insets if text_insets
  shape[:text_rot] = text_rot if text_rot
  shape[:rotation] = rotation if rotation
  shape[:adjust_values] = adjust_values if adjust_values
  shape[:text_font] = text_font if text_font
  shape[:text_end_para_rpr] = text_end_para_rpr if text_end_para_rpr
  shape[:text_def_rpr] = text_def_rpr if text_def_rpr
  shape[:text_align] = text_align if text_align
  shape[:text_font_align] = text_font_align if text_font_align
  shape[:text_def_tab_sz] = text_def_tab_sz if text_def_tab_sz
  shape[:text_indent] = text_indent if text_indent
  shape[:text_anchor_ctr] = text_anchor_ctr unless text_anchor_ctr.nil?
  shape[:text_spacing] = text_spacing if text_spacing
  shape[:text_rtl] = text_rtl unless text_rtl.nil?
  shape[:text_ea_ln_brk] = text_ea_ln_brk unless text_ea_ln_brk.nil?
  shape[:text_latin_ln_brk] = text_latin_ln_brk unless text_latin_ln_brk.nil?
  shape[:text_hanging_punct] = text_hanging_punct unless text_hanging_punct.nil?
  shape[:text_tab_stops] = text_tab_stops if text_tab_stops
  shape[:text_bullet] = text_bullet if text_bullet
  shape[:text_level] = text_level if text_level
  shape[:text_paragraphs] = text_paragraphs if text_paragraphs
  shape[:autofit] = autofit if autofit
  shape[:outer_shadow] = outer_shadow if outer_shadow
  shape[:inner_shadow] = inner_shadow if inner_shadow
  shape[:glow] = glow if glow
  shape[:soft_edge] = soft_edge if soft_edge
  shape[:reflection] = reflection if reflection
  shape[:blur] = blur if blur
  shape[:gradient_fill] = gradient_fill if gradient_fill
  shape[:pattern_fill] = pattern_fill if pattern_fill
  shape[:edit_as] = edit_as if edit_as
  shape[:published] = published unless published.nil?
  shape[:locks_with_sheet] = locks_with_sheet unless locks_with_sheet.nil?
  shape[:prints_with_sheet] = prints_with_sheet unless prints_with_sheet.nil?
  @shapes_data[sheet_name] << shape
end

#add_sheet(name) ⇒ Object

Adds a new sheet. Raises if name is already taken. : (untyped name) -> untyped

Parameters:

  • name (Object)

Returns:

  • (Object)


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
# File 'lib/xlsxrb/ooxml/writer.rb', line 104

def add_sheet(name)
  raise ArgumentError, "sheet already exists: #{name}" if @sheets.key?(name)

  @sheets[name] = {}
  @column_widths[name] = {}
  @column_attrs[name] = {}
  @row_attrs[name] = {}
  @merge_cells[name] = []
  @hyperlinks[name] = {}
  @cell_styles[name] = {}
  @cell_phonetic[name] = {}
  @auto_filters[name] = nil
  @filter_columns[name] = {}
  @sort_state[name] = nil
  @sheet_properties[name] = {}
  @sheet_formats[name] = {}
  @sheet_views[name] = {}
  @freeze_panes[name] = nil
  @selections[name] = nil
  @print_options[name] = {}
  @page_margins[name] = nil
  @page_setup[name] = {}
  @header_footer[name] = {}
  @row_breaks[name] = []
  @col_breaks[name] = []
  @data_validations[name] = []
  @data_validations_options[name] = {}
  @conditional_formats[name] = []
  @tables[name] = []
  @cell_watches[name] = []
  @ignored_errors[name] = []
  @data_consolidate[name] = nil
  @scenarios[name] = nil
  @images[name] = []
  @charts_data[name] = []
  @shapes_data[name] = []
  @comments_data[name] = []
  @pivot_tables_data[name] = []
  @sheet_protection[name] = nil
  @protected_ranges[name] = []
  @phonetic_properties[name] = nil
  @sheet_order << name
end

#add_table(ref, columns:, name: nil, display_name: nil, sheet: nil, totals_row_count: 0, style: nil, **opts) ⇒ Object

Adds a table definition to a sheet. columns: array of column name strings. : (untyped ref, columns: untyped, ?name: untyped?, ?display_name: untyped?, ?sheet: untyped?, ?totals_row_count: ::Integer, ?style: untyped?, **untyped opts) -> untyped

Parameters:

  • ref (Object)
  • columns: (Object)
  • name: (Object) (defaults to: nil)
  • display_name: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)
  • totals_row_count: (Object) (defaults to: 0)
  • style: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# File 'lib/xlsxrb/ooxml/writer.rb', line 883

def add_table(ref, columns:, name: nil, display_name: nil, sheet: nil, totals_row_count: 0, style: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @tables.key?(sheet_name)

  table_id = @tables.values.flatten.size + 1
  tbl_name = name || "Table#{table_id}"
  tbl = {
    id: table_id, ref: ref, name: tbl_name,
    display_name: display_name || tbl_name, columns: columns,
    totals_row_count: totals_row_count
  }
  tbl[:style] = style if style
  %i[header_row_count published comment insert_row insert_row_shift
     header_row_dxf_id data_dxf_id totals_row_dxf_id
     header_row_border_dxf_id table_border_dxf_id totals_row_border_dxf_id
     header_row_cell_style totals_row_cell_style connection_id table_type].each do |key|
    tbl[key] = opts[key] if opts.key?(key)
  end
  @tables[sheet_name] << tbl
end

#add_table_style(name:, elements: [], pivot: nil, table: nil) ⇒ Object

Adds a table style definition. Returns the style name. elements: array of { type:, dxf_id:, size: } : (name: untyped, ?elements: untyped, ?pivot: untyped?, ?table: untyped?) -> untyped

Parameters:

  • name: (Object)
  • elements: (Object) (defaults to: [])
  • pivot: (Object) (defaults to: nil)
  • table: (Object) (defaults to: nil)

Returns:

  • (Object)


563
564
565
566
567
568
569
570
# File 'lib/xlsxrb/ooxml/writer.rb', line 563

def add_table_style(name:, elements: [], pivot: nil, table: nil)
  @table_styles[:styles] ||= []
  style = { name: name, elements: elements }
  style[:pivot] = pivot unless pivot.nil?
  style[:table] = table unless table.nil?
  @table_styles[:styles] << style
  name
end

#anchor_xml(tag, col, row, col_off: 0, row_off: 0) ⇒ Object

: (untyped tag, untyped col, untyped row, ?col_off: ::Integer, ?row_off: ::Integer) -> ::String

Parameters:

  • tag (Object)
  • col (Object)
  • row (Object)
  • col_off: (Object) (defaults to: 0)
  • row_off: (Object) (defaults to: 0)

Returns:

  • (Object)


3500
3501
3502
# File 'lib/xlsxrb/ooxml/writer.rb', line 3500

def anchor_xml(tag, col, row, col_off: 0, row_off: 0)
  "<xdr:#{tag}><xdr:col>#{col}</xdr:col><xdr:colOff>#{col_off}</xdr:colOff><xdr:row>#{row}</xdr:row><xdr:rowOff>#{row_off}</xdr:rowOff></xdr:#{tag}>"
end

#app_propertiesObject

Returns app properties hash. : () -> untyped

Returns:

  • (Object)


606
607
608
# File 'lib/xlsxrb/ooxml/writer.rb', line 606

def app_properties
  @app_properties.dup
end

#app_property(name, value) ⇒ Object

Sets an app property. : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


598
599
600
601
602
# File 'lib/xlsxrb/ooxml/writer.rb', line 598

def app_property(name, value)
  raise ArgumentError, "name must be a Symbol" unless name.is_a?(Symbol)

  @app_properties[name] = value
end

#auto_filter(sheet: nil) ⇒ Object

Returns the autoFilter range for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


355
356
357
358
# File 'lib/xlsxrb/ooxml/writer.rb', line 355

def auto_filter(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @auto_filters[sheet_name]
end

#build_axis_txpr(rotation, font) ⇒ Object

: (untyped rotation, untyped font) -> ("" | ::String)

Parameters:

  • rotation (Object)
  • font (Object)

Returns:

  • (Object)


3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
# File 'lib/xlsxrb/ooxml/writer.rb', line 3737

def build_axis_txpr(rotation, font)
  return "" unless rotation || font

  body_attrs = rotation ? %( rot="#{rotation}") : ""
  rpr_attrs = +""
  rpr_children = +""
  if font
    rpr_attrs << %( sz="#{(font[:size] * 100).to_i}") if font[:size]
    rpr_attrs << %( b="1") if font[:bold]
    rpr_attrs << %( i="1") if font[:italic]
    rpr_children << %(<a:solidFill>#{color_xml(font[:color])}</a:solidFill>) if font[:color]
    rpr_children << %(<a:latin typeface="#{xml_escape(font[:name])}"/>) if font[:name]
  end
  def_rpr = if rpr_children.empty?
              "<a:defRPr#{rpr_attrs}/>"
            else
              "<a:defRPr#{rpr_attrs}>#{rpr_children}</a:defRPr>"
            end
  %(<c:txPr><a:bodyPr#{body_attrs}/><a:lstStyle/><a:p><a:pPr>#{def_rpr}</a:pPr><a:endParaRPr/></a:p></c:txPr>)
end

#build_chart_title_xml(title_spec, overlay: false) ⇒ Object

: (untyped title_spec, ?overlay: bool) -> untyped

Parameters:

  • title_spec (Object)
  • overlay: (Object) (defaults to: false)

Returns:

  • (Object)


3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
# File 'lib/xlsxrb/ooxml/writer.rb', line 3529

def build_chart_title_xml(title_spec, overlay: false)
  overlay_val = overlay ? 1 : 0
  if title_spec.is_a?(Hash)
    text = xml_escape(title_spec[:text].to_s)
    rotation = title_spec[:rotation]
    body_pr = rotation ? %(<a:bodyPr rot="#{rotation}"/>) : "<a:bodyPr/>"
    font = title_spec[:font] || {}
    rpr_attrs = +""
    rpr_attrs << %( b="1") if font[:bold]
    rpr_attrs << %( i="1") if font[:italic]
    rpr_attrs << %( sz="#{font[:size]}") if font[:size]
    rpr_children = +""
    rpr_children << %(<a:solidFill>#{color_xml(font[:color])}</a:solidFill>) if font[:color]
    rpr_children << %(<a:latin typeface="#{xml_escape(font[:name])}"/>) if font[:name]
    rpr_xml = if rpr_children.empty?
                "<a:rPr#{rpr_attrs}/>"
              else
                "<a:rPr#{rpr_attrs}>#{rpr_children}</a:rPr>"
              end
    layout_xml = build_title_layout_xml(title_spec[:layout])
    sp_xml = build_title_sp_pr(title_spec)
    "<c:title><c:tx><c:rich>#{body_pr}<a:lstStyle/><a:p><a:r>#{rpr_xml}<a:t>#{text}</a:t></a:r></a:p></c:rich></c:tx>#{layout_xml}<c:overlay val=\"#{overlay_val}\"/>#{sp_xml}</c:title>"
  else
    "<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>#{xml_escape(title_spec)}</a:t></a:r></a:p></c:rich></c:tx><c:overlay val=\"#{overlay_val}\"/></c:title>"
  end
end

#build_line_end_xml(element, opts) ⇒ Object

: (untyped element, untyped opts) -> ("" | ::String)

Parameters:

  • element (Object)
  • opts (Object)

Returns:

  • (Object)


4869
4870
4871
4872
4873
4874
4875
4876
4877
# File 'lib/xlsxrb/ooxml/writer.rb', line 4869

def build_line_end_xml(element, opts)
  return "" unless opts

  attrs = +""
  attrs << %( type="#{xml_escape(opts[:type])}") if opts[:type]
  attrs << %( w="#{xml_escape(opts[:w])}") if opts[:w]
  attrs << %( len="#{xml_escape(opts[:len])}") if opts[:len]
  "<a:#{element}#{attrs}/>"
end

#build_shared_string_tableObject

: () -> ::Array

Returns:

  • (Object)


2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
# File 'lib/xlsxrb/ooxml/writer.rb', line 2832

def build_shared_string_table
  rt_sst = {}.compare_by_identity # Xlsxrb::Elements::RichText object -> global index
  str_sst = {} # String -> global index
  @sheets.each_value do |sheet_cells|
    sheet_cells.each_value do |value|
      total = rt_sst.size + str_sst.size
      case value
      when Xlsxrb::Elements::RichText
        rt_sst[value] = total unless rt_sst.key?(value)
      when String
        str_sst[value] = total unless str_sst.key?(value)
      else
        next if value.is_a?(Numeric) || value.is_a?(Date) || value == true || value == false || value.is_a?(Xlsxrb::Elements::Formula)

        str = value.to_s
        str_sst[str] = total unless str_sst.key?(str)
      end
    end
  end
  [rt_sst, str_sst]
end

#build_sheet_rels_parts_v2(sheet_name, sheet_tables, table_start_index, drawing_idx, comment_idx, pivot_start, pivot_count) ⇒ Object

: (untyped sheet_name, untyped sheet_tables, untyped table_start_index, untyped drawing_idx, untyped comment_idx, untyped pivot_start, untyped pivot_count) -> untyped

Parameters:

  • sheet_name (Object)
  • sheet_tables (Object)
  • table_start_index (Object)
  • drawing_idx (Object)
  • comment_idx (Object)
  • pivot_start (Object)
  • pivot_count (Object)

Returns:

  • (Object)


2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
# File 'lib/xlsxrb/ooxml/writer.rb', line 2962

def build_sheet_rels_parts_v2(sheet_name, sheet_tables, table_start_index, drawing_idx, comment_idx, pivot_start, pivot_count)
  rels = []
  @hyperlinks[sheet_name].each do |(_cell_ref, link)|
    next unless link[:url]

    rels << { type: "#{DOC_REL_NS}/hyperlink", target: link[:url], external: true }
  end
  sheet_tables.each_with_index do |_tbl, i|
    rels << { type: "#{DOC_REL_NS}/table", target: "../tables/table#{table_start_index + i + 1}.xml" }
  end
  if comment_idx
    rels << { type: "#{DOC_REL_NS}/comments", target: "../comments#{comment_idx}.xml" }
    rels << { type: "#{DOC_REL_NS}/vmlDrawing", target: "../drawings/vmlDrawing#{comment_idx}.vml" }
  end
  rels << { type: "#{DOC_REL_NS}/drawing", target: "../drawings/drawing#{drawing_idx}.xml" } if drawing_idx
  pivot_count.times do |i|
    pt_idx = pivot_start + i + 1
    rels << { type: "#{DOC_REL_NS}/pivotTable", target: "../pivotTables/pivotTable#{pt_idx}.xml" }
  end
  rels
end

#build_title_layout_xml(layout) ⇒ Object

: (untyped layout) -> ("" | untyped)

Parameters:

  • layout (Object)

Returns:

  • (Object)


3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
# File 'lib/xlsxrb/ooxml/writer.rb', line 3594

def build_title_layout_xml(layout)
  return "" unless layout.is_a?(Hash)

  ml = +""
  ml << %(<c:x val="#{layout[:x]}"/>) if layout[:x]
  ml << %(<c:y val="#{layout[:y]}"/>) if layout[:y]
  ml << %(<c:w val="#{layout[:w]}"/>) if layout[:w]
  ml << %(<c:h val="#{layout[:h]}"/>) if layout[:h]
  ml.empty? ? "" : "<c:layout><c:manualLayout>#{ml}</c:manualLayout></c:layout>"
end

#build_title_sp_pr(spec) ⇒ Object

: (untyped spec) -> untyped

Parameters:

  • spec (Object)

Returns:

  • (Object)


3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
# File 'lib/xlsxrb/ooxml/writer.rb', line 3580

def build_title_sp_pr(spec)
  children = +""
  children << %(<a:solidFill>#{color_xml(spec[:fill_color])}</a:solidFill>) if spec[:fill_color]
  children << "<a:noFill/>" if spec[:no_fill]
  if spec[:line_color] || spec[:line_width] || spec[:line_dash]
    lw = spec[:line_width] ? %( w="#{(spec[:line_width] * 12_700).to_i}") : ""
    lf = spec[:line_color] ? %(<a:solidFill>#{color_xml(spec[:line_color])}</a:solidFill>) : ""
    ld = spec[:line_dash] ? %(<a:prstDash val="#{xml_escape(spec[:line_dash])}"/>) : ""
    children << "<a:ln#{lw}>#{lf}#{ld}</a:ln>"
  end
  children.empty? ? "" : "<c:spPr>#{children}</c:spPr>"
end

#calc_propertiesObject

Returns calc properties hash. : () -> untyped

Returns:

  • (Object)


1043
1044
1045
# File 'lib/xlsxrb/ooxml/writer.rb', line 1043

def calc_properties
  @calc_properties.dup
end

#cell_to_col_row(cell_ref) ⇒ Object

: (untyped cell_ref) -> (::Array | ::Array)

Parameters:

  • cell_ref (Object)

Returns:

  • (Object)


4576
4577
4578
4579
4580
4581
4582
4583
# File 'lib/xlsxrb/ooxml/writer.rb', line 4576

def cell_to_col_row(cell_ref)
  m = cell_ref.match(/\A([A-Z]+)(\d+)\z/)
  return [0, 0] unless m

  col = column_letter_to_index(m[1]) - 1
  row = m[2].to_i - 1
  [col, row]
end

#cell_watches(sheet: nil) ⇒ Object

Returns cell watches for the given sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1110
1111
1112
1113
# File 'lib/xlsxrb/ooxml/writer.rb', line 1110

def cell_watches(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@cell_watches[sheet_name] || []).dup
end

#cell_xml(cell_ref, value, style_idx, sst = nil, ph: nil) ⇒ Object

: (untyped cell_ref, untyped value, untyped style_idx, ?untyped? sst, ?ph: untyped?) -> untyped

Parameters:

  • cell_ref (Object)
  • value (Object)
  • style_idx (Object)
  • sst (Object) (defaults to: nil)
  • ph: (Object) (defaults to: nil)

Returns:

  • (Object)


4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
# File 'lib/xlsxrb/ooxml/writer.rb', line 4920

def cell_xml(cell_ref, value, style_idx, sst = nil, ph: nil) # rubocop:disable Naming/MethodParameterName
  s_attr = style_idx ? %( s="#{style_idx}") : ""
  ph_attr = ph ? ' ph="1"' : ""
  case value
  when Xlsxrb::Elements::CellError
    %(<c r="#{cell_ref}" t="e"#{s_attr}#{ph_attr}><v>#{xml_escape(value.code)}</v></c>)
  when Xlsxrb::Elements::Formula
    f_attrs = +""
    case value.type
    when :shared
      f_attrs << %( t="shared" si="#{value.shared_index}")
      f_attrs << %( ref="#{value.ref}") if value.ref
    when :array
      f_attrs << %( t="array" ref="#{value.ref}") if value.ref
    when :data_table
      f_attrs << ' t="dataTable"'
      f_attrs << ' dt2D="1"' if value.dt2d
      f_attrs << ' dtr="1"' if value.dtr
      f_attrs << %( r1="#{value.r1}") if value.r1
      f_attrs << %( r2="#{value.r2}") if value.r2
    end
    f_attrs << ' ca="1"' if value.calculate_always
    f_attrs << ' aca="1"' if value.aca
    f_attrs << ' bx="1"' if value.bx
    t_attr = ""
    cached_val_str = value.cached_value.to_s
    case value.cached_value
    when String
      t_attr = ' t="str"'
    when true
      t_attr = ' t="b"'
      cached_val_str = "1"
    when false
      t_attr = ' t="b"'
      cached_val_str = "0"
    end
    parts = %(<c r="#{cell_ref}"#{t_attr}#{s_attr}#{ph_attr}><f#{f_attrs}>#{xml_escape(value.expression)}</f>)
    parts << "<v>#{xml_escape(cached_val_str)}</v>" unless value.cached_value.nil?
    parts << "</c>"
    parts
  when Xlsxrb::Elements::RichText
    if sst
      rt_sst, = sst
      idx = rt_sst[value]
      %(<c r="#{cell_ref}" t="s"#{s_attr}#{ph_attr}><v>#{idx}</v></c>)
    else
      %(<c r="#{cell_ref}" t="inlineStr"#{s_attr}#{ph_attr}><is>#{rich_text_xml(value)}</is></c>)
    end
  when true, false
    %(<c r="#{cell_ref}" t="b"#{s_attr}#{ph_attr}><v>#{value ? 1 : 0}</v></c>)
  when Time
    serial = Xlsxrb::Ooxml::Utils.datetime_to_serial(value)
    dt_attr = s_attr.empty? && (dt_style = resolve_style_index(datetime_num_fmt_id)) ? %( s="#{dt_style}") : s_attr
    %(<c r="#{cell_ref}"#{dt_attr}#{ph_attr}><v>#{serial}</v></c>)
  when Date
    serial = Xlsxrb::Ooxml::Utils.date_to_serial(value)
    ds_attr = s_attr.empty? && (date_style = resolve_style_index(date_num_fmt_id)) ? %( s="#{date_style}") : s_attr
    %(<c r="#{cell_ref}"#{ds_attr}#{ph_attr}><v>#{serial}</v></c>)
  when Numeric
    %(<c r="#{cell_ref}"#{s_attr}#{ph_attr}><v>#{value}</v></c>)
  else
    if sst
      _, str_sst = sst
      idx = str_sst[value.to_s]
      %(<c r="#{cell_ref}" t="s"#{s_attr}#{ph_attr}><v>#{idx}</v></c>)
    else
      %(<c r="#{cell_ref}" t="inlineStr"#{s_attr}#{ph_attr}><is><t>#{xml_escape(value)}</t></is></c>)
    end
  end
end

#cells(sheet: nil) ⇒ Object

Returns the registered cells for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


160
161
162
163
# File 'lib/xlsxrb/ooxml/writer.rb', line 160

def cells(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @sheets[sheet_name] || {}
end

#charts(sheet: nil) ⇒ Object

Returns chart definitions for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1424
1425
1426
1427
# File 'lib/xlsxrb/ooxml/writer.rb', line 1424

def charts(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @charts_data[sheet_name] || []
end

#client_data_xml(obj) ⇒ Object

: (untyped obj) -> ::String

Parameters:

  • obj (Object)

Returns:

  • (Object)


3505
3506
3507
3508
3509
3510
3511
3512
# File 'lib/xlsxrb/ooxml/writer.rb', line 3505

def client_data_xml(obj)
  cd_attrs = +""
  cd_attrs << ' fLocksWithSheet="0"' if obj[:locks_with_sheet] == false
  cd_attrs << ' fLocksWithSheet="1"' if obj[:locks_with_sheet] == true
  cd_attrs << ' fPrintsWithSheet="0"' if obj[:prints_with_sheet] == false
  cd_attrs << ' fPrintsWithSheet="1"' if obj[:prints_with_sheet] == true
  "<xdr:clientData#{cd_attrs}/>"
end

#col_breaks(sheet: nil) ⇒ Object

Returns column breaks for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


829
830
831
832
# File 'lib/xlsxrb/ooxml/writer.rb', line 829

def col_breaks(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @col_breaks[sheet_name] || []
end

#color_xml(color, alpha: nil, transforms: nil) ⇒ Object Also known as: srgb_clr_xml

: (untyped color, ?alpha: untyped?, ?transforms: untyped?) -> untyped

Parameters:

  • color (Object)
  • alpha: (Object) (defaults to: nil)
  • transforms: (Object) (defaults to: nil)

Returns:

  • (Object)


3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
# File 'lib/xlsxrb/ooxml/writer.rb', line 3697

def color_xml(color, alpha: nil, transforms: nil)
  if color.is_a?(Hash) && color[:scheme]
    tag = "schemeClr"
    val = xml_escape(color[:scheme])
    transforms = color[:transforms] || transforms
  else
    tag = "srgbClr"
    val = xml_escape(normalize_drawing_rgb(color))
  end
  children = +""
  children << %(<a:alpha val="#{alpha}"/>) if alpha
  (transforms || []).each do |t|
    children << %(<a:#{xml_escape(t[:type])} val="#{t[:val]}"/>)
  end
  if children.empty?
    %(<a:#{tag} val="#{val}"/>)
  else
    %(<a:#{tag} val="#{val}">#{children}</a:#{tag}>)
  end
end

#column_attributes(sheet: nil) ⇒ Object

Returns column attributes for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


200
201
202
203
# File 'lib/xlsxrb/ooxml/writer.rb', line 200

def column_attributes(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @column_attrs[sheet_name] || {}
end

#column_letter_to_index(letters) ⇒ Object

: (untyped letters) -> untyped

Parameters:

  • letters (Object)

Returns:

  • (Object)


5630
5631
5632
# File 'lib/xlsxrb/ooxml/writer.rb', line 5630

def column_letter_to_index(letters)
  letters.chars.reduce(0) { |sum, char| (sum * 26) + (char.ord - "A".ord + 1) }
end

#column_widths(sheet: nil) ⇒ Object

Returns column widths for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


181
182
183
184
# File 'lib/xlsxrb/ooxml/writer.rb', line 181

def column_widths(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @column_widths[sheet_name] || {}
end

#comments(sheet: nil) ⇒ Object

Returns comment definitions for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1547
1548
1549
1550
# File 'lib/xlsxrb/ooxml/writer.rb', line 1547

def comments(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @comments_data[sheet_name] || []
end

#compute_dimension(sheet_cells) ⇒ Object

: (untyped sheet_cells) -> ("A1" | ::String)

Parameters:

  • sheet_cells (Object)

Returns:

  • (Object)


5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
# File 'lib/xlsxrb/ooxml/writer.rb', line 5192

def compute_dimension(sheet_cells)
  return "A1" if sheet_cells.empty?

  min_col = Float::INFINITY
  max_col = 0
  min_row = Float::INFINITY
  max_row = 0
  sheet_cells.each_key do |addr|
    col_letter = extract_column_letter(addr)
    row_num = extract_row_number(addr)
    col_idx = column_letter_to_index(col_letter)
    min_col = col_idx if col_idx < min_col
    max_col = col_idx if col_idx > max_col
    min_row = row_num if row_num < min_row
    max_row = row_num if row_num > max_row
  end
  start_col = index_to_column_letter(min_col)
  end_col = index_to_column_letter(max_col)
  "#{start_col}#{min_row}:#{end_col}#{max_row}"
end

#conditional_formats(sheet: nil) ⇒ Object

Returns conditional formatting rules for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


875
876
877
878
# File 'lib/xlsxrb/ooxml/writer.rb', line 875

def conditional_formats(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @conditional_formats[sheet_name] || []
end

#copy_entries_from(filepath) ⇒ Object

Copies all ZIP entries from an existing XLSX file as pass-through. Generated parts override pass-through parts with the same path. : (untyped filepath) -> untyped

Parameters:

  • filepath (Object)

Returns:

  • (Object)


1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
# File 'lib/xlsxrb/ooxml/writer.rb', line 1202

def copy_entries_from(filepath)
  reader = Xlsxrb::Ooxml::Reader.new(filepath)
  reader.entry_names.each do |name|
    @extra_entries[name] = reader.raw_entry(name)
  end

  # Parse [Content_Types].xml for extra content types.
  ct_xml = reader.raw_entry("[Content_Types].xml")
  parse_extra_content_types(ct_xml) if ct_xml && !ct_xml.empty?
end

#core_propertiesObject

Returns core properties hash. : () -> untyped

Returns:

  • (Object)


592
593
594
# File 'lib/xlsxrb/ooxml/writer.rb', line 592

def core_properties
  @core_properties.dup
end

#core_property(name, value) ⇒ Object

Sets a core property. : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


584
585
586
587
588
# File 'lib/xlsxrb/ooxml/writer.rb', line 584

def core_property(name, value)
  raise ArgumentError, "name must be a Symbol" unless name.is_a?(Symbol)

  @core_properties[name] = value
end

#custom_propertiesObject

Returns custom properties array. : () -> untyped

Returns:

  • (Object)


618
619
620
# File 'lib/xlsxrb/ooxml/writer.rb', line 618

def custom_properties
  @custom_properties.map(&:dup)
end

#custom_property(name, value, type: :string) ⇒ Object

Adds a custom document property. type: :string (default), :number, :bool, :date. : (untyped name, untyped value, ?type: ::Symbol) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • type: (Object) (defaults to: :string)

Returns:

  • (Object)


612
613
614
# File 'lib/xlsxrb/ooxml/writer.rb', line 612

def custom_property(name, value, type: :string)
  @custom_properties << { name: name, value: value, type: type }
end

#data_consolidate(sheet: nil) ⇒ Object

Returns data consolidation settings for the given sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1146
1147
1148
1149
# File 'lib/xlsxrb/ooxml/writer.rb', line 1146

def data_consolidate(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @data_consolidate[sheet_name]&.dup
end

#data_validations(sheet: nil) ⇒ Object

Returns data validations for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


848
849
850
851
# File 'lib/xlsxrb/ooxml/writer.rb', line 848

def data_validations(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @data_validations[sheet_name] || []
end

#date_num_fmt_idObject

Returns the numFmtId for dates, registering it on first use. : () -> untyped

Returns:

  • (Object)


4993
4994
4995
# File 'lib/xlsxrb/ooxml/writer.rb', line 4993

def date_num_fmt_id
  @date_num_fmt_id ||= add_number_format(Xlsxrb::Ooxml::Utils::DEFAULT_DATE_FORMAT)
end

#datetime_num_fmt_idObject

Returns the numFmtId for datetime, registering it on first use. : () -> untyped

Returns:

  • (Object)


4999
5000
5001
# File 'lib/xlsxrb/ooxml/writer.rb', line 4999

def datetime_num_fmt_id
  @datetime_num_fmt_id ||= add_number_format(Xlsxrb::Ooxml::Utils::DEFAULT_DATETIME_FORMAT)
end

#defined_namesObject

Returns defined names array. : () -> untyped

Returns:

  • (Object)


951
952
953
# File 'lib/xlsxrb/ooxml/writer.rb', line 951

def defined_names
  @defined_names.map(&:dup)
end

#emit_alignment_xml(alignment) ⇒ Object

: (untyped alignment) -> ::String

Parameters:

  • alignment (Object)

Returns:

  • (Object)


5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
# File 'lib/xlsxrb/ooxml/writer.rb', line 5438

def emit_alignment_xml(alignment)
  attrs = []
  attrs << %(horizontal="#{alignment[:horizontal]}") if alignment[:horizontal]
  attrs << %(vertical="#{alignment[:vertical]}") if alignment[:vertical]
  attrs << %(wrapText="1") if alignment[:wrap_text]
  attrs << %(textRotation="#{alignment[:text_rotation]}") if alignment[:text_rotation]
  attrs << %(indent="#{alignment[:indent]}") if alignment[:indent]
  attrs << %(relativeIndent="#{alignment[:relative_indent]}") if alignment[:relative_indent]
  attrs << %(shrinkToFit="1") if alignment[:shrink_to_fit]
  attrs << %(readingOrder="#{alignment[:reading_order]}") if alignment[:reading_order]
  attrs << %(justifyLastLine="1") if alignment[:justify_last_line]
  "<alignment #{attrs.join(" ")}/>"
end

#emit_border_xml(bdr) ⇒ Object

: (untyped bdr) -> untyped

Parameters:

  • bdr (Object)

Returns:

  • (Object)


5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
# File 'lib/xlsxrb/ooxml/writer.rb', line 5579

def emit_border_xml(bdr)
  border_attrs = []
  border_attrs << ' diagonalUp="1"' if bdr[:diagonal_up]
  border_attrs << ' diagonalDown="1"' if bdr[:diagonal_down]
  border_attrs << ' outline="0"' if bdr[:outline] == false
  parts = ["<border#{border_attrs.join}>"]
  %i[left right top bottom diagonal vertical horizontal].each do |side|
    s = bdr[side]
    if s.is_a?(Hash)
      parts << %(<#{side} style="#{s[:style]}">)
      parts << emit_color_xml(s)
      parts << "</#{side}>"
    else
      parts << "<#{side}/>"
    end
  end
  parts << "</border>"
  parts.join
end

#emit_brk_xml(brk, default_max:) ⇒ Object

: (untyped brk, default_max: untyped) -> ::String

Parameters:

  • brk (Object)
  • default_max: (Object)

Returns:

  • (Object)


5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
# File 'lib/xlsxrb/ooxml/writer.rb', line 5565

def emit_brk_xml(brk, default_max:)
  if brk.is_a?(Hash)
    attrs = %(id="#{brk[:id]}")
    attrs << %( min="#{brk[:min]}") if brk[:min]
    attrs << %( max="#{brk.fetch(:max, default_max)}")
    attrs << ' man="1"' if brk.fetch(:man, true)
    attrs << ' pt="1"' if brk[:pt]
    "<brk #{attrs}/>"
  else
    %(<brk id="#{brk}" max="#{default_max}" man="1"/>)
  end
end

#emit_cf_color_xml(color) ⇒ Object

Emits a element for CF rules, accepting either a plain RGB string or a hash. : (untyped color) -> (untyped | ::String)

Parameters:

  • color (Object)

Returns:

  • (Object)


5183
5184
5185
5186
5187
5188
5189
# File 'lib/xlsxrb/ooxml/writer.rb', line 5183

def emit_cf_color_xml(color)
  if color.is_a?(Hash)
    emit_color_xml(color)
  else
    %(<color rgb="#{color}"/>)
  end
end

#emit_cf_rule(parts, rule) ⇒ Object

: (untyped parts, untyped rule) -> untyped

Parameters:

  • parts (Object)
  • rule (Object)

Returns:

  • (Object)


5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
# File 'lib/xlsxrb/ooxml/writer.rb', line 5093

def emit_cf_rule(parts, rule)
  type = rule[:type]
  if type.is_a?(String) || type.is_a?(Symbol)
    t_str = type.to_s
    snake = t_str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
                 .gsub(/([a-z\d])([A-Z])/, '\1_\2')
                 .downcase.to_sym
    type = snake if CF_TYPE_MAP.key?(snake)
  end
  rule_type = CF_TYPE_MAP[type] || type.to_s
  rule_attrs = %(type="#{rule_type}")
  rule_attrs << %( priority="#{rule[:priority]}") if rule[:priority]
  rule_attrs << %( operator="#{rule[:operator]}") if rule[:operator]
  rule_attrs << %( dxfId="#{rule[:format_id]}") if rule[:format_id]
  rule_attrs << %( stopIfTrue="1") if rule[:stop_if_true]
  rule_attrs << %( aboveAverage="0") if rule[:above_average] == false
  rule_attrs << %( equalAverage="1") if rule[:equal_average]
  rule_attrs << %( rank="#{rule[:rank]}") if rule[:rank]
  rule_attrs << %( percent="1") if rule[:percent]
  rule_attrs << %( bottom="1") if rule[:bottom]
  rule_attrs << %( text="#{xml_escape(rule[:text])}") if rule[:text]
  rule_attrs << %( timePeriod="#{rule[:time_period]}") if rule[:time_period]
  rule_attrs << %( stdDev="#{rule[:std_dev]}") if rule[:std_dev]

  case type
  when :cell_is, :expression, :above_average, :top10, :duplicate_values, :unique_values,
       :contains_text, :not_contains_text, :begins_with, :ends_with,
       :contains_blanks, :not_contains_blanks, :time_period
    formulas = rule[:formulas] || [rule[:formula]].compact
    if formulas.empty?
      parts << "<cfRule #{rule_attrs}/>"
    else
      parts << "<cfRule #{rule_attrs}>"
      formulas.each { |f| parts << "<formula>#{xml_escape(f)}</formula>" }
      parts << "</cfRule>"
    end
  when :color_scale
    cs = rule[:color_scale]
    parts << "<cfRule #{rule_attrs}>"
    parts << "<colorScale>"
    cs[:cfvo]&.each do |cfvo|
      cfvo_attrs = %(type="#{cfvo[:type]}")
      cfvo_attrs << %( val="#{cfvo[:val]}") if cfvo[:val]
      cfvo_attrs << ' gte="0"' if cfvo[:gte] == false
      parts << "<cfvo #{cfvo_attrs}/>"
    end
    cs[:colors]&.each { |c| parts << emit_cf_color_xml(c) }
    parts << "</colorScale>"
    parts << "</cfRule>"
  when :data_bar
    db = rule[:data_bar]
    parts << "<cfRule #{rule_attrs}>"
    db_attrs = +""
    db_attrs << %( minLength="#{db[:min_length]}") if db[:min_length]
    db_attrs << %( maxLength="#{db[:max_length]}") if db[:max_length]
    db_attrs << %( showValue="#{db[:show_value] ? 1 : 0}") unless db[:show_value].nil?
    parts << "<dataBar#{db_attrs}>"
    db[:cfvo]&.each do |cfvo|
      cfvo_attrs = %(type="#{cfvo[:type]}")
      cfvo_attrs << %( val="#{cfvo[:val]}") if cfvo[:val]
      cfvo_attrs << ' gte="0"' if cfvo[:gte] == false
      parts << "<cfvo #{cfvo_attrs}/>"
    end
    parts << emit_cf_color_xml(db[:color]) if db[:color]
    parts << "</dataBar>"
    parts << "</cfRule>"
  when :icon_set
    is = rule[:icon_set]
    parts << "<cfRule #{rule_attrs}>"
    is_attrs = +""
    is_attrs << %( iconSet="#{is[:icon_set]}") if is[:icon_set]
    is_attrs << %( reverse="#{is[:reverse] ? 1 : 0}") unless is[:reverse].nil?
    is_attrs << %( percent="#{is[:percent] ? 1 : 0}") unless is[:percent].nil?
    is_attrs << %( showValue="#{is[:show_value] ? 1 : 0}") unless is[:show_value].nil?
    parts << "<iconSet#{is_attrs}>"
    is[:cfvo]&.each do |cfvo|
      cfvo_attrs = %(type="#{cfvo[:type]}")
      cfvo_attrs << %( val="#{cfvo[:val]}") if cfvo[:val]
      cfvo_attrs << ' gte="0"' if cfvo[:gte] == false
      parts << "<cfvo #{cfvo_attrs}/>"
    end
    parts << "</iconSet>"
    parts << "</cfRule>"
  else
    parts << "<cfRule #{rule_attrs}/>"
  end
end

#emit_color_xml(source, tag: "color") ⇒ Object

: (untyped source, ?tag: ::String) -> (::String | ::String | ::String | ::String | "")

Parameters:

  • source (Object)
  • tag: (Object) (defaults to: "color")

Returns:

  • (Object)


5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
# File 'lib/xlsxrb/ooxml/writer.rb', line 5461

def emit_color_xml(source, tag: "color")
  if source[:auto]
    %(<#{tag} auto="1"/>)
  elsif source[:color] || source[:rgb]
    %(<#{tag} rgb="#{source[:color] || source[:rgb]}"/>)
  elsif source[:theme]
    attrs = [%(theme="#{source[:theme]}")]
    attrs << %(tint="#{source[:tint]}") if source[:tint]
    %(<#{tag} #{attrs.join(" ")}/>)
  elsif source[:indexed]
    %(<#{tag} indexed="#{source[:indexed]}"/>)
  else
    ""
  end
end

#emit_dxf_xml(dxf) ⇒ Object

: (untyped dxf) -> untyped

Parameters:

  • dxf (Object)

Returns:

  • (Object)


5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
# File 'lib/xlsxrb/ooxml/writer.rb', line 5600

def emit_dxf_xml(dxf)
  parts = ["<dxf>"]
  parts << emit_font_xml(dxf[:font]) if dxf[:font]
  if dxf[:num_fmt]
    nf = dxf[:num_fmt]
    parts << %(<numFmt numFmtId="#{nf[:num_fmt_id]}" formatCode="#{xml_escape(nf[:format_code])}"/>)
  end
  parts << emit_fill_xml(dxf[:fill]) if dxf[:fill]
  parts << emit_alignment_xml(dxf[:alignment]) if dxf[:alignment]
  parts << emit_border_xml(dxf[:border]) if dxf[:border]
  parts << emit_protection_xml(dxf[:protection]) if dxf[:protection]
  parts << "</dxf>"
  parts.join
end

#emit_fill_color_xml(tag, fill, prefix) ⇒ Object

: (untyped tag, untyped fill, untyped prefix) -> (::String | ::String | ::String | ::String | "")

Parameters:

  • tag (Object)
  • fill (Object)
  • prefix (Object)

Returns:

  • (Object)


5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
# File 'lib/xlsxrb/ooxml/writer.rb', line 5524

def emit_fill_color_xml(tag, fill, prefix)
  if fill[:"#{prefix}_color"]
    %(<#{tag} rgb="#{fill[:"#{prefix}_color"]}"/>)
  elsif fill[:"#{prefix}_color_theme"]
    attrs = [%(theme="#{fill[:"#{prefix}_color_theme"]}")]
    attrs << %(tint="#{fill[:"#{prefix}_color_tint"]}") if fill[:"#{prefix}_color_tint"]
    %(<#{tag} #{attrs.join(" ")}/>)
  elsif fill[:"#{prefix}_color_indexed"]
    %(<#{tag} indexed="#{fill[:"#{prefix}_color_indexed"]}"/>)
  elsif fill[:"#{prefix}_color_auto"]
    %(<#{tag} auto="1"/>)
  else
    ""
  end
end

#emit_fill_xml(fill) ⇒ Object

: (untyped fill) -> (untyped | ::String)

Parameters:

  • fill (Object)

Returns:

  • (Object)


5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
# File 'lib/xlsxrb/ooxml/writer.rb', line 5506

def emit_fill_xml(fill)
  return emit_gradient_fill_xml(fill[:gradient]) if fill[:gradient]

  has_fg = fill[:fg_color] || fill[:fg_color_theme] || fill[:fg_color_indexed] || fill[:fg_color_auto]
  has_bg = fill[:bg_color] || fill[:bg_color_theme] || fill[:bg_color_indexed] || fill[:bg_color_auto]
  return "<fill><patternFill patternType=\"#{fill[:pattern]}\"/></fill>" if fill[:pattern] && !has_fg && !has_bg

  parts = ["<fill>"]
  pt = fill[:pattern] || "solid"
  parts << %(<patternFill patternType="#{pt}">)
  parts << emit_fill_color_xml("fgColor", fill, :fg)
  parts << emit_fill_color_xml("bgColor", fill, :bg)
  parts << "</patternFill>"
  parts << "</fill>"
  parts.join
end

#emit_filter_xml(filter) ⇒ Object

: (untyped filter) -> untyped

Parameters:

  • filter (Object)

Returns:

  • (Object)


5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
# File 'lib/xlsxrb/ooxml/writer.rb', line 5030

def emit_filter_xml(filter)
  case filter[:type]
  when :filters
    attrs = filter[:blank] ? +' blank="1"' : +""
    attrs << %( calendarType="#{filter[:calendar_type]}") if filter[:calendar_type]
    has_values = filter[:values]&.any?
    has_date_groups = filter[:date_group_items]&.any?
    if has_values || has_date_groups
      parts = ["<filters#{attrs}>"]
      filter[:values]&.each { |v| parts << %(<filter val="#{xml_escape(v)}"/>) }
      filter[:date_group_items]&.each do |dg|
        dg_attrs = %(dateTimeGrouping="#{dg[:date_time_grouping]}")
        dg_attrs << %( year="#{dg[:year]}") if dg[:year]
        dg_attrs << %( month="#{dg[:month]}") if dg[:month]
        dg_attrs << %( day="#{dg[:day]}") if dg[:day]
        dg_attrs << %( hour="#{dg[:hour]}") if dg[:hour]
        dg_attrs << %( minute="#{dg[:minute]}") if dg[:minute]
        dg_attrs << %( second="#{dg[:second]}") if dg[:second]
        parts << "<dateGroupItem #{dg_attrs}/>"
      end
      parts << "</filters>"
      parts.join
    else
      "<filters#{attrs}/>"
    end
  when :custom
    if filter[:filters]
      and_attr = filter[:and] ? ' and="1"' : ""
      parts = ["<customFilters#{and_attr}>"]
      filter[:filters].each do |cf|
        parts << %(<customFilter operator="#{cf[:operator]}" val="#{xml_escape(cf[:val])}"/>)
      end
      parts << "</customFilters>"
      parts.join
    else
      %(<customFilters><customFilter operator="#{filter[:operator]}" val="#{xml_escape(filter[:val])}"/></customFilters>)
    end
  when :dynamic
    dyn_attrs = %( type="#{filter[:dynamic_type]}")
    dyn_attrs << %( val="#{filter[:val]}") if filter[:val]
    dyn_attrs << %( valIso="#{filter[:val_iso]}") if filter[:val_iso]
    dyn_attrs << %( maxVal="#{filter[:max_val]}") if filter[:max_val]
    dyn_attrs << %( maxValIso="#{filter[:max_val_iso]}") if filter[:max_val_iso]
    "<dynamicFilter#{dyn_attrs}/>"
  when :top10
    top_attr = filter[:top] ? ' top="1"' : ""
    pct_attr = filter[:percent] ? ' percent="1"' : ""
    fv_attr = filter[:filter_val] ? %( filterVal="#{filter[:filter_val]}") : ""
    %(<top10#{top_attr}#{pct_attr} val="#{filter[:val]}"#{fv_attr}/>)
  when :color_filter
    cf_attrs = %(dxfId="#{filter[:dxf_id]}")
    cf_attrs << ' cellColor="0"' if filter[:cell_color] == false
    %(<colorFilter #{cf_attrs}/>)
  when :icon_filter
    if_attrs = %(iconSet="#{filter[:icon_set]}")
    if_attrs << %( iconId="#{filter[:icon_id]}") if filter[:icon_id]
    %(<iconFilter #{if_attrs}/>)
  else
    ""
  end
end

#emit_font_xml(font) ⇒ Object

: (untyped font) -> untyped

Parameters:

  • font (Object)

Returns:

  • (Object)


5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
# File 'lib/xlsxrb/ooxml/writer.rb', line 5478

def emit_font_xml(font)
  parts = ["<font>"]
  parts << "<b/>" if font[:bold]
  parts << "<i/>" if font[:italic]
  parts << "<strike/>" if font[:strike]
  parts << "<shadow/>" if font[:shadow]
  parts << "<outline/>" if font[:outline]
  parts << "<condense/>" if font[:condense]
  parts << "<extend/>" if font[:extend]
  if font[:underline]
    parts << if font[:underline] == true
               "<u/>"
             else
               %(<u val="#{font[:underline]}"/>)
             end
  end
  parts << %(<vertAlign val="#{font[:vert_align]}"/>) if font[:vert_align]
  parts << %(<sz val="#{font[:sz]}"/>) if font[:sz]
  parts << emit_color_xml(font)
  parts << %(<name val="#{xml_escape(font[:name])}"/>) if font[:name]
  parts << %(<family val="#{font[:family]}"/>) if font[:family]
  parts << %(<charset val="#{font[:charset]}"/>) if font[:charset]
  parts << %(<scheme val="#{font[:scheme]}"/>) if font[:scheme]
  parts << "</font>"
  parts.join
end

#emit_gradient_fill_xml(gradient) ⇒ Object

: (untyped gradient) -> untyped

Parameters:

  • gradient (Object)

Returns:

  • (Object)


5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
# File 'lib/xlsxrb/ooxml/writer.rb', line 5541

def emit_gradient_fill_xml(gradient)
  attrs = []
  attrs << %(type="#{gradient[:type]}") if gradient[:type]
  attrs << %(degree="#{gradient[:degree]}") if gradient[:degree]
  attrs << %(left="#{gradient[:left]}") if gradient[:left]
  attrs << %(right="#{gradient[:right]}") if gradient[:right]
  attrs << %(top="#{gradient[:top]}") if gradient[:top]
  attrs << %(bottom="#{gradient[:bottom]}") if gradient[:bottom]
  parts = ["<fill>"]
  parts << "<gradientFill#{" #{attrs.join(" ")}" unless attrs.empty?}"
  if gradient[:stops]&.any?
    parts[-1] = "#{parts[-1]}>"
    gradient[:stops].each do |stop|
      parts << %(<stop position="#{stop[:position]}">#{emit_color_xml(stop)}</stop>)
    end
    parts << "</gradientFill>"
  else
    parts[-1] = "#{parts[-1]}/>"
  end
  parts << "</fill>"
  parts.join
end

#emit_protection_xml(protection) ⇒ Object

: (untyped protection) -> ::String

Parameters:

  • protection (Object)

Returns:

  • (Object)


5453
5454
5455
5456
5457
5458
# File 'lib/xlsxrb/ooxml/writer.rb', line 5453

def emit_protection_xml(protection)
  attrs = []
  attrs << %(locked="#{protection[:locked] ? "1" : "0"}") unless protection[:locked].nil?
  attrs << %(hidden="#{protection[:hidden] ? "1" : "0"}") unless protection[:hidden].nil?
  "<protection #{attrs.join(" ")}/>"
end

#enumerate_cell_range(start_cell, end_cell) ⇒ Object

: (untyped start_cell, untyped end_cell) -> (::Array | untyped)

Parameters:

  • start_cell (Object)
  • end_cell (Object)

Returns:

  • (Object)


3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
# File 'lib/xlsxrb/ooxml/writer.rb', line 3652

def enumerate_cell_range(start_cell, end_cell)
  sc = start_cell.match(/\A([A-Z]+)(\d+)\z/)
  ec = end_cell.match(/\A([A-Z]+)(\d+)\z/)
  return [start_cell] unless sc && ec

  start_col = column_letter_to_index(sc[1])
  start_row = sc[2].to_i
  end_col = column_letter_to_index(ec[1])
  end_row = ec[2].to_i
  cells = []
  (start_row..end_row).each do |row|
    (start_col..end_col).each do |col|
      cells << "#{index_to_column_letter(col)}#{row}"
    end
  end
  cells
end

Returns external link definitions. : () -> untyped

Returns:

  • (Object)


1630
1631
1632
# File 'lib/xlsxrb/ooxml/writer.rb', line 1630

def external_links
  @external_links.dup
end

#extract_column_letter(cell_address) ⇒ Object

Extracts the column letter(s) from a cell address, e.g. "A" from "A1". : (untyped cell_address) -> untyped

Parameters:

  • cell_address (Object)

Returns:

  • (Object)


5636
5637
5638
# File 'lib/xlsxrb/ooxml/writer.rb', line 5636

def extract_column_letter(cell_address)
  cell_address.match(/^([A-Z]+)/)[1]
end

#extract_row_number(cell_address) ⇒ Object

Extracts the row number from a cell address, e.g. 1 from "A1". : (untyped cell_address) -> untyped

Parameters:

  • cell_address (Object)

Returns:

  • (Object)


5642
5643
5644
# File 'lib/xlsxrb/ooxml/writer.rb', line 5642

def extract_row_number(cell_address)
  cell_address.match(/(\d+)$/)[1].to_i
end

#file_recovery_propertiesObject

Returns file recovery properties hash. : () -> untyped

Returns:

  • (Object)


1055
1056
1057
# File 'lib/xlsxrb/ooxml/writer.rb', line 1055

def file_recovery_properties
  @file_recovery_properties.dup
end

#file_sharingObject

Returns file sharing hash. : () -> untyped

Returns:

  • (Object)


1019
1020
1021
# File 'lib/xlsxrb/ooxml/writer.rb', line 1019

def file_sharing
  @file_sharing.dup
end

#file_versionObject

Returns file version hash. : () -> untyped

Returns:

  • (Object)


1007
1008
1009
# File 'lib/xlsxrb/ooxml/writer.rb', line 1007

def file_version
  @file_version.dup
end

#filter_columns(sheet: nil) ⇒ Object

Returns filter columns for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


379
380
381
382
# File 'lib/xlsxrb/ooxml/writer.rb', line 379

def filter_columns(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @filter_columns[sheet_name] || {}
end

#freeze_pane(sheet: nil) ⇒ Object

Returns freeze pane settings for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


707
708
709
710
# File 'lib/xlsxrb/ooxml/writer.rb', line 707

def freeze_pane(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @freeze_panes[sheet_name]
end

#generate_app_properties_xmlObject

: () -> untyped

Returns:

  • (Object)


5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
# File 'lib/xlsxrb/ooxml/writer.rb', line 5247

def generate_app_properties_xml
  parts = [
    XML_HEADER,
    %(<Properties xmlns="#{APP_NS}" xmlns:vt="#{VT_NS}">)
  ]
  parts << "<Application>#{xml_escape(@app_properties[:application])}</Application>" if @app_properties[:application]
  parts << "<AppVersion>#{xml_escape(@app_properties[:app_version])}</AppVersion>" if @app_properties[:app_version]
  if @app_properties[:heading_pairs] && @app_properties[:titles_of_parts]
    hp = @app_properties[:heading_pairs]
    tp = @app_properties[:titles_of_parts]
    parts << "<HeadingPairs>"
    parts << %(<vt:vector size="#{hp.size * 2}" baseType="variant">)
    hp.each do |label, count|
      parts << "<vt:variant><vt:lpstr>#{xml_escape(label)}</vt:lpstr></vt:variant>"
      parts << "<vt:variant><vt:i4>#{count}</vt:i4></vt:variant>"
    end
    parts << "</vt:vector>"
    parts << "</HeadingPairs>"
    parts << "<TitlesOfParts>"
    parts << %(<vt:vector size="#{tp.size}" baseType="lpstr">)
    tp.each { |t| parts << "<vt:lpstr>#{xml_escape(t)}</vt:lpstr>" }
    parts << "</vt:vector>"
    parts << "</TitlesOfParts>"
  end
  parts << "</Properties>"
  parts.join
end

#generate_calc_chain_xmlObject

: () -> (nil | untyped)

Returns:

  • (Object)


2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
# File 'lib/xlsxrb/ooxml/writer.rb', line 2233

def generate_calc_chain_xml
  chain_entries = []
  @sheet_order.each_with_index do |sheet_name, i|
    @sheets[sheet_name].each do |address, value|
      chain_entries << { ref: address, sheet_id: i + 1 } if value.is_a?(Xlsxrb::Elements::Formula)
    end
  end
  return nil if chain_entries.empty?

  parts = [XML_HEADER, %(<calcChain xmlns="#{SSML_NS}">)]
  chain_entries.each do |entry|
    parts << %(<c r="#{entry[:ref]}" i="#{entry[:sheet_id]}"/>)
  end
  parts << "</calcChain>"
  parts.join
end

#generate_chart_xml(chart) ⇒ Object

: (untyped chart) -> untyped

Parameters:

  • chart (Object)

Returns:

  • (Object)


3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
# File 'lib/xlsxrb/ooxml/writer.rb', line 3759

def generate_chart_xml(chart)
  chart_type = CHART_TYPE_MAP[chart[:type]] || "barChart"
  no_axes = NO_AXIS_CHARTS.include?(chart_type)
  parts = [
    XML_HEADER,
    %(<c:chartSpace xmlns:c="#{C_NS}" xmlns:a="#{A_NS}" xmlns:r="#{DOC_REL_NS}">)
  ]
  rc = chart[:rounded_corners]
  parts << %(<c:roundedCorners val="#{rc ? 1 : 0}"/>) unless rc.nil?
  parts << %(<c:style val="#{chart[:style]}"/>) if chart[:style]
  if (prot = chart[:protection])
    parts << "<c:protection>"
    parts << %(<c:chartObject val="#{prot[:chart_object] ? 1 : 0}"/>) unless prot[:chart_object].nil?
    parts << %(<c:data val="#{prot[:data] ? 1 : 0}"/>) unless prot[:data].nil?
    parts << %(<c:formatting val="#{prot[:formatting] ? 1 : 0}"/>) unless prot[:formatting].nil?
    parts << %(<c:selection val="#{prot[:selection] ? 1 : 0}"/>) unless prot[:selection].nil?
    parts << %(<c:userInterface val="#{prot[:user_interface] ? 1 : 0}"/>) unless prot[:user_interface].nil?
    parts << "</c:protection>"
  end
  parts << "<c:chart>"

  if chart[:title]
    title_spec = chart[:title]
    if chart[:title_font] || chart[:title_fill_color] || chart[:title_no_fill] ||
       chart[:title_line_color] || chart[:title_line_width] || chart[:title_line_dash] ||
       chart[:title_rotation]
      title_spec = { text: title_spec } unless title_spec.is_a?(Hash)
      title_spec[:font] ||= chart[:title_font] if chart[:title_font]
      title_spec[:fill_color] ||= chart[:title_fill_color] if chart[:title_fill_color]
      title_spec[:no_fill] = chart[:title_no_fill] if title_spec[:no_fill].nil? && !chart[:title_no_fill].nil?
      title_spec[:line_color] ||= chart[:title_line_color] if chart[:title_line_color]
      title_spec[:line_width] ||= chart[:title_line_width] if chart[:title_line_width]
      title_spec[:line_dash] ||= chart[:title_line_dash] if chart[:title_line_dash]
      title_spec[:rotation] ||= chart[:title_rotation] if chart[:title_rotation]
    end
    parts << build_chart_title_xml(title_spec, overlay: chart[:title_overlay])
  end
  atd = chart[:auto_title_deleted]
  parts << %(<c:autoTitleDeleted val="#{atd ? 1 : 0}"/>) unless atd.nil?

  if (v3d = chart[:view_3d])
    parts << "<c:view3D>"
    parts << %(<c:rotX val="#{v3d[:rot_x]}"/>) if v3d[:rot_x]
    parts << %(<c:hPercent val="#{v3d[:h_percent]}"/>) if v3d[:h_percent]
    parts << %(<c:rotY val="#{v3d[:rot_y]}"/>) if v3d[:rot_y]
    parts << %(<c:depthPercent val="#{v3d[:depth_percent]}"/>) if v3d[:depth_percent]
    r_ang = v3d[:r_ang_ax]
    parts << %(<c:rAngAx val="#{r_ang ? 1 : 0}"/>) unless r_ang.nil?
    parts << %(<c:perspective val="#{v3d[:perspective]}"/>) if v3d[:perspective]
    parts << "</c:view3D>"
  end

  %i[floor side_wall back_wall].each do |wall_key|
    next unless (wall = chart[wall_key])

    tag = { floor: "floor", side_wall: "sideWall", back_wall: "backWall" }[wall_key]
    parts << "<c:#{tag}><c:spPr>"
    parts << "<a:solidFill>#{srgb_clr_xml(wall[:fill_color])}</a:solidFill>" if wall[:fill_color]
    parts << "<a:noFill/>" if wall[:no_fill]
    if wall[:line_color] || wall[:line_dash]
      w_attr = wall[:line_width] ? %( w="#{wall[:line_width]}") : ""
      w_fill = wall[:line_color] ? %(<a:solidFill>#{srgb_clr_xml(wall[:line_color])}</a:solidFill>) : ""
      w_dash = wall[:line_dash] ? %(<a:prstDash val="#{xml_escape(wall[:line_dash])}"/>) : ""
      parts << "<a:ln#{w_attr}>#{w_fill}#{w_dash}</a:ln>"
    end
    parts << "</c:spPr></c:#{tag}>"
  end

  parts << "<c:plotArea>"
  pa_layout = chart[:plot_area_layout]
  if pa_layout.is_a?(Hash)
    ml_parts = +""
    ml_parts << %(<c:layoutTarget val="#{xml_escape(pa_layout[:target])}"/>) if pa_layout[:target]
    ml_parts << %(<c:xMode val="#{xml_escape(pa_layout[:x_mode])}"/>) if pa_layout[:x_mode]
    ml_parts << %(<c:yMode val="#{xml_escape(pa_layout[:y_mode])}"/>) if pa_layout[:y_mode]
    ml_parts << %(<c:wMode val="#{xml_escape(pa_layout[:w_mode])}"/>) if pa_layout[:w_mode]
    ml_parts << %(<c:hMode val="#{xml_escape(pa_layout[:h_mode])}"/>) if pa_layout[:h_mode]
    ml_parts << %(<c:x val="#{pa_layout[:x]}"/>) if pa_layout[:x]
    ml_parts << %(<c:y val="#{pa_layout[:y]}"/>) if pa_layout[:y]
    ml_parts << %(<c:w val="#{pa_layout[:w]}"/>) if pa_layout[:w]
    ml_parts << %(<c:h val="#{pa_layout[:h]}"/>) if pa_layout[:h]
    parts << if ml_parts.empty?
               "<c:layout/>"
             else
               "<c:layout><c:manualLayout>#{ml_parts}</c:manualLayout></c:layout>"
             end
  else
    parts << "<c:layout/>"
  end
  parts << "<c:#{chart_type}>"
  parts << %(<c:ofPieType val="#{xml_escape(chart[:of_pie_type] || "pie")}"/>) if chart_type == "ofPieChart"
  if %w[barChart bar3DChart].include?(chart_type)
    bd = chart[:bar_dir] || "col"
    gr = chart[:grouping] || "clustered"
    parts << %(<c:barDir val="#{bd}"/><c:grouping val="#{gr}"/>)
  elsif GROUPING_CHARTS.include?(chart_type)
    parts << %(<c:grouping val="#{chart[:grouping] || "standard"}"/>)
  end
  parts << %(<c:scatterStyle val="#{chart[:scatter_style] || "lineMarker"}"/>) if chart_type == "scatterChart"
  parts << %(<c:radarStyle val="#{chart[:radar_style] || "standard"}"/>) if chart_type == "radarChart"
  vc = chart[:vary_colors]
  parts << %(<c:varyColors val="#{vc ? 1 : 0}"/>) unless vc.nil?
  wf = chart[:wireframe]
  parts << %(<c:wireframe val="#{wf ? 1 : 0}"/>) unless wf.nil?

  all_series = chart[:series] || []
  all_series.each_with_index do |ser, idx|
    ser_order = ser[:order] || idx
    parts << "<c:ser><c:idx val=\"#{idx}\"/><c:order val=\"#{ser_order}\"/>"
    parts << "<c:tx><c:strRef><c:f>#{xml_escape(ser[:name])}</c:f>#{str_cache_xml(ser[:name])}</c:strRef></c:tx>" if ser[:name]
    iin = ser[:invert_if_negative]
    parts << %(<c:invertIfNegative val="#{iin ? 1 : 0}"/>) unless iin.nil?
    parts << %(<c:explosion val="#{ser[:explosion]}"/>) if ser[:explosion]
    ser[:data_points]&.each do |dp|
      parts << "<c:dPt><c:idx val=\"#{dp[:idx]}\"/>"
      dp_iin = dp[:invert_if_negative]
      parts << %(<c:invertIfNegative val="#{dp_iin ? 1 : 0}"/>) unless dp_iin.nil?
      if dp[:marker_symbol] || dp[:marker_size] || dp[:marker_fill] || dp[:marker_no_fill] || dp[:marker_line_color] || dp[:marker_line_dash] || dp[:marker_no_line]
        parts << "<c:marker>"
        parts << %(<c:symbol val="#{xml_escape(dp[:marker_symbol])}"/>) if dp[:marker_symbol]
        parts << %(<c:size val="#{dp[:marker_size]}"/>) if dp[:marker_size]
        if dp[:marker_fill] || dp[:marker_no_fill] || dp[:marker_line_color] || dp[:marker_line_dash] || dp[:marker_no_line]
          mk_sp = +""
          mk_sp << "<a:noFill/>" if dp[:marker_no_fill]
          mk_sp << %(<a:solidFill>#{color_xml(dp[:marker_fill])}</a:solidFill>) if dp[:marker_fill]
          if dp[:marker_no_line]
            mk_sp << "<a:ln><a:noFill/></a:ln>"
          elsif dp[:marker_line_color] || dp[:marker_line_dash]
            mk_ln_w = dp[:marker_line_width] ? %( w="#{(dp[:marker_line_width] * 12_700).to_i}") : ""
            mk_ln_f = dp[:marker_line_color] ? %(<a:solidFill>#{color_xml(dp[:marker_line_color])}</a:solidFill>) : ""
            mk_ln_d = dp[:marker_line_dash] ? %(<a:prstDash val="#{xml_escape(dp[:marker_line_dash])}"/>) : ""
            mk_sp << "<a:ln#{mk_ln_w}>#{mk_ln_f}#{mk_ln_d}</a:ln>"
          end
          parts << "<c:spPr>#{mk_sp}</c:spPr>"
        end
        parts << "</c:marker>"
      end
      dp_b3d = dp[:bubble_3d]
      parts << %(<c:bubble3D val="#{dp_b3d ? 1 : 0}"/>) unless dp_b3d.nil?
      parts << %(<c:explosion val="#{dp[:explosion]}"/>) if dp[:explosion]
      dp_sp_children = +""
      dp_sp_children << %(<a:solidFill>#{color_xml(dp[:fill_color])}</a:solidFill>) if dp[:fill_color]
      dp_sp_children << "<a:noFill/>" if dp[:no_fill]
      if dp[:no_line]
        dp_sp_children << "<a:ln><a:noFill/></a:ln>"
      elsif dp[:line_color] || dp[:line_width] || dp[:line_dash]
        dp_ln_attrs = dp[:line_width] ? %( w="#{(dp[:line_width] * 12_700).to_i}") : ""
        dp_ln_fill = dp[:line_color] ? %(<a:solidFill>#{color_xml(dp[:line_color])}</a:solidFill>) : ""
        dp_ln_dash = dp[:line_dash] ? %(<a:prstDash val="#{xml_escape(dp[:line_dash])}"/>) : ""
        dp_sp_children << "<a:ln#{dp_ln_attrs}>#{dp_ln_fill}#{dp_ln_dash}</a:ln>"
      end
      parts << "<c:spPr>#{dp_sp_children}</c:spPr>" unless dp_sp_children.empty?
      parts << "</c:dPt>"
    end
    if ser[:fill_color] || ser[:no_fill] || ser[:line_color] || ser[:no_line] || ser[:line_width] || ser[:line_cap] || ser[:line_join] || ser[:line_dash]
      parts << "<c:spPr>"
      parts << %(<a:solidFill>#{color_xml(ser[:fill_color])}</a:solidFill>) if ser[:fill_color]
      parts << "<a:noFill/>" if ser[:no_fill]
      if ser[:line_color] || ser[:no_line] || ser[:line_width] || ser[:line_cap] || ser[:line_join] || ser[:line_dash]
        lw = ser[:line_width] ? %( w="#{(ser[:line_width] * 12_700).to_i}") : ""
        lc = ser[:line_cap] ? %( cap="#{xml_escape(ser[:line_cap])}") : ""
        parts << "<a:ln#{lw}#{lc}>"
        parts << "<a:noFill/>" if ser[:no_line]
        parts << %(<a:solidFill>#{color_xml(ser[:line_color])}</a:solidFill>) if ser[:line_color]
        parts << %(<a:prstDash val="#{xml_escape(ser[:line_dash])}"/>) if ser[:line_dash]
        case ser[:line_join]
        when "round" then parts << "<a:round/>"
        when "bevel" then parts << "<a:bevel/>"
        when "miter"
          parts << (ser[:line_miter_limit] ? "<a:miter lim=\"#{ser[:line_miter_limit].to_i}\"/>" : "<a:miter/>")
        end
        parts << "</a:ln>"
      end
      parts << "</c:spPr>"
    end
    if ser[:marker_symbol] || ser[:marker_size] || ser[:marker_fill] || ser[:marker_no_fill] || ser[:marker_line_color] || ser[:marker_line_dash] || ser[:marker_no_line]
      parts << "<c:marker>"
      parts << %(<c:symbol val="#{xml_escape(ser[:marker_symbol])}"/>) if ser[:marker_symbol]
      parts << %(<c:size val="#{ser[:marker_size]}"/>) if ser[:marker_size]
      if ser[:marker_fill] || ser[:marker_no_fill] || ser[:marker_line_color] || ser[:marker_line_dash] || ser[:marker_no_line]
        parts << "<c:spPr>"
        parts << "<a:noFill/>" if ser[:marker_no_fill]
        parts << %(<a:solidFill>#{color_xml(ser[:marker_fill])}</a:solidFill>) if ser[:marker_fill]
        if ser[:marker_no_line]
          parts << "<a:ln><a:noFill/></a:ln>"
        elsif ser[:marker_line_color] || ser[:marker_line_dash]
          mk_ln_w = ser[:marker_line_width] ? %( w="#{(ser[:marker_line_width] * 12_700).to_i}") : ""
          mk_ln_f = ser[:marker_line_color] ? %(<a:solidFill>#{color_xml(ser[:marker_line_color])}</a:solidFill>) : ""
          mk_ln_d = ser[:marker_line_dash] ? %(<a:prstDash val="#{xml_escape(ser[:marker_line_dash])}"/>) : ""
          parts << "<a:ln#{mk_ln_w}>#{mk_ln_f}#{mk_ln_d}</a:ln>"
        end
        parts << "</c:spPr>"
      end
      parts << "</c:marker>"
    end
    if (dl = ser[:data_labels] || chart[:data_labels])
      parts << "<c:dLbls>"
      dl[:labels]&.each do |lbl|
        parts << "<c:dLbl>"
        parts << %(<c:idx val="#{lbl[:idx]}"/>)
        if lbl[:delete]
          parts << '<c:delete val="1"/>'
        else
          if (lbl_layout = lbl[:layout])
            ml = +""
            ml << %(<c:x val="#{lbl_layout[:x]}"/>) if lbl_layout[:x]
            ml << %(<c:y val="#{lbl_layout[:y]}"/>) if lbl_layout[:y]
            parts << (ml.empty? ? "<c:layout/>" : "<c:layout><c:manualLayout>#{ml}</c:manualLayout></c:layout>")
          end
          parts << "<c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>#{xml_escape(lbl[:text])}</a:t></a:r></a:p></c:rich></c:tx>" if lbl[:text]
          if lbl[:num_fmt]
            lnf = lbl[:num_fmt]
            lnf_src = lnf[:source_linked] ? ' sourceLinked="1"' : ""
            parts << %(<c:numFmt formatCode="#{xml_escape(lnf[:format_code])}"#{lnf_src}/>)
          end
          lbl_sp = +""
          lbl_sp << %(<a:solidFill>#{color_xml(lbl[:fill_color])}</a:solidFill>) if lbl[:fill_color]
          lbl_sp << "<a:noFill/>" if lbl[:no_fill]
          if lbl[:line_color] || lbl[:line_width] || lbl[:line_dash]
            lbl_lw = lbl[:line_width] ? %( w="#{(lbl[:line_width] * 12_700).to_i}") : ""
            lbl_lf = lbl[:line_color] ? %(<a:solidFill>#{color_xml(lbl[:line_color])}</a:solidFill>) : ""
            lbl_ld = lbl[:line_dash] ? %(<a:prstDash val="#{xml_escape(lbl[:line_dash])}"/>) : ""
            lbl_sp << "<a:ln#{lbl_lw}>#{lbl_lf}#{lbl_ld}</a:ln>"
          end
          parts << "<c:spPr>#{lbl_sp}</c:spPr>" unless lbl_sp.empty?
          parts << build_axis_txpr(nil, lbl[:font]) if lbl[:font]
          parts << %(<c:dLblPos val="#{lbl[:position]}"/>) if lbl[:position]
          parts << "<c:showLegendKey val=\"#{lbl[:show_legend_key] ? 1 : 0}\"/>" unless lbl[:show_legend_key].nil?
          parts << "<c:showVal val=\"#{lbl[:show_val] ? 1 : 0}\"/>" unless lbl[:show_val].nil?
          parts << "<c:showCatName val=\"#{lbl[:show_cat_name] ? 1 : 0}\"/>" unless lbl[:show_cat_name].nil?
          parts << "<c:showSerName val=\"#{lbl[:show_ser_name] ? 1 : 0}\"/>" unless lbl[:show_ser_name].nil?
          parts << "<c:showPercent val=\"#{lbl[:show_percent] ? 1 : 0}\"/>" unless lbl[:show_percent].nil?
          parts << "<c:showBubbleSize val=\"#{lbl[:show_bubble_size] ? 1 : 0}\"/>" unless lbl[:show_bubble_size].nil?
          parts << "<c:separator>#{xml_escape(lbl[:separator])}</c:separator>" if lbl[:separator]
        end
        parts << "</c:dLbl>"
      end
      if dl[:num_fmt]
        nf = dl[:num_fmt]
        nf_src = nf[:source_linked] ? ' sourceLinked="1"' : ""
        parts << %(<c:numFmt formatCode="#{xml_escape(nf[:format_code])}"#{nf_src}/>)
      end
      dl_sp_children = +""
      dl_sp_children << %(<a:solidFill>#{color_xml(dl[:fill_color])}</a:solidFill>) if dl[:fill_color]
      dl_sp_children << "<a:noFill/>" if dl[:no_fill]
      if dl[:line_color] || dl[:line_width] || dl[:line_dash]
        dl_lw = dl[:line_width] ? %( w="#{(dl[:line_width] * 12_700).to_i}") : ""
        dl_lf = dl[:line_color] ? %(<a:solidFill>#{color_xml(dl[:line_color])}</a:solidFill>) : ""
        dl_ld = dl[:line_dash] ? %(<a:prstDash val="#{xml_escape(dl[:line_dash])}"/>) : ""
        dl_sp_children << "<a:ln#{dl_lw}>#{dl_lf}#{dl_ld}</a:ln>"
      end
      parts << "<c:spPr>#{dl_sp_children}</c:spPr>" unless dl_sp_children.empty?
      parts << build_axis_txpr(nil, dl[:font]) if dl[:font]
      parts << %(<c:dLblPos val="#{dl[:position]}"/>) if dl[:position]
      parts << "<c:showLegendKey val=\"#{dl[:show_legend_key] ? 1 : 0}\"/>" unless dl[:show_legend_key].nil?
      parts << "<c:showVal val=\"#{dl[:show_val] ? 1 : 0}\"/>" unless dl[:show_val].nil?
      parts << "<c:showCatName val=\"#{dl[:show_cat_name] ? 1 : 0}\"/>" unless dl[:show_cat_name].nil?
      parts << "<c:showSerName val=\"#{dl[:show_ser_name] ? 1 : 0}\"/>" unless dl[:show_ser_name].nil?
      parts << "<c:showPercent val=\"#{dl[:show_percent] ? 1 : 0}\"/>" unless dl[:show_percent].nil?
      parts << "<c:showBubbleSize val=\"#{dl[:show_bubble_size] ? 1 : 0}\"/>" unless dl[:show_bubble_size].nil?
      parts << "<c:separator>#{xml_escape(dl[:separator])}</c:separator>" if dl[:separator]
      sl = dl[:show_leader_lines]
      parts << "<c:showLeaderLines val=\"#{sl ? 1 : 0}\"/>" unless sl.nil?
      if dl[:leader_lines]
        ll_spec = dl[:leader_lines]
        if ll_spec.is_a?(Hash)
          ll_sp = +""
          if ll_spec[:line_color] || ll_spec[:line_width] || ll_spec[:line_dash]
            ll_lw = ll_spec[:line_width] ? %( w="#{(ll_spec[:line_width] * 12_700).to_i}") : ""
            ll_lf = ll_spec[:line_color] ? %(<a:solidFill>#{color_xml(ll_spec[:line_color])}</a:solidFill>) : ""
            ll_ld = ll_spec[:line_dash] ? %(<a:prstDash val="#{xml_escape(ll_spec[:line_dash])}"/>) : ""
            ll_sp << "<a:ln#{ll_lw}>#{ll_lf}#{ll_ld}</a:ln>"
          end
          parts << (ll_sp.empty? ? "<c:leaderLines/>" : "<c:leaderLines><c:spPr>#{ll_sp}</c:spPr></c:leaderLines>")
        else
          parts << "<c:leaderLines/>"
        end
      end
      parts << "</c:dLbls>"
    end
    trendline_list = ser[:trendlines] || (ser[:trendline] ? [ser[:trendline]] : [])
    trendline_list.each do |tl|
      parts << "<c:trendline>"
      parts << "<c:name>#{xml_escape(tl[:name])}</c:name>" if tl[:name]
      tl_sp_children = +""
      if tl[:line_color] || tl[:line_width] || tl[:line_dash]
        tl_ln_w = tl[:line_width] ? %( w="#{(tl[:line_width] * 12_700).to_i}") : ""
        tl_ln_f = tl[:line_color] ? %(<a:solidFill>#{color_xml(tl[:line_color])}</a:solidFill>) : ""
        tl_ln_d = tl[:line_dash] ? %(<a:prstDash val="#{xml_escape(tl[:line_dash])}"/>) : ""
        tl_sp_children << "<a:ln#{tl_ln_w}>#{tl_ln_f}#{tl_ln_d}</a:ln>"
      end
      parts << "<c:spPr>#{tl_sp_children}</c:spPr>" unless tl_sp_children.empty?
      parts << %(<c:trendlineType val="#{xml_escape(tl[:type] || "linear")}"/>)
      parts << %(<c:order val="#{tl[:order]}"/>) if tl[:order]
      parts << %(<c:period val="#{tl[:period]}"/>) if tl[:period]
      parts << %(<c:forward val="#{tl[:forward]}"/>) if tl[:forward]
      parts << %(<c:backward val="#{tl[:backward]}"/>) if tl[:backward]
      parts << %(<c:intercept val="#{tl[:intercept]}"/>) if tl[:intercept]
      parts << %(<c:dispRSqr val="#{tl[:disp_r_sqr] ? 1 : 0}"/>) unless tl[:disp_r_sqr].nil?
      parts << %(<c:dispEq val="#{tl[:disp_eq] ? 1 : 0}"/>) unless tl[:disp_eq].nil?
      if tl[:label]
        lbl = tl[:label]
        parts << "<c:trendlineLbl>"
        parts << build_title_layout_xml(lbl[:layout])
        parts << "<c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>#{xml_escape(lbl[:text])}</a:t></a:r></a:p></c:rich></c:tx>" if lbl[:text]
        if lbl[:num_fmt]
          nf = lbl[:num_fmt]
          nf_src = nf.is_a?(Hash) ? nf : { format_code: nf }
          nf_linked = if nf_src.key?(:source_linked)
                        nf_src[:source_linked] ? 1 : 0
                      else
                        0
                      end
          parts << %(<c:numFmt formatCode="#{xml_escape(nf_src[:format_code])}" sourceLinked="#{nf_linked}"/>)
        end
        tll_sp = +""
        tll_sp << %(<a:solidFill>#{color_xml(lbl[:fill_color])}</a:solidFill>) if lbl[:fill_color]
        tll_sp << "<a:noFill/>" if lbl[:no_fill]
        if lbl[:line_color] || lbl[:line_width] || lbl[:line_dash]
          tll_lw = lbl[:line_width] ? %( w="#{(lbl[:line_width] * 12_700).to_i}") : ""
          tll_lf = lbl[:line_color] ? %(<a:solidFill>#{color_xml(lbl[:line_color])}</a:solidFill>) : ""
          tll_ld = lbl[:line_dash] ? %(<a:prstDash val="#{xml_escape(lbl[:line_dash])}"/>) : ""
          tll_sp << "<a:ln#{tll_lw}>#{tll_lf}#{tll_ld}</a:ln>"
        end
        parts << "<c:spPr>#{tll_sp}</c:spPr>" unless tll_sp.empty?
        parts << build_axis_txpr(nil, lbl[:font]) if lbl[:font]
        parts << "</c:trendlineLbl>"
      end
      parts << "</c:trendline>"
    end
    err_bars_list = ser[:error_bars_list] || (ser[:error_bars] ? [ser[:error_bars]] : [])
    err_bars_list.each do |eb|
      parts << "<c:errBars>"
      parts << %(<c:errDir val="#{xml_escape(eb[:direction])}"/>) if eb[:direction]
      parts << %(<c:errBarType val="#{xml_escape(eb[:bar_type] || "both")}"/>)
      parts << %(<c:errValType val="#{xml_escape(eb[:val_type] || "fixedVal")}"/>)
      parts << %(<c:noEndCap val="#{eb[:no_end_cap] ? 1 : 0}"/>) unless eb[:no_end_cap].nil?
      parts << "<c:plus><c:numRef><c:f>#{xml_escape(eb[:plus])}</c:f></c:numRef></c:plus>" if eb[:plus]
      parts << "<c:minus><c:numRef><c:f>#{xml_escape(eb[:minus])}</c:f></c:numRef></c:minus>" if eb[:minus]
      parts << %(<c:val val="#{eb[:val]}"/>) if eb[:val]
      eb_sp_children = +""
      eb_sp_children << %(<a:solidFill>#{color_xml(eb[:fill_color])}</a:solidFill>) if eb[:fill_color]
      eb_sp_children << "<a:noFill/>" if eb[:no_fill]
      if eb[:line_color] || eb[:line_width] || eb[:line_dash]
        eb_ln_w = eb[:line_width] ? %( w="#{(eb[:line_width] * 12_700).to_i}") : ""
        eb_ln_f = eb[:line_color] ? %(<a:solidFill>#{color_xml(eb[:line_color])}</a:solidFill>) : ""
        eb_ln_d = eb[:line_dash] ? %(<a:prstDash val="#{xml_escape(eb[:line_dash])}"/>) : ""
        eb_sp_children << "<a:ln#{eb_ln_w}>#{eb_ln_f}#{eb_ln_d}</a:ln>"
      end
      parts << "<c:spPr>#{eb_sp_children}</c:spPr>" unless eb_sp_children.empty?
      parts << "</c:errBars>"
    end
    uses_xy = %w[scatterChart bubbleChart].include?(chart_type)
    cat_tag = uses_xy ? "xVal" : "cat"
    val_tag = uses_xy ? "yVal" : "val"
    if ser[:cat_ref]
      parts << if uses_xy || ser[:cat_ref_type] == :num
                 "<c:#{cat_tag}><c:numRef><c:f>#{xml_escape(ser[:cat_ref])}</c:f>#{num_cache_xml(ser[:cat_ref])}</c:numRef></c:#{cat_tag}>"
               else
                 "<c:#{cat_tag}><c:strRef><c:f>#{xml_escape(ser[:cat_ref])}</c:f>#{str_cache_xml(ser[:cat_ref])}</c:strRef></c:#{cat_tag}>"
               end
    end
    parts << "<c:#{val_tag}><c:numRef><c:f>#{xml_escape(ser[:val_ref])}</c:f>#{num_cache_xml(ser[:val_ref])}</c:numRef></c:#{val_tag}>" if ser[:val_ref]
    parts << "<c:bubbleSize><c:numRef><c:f>#{xml_escape(ser[:bubble_size_ref])}</c:f>#{num_cache_xml(ser[:bubble_size_ref])}</c:numRef></c:bubbleSize>" if ser[:bubble_size_ref]
    parts << %(<c:smooth val="#{ser[:smooth] ? 1 : 0}"/>) unless ser[:smooth].nil?
    parts << %(<c:shape val="#{xml_escape(ser[:shape])}"/>) if ser[:shape]
    parts << "</c:ser>"
  end

  if chart[:band_fmts]
    parts << "<c:bandFmts>"
    chart[:band_fmts].each do |bf|
      parts << "<c:bandFmt><c:idx val=\"#{bf[:idx]}\"/>"
      bf_sp = +""
      bf_sp << %(<a:solidFill>#{color_xml(bf[:fill_color])}</a:solidFill>) if bf[:fill_color]
      bf_sp << "<a:noFill/>" if bf[:no_fill]
      if bf[:line_color] || bf[:line_width] || bf[:line_dash]
        bf_lw = bf[:line_width] ? %( w="#{(bf[:line_width] * 12_700).to_i}") : ""
        bf_lf = bf[:line_color] ? %(<a:solidFill>#{color_xml(bf[:line_color])}</a:solidFill>) : ""
        bf_ld = bf[:line_dash] ? %(<a:prstDash val="#{xml_escape(bf[:line_dash])}"/>) : ""
        bf_sp << "<a:ln#{bf_lw}>#{bf_lf}#{bf_ld}</a:ln>"
      end
      parts << "<c:spPr>#{bf_sp}</c:spPr>" unless bf_sp.empty?
      parts << "</c:bandFmt>"
    end
    parts << "</c:bandFmts>"
  end

  parts << %(<c:gapWidth val="#{chart[:gap_width]}"/>) if chart[:gap_width]
  parts << %(<c:splitType val="#{xml_escape(chart[:split_type])}"/>) if chart[:split_type]
  parts << %(<c:splitPos val="#{chart[:split_pos]}"/>) if chart[:split_pos]
  if chart[:cust_split]&.any?
    parts << "<c:custSplit>"
    chart[:cust_split].each { |idx| parts << %(<c:secondPiePt val="#{idx}"/>) }
    parts << "</c:custSplit>"
  end
  parts << %(<c:secondPieSize val="#{chart[:second_pie_size]}"/>) if chart[:second_pie_size]
  parts << %(<c:gapDepth val="#{chart[:gap_depth]}"/>) if chart[:gap_depth]
  parts << %(<c:overlap val="#{chart[:overlap]}"/>) if chart[:overlap]
  parts << %(<c:shape val="#{chart[:bar_shape]}"/>) if chart[:bar_shape]
  b3d = chart[:bubble_3d]
  parts << %(<c:bubble3D val="#{b3d ? 1 : 0}"/>) unless b3d.nil?
  parts << %(<c:bubbleScale val="#{chart[:bubble_scale]}"/>) if chart[:bubble_scale]
  snb = chart[:show_neg_bubbles]
  parts << %(<c:showNegBubbles val="#{snb ? 1 : 0}"/>) unless snb.nil?
  parts << %(<c:sizeRepresents val="#{chart[:size_represents]}"/>) if chart[:size_represents]
  parts << %(<c:firstSliceAng val="#{chart[:first_slice_ang]}"/>) if chart[:first_slice_ang]
  parts << %(<c:holeSize val="#{chart[:hole_size]}"/>) if chart[:hole_size]
  if chart[:ser_lines]
    sl_spec = chart[:ser_lines]
    if sl_spec.is_a?(Hash)
      sl_sp = +""
      if sl_spec[:line_color] || sl_spec[:line_width] || sl_spec[:line_dash]
        sl_lw = sl_spec[:line_width] ? %( w="#{(sl_spec[:line_width] * 12_700).to_i}") : ""
        sl_lf = sl_spec[:line_color] ? %(<a:solidFill>#{color_xml(sl_spec[:line_color])}</a:solidFill>) : ""
        sl_ld = sl_spec[:line_dash] ? %(<a:prstDash val="#{xml_escape(sl_spec[:line_dash])}"/>) : ""
        sl_sp << "<a:ln#{sl_lw}>#{sl_lf}#{sl_ld}</a:ln>"
      end
      parts << (sl_sp.empty? ? "<c:serLines/>" : "<c:serLines><c:spPr>#{sl_sp}</c:spPr></c:serLines>")
    else
      parts << "<c:serLines/>"
    end
  end
  if chart[:drop_lines]
    dl_spec = chart[:drop_lines]
    if dl_spec.is_a?(Hash)
      dl_sp = +""
      if dl_spec[:line_color] || dl_spec[:line_width] || dl_spec[:line_dash]
        dl_lw = dl_spec[:line_width] ? %( w="#{(dl_spec[:line_width] * 12_700).to_i}") : ""
        dl_lf = dl_spec[:line_color] ? %(<a:solidFill>#{color_xml(dl_spec[:line_color])}</a:solidFill>) : ""
        dl_ld = dl_spec[:line_dash] ? %(<a:prstDash val="#{xml_escape(dl_spec[:line_dash])}"/>) : ""
        dl_sp << "<a:ln#{dl_lw}>#{dl_lf}#{dl_ld}</a:ln>"
      end
      parts << (dl_sp.empty? ? "<c:dropLines/>" : "<c:dropLines><c:spPr>#{dl_sp}</c:spPr></c:dropLines>")
    else
      parts << "<c:dropLines/>"
    end
  end
  if chart[:hi_low_lines]
    hl_spec = chart[:hi_low_lines]
    if hl_spec.is_a?(Hash)
      hl_sp = +""
      if hl_spec[:line_color] || hl_spec[:line_width] || hl_spec[:line_dash]
        hl_lw = hl_spec[:line_width] ? %( w="#{(hl_spec[:line_width] * 12_700).to_i}") : ""
        hl_lf = hl_spec[:line_color] ? %(<a:solidFill>#{color_xml(hl_spec[:line_color])}</a:solidFill>) : ""
        hl_ld = hl_spec[:line_dash] ? %(<a:prstDash val="#{xml_escape(hl_spec[:line_dash])}"/>) : ""
        hl_sp << "<a:ln#{hl_lw}>#{hl_lf}#{hl_ld}</a:ln>"
      end
      parts << (hl_sp.empty? ? "<c:hiLowLines/>" : "<c:hiLowLines><c:spPr>#{hl_sp}</c:spPr></c:hiLowLines>")
    else
      parts << "<c:hiLowLines/>"
    end
  end
  if chart[:up_down_bars]
    udb = chart[:up_down_bars]
    parts << "<c:upDownBars>"
    parts << %(<c:gapWidth val="#{udb[:gap_width]}"/>) if udb.is_a?(Hash) && udb[:gap_width]
    %i[up_bars down_bars].each do |bar_key|
      tag = bar_key == :up_bars ? "upBars" : "downBars"
      bar = udb.is_a?(Hash) ? udb[bar_key] : nil
      if bar
        bar_sp = +""
        bar_sp << %(<a:solidFill>#{color_xml(bar[:fill_color])}</a:solidFill>) if bar[:fill_color]
        bar_sp << "<a:noFill/>" if bar[:no_fill]
        if bar[:line_color] || bar[:line_width] || bar[:line_dash]
          b_lw = bar[:line_width] ? %( w="#{(bar[:line_width] * 12_700).to_i}") : ""
          b_lf = bar[:line_color] ? %(<a:solidFill>#{color_xml(bar[:line_color])}</a:solidFill>) : ""
          b_ld = bar[:line_dash] ? %(<a:prstDash val="#{xml_escape(bar[:line_dash])}"/>) : ""
          bar_sp << "<a:ln#{b_lw}>#{b_lf}#{b_ld}</a:ln>"
        end
        parts << (bar_sp.empty? ? "<c:#{tag}/>" : "<c:#{tag}><c:spPr>#{bar_sp}</c:spPr></c:#{tag}>")
      else
        parts << "<c:#{tag}/>"
      end
    end
    parts << "</c:upDownBars>"
  end
  mk = chart[:marker]
  parts << %(<c:marker val="#{mk ? 1 : 0}"/>) unless mk.nil?
  sm = chart[:smooth]
  parts << %(<c:smooth val="#{sm ? 1 : 0}"/>) unless sm.nil?
  three_axes = THREE_AXIS_CHARTS.include?(chart_type)
  unless no_axes
    parts << '<c:axId val="1"/><c:axId val="2"/>'
    parts << '<c:axId val="3"/>' if three_axes
  end
  parts << "</c:#{chart_type}>"

  unless no_axes
    cat_del = chart[:cat_axis_delete] ? 1 : 0
    cat_orient = chart[:cat_axis_orientation] || "minMax"
    cat_ax_tag = chart[:cat_axis_type] == :date ? "dateAx" : "catAx"
    parts << %(<c:#{cat_ax_tag}><c:axId val="1"/><c:scaling>)
    parts << %(<c:logBase val="#{chart[:cat_axis_log_base]}"/>) if chart[:cat_axis_log_base]
    parts << %(<c:orientation val="#{cat_orient}"/>)
    parts << %(<c:max val="#{chart[:cat_axis_scaling_max]}"/>) if chart[:cat_axis_scaling_max]
    parts << %(<c:min val="#{chart[:cat_axis_scaling_min]}"/>) if chart[:cat_axis_scaling_min]
    parts << %(</c:scaling><c:delete val="#{cat_del}"/><c:axPos val="#{chart[:cat_axis_pos] || "b"}"/>)
    parts << gridlines_xml("majorGridlines", chart[:cat_axis_major_gridlines])
    parts << gridlines_xml("minorGridlines", chart[:cat_axis_minor_gridlines])
    if chart[:cat_axis_title]
      cat_title_spec = merge_flat_title_styling(chart[:cat_axis_title], chart, :cat_axis_title)
      parts << build_chart_title_xml(cat_title_spec)
    end
    if (cnf = chart[:cat_axis_num_fmt])
      sl = cnf[:source_linked] ? 1 : 0
      parts << %(<c:numFmt formatCode="#{xml_escape(cnf[:format_code])}" sourceLinked="#{sl}"/>)
    end
    parts << %(<c:majorTickMark val="#{chart[:cat_axis_major_tick_mark]}"/>) if chart[:cat_axis_major_tick_mark]
    parts << %(<c:minorTickMark val="#{chart[:cat_axis_minor_tick_mark]}"/>) if chart[:cat_axis_minor_tick_mark]
    parts << %(<c:tickLblPos val="#{chart[:cat_axis_tick_lbl_pos]}"/>) if chart[:cat_axis_tick_lbl_pos]
    if chart[:cat_axis_line_color] || chart[:cat_axis_fill] || chart[:cat_axis_no_fill] || chart[:cat_axis_line_dash]
      parts << "<c:spPr>"
      parts << "<a:noFill/>" if chart[:cat_axis_no_fill]
      parts << %(<a:solidFill>#{color_xml(chart[:cat_axis_fill])}</a:solidFill>) if chart[:cat_axis_fill]
      if chart[:cat_axis_line_color] || chart[:cat_axis_line_dash]
        w_attr = chart[:cat_axis_line_width] ? %( w="#{chart[:cat_axis_line_width]}") : ""
        ca_ln_f = chart[:cat_axis_line_color] ? %(<a:solidFill>#{srgb_clr_xml(chart[:cat_axis_line_color])}</a:solidFill>) : ""
        ca_ln_d = chart[:cat_axis_line_dash] ? %(<a:prstDash val="#{xml_escape(chart[:cat_axis_line_dash])}"/>) : ""
        parts << "<a:ln#{w_attr}>#{ca_ln_f}#{ca_ln_d}</a:ln>"
      end
      parts << "</c:spPr>"
    end
    parts << build_axis_txpr(chart[:cat_axis_label_rotation], chart[:cat_axis_font])
    parts << '<c:crossAx val="2"/>'
    parts << %(<c:crosses val="#{chart[:cat_axis_crosses]}"/>) if chart[:cat_axis_crosses]
    parts << %(<c:crossesAt val="#{chart[:cat_axis_crosses_at]}"/>) if !chart[:cat_axis_crosses] && chart[:cat_axis_crosses_at]
    ca_auto = chart[:cat_axis_auto]
    parts << %(<c:auto val="#{ca_auto ? 1 : 0}"/>) unless ca_auto.nil?
    parts << %(<c:lblAlgn val="#{xml_escape(chart[:cat_axis_lbl_algn])}"/>) if chart[:cat_axis_lbl_algn]
    parts << %(<c:lblOffset val="#{chart[:cat_axis_lbl_offset]}"/>) if chart[:cat_axis_lbl_offset]
    parts << %(<c:tickLblSkip val="#{chart[:cat_axis_tick_lbl_skip]}"/>) if chart[:cat_axis_tick_lbl_skip]
    parts << %(<c:tickMarkSkip val="#{chart[:cat_axis_tick_mark_skip]}"/>) if chart[:cat_axis_tick_mark_skip]
    nml = chart[:cat_axis_no_multi_lvl_lbl]
    parts << %(<c:noMultiLvlLbl val="#{nml ? 1 : 0}"/>) unless nml.nil?
    if cat_ax_tag == "dateAx"
      parts << %(<c:baseTimeUnit val="#{chart[:cat_axis_base_time_unit]}"/>) if chart[:cat_axis_base_time_unit]
      parts << %(<c:majorUnit val="#{chart[:cat_axis_major_unit]}"/>) if chart[:cat_axis_major_unit]
      parts << %(<c:majorTimeUnit val="#{chart[:cat_axis_major_time_unit]}"/>) if chart[:cat_axis_major_time_unit]
      parts << %(<c:minorUnit val="#{chart[:cat_axis_minor_unit]}"/>) if chart[:cat_axis_minor_unit]
      parts << %(<c:minorTimeUnit val="#{chart[:cat_axis_minor_time_unit]}"/>) if chart[:cat_axis_minor_time_unit]
    end
    parts << "</c:#{cat_ax_tag}>"
    val_del = chart[:val_axis_delete] ? 1 : 0
    val_orient = chart[:val_axis_orientation] || "minMax"
    parts << %(<c:valAx><c:axId val="2"/><c:scaling>)
    parts << %(<c:logBase val="#{chart[:val_axis_log_base]}"/>) if chart[:val_axis_log_base]
    parts << %(<c:orientation val="#{val_orient}"/>)
    parts << %(<c:max val="#{chart[:val_axis_scaling_max]}"/>) if chart[:val_axis_scaling_max]
    parts << %(<c:min val="#{chart[:val_axis_scaling_min]}"/>) if chart[:val_axis_scaling_min]
    parts << %(</c:scaling><c:delete val="#{val_del}"/><c:axPos val="#{chart[:val_axis_pos] || "l"}"/>)
    parts << gridlines_xml("majorGridlines", chart[:val_axis_major_gridlines])
    parts << gridlines_xml("minorGridlines", chart[:val_axis_minor_gridlines])
    if chart[:val_axis_title]
      val_title_spec = merge_flat_title_styling(chart[:val_axis_title], chart, :val_axis_title)
      parts << build_chart_title_xml(val_title_spec)
    end
    if (vnf = chart[:val_axis_num_fmt])
      sl = vnf[:source_linked] ? 1 : 0
      parts << %(<c:numFmt formatCode="#{xml_escape(vnf[:format_code])}" sourceLinked="#{sl}"/>)
    end
    parts << %(<c:majorTickMark val="#{chart[:val_axis_major_tick_mark]}"/>) if chart[:val_axis_major_tick_mark]
    parts << %(<c:minorTickMark val="#{chart[:val_axis_minor_tick_mark]}"/>) if chart[:val_axis_minor_tick_mark]
    parts << %(<c:tickLblPos val="#{chart[:val_axis_tick_lbl_pos]}"/>) if chart[:val_axis_tick_lbl_pos]
    if chart[:val_axis_line_color] || chart[:val_axis_fill] || chart[:val_axis_no_fill] || chart[:val_axis_line_dash]
      parts << "<c:spPr>"
      parts << "<a:noFill/>" if chart[:val_axis_no_fill]
      parts << %(<a:solidFill>#{color_xml(chart[:val_axis_fill])}</a:solidFill>) if chart[:val_axis_fill]
      if chart[:val_axis_line_color] || chart[:val_axis_line_dash]
        w_attr = chart[:val_axis_line_width] ? %( w="#{chart[:val_axis_line_width]}") : ""
        va_ln_f = chart[:val_axis_line_color] ? %(<a:solidFill>#{srgb_clr_xml(chart[:val_axis_line_color])}</a:solidFill>) : ""
        va_ln_d = chart[:val_axis_line_dash] ? %(<a:prstDash val="#{xml_escape(chart[:val_axis_line_dash])}"/>) : ""
        parts << "<a:ln#{w_attr}>#{va_ln_f}#{va_ln_d}</a:ln>"
      end
      parts << "</c:spPr>"
    end
    parts << build_axis_txpr(chart[:val_axis_label_rotation], chart[:val_axis_font])
    parts << '<c:crossAx val="1"/>'
    parts << %(<c:crosses val="#{chart[:val_axis_crosses]}"/>) if chart[:val_axis_crosses]
    parts << %(<c:crossesAt val="#{chart[:val_axis_crosses_at]}"/>) if !chart[:val_axis_crosses] && chart[:val_axis_crosses_at]
    parts << %(<c:crossBetween val="#{chart[:val_axis_cross_between]}"/>) if chart[:val_axis_cross_between]
    parts << %(<c:majorUnit val="#{chart[:val_axis_major_unit]}"/>) if chart[:val_axis_major_unit]
    parts << %(<c:minorUnit val="#{chart[:val_axis_minor_unit]}"/>) if chart[:val_axis_minor_unit]
    if chart[:val_axis_disp_units]
      du = chart[:val_axis_disp_units]
      if du.is_a?(Hash)
        parts << "<c:dispUnits>"
        parts << %(<c:builtInUnit val="#{xml_escape(du[:built_in_unit])}"/>) if du[:built_in_unit]
        parts << %(<c:custUnit val="#{du[:cust_unit]}"/>) if du[:cust_unit]
        if du[:label]
          dul = du[:label]
          parts << "<c:dispUnitsLbl>"
          if dul[:num_fmt]
            nf = dul[:num_fmt]
            nf_src = nf.is_a?(Hash) ? nf : { format_code: nf }
            nf_linked = if nf_src.key?(:source_linked)
                          nf_src[:source_linked] ? 1 : 0
                        else
                          0
                        end
            parts << %(<c:numFmt formatCode="#{xml_escape(nf_src[:format_code])}" sourceLinked="#{nf_linked}"/>)
          end
          dul_sp = +""
          dul_sp << %(<a:solidFill>#{color_xml(dul[:fill_color])}</a:solidFill>) if dul[:fill_color]
          dul_sp << "<a:noFill/>" if dul[:no_fill]
          if dul[:line_color] || dul[:line_width] || dul[:line_dash]
            dul_lw = dul[:line_width] ? %( w="#{(dul[:line_width] * 12_700).to_i}") : ""
            dul_lf = dul[:line_color] ? %(<a:solidFill>#{color_xml(dul[:line_color])}</a:solidFill>) : ""
            dul_ld = dul[:line_dash] ? %(<a:prstDash val="#{xml_escape(dul[:line_dash])}"/>) : ""
            dul_sp << "<a:ln#{dul_lw}>#{dul_lf}#{dul_ld}</a:ln>"
          end
          parts << "<c:spPr>#{dul_sp}</c:spPr>" unless dul_sp.empty?
          parts << build_axis_txpr(nil, dul[:font]) if dul[:font]
          parts << "</c:dispUnitsLbl>"
        end
        parts << "</c:dispUnits>"
      else
        parts << %(<c:dispUnits><c:builtInUnit val="#{xml_escape(du.to_s)}"/></c:dispUnits>)
      end
    end
    parts << "</c:valAx>"

    if three_axes
      parts << '<c:serAx><c:axId val="3"/><c:scaling><c:orientation val="minMax"/></c:scaling>'
      parts << '<c:delete val="0"/><c:axPos val="b"/><c:crossAx val="2"/></c:serAx>'
    end
  end

  if chart[:data_table]
    dt = chart[:data_table]
    parts << "<c:dTable>"
    parts << %(<c:showHorzBorder val="#{dt[:show_horz_border] ? 1 : 0}"/>) unless dt[:show_horz_border].nil?
    parts << %(<c:showVertBorder val="#{dt[:show_vert_border] ? 1 : 0}"/>) unless dt[:show_vert_border].nil?
    parts << %(<c:showOutline val="#{dt[:show_outline] ? 1 : 0}"/>) unless dt[:show_outline].nil?
    parts << %(<c:showKeys val="#{dt[:show_keys] ? 1 : 0}"/>) unless dt[:show_keys].nil?
    dt_sp_children = +""
    dt_sp_children << %(<a:solidFill>#{color_xml(dt[:fill_color])}</a:solidFill>) if dt[:fill_color]
    dt_sp_children << "<a:noFill/>" if dt[:no_fill]
    if dt[:line_color] || dt[:line_width] || dt[:line_dash]
      dt_ln_w = dt[:line_width] ? %( w="#{(dt[:line_width] * 12_700).to_i}") : ""
      dt_ln_f = dt[:line_color] ? %(<a:solidFill>#{color_xml(dt[:line_color])}</a:solidFill>) : ""
      dt_ln_d = dt[:line_dash] ? %(<a:prstDash val="#{xml_escape(dt[:line_dash])}"/>) : ""
      dt_sp_children << "<a:ln#{dt_ln_w}>#{dt_ln_f}#{dt_ln_d}</a:ln>"
    end
    parts << "<c:spPr>#{dt_sp_children}</c:spPr>" unless dt_sp_children.empty?
    parts << build_axis_txpr(nil, dt[:font]) if dt[:font]
    parts << "</c:dTable>"
  end

  if chart[:plot_area_fill] || chart[:plot_area_no_fill] || chart[:plot_area_line_color] || chart[:plot_area_line_dash]
    pa_sp = +""
    pa_sp << %(<a:solidFill>#{color_xml(chart[:plot_area_fill])}</a:solidFill>) if chart[:plot_area_fill]
    pa_sp << "<a:noFill/>" if chart[:plot_area_no_fill]
    if chart[:plot_area_line_color] || chart[:plot_area_line_dash]
      pa_ln_w = chart[:plot_area_line_width] ? %( w="#{chart[:plot_area_line_width].to_i}") : ""
      pa_ln_f = chart[:plot_area_line_color] ? %(<a:solidFill>#{color_xml(chart[:plot_area_line_color])}</a:solidFill>) : ""
      pa_ln_d = chart[:plot_area_line_dash] ? %(<a:prstDash val="#{xml_escape(chart[:plot_area_line_dash])}"/>) : ""
      pa_sp << "<a:ln#{pa_ln_w}>#{pa_ln_f}#{pa_ln_d}</a:ln>"
    end
    parts << "<c:spPr>#{pa_sp}</c:spPr>"
  end

  parts << "</c:plotArea>"
  legend_pos = chart.dig(:legend, :position) || "r"
  legend_overlay = chart.dig(:legend, :overlay)
  parts << %(<c:legend><c:legendPos val="#{legend_pos}"/>)
  legend_entries = chart.dig(:legend, :entries)
  legend_entries&.each do |entry|
    parts << %(<c:legendEntry><c:idx val="#{entry[:idx]}"/>)
    if !entry[:delete].nil?
      parts << %(<c:delete val="#{entry[:delete] ? 1 : 0}"/>)
    elsif entry[:font]
      parts << build_axis_txpr(nil, entry[:font])
    end
    parts << "</c:legendEntry>"
  end
  legend_layout = chart.dig(:legend, :layout)
  if legend_layout.is_a?(Hash)
    ml_parts = +""
    ml_parts << %(<c:layoutTarget val="#{xml_escape(legend_layout[:target])}"/>) if legend_layout[:target]
    ml_parts << %(<c:xMode val="#{xml_escape(legend_layout[:x_mode])}"/>) if legend_layout[:x_mode]
    ml_parts << %(<c:yMode val="#{xml_escape(legend_layout[:y_mode])}"/>) if legend_layout[:y_mode]
    ml_parts << %(<c:wMode val="#{xml_escape(legend_layout[:w_mode])}"/>) if legend_layout[:w_mode]
    ml_parts << %(<c:hMode val="#{xml_escape(legend_layout[:h_mode])}"/>) if legend_layout[:h_mode]
    ml_parts << %(<c:x val="#{legend_layout[:x]}"/>) if legend_layout[:x]
    ml_parts << %(<c:y val="#{legend_layout[:y]}"/>) if legend_layout[:y]
    ml_parts << %(<c:w val="#{legend_layout[:w]}"/>) if legend_layout[:w]
    ml_parts << %(<c:h val="#{legend_layout[:h]}"/>) if legend_layout[:h]
    parts << "<c:layout><c:manualLayout>#{ml_parts}</c:manualLayout></c:layout>" unless ml_parts.empty?
  end
  parts << %(<c:overlay val="#{legend_overlay ? 1 : 0}"/>) unless legend_overlay.nil?
  leg_sp_children = +""
  leg_fill = chart.dig(:legend, :fill_color)
  leg_sp_children << %(<a:solidFill>#{color_xml(leg_fill)}</a:solidFill>) if leg_fill
  leg_no_fill = chart.dig(:legend, :no_fill)
  leg_sp_children << "<a:noFill/>" if leg_no_fill
  leg_lc = chart.dig(:legend, :line_color)
  leg_lw = chart.dig(:legend, :line_width)
  leg_ld = chart.dig(:legend, :line_dash)
  if leg_lc || leg_lw || leg_ld
    lw_attr = leg_lw ? %( w="#{(leg_lw * 12_700).to_i}") : ""
    lf = leg_lc ? %(<a:solidFill>#{color_xml(leg_lc)}</a:solidFill>) : ""
    ld = leg_ld ? %(<a:prstDash val="#{xml_escape(leg_ld)}"/>) : ""
    leg_sp_children << "<a:ln#{lw_attr}>#{lf}#{ld}</a:ln>"
  end
  parts << "<c:spPr>#{leg_sp_children}</c:spPr>" unless leg_sp_children.empty?
  if (lfont = chart.dig(:legend, :font))
    parts << build_axis_txpr(nil, lfont)
  end
  parts << %(</c:legend>)
  pvo = chart[:plot_vis_only]
  parts << %(<c:plotVisOnly val="#{pvo ? 1 : 0}"/>) unless pvo.nil?
  parts << %(<c:dispBlanksAs val="#{chart[:disp_blanks_as]}"/>) if chart[:disp_blanks_as]
  sdom = chart[:show_d_lbls_over_max]
  parts << %(<c:showDLblsOverMax val="#{sdom ? 1 : 0}"/>) unless sdom.nil?
  parts << "</c:chart>"
  if chart[:chart_fill] || chart[:chart_no_fill] || chart[:chart_line_color] || chart[:chart_line_dash]
    cs_sp = +""
    cs_sp << %(<a:solidFill>#{color_xml(chart[:chart_fill])}</a:solidFill>) if chart[:chart_fill]
    cs_sp << "<a:noFill/>" if chart[:chart_no_fill]
    if chart[:chart_line_color] || chart[:chart_line_dash]
      cs_lw = chart[:chart_line_width] ? %( w="#{(chart[:chart_line_width] * 12_700).to_i}") : ""
      cs_ln_f = chart[:chart_line_color] ? %(<a:solidFill>#{color_xml(chart[:chart_line_color])}</a:solidFill>) : ""
      cs_ln_d = chart[:chart_line_dash] ? %(<a:prstDash val="#{xml_escape(chart[:chart_line_dash])}"/>) : ""
      cs_sp << "<a:ln#{cs_lw}>#{cs_ln_f}#{cs_ln_d}</a:ln>"
    end
    parts << "<c:spPr>#{cs_sp}</c:spPr>"
  end
  parts << build_axis_txpr(nil, chart[:chart_font]) if chart[:chart_font]
  if (ps = chart[:print_settings])
    parts << "<c:printSettings>"
    if (hf = ps[:header_footer])
      parts << "<c:headerFooter>"
      parts << "<c:oddHeader>#{xml_escape(hf[:odd_header])}</c:oddHeader>" if hf[:odd_header]
      parts << "<c:oddFooter>#{xml_escape(hf[:odd_footer])}</c:oddFooter>" if hf[:odd_footer]
      parts << "<c:evenHeader>#{xml_escape(hf[:even_header])}</c:evenHeader>" if hf[:even_header]
      parts << "<c:evenFooter>#{xml_escape(hf[:even_footer])}</c:evenFooter>" if hf[:even_footer]
      parts << "<c:firstHeader>#{xml_escape(hf[:first_header])}</c:firstHeader>" if hf[:first_header]
      parts << "<c:firstFooter>#{xml_escape(hf[:first_footer])}</c:firstFooter>" if hf[:first_footer]
      parts << "</c:headerFooter>"
    end
    if (pm = ps[:page_margins])
      pm_attrs = %w[b l r t header footer].filter_map { |a| pm[a.to_sym] ? %( #{a}="#{pm[a.to_sym]}") : nil }.join
      parts << "<c:pageMargins#{pm_attrs}/>"
    end
    if (psu = ps[:page_setup])
      psu_parts = +""
      psu_parts << %( paperSize="#{psu[:paper_size]}") if psu[:paper_size]
      psu_parts << %( firstPageNumber="#{psu[:first_page_number]}") if psu[:first_page_number]
      psu_parts << %( orientation="#{xml_escape(psu[:orientation])}") if psu[:orientation]
      psu_parts << %( horizontalDpi="#{psu[:horizontal_dpi]}") if psu[:horizontal_dpi]
      psu_parts << %( verticalDpi="#{psu[:vertical_dpi]}") if psu[:vertical_dpi]
      psu_parts << %( copies="#{psu[:copies]}") if psu[:copies]
      parts << "<c:pageSetup#{psu_parts}/>"
    end
    parts << "</c:printSettings>"
  end
  parts << "</c:chartSpace>"
  parts.join
end

#generate_comments_xml(sheet_comments) ⇒ Object

: (untyped sheet_comments) -> untyped

Parameters:

  • sheet_comments (Object)

Returns:

  • (Object)


4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
# File 'lib/xlsxrb/ooxml/writer.rb', line 4521

def generate_comments_xml(sheet_comments)
  authors = sheet_comments.map { |c| c[:author] }.uniq
  parts = [
    XML_HEADER,
    %(<comments xmlns="#{SSML_NS}">),
    "<authors>"
  ]
  authors.each { |a| parts << "<author>#{xml_escape(a)}</author>" }
  parts << "</authors><commentList>"
  sheet_comments.each do |c|
    aid = authors.index(c[:author]) || 0
    text_xml = if c[:text].is_a?(Xlsxrb::Elements::RichText)
                 rich_text_xml(c[:text])
               else
                 "<r><t>#{xml_escape(c[:text])}</t></r>"
               end
    comment_attrs = %(ref="#{c[:ref]}" authorId="#{aid}")
    comment_attrs << %( guid="#{c[:guid]}") if c[:guid]
    comment_attrs << %( shapeId="#{c[:shape_id]}") if c[:shape_id]
    parts << "<comment #{comment_attrs}><text>#{text_xml}</text></comment>"
  end
  parts << "</commentList></comments>"
  parts.join
end

#generate_content_types_xml(all_entries = {}) ⇒ Object

: (?::Hash[untyped, untyped] all_entries) -> untyped

Parameters:

  • all_entries (Object) (defaults to: {})

Returns:

  • (Object)


1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
# File 'lib/xlsxrb/ooxml/writer.rb', line 1870

def generate_content_types_xml(all_entries = {})
  defaults = {
    "rels" => "application/vnd.openxmlformats-package.relationships+xml",
    "xml" => "application/xml"
  }

  # Add image extension defaults.
  image_exts = {}
  @images.each_value do |imgs|
    imgs.each do |img|
      ext = img[: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"
             else "image/#{ext}"
             end
      image_exts[ext] = mime
    end
  end
  defaults.merge!(image_exts)

  # Add vml extension if comments exist.
  defaults["vml"] = "application/vnd.openxmlformats-officedocument.vmlDrawing" if @comment_count.to_i.positive?

  # Merge extra defaults from pass-through.
  defaults.merge!(@extra_ct_defaults)

  # Add bin extension if macros are preserved.
  defaults["bin"] = "application/vnd.ms-office.vbaProject" if @preserve_macros

  workbook_ct = if @preserve_macros
                  "application/vnd.ms-excel.sheet.macroEnabled.main+xml"
                else
                  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"
                end

  overrides = {}
  overrides["/xl/workbook.xml"] = workbook_ct
  overrides["/xl/styles.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"

  @sheet_order.each_with_index do |_, i|
    overrides["/xl/worksheets/sheet#{i + 1}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"
  end
  overrides["/xl/sharedStrings.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" if @use_shared_strings

  table_idx = 0
  @sheet_order.each do |sn|
    (@tables[sn] || []).each do
      table_idx += 1
      overrides["/xl/tables/table#{table_idx}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"
    end
  end

  # Drawings.
  (1..@drawing_count.to_i).each do |d|
    overrides["/xl/drawings/drawing#{d}.xml"] = "application/vnd.openxmlformats-officedocument.drawing+xml"
  end

  # Charts.
  (1..@chart_count.to_i).each do |c|
    overrides["/xl/charts/chart#{c}.xml"] = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"
  end

  # Comments.
  (1..@comment_count.to_i).each do |c|
    overrides["/xl/comments#{c}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml"
  end

  # Pivot tables and cache.
  (1..@pivot_table_count.to_i).each do |p|
    overrides["/xl/pivotTables/pivotTable#{p}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml"
  end
  (1..@pivot_cache_count.to_i).each do |p|
    overrides["/xl/pivotCache/pivotCacheDefinition#{p}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml"
    overrides["/xl/pivotCache/pivotCacheRecords#{p}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"
  end

  # External links.
  @external_links.each_with_index do |_, idx|
    overrides["/xl/externalLinks/externalLink#{idx + 1}.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml"
  end

  # calcChain.
  overrides["/xl/calcChain.xml"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml" if all_entries.key?("xl/calcChain.xml")

  overrides["/docProps/core.xml"] = "application/vnd.openxmlformats-package.core-properties+xml" unless @core_properties.empty?
  overrides["/docProps/app.xml"] = "application/vnd.openxmlformats-officedocument.extended-properties+xml" unless @app_properties.empty?
  overrides["/docProps/custom.xml"] = "application/vnd.openxmlformats-officedocument.custom-properties+xml" unless @custom_properties.empty?

  # Merge extra overrides from pass-through.
  overrides.merge!(@extra_ct_overrides) { |_k, generated, _extra| generated }

  parts = [XML_HEADER, %(<Types xmlns="#{CT_NS}">)]
  defaults.each { |ext, ct| parts << %(<Default Extension="#{ext}" ContentType="#{ct}"/>) }
  overrides.each { |pn, ct| parts << %(<Override PartName="#{pn}" ContentType="#{ct}"/>) }
  parts << "</Types>"
  parts.join
end

#generate_core_properties_xmlObject

: () -> untyped

Returns:

  • (Object)


5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
# File 'lib/xlsxrb/ooxml/writer.rb', line 5225

def generate_core_properties_xml
  parts = [
    XML_HEADER,
    %(<cp:coreProperties xmlns:cp="#{CP_NS}" xmlns:dc="#{DC_NS}" xmlns:dcterms="#{DCTERMS_NS}" xmlns:xsi="#{XSI_NS}">)
  ]
  parts << "<dc:title>#{xml_escape(@core_properties[:title])}</dc:title>" if @core_properties[:title]
  parts << "<dc:subject>#{xml_escape(@core_properties[:subject])}</dc:subject>" if @core_properties[:subject]
  parts << "<dc:creator>#{xml_escape(@core_properties[:creator])}</dc:creator>" if @core_properties[:creator]
  parts << "<cp:keywords>#{xml_escape(@core_properties[:keywords])}</cp:keywords>" if @core_properties[:keywords]
  parts << "<dc:description>#{xml_escape(@core_properties[:description])}</dc:description>" if @core_properties[:description]
  parts << "<cp:lastModifiedBy>#{xml_escape(@core_properties[:last_modified_by])}</cp:lastModifiedBy>" if @core_properties[:last_modified_by]
  parts << "<cp:revision>#{xml_escape(@core_properties[:revision])}</cp:revision>" if @core_properties[:revision]
  parts << %(<dcterms:created xsi:type="dcterms:W3CDTF">#{xml_escape(@core_properties[:created])}</dcterms:created>) if @core_properties[:created]
  parts << %(<dcterms:modified xsi:type="dcterms:W3CDTF">#{xml_escape(@core_properties[:modified])}</dcterms:modified>) if @core_properties[:modified]
  parts << "<cp:category>#{xml_escape(@core_properties[:category])}</cp:category>" if @core_properties[:category]
  parts << "<cp:contentStatus>#{xml_escape(@core_properties[:content_status])}</cp:contentStatus>" if @core_properties[:content_status]
  parts << "<dc:language>#{xml_escape(@core_properties[:language])}</dc:language>" if @core_properties[:language]
  parts << "</cp:coreProperties>"
  parts.join
end

#generate_custom_properties_xmlObject

: () -> untyped

Returns:

  • (Object)


5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
# File 'lib/xlsxrb/ooxml/writer.rb', line 5276

def generate_custom_properties_xml
  custom_ns = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
  parts = [
    XML_HEADER,
    %(<Properties xmlns="#{custom_ns}" xmlns:vt="#{VT_NS}">)
  ]
  @custom_properties.each_with_index do |prop, idx|
    fmtid = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
    pid = idx + 2 # pids start at 2
    parts << %(<property fmtid="#{fmtid}" pid="#{pid}" name="#{xml_escape(prop[:name])}">)
    parts << case prop[:type]
             when :number, :int, :i4
               "<vt:i4>#{prop[:value]}</vt:i4>"
             when :float, :r8
               "<vt:r8>#{prop[:value]}</vt:r8>"
             when :bool
               "<vt:bool>#{prop[:value] ? "true" : "false"}</vt:bool>"
             when :date, :filetime
               "<vt:filetime>#{prop[:value]}</vt:filetime>"
             else
               "<vt:lpwstr>#{xml_escape(prop[:value].to_s)}</vt:lpwstr>"
             end
    parts << "</property>"
  end
  parts << "</Properties>"
  parts.join
end

#generate_drawing_rels(rels_data) ⇒ Object

: (untyped rels_data) -> untyped

Parameters:

  • rels_data (Object)

Returns:

  • (Object)


3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
# File 'lib/xlsxrb/ooxml/writer.rb', line 3515

def generate_drawing_rels(rels_data)
  parts = [XML_HEADER, %(<Relationships xmlns="#{REL_NS}">)]
  rels_data.each_with_index do |rel, i|
    rel_type = case rel[:type]
               when :image then "#{DOC_REL_NS}/image"
               when :chart then "#{DOC_REL_NS}/chart"
               end
    parts << %(<Relationship Id="rId#{i + 1}" Type="#{rel_type}" Target="#{rel[:target]}"/>)
  end
  parts << "</Relationships>"
  parts.join
end

#generate_drawing_xml(drawing_parts) ⇒ Object

: (untyped drawing_parts) -> untyped

Parameters:

  • drawing_parts (Object)

Returns:

  • (Object)


2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
# File 'lib/xlsxrb/ooxml/writer.rb', line 2996

def generate_drawing_xml(drawing_parts)
  parts = [
    XML_HEADER,
    %(<xdr:wsDr xmlns:xdr="#{XDR_NS}" xmlns:a="#{A_NS}" xmlns:r="#{DOC_REL_NS}">)
  ]

  drawing_parts.each do |dp|
    case dp[:kind]
    when :pic
      img = dp[:img]
      rid = "rId#{dp[:rid_index]}"
      ea = img[:edit_as] || "oneCell"
      img_pub_attr = img[:published] ? ' fPublished="1"' : ""
      parts << %(<xdr:twoCellAnchor editAs="#{xml_escape(ea)}"#{img_pub_attr}>)
      parts << anchor_xml("from", img[:from_col], img[:from_row], col_off: img[:from_col_off] || 0, row_off: img[:from_row_off] || 0)
      parts << anchor_xml("to", img[:to_col], img[:to_row], col_off: img[:to_col_off] || 0, row_off: img[:to_row_off] || 0)
      macro_attr = img[:macro] ? %( macro="#{xml_escape(img[:macro])}") : ""
      parts << "<xdr:pic#{macro_attr}>"
      descr_attr = img[:description] ? %( descr="#{xml_escape(img[:description])}") : ""
      title_attr = img[:title] ? %( title="#{xml_escape(img[:title])}") : ""
      hidden_attr = img[:hidden] ? ' hidden="1"' : ""
      pic_lock_attrs = +""
      pic_lock_attrs << ' noChangeAspect="1"' if img[:no_change_aspect]
      pic_lock_attrs << ' noCrop="1"' if img[:no_crop]
      pic_locks = pic_lock_attrs.empty? ? "<a:picLocks/>" : "<a:picLocks#{pic_lock_attrs}/>"
      parts << %(<xdr:nvPicPr><xdr:cNvPr id="#{dp[:rid_index] + 1}" name="#{xml_escape(img[:name])}"#{descr_attr}#{title_attr}#{hidden_attr}/><xdr:cNvPicPr>#{pic_locks}</xdr:cNvPicPr></xdr:nvPicPr>)
      src_rect_xml = if img[:src_rect]
                       sr = img[:src_rect]
                       sr_attrs = +""
                       sr_attrs << %( t="#{sr[:top]}") if sr[:top]
                       sr_attrs << %( b="#{sr[:bottom]}") if sr[:bottom]
                       sr_attrs << %( l="#{sr[:left]}") if sr[:left]
                       sr_attrs << %( r="#{sr[:right]}") if sr[:right]
                       "<a:srcRect#{sr_attrs}/>"
                     else
                       ""
                     end
      blip_xml = if img[:alpha_mod_fix]
                   %(<a:blip r:embed="#{rid}"><a:alphaModFix amt="#{img[:alpha_mod_fix]}"/></a:blip>)
                 else
                   %(<a:blip r:embed="#{rid}"/>)
                 end
      parts << %(<xdr:blipFill>#{blip_xml}#{src_rect_xml}<a:stretch><a:fillRect/></a:stretch></xdr:blipFill>)
      img_line_xml = if img[:line_color]
                       ln_w_attr = img[:line_width] ? %( w="#{img[:line_width].to_i}") : ""
                       %(<a:ln#{ln_w_attr}><a:solidFill>#{color_xml(img[:line_color])}</a:solidFill></a:ln>)
                     else
                       ""
                     end
      img_xfrm_xml = img[:rotation] ? %(<a:xfrm rot="#{img[:rotation].to_i}"><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></a:xfrm>) : ""
      parts << %(<xdr:spPr>#{img_xfrm_xml}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>#{img_line_xml}</xdr:spPr>)
      parts << "</xdr:pic>"
      parts << client_data_xml(img)
      parts << "</xdr:twoCellAnchor>"
    when :chart
      chart = dp[:chart]
      rid = "rId#{dp[:rid_index]}"
      chart_ea_attr = chart[:edit_as] ? %( editAs="#{xml_escape(chart[:edit_as])}") : ""
      chart_pub_attr = chart[:published] ? ' fPublished="1"' : ""
      parts << "<xdr:twoCellAnchor#{chart_ea_attr}#{chart_pub_attr}>"
      parts << anchor_xml("from", chart[:from_col], chart[:from_row], col_off: chart[:from_col_off] || 0, row_off: chart[:from_row_off] || 0)
      parts << anchor_xml("to", chart[:to_col], chart[:to_row], col_off: chart[:to_col_off] || 0, row_off: chart[:to_row_off] || 0)
      gf_macro = chart[:frame_macro] ? xml_escape(chart[:frame_macro]) : ""
      parts << %(<xdr:graphicFrame macro="#{gf_macro}">)
      chart_frame_name = chart[:name] || chart[:title] || "Chart"
      chart_descr_attr = chart[:description] ? %( descr="#{xml_escape(chart[:description])}") : ""
      chart_title_attr = chart[:frame_title] ? %( title="#{xml_escape(chart[:frame_title])}") : ""
      chart_hidden_attr = chart[:frame_hidden] ? ' hidden="1"' : ""
      cnv_gf_pr = if chart[:frame_no_grp]
                    '<xdr:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></xdr:cNvGraphicFramePr>'
                  else
                    "<xdr:cNvGraphicFramePr/>"
                  end
      parts << %(<xdr:nvGraphicFramePr><xdr:cNvPr id="#{dp[:rid_index] + 1}" name="#{xml_escape(chart_frame_name)}"#{chart_descr_attr}#{chart_title_attr}#{chart_hidden_attr}/>#{cnv_gf_pr}</xdr:nvGraphicFramePr>)
      parts << '<xdr:xfrm><a:off x="0" y="0"/><a:ext cx="5000000" cy="3000000"/></xdr:xfrm>'
      parts << %(<a:graphic><a:graphicData uri="#{C_NS}"><c:chart xmlns:c="#{C_NS}" xmlns:r="#{DOC_REL_NS}" r:id="#{rid}"/></a:graphicData></a:graphic>)
      parts << "</xdr:graphicFrame>"
      parts << client_data_xml(chart)
      parts << "</xdr:twoCellAnchor>"
    when :sp
      shape = dp[:shape]
      shape_ea_attr = shape[:edit_as] ? %( editAs="#{xml_escape(shape[:edit_as])}") : ""
      shape_pub_attr = shape[:published] ? ' fPublished="1"' : ""
      parts << "<xdr:twoCellAnchor#{shape_ea_attr}#{shape_pub_attr}>"
      parts << anchor_xml("from", shape[:from_col], shape[:from_row], col_off: shape[:from_col_off] || 0, row_off: shape[:from_row_off] || 0)
      parts << anchor_xml("to", shape[:to_col], shape[:to_row], col_off: shape[:to_col_off] || 0, row_off: shape[:to_row_off] || 0)
      sp_macro_attr = shape[:macro] ? %( macro="#{xml_escape(shape[:macro])}") : ""
      sp_textlink_attr = shape[:textlink] ? %( textlink="#{xml_escape(shape[:textlink])}") : ""
      parts << "<xdr:sp#{sp_macro_attr}#{sp_textlink_attr}>"
      shape_descr_attr = shape[:description] ? %( descr="#{xml_escape(shape[:description])}") : ""
      shape_title_attr = shape[:title] ? %( title="#{xml_escape(shape[:title])}") : ""
      shape_hidden_attr = shape[:hidden] ? ' hidden="1"' : ""
      sp_lock_attrs = +""
      sp_lock_attrs << ' noGrp="1"' if shape[:no_grp]
      sp_lock_attrs << ' noRot="1"' if shape[:no_rot]
      sp_lock_attrs << ' fLocksText="1"' if shape[:f_locks_text]
      cnv_sp_pr = if sp_lock_attrs.empty?
                    "<xdr:cNvSpPr/>"
                  else
                    "<xdr:cNvSpPr><a:spLocks#{sp_lock_attrs}/></xdr:cNvSpPr>"
                  end
      parts << %(<xdr:nvSpPr><xdr:cNvPr id="#{dp[:id]}" name="#{xml_escape(shape[:name])}"#{shape_descr_attr}#{shape_title_attr}#{shape_hidden_attr}/>#{cnv_sp_pr}</xdr:nvSpPr>)
      shape_fill_xml = if shape[:no_fill]
                         "<a:noFill/>"
                       elsif shape[:fill_color]
                         "<a:solidFill>#{srgb_clr_xml(shape[:fill_color], alpha: shape[:fill_alpha], transforms: shape[:fill_color_transforms])}</a:solidFill>"
                       elsif shape[:gradient_fill]
                         gf = shape[:gradient_fill]
                         gf_attrs = +""
                         gf_attrs << %( rotWithShape="#{gf[:rot_with_shape] ? 1 : 0}") unless gf[:rot_with_shape].nil?
                         gf_attrs << %( flip="#{xml_escape(gf[:flip])}") if gf[:flip]
                         gs_xml = (gf[:stops] || []).map { |gs| %(<a:gs pos="#{gs[:pos]}">#{color_xml(gs[:color])}</a:gs>) }.join
                         type_xml = if gf[:path]
                                      %(<a:path path="#{xml_escape(gf[:path])}"/>)
                                    elsif gf[:angle]
                                      scaled_attr = gf[:scaled] ? %( scaled="1") : %( scaled="0")
                                      %(<a:lin ang="#{gf[:angle]}"#{scaled_attr}/>)
                                    else
                                      ""
                                    end
                         tile_xml = gf[:tile_rect] ? %(<a:tileRect#{gf[:tile_rect].map { |k, v| %( #{k}="#{v}") }.join}/>) : ""
                         "<a:gradFill#{gf_attrs}><a:gsLst>#{gs_xml}</a:gsLst>#{type_xml}#{tile_xml}</a:gradFill>"
                       elsif shape[:pattern_fill]
                         pf = shape[:pattern_fill]
                         pf_children = +""
                         pf_children << %(<a:fgClr>#{color_xml(pf[:fg_color])}</a:fgClr>) if pf[:fg_color]
                         pf_children << %(<a:bgClr>#{color_xml(pf[:bg_color])}</a:bgClr>) if pf[:bg_color]
                         %(<a:pattFill prst="#{xml_escape(pf[:preset])}">#{pf_children}</a:pattFill>)
                       else
                         ""
                       end
      shape_line_xml = if shape[:no_line]
                         "<a:ln><a:noFill/></a:ln>"
                       elsif shape[:line_color] || shape[:line_dash] || shape[:line_custom_dash] || shape[:head_end] || shape[:tail_end] || shape[:line_cap] || shape[:line_align] || shape[:line_compound] || shape[:line_join]
                         ln_attrs = +(shape[:line_width] ? %( w="#{shape[:line_width].to_i}") : "")
                         ln_attrs << %( cap="#{xml_escape(shape[:line_cap])}") if shape[:line_cap]
                         ln_attrs << %( algn="#{xml_escape(shape[:line_align])}") if shape[:line_align]
                         ln_attrs << %( cmpd="#{xml_escape(shape[:line_compound])}") if shape[:line_compound]
                         fill_part = if shape[:line_color]
                                       "<a:solidFill>#{srgb_clr_xml(shape[:line_color], alpha: shape[:line_alpha], transforms: shape[:line_color_transforms])}</a:solidFill>"
                                     else
                                       ""
                                     end
                         dash_part = if shape[:line_custom_dash]
                                       ds_xml = shape[:line_custom_dash].map { |ds| %(<a:ds d="#{ds[:d]}" sp="#{ds[:sp]}"/>) }.join
                                       "<a:custDash>#{ds_xml}</a:custDash>"
                                     elsif shape[:line_dash]
                                       %(<a:prstDash val="#{xml_escape(shape[:line_dash])}"/>)
                                     else
                                       ""
                                     end
                         head_part = build_line_end_xml("headEnd", shape[:head_end])
                         tail_part = build_line_end_xml("tailEnd", shape[:tail_end])
                         join_part = case shape[:line_join]
                                     when "round" then "<a:round/>"
                                     when "bevel" then "<a:bevel/>"
                                     when "miter"
                                       shape[:line_miter_limit] ? "<a:miter lim=\"#{shape[:line_miter_limit].to_i}\"/>" : "<a:miter/>"
                                     else ""
                                     end
                         %(<a:ln#{ln_attrs}>#{fill_part}#{dash_part}#{head_part}#{tail_part}#{join_part}</a:ln>)
                       else
                         ""
                       end
      shape_xfrm_xml = shape[:rotation] ? %(<a:xfrm rot="#{shape[:rotation].to_i}"><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></a:xfrm>) : ""
      av_lst_xml = if shape[:adjust_values]&.any?
                     gds = shape[:adjust_values].map { |gd| %(<a:gd name="#{xml_escape(gd[:name])}" fmla="#{xml_escape(gd[:fmla])}"/>) }
                     "<a:avLst>#{gds.join}</a:avLst>"
                   else
                     "<a:avLst/>"
                   end
      effect_lst_xml = if shape[:outer_shadow] || shape[:inner_shadow] || shape[:glow] || shape[:soft_edge] || shape[:reflection] || shape[:blur]
                         effect_children = +""
                         if shape[:outer_shadow]
                           os = shape[:outer_shadow]
                           os_attrs = +""
                           os_attrs << %( blurRad="#{os[:blur_rad]}") if os[:blur_rad]
                           os_attrs << %( dist="#{os[:dist]}") if os[:dist]
                           os_attrs << %( dir="#{os[:dir]}") if os[:dir]
                           os_attrs << %( algn="#{xml_escape(os[:algn])}") if os[:algn]
                           os_attrs << %( rotWithShape="#{os[:rot_with_shape] ? 1 : 0}") unless os[:rot_with_shape].nil?
                           os_color = os[:color] ? srgb_clr_xml(os[:color], alpha: os[:alpha]) : ""
                           effect_children << "<a:outerShdw#{os_attrs}>#{os_color}</a:outerShdw>"
                         end
                         if shape[:glow]
                           gl = shape[:glow]
                           gl_attrs = +""
                           gl_attrs << %( rad="#{gl[:rad]}") if gl[:rad]
                           gl_color = gl[:color] ? srgb_clr_xml(gl[:color], alpha: gl[:alpha]) : ""
                           effect_children << "<a:glow#{gl_attrs}>#{gl_color}</a:glow>"
                         end
                         if shape[:inner_shadow]
                           is = shape[:inner_shadow]
                           is_attrs = +""
                           is_attrs << %( blurRad="#{is[:blur_rad]}") if is[:blur_rad]
                           is_attrs << %( dist="#{is[:dist]}") if is[:dist]
                           is_attrs << %( dir="#{is[:dir]}") if is[:dir]
                           is_color = is[:color] ? srgb_clr_xml(is[:color], alpha: is[:alpha]) : ""
                           effect_children << "<a:innerShdw#{is_attrs}>#{is_color}</a:innerShdw>"
                         end
                         if shape[:reflection]
                           rf = shape[:reflection]
                           rf_attrs = +""
                           rf_attrs << %( blurRad="#{rf[:blur_rad]}") if rf[:blur_rad]
                           rf_attrs << %( stA="#{rf[:st_a]}") if rf[:st_a]
                           rf_attrs << %( endA="#{rf[:end_a]}") if rf[:end_a]
                           rf_attrs << %( dist="#{rf[:dist]}") unless rf[:dist].nil?
                           rf_attrs << %( dir="#{rf[:dir]}") if rf[:dir]
                           rf_attrs << %( fadeDir="#{rf[:fade_dir]}") if rf[:fade_dir]
                           rf_attrs << %( sx="#{rf[:sx]}") if rf[:sx]
                           rf_attrs << %( sy="#{rf[:sy]}") if rf[:sy]
                           rf_attrs << %( kx="#{rf[:kx]}") if rf[:kx]
                           rf_attrs << %( ky="#{rf[:ky]}") if rf[:ky]
                           rf_attrs << %( algn="#{xml_escape(rf[:algn])}") if rf[:algn]
                           rf_attrs << %( rotWithShape="#{rf[:rot_with_shape] ? 1 : 0}") unless rf[:rot_with_shape].nil?
                           effect_children << "<a:reflection#{rf_attrs}/>"
                         end
                         if shape[:soft_edge]
                           se = shape[:soft_edge]
                           effect_children << %(<a:softEdge rad="#{se[:rad]}"/>)
                         end
                         if shape[:blur]
                           bl = shape[:blur]
                           bl_attrs = +""
                           bl_attrs << %( rad="#{bl[:rad]}") if bl[:rad]
                           bl_attrs << %( grow="#{bl[:grow] ? 1 : 0}") unless bl[:grow].nil?
                           effect_children << "<a:blur#{bl_attrs}/>"
                         end
                         "<a:effectLst>#{effect_children}</a:effectLst>"
                       else
                         ""
                       end
      parts << %(<xdr:spPr>#{shape_xfrm_xml}<a:prstGeom prst="#{xml_escape(shape[:preset])}">#{av_lst_xml}</a:prstGeom>#{shape_fill_xml}#{shape_line_xml}#{effect_lst_xml}</xdr:spPr>)
      if shape[:text] || shape[:text_paragraphs]
        body_pr_attrs = +""
        body_pr_attrs << %( rot="#{shape[:text_rot]}") if shape[:text_rot]
        body_pr_attrs << %( spcFirstLastPara="1") if shape[:text_spc_first_last_para]
        body_pr_attrs << %( wrap="#{xml_escape(shape[:text_wrap])}") if shape[:text_wrap]
        body_pr_attrs << %( anchor="#{xml_escape(shape[:text_anchor])}") if shape[:text_anchor]
        body_pr_attrs << %( anchorCtr="1") if shape[:text_anchor_ctr]
        body_pr_attrs << %( vertOverflow="#{xml_escape(shape[:text_vert_overflow])}") if shape[:text_vert_overflow]
        body_pr_attrs << %( horzOverflow="#{xml_escape(shape[:text_horz_overflow])}") if shape[:text_horz_overflow]
        body_pr_attrs << %( numCol="#{shape[:text_num_col]}") if shape[:text_num_col]
        body_pr_attrs << %( spcCol="#{shape[:text_spc_col]}") if shape[:text_spc_col]
        body_pr_attrs << %( rtlCol="1") if shape[:text_rtl_col]
        body_pr_attrs << %( fromWordArt="1") if shape[:text_from_word_art]
        body_pr_attrs << %( upright="1") if shape[:text_upright]
        body_pr_attrs << %( compatLnSpc="1") if shape[:text_compat_ln_spc]
        body_pr_attrs << %( forceAA="1") if shape[:text_force_aa]
        body_pr_attrs << %( vert="#{xml_escape(shape[:text_vertical])}") if shape[:text_vertical]
        if shape[:text_insets]
          ins = shape[:text_insets]
          body_pr_attrs << %( lIns="#{ins[:left]}") if ins[:left]
          body_pr_attrs << %( tIns="#{ins[:top]}") if ins[:top]
          body_pr_attrs << %( rIns="#{ins[:right]}") if ins[:right]
          body_pr_attrs << %( bIns="#{ins[:bottom]}") if ins[:bottom]
        end
        body_pr_children = +""
        if shape[:text_warp]
          tw = shape[:text_warp]
          body_pr_children << %(<a:prstTxWarp prst="#{xml_escape(tw[:preset])}"><a:avLst/></a:prstTxWarp>)
        end
        autofit_xml = case shape[:autofit]
                      when "none" then "<a:noAutofit/>"
                      when "shape" then "<a:spAutoFit/>"
                      when "normal" then "<a:normAutofit/>"
                      when Hash
                        af = shape[:autofit]
                        case af[:type]
                        when "normal"
                          na_attrs = +""
                          na_attrs << %( fontScale="#{af[:font_scale]}") if af[:font_scale]
                          na_attrs << %( lnSpcReduction="#{af[:ln_spc_reduction]}") if af[:ln_spc_reduction]
                          "<a:normAutofit#{na_attrs}/>"
                        when "none" then "<a:noAutofit/>"
                        when "shape" then "<a:spAutoFit/>"
                        else ""
                        end
                      else ""
                      end
        body_pr_children << autofit_xml
        body_pr_xml = if body_pr_children.empty?
                        "<a:bodyPr#{body_pr_attrs}/>"
                      else
                        "<a:bodyPr#{body_pr_attrs}>#{body_pr_children}</a:bodyPr>"
                      end
        parts << "<xdr:txBody>#{body_pr_xml}<a:lstStyle/>"
        if shape[:text_paragraphs]
          shape[:text_paragraphs].each { |para| parts << paragraph_xml(para) }
        elsif shape[:text]
          parts << paragraph_xml(
            text: shape[:text], font: shape[:text_font],
            align: shape[:text_align], font_align: shape[:text_font_align],
            def_tab_sz: shape[:text_def_tab_sz], rtl: shape[:text_rtl],
            ea_ln_brk: shape[:text_ea_ln_brk], latin_ln_brk: shape[:text_latin_ln_brk],
            hanging_punct: shape[:text_hanging_punct], level: shape[:text_level],
            indent: shape[:text_indent], spacing: shape[:text_spacing],
            tab_stops: shape[:text_tab_stops], bullet: shape[:text_bullet],
            def_rpr: shape[:text_def_rpr], end_para_rpr: shape[:text_end_para_rpr]
          )
        end
        parts << "</xdr:txBody>"
      end
      parts << "</xdr:sp>"
      parts << client_data_xml(shape)
      parts << "</xdr:twoCellAnchor>"
    end
  end

  parts << "</xdr:wsDr>"
  parts.join
end

: (untyped ext_link) -> untyped

Parameters:

  • ext_link (Object)

Returns:

  • (Object)


4849
4850
4851
4852
4853
4854
4855
4856
# File 'lib/xlsxrb/ooxml/writer.rb', line 4849

def generate_external_link_rels(ext_link)
  [
    XML_HEADER,
    %(<Relationships xmlns="#{REL_NS}">),
    %(<Relationship Id="rId1" Type="#{DOC_REL_NS}/externalLinkPath" Target="#{xml_escape(ext_link[:target])}" TargetMode="External"/>),
    "</Relationships>"
  ].join
end

: (untyped ext_link) -> untyped

Parameters:

  • ext_link (Object)

Returns:

  • (Object)


4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
# File 'lib/xlsxrb/ooxml/writer.rb', line 4832

def generate_external_link_xml(ext_link)
  parts = [
    XML_HEADER,
    %(<externalLink xmlns="#{SSML_NS}" xmlns:r="#{DOC_REL_NS}">),
    '<externalBook r:id="rId1">'
  ]
  unless ext_link[:sheet_names].empty?
    parts << "<sheetNames>"
    ext_link[:sheet_names].each { |sn| parts << %(<sheetName val="#{xml_escape(sn)}"/>) }
    parts << "</sheetNames>"
  end
  parts << "</externalBook>"
  parts << "</externalLink>"
  parts.join
end

#generate_generic_rels(rels_data) ⇒ Object

: (untyped rels_data) -> untyped

Parameters:

  • rels_data (Object)

Returns:

  • (Object)


2985
2986
2987
2988
2989
2990
2991
2992
2993
# File 'lib/xlsxrb/ooxml/writer.rb', line 2985

def generate_generic_rels(rels_data)
  parts = [XML_HEADER, %(<Relationships xmlns="#{REL_NS}">)]
  rels_data.each_with_index do |rel, i|
    ext_attr = rel[:external] ? ' TargetMode="External"' : ""
    parts << %(<Relationship Id="rId#{i + 1}" Type="#{rel[:type]}" Target="#{xml_escape(rel[:target])}"#{ext_attr}/>)
  end
  parts << "</Relationships>"
  parts.join
end

#generate_pivot_cache_definition_xml(pivot_table, _cache_id) ⇒ Object

: (untyped pivot_table, untyped _cache_id) -> untyped

Parameters:

  • pivot_table (Object)
  • _cache_id (Object)

Returns:

  • (Object)


4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
# File 'lib/xlsxrb/ooxml/writer.rb', line 4730

def generate_pivot_cache_definition_xml(pivot_table, _cache_id)
  pcd_attrs = %( xmlns="#{SSML_NS}" xmlns:r="#{DOC_REL_NS}" r:id="rId1" refreshOnLoad="1")
  pcd_attrs << ' saveData="0"' if pivot_table[:cache_save_data] == false
  pcd_attrs << ' enableRefresh="0"' if pivot_table[:cache_enable_refresh] == false
  pcd_attrs << %( refreshedBy="#{xml_escape(pivot_table[:cache_refreshed_by])}") if pivot_table[:cache_refreshed_by]
  pcd_attrs << %( refreshedVersion="#{pivot_table[:cache_refreshed_version]}") if pivot_table[:cache_refreshed_version]
  pcd_attrs << %( createdVersion="#{pivot_table[:cache_created_version]}") if pivot_table[:cache_created_version]
  pcd_attrs << %( recordCount="#{pivot_table[:cache_record_count]}") if pivot_table[:cache_record_count]
  pcd_attrs << ' optimizeMemory="1"' if pivot_table[:cache_optimize_memory]
  parts = [
    XML_HEADER,
    "<pivotCacheDefinition#{pcd_attrs}>"
  ]

  # Parse source ref: "Sheet1!A1:C4" => sheet name + range.
  source = pivot_table[:source_ref]
  ws_name_attr = pivot_table[:source_name] ? %( name="#{xml_escape(pivot_table[:source_name])}") : ""
  if source.include?("!")
    sname, srange = source.split("!", 2)
    sname = sname.delete("'")
    parts << %(<cacheSource type="worksheet"><worksheetSource ref="#{srange}" sheet="#{xml_escape(sname)}"#{ws_name_attr}/></cacheSource>)
  else
    parts << %(<cacheSource type="worksheet"><worksheetSource ref="#{source}"#{ws_name_attr}/></cacheSource>)
  end

  field_count = pivot_table[:field_names] ? pivot_table[:field_names].size : (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size)
  parts << %(<cacheFields count="#{field_count}">)
  field_count.times do |fi|
    fname = if pivot_table[:field_names] && pivot_table[:field_names][fi]
              pivot_table[:field_names][fi]
            else
              df = pivot_table[:data_fields].find { |d| d[:fld] == fi }
              df ? df[:name] : "Field#{fi + 1}"
            end
    fa = pivot_table[:field_attrs] && pivot_table[:field_attrs][fi]
    cf_num_fmt = (fa && fa[:cache_num_fmt_id]) || 0
    cf_attrs = %( name="#{xml_escape(fname)}" numFmtId="#{cf_num_fmt}")
    cf_attrs << %( caption="#{xml_escape(fa[:cache_caption])}") if fa && fa[:cache_caption]
    cf_attrs << %( formula="#{xml_escape(fa[:cache_formula])}") if fa && fa[:cache_formula]
    field_items = pivot_table[:items] && pivot_table[:items][fi]
    if field_items
      parts << "<cacheField#{cf_attrs}>"
      parts << %(<sharedItems count="#{field_items.size}">)
      field_items.each { |v| parts << %(<s v="#{xml_escape(v.to_s)}"/>) }
      parts << "</sharedItems>"
      parts << "</cacheField>"
    else
      parts << "<cacheField#{cf_attrs}><sharedItems/></cacheField>"
    end
  end
  parts << "</cacheFields>"
  parts << "</pivotCacheDefinition>"
  parts.join
end

#generate_pivot_cache_records_xml(pivot_table) ⇒ Object

: (untyped pivot_table) -> untyped

Parameters:

  • pivot_table (Object)

Returns:

  • (Object)


4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
# File 'lib/xlsxrb/ooxml/writer.rb', line 4786

def generate_pivot_cache_records_xml(pivot_table)
  items = pivot_table[:items]
  if items&.values&.any? { |v| v && !v.empty? }
    max_len = items.values.map { |v| v ? v.size : 0 }.max
    parts = [XML_HEADER, %(<pivotCacheRecords xmlns="#{SSML_NS}" count="#{max_len}">)]
    max_len.times do |ri|
      parts << "<r>"
      field_count = pivot_table[:field_names] ? pivot_table[:field_names].size : (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size)
      field_count.times do |fi|
        field_items = items[fi]
        parts << if field_items
                   %(<x v="#{ri < field_items.size ? ri : 0}"/>)
                 else
                   %(<n v="0"/>)
                 end
      end
      parts << "</r>"
    end
    parts << "</pivotCacheRecords>"
    parts.join
  else
    [XML_HEADER, %(<pivotCacheRecords xmlns="#{SSML_NS}" count="0"/>)].join
  end
end

#generate_pivot_cache_rels(cache_id) ⇒ Object

: (untyped cache_id) -> untyped

Parameters:

  • cache_id (Object)

Returns:

  • (Object)


4812
4813
4814
4815
4816
4817
4818
4819
# File 'lib/xlsxrb/ooxml/writer.rb', line 4812

def generate_pivot_cache_rels(cache_id)
  [
    XML_HEADER,
    %(<Relationships xmlns="#{REL_NS}">),
    %(<Relationship Id="rId1" Type="#{DOC_REL_NS}/pivotCacheRecords" Target="pivotCacheRecords#{cache_id}.xml"/>),
    "</Relationships>"
  ].join
end

#generate_pivot_table_rels(cache_id) ⇒ Object

: (untyped cache_id) -> untyped

Parameters:

  • cache_id (Object)

Returns:

  • (Object)


4822
4823
4824
4825
4826
4827
4828
4829
# File 'lib/xlsxrb/ooxml/writer.rb', line 4822

def generate_pivot_table_rels(cache_id)
  [
    XML_HEADER,
    %(<Relationships xmlns="#{REL_NS}">),
    %(<Relationship Id="rId1" Type="#{DOC_REL_NS}/pivotCacheDefinition" Target="../pivotCache/pivotCacheDefinition#{cache_id}.xml"/>),
    "</Relationships>"
  ].join
end

#generate_pivot_table_xml(pivot_table, cache_id) ⇒ Object

: (untyped pivot_table, untyped cache_id) -> untyped

Parameters:

  • pivot_table (Object)
  • cache_id (Object)

Returns:

  • (Object)


4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
# File 'lib/xlsxrb/ooxml/writer.rb', line 4586

def generate_pivot_table_xml(pivot_table, cache_id)
  data_caption = pivot_table[:data_caption] || (pivot_table[:data_fields].first ? pivot_table[:data_fields].first[:name] : "Values")
  pt_attrs = %( xmlns="#{SSML_NS}" name="#{xml_escape(pivot_table[:name])}" cacheId="#{cache_id}" dataCaption="#{xml_escape(data_caption)}")
  pt_attrs << %( grandTotalCaption="#{xml_escape(pivot_table[:grand_total_caption])}") if pivot_table[:grand_total_caption]
  pt_attrs << %( errorCaption="#{xml_escape(pivot_table[:error_caption])}") if pivot_table[:error_caption]
  pt_attrs << ' showError="1"' if pivot_table[:show_error]
  pt_attrs << %( missingCaption="#{xml_escape(pivot_table[:missing_caption])}") if pivot_table[:missing_caption]
  pt_attrs << ' showMissing="0"' if pivot_table[:show_missing] == false
  pt_attrs << %( tag="#{xml_escape(pivot_table[:tag])}") if pivot_table[:tag]
  pt_attrs << %( dataOnRows="1") if pivot_table[:data_on_rows]
  pt_attrs << %( dataOnRows="0") unless pivot_table[:data_on_rows]
  pt_attrs << %( rowGrandTotals="0") if pivot_table[:row_grand_totals] == false
  pt_attrs << %( colGrandTotals="0") if pivot_table[:col_grand_totals] == false
  pt_attrs << %( compact="0") if pivot_table[:compact] == false
  pt_attrs << %( outline="0") if pivot_table[:outline] == false
  pt_attrs << %( outlineData="1") if pivot_table[:outline_data]
  pt_attrs << %( compactData="0") if pivot_table[:compact_data] == false
  pt_attrs << %( showHeaders="0") if pivot_table[:show_headers] == false
  pt_attrs << %( showMultipleLabel="0") if pivot_table[:show_multiple_label] == false
  pt_attrs << %( showDataDropDown="0") if pivot_table[:show_data_drop_down] == false
  pt_attrs << %( indent="#{pivot_table[:indent]}") if pivot_table[:indent]
  pt_attrs << ' published="1"' if pivot_table[:published]
  pt_attrs << ' editData="1"' if pivot_table[:edit_data]
  pt_attrs << ' disableFieldList="1"' if pivot_table[:disable_field_list]
  pt_attrs << ' visualTotals="0"' if pivot_table[:visual_totals] == false
  pt_attrs << ' printDrill="1"' if pivot_table[:print_drill]
  pt_attrs << %( createdVersion="#{pivot_table[:created_version]}") if pivot_table[:created_version]
  pt_attrs << %( updatedVersion="#{pivot_table[:updated_version]}") if pivot_table[:updated_version]
  pt_attrs << %( minRefreshableVersion="#{pivot_table[:min_refreshable_version]}") if pivot_table[:min_refreshable_version]
  anf = pivot_table.fetch(:apply_number_formats, false)
  abf = pivot_table.fetch(:apply_border_formats, false)
  aff = pivot_table.fetch(:apply_font_formats, false)
  apf = pivot_table.fetch(:apply_pattern_formats, false)
  aaf = pivot_table.fetch(:apply_alignment_formats, false)
  awf = pivot_table.fetch(:apply_width_height_formats, true)
  pt_attrs << %( applyNumberFormats="#{anf ? 1 : 0}")
  pt_attrs << %( applyBorderFormats="#{abf ? 1 : 0}")
  pt_attrs << %( applyFontFormats="#{aff ? 1 : 0}")
  pt_attrs << %( applyPatternFormats="#{apf ? 1 : 0}")
  pt_attrs << %( applyAlignmentFormats="#{aaf ? 1 : 0}")
  pt_attrs << %( applyWidthHeightFormats="#{awf ? 1 : 0}")
  pt_attrs << ' multipleFieldFilters="0"' if pivot_table[:multiple_field_filters] == false
  pt_attrs << ' showDrill="0"' if pivot_table[:show_drill] == false
  pt_attrs << ' showDataTips="0"' if pivot_table[:show_data_tips] == false
  pt_attrs << ' enableDrill="0"' if pivot_table[:enable_drill] == false
  pt_attrs << ' showMemberPropertyTips="0"' if pivot_table[:show_member_property_tips] == false
  pt_attrs << ' itemPrintTitles="1"' if pivot_table[:item_print_titles]
  pt_attrs << ' fieldPrintTitles="1"' if pivot_table[:field_print_titles]
  pt_attrs << ' preserveFormatting="0"' if pivot_table[:preserve_formatting] == false
  pt_attrs << ' pageOverThenDown="1"' if pivot_table[:page_over_then_down]
  pt_attrs << %( pageWrap="#{pivot_table[:page_wrap]}") if pivot_table[:page_wrap]
  parts = [
    XML_HEADER,
    "<pivotTableDefinition#{pt_attrs}>"
  ]

  # Compute field count from source range or explicit field_names.
  field_count = if pivot_table[:field_names]
                  pivot_table[:field_names].size
                else
                  (pivot_table[:row_fields].size + pivot_table[:col_fields].size + pivot_table[:data_fields].size).clamp(1, 100)
                end
  loc_attrs = %(<location ref="#{pivot_table[:dest_ref]}" firstHeaderRow="1" firstDataRow="1" firstDataCol="1")
  loc_attrs << %( rowPageCount="#{pivot_table[:row_page_count]}") if pivot_table[:row_page_count]
  loc_attrs << %( colPageCount="#{pivot_table[:col_page_count]}") if pivot_table[:col_page_count]
  loc_attrs << "/>"
  parts << loc_attrs
  parts << %(<pivotFields count="#{field_count}">)
  field_count.times do |fi|
    attrs = +""
    if pivot_table[:row_fields].include?(fi)
      attrs << ' axis="axisRow"'
    elsif pivot_table[:col_fields].include?(fi)
      attrs << ' axis="axisCol"'
    end
    attrs << ' dataField="1"' if pivot_table[:data_fields].any? { |df| df[:fld] == fi }
    fa = pivot_table[:field_attrs] && pivot_table[:field_attrs][fi]
    attrs << %( compact="#{fa[:compact] ? "1" : "0"}") if fa && !fa[:compact].nil?
    attrs << %( outline="#{fa[:outline] ? "1" : "0"}") if fa && !fa[:outline].nil?
    attrs << %( subtotalTop="#{fa[:subtotal_top] ? "1" : "0"}") if fa && !fa[:subtotal_top].nil?
    attrs << %( showAll="#{fa && fa[:show_all] == true ? "1" : "0"}")
    attrs << %( numFmtId="#{fa[:num_fmt_id]}") if fa && fa[:num_fmt_id]
    attrs << %( sortType="#{xml_escape(fa[:sort_type])}") if fa && fa[:sort_type]
    attrs << ' defaultSubtotal="0"' if fa && fa[:default_subtotal] == false
    attrs << ' insertBlankRow="1"' if fa && fa[:insert_blank_row]
    attrs << ' insertPageBreak="1"' if fa && fa[:insert_page_break]
    attrs << ' includeNewItemsInFilter="1"' if fa && fa[:include_new_items_in_filter]

    field_items = pivot_table[:items] && pivot_table[:items][fi]
    if field_items
      parts << "<pivotField#{attrs}>"
      parts << %(<items count="#{field_items.size + 1}">)
      field_items.size.times { |ix| parts << %(<item x="#{ix}"/>) }
      parts << '<item t="default"/>'
      parts << "</items>"
      parts << "</pivotField>"
    else
      parts << "<pivotField#{attrs}/>"
    end
  end
  parts << "</pivotFields>"

  unless pivot_table[:row_fields].empty?
    parts << %(<rowFields count="#{pivot_table[:row_fields].size}">)
    pivot_table[:row_fields].each { |f| parts << %(<field x="#{f}"/>) }
    parts << "</rowFields>"
  end

  unless pivot_table[:col_fields].empty?
    parts << %(<colFields count="#{pivot_table[:col_fields].size}">)
    pivot_table[:col_fields].each { |f| parts << %(<field x="#{f}"/>) }
    parts << "</colFields>"
  end

  unless pivot_table[:data_fields].empty?
    parts << %(<dataFields count="#{pivot_table[:data_fields].size}">)
    pivot_table[:data_fields].each do |df|
      df_attrs = %( name="#{xml_escape(df[:name])}" fld="#{df[:fld]}" subtotal="#{df[:subtotal] || "sum"}")
      df_attrs << %( showDataAs="#{xml_escape(df[:show_data_as])}") if df[:show_data_as]
      df_attrs << %( baseField="#{df[:base_field]}") if df[:base_field]
      df_attrs << %( baseItem="#{df[:base_item]}") if df[:base_item]
      df_attrs << %( numFmtId="#{df[:num_fmt_id]}") if df[:num_fmt_id]
      parts << "<dataField#{df_attrs}/>"
    end
    parts << "</dataFields>"
  end

  if pivot_table[:pivot_table_style]
    psi = pivot_table[:pivot_table_style]
    psi_attrs = +""
    psi_attrs << %( name="#{xml_escape(psi[:name])}") if psi[:name]
    psi_attrs << %( showRowHeaders="#{psi[:show_row_headers] ? "1" : "0"}") unless psi[:show_row_headers].nil?
    psi_attrs << %( showColHeaders="#{psi[:show_col_headers] ? "1" : "0"}") unless psi[:show_col_headers].nil?
    psi_attrs << %( showRowStripes="#{psi[:show_row_stripes] ? "1" : "0"}") unless psi[:show_row_stripes].nil?
    psi_attrs << %( showColStripes="#{psi[:show_col_stripes] ? "1" : "0"}") unless psi[:show_col_stripes].nil?
    psi_attrs << %( showLastColumn="#{psi[:show_last_column] ? "1" : "0"}") unless psi[:show_last_column].nil?
    parts << "<pivotTableStyleInfo#{psi_attrs}/>"
  end

  parts << "</pivotTableDefinition>"
  parts.join
end

#generate_rels_rootObject

: () -> untyped

Returns:

  • (Object)


1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
# File 'lib/xlsxrb/ooxml/writer.rb', line 1972

def generate_rels_root
  rid_counter = 1
  parts = [
    XML_HEADER,
    %(<Relationships xmlns="#{REL_NS}">),
    %(<Relationship Id="rId#{rid_counter}" Type="#{DOC_REL_NS}/officeDocument" Target="xl/workbook.xml"/>)
  ]
  unless @core_properties.empty?
    rid_counter += 1
    parts << %(<Relationship Id="rId#{rid_counter}" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>)
  end
  if @app_properties.any?
    rid_counter += 1
    parts << %(<Relationship Id="rId#{rid_counter}" Type="#{DOC_REL_NS}/extended-properties" Target="docProps/app.xml"/>)
  end
  unless @custom_properties.empty?
    rid_counter += 1
    parts << %(<Relationship Id="rId#{rid_counter}" Type="#{DOC_REL_NS}/custom-properties" Target="docProps/custom.xml"/>)
  end
  parts << "</Relationships>"
  parts.join
end

#generate_shared_strings_xml(sst) ⇒ Object

: (untyped sst) -> untyped

Parameters:

  • sst (Object)

Returns:

  • (Object)


2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
# File 'lib/xlsxrb/ooxml/writer.rb', line 2855

def generate_shared_strings_xml(sst)
  rt_sst, str_sst = sst
  total = rt_sst.size + str_sst.size
  entries = Array.new(total)
  rt_sst.each { |rt, idx| entries[idx] = { type: :rt, value: rt } }
  str_sst.each { |str, idx| entries[idx] = { type: :str, value: str } }

  parts = [XML_HEADER, %(<sst xmlns="#{SSML_NS}" count="#{total}" uniqueCount="#{total}">)]
  entries.each do |entry|
    parts << if entry[:type] == :rt
               "<si>#{rich_text_xml(entry[:value])}</si>"
             else
               "<si><t>#{xml_escape(entry[:value])}</t></si>"
             end
  end
  parts << "</sst>"
  parts.join
end

#generate_styles_xmlObject

: () -> untyped

Returns:

  • (Object)


5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
# File 'lib/xlsxrb/ooxml/writer.rb', line 5305

def generate_styles_xml
  parts = [
    XML_HEADER,
    %(<styleSheet xmlns="#{SSML_NS}">)
  ]

  # numFmts
  unless @num_fmts.empty?
    parts << %(<numFmts count="#{@num_fmts.size}">)
    @num_fmts.each do |nf|
      parts << %(<numFmt numFmtId="#{nf[:num_fmt_id]}" formatCode="#{xml_escape(nf[:format_code])}"/>)
    end
    parts << "</numFmts>"
  end

  # fonts
  parts << %(<fonts count="#{@fonts.size}">)
  @fonts.each { |f| parts << emit_font_xml(f) }
  parts << "</fonts>"

  # fills
  parts << %(<fills count="#{@fills.size}">)
  @fills.each { |f| parts << emit_fill_xml(f) }
  parts << "</fills>"

  # borders
  parts << %(<borders count="#{@borders.size}">)
  @borders.each { |b| parts << emit_border_xml(b) }
  parts << "</borders>"

  # cellStyleXfs
  parts << %(<cellStyleXfs count="#{@cell_style_xfs.size}">)
  @cell_style_xfs.each do |xf|
    parts << %(<xf numFmtId="#{xf[:num_fmt_id]}" fontId="#{xf[:font_id]}" fillId="#{xf[:fill_id]}" borderId="#{xf[:border_id]}"/>)
  end
  parts << "</cellStyleXfs>"

  # cellXfs
  parts << %(<cellXfs count="#{@xf_entries.size}">)
  @xf_entries.each do |xf|
    apply_attrs = []
    apply_attrs << ' applyNumberFormat="1"' if xf[:num_fmt_id].positive?
    apply_attrs << ' applyFont="1"' if xf[:font_id].positive?
    apply_attrs << ' applyFill="1"' if xf[:fill_id].positive?
    apply_attrs << ' applyBorder="1"' if xf[:border_id].positive?
    apply_attrs << ' applyAlignment="1"' if xf[:alignment]
    apply_attrs << ' applyProtection="1"' if xf[:protection]
    apply_attrs << ' quotePrefix="1"' if xf[:quote_prefix]
    apply_attrs << ' pivotButton="1"' if xf[:pivot_button]
    children = []
    children << emit_alignment_xml(xf[:alignment]) if xf[:alignment]
    children << emit_protection_xml(xf[:protection]) if xf[:protection]
    xf_id = xf[:xf_id] || 0
    parts << if children.any?
               %(<xf numFmtId="#{xf[:num_fmt_id]}" fontId="#{xf[:font_id]}" fillId="#{xf[:fill_id]}" borderId="#{xf[:border_id]}" xfId="#{xf_id}"#{apply_attrs.join}>#{children.join}</xf>)
             else
               %(<xf numFmtId="#{xf[:num_fmt_id]}" fontId="#{xf[:font_id]}" fillId="#{xf[:fill_id]}" borderId="#{xf[:border_id]}" xfId="#{xf_id}"#{apply_attrs.join}/>)
             end
  end
  parts << "</cellXfs>"

  # cellStyles
  parts << %(<cellStyles count="#{@cell_style_names.size}">)
  @cell_style_names.each do |cs|
    cs_attrs = %(name="#{xml_escape(cs[:name])}" xfId="#{cs[:xf_id]}")
    cs_attrs << %( builtinId="#{cs[:builtin_id]}") if cs[:builtin_id]
    cs_attrs << %( iLevel="#{cs[:i_level]}") if cs[:i_level]
    cs_attrs << ' hidden="1"' if cs[:hidden]
    cs_attrs << ' customBuiltin="1"' if cs[:custom_builtin]
    parts << "<cellStyle #{cs_attrs}/>"
  end
  parts << "</cellStyles>"

  # dxfs
  unless @dxfs.empty?
    parts << %(<dxfs count="#{@dxfs.size}">)
    @dxfs.each { |d| parts << emit_dxf_xml(d) }
    parts << "</dxfs>"
  end

  # tableStyles
  ts_styles = @table_styles[:styles] || []
  unless ts_styles.empty? && @table_styles[:default_table_style].nil? && @table_styles[:default_pivot_style].nil?
    ts_attrs = [%(count="#{ts_styles.size}")]
    ts_attrs << %(defaultTableStyle="#{xml_escape(@table_styles[:default_table_style])}") if @table_styles[:default_table_style]
    ts_attrs << %(defaultPivotStyle="#{xml_escape(@table_styles[:default_pivot_style])}") if @table_styles[:default_pivot_style]
    if ts_styles.empty?
      parts << "<tableStyles #{ts_attrs.join(" ")}/>"
    else
      parts << "<tableStyles #{ts_attrs.join(" ")}>"
      ts_styles.each do |ts|
        s_attrs = [%(name="#{xml_escape(ts[:name])}")]
        s_attrs << %(pivot="0") if ts[:pivot] == false
        s_attrs << %(table="0") if ts[:table] == false
        s_attrs << %(count="#{ts[:elements].size}") unless ts[:elements].empty?
        if ts[:elements].empty?
          parts << "<tableStyle #{s_attrs.join(" ")}/>"
        else
          parts << "<tableStyle #{s_attrs.join(" ")}>"
          ts[:elements].each do |el|
            el_attrs = [%(type="#{el[:type]}")]
            el_attrs << %(size="#{el[:size]}") if el[:size] && el[:size] != 1
            el_attrs << %(dxfId="#{el[:dxf_id]}") if el[:dxf_id]
            parts << "<tableStyleElement #{el_attrs.join(" ")}/>"
          end
          parts << "</tableStyle>"
        end
      end
      parts << "</tableStyles>"
    end
  end

  # colors
  unless @indexed_colors.empty? && @mru_colors.empty?
    parts << "<colors>"
    unless @indexed_colors.empty?
      parts << "<indexedColors>"
      @indexed_colors.each { |c| parts << %(<rgbColor rgb="#{c}"/>) }
      parts << "</indexedColors>"
    end
    unless @mru_colors.empty?
      parts << "<mruColors>"
      @mru_colors.each { |c| parts << emit_color_xml(c) }
      parts << "</mruColors>"
    end
    parts << "</colors>"
  end

  parts << "</styleSheet>"
  parts.join
end

#generate_table_xml(tbl) ⇒ Object

: (untyped tbl) -> untyped

Parameters:

  • tbl (Object)

Returns:

  • (Object)


2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
# File 'lib/xlsxrb/ooxml/writer.rb', line 2875

def generate_table_xml(tbl)
  trc = tbl[:totals_row_count].to_i
  table_attrs = %(xmlns="#{SSML_NS}" id="#{tbl[:id]}" name="#{xml_escape(tbl[:name])}" displayName="#{xml_escape(tbl[:display_name])}" ref="#{tbl[:ref]}")
  table_attrs << %( comment="#{xml_escape(tbl[:comment])}") if tbl[:comment]
  hrc = tbl[:header_row_count]
  table_attrs << %( headerRowCount="#{hrc}") if hrc && hrc != 1
  table_attrs << ' insertRow="1"' if tbl[:insert_row]
  table_attrs << ' insertRowShift="1"' if tbl[:insert_row_shift]
  table_attrs << %( totalsRowCount="#{trc}") if trc.positive?
  table_attrs << ' totalsRowShown="0"' if trc.zero?
  table_attrs << ' published="1"' if tbl[:published]
  table_attrs << %( headerRowDxfId="#{tbl[:header_row_dxf_id]}") if tbl[:header_row_dxf_id]
  table_attrs << %( dataDxfId="#{tbl[:data_dxf_id]}") if tbl[:data_dxf_id]
  table_attrs << %( totalsRowDxfId="#{tbl[:totals_row_dxf_id]}") if tbl[:totals_row_dxf_id]
  table_attrs << %( headerRowBorderDxfId="#{tbl[:header_row_border_dxf_id]}") if tbl[:header_row_border_dxf_id]
  table_attrs << %( tableBorderDxfId="#{tbl[:table_border_dxf_id]}") if tbl[:table_border_dxf_id]
  table_attrs << %( totalsRowBorderDxfId="#{tbl[:totals_row_border_dxf_id]}") if tbl[:totals_row_border_dxf_id]
  table_attrs << %( headerRowCellStyle="#{xml_escape(tbl[:header_row_cell_style])}") if tbl[:header_row_cell_style]
  table_attrs << %( totalsRowCellStyle="#{xml_escape(tbl[:totals_row_cell_style])}") if tbl[:totals_row_cell_style]
  table_attrs << %( connectionId="#{tbl[:connection_id]}") if tbl[:connection_id]
  table_attrs << %( tableType="#{xml_escape(tbl[:table_type])}") if tbl[:table_type]
  parts = [
    XML_HEADER,
    "<table #{table_attrs}>",
    %(<autoFilter ref="#{tbl[:ref]}"/>),
    %(<tableColumns count="#{tbl[:columns].size}">)
  ]
  tbl[:columns].each_with_index do |col, i|
    col_name = col.is_a?(Hash) ? col[:name] : col
    col_attrs = %(id="#{i + 1}" name="#{xml_escape(col_name)}")
    if col.is_a?(Hash)
      col_attrs << %( totalsRowFunction="#{col[:totals_row_function]}") if col[:totals_row_function]
      col_attrs << %( totalsRowLabel="#{xml_escape(col[:totals_row_label])}") if col[:totals_row_label]
      col_attrs << %( dataDxfId="#{col[:data_dxf_id]}") if col[:data_dxf_id]
      col_attrs << %( totalsRowDxfId="#{col[:totals_row_dxf_id]}") if col[:totals_row_dxf_id]
      col_attrs << %( headerRowDxfId="#{col[:header_row_dxf_id]}") if col[:header_row_dxf_id]
      col_attrs << %( dataCellStyle="#{xml_escape(col[:data_cell_style])}") if col[:data_cell_style]
      if col[:calculated_column_formula] || col[:totals_row_formula]
        parts << "<tableColumn #{col_attrs}>"
        parts << "<calculatedColumnFormula>#{xml_escape(col[:calculated_column_formula])}</calculatedColumnFormula>" if col[:calculated_column_formula]
        parts << "<totalsRowFormula>#{xml_escape(col[:totals_row_formula])}</totalsRowFormula>" if col[:totals_row_formula]
        parts << "</tableColumn>"
      else
        parts << "<tableColumn #{col_attrs}/>"
      end
    else
      parts << "<tableColumn #{col_attrs}/>"
    end
  end
  parts << "</tableColumns>"
  style = tbl[:style] || {}
  style_name = style[:name] || "TableStyleMedium2"
  sfc = style[:show_first_column] ? "1" : "0"
  slc = style[:show_last_column] ? "1" : "0"
  srs = if style.key?(:show_row_stripes)
          style[:show_row_stripes] ? "1" : "0"
        else
          "1"
        end
  scs = style[:show_column_stripes] ? "1" : "0"
  parts << %(<tableStyleInfo name="#{xml_escape(style_name)}" showFirstColumn="#{sfc}" showLastColumn="#{slc}" showRowStripes="#{srs}" showColumnStripes="#{scs}"/>)
  parts << "</table>"
  parts.join
end

#generate_vml_drawing_xml(sheet_comments) ⇒ Object

: (untyped sheet_comments) -> untyped

Parameters:

  • sheet_comments (Object)

Returns:

  • (Object)


4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
# File 'lib/xlsxrb/ooxml/writer.rb', line 4547

def generate_vml_drawing_xml(sheet_comments)
  parts = [
    '<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">',
    '<o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout>',
    '<v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe">',
    '<v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/>',
    "</v:shapetype>"
  ]
  sheet_comments.each_with_index do |c, idx|
    col, row = cell_to_col_row(c[:ref])
    shape_id = 1025 + idx
    parts << %(<v:shape id="_x0000_s#{shape_id}" type="#_x0000_t202" style="position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;z-index:#{idx + 1};visibility:hidden" fillcolor="#ffffe1" o:insetmode="auto">)
    parts << '<v:fill color2="#ffffe1"/>'
    parts << '<v:shadow on="t" color="black" obscured="t"/>'
    parts << '<v:path o:connecttype="none"/>'
    parts << '<v:textbox style="mso-direction-alt:auto"><div style="text-align:left"></div></v:textbox>'
    parts << '<x:ClientData ObjectType="Note">'
    parts << "<x:MoveWithCells/><x:SizeWithCells/>"
    parts << "<x:Anchor>#{col + 1}, 15, #{row}, 10, #{col + 3}, 15, #{row + 4}, 4</x:Anchor>"
    parts << "<x:AutoFill>False</x:AutoFill>"
    parts << "<x:Row>#{row}</x:Row>"
    parts << "<x:Column>#{col}</x:Column>"
    parts << "</x:ClientData></v:shape>"
  end
  parts << "</xml>"
  parts.join
end

#generate_workbook_rels(has_calc_chain: false) ⇒ Object

: (?has_calc_chain: bool) -> untyped

Parameters:

  • has_calc_chain: (Object) (defaults to: false)

Returns:

  • (Object)


2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
# File 'lib/xlsxrb/ooxml/writer.rb', line 2201

def generate_workbook_rels(has_calc_chain: false)
  parts = [
    XML_HEADER,
    %(<Relationships xmlns="#{REL_NS}">)
  ]
  @sheet_order.each_with_index do |_, i|
    parts << %(<Relationship Id="rId#{i + 1}" Type="#{DOC_REL_NS}/worksheet" Target="worksheets/sheet#{i + 1}.xml"/>)
  end
  next_rid = @sheet_order.size + 1
  parts << %(<Relationship Id="rId#{next_rid}" Type="#{DOC_REL_NS}/styles" Target="styles.xml"/>)
  next_rid += 1
  if @use_shared_strings
    parts << %(<Relationship Id="rId#{next_rid}" Type="#{DOC_REL_NS}/sharedStrings" Target="sharedStrings.xml"/>)
    next_rid += 1
  end
  (1..@pivot_cache_count.to_i).each do |c|
    parts << %(<Relationship Id="rId#{next_rid}" Type="#{DOC_REL_NS}/pivotCacheDefinition" Target="pivotCache/pivotCacheDefinition#{c}.xml"/>)
    next_rid += 1
  end
  @external_links.each_with_index do |_, idx|
    parts << %(<Relationship Id="rId#{next_rid}" Type="#{DOC_REL_NS}/externalLink" Target="externalLinks/externalLink#{idx + 1}.xml"/>)
    next_rid += 1
  end
  if has_calc_chain
    parts << %(<Relationship Id="rId#{next_rid}" Type="#{DOC_REL_NS}/calcChain" Target="calcChain.xml"/>)
    next_rid += 1
  end
  parts << "</Relationships>"
  parts.join
end

#generate_workbook_xml(pivot_cache_count = 0) ⇒ Object

: (?::Integer pivot_cache_count) -> untyped

Parameters:

  • pivot_cache_count (Object) (defaults to: 0)

Returns:

  • (Object)


1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
# File 'lib/xlsxrb/ooxml/writer.rb', line 1996

def generate_workbook_xml(pivot_cache_count = 0)
  wb_attrs = %(xmlns="#{SSML_NS}" xmlns:r="#{DOC_REL_NS}")
  wb_attrs << %( conformance="#{@workbook_properties[:conformance]}") if @workbook_properties[:conformance]
  parts = [
    XML_HEADER,
    "<workbook #{wb_attrs}>"
  ]

  # fileVersion
  unless @file_version.empty?
    fv_attrs = []
    fv_attrs << %(appName="#{xml_escape(@file_version[:app_name])}") if @file_version[:app_name]
    fv_attrs << %(lastEdited="#{@file_version[:last_edited]}") if @file_version[:last_edited]
    fv_attrs << %(lowestEdited="#{@file_version[:lowest_edited]}") if @file_version[:lowest_edited]
    fv_attrs << %(rupBuild="#{@file_version[:rup_build]}") if @file_version[:rup_build]
    fv_attrs << %(codeName="#{xml_escape(@file_version[:code_name])}") if @file_version[:code_name]
    parts << "<fileVersion #{fv_attrs.join(" ")}/>" unless fv_attrs.empty?
  end

  # fileSharing
  unless @file_sharing.empty?
    fs_attrs = []
    fs_attrs << 'readOnlyRecommended="1"' if @file_sharing[:read_only_recommended]
    fs_attrs << %(userName="#{xml_escape(@file_sharing[:user_name])}") if @file_sharing[:user_name]
    fs_attrs << %(algorithmName="#{xml_escape(@file_sharing[:algorithm_name])}") if @file_sharing[:algorithm_name]
    fs_attrs << %(hashValue="#{@file_sharing[:hash_value]}") if @file_sharing[:hash_value]
    fs_attrs << %(saltValue="#{@file_sharing[:salt_value]}") if @file_sharing[:salt_value]
    fs_attrs << %(spinCount="#{@file_sharing[:spin_count]}") if @file_sharing[:spin_count]
    parts << "<fileSharing #{fs_attrs.join(" ")}/>" unless fs_attrs.empty?
  end

  # workbookPr
  unless @workbook_properties.empty?
    attrs = []
    attrs << %(date1904="#{@workbook_properties[:date1904] ? 1 : 0}") unless @workbook_properties[:date1904].nil?
    attrs << %(dateCompatibility="0") if @workbook_properties[:date_compatibility] == false
    attrs << %(defaultThemeVersion="#{@workbook_properties[:default_theme_version]}") if @workbook_properties[:default_theme_version]
    attrs << %(codeName="#{xml_escape(@workbook_properties[:code_name])}") if @workbook_properties[:code_name]
    attrs << %(filterPrivacy="1") if @workbook_properties[:filter_privacy]
    attrs << %(autoCompressPictures="0") if @workbook_properties[:auto_compress_pictures] == false
    attrs << %(backupFile="1") if @workbook_properties[:backup_file]
    attrs << %(showObjects="#{xml_escape(@workbook_properties[:show_objects])}") if @workbook_properties[:show_objects]
    attrs << %(updateLinks="#{xml_escape(@workbook_properties[:update_links])}") if @workbook_properties[:update_links]
    attrs << %(refreshAllConnections="1") if @workbook_properties[:refresh_all_connections]
    attrs << %(checkCompatibility="1") if @workbook_properties[:check_compatibility]
    attrs << %(hidePivotFieldList="1") if @workbook_properties[:hide_pivot_field_list]
    attrs << %(showBorderUnselectedTables="0") if @workbook_properties[:show_border_unselected_tables] == false
    attrs << %(promptedSolutions="1") if @workbook_properties[:prompted_solutions]
    attrs << %(showInkAnnotation="0") if @workbook_properties[:show_ink_annotation] == false
    attrs << %(saveExternalLinkValues="0") if @workbook_properties[:save_external_link_values] == false
    attrs << %(showPivotChartFilter="1") if @workbook_properties[:show_pivot_chart_filter]
    attrs << %(allowRefreshQuery="1") if @workbook_properties[:allow_refresh_query]
    attrs << %(publishItems="1") if @workbook_properties[:publish_items]
    parts << "<workbookPr #{attrs.join(" ")}/>" unless attrs.empty?
  end

  # bookViews/workbookView
  unless @workbook_views.empty?
    attrs = []
    attrs << %(visibility="#{@workbook_views[:visibility]}") if @workbook_views[:visibility]
    attrs << 'minimized="1"' if @workbook_views[:minimized]
    shs = @workbook_views[:show_horizontal_scroll]
    attrs << %(showHorizontalScroll="#{shs ? 1 : 0}") unless shs.nil?
    svs = @workbook_views[:show_vertical_scroll]
    attrs << %(showVerticalScroll="#{svs ? 1 : 0}") unless svs.nil?
    sst = @workbook_views[:show_sheet_tabs]
    attrs << %(showSheetTabs="#{sst ? 1 : 0}") unless sst.nil?
    attrs << %(xWindow="#{@workbook_views[:x_window]}") if @workbook_views[:x_window]
    attrs << %(yWindow="#{@workbook_views[:y_window]}") if @workbook_views[:y_window]
    attrs << %(windowWidth="#{@workbook_views[:window_width]}") if @workbook_views[:window_width]
    attrs << %(windowHeight="#{@workbook_views[:window_height]}") if @workbook_views[:window_height]
    attrs << %(tabRatio="#{@workbook_views[:tab_ratio]}") if @workbook_views[:tab_ratio]
    attrs << %(firstSheet="#{@workbook_views[:first_sheet]}") if @workbook_views[:first_sheet]
    attrs << %(activeTab="#{@workbook_views[:active_tab]}") if @workbook_views[:active_tab]
    afdg = @workbook_views[:auto_filter_date_grouping]
    attrs << %(autoFilterDateGrouping="#{afdg ? 1 : 0}") unless afdg.nil?
    parts << "<bookViews>"
    parts << "<workbookView #{attrs.join(" ")}/>" unless attrs.empty?
    parts << "</bookViews>"
  end

  parts << "<sheets>"
  @sheet_order.each_with_index do |name, i|
    state = @sheet_states[name]
    state_attr = case state
                 when :hidden then ' state="hidden"'
                 when :very_hidden then ' state="veryHidden"'
                 else ""
                 end
    parts << %(<sheet name="#{xml_escape(name)}" sheetId="#{i + 1}"#{state_attr} r:id="rId#{i + 1}"/>)
  end
  parts << "</sheets>"

  # workbookProtection
  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 << 'lockRevision="1"' if @workbook_protection[:lock_revision]
    if @workbook_protection[:algorithm_name]
      wp_attrs << %(workbookAlgorithmName="#{xml_escape(@workbook_protection[:algorithm_name])}")
      wp_attrs << %(workbookHashValue="#{xml_escape(@workbook_protection[:hash_value])}") if @workbook_protection[:hash_value]
      wp_attrs << %(workbookSaltValue="#{xml_escape(@workbook_protection[:salt_value])}") if @workbook_protection[:salt_value]
      wp_attrs << %(workbookSpinCount="#{@workbook_protection[:spin_count]}") if @workbook_protection[:spin_count]
    elsif @workbook_protection[:password]
      wp_attrs << %(workbookPassword="#{xml_escape(@workbook_protection[:password])}")
    end
    if @workbook_protection[:revisions_algorithm_name]
      wp_attrs << %(revisionsAlgorithmName="#{xml_escape(@workbook_protection[:revisions_algorithm_name])}")
      wp_attrs << %(revisionsHashValue="#{xml_escape(@workbook_protection[:revisions_hash_value])}") if @workbook_protection[:revisions_hash_value]
      wp_attrs << %(revisionsSaltValue="#{xml_escape(@workbook_protection[:revisions_salt_value])}") if @workbook_protection[:revisions_salt_value]
      wp_attrs << %(revisionsSpinCount="#{@workbook_protection[:revisions_spin_count]}") if @workbook_protection[:revisions_spin_count]
    elsif @workbook_protection[:revisions_password]
      wp_attrs << %(revisionsPassword="#{xml_escape(@workbook_protection[:revisions_password])}")
    end
    parts << "<workbookProtection #{wp_attrs.join(" ")}/>" unless wp_attrs.empty?
  end

  # externalReferences
  unless @external_links.empty?
    # rId for external links: after sheets + styles + optional SST + pivot caches
    el_rid_base = @sheet_order.size + 1 + (@use_shared_strings ? 1 : 0) + 1 + pivot_cache_count
    parts << "<externalReferences>"
    @external_links.each_with_index do |_, idx|
      parts << %(<externalReference r:id="rId#{el_rid_base + idx}"/>)
    end
    parts << "</externalReferences>"
  end

  # definedNames
  unless @defined_names.empty?
    parts << "<definedNames>"
    @defined_names.each do |dn|
      attrs = %(name="#{xml_escape(dn[:name])}")
      attrs << %( localSheetId="#{dn[:local_sheet_id]}") if dn[:local_sheet_id]
      attrs << ' hidden="1"' if dn[:hidden]
      attrs << %( comment="#{xml_escape(dn[:comment])}") if dn[:comment]
      attrs << %( description="#{xml_escape(dn[:description])}") if dn[:description]
      attrs << ' function="1"' if dn[:function]
      attrs << ' vbProcedure="1"' if dn[:vb_procedure]
      attrs << ' xlm="1"' if dn[:xlm]
      attrs << %( shortcutKey="#{xml_escape(dn[:shortcut_key])}") if dn[:shortcut_key]
      attrs << ' publishToServer="1"' if dn[:publish_to_server]
      attrs << ' workbookParameter="1"' if dn[:workbook_parameter]
      attrs << %( functionGroupId="#{dn[:function_group_id]}") if dn[:function_group_id]
      attrs << %( customMenu="#{xml_escape(dn[:custom_menu])}") if dn[:custom_menu]
      attrs << %( help="#{xml_escape(dn[:help])}") if dn[:help]
      attrs << %( statusBar="#{xml_escape(dn[:status_bar])}") if dn[:status_bar]
      parts << "<definedName #{attrs}>#{xml_escape(dn[:value])}</definedName>"
    end
    parts << "</definedNames>"
  end

  # calcPr
  unless @calc_properties.empty?
    attrs = []
    attrs << %(calcId="#{@calc_properties[:calc_id]}") if @calc_properties[:calc_id]
    attrs << %(calcMode="#{@calc_properties[:calc_mode]}") if @calc_properties[:calc_mode]
    attrs << %(fullCalcOnLoad="#{@calc_properties[:full_calc_on_load] ? 1 : 0}") unless @calc_properties[:full_calc_on_load].nil?
    attrs << %(iterate="#{@calc_properties[:iterate] ? 1 : 0}") unless @calc_properties[:iterate].nil?
    attrs << %(iterateCount="#{@calc_properties[:iterate_count]}") if @calc_properties[:iterate_count]
    attrs << %(iterateDelta="#{@calc_properties[:iterate_delta]}") if @calc_properties[:iterate_delta]
    attrs << %(refMode="#{@calc_properties[:ref_mode]}") if @calc_properties[:ref_mode]
    attrs << %(calcCompleted="#{@calc_properties[:calc_completed] ? 1 : 0}") unless @calc_properties[:calc_completed].nil?
    attrs << %(calcOnSave="#{@calc_properties[:calc_on_save] ? 1 : 0}") unless @calc_properties[:calc_on_save].nil?
    fp = @calc_properties[:full_precision]
    attrs << %(fullPrecision="#{fp ? 1 : 0}") unless fp.nil?
    conc = @calc_properties[:concurrent_calc]
    attrs << %(concurrentCalc="#{conc ? 1 : 0}") unless conc.nil?
    attrs << %(concurrentManualCount="#{@calc_properties[:concurrent_manual_count]}") if @calc_properties[:concurrent_manual_count]
    ffc = @calc_properties[:force_full_calc]
    attrs << %(forceFullCalc="#{ffc ? 1 : 0}") unless ffc.nil?
    parts << "<calcPr #{attrs.join(" ")}/>" unless attrs.empty?
  end

  # pivotCaches (reference from workbook to cache definition rels)
  if pivot_cache_count.positive?
    # rId layout: sheets(1..N), styles(N+1), optional SST(N+2), then pivot caches
    pivot_rid_base = @sheet_order.size + 1 + (@use_shared_strings ? 1 : 0) + 1
    parts << "<pivotCaches>"
    pivot_cache_count.times do |ci|
      parts << %(<pivotCache cacheId="#{ci + 1}" r:id="rId#{pivot_rid_base + ci}"/>)
    end
    parts << "</pivotCaches>"
  end

  # fileRecoveryPr
  unless @file_recovery_properties.empty?
    frp_attrs = []
    ar = @file_recovery_properties[:auto_recover]
    frp_attrs << %(autoRecover="#{ar ? 1 : 0}") unless ar.nil?
    cs = @file_recovery_properties[:crash_save]
    frp_attrs << %(crashSave="#{cs ? 1 : 0}") unless cs.nil?
    del = @file_recovery_properties[:data_extract_load]
    frp_attrs << %(dataExtractLoad="#{del ? 1 : 0}") unless del.nil?
    rl = @file_recovery_properties[:repair_load]
    frp_attrs << %(repairLoad="#{rl ? 1 : 0}") unless rl.nil?
    parts << "<fileRecoveryPr #{frp_attrs.join(" ")}/>" unless frp_attrs.empty?
  end

  parts << "</workbook>"
  parts.join
end

#generate_worksheet_rels(sheet_hyperlinks, sheet_tables = [], table_start_index = 0) ⇒ Object

: (untyped sheet_hyperlinks, ?untyped sheet_tables, ?::Integer table_start_index) -> untyped

Parameters:

  • sheet_hyperlinks (Object)
  • sheet_tables (Object) (defaults to: [])
  • table_start_index (Object) (defaults to: 0)

Returns:

  • (Object)


2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
# File 'lib/xlsxrb/ooxml/writer.rb', line 2941

def generate_worksheet_rels(sheet_hyperlinks, sheet_tables = [], table_start_index = 0)
  parts = [
    XML_HEADER,
    %(<Relationships xmlns="#{REL_NS}">)
  ]
  rid = 0
  sheet_hyperlinks.each do |(_cell_ref, link)|
    next unless link[:url]

    rid += 1
    parts << %(<Relationship Id="rId#{rid}" Type="#{DOC_REL_NS}/hyperlink" Target="#{xml_escape(link[:url])}" TargetMode="External"/>)
  end
  sheet_tables.each_with_index do |_tbl, i|
    rid += 1
    parts << %(<Relationship Id="rId#{rid}" Type="#{DOC_REL_NS}/table" Target="../tables/table#{table_start_index + i + 1}.xml"/>)
  end
  parts << "</Relationships>"
  parts.join
end

#generate_worksheet_xml(sheet_cells, sheet_col_widths, sheet_col_attrs, sheet_row_attrs, sheet_auto_filter, sheet_filter_cols, sheet_sort, sheet_merge_cells, sheet_hyperlinks, sheet_cell_styles, sheet_props, sheet_fmt, sheet_sv, sheet_fp, sheet_sel, sheet_po, sheet_pm, sheet_ps, sheet_hf, sheet_rb, sheet_cb, sheet_dv, sheet_cf, sst = nil, sheet_tables = [], hyperlink_count = 0, has_drawing: false, has_comments: false, sheet_prot: nil, vml_rid: nil, phonetic_pr: nil, dv_options: {}, prot_ranges: [], cell_watches: [], ignored_errors: [], data_consol: nil, sheet_scenarios: nil, cell_phonetic: {}) ⇒ Object

: (untyped sheet_cells, untyped sheet_col_widths, untyped sheet_col_attrs, untyped sheet_row_attrs, untyped sheet_auto_filter, untyped sheet_filter_cols, untyped sheet_sort, untyped sheet_merge_cells, untyped sheet_hyperlinks, untyped sheet_cell_styles, untyped sheet_props, untyped sheet_fmt, untyped sheet_sv, untyped sheet_fp, untyped sheet_sel, untyped sheet_po, untyped sheet_pm, untyped sheet_ps, untyped sheet_hf, untyped sheet_rb, untyped sheet_cb, untyped sheet_dv, untyped sheet_cf, ?untyped? sst, ?untyped sheet_tables, ?::Integer hyperlink_count, ?has_drawing: bool, ?has_comments: bool, ?sheet_prot: untyped?, ?vml_rid: untyped?, ?phonetic_pr: untyped?, ?dv_options: ::Hash[untyped, untyped], ?prot_ranges: untyped, ?cell_watches: untyped, ?ignored_errors: untyped, ?data_consol: untyped?, ?sheet_scenarios: untyped?, ?cell_phonetic: ::Hash[untyped, untyped]) -> untyped

Parameters:

  • sheet_cells (Object)
  • sheet_col_widths (Object)
  • sheet_col_attrs (Object)
  • sheet_row_attrs (Object)
  • sheet_auto_filter (Object)
  • sheet_filter_cols (Object)
  • sheet_sort (Object)
  • sheet_merge_cells (Object)
  • sheet_hyperlinks (Object)
  • sheet_cell_styles (Object)
  • sheet_props (Object)
  • sheet_fmt (Object)
  • sheet_sv (Object)
  • sheet_fp (Object)
  • sheet_sel (Object)
  • sheet_po (Object)
  • sheet_pm (Object)
  • sheet_ps (Object)
  • sheet_hf (Object)
  • sheet_rb (Object)
  • sheet_cb (Object)
  • sheet_dv (Object)
  • sheet_cf (Object)
  • sst (Object) (defaults to: nil)
  • sheet_tables (Object) (defaults to: [])
  • hyperlink_count (Object) (defaults to: 0)
  • has_drawing: (Object) (defaults to: false)
  • has_comments: (Object) (defaults to: false)
  • sheet_prot: (Object) (defaults to: nil)
  • vml_rid: (Object) (defaults to: nil)
  • phonetic_pr: (Object) (defaults to: nil)
  • dv_options: (Object) (defaults to: {})
  • prot_ranges: (Object) (defaults to: [])
  • cell_watches: (Object) (defaults to: [])
  • ignored_errors: (Object) (defaults to: [])
  • data_consol: (Object) (defaults to: nil)
  • sheet_scenarios: (Object) (defaults to: nil)
  • cell_phonetic: (Object) (defaults to: {})

Returns:

  • (Object)


2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
# File 'lib/xlsxrb/ooxml/writer.rb', line 2251

def generate_worksheet_xml(sheet_cells, sheet_col_widths, sheet_col_attrs, sheet_row_attrs, sheet_auto_filter, sheet_filter_cols, sheet_sort, sheet_merge_cells, sheet_hyperlinks, sheet_cell_styles, sheet_props, sheet_fmt, sheet_sv, sheet_fp, sheet_sel, sheet_po, sheet_pm, sheet_ps, sheet_hf, sheet_rb, sheet_cb, sheet_dv, sheet_cf, sst = nil, sheet_tables = [], hyperlink_count = 0, has_drawing: false, has_comments: false, sheet_prot: nil, vml_rid: nil, phonetic_pr: nil, dv_options: {}, prot_ranges: [], cell_watches: [], ignored_errors: [], data_consol: nil, sheet_scenarios: nil, cell_phonetic: {})
  needs_r_ns = !sheet_hyperlinks.empty? || sheet_tables.any? || has_drawing || has_comments
  worksheet_attrs = %(xmlns="#{SSML_NS}")
  worksheet_attrs << %( xmlns:r="#{DOC_REL_NS}") if needs_r_ns
  parts = [
    XML_HEADER,
    "<worksheet #{worksheet_attrs}>"
  ]

  # Emit <sheetPr> if sheet properties are defined.
  unless sheet_props.empty?
    sp_attrs = []
    sp_attrs << 'syncHorizontal="1"' if sheet_props[:sync_horizontal]
    sp_attrs << 'syncVertical="1"' if sheet_props[:sync_vertical]
    sp_attrs << %(syncRef="#{sheet_props[:sync_ref]}") if sheet_props[:sync_ref]
    sp_attrs << 'transitionEvaluation="1"' if sheet_props[:transition_evaluation]
    sp_attrs << 'transitionEntry="1"' if sheet_props[:transition_entry]
    sp_attrs << %(codeName="#{xml_escape(sheet_props[:code_name])}") if sheet_props[:code_name]
    sp_attrs << 'filterMode="1"' if sheet_props[:filter_mode]
    sp_attrs << 'published="0"' if sheet_props[:published] == false
    sp_attrs << 'enableFormatConditionsCalculation="0"' if sheet_props[:enable_format_conditions_calculation] == false
    sp_children = []
    if sheet_props[:tab_color]
      sp_children << %(<tabColor rgb="#{sheet_props[:tab_color]}"/>)
    elsif sheet_props[:tab_color_theme]
      tc_attrs = [%(theme="#{sheet_props[:tab_color_theme]}")]
      tc_attrs << %(tint="#{sheet_props[:tab_color_tint]}") if sheet_props[:tab_color_tint]
      sp_children << "<tabColor #{tc_attrs.join(" ")}/>"
    elsif sheet_props[:tab_color_indexed]
      sp_children << %(<tabColor indexed="#{sheet_props[:tab_color_indexed]}"/>)
    elsif sheet_props[:tab_color_auto]
      sp_children << '<tabColor auto="1"/>'
    end
    sb = sheet_props[:summary_below]
    sr = sheet_props[:summary_right]
    as = sheet_props[:apply_styles]
    sos = sheet_props[:show_outline_symbols]
    unless sb.nil? && sr.nil? && as.nil? && sos.nil?
      outline_attrs = []
      outline_attrs << %(applyStyles="#{as ? 1 : 0}") unless as.nil?
      outline_attrs << %(summaryBelow="#{sb ? 1 : 0}") unless sb.nil?
      outline_attrs << %(summaryRight="#{sr ? 1 : 0}") unless sr.nil?
      outline_attrs << %(showOutlineSymbols="#{sos ? 1 : 0}") unless sos.nil?
      sp_children << "<outlinePr #{outline_attrs.join(" ")}/>"
    end
    ftp = sheet_props[:fit_to_page]
    apb = sheet_props[:auto_page_breaks]
    unless ftp.nil? && apb.nil?
      psp_attrs = []
      psp_attrs << %(fitToPage="#{ftp ? 1 : 0}") unless ftp.nil?
      psp_attrs << %(autoPageBreaks="#{apb ? 1 : 0}") unless apb.nil?
      sp_children << "<pageSetUpPr #{psp_attrs.join(" ")}/>"
    end
    if !sp_children.empty? || !sp_attrs.empty?
      sp_open = sp_attrs.empty? ? "<sheetPr>" : "<sheetPr #{sp_attrs.join(" ")}>"
      parts << sp_open
      parts.concat(sp_children)
      parts << "</sheetPr>"
    end
  end

  # Emit <dimension> computed from cell addresses.
  parts << %(<dimension ref="#{compute_dimension(sheet_cells)}"/>) unless sheet_cells.empty?

  # Emit <sheetViews> if sheet view properties, freeze pane, or selection are defined.
  if !sheet_sv.empty? || sheet_fp || sheet_sel
    parts << "<sheetViews>"
    sv_attrs = []
    wp = sheet_sv[:window_protection]
    sv_attrs << %(windowProtection="#{wp ? 1 : 0}") unless wp.nil?
    sf = sheet_sv[:show_formulas]
    sv_attrs << %(showFormulas="#{sf ? 1 : 0}") unless sf.nil?
    sgl = sheet_sv[:show_grid_lines]
    sv_attrs << %(showGridLines="#{sgl ? 1 : 0}") unless sgl.nil?
    srch = sheet_sv[:show_row_col_headers]
    sv_attrs << %(showRowColHeaders="#{srch ? 1 : 0}") unless srch.nil?
    sz = sheet_sv[:show_zeros]
    sv_attrs << %(showZeros="#{sz ? 1 : 0}") unless sz.nil?
    rtl = sheet_sv[:right_to_left]
    sv_attrs << %(rightToLeft="#{rtl ? 1 : 0}") unless rtl.nil?
    sv_attrs << 'tabSelected="1"' if sheet_sv[:tab_selected]
    sr = sheet_sv[:show_ruler]
    sv_attrs << %(showRuler="#{sr ? 1 : 0}") unless sr.nil?
    sos = sheet_sv[:show_outline_symbols]
    sv_attrs << %(showOutlineSymbols="#{sos ? 1 : 0}") unless sos.nil?
    dgc = sheet_sv[:default_grid_color]
    sv_attrs << %(defaultGridColor="#{dgc ? 1 : 0}") unless dgc.nil?
    sws = sheet_sv[:show_white_space]
    sv_attrs << %(showWhiteSpace="#{sws ? 1 : 0}") unless sws.nil?
    sv_attrs << %(view="#{sheet_sv[:view]}") if sheet_sv[:view]
    sv_attrs << %(topLeftCell="#{sheet_sv[:top_left_cell]}") if sheet_sv[:top_left_cell]
    sv_attrs << %(colorId="#{sheet_sv[:color_id]}") if sheet_sv[:color_id]
    zs = sheet_sv[:zoom_scale]
    sv_attrs << %(zoomScale="#{zs}") if zs
    sv_attrs << %(zoomScaleNormal="#{sheet_sv[:zoom_scale_normal]}") if sheet_sv[:zoom_scale_normal]
    sv_attrs << %(zoomScaleSheetLayoutView="#{sheet_sv[:zoom_scale_sheet_layout_view]}") if sheet_sv[:zoom_scale_sheet_layout_view]
    sv_attrs << %(zoomScalePageLayoutView="#{sheet_sv[:zoom_scale_page_layout_view]}") if sheet_sv[:zoom_scale_page_layout_view]
    sv_attrs << 'workbookViewId="0"'
    parts << "<sheetView #{sv_attrs.join(" ")}>"

    if sheet_fp && sheet_fp[:state] == :split
      pane_attrs = []
      pane_attrs << %(xSplit="#{sheet_fp[:x_split]}") if sheet_fp[:x_split].to_i.positive?
      pane_attrs << %(ySplit="#{sheet_fp[:y_split]}") if sheet_fp[:y_split].to_i.positive?
      pane_attrs << %(topLeftCell="#{sheet_fp[:top_left_cell]}") if sheet_fp[:top_left_cell]
      has_x = sheet_fp[:x_split].to_i.positive?
      has_y = sheet_fp[:y_split].to_i.positive?
      active_pane = if has_y && has_x
                      "bottomRight"
                    elsif has_y
                      "bottomLeft"
                    else
                      "topRight"
                    end
      pane_attrs << %(activePane="#{active_pane}")
      parts << "<pane #{pane_attrs.join(" ")}/>"
    elsif sheet_fp && (sheet_fp[:row].to_i.positive? || sheet_fp[:col].to_i.positive?)
      top_left = "#{index_to_column_letter(sheet_fp[:col].to_i + 1)}#{sheet_fp[:row].to_i + 1}"
      pane_attrs = []
      pane_attrs << %(ySplit="#{sheet_fp[:row]}") if sheet_fp[:row].to_i.positive?
      pane_attrs << %(xSplit="#{sheet_fp[:col]}") if sheet_fp[:col].to_i.positive?
      pane_attrs << %(topLeftCell="#{top_left}")
      active_pane = if sheet_fp[:row].to_i.positive? && sheet_fp[:col].to_i.positive?
                      "bottomRight"
                    elsif sheet_fp[:row].to_i.positive?
                      "bottomLeft"
                    else
                      "topRight"
                    end
      pane_attrs << %(activePane="#{active_pane}")
      pane_attrs << 'state="frozen"'
      parts << "<pane #{pane_attrs.join(" ")}/>"
    end

    if sheet_sel
      sel_attrs = []
      sel_attrs << %(pane="#{sheet_sel[:pane]}") if sheet_sel[:pane]
      sel_attrs << %(activeCell="#{sheet_sel[:active_cell]}") if sheet_sel[:active_cell]
      sel_attrs << %(activeCellId="#{sheet_sel[:active_cell_id]}") if sheet_sel[:active_cell_id]
      sel_attrs << %(sqref="#{sheet_sel[:sqref]}") if sheet_sel[:sqref]
      parts << "<selection #{sel_attrs.join(" ")}/>"
    end

    parts << "</sheetView>"
    parts << "</sheetViews>"
  end

  # Emit <sheetFormatPr> if sheet format properties are defined.
  unless sheet_fmt.empty?
    fmt_attrs = []
    fmt_attrs << %(defaultRowHeight="#{sheet_fmt[:default_row_height]}") if sheet_fmt[:default_row_height]
    fmt_attrs << %(defaultColWidth="#{sheet_fmt[:default_col_width]}") if sheet_fmt[:default_col_width]
    fmt_attrs << %(baseColWidth="#{sheet_fmt[:base_col_width]}") if sheet_fmt[:base_col_width]
    fmt_attrs << %(outlineLevelRow="#{sheet_fmt[:outline_level_row]}") if sheet_fmt[:outline_level_row]
    fmt_attrs << %(outlineLevelCol="#{sheet_fmt[:outline_level_col]}") if sheet_fmt[:outline_level_col]
    fmt_attrs << 'customHeight="1"' if sheet_fmt[:custom_height]
    fmt_attrs << 'zeroHeight="1"' if sheet_fmt[:zero_height]
    fmt_attrs << 'thickTop="1"' if sheet_fmt[:thick_top]
    fmt_attrs << 'thickBottom="1"' if sheet_fmt[:thick_bottom]
    parts << "<sheetFormatPr #{fmt_attrs.join(" ")}/>"
  end

  # Emit <cols> if column widths or column attributes are defined.
  all_cols = sheet_col_widths.keys | sheet_col_attrs.keys
  unless all_cols.empty?
    parts << "<cols>"
    all_cols.sort_by { |col| column_letter_to_index(col) }.each do |col_letter|
      idx = column_letter_to_index(col_letter)
      width = sheet_col_widths[col_letter]
      ca = sheet_col_attrs[col_letter] || {}
      col_attrs = %(min="#{idx}" max="#{idx}")
      col_attrs << %( width="#{width}" customWidth="1") if width
      col_attrs << ' hidden="1"' if ca[:hidden]
      col_attrs << ' bestFit="1"' if ca[:best_fit]
      col_attrs << %( outlineLevel="#{ca[:outline_level]}") if ca[:outline_level]
      col_attrs << ' collapsed="1"' if ca[:collapsed]
      col_attrs << %( style="#{ca[:style]}") if ca[:style]
      col_attrs << ' phonetic="1"' if ca[:phonetic]
      parts << "<col #{col_attrs}/>"
    end
    parts << "</cols>"
  end

  parts << "<sheetData>"

  # Group cells by row number.
  cells_by_row = {}
  sheet_cells.each do |address, value|
    row_num = extract_row_number(address)
    col_letter = extract_column_letter(address)
    cells_by_row[row_num] ||= {}
    cells_by_row[row_num][col_letter] = value
  end

  # Include rows that have attributes but no cells.
  sheet_row_attrs.each_key { |rn| cells_by_row[rn] ||= {} }

  # Emit rows in ascending order.
  cells_by_row.sort.each do |row_num, row_cells|
    attrs = %(r="#{row_num}")
    ra = sheet_row_attrs[row_num]
    if ra
      attrs << %( ht="#{ra[:height]}" customHeight="1") if ra[:height]
      attrs << ' hidden="1"' if ra[:hidden]
      attrs << %( outlineLevel="#{ra[:outline_level]}") if ra[:outline_level]
      attrs << ' collapsed="1"' if ra[:collapsed]
      attrs << %( s="#{ra[:style]}" customFormat="1") if ra.key?(:style)
      attrs << ' thickTop="1"' if ra[:thick_top]
      attrs << ' thickBot="1"' if ra[:thick_bot]
      attrs << ' ph="1"' if ra[:ph]
    end
    parts << "<row #{attrs}>"
    row_cells.sort_by { |col, _| column_letter_to_index(col) }.each do |col_letter, value|
      cell_ref = "#{col_letter}#{row_num}"
      style_idx = resolve_style_index(sheet_cell_styles[cell_ref])
      parts << cell_xml(cell_ref, value, style_idx, sst, ph: cell_phonetic[cell_ref])
    end
    parts << "</row>"
  end

  parts << "</sheetData>"

  # Emit <sheetCalcPr> if fullCalcOnLoad is set.
  parts << '<sheetCalcPr fullCalcOnLoad="1"/>' if sheet_props[:full_calc_on_load]

  # Emit <sheetProtection> if defined.
  if sheet_prot
    sp_attrs = []
    sp_attrs << 'sheet="1"' if sheet_prot[:sheet] != false
    sp_attrs << 'objects="1"' if sheet_prot[:objects]
    sp_attrs << 'scenarios="1"' if sheet_prot[:scenarios]
    sp_attrs << 'formatCells="0"' if sheet_prot[:format_cells] == false
    sp_attrs << 'formatColumns="0"' if sheet_prot[:format_columns] == false
    sp_attrs << 'formatRows="0"' if sheet_prot[:format_rows] == false
    sp_attrs << 'insertColumns="0"' if sheet_prot[:insert_columns] == false
    sp_attrs << 'insertRows="0"' if sheet_prot[:insert_rows] == false
    sp_attrs << 'insertHyperlinks="0"' if sheet_prot[:insert_hyperlinks] == false
    sp_attrs << 'deleteColumns="0"' if sheet_prot[:delete_columns] == false
    sp_attrs << 'deleteRows="0"' if sheet_prot[:delete_rows] == false
    sp_attrs << 'selectLockedCells="1"' if sheet_prot[:select_locked_cells]
    sp_attrs << 'sort="0"' if sheet_prot[:sort] == false
    sp_attrs << 'autoFilter="0"' if sheet_prot[:auto_filter] == false
    sp_attrs << 'pivotTables="0"' if sheet_prot[:pivot_tables] == false
    sp_attrs << 'selectUnlockedCells="1"' if sheet_prot[:select_unlocked_cells]
    if sheet_prot[:algorithm_name]
      sp_attrs << %(algorithmName="#{xml_escape(sheet_prot[:algorithm_name])}")
      sp_attrs << %(hashValue="#{xml_escape(sheet_prot[:hash_value])}") if sheet_prot[:hash_value]
      sp_attrs << %(saltValue="#{xml_escape(sheet_prot[:salt_value])}") if sheet_prot[:salt_value]
      sp_attrs << %(spinCount="#{sheet_prot[:spin_count]}") if sheet_prot[:spin_count]
    elsif sheet_prot[:password]
      sp_attrs << %(password="#{xml_escape(sheet_prot[:password])}")
    end
    parts << "<sheetProtection #{sp_attrs.join(" ")}/>"
  end

  # Emit <protectedRanges> if defined.
  unless prot_ranges.empty?
    parts << "<protectedRanges>"
    prot_ranges.each do |pr|
      pr_attrs = [%(sqref="#{pr[:sqref]}"), %(name="#{xml_escape(pr[:name])}")]
      if pr[:algorithm_name]
        pr_attrs << %(algorithmName="#{xml_escape(pr[:algorithm_name])}")
        pr_attrs << %(hashValue="#{xml_escape(pr[:hash_value])}") if pr[:hash_value]
        pr_attrs << %(saltValue="#{xml_escape(pr[:salt_value])}") if pr[:salt_value]
        pr_attrs << %(spinCount="#{pr[:spin_count]}") if pr[:spin_count]
      end
      sds = pr[:security_descriptors] || []
      if sds.empty?
        parts << "<protectedRange #{pr_attrs.join(" ")}/>"
      else
        parts << "<protectedRange #{pr_attrs.join(" ")}>"
        sds.each { |sd| parts << "<securityDescriptor>#{xml_escape(sd)}</securityDescriptor>" }
        parts << "</protectedRange>"
      end
    end
    parts << "</protectedRanges>"
  end

  # Emit <scenarios> if defined.
  if sheet_scenarios
    sc_attrs = []
    sc_attrs << %(current="#{sheet_scenarios[:current]}") if sheet_scenarios[:current]
    sc_attrs << %(show="#{sheet_scenarios[:show]}") if sheet_scenarios[:show]
    sc_attrs << %(sqref="#{sheet_scenarios[:sqref]}") if sheet_scenarios[:sqref]
    items = sheet_scenarios[:scenarios] || []
    sc_attr_str = sc_attrs.empty? ? "" : " #{sc_attrs.join(" ")}"
    parts << "<scenarios#{sc_attr_str}>"
    items.each do |sc|
      s_attrs = [%(name="#{xml_escape(sc[:name])}")]
      s_attrs << 'locked="1"' if sc[:locked]
      s_attrs << 'hidden="1"' if sc[:hidden]
      s_attrs << %(count="#{sc[:input_cells].size}") if sc[:input_cells]&.any?
      s_attrs << %(user="#{xml_escape(sc[:user])}") if sc[:user]
      s_attrs << %(comment="#{xml_escape(sc[:comment])}") if sc[:comment]
      parts << "<scenario #{s_attrs.join(" ")}>"
      (sc[:input_cells] || []).each do |ic|
        ic_attrs = [%(r="#{ic[:r]}"), %(val="#{xml_escape(ic[:val].to_s)}")]
        ic_attrs << 'deleted="1"' if ic[:deleted]
        ic_attrs << 'undone="1"' if ic[:undone]
        ic_attrs << %(numFmtId="#{ic[:num_fmt_id]}") if ic[:num_fmt_id]
        parts << "<inputCells #{ic_attrs.join(" ")}/>"
      end
      parts << "</scenario>"
    end
    parts << "</scenarios>"
  end

  # Emit <autoFilter> with optional filterColumns.
  if sheet_auto_filter
    if sheet_filter_cols.empty?
      parts << %(<autoFilter ref="#{sheet_auto_filter}"/>)
    else
      parts << %(<autoFilter ref="#{sheet_auto_filter}">)
      sheet_filter_cols.sort.each do |col_id, filter|
        fc_attrs = %( colId="#{col_id}")
        fc_attrs << ' hiddenButton="1"' if filter[:hidden_button]
        fc_attrs << ' showButton="0"' if filter[:show_button] == false
        parts << "<filterColumn#{fc_attrs}>"
        parts << emit_filter_xml(filter)
        parts << "</filterColumn>"
      end
      parts << "</autoFilter>"
    end
  end

  # Emit <sortState> if defined.
  if sheet_sort
    ss_attrs = %( ref="#{sheet_sort[:ref]}")
    ss_attrs << ' columnSort="1"' if sheet_sort[:column_sort]
    ss_attrs << ' caseSensitive="1"' if sheet_sort[:case_sensitive]
    ss_attrs << %( sortMethod="#{sheet_sort[:sort_method]}") if sheet_sort[:sort_method]
    parts << "<sortState#{ss_attrs}>"
    sheet_sort[:sort_conditions].each do |sc|
      sc_attrs = %(ref="#{sc[:ref]}")
      sc_attrs << ' descending="1"' if sc[:descending]
      sc_attrs << %( sortBy="#{sc[:sort_by]}") if sc[:sort_by]
      sc_attrs << %( customList="#{xml_escape(sc[:custom_list])}") if sc[:custom_list]
      sc_attrs << %( dxfId="#{sc[:dxf_id]}") if sc[:dxf_id]
      sc_attrs << %( iconSet="#{sc[:icon_set]}") if sc[:icon_set]
      sc_attrs << %( iconId="#{sc[:icon_id]}") if sc[:icon_id]
      parts << "<sortCondition #{sc_attrs}/>"
    end
    parts << "</sortState>"
  end

  # Emit <dataConsolidate> if defined.
  if data_consol
    dc_attrs = []
    dc_attrs << %(function="#{data_consol[:function]}") if data_consol[:function] && data_consol[:function] != "sum"
    dc_attrs << 'startLabels="1"' if data_consol[:start_labels]
    dc_attrs << 'leftLabels="1"' if data_consol[:left_labels]
    dc_attrs << 'topLabels="1"' if data_consol[:top_labels]
    dc_attrs << 'link="1"' if data_consol[:link]
    refs = data_consol[:data_refs] || []
    dc_attr_str = dc_attrs.empty? ? "" : " #{dc_attrs.join(" ")}"
    if refs.empty?
      parts << "<dataConsolidate#{dc_attr_str}/>"
    else
      parts << "<dataConsolidate#{dc_attr_str}>"
      parts << %(<dataRefs count="#{refs.size}">)
      refs.each do |r|
        ref_attrs = []
        ref_attrs << %(ref="#{r[:ref]}") if r[:ref]
        ref_attrs << %(name="#{xml_escape(r[:name])}") if r[:name]
        ref_attrs << %(sheet="#{xml_escape(r[:sheet])}") if r[:sheet]
        parts << "<dataRef #{ref_attrs.join(" ")}/>"
      end
      parts << "</dataRefs>"
      parts << "</dataConsolidate>"
    end
  end

  # Emit <mergeCells> if merge ranges are defined.
  unless sheet_merge_cells.empty?
    parts << %(<mergeCells count="#{sheet_merge_cells.size}">)
    sheet_merge_cells.each { |ref| parts << %(<mergeCell ref="#{ref}"/>) }
    parts << "</mergeCells>"
  end

  # Emit <phoneticPr> if defined.
  if phonetic_pr
    pp_attrs = []
    pp_attrs << %(fontId="#{phonetic_pr[:font_id]}") if phonetic_pr[:font_id]
    pp_attrs << %(type="#{phonetic_pr[:type]}") if phonetic_pr[:type]
    pp_attrs << %(alignment="#{phonetic_pr[:alignment]}") if phonetic_pr[:alignment]
    parts << "<phoneticPr #{pp_attrs.join(" ")}/>"
  end

  # Emit <hyperlinks> if hyperlinks are defined.
  unless sheet_hyperlinks.empty?
    parts << "<hyperlinks>"
    ext_rid = 0
    sheet_hyperlinks.each do |(cell_ref, link)|
      attrs = %(ref="#{cell_ref}")
      if link[:url]
        ext_rid += 1
        attrs << %( r:id="rId#{ext_rid}")
      end
      attrs << %( display="#{xml_escape(link[:display])}") if link[:display]
      attrs << %( tooltip="#{xml_escape(link[:tooltip])}") if link[:tooltip]
      attrs << %( location="#{xml_escape(link[:location])}") if link[:location]
      parts << %(<hyperlink #{attrs}/>)
    end
    parts << "</hyperlinks>"
  end

  # Emit <conditionalFormatting> if defined.
  unless sheet_cf.empty?
    sheet_cf.group_by { |cf| cf[:sqref] }.each do |sqref, rules|
      cf_attrs = %( sqref="#{sqref}")
      cf_attrs << ' pivot="1"' if rules.any? { |r| r[:pivot] }
      parts << "<conditionalFormatting#{cf_attrs}>"
      rules.each do |cf|
        emit_cf_rule(parts, cf)
      end
      parts << "</conditionalFormatting>"
    end
  end

  # Emit <dataValidations> if defined.
  unless sheet_dv.empty?
    dv_container_attrs = %( count="#{sheet_dv.size}")
    dv_container_attrs << ' disablePrompts="1"' if dv_options[:disable_prompts]
    dv_container_attrs << %( xWindow="#{dv_options[:x_window]}") if dv_options[:x_window]
    dv_container_attrs << %( yWindow="#{dv_options[:y_window]}") if dv_options[:y_window]
    parts << "<dataValidations#{dv_container_attrs}>"
    sheet_dv.each do |dv|
      dv_attrs = %(sqref="#{dv[:sqref]}")
      dv_attrs << %( type="#{dv[:type]}") if dv[:type]
      dv_attrs << %( operator="#{dv[:operator]}") if dv[:operator]
      dv_attrs << %( errorStyle="#{dv[:error_style]}") if dv[:error_style]
      dv_attrs << ' allowBlank="1"' if dv[:allow_blank]
      dv_attrs << ' showInputMessage="1"' if dv[:show_input_message]
      dv_attrs << ' showErrorMessage="1"' if dv[:show_error_message]
      dv_attrs << %( errorTitle="#{xml_escape(dv[:error_title])}") if dv[:error_title]
      dv_attrs << %( error="#{xml_escape(dv[:error])}") if dv[:error]
      dv_attrs << %( promptTitle="#{xml_escape(dv[:prompt_title])}") if dv[:prompt_title]
      dv_attrs << %( prompt="#{xml_escape(dv[:prompt])}") if dv[:prompt]
      dv_attrs << ' showDropDown="1"' if dv[:show_drop_down]
      dv_attrs << %( imeMode="#{dv[:ime_mode]}") if dv[:ime_mode]
      if dv[:formula1] || dv[:formula2]
        parts << "<dataValidation #{dv_attrs}>"
        parts << "<formula1>#{xml_escape(dv[:formula1])}</formula1>" if dv[:formula1]
        parts << "<formula2>#{xml_escape(dv[:formula2])}</formula2>" if dv[:formula2]
        parts << "</dataValidation>"
      else
        parts << "<dataValidation #{dv_attrs}/>"
      end
    end
    parts << "</dataValidations>"
  end

  # Emit <printOptions> if defined.
  unless sheet_po.empty?
    po_attrs = []
    po_attrs << 'gridLines="1"' if sheet_po[:grid_lines]
    po_attrs << 'headings="1"' if sheet_po[:headings]
    po_attrs << 'horizontalCentered="1"' if sheet_po[:horizontal_centered]
    po_attrs << 'verticalCentered="1"' if sheet_po[:vertical_centered]
    po_attrs << 'gridLinesSet="0"' if sheet_po[:grid_lines_set] == false
    parts << "<printOptions #{po_attrs.join(" ")}/>" unless po_attrs.empty?
  end

  # Emit <pageMargins> if defined.
  if sheet_pm
    pm_attrs = %w[left right top bottom header footer].filter_map do |k|
      v = sheet_pm[k.to_sym]
      %(#{k}="#{v}") if v
    end
    parts << "<pageMargins #{pm_attrs.join(" ")}/>" unless pm_attrs.empty?
  end

  # Emit <pageSetup> if defined.
  unless sheet_ps.empty?
    ps_attrs = []
    ps_attrs << %(orientation="#{sheet_ps[:orientation]}") if sheet_ps[:orientation]
    ps_attrs << %(paperSize="#{sheet_ps[:paper_size]}") if sheet_ps[:paper_size]
    ps_attrs << %(scale="#{sheet_ps[:scale]}") if sheet_ps[:scale]
    ps_attrs << %(fitToWidth="#{sheet_ps[:fit_to_width]}") if sheet_ps[:fit_to_width]
    ps_attrs << %(fitToHeight="#{sheet_ps[:fit_to_height]}") if sheet_ps[:fit_to_height]
    ps_attrs << %(pageOrder="#{sheet_ps[:page_order]}") if sheet_ps[:page_order]
    ps_attrs << 'blackAndWhite="1"' if sheet_ps[:black_and_white]
    ps_attrs << 'draft="1"' if sheet_ps[:draft]
    ps_attrs << %(cellComments="#{sheet_ps[:cell_comments]}") if sheet_ps[:cell_comments]
    ps_attrs << %(firstPageNumber="#{sheet_ps[:first_page_number]}") if sheet_ps[:first_page_number]
    ps_attrs << 'useFirstPageNumber="1"' if sheet_ps[:use_first_page_number]
    ps_attrs << %(horizontalDpi="#{sheet_ps[:horizontal_dpi]}") if sheet_ps[:horizontal_dpi]
    ps_attrs << %(verticalDpi="#{sheet_ps[:vertical_dpi]}") if sheet_ps[:vertical_dpi]
    ps_attrs << %(copies="#{sheet_ps[:copies]}") if sheet_ps[:copies]
    ps_attrs << %(paperHeight="#{sheet_ps[:paper_height]}") if sheet_ps[:paper_height]
    ps_attrs << %(paperWidth="#{sheet_ps[:paper_width]}") if sheet_ps[:paper_width]
    ps_attrs << %(errors="#{sheet_ps[:errors]}") if sheet_ps[:errors]
    ps_attrs << 'usePrinterDefaults="0"' if sheet_ps[:use_printer_defaults] == false
    parts << "<pageSetup #{ps_attrs.join(" ")}/>" unless ps_attrs.empty?
  end

  # Emit <headerFooter> if defined.
  unless sheet_hf.empty?
    hf_attrs = []
    hf_attrs << 'differentFirst="1"' if sheet_hf[:different_first]
    hf_attrs << 'differentOddEven="1"' if sheet_hf[:different_odd_even]
    hf_attrs << 'scaleWithDoc="0"' if sheet_hf[:scale_with_doc] == false
    hf_attrs << 'alignWithMargins="0"' if sheet_hf[:align_with_margins] == false
    hf_tag = hf_attrs.empty? ? "<headerFooter>" : "<headerFooter #{hf_attrs.join(" ")}>"
    parts << hf_tag
    parts << "<oddHeader>#{xml_escape(sheet_hf[:odd_header])}</oddHeader>" if sheet_hf[:odd_header]
    parts << "<oddFooter>#{xml_escape(sheet_hf[:odd_footer])}</oddFooter>" if sheet_hf[:odd_footer]
    parts << "<evenHeader>#{xml_escape(sheet_hf[:even_header])}</evenHeader>" if sheet_hf[:even_header]
    parts << "<evenFooter>#{xml_escape(sheet_hf[:even_footer])}</evenFooter>" if sheet_hf[:even_footer]
    parts << "<firstHeader>#{xml_escape(sheet_hf[:first_header])}</firstHeader>" if sheet_hf[:first_header]
    parts << "<firstFooter>#{xml_escape(sheet_hf[:first_footer])}</firstFooter>" if sheet_hf[:first_footer]
    parts << "</headerFooter>"
  end

  # Emit <rowBreaks> if defined.
  unless sheet_rb.empty?
    manual_count = sheet_rb.count { |r| r.is_a?(Hash) ? r.fetch(:man, true) : true }
    parts << %(<rowBreaks count="#{sheet_rb.size}" manualBreakCount="#{manual_count}">)
    sheet_rb.each { |r| parts << emit_brk_xml(r, default_max: 16_383) }
    parts << "</rowBreaks>"
  end

  # Emit <colBreaks> if defined.
  unless sheet_cb.empty?
    manual_count = sheet_cb.count { |c| c.is_a?(Hash) ? c.fetch(:man, true) : true }
    parts << %(<colBreaks count="#{sheet_cb.size}" manualBreakCount="#{manual_count}">)
    sheet_cb.each { |c| parts << emit_brk_xml(c, default_max: 1_048_575) }
    parts << "</colBreaks>"
  end

  # Emit <cellWatches> if defined.
  unless cell_watches.empty?
    parts << "<cellWatches>"
    cell_watches.each { |r| parts << %(<cellWatch r="#{r}"/>) }
    parts << "</cellWatches>"
  end

  # Emit <ignoredErrors> if defined.
  unless ignored_errors.empty?
    parts << "<ignoredErrors>"
    ignored_errors.each do |ie|
      ie_attrs = %( sqref="#{ie[:sqref]}")
      ie_attrs << ' evalError="1"' if ie[:eval_error]
      ie_attrs << ' twoDigitTextYear="1"' if ie[:two_digit_text_year]
      ie_attrs << ' numberStoredAsText="1"' if ie[:number_stored_as_text]
      ie_attrs << ' formula="1"' if ie[:formula]
      ie_attrs << ' formulaRange="1"' if ie[:formula_range]
      ie_attrs << ' unlockedFormula="1"' if ie[:unlocked_formula]
      ie_attrs << ' emptyCellReference="1"' if ie[:empty_cell_reference]
      ie_attrs << ' listDataValidation="1"' if ie[:list_data_validation]
      ie_attrs << ' calculatedColumn="1"' if ie[:calculated_column]
      parts << "<ignoredError#{ie_attrs}/>"
    end
    parts << "</ignoredErrors>"
  end

  # Emit <tableParts> if tables are defined.
  unless sheet_tables.empty?
    parts << %(<tableParts count="#{sheet_tables.size}">)
    sheet_tables.each_with_index do |_tbl, i|
      rid = hyperlink_count + i + 1
      parts << %(<tablePart r:id="rId#{rid}"/>)
    end
    parts << "</tableParts>"
  end

  # Emit <drawing> reference if images or charts exist.
  if has_drawing
    # The drawing rId is after hyperlinks + tables + comments + vml
    drawing_rid = hyperlink_count + sheet_tables.size + (has_comments ? 2 : 0) + 1
    parts << %(<drawing r:id="rId#{drawing_rid}"/>)
  end

  # Emit <legacyDrawing> reference if comments exist (VML shapes).
  parts << %(<legacyDrawing r:id="rId#{vml_rid}"/>) if vml_rid

  parts << "</worksheet>"
  parts.join
end

#gridlines_xml(tag, spec) ⇒ Object

: (untyped tag, untyped spec) -> ("" | untyped)

Parameters:

  • tag (Object)
  • spec (Object)

Returns:

  • (Object)


3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
# File 'lib/xlsxrb/ooxml/writer.rb', line 3606

def gridlines_xml(tag, spec)
  return "" unless spec

  if spec.is_a?(Hash)
    sp_children = +""
    if spec[:line_color] || spec[:line_width] || spec[:line_dash]
      lw = spec[:line_width] ? %( w="#{(spec[:line_width] * 12_700).to_i}") : ""
      lf = spec[:line_color] ? %(<a:solidFill>#{color_xml(spec[:line_color])}</a:solidFill>) : ""
      ld = spec[:line_dash] ? %(<a:prstDash val="#{xml_escape(spec[:line_dash])}"/>) : ""
      sp_children << "<a:ln#{lw}>#{lf}#{ld}</a:ln>"
    end
    sp_children.empty? ? "<c:#{tag}/>" : "<c:#{tag}><c:spPr>#{sp_children}</c:spPr></c:#{tag}>"
  else
    "<c:#{tag}/>"
  end
end

Returns header/footer for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


797
798
799
800
# File 'lib/xlsxrb/ooxml/writer.rb', line 797

def header_footer(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@header_footer[sheet_name] || {}).dup
end

Adds a hyperlink on a cell. : (untyped cell_address, ?untyped? url, ?sheet: untyped?, ?display: untyped?, ?tooltip: untyped?, ?location: untyped?) -> untyped

Parameters:

  • cell_address (Object)
  • url (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)
  • display: (Object) (defaults to: nil)
  • tooltip: (Object) (defaults to: nil)
  • location: (Object) (defaults to: nil)

Returns:

  • (Object)


321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/xlsxrb/ooxml/writer.rb', line 321

def hyperlink(cell_address, url = nil, sheet: nil, display: nil, tooltip: nil, location: nil)
  validate_cell_address!(cell_address)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @hyperlinks.key?(sheet_name)
  raise ArgumentError, "url or location required" if url.nil? && location.nil?

  link = {}
  link[:url] = url if url
  link[:display] = display if display
  link[:tooltip] = tooltip if tooltip
  link[:location] = location if location
  @hyperlinks[sheet_name][cell_address] = link
end

Returns hyperlinks for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


337
338
339
340
# File 'lib/xlsxrb/ooxml/writer.rb', line 337

def hyperlinks(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @hyperlinks[sheet_name] || {}
end

#ignored_errors(sheet: nil) ⇒ Object

Returns ignored errors for the given sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1129
1130
1131
1132
# File 'lib/xlsxrb/ooxml/writer.rb', line 1129

def ignored_errors(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@ignored_errors[sheet_name] || []).dup
end

#images(sheet: nil) ⇒ Object

Returns images for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1251
1252
1253
1254
# File 'lib/xlsxrb/ooxml/writer.rb', line 1251

def images(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @images[sheet_name] || []
end

#index_to_column_letter(index) ⇒ Object

: (untyped index) -> untyped

Parameters:

  • index (Object)

Returns:

  • (Object)


5214
5215
5216
5217
5218
5219
5220
5221
5222
# File 'lib/xlsxrb/ooxml/writer.rb', line 5214

def index_to_column_letter(index)
  result = +""
  while index.positive?
    index -= 1
    result.prepend(("A".ord + (index % 26)).chr)
    index /= 26
  end
  result
end

#indexed_colorsObject

Returns the indexed colors palette. : () -> untyped

Returns:

  • (Object)


534
535
536
# File 'lib/xlsxrb/ooxml/writer.rb', line 534

def indexed_colors
  @indexed_colors.dup
end

#insert_image(file_data, ext: "png", from_col: 0, from_row: 0, to_col: 5, to_row: 10, from_col_off: nil, from_row_off: nil, to_col_off: nil, to_row_off: nil, name: nil, description: nil, title: nil, hidden: nil, macro: nil, no_change_aspect: true, no_crop: nil, line_color: nil, line_width: nil, rotation: nil, edit_as: nil, published: nil, locks_with_sheet: nil, prints_with_sheet: nil, src_rect: nil, alpha_mod_fix: nil, sheet: nil) ⇒ Object

Inserts an image from file data into the given sheet. file_data: raw image bytes. ext: file extension (e.g. "png"). from_col/from_row: anchor start. to_col/to_row: anchor end. : (untyped file_data, ?ext: ::String, ?from_col: ::Integer, ?from_row: ::Integer, ?to_col: ::Integer, ?to_row: ::Integer, ?from_col_off: untyped?, ?from_row_off: untyped?, ?to_col_off: untyped?, ?to_row_off: untyped?, ?name: untyped?, ?description: untyped?, ?title: untyped?, ?hidden: untyped?, ?macro: untyped?, ?no_change_aspect: bool, ?no_crop: untyped?, ?line_color: untyped?, ?line_width: untyped?, ?rotation: untyped?, ?edit_as: untyped?, ?published: untyped?, ?locks_with_sheet: untyped?, ?prints_with_sheet: untyped?, ?src_rect: untyped?, ?alpha_mod_fix: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • file_data (Object)
  • ext: (Object) (defaults to: "png")
  • from_col: (Object) (defaults to: 0)
  • from_row: (Object) (defaults to: 0)
  • to_col: (Object) (defaults to: 5)
  • to_row: (Object) (defaults to: 10)
  • from_col_off: (Object) (defaults to: nil)
  • from_row_off: (Object) (defaults to: nil)
  • to_col_off: (Object) (defaults to: nil)
  • to_row_off: (Object) (defaults to: nil)
  • name: (Object) (defaults to: nil)
  • description: (Object) (defaults to: nil)
  • title: (Object) (defaults to: nil)
  • hidden: (Object) (defaults to: nil)
  • macro: (Object) (defaults to: nil)
  • no_change_aspect: (Object) (defaults to: true)
  • no_crop: (Object) (defaults to: nil)
  • line_color: (Object) (defaults to: nil)
  • line_width: (Object) (defaults to: nil)
  • rotation: (Object) (defaults to: nil)
  • edit_as: (Object) (defaults to: nil)
  • published: (Object) (defaults to: nil)
  • locks_with_sheet: (Object) (defaults to: nil)
  • prints_with_sheet: (Object) (defaults to: nil)
  • src_rect: (Object) (defaults to: nil)
  • alpha_mod_fix: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
# File 'lib/xlsxrb/ooxml/writer.rb', line 1217

def insert_image(file_data, ext: "png", from_col: 0, from_row: 0, to_col: 5, to_row: 10, from_col_off: nil, from_row_off: nil, to_col_off: nil, to_row_off: nil, name: nil, description: nil, title: nil, hidden: nil, macro: nil, no_change_aspect: true, no_crop: nil, line_color: nil, line_width: nil, rotation: nil, edit_as: nil, published: nil, locks_with_sheet: nil, prints_with_sheet: nil, src_rect: nil, alpha_mod_fix: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @images.key?(sheet_name)

  img_name = name || "Picture #{@images[sheet_name].size + 1}"
  img = {
    file_data: file_data, ext: ext, name: img_name,
    from_col: from_col, from_row: from_row,
    to_col: to_col, to_row: to_row
  }
  img[:from_col_off] = from_col_off if from_col_off
  img[:from_row_off] = from_row_off if from_row_off
  img[:to_col_off] = to_col_off if to_col_off
  img[:to_row_off] = to_row_off if to_row_off
  img[:description] = description if description
  img[:title] = title if title
  img[:hidden] = hidden unless hidden.nil?
  img[:macro] = macro if macro
  img[:no_change_aspect] = no_change_aspect
  img[:no_crop] = no_crop unless no_crop.nil?
  img[:line_color] = line_color if line_color
  img[:line_width] = line_width if line_width
  img[:rotation] = rotation if rotation
  img[:edit_as] = edit_as if edit_as
  img[:published] = published unless published.nil?
  img[:locks_with_sheet] = locks_with_sheet unless locks_with_sheet.nil?
  img[:prints_with_sheet] = prints_with_sheet unless prints_with_sheet.nil?
  img[:src_rect] = src_rect if src_rect
  img[:alpha_mod_fix] = alpha_mod_fix if alpha_mod_fix
  @images[sheet_name] << img
end

#merge(range, sheet: nil) ⇒ Object

Merges a range of cells (e.g. "A1:B2"). : (untyped range, ?sheet: untyped?) -> untyped

Parameters:

  • range (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


303
304
305
306
307
308
309
310
# File 'lib/xlsxrb/ooxml/writer.rb', line 303

def merge(range, sheet: nil)
  raise ArgumentError, "range must be a String like 'A1:B2'" unless range.is_a?(String) && range.match?(/\A[A-Z]+\d+:[A-Z]+\d+\z/)

  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @merge_cells.key?(sheet_name)

  @merge_cells[sheet_name] << range
end

#merge_flat_title_styling(title_spec, chart, prefix) ⇒ Object

: (untyped title_spec, untyped chart, untyped prefix) -> untyped

Parameters:

  • title_spec (Object)
  • chart (Object)
  • prefix (Object)

Returns:

  • (Object)


3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
# File 'lib/xlsxrb/ooxml/writer.rb', line 3557

def merge_flat_title_styling(title_spec, chart, prefix)
  font_key = :"#{prefix}_font"
  fill_key = :"#{prefix}_fill"
  no_fill_key = :"#{prefix}_no_fill"
  lc_key = :"#{prefix}_line_color"
  lw_key = :"#{prefix}_line_width"
  ld_key = :"#{prefix}_line_dash"
  rot_key = :"#{prefix}_rotation"
  return title_spec unless chart[font_key] || chart[fill_key] || chart[no_fill_key] ||
                           chart[lc_key] || chart[lw_key] || chart[ld_key] || chart[rot_key]

  spec = title_spec.is_a?(Hash) ? title_spec : { text: title_spec }
  spec[:font] ||= chart[font_key] if chart[font_key]
  spec[:fill_color] ||= chart[fill_key] if chart[fill_key]
  spec[:no_fill] = chart[no_fill_key] if spec[:no_fill].nil? && !chart[no_fill_key].nil?
  spec[:line_color] ||= chart[lc_key] if chart[lc_key]
  spec[:line_width] ||= chart[lw_key] if chart[lw_key]
  spec[:line_dash] ||= chart[ld_key] if chart[ld_key]
  spec[:rotation] ||= chart[rot_key] if chart[rot_key]
  spec
end

#merged_cells(sheet: nil) ⇒ Object

Returns merged cell ranges for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


314
315
316
317
# File 'lib/xlsxrb/ooxml/writer.rb', line 314

def merged_cells(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @merge_cells[sheet_name] || []
end

#mru_colorsObject

Returns the MRU colors. : () -> untyped

Returns:

  • (Object)


548
549
550
# File 'lib/xlsxrb/ooxml/writer.rb', line 548

def mru_colors
  @mru_colors.map(&:dup)
end

#normalize_drawing_rgb(color) ⇒ Object

: (untyped color) -> untyped

Parameters:

  • color (Object)

Returns:

  • (Object)


3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
# File 'lib/xlsxrb/ooxml/writer.rb', line 3719

def normalize_drawing_rgb(color)
  str = color.to_s
  hex = str.delete_prefix("#")

  # Common shorthand (e.g. #f00 -> FF0000)
  return hex.chars.map { |c| c * 2 }.join.upcase if hex.match?(/\A[0-9A-Fa-f]{3}\z/)

  # ARGB -> RGB for DrawingML srgbClr (expects RRGGBB)
  return hex[-6, 6].upcase if hex.match?(/\A[0-9A-Fa-f]{8}\z/)

  return hex.upcase if hex.match?(/\A[0-9A-Fa-f]{6}\z/)

  str
end

#num_cache_xml(ref) ⇒ Object

: (untyped ref) -> ("" | ::String)

Parameters:

  • ref (Object)

Returns:

  • (Object)


3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
# File 'lib/xlsxrb/ooxml/writer.rb', line 3671

def num_cache_xml(ref)
  values = resolve_sheet_ref(ref)
  return "" unless values

  pts = values.each_with_index.filter_map do |v, i|
    next unless v

    %(<c:pt idx="#{i}"><c:v>#{xml_escape(v.to_s)}</c:v></c:pt>)
  end
  %(<c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="#{values.size}"/>#{pts.join}</c:numCache>)
end

#page_margins(sheet: nil) ⇒ Object

Returns page margins for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


765
766
767
768
# File 'lib/xlsxrb/ooxml/writer.rb', line 765

def page_margins(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @page_margins[sheet_name]
end

#page_setup(sheet: nil) ⇒ Object

Returns page setup for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


781
782
783
784
# File 'lib/xlsxrb/ooxml/writer.rb', line 781

def page_setup(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@page_setup[sheet_name] || {}).dup
end

#paragraph_xml(para) ⇒ Object

: (untyped para) -> ::String

Parameters:

  • para (Object)

Returns:

  • (Object)


3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
# File 'lib/xlsxrb/ooxml/writer.rb', line 3310

def paragraph_xml(para)
  ppr_attrs = +""
  ppr_attrs << %( algn="#{xml_escape(para[:align])}") if para[:align]
  ppr_attrs << %( fontAlgn="#{xml_escape(para[:font_align])}") if para[:font_align]
  ppr_attrs << %( defTabSz="#{para[:def_tab_sz]}") if para[:def_tab_sz]
  ppr_attrs << %( rtl="1") if para[:rtl]
  ppr_attrs << %( eaLnBrk="1") if para[:ea_ln_brk]
  ppr_attrs << %( latinLnBrk="1") if para[:latin_ln_brk]
  ppr_attrs << %( hangingPunct="1") if para[:hanging_punct]
  ppr_attrs << %( lvl="#{para[:level]}") if para[:level]
  if para[:indent]
    ti = para[:indent]
    ppr_attrs << %( marL="#{ti[:left]}") if ti[:left]
    ppr_attrs << %( marR="#{ti[:right]}") if ti[:right]
    ppr_attrs << %( indent="#{ti[:indent]}") if ti[:indent]
  end
  ppr_children = +""
  if para[:spacing]
    ts = para[:spacing]
    if ts[:line]
      ppr_children << %(<a:lnSpc><a:spcPts val="#{ts[:line]}"/></a:lnSpc>)
    elsif ts[:line_pct]
      ppr_children << %(<a:lnSpc><a:spcPct val="#{ts[:line_pct]}"/></a:lnSpc>)
    end
    if ts[:before]
      ppr_children << %(<a:spcBef><a:spcPts val="#{ts[:before]}"/></a:spcBef>)
    elsif ts[:before_pct]
      ppr_children << %(<a:spcBef><a:spcPct val="#{ts[:before_pct]}"/></a:spcBef>)
    end
    if ts[:after]
      ppr_children << %(<a:spcAft><a:spcPts val="#{ts[:after]}"/></a:spcAft>)
    elsif ts[:after_pct]
      ppr_children << %(<a:spcAft><a:spcPct val="#{ts[:after_pct]}"/></a:spcAft>)
    end
  end
  if para[:tab_stops]&.any?
    tabs = para[:tab_stops].map do |tab|
      tab_attrs = %( pos="#{tab[:pos]}")
      tab_attrs << %( algn="#{xml_escape(tab[:align])}") if tab[:align]
      "<a:tab#{tab_attrs}/>"
    end
    ppr_children << "<a:tabLst>#{tabs.join}</a:tabLst>"
  end
  if para[:bullet]
    bu = para[:bullet]
    ppr_children << %(<a:buClr>#{color_xml(bu[:color])}</a:buClr>) if bu[:color]
    ppr_children << %(<a:buSzPts val="#{bu[:size_pts]}"/>) if bu[:size_pts]
    ppr_children << %(<a:buSzPct val="#{bu[:size_pct]}"/>) if bu[:size_pct]
    ppr_children << %(<a:buFont typeface="#{xml_escape(bu[:font])}"/>) if bu[:font]
    case bu[:type]
    when "none"
      ppr_children << "<a:buNone/>"
    when "char"
      ppr_children << %(<a:buChar char="#{xml_escape(bu[:char])}"/>)
    when "auto"
      auto_attrs = %( type="#{xml_escape(bu[:auto_type])}")
      auto_attrs << %( startAt="#{bu[:start_at]}") if bu[:start_at]
      ppr_children << "<a:buAutoNum#{auto_attrs}/>"
    end
  end
  ppr_children << text_char_props_xml("a:defRPr", para[:def_rpr]) if para[:def_rpr]
  ppr_xml = if ppr_attrs.empty? && ppr_children.empty?
              ""
            elsif ppr_children.empty?
              "<a:pPr#{ppr_attrs}/>"
            else
              "<a:pPr#{ppr_attrs}>#{ppr_children}</a:pPr>"
            end
  end_para_rpr_xml = para[:end_para_rpr] ? text_char_props_xml("a:endParaRPr", para[:end_para_rpr]) : ""
  runs_xml = if para[:runs]
               para[:runs].map do |run|
                 run_rpr = run[:font] ? text_char_props_xml("a:rPr", run[:font]) : ""
                 "<a:r>#{run_rpr}<a:t>#{xml_escape(run[:text] || "")}</a:t></a:r>"
               end.join
             else
               rpr_xml = para[:font] ? text_char_props_xml("a:rPr", para[:font]) : ""
               "<a:r>#{rpr_xml}<a:t>#{xml_escape(para[:text] || "")}</a:t></a:r>"
             end
  "<a:p>#{ppr_xml}#{runs_xml}#{end_para_rpr_xml}</a:p>"
end

#parse_extra_content_types(ct_xml) ⇒ Object

: (untyped ct_xml) -> untyped

Parameters:

  • ct_xml (Object)

Returns:

  • (Object)


4859
4860
4861
4862
4863
4864
4865
4866
# File 'lib/xlsxrb/ooxml/writer.rb', line 4859

def parse_extra_content_types(ct_xml)
  ct_xml.scan(/<Default\s+Extension="([^"]+)"\s+ContentType="([^"]+)"/).each do |ext, ct|
    @extra_ct_defaults[ext] ||= ct
  end
  ct_xml.scan(/<Override\s+PartName="([^"]+)"\s+ContentType="([^"]+)"/).each do |pn, ct|
    @extra_ct_overrides[pn] ||= ct
  end
end

#phonetic_properties(sheet: nil) ⇒ Object

Returns phonetic properties for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


649
650
651
652
# File 'lib/xlsxrb/ooxml/writer.rb', line 649

def phonetic_properties(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @phonetic_properties[sheet_name]&.dup
end

#pivot_tables(sheet: nil) ⇒ Object

Returns pivot table definitions for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1615
1616
1617
1618
# File 'lib/xlsxrb/ooxml/writer.rb', line 1615

def pivot_tables(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @pivot_tables_data[sheet_name] || []
end

#preserve_macros!Object

Enables macro preservation mode. Required when copy_entries_from loads a .xlsm file. : () -> untyped

Returns:

  • (Object)


1636
1637
1638
# File 'lib/xlsxrb/ooxml/writer.rb', line 1636

def preserve_macros!
  @preserve_macros = true
end

#preserve_macros?Object

Returns whether macro preservation is enabled. : () -> untyped

Returns:

  • (Object)


1642
1643
1644
# File 'lib/xlsxrb/ooxml/writer.rb', line 1642

def preserve_macros?
  @preserve_macros
end

Returns print options for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


742
743
744
745
# File 'lib/xlsxrb/ooxml/writer.rb', line 742

def print_options(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@print_options[sheet_name] || {}).dup
end

#protected_ranges(sheet: nil) ⇒ Object

Returns protected ranges for the given sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1094
1095
1096
1097
# File 'lib/xlsxrb/ooxml/writer.rb', line 1094

def protected_ranges(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@protected_ranges[sheet_name] || []).map(&:dup)
end

#resolve_sheet_ref(ref) ⇒ Object

Resolves a cell reference like "Sheet1!$A$1:$A$5" to an array of values from @sheets. : (untyped ref) -> (nil | untyped)

Parameters:

  • ref (Object)

Returns:

  • (Object)


3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
# File 'lib/xlsxrb/ooxml/writer.rb', line 3625

def resolve_sheet_ref(ref)
  return nil unless ref

  m = if ref.start_with?("'")
        ref.match(/\A'([^']+)'!(.+)\z/)

      else
        ref.match(/\A([^!]+)!(.+)\z/)

      end
  return nil unless m

  sheet_name = m[1]
  range_part = m[2]
  return nil unless @sheets.key?(sheet_name)

  range_part = range_part.delete("$")
  cells = if range_part.include?(":")
            start_cell, end_cell = range_part.split(":", 2)
            enumerate_cell_range(start_cell, end_cell)
          else
            [range_part]
          end
  cells.map { |addr| @sheets[sheet_name][addr] }
end

#resolve_style_index(style_value) ⇒ Object

Maps a numFmtId to a cellXfs index. Index 0 is the default (no format). : (untyped style_value) -> (nil | untyped)

Parameters:

  • style_value (Object)

Returns:

  • (Object)


5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
# File 'lib/xlsxrb/ooxml/writer.rb', line 5005

def resolve_style_index(style_value)
  return nil if style_value.nil?

  # New-style: { xf_index: N } from set_cell_style.
  return style_value[:xf_index] if style_value.is_a?(Hash) && style_value.key?(:xf_index)

  # Legacy: raw num_fmt_id from set_cell_format — find or create matching xf entry.
  num_fmt_id = style_value
  @xf_index_map ||= begin
    map = {}
    @num_fmts.each_with_index do |nf, _i|
      entry = { num_fmt_id: nf[:num_fmt_id], font_id: 0, fill_id: 0, border_id: 0 }
      idx = @xf_entries.index(entry)
      unless idx
        @xf_entries << entry
        idx = @xf_entries.size - 1
      end
      map[nf[:num_fmt_id]] = idx
    end
    map
  end
  @xf_index_map[num_fmt_id]
end

#rich_text_xml(rich_text) ⇒ Object

: (untyped rich_text) -> untyped

Parameters:

  • rich_text (Object)

Returns:

  • (Object)


4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
# File 'lib/xlsxrb/ooxml/writer.rb', line 4891

def rich_text_xml(rich_text)
  rich_text.runs.map do |run|
    font = run[:font]
    if font && !font.empty?
      rpr = +""
      rpr << "<b/>" if font[:bold]
      rpr << "<i/>" if font[:italic]
      rpr << "<strike/>" if font[:strike]
      if font[:underline]
        rpr << if font[:underline] == true
                 "<u/>"
               else
                 %(<u val="#{font[:underline]}"/>)
               end
      end
      rpr << %(<vertAlign val="#{font[:vert_align]}"/>) if font[:vert_align]
      rpr << %(<sz val="#{font[:sz]}"/>) if font[:sz]
      rpr << emit_color_xml(font)
      rpr << %(<rFont val="#{xml_escape(font[:name])}"/>) if font[:name]
      rpr << %(<family val="#{font[:family]}"/>) if font[:family]
      rpr << %(<scheme val="#{font[:scheme]}"/>) if font[:scheme]
      "<r><rPr>#{rpr}</rPr><t>#{xml_escape(run[:text])}</t></r>"
    else
      "<r><t>#{xml_escape(run[:text])}</t></r>"
    end
  end.join
end

#row_attributes(sheet: nil) ⇒ Object

Returns row attributes for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


296
297
298
299
# File 'lib/xlsxrb/ooxml/writer.rb', line 296

def row_attributes(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @row_attrs[sheet_name] || {}
end

#row_breaks(sheet: nil) ⇒ Object

Returns row breaks for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


813
814
815
816
# File 'lib/xlsxrb/ooxml/writer.rb', line 813

def row_breaks(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @row_breaks[sheet_name] || []
end

#scenarios(sheet: nil) ⇒ Object

Returns scenarios for the given sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1163
1164
1165
1166
# File 'lib/xlsxrb/ooxml/writer.rb', line 1163

def scenarios(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @scenarios[sheet_name]&.dup
end

#selection(sheet: nil) ⇒ Object

Returns selection for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


726
727
728
729
# File 'lib/xlsxrb/ooxml/writer.rb', line 726

def selection(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @selections[sheet_name]
end

#set_auto_filter(range, sheet: nil) ⇒ Object

Sets an autoFilter range (e.g. "A1:B10") for the given sheet. : (untyped range, ?sheet: untyped?) -> untyped

Parameters:

  • range (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


344
345
346
347
348
349
350
351
# File 'lib/xlsxrb/ooxml/writer.rb', line 344

def set_auto_filter(range, sheet: nil)
  raise ArgumentError, "range must be a String like 'A1:B10'" unless range.is_a?(String) && range.match?(/\A[A-Z]+\d+:[A-Z]+\d+\z/)

  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @auto_filters.key?(sheet_name)

  @auto_filters[sheet_name] = range
end

#set_calc_property(name, value) ⇒ Object

Sets a calc property (e.g. :calc_id, :full_calc_on_load). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


1037
1038
1039
# File 'lib/xlsxrb/ooxml/writer.rb', line 1037

def set_calc_property(name, value)
  @calc_properties[name] = value
end

#set_cell(cell_address, value, sheet: nil) ⇒ Object

Registers a cell value at the given address (e.g. "A1"). : (untyped cell_address, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • cell_address (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


150
151
152
153
154
155
156
# File 'lib/xlsxrb/ooxml/writer.rb', line 150

def set_cell(cell_address, value, sheet: nil)
  validate_cell_address!(cell_address)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)

  @sheets[sheet_name][cell_address] = value
end

#set_cell_format(cell_address, num_fmt_id, sheet: nil) ⇒ Object

Sets a number format on a cell. num_fmt_id is from add_number_format or a built-in id. : (untyped cell_address, untyped num_fmt_id, ?sheet: untyped?) -> untyped

Parameters:

  • cell_address (Object)
  • num_fmt_id (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


418
419
420
421
422
423
424
# File 'lib/xlsxrb/ooxml/writer.rb', line 418

def set_cell_format(cell_address, num_fmt_id, sheet: nil)
  validate_cell_address!(cell_address)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @cell_styles.key?(sheet_name)

  @cell_styles[sheet_name][cell_address] = num_fmt_id
end

#set_cell_phonetic(cell_address, sheet: nil) ⇒ Object

Marks a cell as containing phonetic text (ph="1" on the element). : (untyped cell_address, ?sheet: untyped?) -> untyped

Parameters:

  • cell_address (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


508
509
510
511
512
513
514
# File 'lib/xlsxrb/ooxml/writer.rb', line 508

def set_cell_phonetic(cell_address, sheet: nil)
  validate_cell_address!(cell_address)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @cell_phonetic.key?(sheet_name)

  @cell_phonetic[sheet_name][cell_address] = true
end

#set_cell_style(cell_address, style_id, sheet: nil) ⇒ Object

Sets a cell style by xf index (from add_cell_style). : (untyped cell_address, untyped style_id, ?sheet: untyped?) -> untyped

Parameters:

  • cell_address (Object)
  • style_id (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


498
499
500
501
502
503
504
# File 'lib/xlsxrb/ooxml/writer.rb', line 498

def set_cell_style(cell_address, style_id, sheet: nil)
  validate_cell_address!(cell_address)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @cell_styles.key?(sheet_name)

  @cell_styles[sheet_name][cell_address] = { xf_index: style_id }
end

#set_column_attribute(col_letter, name, value, sheet: nil) ⇒ Object

Sets a column attribute (e.g. :hidden, :best_fit, :outline_level, :collapsed, :style). : (untyped col_letter, untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • col_letter (Object)
  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


188
189
190
191
192
193
194
195
196
# File 'lib/xlsxrb/ooxml/writer.rb', line 188

def set_column_attribute(col_letter, name, value, sheet: nil)
  raise ArgumentError, "column must be a String of uppercase letters" unless col_letter.is_a?(String) && col_letter.match?(/\A[A-Z]+\z/)

  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @column_attrs.key?(sheet_name)

  @column_attrs[sheet_name][col_letter] ||= {}
  @column_attrs[sheet_name][col_letter][name] = value
end

#set_column_width(col_letter, width, sheet: nil) ⇒ Object

Sets the width for a column (e.g. "A", "BC"). : (untyped col_letter, untyped width, ?sheet: untyped?) -> untyped

Parameters:

  • col_letter (Object)
  • width (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


167
168
169
170
171
172
173
174
175
176
177
# File 'lib/xlsxrb/ooxml/writer.rb', line 167

def set_column_width(col_letter, width, sheet: nil)
  raise ArgumentError, "column must be a String of uppercase letters" unless col_letter.is_a?(String) && col_letter.match?(/\A[A-Z]+\z/)

  col_index = column_letter_to_index(col_letter)
  raise ArgumentError, "column out of range: #{col_letter}" unless col_index.between?(1, MAX_COLUMN_INDEX)

  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @column_widths.key?(sheet_name)

  @column_widths[sheet_name][col_letter] = width
end

#set_data_consolidate(sheet: nil, **opts) ⇒ Object

Sets data consolidation options for the given sheet. Options: function:, start_labels:, top_labels:, link:, data_refs: [name:, sheet:] : (?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


1137
1138
1139
1140
1141
1142
# File 'lib/xlsxrb/ooxml/writer.rb', line 1137

def set_data_consolidate(sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)

  @data_consolidate[sheet_name] = opts
end

#set_data_validations_option(name, value, sheet: nil) ⇒ Object

Sets a data validations container option (e.g. disable_prompts, x_window, y_window). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


855
856
857
858
859
860
# File 'lib/xlsxrb/ooxml/writer.rb', line 855

def set_data_validations_option(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @data_validations_options.key?(sheet_name)

  @data_validations_options[sheet_name][name] = value
end

#set_file_recovery_property(name, value) ⇒ Object

Sets a file recovery property (e.g. :auto_recover, :crash_save). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


1049
1050
1051
# File 'lib/xlsxrb/ooxml/writer.rb', line 1049

def set_file_recovery_property(name, value)
  @file_recovery_properties[name] = value
end

#set_file_sharing(name, value) ⇒ Object

Sets a file sharing property (e.g. :read_only_recommended, :user_name). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


1013
1014
1015
# File 'lib/xlsxrb/ooxml/writer.rb', line 1013

def set_file_sharing(name, value)
  @file_sharing[name] = value
end

#set_file_version(name, value) ⇒ Object

Sets a file version property (e.g. :app_name, :last_edited, :lowest_edited, :rup_build, :code_name). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


1001
1002
1003
# File 'lib/xlsxrb/ooxml/writer.rb', line 1001

def set_file_version(name, value)
  @file_version[name] = value
end

#set_freeze_pane(row: 0, col: 0, sheet: nil) ⇒ Object

Sets a freeze pane. row: rows to freeze from top, col: columns to freeze from left. : (?row: ::Integer, ?col: ::Integer, ?sheet: untyped?) -> untyped

Parameters:

  • row: (Object) (defaults to: 0)
  • col: (Object) (defaults to: 0)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


688
689
690
691
692
693
# File 'lib/xlsxrb/ooxml/writer.rb', line 688

def set_freeze_pane(row: 0, col: 0, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @freeze_panes.key?(sheet_name)

  @freeze_panes[sheet_name] = { row: row, col: col, state: :frozen }
end

Sets header/footer text (:odd_header, :odd_footer, :even_header, :even_footer). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


788
789
790
791
792
793
# File 'lib/xlsxrb/ooxml/writer.rb', line 788

def set_header_footer(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @header_footer.key?(sheet_name)

  @header_footer[sheet_name][name] = value
end

#set_indexed_colors(colors) ⇒ Object

Sets the indexed colors palette (array of ARGB hex strings, e.g. ["FF000000", "FFFFFFFF"]). rubocop:disable Naming/AccessorMethodName : (untyped colors) -> untyped

Parameters:

  • colors (Object)

Returns:

  • (Object)


527
528
529
# File 'lib/xlsxrb/ooxml/writer.rb', line 527

def set_indexed_colors(colors)
  @indexed_colors = colors
end

#set_mru_colors(colors) ⇒ Object

Sets the MRU (most recently used) colors (array of color hashes, e.g. ["FFFF0000"]). rubocop:disable Naming/AccessorMethodName : (untyped colors) -> untyped

Parameters:

  • colors (Object)

Returns:

  • (Object)


541
542
543
# File 'lib/xlsxrb/ooxml/writer.rb', line 541

def set_mru_colors(colors)
  @mru_colors = colors
end

#set_page_margins(left: nil, right: nil, top: nil, bottom: nil, header: nil, footer: nil, sheet: nil) ⇒ Object

Sets page margins (all values in inches). : (?left: untyped?, ?right: untyped?, ?top: untyped?, ?bottom: untyped?, ?header: untyped?, ?footer: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • left: (Object) (defaults to: nil)
  • right: (Object) (defaults to: nil)
  • top: (Object) (defaults to: nil)
  • bottom: (Object) (defaults to: nil)
  • header: (Object) (defaults to: nil)
  • footer: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


749
750
751
752
753
754
755
756
757
758
759
760
761
# File 'lib/xlsxrb/ooxml/writer.rb', line 749

def set_page_margins(left: nil, right: nil, top: nil, bottom: nil, header: nil, footer: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @page_margins.key?(sheet_name)

  m = {}
  m[:left] = left if left
  m[:right] = right if right
  m[:top] = top if top
  m[:bottom] = bottom if bottom
  m[:header] = header if header
  m[:footer] = footer if footer
  @page_margins[sheet_name] = m
end

#set_page_setup(name, value, sheet: nil) ⇒ Object

Sets a page setup property (e.g. :orientation, :paper_size, :scale, :fit_to_width, :fit_to_height). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


772
773
774
775
776
777
# File 'lib/xlsxrb/ooxml/writer.rb', line 772

def set_page_setup(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @page_setup.key?(sheet_name)

  @page_setup[sheet_name][name] = value
end

#set_phonetic_properties(props, sheet: nil) ⇒ Object

Sets phonetic properties for a sheet (e.g. :font_id, :type, :alignment). : (untyped props, ?sheet: untyped?) -> untyped

Parameters:

  • props (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


640
641
642
643
644
645
# File 'lib/xlsxrb/ooxml/writer.rb', line 640

def set_phonetic_properties(props, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @phonetic_properties.key?(sheet_name)

  @phonetic_properties[sheet_name] = props
end

#set_print_area(range, sheet: nil) ⇒ Object

Sets the print area for a sheet. range should be like "A1:D20". Generates the _xlnm.Print_Area defined name automatically. : (untyped range, ?sheet: untyped?) -> untyped

Parameters:

  • range (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


958
959
960
961
962
963
964
965
966
967
# File 'lib/xlsxrb/ooxml/writer.rb', line 958

def set_print_area(range, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)

  value = "'#{sheet_name}'!#{absolute_range(range)}"
  # Remove any existing print area for this sheet
  idx = @sheet_order.index(sheet_name)
  @defined_names.reject! { |dn| dn[:name] == "_xlnm.Print_Area" && dn[:local_sheet_id] == idx }
  add_defined_name("_xlnm.Print_Area", value, sheet: sheet_name)
end

#set_print_option(name, value, sheet: nil) ⇒ Object

Sets a print option (e.g. :grid_lines, :headings, :horizontal_centered, :vertical_centered). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


733
734
735
736
737
738
# File 'lib/xlsxrb/ooxml/writer.rb', line 733

def set_print_option(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @print_options.key?(sheet_name)

  @print_options[sheet_name][name] = value
end

#set_print_titles(rows: nil, cols: nil, sheet: nil) ⇒ Object

Sets print titles (rows and/or columns to repeat on each page). rows: "1:3" repeats rows 1-3, cols: "A:B" repeats columns A-B. : (?rows: untyped?, ?cols: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • rows: (Object) (defaults to: nil)
  • cols: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


972
973
974
975
976
977
978
979
980
981
982
983
984
985
# File 'lib/xlsxrb/ooxml/writer.rb', line 972

def set_print_titles(rows: nil, cols: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)
  raise ArgumentError, "at least one of rows: or cols: must be specified" unless rows || cols

  parts = []
  parts << "'#{sheet_name}'!$#{cols.sub(":", ":$")}" if cols
  parts << "'#{sheet_name}'!$#{rows.sub(":", ":$")}" if rows
  value = parts.join(",")

  idx = @sheet_order.index(sheet_name)
  @defined_names.reject! { |dn| dn[:name] == "_xlnm.Print_Titles" && dn[:local_sheet_id] == idx }
  add_defined_name("_xlnm.Print_Titles", value, sheet: sheet_name)
end

#set_row_collapsed(row_num, collapsed: true, sheet: nil) ⇒ Object

Sets a row collapsed state. : (untyped row_num, ?collapsed: bool, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • collapsed: (Object) (defaults to: true)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


240
241
242
243
244
245
246
247
# File 'lib/xlsxrb/ooxml/writer.rb', line 240

def set_row_collapsed(row_num, collapsed: true, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:collapsed] = collapsed
end

#set_row_height(row_num, height, sheet: nil) ⇒ Object

Sets a row height. : (untyped row_num, untyped height, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • height (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


207
208
209
210
211
212
213
214
# File 'lib/xlsxrb/ooxml/writer.rb', line 207

def set_row_height(row_num, height, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:height] = height
end

#set_row_hidden(row_num, hidden: true, sheet: nil) ⇒ Object

Hides a row. : (untyped row_num, ?hidden: bool, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • hidden: (Object) (defaults to: true)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


218
219
220
221
222
223
224
225
# File 'lib/xlsxrb/ooxml/writer.rb', line 218

def set_row_hidden(row_num, hidden: true, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:hidden] = hidden
end

#set_row_outline_level(row_num, level, sheet: nil) ⇒ Object

Sets a row outline level. : (untyped row_num, untyped level, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • level (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


229
230
231
232
233
234
235
236
# File 'lib/xlsxrb/ooxml/writer.rb', line 229

def set_row_outline_level(row_num, level, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:outline_level] = level
end

#set_row_phonetic(row_num, phonetic: true, sheet: nil) ⇒ Object

Sets a row phonetic flag. : (untyped row_num, ?phonetic: bool, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • phonetic: (Object) (defaults to: true)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


285
286
287
288
289
290
291
292
# File 'lib/xlsxrb/ooxml/writer.rb', line 285

def set_row_phonetic(row_num, phonetic: true, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:ph] = phonetic
end

#set_row_style(row_num, style_id, sheet: nil) ⇒ Object

Sets a row default style index (cellXfs index). : (untyped row_num, untyped style_id, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • style_id (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


251
252
253
254
255
256
257
258
259
# File 'lib/xlsxrb/ooxml/writer.rb', line 251

def set_row_style(row_num, style_id, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1
  raise ArgumentError, "style_id must be a non-negative Integer" unless style_id.is_a?(Integer) && style_id >= 0

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:style] = style_id
end

#set_row_thick_bot(row_num, thick: true, sheet: nil) ⇒ Object

Sets a row thick bottom border flag. : (untyped row_num, ?thick: bool, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • thick: (Object) (defaults to: true)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


274
275
276
277
278
279
280
281
# File 'lib/xlsxrb/ooxml/writer.rb', line 274

def set_row_thick_bot(row_num, thick: true, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:thick_bot] = thick
end

#set_row_thick_top(row_num, thick: true, sheet: nil) ⇒ Object

Sets a row thick top border flag. : (untyped row_num, ?thick: bool, ?sheet: untyped?) -> untyped

Parameters:

  • row_num (Object)
  • thick: (Object) (defaults to: true)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


263
264
265
266
267
268
269
270
# File 'lib/xlsxrb/ooxml/writer.rb', line 263

def set_row_thick_top(row_num, thick: true, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @row_attrs.key?(sheet_name)
  raise ArgumentError, "row must be a positive Integer" unless row_num.is_a?(Integer) && row_num >= 1

  @row_attrs[sheet_name][row_num] ||= {}
  @row_attrs[sheet_name][row_num][:thick_top] = thick
end

#set_scenarios(sheet: nil, **opts) ⇒ Object

Sets scenarios for the given sheet. Options: current:, show:, sqref:, scenarios: [input_cells: [{r:, val:, ...], ...}] : (?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


1154
1155
1156
1157
1158
1159
# File 'lib/xlsxrb/ooxml/writer.rb', line 1154

def set_scenarios(sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)

  @scenarios[sheet_name] = opts
end

#set_selection(active_cell, sqref: nil, pane: nil, active_cell_id: nil, sheet: nil) ⇒ Object

Sets the active cell selection. : (untyped active_cell, ?sqref: untyped?, ?pane: untyped?, ?active_cell_id: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • active_cell (Object)
  • sqref: (Object) (defaults to: nil)
  • pane: (Object) (defaults to: nil)
  • active_cell_id: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


714
715
716
717
718
719
720
721
722
# File 'lib/xlsxrb/ooxml/writer.rb', line 714

def set_selection(active_cell, sqref: nil, pane: nil, active_cell_id: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @selections.key?(sheet_name)

  sel = { active_cell: active_cell, sqref: sqref || active_cell }
  sel[:pane] = pane if pane
  sel[:active_cell_id] = active_cell_id if active_cell_id
  @selections[sheet_name] = sel
end

#set_sheet_format(name, value, sheet: nil) ⇒ Object

Sets a sheet format property (e.g. :default_row_height, :default_col_width, :base_col_width). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


656
657
658
659
660
661
# File 'lib/xlsxrb/ooxml/writer.rb', line 656

def set_sheet_format(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheet_formats.key?(sheet_name)

  @sheet_formats[sheet_name][name] = value
end

#set_sheet_property(name, value, sheet: nil) ⇒ Object

Sets a sheet-level property (e.g. :tab_color, :summary_below, :summary_right). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


624
625
626
627
628
629
# File 'lib/xlsxrb/ooxml/writer.rb', line 624

def set_sheet_property(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheet_properties.key?(sheet_name)

  @sheet_properties[sheet_name][name] = value
end

#set_sheet_protection(sheet: nil, **opts) ⇒ Object

Sets sheet protection options. Options: :password, :sheet, :objects, :scenarios, :format_cells, :format_columns, :format_rows, :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells, :algorithm_name, :hash_value, :salt_value, :spin_count : (?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


1065
1066
1067
1068
1069
1070
# File 'lib/xlsxrb/ooxml/writer.rb', line 1065

def set_sheet_protection(sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)

  @sheet_protection[sheet_name] = opts
end

#set_sheet_state(sheet_name, state) ⇒ Object

Sets a sheet's visibility state (:visible, :hidden, :very_hidden). : (untyped sheet_name, untyped state) -> untyped

Parameters:

  • sheet_name (Object)
  • state (Object)

Returns:

  • (Object)


919
920
921
922
923
924
# File 'lib/xlsxrb/ooxml/writer.rb', line 919

def set_sheet_state(sheet_name, state)
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheets.key?(sheet_name)
  raise ArgumentError, "state must be :visible, :hidden, or :very_hidden" unless %i[visible hidden very_hidden].include?(state)

  @sheet_states[sheet_name] = state
end

#set_sheet_view(name, value, sheet: nil) ⇒ Object

Sets a sheet view property (e.g. :show_grid_lines, :show_row_col_headers, :right_to_left, :zoom_scale). : (untyped name, untyped value, ?sheet: untyped?) -> untyped

Parameters:

  • name (Object)
  • value (Object)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


672
673
674
675
676
677
# File 'lib/xlsxrb/ooxml/writer.rb', line 672

def set_sheet_view(name, value, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sheet_views.key?(sheet_name)

  @sheet_views[sheet_name][name] = value
end

#set_sort_state(ref, sort_conditions, sheet: nil, **opts) ⇒ Object

Sets a sort state for the sheet. ref: sort range, sort_conditions: array of { ref:, descending: }. Options: column_sort:, case_sensitive:, sort_method: : (untyped ref, untyped sort_conditions, ?sheet: untyped?, **untyped opts) -> untyped

Parameters:

  • ref (Object)
  • sort_conditions (Object)
  • sheet: (Object) (defaults to: nil)
  • opts (Object)

Returns:

  • (Object)


387
388
389
390
391
392
393
394
395
396
# File 'lib/xlsxrb/ooxml/writer.rb', line 387

def set_sort_state(ref, sort_conditions, sheet: nil, **opts)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @sort_state.key?(sheet_name)

  ss = { ref: ref, sort_conditions: sort_conditions }
  %i[column_sort case_sensitive sort_method].each do |key|
    ss[key] = opts[key] if opts.key?(key)
  end
  @sort_state[sheet_name] = ss
end

#set_split_pane(x_split: 0, y_split: 0, top_left_cell: nil, sheet: nil) ⇒ Object

Sets a split pane (non-frozen). x_split/y_split are in 1/20th of a point (twips). top_left_cell: the cell at top-left of the bottom-right pane. : (?x_split: ::Integer, ?y_split: ::Integer, ?top_left_cell: untyped?, ?sheet: untyped?) -> untyped

Parameters:

  • x_split: (Object) (defaults to: 0)
  • y_split: (Object) (defaults to: 0)
  • top_left_cell: (Object) (defaults to: nil)
  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


698
699
700
701
702
703
# File 'lib/xlsxrb/ooxml/writer.rb', line 698

def set_split_pane(x_split: 0, y_split: 0, top_left_cell: nil, sheet: nil)
  sheet_name = sheet || @sheet_order.first
  raise ArgumentError, "unknown sheet: #{sheet_name}" unless @freeze_panes.key?(sheet_name)

  @freeze_panes[sheet_name] = { x_split: x_split, y_split: y_split, top_left_cell: top_left_cell, state: :split }
end

#set_table_styles_option(name, value) ⇒ Object

Sets table styles options (defaultTableStyle, defaultPivotStyle). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


554
555
556
557
558
# File 'lib/xlsxrb/ooxml/writer.rb', line 554

def set_table_styles_option(name, value)
  raise ArgumentError, "name must be a Symbol" unless name.is_a?(Symbol)

  @table_styles[name] = value
end

#set_workbook_property(name, value) ⇒ Object

Sets a workbook property (e.g. :date1904, :default_theme_version). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


989
990
991
# File 'lib/xlsxrb/ooxml/writer.rb', line 989

def set_workbook_property(name, value)
  @workbook_properties[name] = value
end

#set_workbook_protection(**opts) ⇒ Object

Sets workbook protection options. Options: :lock_structure, :lock_windows, :password, :algorithm_name, :hash_value, :salt_value, :spin_count : (**untyped opts) -> untyped

Parameters:

  • opts (Object)

Returns:

  • (Object)


1171
1172
1173
# File 'lib/xlsxrb/ooxml/writer.rb', line 1171

def set_workbook_protection(**opts)
  @workbook_protection = opts
end

#set_workbook_view(name, value) ⇒ Object

Sets a workbook view property (e.g. :active_tab, :first_sheet). : (untyped name, untyped value) -> untyped

Parameters:

  • name (Object)
  • value (Object)

Returns:

  • (Object)


1025
1026
1027
# File 'lib/xlsxrb/ooxml/writer.rb', line 1025

def set_workbook_view(name, value)
  @workbook_views[name] = value
end

#shapes(sheet: nil) ⇒ Object

Returns shape definitions for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1527
1528
1529
1530
# File 'lib/xlsxrb/ooxml/writer.rb', line 1527

def shapes(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @shapes_data[sheet_name] || []
end

#sheet_format(sheet: nil) ⇒ Object

Returns sheet format properties for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


665
666
667
668
# File 'lib/xlsxrb/ooxml/writer.rb', line 665

def sheet_format(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@sheet_formats[sheet_name] || {}).dup
end

#sheet_properties(sheet: nil) ⇒ Object

Returns sheet properties for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


633
634
635
636
# File 'lib/xlsxrb/ooxml/writer.rb', line 633

def sheet_properties(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@sheet_properties[sheet_name] || {}).dup
end

#sheet_protection(sheet: nil) ⇒ Object

Returns sheet protection settings for the given sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


1074
1075
1076
1077
# File 'lib/xlsxrb/ooxml/writer.rb', line 1074

def sheet_protection(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @sheet_protection[sheet_name]&.dup
end

#sheet_state(sheet_name) ⇒ Object

Returns the sheet state for a given sheet. : (untyped sheet_name) -> untyped

Parameters:

  • sheet_name (Object)

Returns:

  • (Object)


928
929
930
# File 'lib/xlsxrb/ooxml/writer.rb', line 928

def sheet_state(sheet_name)
  @sheet_states[sheet_name] || :visible
end

#sheet_view(sheet: nil) ⇒ Object

Returns sheet view properties for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


681
682
683
684
# File 'lib/xlsxrb/ooxml/writer.rb', line 681

def sheet_view(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  (@sheet_views[sheet_name] || {}).dup
end

#sort_state(sheet: nil) ⇒ Object

Returns sort state for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


400
401
402
403
# File 'lib/xlsxrb/ooxml/writer.rb', line 400

def sort_state(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @sort_state[sheet_name]
end

#str_cache_xml(ref) ⇒ Object

: (untyped ref) -> ("" | ::String)

Parameters:

  • ref (Object)

Returns:

  • (Object)


3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
# File 'lib/xlsxrb/ooxml/writer.rb', line 3684

def str_cache_xml(ref)
  values = resolve_sheet_ref(ref)
  return "" unless values

  pts = values.each_with_index.filter_map do |v, i|
    next unless v

    %(<c:pt idx="#{i}"><c:v>#{xml_escape(v.to_s)}</c:v></c:pt>)
  end
  %(<c:strCache><c:ptCount val="#{values.size}"/>#{pts.join}</c:strCache>)
end

#table_stylesObject

Returns table styles configuration. : () -> untyped

Returns:

  • (Object)


574
575
576
577
578
579
580
# File 'lib/xlsxrb/ooxml/writer.rb', line 574

def table_styles
  deep_copy = {}
  @table_styles.each do |k, v|
    deep_copy[k] = v.is_a?(Array) ? v.map(&:dup) : v
  end
  deep_copy
end

#tables(sheet: nil) ⇒ Object

Returns table definitions for the first (or given) sheet. : (?sheet: untyped?) -> untyped

Parameters:

  • sheet: (Object) (defaults to: nil)

Returns:

  • (Object)


906
907
908
909
# File 'lib/xlsxrb/ooxml/writer.rb', line 906

def tables(sheet: nil)
  sheet_name = sheet || @sheet_order.first
  @tables[sheet_name] || []
end

#text_char_props_xml(tag, font) ⇒ Object

: (untyped tag, untyped font) -> untyped

Parameters:

  • tag (Object)
  • font (Object)

Returns:

  • (Object)


3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
# File 'lib/xlsxrb/ooxml/writer.rb', line 3392

def text_char_props_xml(tag, font)
  attrs = +""
  attrs << %( b="1") if font[:bold]
  attrs << %( i="1") if font[:italic]
  attrs << %( noProof="1") if font[:no_proof]
  attrs << %( normalizeH="1") if font[:normalize_h]
  attrs << %( kumimoji="1") if font[:kumimoji]
  attrs << %( sz="#{font[:size]}") if font[:size]
  attrs << %( strike="#{xml_escape(font[:strike])}") if font[:strike]
  attrs << %( u="#{xml_escape(font[:underline])}") if font[:underline]
  attrs << %( baseline="#{font[:baseline]}") if font[:baseline]
  attrs << %( spc="#{font[:spacing]}") if font[:spacing]
  attrs << %( kern="#{font[:kern]}") if font[:kern]
  attrs << %( cap="#{xml_escape(font[:cap])}") if font[:cap]
  attrs << %( lang="#{xml_escape(font[:lang])}") if font[:lang]
  attrs << %( altLang="#{xml_escape(font[:alt_lang])}") if font[:alt_lang]
  attrs << %( dirty="1") if font[:dirty]
  attrs << %( smtClean="1") if font[:smt_clean]
  attrs << %( err="1") if font[:err]
  attrs << %( bmk="#{xml_escape(font[:bmk])}") if font[:bmk]
  children = +""
  children << %(<a:solidFill>#{color_xml(font[:color])}</a:solidFill>) if font[:color]
  children << %(<a:highlight>#{color_xml(font[:highlight])}</a:highlight>) if font[:highlight]
  children << %(<a:latin typeface="#{xml_escape(font[:name])}"/>) if font[:name]
  children << %(<a:ea typeface="#{xml_escape(font[:ea_font])}"/>) if font[:ea_font]
  children << %(<a:cs typeface="#{xml_escape(font[:cs_font])}"/>) if font[:cs_font]
  children << %(<a:sym typeface="#{xml_escape(font[:sym_font])}"/>) if font[:sym_font]
  children << "<a:uFillTx/>" if font[:u_fill_tx]
  children << "<a:uLnTx/>" if font[:u_ln_tx]
  if font[:line_color] || font[:line_width] || font[:line_dash] || font[:line_cap] || font[:line_join]
    ln_attrs = +(font[:line_width] ? %( w="#{font[:line_width].to_i}") : "")
    ln_attrs << %( cap="#{xml_escape(font[:line_cap])}") if font[:line_cap]
    ln_fill = font[:line_color] ? %(<a:solidFill>#{color_xml(font[:line_color])}</a:solidFill>) : ""
    ln_dash = font[:line_dash] ? %(<a:prstDash val="#{xml_escape(font[:line_dash])}"/>) : ""
    ln_join = case font[:line_join]
              when "round" then "<a:round/>"
              when "bevel" then "<a:bevel/>"
              when "miter"
                font[:line_miter_limit] ? "<a:miter lim=\"#{font[:line_miter_limit].to_i}\"/>" : "<a:miter/>"
              else ""
              end
    children << "<a:ln#{ln_attrs}>#{ln_fill}#{ln_dash}#{ln_join}</a:ln>"
  end
  if font[:outer_shadow] || font[:inner_shadow] || font[:glow] || font[:soft_edge] || font[:reflection] || font[:blur]
    eff = +""
    if font[:outer_shadow]
      os = font[:outer_shadow]
      oa = +""
      oa << %( blurRad="#{os[:blur_rad]}") if os[:blur_rad]
      oa << %( dist="#{os[:dist]}") if os[:dist]
      oa << %( dir="#{os[:dir]}") if os[:dir]
      oa << %( algn="#{xml_escape(os[:algn])}") if os[:algn]
      oa << %( rotWithShape="#{os[:rot_with_shape] ? 1 : 0}") unless os[:rot_with_shape].nil?
      oc = os[:color] ? srgb_clr_xml(os[:color], alpha: os[:alpha]) : ""
      eff << "<a:outerShdw#{oa}>#{oc}</a:outerShdw>"
    end
    if font[:glow]
      gl = font[:glow]
      ga = +(gl[:rad] ? %( rad="#{gl[:rad]}") : "")
      gc = gl[:color] ? srgb_clr_xml(gl[:color], alpha: gl[:alpha]) : ""
      eff << "<a:glow#{ga}>#{gc}</a:glow>"
    end
    if font[:inner_shadow]
      is = font[:inner_shadow]
      ia = +""
      ia << %( blurRad="#{is[:blur_rad]}") if is[:blur_rad]
      ia << %( dist="#{is[:dist]}") if is[:dist]
      ia << %( dir="#{is[:dir]}") if is[:dir]
      ic = is[:color] ? srgb_clr_xml(is[:color], alpha: is[:alpha]) : ""
      eff << "<a:innerShdw#{ia}>#{ic}</a:innerShdw>"
    end
    if font[:reflection]
      rf = font[:reflection]
      ra = +""
      ra << %( blurRad="#{rf[:blur_rad]}") if rf[:blur_rad]
      ra << %( stA="#{rf[:st_a]}") if rf[:st_a]
      ra << %( endA="#{rf[:end_a]}") if rf[:end_a]
      ra << %( dist="#{rf[:dist]}") unless rf[:dist].nil?
      ra << %( dir="#{rf[:dir]}") if rf[:dir]
      ra << %( fadeDir="#{rf[:fade_dir]}") if rf[:fade_dir]
      ra << %( sx="#{rf[:sx]}") if rf[:sx]
      ra << %( sy="#{rf[:sy]}") if rf[:sy]
      ra << %( kx="#{rf[:kx]}") if rf[:kx]
      ra << %( ky="#{rf[:ky]}") if rf[:ky]
      ra << %( algn="#{xml_escape(rf[:algn])}") if rf[:algn]
      ra << %( rotWithShape="#{rf[:rot_with_shape] ? 1 : 0}") unless rf[:rot_with_shape].nil?
      eff << "<a:reflection#{ra}/>"
    end
    if font[:soft_edge]
      se = font[:soft_edge]
      eff << %(<a:softEdge rad="#{se[:rad]}"/>)
    end
    if font[:blur]
      bl = font[:blur]
      ba = +(bl[:rad] ? %( rad="#{bl[:rad]}") : "")
      ba << %( grow="#{bl[:grow] ? 1 : 0}") unless bl[:grow].nil?
      eff << "<a:blur#{ba}/>"
    end
    children << "<a:effectLst>#{eff}</a:effectLst>"
  end
  if children.empty?
    "<#{tag}#{attrs}/>"
  else
    "<#{tag}#{attrs}>#{children}</#{tag}>"
  end
end

#use_shared_strings!Object

Enables shared string table mode (strings stored in sharedStrings.xml). : () -> untyped

Returns:

  • (Object)


913
914
915
# File 'lib/xlsxrb/ooxml/writer.rb', line 913

def use_shared_strings!
  @use_shared_strings = true
end

#validate_cell_address!(cell_address) ⇒ Object

: (untyped cell_address) -> untyped

Parameters:

  • cell_address (Object)

Returns:

  • (Object)


5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
# File 'lib/xlsxrb/ooxml/writer.rb', line 5616

def validate_cell_address!(cell_address)
  raise ArgumentError, "cell address must be a String" unless cell_address.is_a?(String)

  match = cell_address.match(CELL_ADDRESS_PATTERN)
  raise ArgumentError, "invalid cell address: #{cell_address.inspect}" unless match

  row_num = match[2].to_i
  raise ArgumentError, "row out of range: #{row_num}" unless row_num.between?(1, MAX_ROW)

  col_index = column_letter_to_index(match[1])
  raise ArgumentError, "column out of range: #{match[1]}" unless col_index.between?(1, MAX_COLUMN_INDEX)
end

#workbook_propertiesObject

Returns workbook properties hash. : () -> untyped

Returns:

  • (Object)


995
996
997
# File 'lib/xlsxrb/ooxml/writer.rb', line 995

def workbook_properties
  @workbook_properties.dup
end

#workbook_protectionObject

Returns workbook protection settings. : () -> untyped

Returns:

  • (Object)


1177
1178
1179
# File 'lib/xlsxrb/ooxml/writer.rb', line 1177

def workbook_protection
  @workbook_protection&.dup
end

#workbook_viewsObject

Returns workbook view properties hash. : () -> untyped

Returns:

  • (Object)


1031
1032
1033
# File 'lib/xlsxrb/ooxml/writer.rb', line 1031

def workbook_views
  @workbook_views.dup
end

#write(filepath) ⇒ Object

Writes the workbook as an XLSX file to the given path. : (untyped filepath) -> untyped

Parameters:

  • filepath (Object)

Returns:

  • (Object)


1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
# File 'lib/xlsxrb/ooxml/writer.rb', line 1648

def write(filepath)
  # Pre-register date/datetime formats if any sheet contains Date or Time values.
  needs_date = false
  needs_datetime = false
  @sheet_order.each do |sn|
    @sheets[sn].each_value do |v|
      needs_datetime = true if v.is_a?(Time)
      needs_date = true if v.is_a?(Date) && !v.is_a?(Time)
    end
    break if needs_date && needs_datetime
  end
  date_num_fmt_id if needs_date
  datetime_num_fmt_id if needs_datetime

  # Clear memoized xf index map so it picks up all registered formats.
  @xf_index_map = nil
  # Pre-populate xf entries for legacy num_fmt-based styles.
  @num_fmts.each { |nf| resolve_style_index(nf[:num_fmt_id]) }

  # Build shared string table if enabled.
  sst = build_shared_string_table if @use_shared_strings

  # Track generated drawing/image/chart/comment/pivot indices.
  @drawing_count = 0
  @chart_count = 0
  @comment_count = 0
  @pivot_cache_count = 0
  @pivot_table_count = 0
  @media_count = 0

  # Pre-compute total pivot cache count for workbook XML.
  total_pivot_caches = @pivot_tables_data.values.sum(&:size)

  entries = {
    "_rels/.rels" => generate_rels_root,
    "xl/workbook.xml" => generate_workbook_xml(total_pivot_caches),
    "xl/styles.xml" => generate_styles_xml
  }

  entries["docProps/core.xml"] = generate_core_properties_xml unless @core_properties.empty?
  entries["docProps/app.xml"] = generate_app_properties_xml unless @app_properties.empty?
  entries["docProps/custom.xml"] = generate_custom_properties_xml unless @custom_properties.empty?
  entries["xl/sharedStrings.xml"] = generate_shared_strings_xml(sst) if sst

  table_index = 0
  @sheet_order.each_with_index do |sheet_name, i|
    sheet_images = @images[sheet_name] || []
    sheet_charts = @charts_data[sheet_name] || []
    sheet_shapes = @shapes_data[sheet_name] || []
    sheet_comments = @comments_data[sheet_name] || []
    sheet_pivots = @pivot_tables_data[sheet_name] || []
    has_drawing = sheet_images.any? || sheet_charts.any? || sheet_shapes.any?
    has_comments = sheet_comments.any?

    # Pre-increment counters so rels reference correct paths.
    sheet_drawing_idx = has_drawing ? (@drawing_count += 1) : nil
    sheet_comment_idx = has_comments ? (@comment_count += 1) : nil
    sheet_pivot_start = @pivot_table_count
    sheet_cache_start = @pivot_cache_count
    sheet_pivots.each do
      @pivot_cache_count += 1
      @pivot_table_count += 1
    end

    # Build per-sheet rels first (needed for rId calculation in worksheet XML).
    sheet_tables = @tables[sheet_name] || []
    sheet_rels_parts = build_sheet_rels_parts_v2(
      sheet_name, sheet_tables, table_index,
      sheet_drawing_idx, sheet_comment_idx,
      sheet_pivot_start, sheet_pivots.size
    )

    # Calculate the legacyDrawing rId if comments exist.
    # The VML rel is always the one after the comments rel in rels.
    vml_rid = nil
    if has_comments
      vml_idx = sheet_rels_parts.index { |r| r[:type]&.end_with?("/vmlDrawing") }
      vml_rid = vml_idx + 1 if vml_idx # 1-based rId
    end

    entries["xl/worksheets/sheet#{i + 1}.xml"] = generate_worksheet_xml(
      @sheets[sheet_name], @column_widths[sheet_name], @column_attrs[sheet_name], @row_attrs[sheet_name],
      @auto_filters[sheet_name], @filter_columns[sheet_name], @sort_state[sheet_name],
      @merge_cells[sheet_name], @hyperlinks[sheet_name],
      @cell_styles[sheet_name], @sheet_properties[sheet_name], @sheet_formats[sheet_name],
      @sheet_views[sheet_name], @freeze_panes[sheet_name], @selections[sheet_name],
      @print_options[sheet_name], @page_margins[sheet_name], @page_setup[sheet_name],
      @header_footer[sheet_name], @row_breaks[sheet_name], @col_breaks[sheet_name],
      @data_validations[sheet_name], @conditional_formats[sheet_name], sst,
      @tables[sheet_name] || [], @hyperlinks[sheet_name].size,
      has_drawing:, has_comments:,
      sheet_prot: @sheet_protection[sheet_name], vml_rid:,
      phonetic_pr: @phonetic_properties[sheet_name],
      dv_options: @data_validations_options[sheet_name],
      prot_ranges: @protected_ranges[sheet_name],
      cell_watches: @cell_watches[sheet_name],
      ignored_errors: @ignored_errors[sheet_name],
      data_consol: @data_consolidate[sheet_name],
      sheet_scenarios: @scenarios[sheet_name],
      cell_phonetic: @cell_phonetic[sheet_name]
    )

    # Generate drawing XML + media + chart entries.
    if has_drawing
      drawing_rels_data = []
      drawing_parts = []

      sheet_images.each do |img|
        @media_count += 1
        media_path = "xl/media/image#{@media_count}.#{img[:ext]}"
        entries[media_path] = img[:file_data]
        drawing_rels_data << { type: :image, target: "../media/image#{@media_count}.#{img[:ext]}" }
        drawing_parts << { kind: :pic, img: img, rid_index: drawing_rels_data.size }
      end

      sheet_charts.each do |chart|
        @chart_count += 1
        chart_path = "xl/charts/chart#{@chart_count}.xml"
        entries[chart_path] = 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

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

      entries["xl/drawings/drawing#{sheet_drawing_idx}.xml"] = generate_drawing_xml(drawing_parts)
      entries["xl/drawings/_rels/drawing#{sheet_drawing_idx}.xml.rels"] = generate_drawing_rels(drawing_rels_data) unless drawing_rels_data.empty?
    end

    # Generate comments XML and VML drawing.
    if has_comments
      entries["xl/comments#{sheet_comment_idx}.xml"] = generate_comments_xml(sheet_comments)
      entries["xl/drawings/vmlDrawing#{sheet_comment_idx}.vml"] = generate_vml_drawing_xml(sheet_comments)
    end

    # Generate pivot table + cache entries.
    sheet_pivots.each_with_index do |pt, pi|
      cache_idx = sheet_cache_start + pi + 1
      pt_idx = sheet_pivot_start + pi + 1
      entries["xl/pivotCache/pivotCacheDefinition#{cache_idx}.xml"] = generate_pivot_cache_definition_xml(pt, cache_idx)
      entries["xl/pivotCache/pivotCacheRecords#{cache_idx}.xml"] = generate_pivot_cache_records_xml(pt)
      entries["xl/pivotTables/pivotTable#{pt_idx}.xml"] = generate_pivot_table_xml(pt, cache_idx)
      entries["xl/pivotCache/_rels/pivotCacheDefinition#{cache_idx}.xml.rels"] = generate_pivot_cache_rels(cache_idx)
      entries["xl/pivotTables/_rels/pivotTable#{pt_idx}.xml.rels"] = generate_pivot_table_rels(cache_idx)
    end

    # Emit worksheet rels if any relationships exist.
    entries["xl/worksheets/_rels/sheet#{i + 1}.xml.rels"] = generate_generic_rels(sheet_rels_parts) unless sheet_rels_parts.empty?

    sheet_tables.each do |tbl|
      table_index += 1
      entries["xl/tables/table#{table_index}.xml"] = generate_table_xml(tbl)
    end
  end

  # Generate calcChain.xml if any cells have formulas.
  calc_chain_xml = generate_calc_chain_xml
  entries["xl/calcChain.xml"] = calc_chain_xml if calc_chain_xml

  # Generate external link entries.
  @external_links.each_with_index do |el, idx|
    link_num = idx + 1
    entries["xl/externalLinks/externalLink#{link_num}.xml"] = generate_external_link_xml(el)
    entries["xl/externalLinks/_rels/externalLink#{link_num}.xml.rels"] = generate_external_link_rels(el)
  end

  # Generate workbook rels (needs to know pivot cache count).
  entries["xl/_rels/workbook.xml.rels"] = generate_workbook_rels(has_calc_chain: entries.key?("xl/calcChain.xml"))

  # Content types must be generated after all entries are known.
  entries["[Content_Types].xml"] = generate_content_types_xml(entries)

  # Merge extra (pass-through) entries — generated entries take priority.
  merged = @extra_entries.merge(entries)

  generator = ZipGenerator.new(filepath)
  merged.each { |path, content| generator.add_entry(path, content) }
  generator.generate
end

#xml_escape(value) ⇒ Object

: (untyped value) -> untyped

Parameters:

  • value (Object)

Returns:

  • (Object)


4880
4881
4882
4883
4884
4885
4886
4887
4888
# File 'lib/xlsxrb/ooxml/writer.rb', line 4880

def xml_escape(value)
  value.to_s
       .gsub(/[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/, "")
       .gsub("&", "&amp;")
       .gsub("<", "&lt;")
       .gsub(">", "&gt;")
       .gsub('"', "&quot;")
       .gsub("'", "&apos;")
end