Class: Writexlsx::Workbook

Inherits:
Object
  • Object
show all
Includes:
Utility::CellReference, Utility::Common, Utility::XmlPrimitives, ChartData, FormatPreparation, Initialization, PackagePreparation
Defined in:
lib/write_xlsx/workbook.rb,
lib/write_xlsx/workbook/chart_data.rb,
lib/write_xlsx/workbook/initialization.rb,
lib/write_xlsx/workbook/workbook_writer.rb,
lib/write_xlsx/workbook/format_preparation.rb,
lib/write_xlsx/workbook/package_preparation.rb

Direct Known Subclasses

WriteXLSX

Defined Under Namespace

Modules: ChartData, FormatPreparation, Initialization, PackagePreparation

Constant Summary collapse

EMPTY_HASH =

Add a string to the shared string table, if it isn't already there, and return the string index.

{}.freeze

Constants included from Constants

Constants::COL_MAX, Constants::ROW_MAX, Constants::SHEETNAME_MAX, Constants::STR_MAX

Constants included from Utility::Common

Utility::Common::PERL_TRUE_VALUES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Initialization

#assemble_xml_file

Methods included from Utility::XmlPrimitives

#r_id_attributes, #write_color, #write_xml_declaration

Methods included from Utility::CellReference

#row_col_notation, #substitute_cellref, #xl_cell_to_rowcol, #xl_col_to_name, #xl_range, #xl_range_formula, #xl_rowcol_to_cell

Methods included from Utility::Common

#absolute_char, #check_parameter, #float_to_str, #ptrue?, #put_deprecate_message

Constructor Details

#initialize(file, *option_params) ⇒ Workbook

Lifecycle



83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/write_xlsx/workbook.rb', line 83

def initialize(file, *option_params)
  options, default_formats = process_workbook_options(*option_params)

  setup_core_state(file, options, default_formats)
  setup_workbook_state(options)
  setup_format_state(default_formats)
  setup_shared_strings
  setup_embedded_assets
  setup_calculation_state
  setup_default_formats
  set_color_palette
end

Instance Attribute Details

#activesheetObject

:nodoc:



561
562
563
# File 'lib/write_xlsx/workbook.rb', line 561

def activesheet # :nodoc:
  @activesheet ||= 0
end

#chartsObject

:nodoc:



75
76
77
# File 'lib/write_xlsx/workbook.rb', line 75

def charts
  @charts
end

#custom_propertiesObject (readonly)

:nodoc:



63
64
65
# File 'lib/write_xlsx/workbook.rb', line 63

def custom_properties
  @custom_properties
end

#default_url_formatObject (readonly) Also known as: get_default_url_format

Get the default url format used when a user defined format isn't specified with write_url(). The format is the hyperlink style defined by Excel for the default theme.



479
480
481
# File 'lib/write_xlsx/workbook.rb', line 479

def default_url_format
  @default_url_format
end

#doc_propertiesObject (readonly)

:nodoc:



62
63
64
# File 'lib/write_xlsx/workbook.rb', line 62

def doc_properties
  @doc_properties
end

#drawingsObject

:nodoc:



60
61
62
# File 'lib/write_xlsx/workbook.rb', line 60

def drawings
  @drawings
end

#embedded_descriptionsObject (readonly)

:nodoc:



73
74
75
# File 'lib/write_xlsx/workbook.rb', line 73

def embedded_descriptions
  @embedded_descriptions
end

#embedded_image_indexesObject (readonly)

:nodec:



71
72
73
# File 'lib/write_xlsx/workbook.rb', line 71

def embedded_image_indexes
  @embedded_image_indexes
end

#embedded_imagesObject (readonly)

:nodoc:



72
73
74
# File 'lib/write_xlsx/workbook.rb', line 72

def embedded_images
  @embedded_images
end

#excel2003_styleObject (readonly)

:nodoc:



67
68
69
# File 'lib/write_xlsx/workbook.rb', line 67

def excel2003_style
  @excel2003_style
end

#firstsheetObject

:nodoc:



557
558
559
# File 'lib/write_xlsx/workbook.rb', line 557

def firstsheet # :nodoc:
  @firstsheet ||= 0
end

#has_embedded_descriptions=(value) ⇒ Object (writeonly)

:nodoc:



74
75
76
# File 'lib/write_xlsx/workbook.rb', line 74

def has_embedded_descriptions=(value)
  @has_embedded_descriptions = value
end

#image_typesObject (readonly)

