Class: Writexlsx::Workbook

Inherits:
Object
  • Object
show all
Includes:
Utility
Defined in:
lib/write_xlsx/workbook.rb

Direct Known Subclasses

WriteXLSX

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 Utility

Utility::CHAR_WIDTHS, Utility::COL_MAX, Utility::PERL_TRUE_VALUES, Utility::ROW_MAX, Utility::SHEETNAME_MAX, Utility::STR_MAX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utility

#absolute_char, #check_dimensions, #check_dimensions_and_update_max_min_values, #check_parameter, #color, #convert_date_time, #convert_font_args, #dash_types, delete_files, #escape_url, #fill_properties, #float_to_str, #get_font_latin_attributes, #get_font_style_attributes, #layout_properties, #legend_properties, #line_fill_properties, #line_properties, #palette_color, #params_to_font, #pattern_properties, #pixels_to_points, #process_workbook_options, #ptrue?, #put_deprecate_message, #quote_sheetname, #r_id_attributes, #row_col_notation, #shape_style_base, #store_col_max_min_values, #store_row_max_min_values, #substitute_cellref, #underline_attributes, #v_shape_attributes_base, #v_shape_style_base, #value_or_raise, #write_a_body_pr, #write_a_def_rpr, #write_a_end_para_rpr, #write_a_lst_style, #write_a_p_formula, #write_a_p_pr_formula, #write_a_solid_fill, #write_a_srgb_clr, #write_anchor, #write_auto_fill, #write_color, #write_comment_path, #write_def_rpr_r_pr_common, #write_div, #write_fill, #write_font, #write_stroke, #write_tx_pr, #write_xml_declaration, #xl_cell_to_rowcol, #xl_col_to_name, #xl_range, #xl_range_formula, #xl_rowcol_to_cell, #xl_string_pixel_width

Constructor Details

#initialize(file, *option_params) ⇒ Workbook

Returns a new instance of Workbook.



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
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/write_xlsx/workbook.rb', line 39

def initialize(file, *option_params)
  options, default_formats = process_workbook_options(*option_params)
  @writer = Package::XMLWriterSimple.new

  @file = file
  @tempdir = options[:tempdir] ||
             File.join(
               Dir.tmpdir,
               Digest::MD5.hexdigest("#{Time.now.to_f}-#{Process.pid}")
             )
  @date_1904           = options[:date_1904] || false
  @activesheet         = 0
  @firstsheet          = 0
  @selected            = 0
  @fileclosed          = false
  @worksheets          = Sheets.new
  @charts              = []
  @drawings            = []
  @formats             = Formats.new
  @xf_formats          = []
  @dxf_formats         = []
  @font_count          = 0
  @num_formats         = []
  @defined_names       = []
  @named_ranges        = []
  @custom_colors       = []
  @doc_properties      = {}
  @custom_properties   = []
  @optimization        = options[:optimization] || 0
  @x_window            = 240
  @y_window            = 15
  @window_width        = 16095
  @window_height       = 9660
  @tab_ratio           = 600
  @excel2003_style     = options[:excel2003_style] || false
  @table_count         = 0
  @image_types         = {}
  @images              = []
  @strings_to_urls     = options[:strings_to_urls].nil? || options[:strings_to_urls] ? true : false

  @max_url_length      = 2079
  @has_comments        = false
  @read_only           = 0
          = false
  if options[:max_url_length]
    @max_url_length = options[:max_url_length]

    @max_url_length = 2079 if @max_url_length < 250
  end
  # Structures for the shared strings data.
  @shared_strings = Package::SharedStrings.new

  # Formula calculation default settings.
  @calc_id             = 124519
  @calc_mode           = 'auto'
  @calc_on_load        = true

  if @excel2003_style
    add_format(default_formats.merge(
                 xf_index:    0,
                 font_family: 0,
                 font:        'Arial',
                 size:        10,
                 theme:       -1
               ))
  else
    add_format(default_formats.merge(xf_index: 0))
  end

  # Add a default URL format.
  @default_url_format = add_format(hyperlink: 1)

  set_color_palette
