Class: Workbook
- Inherits:
-
BIFFWriter
- Object
- WriteFile
- BIFFWriter
- Workbook
- Extended by:
- Forwardable
- Defined in:
- lib/writeexcel/workbook.rb,
lib/writeexcel/worksheets.rb,
lib/writeexcel/shared_string_table.rb
Direct Known Subclasses
Defined Under Namespace
Classes: SharedString, SharedStringTable, Worksheets
Constant Summary collapse
- BOF =
:nodoc:
12
- EOF =
:nodoc:
4
Constants inherited from BIFFWriter
BIFFWriter::BIFF_Version, BIFFWriter::BigEndian
Instance Attribute Summary collapse
-
#compatibility ⇒ Object
readonly
Returns the value of attribute compatibility.
-
#date_1904 ⇒ Object
readonly
Returns the value of attribute date_1904.
-
#ext_refs ⇒ Object
readonly
Returns the value of attribute ext_refs.
-
#palette ⇒ Object
readonly
Returns the value of attribute palette.
-
#parser ⇒ Object
readonly
Returns the value of attribute parser.
-
#tempdir ⇒ Object
readonly
Returns the value of attribute tempdir.
-
#url_format ⇒ Object
readonly
Returns the value of attribute url_format.
-
#worksheets ⇒ Object
readonly
Returns the value of attribute worksheets.
Attributes inherited from BIFFWriter
Instance Method Summary collapse
-
#add_chart(properties) ⇒ Object
Create a chart for embedding or as as new sheet.
-
#add_chart_ext(filename, chartname, name_utf16be = false) ⇒ Object
Add an externally created chart.
-
#add_format(*args) ⇒ Object
The add_format method can be used to create new Format objects which are used to apply formatting to a cell.
-
#add_worksheet(sheetname = '', name_utf16be = false) ⇒ Object
Add a new worksheet to the Excel workbook.
-
#biff_only=(val) ⇒ Object
:nodoc:.
-
#close ⇒ Object
Calls finalization methods and explicitly close the OLEwriter files handle.
-
#compatibility_mode(mode = true) ⇒ Object
Set the compatibility mode.
-
#define_name(name, formula, encoding = 0) ⇒ Object
This method is used to defined a name that can be used to represent a value, a single cell or a range of cells in a workbook.
-
#extsst_bucket_size ⇒ Object
:nodoc:.
-
#extsst_buckets ⇒ Object
:nodoc:.
- #get_1904 ⇒ Object
-
#initialize(file, default_formats = {}) ⇒ Workbook
constructor
file is a filename (as string) or io object where to out spreadsheet data.
-
#localtime=(val) ⇒ Object
:nodoc:.
-
#set_1904(mode = true) ⇒ Object
Set the date system: false = 1900 (the default), true = 1904.
-
#set_codepage(type = 1) ⇒ Object
The default code page or character set used by WriteExcel is ANSI.
-
#set_country(code = 1) ⇒ Object
store the country code.
-
#set_custom_color(index, red = nil, green = nil, blue = nil) ⇒ Object
Change the RGB components of the elements in the colour palette.
-
#set_properties(params) ⇒ Object
Set the document properties such as Title, Author etc.
-
#set_tempdir(dir = '') ⇒ Object
Change the default temp directory.
-
#sheets(*args) ⇒ Object
get array of Worksheet objects.
-
#summary ⇒ Object
:nodoc:.
- #update_str_table(str) ⇒ Object
Methods inherited from BIFFWriter
#add_continue, #add_mso_generic, #append, #clear_data_for_test, #get_data, #inspect, #not_using_tmpfile, #prepend, #print_caller_info, #set_byte_order, #store_bof, #store_eof, #unpack_record
Methods included from CallerInfo
Methods inherited from WriteFile
Constructor Details
#initialize(file, default_formats = {}) ⇒ Workbook
file is a filename (as string) or io object where to out spreadsheet data. you can set default format of workbook using default_formats.
A new Excel workbook is created using the new() constructor which accepts either a filename or an IO object as a parameter. The following example creates a new Excel file based on a filename:
workbook = WriteExcel.new('filename.xls')
worksheet = workbook.add_worksheet
worksheet.write(0, 0, 'Hi Excel!')
Here are some other examples of using new():
workbook1 = WriteExcel.new(filename)
workbook2 = WriteExcel.new('/tmp/filename.xls')
workbook3 = WriteExcel.new("c:\\tmp\\filename.xls")
workbook4 = WriteExcel.new('c:\tmp\filename.xls')
The last two examples demonstrates how to create a file on DOS or Windows where it is necessary to either escape the directory separator \ or to use single quotes to ensure that it isn’t interpolated.
The new() constructor returns a WriteExcel object that you can use to add worksheets and store data.
If the file cannot be created, due to file permissions or some other reason, new will raise Exception Errno::EXXX.
You can also pass a valid IO object to the new() constructor.:
require 'stringio'
io = StringIO.new
workbook = WriteExcel.new(io) # After workbook.close, you can get excel data as io.string
And, you can also pass default format properties.
workbook = WriteExcel.new(filename, :font => 'Courier New', :size => 11)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/writeexcel/workbook.rb', line 70 def initialize(file, default_formats = {}) super() @file = file @default_formats = default_formats @parser = Writeexcel::Formula.new(@byte_order) @tempdir = nil @date_1904 = false @xf_index = 0 @biffsize = 0 @sheet_count = 0 @chart_count = 0 @codepage = 0x04E4 @country = 1 @worksheets = Worksheets.new @formats = [] @palette = [] @biff_only = 0 @internal_fh = 0 @fh_out = "" @shared_string_table = SharedStringTable.new @extsst_offsets = [] # array of [global_offset, local_offset] @extsst_buckets = 0 @extsst_bucket_size = 0 @ext_refs = {} @mso_clusters = [] @mso_size = 0 @hideobj = false @summary = '' @doc_summary = '' @localtime = Time.now @defined_names = [] @fileclosed = nil setup_built_in_formats(default_formats) # Add the default format for hyperlinks @url_format = add_format(:color => 'blue', :underline => 1) if file.respond_to?(:to_str) && file != '' @fh_out = open(file, "wb") @internal_fh = 1 else @fh_out = file end # Set colour palette. set_palette_xl97 end |
Instance Attribute Details
#compatibility ⇒ Object (readonly)
Returns the value of attribute compatibility.
24 25 26 |
# File 'lib/writeexcel/workbook.rb', line 24 def compatibility @compatibility end |
#date_1904 ⇒ Object (readonly)
Returns the value of attribute date_1904.
23 24 25 |
# File 'lib/writeexcel/workbook.rb', line 23 def date_1904 @date_1904 end |
#ext_refs ⇒ Object (readonly)
Returns the value of attribute ext_refs.
25 26 27 |
# File 'lib/writeexcel/workbook.rb', line 25 def ext_refs @ext_refs end |
#palette ⇒ Object (readonly)
Returns the value of attribute palette.
24 25 26 |
# File 'lib/writeexcel/workbook.rb', line 24 def palette @palette end |
#parser ⇒ Object (readonly)
Returns the value of attribute parser.
23 24 25 |
# File 'lib/writeexcel/workbook.rb', line 23 def parser @parser end |
#tempdir ⇒ Object (readonly)
Returns the value of attribute tempdir.
23 24 25 |
# File 'lib/writeexcel/workbook.rb', line 23 def tempdir @tempdir end |
#url_format ⇒ Object (readonly)
Returns the value of attribute url_format.
23 24 25 |
# File 'lib/writeexcel/workbook.rb', line 23 def url_format @url_format end |
#worksheets ⇒ Object (readonly)
Returns the value of attribute worksheets.
26 27 28 |
# File 'lib/writeexcel/workbook.rb', line 26 def worksheets @worksheets end |
Instance Method Details
#add_chart(properties) ⇒ Object
Create a chart for embedding or as as new sheet.
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() Worksheet method.
chart = workbook.add_chart(:type => 'Chart::Column')
The properties that can be set are:
:type (required)
:name (optional)
:name_utf16be (optional)
:embedded (optional)
-
:type
This is a required parameter. It defines the type of chart that will be created.
chart = workbook.add_chart(:type => 'Chart::Line')
The available types are:
'Chart::Column'
'Chart::Bar'
'Chart::Line'
'Chart::Area'
'Chart::Pie'
'Chart::Scatter'
'Chart::Stock'
-
:name
Set the name for the chart sheet. The name property is optional and if it isn’t supplied will default to Chart1 .. n. The name must be a valid Excel worksheet name. See add_worksheet() for more details on valid sheet names. The :name property can be omitted for embedded charts.
chart = workbook.add_chart(
:type => 'Chart::Line',
:name => 'Results Chart'
)
-
:name_utf16be
if :name is UTF-16BE format, pass true as :name_utf16be
-
:encoding
if :name is UTF-16BE format, pass 1 as :encoding. This key is obsolete in v0.7 or later. Use :name_utf16be instead.
-
:embedded
Specifies true that the Chart object will be inserted in a worksheet via the insert_chart() Worksheet method. It is an error to try insert a Chart that doesn’t have this flag set.
chart = workbook.add_chart(:type => 'Chart::Line', :embedded => true)
# Configure the chart.
...
# Insert the chart into the a worksheet.
worksheet.insert_chart('E2', chart)
See WriteExcel::Chart for details on how to configure the chart object once it is created. See also the chart_*.rb programs in the examples directory of the distro.
301 302 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 333 |
# File 'lib/writeexcel/workbook.rb', line 301 def add_chart(properties) name = '' name_utf16be = false # Type must be specified so we can create the required chart instance. type = properties[:type] raise "Must define chart type in add_chart()" if type.nil? # Ensure that the chart defaults to non embedded. = properties[:embedded] # Check the worksheet name for non-embedded charts. unless properties[:name_utf16be] = true if properties[:encoding] == 1 name, name_utf16be = check_sheetname(properties[:name], properties[:name_utf16be], true) end init_data = [ self, name, name_utf16be ] chart = Writeexcel::Chart.factory(type, *init_data) # If the chart isn't embedded let the workbook control it. if ! @worksheets << chart # Store ref for iterator else chart. end chart end |
#add_chart_ext(filename, chartname, name_utf16be = false) ⇒ Object
Add an externally created chart.
This method is use to include externally generated charts in a WriteExcel file.
chart = workbook.add_chart_ext('chart01.bin', 'Chart1')
This feature is semi-deprecated in favour of the “native” charts created using add_chart(). Read external_charts.txt in the external_charts directory of the distro for a full explanation.
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/writeexcel/workbook.rb', line 347 def add_chart_ext(filename, chartname, name_utf16be = false) type = 'extarnal' name, name_utf16be = check_sheetname(chartname, name_utf16be) init_data = [ filename, name, name_utf16be ] chart = Writeexcel::Chart.factory(self, type, init_data) @worksheets << chart # Store ref for iterator chart end |
#add_format(*args) ⇒ 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(props) # Set properties at creation
format2 = workbook.add_format # Set properties later
See the “CELL FORMATTING” section for more details about Format properties and how to set them.
373 374 375 376 377 378 379 380 |
# File 'lib/writeexcel/workbook.rb', line 373 def add_format(*args) fmts = {} args.each { |arg| fmts = fmts.merge(arg) } format = Writeexcel::Format.new(@xf_index, @default_formats.merge(fmts)) @xf_index += 1 @formats.push format # Store format reference format end |
#add_worksheet(sheetname = '', name_utf16be = false) ⇒ Object
Add a new worksheet to the Excel workbook.
if sheetname is UTF-16BE format, pass true as name_utf16be.
At least one worksheet should be added to a new workbook. A worksheet is used to write data into cells:
worksheet1 = workbook.add_worksheet # Sheet1
worksheet2 = workbook.add_worksheet('Foglio2') # Foglio2
worksheet3 = workbook.add_worksheet('Data') # Data
worksheet4 = workbook.add_worksheet # Sheet4
If sheetname is not specified the default Excel convention will be followed, i.e. Sheet1, Sheet2, etc. The utf_16_be parameter is optional, see below.
The worksheet name must be a valid Excel worksheet name, i.e. it cannot contain any of the following characters, [ ] : * ? / \ and it must be less than 32 characters. In addition, you cannot use the same, case insensitive, sheetname for more than one worksheet.
This method will also handle strings in UTF-8 format.
worksheet = workbook.add_worksheet("シート名")
UTF-16BE worksheet names using an additional optional parameter:
name = [0x263a].pack('n')
worksheet = workbook.add_worksheet(name, true) # Smiley
215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'lib/writeexcel/workbook.rb', line 215 def add_worksheet(sheetname = '', name_utf16be = false) name, name_utf16be = check_sheetname(sheetname, name_utf16be) init_data = [ self, name, name_utf16be ] worksheet = Writeexcel::Worksheet.new(*init_data) @worksheets << worksheet # Store ref for iterator @parser.set_ext_sheets(name, worksheet.index) # Store names in Formula.rb worksheet end |
#biff_only=(val) ⇒ Object
:nodoc:
793 794 795 |
# File 'lib/writeexcel/workbook.rb', line 793 def biff_only=(val) # :nodoc: @biff_only = val end |
#close ⇒ Object
Calls finalization methods and explicitly close the OLEwriter files handle.
An explicit close() is required if the file must be closed prior to performing some external action on it such as copying it, reading its size or attaching it to an email.
In general, if you create a file with a size of 0 bytes or you fail to create a file you need to call close().
137 138 139 140 141 142 143 |
# File 'lib/writeexcel/workbook.rb', line 137 def close return if fileclosed? # Prevent close() from being called twice. @fileclosed = true store_workbook cleanup end |
#compatibility_mode(mode = true) ⇒ Object
Set the compatibility mode.
This method is used to improve compatibility with third party applications that read Excel files.
workbook.compatibility_mode
An Excel file is comprised of binary records that describe properties of a spreadsheet. Excel is reasonably liberal about this and, outside of a core subset, it doesn’t require every possible record to be present when it reads a file. This is also true of Gnumeric and OpenOffice.Org Calc.
WriteExcel takes advantage of this fact to omit some records in order to minimise the amount of data stored in memory and to simplify and speed up the writing of files. However, some third party applications that read Excel files often expect certain records to be present. In “compatibility mode” WriteExcel writes these records and tries to be as close to an Excel generated file as possible.
Applications that require compatibility_mode() are Apache POI, Apple Numbers, and Quickoffice on Nokia, Palm and other devices. You should also use compatibility_mode() if your Excel file will be used as an external data source by another Excel file.
If you encounter other situations that require compatibility_mode(), please let me know.
It should be noted that compatibility_mode() requires additional data to be stored in memory and additional processing. This incurs a memory and speed penalty and may not be suitable for very large files (>20MB).
You must call compatibility_mode() before calling add_worksheet().
Excel doesn’t require every possible Biff record to be present in a file. In particular if the indexing records INDEX, ROW and DBCELL aren’t present it just ignores the fact and reads the cells anyway. This is also true of the EXTSST record. Gnumeric and OOo also take this approach. This allows WriteExcel to ignore these records in order to minimise the amount of data stored in memory. However, other third party applications that read Excel files often expect these records to be present. In “compatibility mode” WriteExcel writes these records and tries to be as close to an Excel generated file as possible.
This requires additional data to be stored in memory until the file is about to be written. This incurs a memory and speed penalty and may not be suitable for very large files.
431 432 433 434 435 436 |
# File 'lib/writeexcel/workbook.rb', line 431 def compatibility_mode(mode = true) unless sheets.empty? raise "compatibility_mode() must be called before add_worksheet()" end @compatibility = mode end |
#define_name(name, formula, encoding = 0) ⇒ Object
This method is used to defined a name that can be used to represent a value, a single cell or a range of cells in a workbook.
workbook.define_name('Exchange_rate', '=0.96')
workbook.define_name('Sales', '=Sheet1!$G$1:$H$10')
workbook.define_name('Sheet2!Sales', '=Sheet2!$G$1:$G$10')
See the defined_name.rb program in the examples dir of the distro.
Note: This currently a beta feature. More documentation and examples will be added.
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 |
# File 'lib/writeexcel/workbook.rb', line 644 def define_name(name, formula, encoding = 0) sheet_index = 0 if name =~ /^(.*)!(.*)$/ sheetname = $1 name = $2 sheet_index = 1 + @parser.get_sheet_index(sheetname) end # Strip the = sign at the beginning of the formula string formula = formula.sub(/^=/, '') # Parse the formula using the parser in Formula.pm parser = @parser # In order to raise formula errors from the point of view of the calling # program we use an eval block and re-raise the error from here. # tokens = parser.parse_formula(formula) # Force 2d ranges to be a reference class. tokens.collect! { |t| t.gsub(/_ref3d/, '_ref3dR') } tokens.collect! { |t| t.gsub(/_range3d/, '_range3dR') } # Parse the tokens into a formula string. formula = parser.parse_tokens(tokens) defined_names.push( { :name => name, :encoding => encoding, :sheet_index => sheet_index, :formula => formula } ) index = defined_names.size parser.set_ext_name(name, index) end |
#extsst_bucket_size ⇒ Object
:nodoc:
789 790 791 |
# File 'lib/writeexcel/workbook.rb', line 789 def extsst_bucket_size # :nodoc: @extsst_bucket_size end |
#extsst_buckets ⇒ Object
:nodoc:
785 786 787 |
# File 'lib/writeexcel/workbook.rb', line 785 def extsst_buckets # :nodoc: @extsst_buckets end |
#get_1904 ⇒ Object
465 466 467 |
# File 'lib/writeexcel/workbook.rb', line 465 def get_1904 @date_1904 end |
#localtime=(val) ⇒ Object
:nodoc:
801 802 803 |
# File 'lib/writeexcel/workbook.rb', line 801 def localtime=(val) # :nodoc: @localtime = val end |
#set_1904(mode = true) ⇒ Object
Set the date system: false = 1900 (the default), true = 1904
Excel stores dates as real numbers where the integer part stores the number of days since the epoch and the fractional part stores the percentage of the day. The epoch can be either 1900 or 1904. Excel for Windows uses 1900 and Excel for Macintosh uses 1904. However, Excel on either platform will convert automatically between one system and the other.
WriteExcel stores dates in the 1900 format by default. If you wish to change this you can call the set_1904() workbook method. You can query the current value by calling the get_1904() workbook method. This returns false for 1900 and true for 1904.
See also “DATES AND TIME IN EXCEL” for more information about working with Excel’s date system.
In general you probably won’t need to use set_1904().
458 459 460 461 462 463 |
# File 'lib/writeexcel/workbook.rb', line 458 def set_1904(mode = true) unless sheets.empty? raise "set_1904() must be called before add_worksheet()" end @date_1904 = (!mode || mode == 0) ? false : true end |
#set_codepage(type = 1) ⇒ Object
The default code page or character set used by WriteExcel is ANSI. This is also the default used by Excel for Windows. Occasionally however it may be necessary to change the code page via the set_codepage() method.
Changing the code page may be required if your are using WriteExcel on the Macintosh and you are using characters outside the ASCII 128 character set:
workbook.set_codepage(1) # ANSI, MS Windows
workbook.set_codepage(2) # Apple Macintosh
The set_codepage() method is rarely required.
612 613 614 615 616 617 618 |
# File 'lib/writeexcel/workbook.rb', line 612 def set_codepage(type = 1) if type == 2 @codepage = 0x8000 else @codepage = 0x04E4 end end |
#set_country(code = 1) ⇒ Object
store the country code.
Some non-english versions of Excel may need this set to some value other than 1 = “United States”. In general the country code is equal to the international dialling code.
627 628 629 |
# File 'lib/writeexcel/workbook.rb', line 627 def set_country(code = 1) @country = code end |
#set_custom_color(index, red = nil, green = nil, blue = nil) ⇒ Object
Change the RGB components of the elements in the colour palette.
The set_custom_color() method can be used to override one of the built-in palette values with a more suitable colour.
The value for index should be in the range 8..63, see “COLOURS IN EXCEL”.
The default named colours use the following indices:
8 => black
9 => white
10 => red
11 => lime
12 => blue
13 => yellow
14 => magenta
15 => cyan
16 => brown
17 => green
18 => navy
20 => purple
22 => silver
23 => gray
33 => pink
53 => orange
A new colour is set using its RGB (red green blue) components. The red, green and blue values must be in the range 0..255. You can determine the required values in Excel using the Tools->Options->Colors->Modify dialog.
The set_custom_color() workbook method can also be used with a HTML style #rrggbb hex value:
workbook.set_custom_color(40, 255, 102, 0 ) # Orange
workbook.set_custom_color(40, 0xFF, 0x66, 0x00) # Same thing
workbook.set_custom_color(40, '#FF6600' ) # Same thing
font = workbook.add_format(:color => 40) # Use the modified colour
The return value from set_custom_color() is the index of the colour that was changed:
ferrari = workbook.set_custom_color(40, 216, 12, 12)
format = workbook.add_format(
:bg_color => $ferrari,
:pattern => 1,
:border => 1
)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/writeexcel/workbook.rb', line 520 def set_custom_color(index, red = nil, green = nil, blue = nil) # Match a HTML #xxyyzz style parameter if !red.nil? && red =~ /^#(\w\w)(\w\w)(\w\w)/ red = $1.hex green = $2.hex blue = $3.hex end # Check that the colour index is the right range if index < 8 || index > 64 raise "Color index #{index} outside range: 8 <= index <= 64" end # 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, 0] index + 8 end |
#set_properties(params) ⇒ Object
Set the document properties such as Title, Author etc. These are written to property sets in the OLE container.
The set_properties method can be used to set the document properties of the Excel file created by WriteExcel. These properties are visible when you use the File->Properties menu option in Excel and are also available to external applications that read or index windows files.
The properties should be passed as a hash of values as follows:
workbook.set_properties(
:title => 'This is an example spreadsheet',
:author => 'cxn03651',
:comments => 'Created with Ruby and WriteExcel',
)
The properties that can be set are:
* :title
* :subject
* :author
* :manager
* :company
* :category
* :keywords
* :comments
User defined properties are not supported due to effort required.
You can also pass UTF-8 strings as properties.
workbook.set_properties(
:subject => "住所録"
)
Usually WriteExcel allows you to use UTF-16. However, document properties don’t support UTF-16 for these type of strings.
In order to promote the usefulness of Ruby and the WriteExcel module consider adding a comment such as the following when using document properties:
workbook.set_properties(
...,
:comments => 'Created with Ruby and writeexcel',
...,
)
See also the properties.rb program in the examples directory of the distro.
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 |
# File 'lib/writeexcel/workbook.rb', line 736 def set_properties(params) # Ignore if no args were passed. return -1 if !params.respond_to?(:to_hash) || params.empty? params.each do |k, v| params[k] = convert_to_ascii_if_ascii(v) if v.respond_to?(:to_str) end # Check for valid input parameters. check_valid_params_for_properties(params) # Set the creation time unless specified by the user. params[:created] = @localtime unless params.has_key?(:created) # # Create the SummaryInformation property set. # # Get the codepage of the strings in the property set. properties = [:title, :subject, :author, :keywords, :comments, :last_author] params[:codepage] = get_property_set_codepage(params, properties) # Create an array of property set values. properties.unshift(:codepage) properties.push(:created) # Pack the property sets. @summary = create_summary_property_set(property_sets(properties, params)) # # Create the DocSummaryInformation property set. # # Get the codepage of the strings in the property set. properties = [:category, :manager, :company] params[:codepage] = get_property_set_codepage(params, properties) # Create an array of property set values. properties.unshift(:codepage) # Pack the property sets. @doc_summary = create_doc_summary_property_set(property_sets(properties, params)) # Set a flag for when the files is written. @add_doc_properties = true end |
#set_tempdir(dir = '') ⇒ Object
Change the default temp directory
For speed and efficiency WriteExcel stores worksheet data in temporary files prior to assembling the final workbook.
If WriteExcel is unable to create these temporary files it will store the required data in memory. This can be slow for large files.
The problem occurs mainly with IIS on Windows although it could feasibly occur on Unix systems as well. The problem generally occurs because the default temp file directory is defined as C:/ or some other directory that IIS doesn’t provide write access to.
To check if this might be a problem on a particular system you can run a simple test program with -w or use warnings. This will generate a warning if the module cannot create the required temporary files:
#!/usr/bin/ruby -w
require 'WriteExcel'
workbook = WriteExcel.new('test.xls')
worksheet = workbook.add_worksheet
workbook.close
To avoid this problem the set_tempdir() method can be used to specify a directory that is accessible for the creation of temporary files.
Even if the default temporary file directory is accessible you may wish to specify an alternative location for security or maintenance reasons:
workbook.set_tempdir('/tmp/writeexcel')
workbook.set_tempdir('c:\windows\temp\writeexcel')
The directory for the temporary file must exist, set_tempdir() will not create a new directory.
One disadvantage of using the set_tempdir() method is that on some Windows systems it will limit you to approximately 800 concurrent tempfiles. This means that a single program running on one of these systems will be limited to creating a total of 800 workbook and worksheet objects. You can run multiple, non-concurrent programs to work around this if necessary.
592 593 594 595 596 597 |
# File 'lib/writeexcel/workbook.rb', line 592 def set_tempdir(dir = '') raise "#{dir} is not a valid directory" if dir != '' && !FileTest.directory?(dir) raise "set_tempdir must be called before add_worksheet" unless sheets.empty? @tempdir = dir 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.
The sheets() method returns a array, or a sliced array, of the worksheets in a workbook.
If no arguments are passed the method returns a list of all the worksheets in the workbook. This is useful if you want to repeat an operation on each worksheet:
workbook.sheets.each do |worksheet|
print worksheet.get_name
end
You can also specify a slice list to return one or more worksheet objects:
worksheet = workbook.sheets(0)
worksheet.write('A1', 'Hello')
you can write the above example as:
workbook.sheets(0).write('A1', 'Hello')
The following example returns the first and last worksheet in a workbook:
workbook.sheets(0, -1).each do |sheet|
# Do something
end
177 178 179 180 181 182 183 |
# File 'lib/writeexcel/workbook.rb', line 177 def sheets(*args) if args.empty? @worksheets else args.collect{|i| @worksheets[i] } end end |
#summary ⇒ Object
:nodoc:
797 798 799 |
# File 'lib/writeexcel/workbook.rb', line 797 def summary # :nodoc: @summary end |
#update_str_table(str) ⇒ Object
805 806 807 |
# File 'lib/writeexcel/workbook.rb', line 805 def update_str_table(str) @shared_string_table << str end |