:nodoc:



64
65
66
# File 'lib/write_xlsx/workbook.rb', line 64

def image_types
  @image_types
end

#imagesObject (readonly)

:nodoc:



64
65
66
# File 'lib/write_xlsx/workbook.rb', line 64

def images
  @images
end

#max_url_lengthObject (readonly)

:nodoc:



68
69
70
# File 'lib/write_xlsx/workbook.rb', line 68

def max_url_length
  @max_url_length
end

#named_rangesObject (readonly)

:nodoc:



61
62
63
# File 'lib/write_xlsx/workbook.rb', line 61

def named_ranges
  @named_ranges
end

#paletteObject (readonly)

:nodoc:



58
59
60
# File 'lib/write_xlsx/workbook.rb', line 58

def palette
  @palette
end

#read_onlyObject (readonly)

:nodoc:



70
71
72
# File 'lib/write_xlsx/workbook.rb', line 70

def read_only
  @read_only
end

#shared_stringsObject (readonly)

:nodoc:



65
66
67
# File 'lib/write_xlsx/workbook.rb', line 65

def shared_strings
  @shared_strings
end

#strings_to_urlsObject (readonly)

:nodoc:



69
70
71
# File 'lib/write_xlsx/workbook.rb', line 69

def strings_to_urls
  @strings_to_urls
end

#vba_projectObject (readonly)

:nodoc:



66
67
68
# File 'lib/write_xlsx/workbook.rb', line 66

def vba_project
  @vba_project
end

#worksheetsObject (readonly)

:nodoc:



59
60
61
# File 'lib/write_xlsx/workbook.rb', line 59

def worksheets
  @worksheets
end

#writerObject (readonly)

Returns the value of attribute writer.



484
485
486
# File 'lib/write_xlsx/workbook.rb', line 484

def writer
  @writer
end

Instance Method Details

#add_chart(params = {}) ⇒ Object

This method is use to create a new chart either as a standalone worksheet (the default) or as an embeddable object that can be inserted into a worksheet via the insert_chart method.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/write_xlsx/workbook.rb', line 125

def add_chart(params = {})
  # Type must be specified so we can create the required chart instance.
  type     = params[:type]
  embedded = params[:embedded]
  name     = params[:name]
  raise "Must define chart type in add_chart()" unless type

  chart = Chart.factory(type, params[:subtype])
  chart.palette = @palette

  # If the chart isn't embedded let the workbook control it.
  if ptrue?(embedded)
    chart.name = name if name

    # Set index to 0 so that the activate() and set_first_sheet() methods
    # point back to the first worksheet if used for embedded charts.
    chart.index = 0
    chart.set_embedded_config_data
  else
    # Check the worksheet name for non-embedded charts.
    sheetname  = check_chart_sheetname(name)
    chartsheet = Chartsheet.new(self, @worksheets.size, sheetname)
    chartsheet.chart = chart
    @worksheets << chartsheet
  end
  @charts << chart
  ptrue?(embedded) ? chart : chartsheet
end

#add_format(property_hash = {}) ⇒ Object

The add_format method can be used to create new Format objects which are used to apply formatting to a cell. You can either define the properties at creation time via a hash of property values or later via method calls.

format1 = workbook.add_format(property_hash) # Set properties at creation
format2 = workbook.add_format                # Set properties later


163
164
165
166
167
168
169
170
171
172
173
# File 'lib/write_xlsx/workbook.rb', line 163

def add_format(property_hash = {})
  properties = {}
  properties.update(font: 'Arial', size: 10, theme: -1) if @excel2003_style
  properties.update(property_hash)

  format = Format.new(@formats, properties)

  @formats.formats.push(format)    # Store format reference

  format
end

#add_shape(properties = {}) ⇒ Object

The add_shape method can be used to create new shapes that may be inserted into a worksheet.



179
180
181
182
183
184
185
186
# File 'lib/write_xlsx/workbook.rb', line 179

def add_shape(properties = {})
  shape = Shape.new(properties)
  shape.palette = @palette

  @shapes ||= []
  @shapes << shape  # Store shape reference.
  shape
end

#add_vba_project(vba_project) ⇒ Object

The add_vba_project method can be used to add macros or functions to an WriteXLSX file using a binary VBA project file that has been extracted from an existing Excel xlsm file.



364
365
366
# File 'lib/write_xlsx/workbook.rb', line 364

def add_vba_project(vba_project)
  @vba_project = vba_project
end