end

Instance Attribute Details

#activesheetObject

:nodoc:



592
593
594
# File 'lib/write_xlsx/workbook.rb', line 592

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

#chartsObject (readonly)

:nodoc:



27
28
29
# File 'lib/write_xlsx/workbook.rb', line 27

def charts
  @charts
end

#custom_propertiesObject (readonly)

:nodoc:



30
31
32
# File 'lib/write_xlsx/workbook.rb', line 30

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.



489
490
491
# File 'lib/write_xlsx/workbook.rb', line 489

def default_url_format
  @default_url_format
end

#doc_propertiesObject (readonly)

:nodoc:



29
30
31
# File 'lib/write_xlsx/workbook.rb', line 29

def doc_properties
  @doc_properties
end

#drawingsObject (readonly)

:nodoc:



27
28
29
# File 'lib/write_xlsx/workbook.rb', line 27

def drawings
  @drawings
end

#excel2003_styleObject (readonly)

:nodoc:



34
35
36
# File 'lib/write_xlsx/workbook.rb', line 34

def excel2003_style
  @excel2003_style
end

#firstsheetObject

:nodoc:



588
589
590
# File 'lib/write_xlsx/workbook.rb', line 588

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

#image_typesObject (readonly)

:nodoc:



31
32
33
# File 'lib/write_xlsx/workbook.rb', line 31

def image_types
  @image_types
end

#imagesObject (readonly)

:nodoc:



31
32
33
# File 'lib/write_xlsx/workbook.rb', line 31

def images
  @images
end

#max_url_lengthObject (readonly)

:nodoc:



35
36
37
# File 'lib/write_xlsx/workbook.rb', line 35

def max_url_length
  @max_url_length
end

#named_rangesObject (readonly)

:nodoc:



28
29
30
# File 'lib/write_xlsx/workbook.rb', line 28

def named_ranges
  @named_ranges
end

#paletteObject (readonly)

:nodoc:



26
27
28
# File 'lib/write_xlsx/workbook.rb', line 26

def palette
  @palette
end

#read_onlyObject (readonly)

:nodoc:



37
38
39
# File 'lib/write_xlsx/workbook.rb', line 37

def read_only
  @read_only
end

#shared_stringsObject (readonly)

:nodoc:



32
33
34
# File 'lib/write_xlsx/workbook.rb', line 32

def shared_strings
  @shared_strings
end

#strings_to_urlsObject (readonly)

:nodoc:



36
37
38
# File 'lib/write_xlsx/workbook.rb', line 36

def strings_to_urls
  @strings_to_urls
end

#vba_projectObject (readonly)

:nodoc:



33
34
35
# File 'lib/write_xlsx/workbook.rb', line 33

def vba_project
  @vba_project
end

#worksheetsObject (readonly)

:nodoc:



27
28
29
# File 'lib/write_xlsx/workbook.rb', line 27

def worksheets
  @worksheets
end

#writerObject (readonly)

Returns the value of attribute writer.



526
527
528
# File 'lib/write_xlsx/workbook.rb', line 526

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.



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/write_xlsx/workbook.rb', line 236

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


274
275
276
277
278
279
280
281
282
283
284
# File 'lib/write_xlsx/workbook.rb', line 274

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.



290
291
292
293
294
295
296
297
# File 'lib/write_xlsx/workbook.rb', line 290

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.



449
450
451
# File 'lib/write_xlsx/workbook.rb', line 449

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:



224
225
226
227
228
229
# File 'lib/write_xlsx/workbook.rb', line 224

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

#assemble_xml_fileObject

user must not use. it is internal method.



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/write_xlsx/workbook.rb', line 185