#add_worksheet(name = '') ⇒ Object

At least one worksheet should be added to a new workbook. A worksheet is used to write data into cells:



113
114
115
116
117
118
# File 'lib/write_xlsx/workbook.rb', line 113

def add_worksheet(name = '')
  name = check_sheetname(name)
  worksheet = Worksheet.new(self, @worksheets.size, name)
  @worksheets << worksheet
  worksheet
end

#chartsheet_countObject



519
520
521
# File 'lib/write_xlsx/workbook.rb', line 519

def chartsheet_count
  @worksheets.chartsheet_count
end

#chartsheetsObject



549
550
551
# File 'lib/write_xlsx/workbook.rb', line 549

def chartsheets
  @worksheets.chartsheets
end

#closeObject



96
97
98
99
100
101
102
# File 'lib/write_xlsx/workbook.rb', line 96

def close
  # In case close() is called twice.
  return if @fileclosed

  @fileclosed = true
  store_workbook
end

#date_1904?Boolean

Workbook state queries

Returns:

  • (Boolean)


492
493
494
495
# File 'lib/write_xlsx/workbook.rb', line 492

def date_1904? # :nodoc:
  @date_1904 ||= false
  !!@date_1904
end

#define_name(name, formula) ⇒ Object

Create a defined name in Excel. We handle global/workbook level names and local/worksheet names.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/write_xlsx/workbook.rb', line 218

def define_name(name, formula)
  sheet_index = nil
  sheetname   = ''

  # Local defined names are formatted like "Sheet1!name".
  if name =~ /^(.*)!(.*)$/
    sheetname   = ::Regexp.last_match(1)
    name        = ::Regexp.last_match(2)
    sheet_index = @worksheets.index_by_name(sheetname)
  else
    sheet_index = -1   # Use -1 to indicate global names.
  end

  # Raise if the sheet index wasn't found.
  raise "Unknown sheet name #{sheetname} in defined_name()" unless sheet_index

  # Raise if the name contains invalid chars as defined by Excel help.
  # Refer to the following to see Excel's syntax rules for defined names:
  # http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010147120.aspx#BMsyntax_rules_for_names
  #
  raise "Invalid characters in name '#{name}' used in defined_name()" if name =~ /\A[-0-9 !"#$%&'()*+,.:;<=>?@\[\]\^`{}~]/ || name =~ /.+[- !"#$%&'()*+,\\:;<=>?@\[\]\^`{}~]/

  # Raise if the name looks like a cell name.
  raise "Invalid name '#{name}' looks like a cell name in defined_name()" if name =~ /^[a-zA-Z][a-zA-Z]?[a-dA-D]?[0-9]+$/

  # Raise if the name looks like a R1C1
  raise "Invalid name '#{name}' like a RC cell ref in defined_name()" if name =~ /\A[rcRC]\Z/ || name =~ /\A[rcRC]\d+[rcRC]\d+\Z/

  @defined_names.push([name, sheet_index, formula.sub(/^=/, '')])
end

#get_1904Object

return date system. false = 1900, true = 1904



206
207
208
# File 'lib/write_xlsx/workbook.rb', line 206

def get_1904
  @date_1904
end

#has_dynamic_functions?Boolean

Returns:

  • (Boolean)


497
498
499
# File 'lib/write_xlsx/workbook.rb', line 497

def has_dynamic_functions?
  @has_dynamic_functions
end

#has_embedded_descriptions?Boolean

Returns:

  • (Boolean)


573
574
575
# File 'lib/write_xlsx/workbook.rb', line 573

def has_embedded_descriptions?
  @has_embedded_descriptions
end

#has_embedded_images?Boolean

Returns:

  • (Boolean)


569
570
571
# File 'lib/write_xlsx/workbook.rb', line 569

def has_embedded_images?
  @has_embedded_images
end

#has_metadata?Boolean

Returns:

  • (Boolean)


565
566
567
# File 'lib/write_xlsx/workbook.rb', line 565

def has_metadata?
  
end

#non_chartsheet_countObject



523
524
525
# File 'lib/write_xlsx/workbook.rb', line 523

def non_chartsheet_count
  @worksheets.worksheets.count
end

#non_chartsheetsObject



553
554
555
# File 'lib/write_xlsx/workbook.rb', line 553

def non_chartsheets
  @worksheets.worksheets
end

#num_comment_filesObject



545
546
547
# File 'lib/write_xlsx/workbook.rb', line 545

def num_comment_files
  @worksheets.select { |sheet| sheet.has_comments? }.count
end

#num_vml_filesObject



541
542
543
# File 'lib/write_xlsx/workbook.rb', line 541

def num_vml_files
  @worksheets.select { |sheet| sheet.has_vml? || sheet.has_header_vml? }.count
end

Set the Excel "Read-only recommended" save option.



378
379
380
# File 'lib/write_xlsx/workbook.rb', line 378

def read_only_recommended
  @read_only = 2
end

#set_1904(mode = true) ⇒ Object

Set the date system: false = 1900 (the default), true = 1904



197
198
199
200
201
# File 'lib/write_xlsx/workbook.rb', line 197

def set_1904(mode = true)
  raise "set_1904() must be called before add_worksheet()" unless sheets.empty?

  @date_1904 = ptrue?(mode)
end

#set_calc_mode(mode, calc_id = nil) ⇒ Object

set_calc_mode()

Set the Excel caclcuation mode for the workbook.



387
388
389
390
391
392
393
394
395
396
397
# File 'lib/write_xlsx/workbook.rb', line 387

def set_calc_mode(mode, calc_id = nil)
  @calc_mode = mode || 'auto'

  if mode == 'manual'
    @calc_on_load = false
  elsif mode == 'auto_except_tables'
    @calc_mode = 'autoNoTable'
  end

  @calc_id = calc_id if calc_id
end

#set_custom_color(index, red = 0, green = 0, blue = 0) ⇒ Object

Change the RGB components of the elements in the colour palette.



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/write_xlsx/workbook.rb', line 402

def set_custom_color(index, red = 0, green = 0, blue = 0)
  # Match a HTML #xxyyzz style parameter
  if red.to_s =~ /^#(\w\w)(\w\w)(\w\w)/
    red   = ::Regexp.last_match(1).hex
    green = ::Regexp.last_match(2).hex
    blue  = ::Regexp.last_match(3).hex
  end

  # Check that the colour index is the right range
  raise "Color index #{index} outside range: 8 <= index <= 64" if index < 8 || index > 64

  # Check that the colour components are in the right range
  if (red   < 0 || red   > 255) ||
     (green < 0 || green > 255) ||
     (blue  < 0 || blue  > 255)
    raise "Color component outside range: 0 <= color <= 255"
  end

  index -= 8       # Adjust colour index (wingless dragonfly)

  # Set the RGB value
  @palette[index] = [red, green, blue]

  # Store the custome colors for the style.xml file.
  @custom_colors << sprintf("FF%02X%02X%02X", red, green, blue)

  index + 8
end

#set_custom_property(name, value, type = nil) ⇒ Object

Set a user defined custom document property.



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/write_xlsx/workbook.rb', line 322

def set_custom_property(name, value, type = nil)
  # Valid types.
  valid_type = {
    'text'       => 1,
    'date'       => 1,
    'number'     => 1,
    'number_int' => 1,
    'bool'       => 1
  }

  raise "The name and value parameters must be defined in set_custom_property()" if !name || (type != 'bool' && !value)

  # Determine the type for strings and numbers if it hasn't been specified.
  unless ptrue?(type)
    type = if value =~ /^\d+$/
             'number_int'
           elsif value =~
                 /^([+-]?)(?=[0-9]|\.[0-9])[0-9]*(\.[0-9]*)?([Ee]([+-]?[0-9]+))?$/
             'number'
           else
             'text'
           end
  end

  # Check for valid validation types.
  raise "Unknown custom type '$type' in set_custom_property()" unless valid_type[type]

  #  Check for strings longer than Excel's limit of 255 chars.
  raise "Length of text custom value '$value' exceeds Excel's limit of 255 in set_custom_property()" if type == 'text' && value.length > 255

  if type == 'bool'
    value = value ? 1 : 0
  end

  @custom_properties << [name, value, type]
end

#set_properties(params) ⇒ Object

The set_properties method can be used to set the document properties of the Excel file created by WriteXLSX. These properties are visible when you use the Office Button -> Prepare -> Properties option in Excel and are also available to external applications that read or index windows files.



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/write_xlsx/workbook.rb', line 288

def set_properties(params)
  # Ignore if no args were passed.
  return -1 if params.empty?

  # List of valid input parameters.
  valid = {
    title:          1,
    subject:        1,
    author:         1,
    keywords:       1,
    comments:       1,
    last_author:    1,
    created:        1,
    category:       1,
    manager:        1,
    company:        1,
    status:         1,
    hyperlink_base: 1
  }

  # Check for valid input parameters.
  params.each_key do |key|
    return -1 unless valid.has_key?(key)
  end

  # Set the creation time unless specified by the user.
  params[:created] = @createtime unless params.has_key?(:created)

  @doc_properties = params.dup
end

#set_size(width = nil, height = nil) ⇒ Object

Set the workbook size.



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/write_xlsx/workbook.rb', line 252

def set_size(width = nil, height = nil)
  @window_width = if ptrue?(width)
                    # Convert to twips at 96 dpi.
                    width.to_i * 1440 / 96
                  else
                    16095
                  end

  @window_height = if ptrue?(height)
                     # Convert to twips at 96 dpi.
                     height.to_i * 1440 / 96
                   else
                     9660
                   end
end

#set_tab_ratio(tab_ratio = nil) ⇒ Object

Set the ratio of space for worksheet tabs.



271
272
273
274
275
276
277
278
279
# File 'lib/write_xlsx/workbook.rb', line 271

def set_tab_ratio(tab_ratio = nil)
  return unless tab_ratio

  if tab_ratio < 0 || tab_ratio > 100
    raise "Tab ratio outside range: 0 <= zoom <= 100"
  else
    @tab_ratio = (tab_ratio * 10).to_i
  end
end

#set_tempdir(dir) ⇒ Object



210
211
212
# File 'lib/write_xlsx/workbook.rb', line 210

def set_tempdir(dir)
  @tempdir = dir.dup
end

#set_vba_name(vba_codename = nil) ⇒ Object

Set the VBA name for the workbook.



371
372
373
# File 'lib/write_xlsx/workbook.rb', line 371

def set_vba_name(vba_codename = nil)
  @vba_codename = vba_codename || 'ThisWorkbook'
end

#set_xml_writer(filename) ⇒ Object

user must not use. it is internal method.



463
464
465
# File 'lib/write_xlsx/workbook.rb', line 463

def set_xml_writer(filename)  # :nodoc:
  @writer.set_xml_writer(filename)
end

#shared_string_index(str) ⇒ Object

:nodoc:



507
508
509
# File 'lib/write_xlsx/workbook.rb', line 507

def shared_string_index(str) # :nodoc:
  @shared_strings.index(str, EMPTY_HASH)
end

#shared_strings_empty?Boolean

:nodoc:

Returns:

  • (Boolean)


515
516
517
# File 'lib/write_xlsx/workbook.rb', line 515

def shared_strings_empty?  # :nodoc:
  @shared_strings.empty?
end

#sheets(*args) ⇒ Object

get array of Worksheet objects

:call-seq: sheets -> array of all Wordsheet object sheets(1, 3, 4) -> array of spcified Worksheet object.



444
445
446
447
448
449
450
# File 'lib/write_xlsx/workbook.rb', line 444

def sheets(*args)
  if args.empty?
    @worksheets
  else
    args.collect { |i| @worksheets[i] }
  end
end

#store_image_types(type) ⇒ Object

Store the image types (PNG/JPEG/etc) used in the workbook to use in these Content_Types file.



581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/write_xlsx/workbook.rb', line 581

def store_image_types(type)
  case type
  when 'png'
    @image_types[:png] = 1
  when 'jpeg'
    @image_types[:jpeg] = 1
  when 'gif'
    @image_types[:gif] = 1
  when 'bmp'
    @image_types[:bmp] = 1
  end
end

#str_uniqueObject

:nodoc:



511
512
513
# File 'lib/write_xlsx/workbook.rb', line 511

def str_unique   # :nodoc:
  @shared_strings.unique_count
end

#style_propertiesObject



527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/write_xlsx/workbook.rb', line 527

def style_properties
  [
    @xf_formats,
    @palette,
    @font_count,
    @num_formats,
    @border_count,
    @fill_count,
    @custom_colors,
    @dxf_formats,
    @has_comments
  ]
end

#worksheet_by_name(sheetname = nil) ⇒ Object Also known as: get_worksheet_by_name

Return a worksheet object in the workbook using the sheetname.



455
456
457
# File 'lib/write_xlsx/workbook.rb', line 455

def worksheet_by_name(sheetname = nil)
  sheets.select { |s| s.name == sheetname }.first
end

#xml_strObject

user must not use. it is internal method.



470
471
472
# File 'lib/write_xlsx/workbook.rb', line 470

def xml_str  # :nodoc:
  @writer.string
end