def assemble_xml_file  # :nodoc:
  return unless @writer

  # Prepare format object for passing to Style.rb.
  prepare_format_properties

  write_xml_declaration do
    # Write the root workbook element.
    write_workbook do
      # Write the XLSX file version.
      write_file_version

      # Write the fileSharing element.
      write_file_sharing

      # Write the workbook properties.
      write_workbook_pr

      # Write the workbook view properties.
      write_book_views

      # Write the worksheet names and ids.
      @worksheets.write_sheets(@writer)

      # Write the workbook defined names.
      write_defined_names

      # Write the workbook calculation properties.
      write_calc_pr

      # Write the workbook extension storage.
      # write_ext_lst
    end
  end
end

#chartsheet_countObject



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

def chartsheet_count
  @worksheets.chartsheet_count
end

#chartsheetsObject



580
581
582
# File 'lib/write_xlsx/workbook.rb', line 580

def chartsheets
  @worksheets.chartsheets
end

#closeObject

The close method is used to close an Excel file.



117
118
119
120
121
122
123
# File 'lib/write_xlsx/workbook.rb', line 117

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

  @fileclosed = true
  store_workbook
end

#date_1904?Boolean

:nodoc:

Returns:

  • (Boolean)


528
529
530
531
# File 'lib/write_xlsx/workbook.rb', line 528

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.



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/write_xlsx/workbook.rb', line 303

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



160
161
162
# File 'lib/write_xlsx/workbook.rb', line 160

def get_1904
  @date_1904
end

#has_metadata?Boolean

Returns:

  • (Boolean)


596
597
598
# File 'lib/write_xlsx/workbook.rb', line 596

def has_metadata?
  
end

#non_chartsheet_countObject



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

def non_chartsheet_count
  @worksheets.worksheets.count
end

#non_chartsheetsObject



584
585
586
# File 'lib/write_xlsx/workbook.rb', line 584

def non_chartsheets
  @worksheets.worksheets
end

#num_comment_filesObject



576
577
578
# File 'lib/write_xlsx/workbook.rb', line 576

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

#num_vml_filesObject



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

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

Set the Excel “Read-only recommended” save option.



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

def read_only_recommended
  @read_only = 2
end

#set_1904(mode = true) ⇒ Object

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



151
152
153
154
155
# File 'lib/write_xlsx/workbook.rb', line 151

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.



472
473
474
475
476
477
478
479
480
481
482
# File 'lib/write_xlsx/workbook.rb', line 472

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.



495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/write_xlsx/workbook.rb', line 495

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.



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/write_xlsx/workbook.rb', line 407

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.



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/write_xlsx/workbook.rb', line 373

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.



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/write_xlsx/workbook.rb', line 337

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.



356
357
358
359
360
361
362
363
364
# File 'lib/write_xlsx/workbook.rb', line 356

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



164
165
166
# File 'lib/write_xlsx/workbook.rb', line 164

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

#set_vba_name(vba_codename = nil) ⇒ Object

Set the VBA name for the workbook.



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

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.



171
172
173
# File 'lib/write_xlsx/workbook.rb', line 171

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

#shared_string_index(str) ⇒ Object

:nodoc:



538
539
540
# File 'lib/write_xlsx/workbook.rb', line 538

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

#shared_strings_empty?Boolean

:nodoc:

Returns:

  • (Boolean)


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

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.


132
133
134
135
136
137
138
# File 'lib/write_xlsx/workbook.rb', line 132

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

#str_uniqueObject

:nodoc:



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

def str_unique   # :nodoc:
  @shared_strings.unique_count
end

#style_propertiesObject



558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/write_xlsx/workbook.rb', line 558

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.



143
144
145
# File 'lib/write_xlsx/workbook.rb', line 143

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

#xml_strObject

user must not use. it is internal method.



178
179
180
# File 'lib/write_xlsx/workbook.rb', line 178

def xml_str  # :nodoc:
  @writer.string
end