|
Spreadsheet::WriteExcel(3) User Contributed Perl Documentation Spreadsheet::WriteExcel(3) NAME Spreadsheet::WriteExcel - Write to a cross-platform Excel binary file. VERSION This document refers to version 2.21 of Spreadsheet::WriteExcel, released March 9, 2007. SYNOPSIS To write a string, a formatted string, a number and a formula to the first worksheet in an Excel workbook called perl.xls: use Spreadsheet::WriteExcel; # Create a new Excel workbook my $workbook = Spreadsheet::WriteExcel->new('perl.xls'); # Add a worksheet $worksheet = $workbook->add_worksheet(); # Add and define a format $format = $workbook->add_format(); # Add a format $format->set_bold(); $format->set_color('red'); $format->set_align('center'); # Write a formatted and unformatted string, row and column notation. $col = $row = 0; $worksheet->write($row, $col, 'Hi Excel!', $format); $worksheet->write(1, $col, 'Hi Excel!'); # Write a number and a formula using A1 notation $worksheet->write('A3', 1.2345); $worksheet->write('A4', '=SIN(PI()/4)'); DESCRIPTION The Spreadsheet::WriteExcel module can be used to create a cross-platform Excel binary file. Multiple worksheets can be added to a workbook and formatting can be applied to cells. Text, numbers, formulas, hyperlinks and images can be written to the cells. The Excel file produced by this module is compatible with 97, 2000, 2002 and 2003. The module will work on the majority of Windows, UNIX and Macintosh platforms. Generated files are also compatible with the Linux/UNIX spreadsheet applications Gnumeric and OpenOffice.org. This module cannot be used to write to an existing Excel file (See "MODIFYING AND REWRIT- ING EXCEL FILES"). QUICK START Spreadsheet::WriteExcel tries to provide an interface to as many of Excel's features as possible. As a result there is a lot of documentation to accompany the interface and it can be difficult at first glance to see what it important and what is not. So for those of you who prefer to assemble Ikea furniture first and then read the instructions, here are three easy steps: 1. Create a new Excel workbook (i.e. file) using "new()". 2. Add a worksheet to the new workbook using "add_worksheet()". 3. Write to the worksheet using "write()". Like this: use Spreadsheet::WriteExcel; # Step 0 my $workbook = Spreadsheet::WriteExcel->new('perl.xls'); # Step 1 $worksheet = $workbook->add_worksheet(); # Step 2 $worksheet->write('A1', 'Hi Excel!'); # Step 3 This will create an Excel file called "perl.xls" with a single worksheet and the text 'Hi Excel!' in the relevant cell. And that's it. Okay, so there is actually a zeroth step as well, but "use module" goes without saying. There are also more than 80 examples that come with the distribution and which you can use to get you started. See EXAMPLES. Those of you who read the instructions first and assemble the furniture afterwards will know how to proceed. ;-) WORKBOOK METHODS The Spreadsheet::WriteExcel module provides an object oriented interface to a new Excel workbook. The following methods are available through a new workbook. new() close() set_tempdir() add_worksheet() add_chart_ext() add_format() set_custom_color() sheets() set_1904() set_codepage() If you are unfamiliar with object oriented interfaces or the way that they are implemented in Perl have a look at "perlobj" and "perltoot" in the main Perl documentation. new() A new Excel workbook is created using the "new()" constructor which accepts either a file- name or a filehandle as a parameter. The following example creates a new Excel file based on a filename: my $workbook = Spreadsheet::WriteExcel->new('filename.xls'); my $worksheet = $workbook->add_worksheet(); $worksheet->write(0, 0, 'Hi Excel!'); Here are some other examples of using "new()" with filenames: my $workbook1 = Spreadsheet::WriteExcel->new($filename); my $workbook2 = Spreadsheet::WriteExcel->new('/tmp/filename.xls'); my $workbook3 = Spreadsheet::WriteExcel->new("c:\\tmp\\filename.xls"); my $workbook4 = Spreadsheet::WriteExcel->new('c:\tmp\filename.xls'); The last two examples demonstrates how to create a file on DOS or Windows where it is nec- essary to either escape the directory separator "\" or to use single quotes to ensure that it isn't interpolated. For more information see "perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?". The "new()" constructor returns a Spreadsheet::WriteExcel object that you can use to add worksheets and store data. It should be noted that although "my" is not specifically required it defines the scope of the new workbook variable and, in the majority of cases, ensures that the workbook is closed properly without explicitly calling the "close()" method. If the file cannot be created, due to file permissions or some other reason, "new" will return "undef". Therefore, it is good practice to check the return value of "new" before proceeding. As usual the Perl variable $! will be set if there is a file creation error. You will also see one of the warning messages detailed in DIAGNOSTICS: my $workbook = Spreadsheet::WriteExcel->new('protected.xls'); die "Problems creating new Excel file: $!" unless defined $workbook; You can also pass a valid filehandle to the "new()" constructor. For example in a CGI pro- gram you could do something like this: binmode(STDOUT); my $workbook = Spreadsheet::WriteExcel->new(\*STDOUT); The requirement for "binmode()" is explained below. For CGI programs you can also use the special Perl filename '-' which will redirect the output to STDOUT: my $workbook = Spreadsheet::WriteExcel->new('-'); See also, the "cgi.pl" program in the "examples" directory of the distro. However, this special case will not work in "mod_perl" programs where you will have to do something like the following: # mod_perl 1 ... tie *XLS, 'Apache'; binmode(XLS); my $workbook = Spreadsheet::WriteExcel->new(\*XLS); ... # mod_perl 2 ... tie *XLS => $r; # Tie to the Apache::RequestRec object binmode(*XLS); my $workbook = Spreadsheet::WriteExcel->new(\*XLS); ... See also, the "mod_perl1.pl" and "mod_perl2.pl" programs in the "examples" directory of the distro. Filehandles can also be useful if you want to stream an Excel file over a socket or if you want to store an Excel file in a scalar. For example here is a way to write an Excel file to a scalar with "perl 5.8": #!/usr/bin/perl -w use strict; use Spreadsheet::WriteExcel; # Requires perl 5.8 or later open my $fh, '>', \my $str or die "Failed to open filehandle: $!"; my $workbook = Spreadsheet::WriteExcel->new($fh); my $worksheet = $workbook->add_worksheet(); $worksheet->write(0, 0, 'Hi Excel!'); $workbook->close(); # The Excel file in now in $str. Remember to binmode() the output # filehandle before printing it. binmode STDOUT; print $str; See also the "write_to_scalar.pl" and "filehandle.pl" programs in the "examples" directory of the distro. Note about the requirement for "binmode()": An Excel file is comprised of binary data. Therefore, if you are using a filehandle you should ensure that you "binmode()" it prior to passing it to "new()".You should do this regardless of whether you are on a Windows platform or not. This applies especially to users of perl 5.8 on systems where "UTF-8" is likely to be in operation such as RedHat Linux 9. If your program, either intentionally or not, writes "UTF-8" data to a filehandle that is passed to "new()" it will corrupt the Excel file that is created. You don't have to worry about "binmode()" if you are using filenames instead of filehan- dles. Spreadsheet::WriteExcel performs the "binmode()" internally when it converts the filename to a filehandle. For more information about "binmode()" see "perlfunc" and "per- lopentut" in the main Perl documentation. add_worksheet($sheetname, $utf_16_be) 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. On systems with "perl 5.8" and later the "add_worksheet()" method will also handle strings in "UTF-8" format. $worksheet = $workbook->add_worksheet("\x{263a}"); # Smiley On earlier Perl systems your can specify "UTF-16BE" worksheet names using an additional optional parameter: my $name = pack 'n', 0x263a; $worksheet = $workbook->add_worksheet($name, 1); # Smiley add_format(%properties) 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. add_chart_ext($chart_data, $chartname) This method is use to include externally generated charts in a Spreadsheet::WriteExcel file. my $chart = $workbook->add_chart_ext('chart01.bin', 'Chart1'); This feature is new and would be best described as experimental. Read "charts.txt" in the charts directory of the distro for a full explanation. close() In general your Excel file will be closed automatically when your program ends or when the Workbook object goes out of scope, however the "close()" method can be used to explicitly close an Excel file. $workbook->close(); 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 addition, "close()" may be required to prevent perl's garbage collector from disposing of the Workbook, Worksheet and Format objects in the wrong order. Situations where this can occur are: ? If "my()" was not used to declare the scope of a workbook variable created using "new()". ? If the "new()", "add_worksheet()" or "add_format()" methods are called in subroutines. The reason for this is that Spreadsheet::WriteExcel relies on Perl's "DESTROY" mechanism to trigger destructor methods in a specific sequence. This may not happen in cases where the Workbook, Worksheet and Format variables are not lexically scoped or where they have different lexical scopes. 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()". The return value of "close()" is the same as that returned by perl when it closes the file created by "new()". This allows you to handle error conditions in the usual way: $workbook->close() or die "Error closing file: $!"; 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. Spreadsheet::WriteExcel takes advantage of this fact to omit some records in order to min- imise 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" Spreadsheet::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, and Quickoffice on Nokia, Palm and other devices. If you encounter others, please let me know. It should be noted that "compatibility_mode()" requires additional data to be stored in memory and additonal 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()". set_tempdir() For speed and efficiency "Spreadsheet::WriteExcel" stores worksheet data in temporary files prior to assembling the final workbook. If Spreadsheet::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 pro- gram with "-w" or "use warnings". This will generate a warning if the module cannot create the required temporary files: #!/usr/bin/perl -w use Spreadsheet::WriteExcel; my $workbook = Spreadsheet::WriteExcel->new('test.xls'); my $worksheet = $workbook->add_worksheet(); To avoid this problem the "set_tempdir()" method can be used to specify a directory that is accessible for the creation of temporary files. The "File::Temp" module is used to create the temporary files. File::Temp uses "File::Spec" to determine an appropriate location for these files such as "/tmp" or "c:\windows\temp". You can find out which directory is used on your system as follows: perl -MFile::Spec -le "print File::Spec->tmpdir" 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. set_custom_color($index, $red, $green, $blue) 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 my $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: my $ferrari = $workbook->set_custom_color(40, 216, 12, 12); my $format = $workbook->add_format( bg_color => $ferrari, pattern => 1, border => 1 ); sheets(0, 1, ...) The "sheets()" method returns a list, or a sliced list, of the worksheets in a workbook. If no arguments are passed the method returns a list of all the worksheets in the work- book. This is useful if you want to repeat an operation on each worksheet: foreach $worksheet ($workbook->sheets()) { print $worksheet->get_name(); } You can also specify a slice list to return one or more worksheet objects: $worksheet = $workbook->sheets(0); $worksheet->write('A1', 'Hello'); Or since return value from "sheets()" is a reference to a worksheet object 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: foreach $worksheet ($workbook->sheets(0, -1)) { # Do something } Array slices are explained in the perldata manpage. set_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. How- ever, Excel on either platform will convert automatically between one system and the other. Spreadsheet::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 0 for 1900 and 1 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()". set_codepage($codepage) The default code page or character set used by Spreadsheet::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 Spreadsheet::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. WORKSHEET METHODS A new worksheet is created by calling the "add_worksheet()" method from a workbook object: $worksheet1 = $workbook->add_worksheet(); $worksheet2 = $workbook->add_worksheet(); The following methods are available through a new worksheet: write() write_number() write_string() write_utf16be_string() write_utf16le_string() keep_leading_zeros() write_blank() write_row() write_col() write_date_time() write_url() write_url_range() write_formula() store_formula() repeat_formula() write_comment() show_comments() add_write_handler() insert_image() embed_chart() get_name() activate() select() hide() set_first_sheet() protect() set_selection() set_row() set_column() outline_settings() freeze_panes() split_panes() merge_range() set_zoom() right_to_left() hide_zero() set_tab_color() autofilter() filter_column() Cell notation Spreadsheet::WriteExcel supports two forms of notation to designate the position of cells: Row-column notation and A1 notation. Row-column notation uses a zero based index for both row and column while A1 notation uses the standard Excel alphanumeric sequence of column letter and 1-based row. For example: (0, 0) # The top left cell in row-column notation. ('A1') # The top left cell in A1 notation. (1999, 29) # Row-column notation. ('AD2000') # The same cell in A1 notation. Row-column notation is useful if you are referring to cells programmatically: for my $i (0 .. 9) { $worksheet->write($i, 0, 'Hello'); # Cells A1 to A10 } A1 notation is useful for setting up a worksheet manually and for working with formulas: $worksheet->write('H1', 200); $worksheet->write('H2', '=H1+1'); In formulas and applicable methods you can also use the "A:A" column notation: $worksheet->write('A1', '=SUM(B:B)'); The "Spreadsheet::WriteExcel::Utility" module that is included in the distro contains helper functions for dealing with A1 notation, for example: use Spreadsheet::WriteExcel::Utility; ($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2) $str = xl_rowcol_to_cell(1, 2); # C2 For simplicity, the parameter lists for the worksheet method calls in the following sec- tions are given in terms of row-column notation. In all cases it is also possible to use A1 notation. Note: in Excel it is also possible to use a R1C1 notation. This is not supported by Spreadsheet::WriteExcel. write($row, $column, $token, $format) Excel makes a distinction between data types such as strings, numbers, blanks, formulas and hyperlinks. To simplify the process of writing data the "write()" method acts as a general alias for several more specific methods: write_string() write_number() write_blank() write_formula() write_url() write_row() write_col() The general rule is that if the data looks like a something then a something is written. Here are some examples in both row-column and A1 notation: # Same as: $worksheet->write(0, 0, 'Hello' ); # write_string() $worksheet->write(1, 0, 'One' ); # write_string() $worksheet->write(2, 0, 2 ); # write_number() $worksheet->write(3, 0, 3.00001 ); # write_number() $worksheet->write(4, 0, "" ); # write_blank() $worksheet->write(5, 0, '' ); # write_blank() $worksheet->write(6, 0, undef ); # write_blank() $worksheet->write(7, 0 ); # write_blank() $worksheet->write(8, 0, 'http://www.perl.com/'); # write_url() $worksheet->write('A9', 'ftp://ftp.cpan.org/' ); # write_url() $worksheet->write('A10', 'internal:Sheet1!A1' ); # write_url() $worksheet->write('A11', 'external:c:\foo.xls' ); # write_url() $worksheet->write('A12', '=A3 + 3*A4' ); # write_formula() $worksheet->write('A13', '=SIN(PI()/4)' ); # write_formula() $worksheet->write('A14', \@array ); # write_row() $worksheet->write('A15', [\@array] ); # write_col() # And if the keep_leading_zeros property is set: $worksheet->write('A16, 2 ); # write_number() $worksheet->write('A17, 02 ); # write_string() $worksheet->write('A18, 00002 ); # write_string() The "looks like" rule is defined by regular expressions: "write_number()" if $token is a number based on the following regex: "$token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/". "write_string()" if "keep_leading_zeros()" is set and $token is an integer with leading zeros based on the following regex: "$token =~ /^0\d+$/". "write_blank()" if $token is undef or a blank string: "undef", "" or ''. "write_url()" if $token is a http, https, ftp or mailto URL based on the following regexes: "$token =~ m|^[fh]tt?ps?://|" or "$token =~ m|^mailto:|". "write_url()" if $token is an internal or external sheet reference based on the following regex: "$token =~ m[^(in|ex)ternal:]". "write_formula()" if the first character of $token is "=". "write_row()" if $token is an array ref. "write_col()" if $token is an array ref of array refs. "write_string()" if none of the previous conditions apply. The $format parameter is optional. It should be a valid Format object, see "CELL FORMAT- TING": my $format = $workbook->add_format(); $format->set_bold(); $format->set_color('red'); $format->set_align('center'); $worksheet->write(4, 0, 'Hello', $format); # Formatted string The write() method will ignore empty strings or "undef" tokens unless a format is also supplied. As such you needn't worry about special handling for empty or "undef" values in your data. See also the "write_blank()" method. One problem with the "write()" method is that occasionally data looks like a number but you don't want it treated as a number. For example, zip codes or ID numbers often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. You can change this default behaviour by using the "keep_leading_zeros()" method. While this property is in place any integers with leading zeros will be treated as strings and the zeros will be preserved. See the "keep_leading_zeros()" section for a full discussion of this issue. You can also add your own data handlers to the "write()" method using "add_write_han- dler()". On systems with "perl 5.8" and later the "write()" method will also handle Unicode strings in "UTF-8" format. The "write" methods return: 0 for success. -1 for insufficient number of arguments. -2 for row or column out of bounds. -3 for string too long. write_number($row, $column, $number, $format) Write an integer or a float to the cell specified by $row and $column: $worksheet->write_number(0, 0, 123456); $worksheet->write_number('A2', 2.3451); See the note about "Cell notation". The $format parameter is optional. In general it is sufficient to use the "write()" method. write_string($row, $column, $string, $format) Write a string to the cell specified by $row and $column: $worksheet->write_string(0, 0, 'Your text here' ); $worksheet->write_string('A2', 'or here' ); The maximum string size is 32767 characters. However the maximum string segment that Excel can display in a cell is 1000. All 32767 characters can be displayed in the formula bar. The $format parameter is optional. On systems with "perl 5.8" and later the "write()" method will also handle strings in "UTF-8" format. With older perls you can also write Unicode in "UTF16" format via the "write_utf16be_string()" method. See also the "unicode_*.pl" programs in the examples directory of the distro. In general it is sufficient to use the "write()" method. However, you may sometimes wish to use the "write_string()" method to write data that looks like a number but that you don't want treated as a number. For example, zip codes or phone numbers: # Write as a plain string $worksheet->write_string('A1', '01209'); However, if the user edits this string Excel may convert it back to a number. To get around this you can use the Excel text format "@": # Format as a string. Doesn't change to a number when edited my $format1 = $workbook->add_format(num_format => '@'); $worksheet->write_string('A2', '01209', $format1); See also the note about "Cell notation". write_utf16be_string($row, $column, $string, $format) This method is used to write "UTF-16BE" strings to a cell in Excel. It is functionally the same as the "write_string()" method except that the string should be in "UTF-16BE" Unicode format. It is generally easier, when using Spreadsheet::WriteExcel, to write unicode strings in "UTF-8" format, see "UNICODE IN EXCEL". The "write_utf16be_string()" method is mainly of use in versions of perl prior to 5.8. The following is a simple example showing how to write some Unicode strings in "UTF-16BE" format: #!/usr/bin/perl -w use strict; use Spreadsheet::WriteExcel; use Unicode::Map(); my $workbook = Spreadsheet::WriteExcel->new('utf_16_be.xls'); my $worksheet = $workbook->add_worksheet(); # Increase the column width for clarity $worksheet->set_column('A:A', 25); # Write a Unicode character # my $smiley = pack 'n', 0x263a; # Increase the font size for legibility. my $big_font = $workbook->add_format(size => 72); $worksheet->write_utf16be_string('A3', $smiley, $big_font); # Write a phrase in Cyrillic using a hex-encoded string # my $str = pack 'H*', '042d0442043e0020044404400430043704300020043d' . '043000200440044304410441043a043e043c0021'; $worksheet->write_utf16be_string('A5', $str); # Map a string to UTF-16BE using an external module. # my $map = Unicode::Map->new('ISO-8859-1'); my $utf16 = $map->to_unicode('Hello world!'); $worksheet->write_utf16be_string('A7', $utf16); You can convert ASCII encodings to the required "UTF-16BE" format using one of the many Unicode modules on CPAN. For example "Unicode::Map" and "Unicode::String": http://search.cpan.org/author/MSCHWARTZ/Unicode-Map/Map.pm and http://search.cpan.org/author/GAAS/Unicode-String/String.pm For a full list of the Perl Unicode modules see: http://search.cpan.org/search?query=uni- code&mode=all "UTF-16BE" is the format most often returned by "Perl" modules that generate "UTF-16". To write "UTF-16" strings in little-endian format use the "write_utf16be_string_le()" method below. The "write_utf16be_string()" method was previously called "write_unicode()". That, overly general, name is still supported but deprecated. See also the "unicode_*.pl" programs in the examples directory of the distro. write_utf16le_string($row, $column, $string, $format) This method is the same as "write_utf16be()" except that the string should be 16-bit char- acters in little-endian format. This is generally referred to as "UTF-16LE". See "UNICODE IN EXCEL". "UTF-16" data can be changed from little-endian to big-endian format (and vice-versa) as follows: $utf16be = pack 'n*', unpack 'v*', $utf16le; keep_leading_zeros() This method changes the default handling of integers with leading zeros when using the "write()" method. The "write()" method uses regular expressions to determine what type of data to write to an Excel worksheet. If the data looks like a number it writes a number using "write_number()". One problem with this approach is that occasionally data looks like a number but you don't want it treated as a number. Zip codes and ID numbers, for example, often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. This is the also the default behaviour when you enter data manually in Excel. To get around this you can use one of three options. Write a formatted number, write the number as a string or use the "keep_leading_zeros()" method to change the default behaviour of "write()": # Implicitly write a number, the leading zero is removed: 1209 $worksheet->write('A1', '01209'); # Write a zero padded number using a format: 01209 my $format1 = $workbook->add_format(num_format => '00000'); $worksheet->write('A2', '01209', $format1); # Write explicitly as a string: 01209 $worksheet->write_string('A3', '01209'); # Write implicitly as a string: 01209 $worksheet->keep_leading_zeros(); $worksheet->write('A4', '01209'); The above code would generate a worksheet that looked like the following: ----------------------------------------------------------- | | A | B | C | D | ... ----------------------------------------------------------- | 1 | 1209 | | | | ... | 2 | 01209 | | | | ... | 3 | 01209 | | | | ... | 4 | 01209 | | | | ... The examples are on different sides of the cells due to the fact that Excel displays strings with a left justification and numbers with a right justification by default. You can change this by using a format to justify the data, see "CELL FORMATTING". It should be noted that if the user edits the data in examples "A3" and "A4" the strings will revert back to numbers. Again this is Excel's default behaviour. To avoid this you can use the text format "@": # Format as a string (01209) my $format2 = $workbook->add_format(num_format => '@'); $worksheet->write_string('A5', '01209', $format2); The "keep_leading_zeros()" property is off by default. The "keep_leading_zeros()" method takes 0 or 1 as an argument. It defaults to 1 if an argument isn't specified: $worksheet->keep_leading_zeros(); # Set on $worksheet->keep_leading_zeros(1); # Set on $worksheet->keep_leading_zeros(0); # Set off See also the "add_write_handler()" method. write_blank($row, $column, $format) Write a blank cell specified by $row and $column: $worksheet->write_blank(0, 0, $format); This method is used to add formatting to a cell which doesn't contain a string or number value. Excel differentiates between an "Empty" cell and a "Blank" cell. An "Empty" cell is a cell which doesn't contain data whilst a "Blank" cell is a cell which doesn't contain data but does contain formatting. Excel stores "Blank" cells but ignores "Empty" cells. As such, if you write an empty cell without formatting it is ignored: $worksheet->write('A1', undef, $format); # write_blank() $worksheet->write('A2', undef ); # Ignored This seemingly uninteresting fact means that you can write arrays of data without special treatment for undef or empty string values. See the note about "Cell notation". write_row($row, $column, $array_ref, $format) The "write_row()" method can be used to write a 1D or 2D array of data in one go. This is useful for converting the results of a database query into an Excel worksheet. You must pass a reference to the array of data rather than the array itself. The "write()" method is then called for each element of the data. For example: @array = ('awk', 'gawk', 'mawk'); $array_ref = \@array; $worksheet->write_row(0, 0, $array_ref); # The above example is equivalent to: $worksheet->write(0, 0, $array[0]); $worksheet->write(0, 1, $array[1]); $worksheet->write(0, 2, $array[2]); Note: For convenience the "write()" method behaves in the same way as "write_row()" if it is passed an array reference. Therefore the following two method calls are equivalent: $worksheet->write_row('A1', $array_ref); # Write a row of data $worksheet->write( 'A1', $array_ref); # Same thing As with all of the write methods the $format parameter is optional. If a format is speci- fied it is applied to all the elements of the data array. Array references within the data will be treated as columns. This allows you to write 2D arrays of data in one go. For example: @eec = ( ['maggie', 'milly', 'molly', 'may' ], [13, 14, 15, 16 ], ['shell', 'star', 'crab', 'stone'] ); $worksheet->write_row('A1', \@eec); Would produce a worksheet as follows: ----------------------------------------------------------- | | A | B | C | D | E | ... ----------------------------------------------------------- | 1 | maggie | 13 | shell | ... | ... | ... | 2 | milly | 14 | star | ... | ... | ... | 3 | molly | 15 | crab | ... | ... | ... | 4 | may | 16 | stone | ... | ... | ... | 5 | ... | ... | ... | ... | ... | ... | 6 | ... | ... | ... | ... | ... | ... To write the data in a row-column order refer to the "write_col()" method below. Any "undef" values in the data will be ignored unless a format is applied to the data, in which case a formatted blank cell will be written. In either case the appropriate row or column value will still be incremented. To find out more about array references refer to "perlref" and "perlreftut" in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to "perl- lol". The "write_row()" method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the "write()" method above. See also the "write_arrays.pl" program in the "examples" directory of the distro. The "write_row()" method allows the following idiomatic conversion of a text file to an Excel file: #!/usr/bin/perl -w use strict; use Spreadsheet::WriteExcel; my $workbook = Spreadsheet::WriteExcel->new('file.xls'); my $worksheet = $workbook->add_worksheet(); open INPUT, 'file.txt' or die "Couldn't open file: $!"; $worksheet->write($.-1, 0, [split]) while <INPUT>; write_col($row, $column, $array_ref, $format) The "write_col()" method can be used to write a 1D or 2D array of data in one go. This is useful for converting the results of a database query into an Excel worksheet. You must pass a reference to the array of data rather than the array itself. The "write()" method is then called for each element of the data. For example: @array = ('awk', 'gawk', 'mawk'); $array_ref = \@array; $worksheet->write_col(0, 0, $array_ref); # The above example is equivalent to: $worksheet->write(0, 0, $array[0]); $worksheet->write(1, 0, $array[1]); $worksheet->write(2, 0, $array[2]); As with all of the write methods the $format parameter is optional. If a format is speci- fied it is applied to all the elements of the data array. Array references within the data will be treated as rows. This allows you to write 2D arrays of data in one go. For example: @eec = ( ['maggie', 'milly', 'molly', 'may' ], [13, 14, 15, 16 ], ['shell', 'star', 'crab', 'stone'] ); $worksheet->write_col('A1', \@eec); Would produce a worksheet as follows: ----------------------------------------------------------- | | A | B | C | D | E | ... ----------------------------------------------------------- | 1 | maggie | milly | molly | may | ... | ... | 2 | 13 | 14 | 15 | 16 | ... | ... | 3 | shell | star | crab | stone | ... | ... | 4 | ... | ... | ... | ... | ... | ... | 5 | ... | ... | ... | ... | ... | ... | 6 | ... | ... | ... | ... | ... | ... To write the data in a column-row order refer to the "write_row()" method above. Any "undef" values in the data will be ignored unless a format is applied to the data, in which case a formatted blank cell will be written. In either case the appropriate row or column value will still be incremented. As noted above the "write()" method can be used as a synonym for "write_row()" and "write_row()" handles nested array refs as columns. Therefore, the following two method calls are equivalent although the more explicit call to "write_col()" would be preferable for maintainability: $worksheet->write_col('A1', $array_ref ); # Write a column of data $worksheet->write( 'A1', [ $array_ref ]); # Same thing To find out more about array references refer to "perlref" and "perlreftut" in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to "perl- lol". The "write_col()" method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the "write()" method above. See also the "write_arrays.pl" program in the "examples" directory of the distro. write_date_time($row, $col, $date_string, $format) The "write_date_time()" method can be used to write a date or time to the cell specified by $row and $column: $worksheet->write_date_time('A1', '2004-05-13T23:20', $date_format); The $date_string should be in the following format: yyyy-mm-ddThh:mm:ss.sss This conforms to an ISO8601 date but it should be noted that the full range of ISO8601 formats are not supported. The following variations on the $date_string parameter are permitted: yyyy-mm-ddThh:mm:ss.sss # Standard format yyyy-mm-ddT # No time Thh:mm:ss.sss # No date yyyy-mm-ddThh:mm:ss.sssZ # Additional Z (but not time zones) yyyy-mm-ddThh:mm:ss # No fractional seconds yyyy-mm-ddThh:mm # No seconds Note that the "T" is required in all cases. A date should always have a $format, otherwise it will appear as a number, see "DATES AND TIME IN EXCEL" and "CELL FORMATTING". Here is a typical example: my $date_format = $workbook->add_format(num_format => 'mm/dd/yy'); $worksheet->write_date_time('A1', '2004-05-13T23:20', $date_format); Valid dates should be in the range 1900-01-01 to 9999-12-31, for the 1900 epoch and 1904-01-01 to 9999-12-31, for the 1904 epoch. As with Excel, dates outside these ranges will be written as a string. See also the date_time.pl program in the "examples" directory of the distro. write_url($row, $col, $url, $label, $format) Write a hyperlink to a URL in the cell specified by $row and $column. The hyperlink is comprised of two elements: the visible label and the invisible link. The visible label is the same as the link unless an alternative label is specified. The parameters $label and the $format are optional and their position is interchangeable. The label is written using the "write()" method. Therefore it is possible to write strings, numbers or formulas as labels. There are four web style URI's supported: "http://", "https://", "ftp://" and "mailto:": $worksheet->write_url(0, 0, 'ftp://www.perl.org/' ); $worksheet->write_url(1, 0, 'http://www.perl.com/', 'Perl home' ); $worksheet->write_url('A3', 'http://www.perl.com/', $format ); $worksheet->write_url('A4', 'http://www.perl.com/', 'Perl', $format); $worksheet->write_url('A5', 'mailto:' ); There are two local URIs supported: "internal:" and "external:". These are used for hyper- links to internal worksheet references or external workbook and worksheet references: $worksheet->write_url('A6', 'internal:Sheet2!A1' ); $worksheet->write_url('A7', 'internal:Sheet2!A1', $format ); $worksheet->write_url('A8', 'internal:Sheet2!A1:B2' ); $worksheet->write_url('A9', q{internal:'Sales Data'!A1} ); $worksheet->write_url('A10', 'external:c:\temp\foo.xls' ); $worksheet->write_url('A11', 'external:c:\temp\foo.xls#Sheet2!A1' ); $worksheet->write_url('A12', 'external:..\..\..\foo.xls' ); $worksheet->write_url('A13', 'external:..\..\..\foo.xls#Sheet2!A1' ); $worksheet->write_url('A13', 'external:\\\\NETWORK\share\foo.xls' ); All of the these URI types are recognised by the "write()" method, see above. Worksheet references are typically of the form "Sheet1!A1". You can also refer to a work- sheet range using the standard Excel notation: "Sheet1!A1:B2". In external links the workbook and worksheet name must be separated by the "#" character: "external:Workbook.xls#Sheet1!A1'". You can also link to a named range in the target worksheet. For example say you have a named range called "my_name" in the workbook "c:\temp\foo.xls" you could link to it as follows: $worksheet->write_url('A14', 'external:c:\temp\foo.xls#my_name'); Note, you cannot currently create named ranges with "Spreadsheet::WriteExcel". Excel requires that worksheet names containing spaces or non alphanumeric characters are single quoted as follows "'Sales Data'!A1". If you need to do this in a single quoted string then you can either escape the single quotes "\'" or use the quote operator "q{}" as described in "perlop" in the main Perl documentation. Links to network files are also supported. MS/Novell Network files normally begin with two back slashes as follows "\\NETWORK\etc". In order to generate this in a single or double quoted string you will have to escape the backslashes, '\\\\NETWORK\etc'. If you are using double quote strings then you should be careful to escape anything that looks like a metacharacter. For more information see "perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?". Finally, you can avoid most of these quoting problems by using forward slashes. These are translated internally to backslashes: $worksheet->write_url('A14', "external:c:/temp/foo.xls" ); $worksheet->write_url('A15', 'external://NETWORK/share/foo.xls' ); See also, the note about "Cell notation". write_url_range($row1, $col1, $row2, $col2, $url, $string, $format) This method is essentially the same as the "write_url()" method described above. The main difference is that you can specify a link for a range of cells: $worksheet->write_url(0, 0, 0, 3, 'ftp://www.perl.org/' ); $worksheet->write_url(1, 0, 0, 3, 'http://www.perl.com/', 'Perl home'); $worksheet->write_url('A3:D3', 'internal:Sheet2!A1' ); $worksheet->write_url('A4:D4', 'external:c:\temp\foo.xls' ); This method is generally only required when used in conjunction with merged cells. See the "merge_range()" method and the "merge" property of a Format object, "CELL FORMATTING". There is no way to force this behaviour through the "write()" method. The parameters $string and the $format are optional and their position is interchangeable. However, they are applied only to the first cell in the range. See also, the note about "Cell notation". write_formula($row, $column, $formula, $format, $value) Write a formula or function to the cell specified by $row and $column: $worksheet->write_formula(0, 0, '=$B$3 + B4' ); $worksheet->write_formula(1, 0, '=SIN(PI()/4)'); $worksheet->write_formula(2, 0, '=SUM(B1:B5)' ); $worksheet->write_formula('A4', '=IF(A3>1,"Yes", "No")' ); $worksheet->write_formula('A5', '=AVERAGE(1, 2, 3, 4)' ); $worksheet->write_formula('A6', '=DATEVALUE("1-Jan-2001")'); See the note about "Cell notation". For more information about writing Excel formulas see "FORMULAS AND FUNCTIONS IN EXCEL" See also the section "Improving performance when working with formulas" and the "store_formula()" and "repeat_formula()" methods. If required, it is also possible to specify the calculated value of the formula. This is occasionally necessary when working with non-Excel applications that don't calculated the value of the formula. The calculated $value is added at the end of the argument list: $worksheet->write('A1', '=2+2', $format, 4); However, this probably isn't something that will ever need to do. If you do use this fea- ture then do so with care. store_formula($formula) The "store_formula()" method is used in conjunction with "repeat_formula()" to speed up the generation of repeated formulas. See "Improving performance when working with formu- las" in "FORMULAS AND FUNCTIONS IN EXCEL". The "store_formula()" method pre-parses a textual representation of a formula and stores it for use at a later stage by the "repeat_formula()" method. "store_formula()" carries the same speed penalty as "write_formula()". However, in prac- tice it will be used less frequently. The return value of this method is a scalar that can be thought of as a reference to a formula. my $sin = $worksheet->store_formula('=SIN(A1)'); my $cos = $worksheet->store_formula('=COS(A1)'); $worksheet->repeat_formula('B1', $sin, $format, 'A1', 'A2'); $worksheet->repeat_formula('C1', $cos, $format, 'A1', 'A2'); Although "store_formula()" is a worksheet method the return value can be used in any work- sheet: my $now = $worksheet->store_formula('=NOW()'); $worksheet1->repeat_formula('B1', $now); $worksheet2->repeat_formula('B1', $now); $worksheet3->repeat_formula('B1', $now); repeat_formula($row, $col, $formula, $format, ($pattern => $replace, ...)) The "repeat_formula()" method is used in conjunction with "store_formula()" to speed up the generation of repeated formulas. See "Improving performance when working with formu- las" in "FORMULAS AND FUNCTIONS IN EXCEL". In many respects "repeat_formula()" behaves like "write_formula()" except that it is sig- nificantly faster. The "repeat_formula()" method creates a new formula based on the pre-parsed tokens returned by "store_formula()". The new formula is generated by substituting $pattern, $replace pairs in the stored formula: my $formula = $worksheet->store_formula('=A1 * 3 + 50'); for my $row (0..99) { $worksheet->repeat_formula($row, 1, $formula, $format, 'A1', 'A'.($row +1)); } It should be noted that "repeat_formula()" doesn't modify the tokens. In the above example the substitution is always made against the original token, "A1", which doesn't change. As usual, you can use "undef" if you don't wish to specify a $format: $worksheet->repeat_formula('B2', $formula, $format, 'A1', 'A2'); $worksheet->repeat_formula('B3', $formula, undef, 'A1', 'A3'); The substitutions are made from left to right and you can use as many $pattern, $replace pairs as you need. However, each substitution is made only once: my $formula = $worksheet->store_formula('=A1 + A1'); # Gives '=B1 + A1' $worksheet->repeat_formula('B1', $formula, undef, 'A1', 'B1'); # Gives '=B1 + B1' $worksheet->repeat_formula('B2', $formula, undef, ('A1', 'B1') x 2); Since the $pattern is interpolated each time that it is used it is worth using the "qr" operator to quote the pattern. The "qr" operator is explained in the "perlop" man page. $worksheet->repeat_formula('B1', $formula, $format, qr/A1/, 'A2'); Care should be taken with the values that are substituted. The formula returned by "repeat_formula()" contains several other tokens in addition to those in the formula and these might also match the pattern that you are trying to replace. In particular you should avoid substituting a single 0, 1, 2 or 3. You should also be careful to avoid false matches. For example the following snippet is meant to change the stored formula in steps from "=A1 + SIN(A1)" to "=A10 + SIN(A10)". my $formula = $worksheet->store_formula('=A1 + SIN(A1)'); for my $row (1 .. 10) { $worksheet->repeat_formula($row -1, 1, $formula, undef, qw/A1/, 'A' . $row, #! Bad. qw/A1/, 'A' . $row #! Bad. ); } However it contains a bug. In the last iteration of the loop when $row is 10 the following substitutions will occur: s/A1/A10/; changes =A1 + SIN(A1) to =A10 + SIN(A1) s/A1/A10/; changes =A10 + SIN(A1) to =A100 + SIN(A1) # !! The solution in this case is to use a more explicit match such as "qw/^A1$/": $worksheet->repeat_formula($row -1, 1, $formula, undef, qw/^A1$/, 'A' . $row, qw/^A1$/, 'A' . $row ); Another similar problem occurs due to the fact that substitutions are made in order. For example the following snippet is meant to change the stored formula from "=A10 + A11" to "=A11 + A12": my $formula = $worksheet->store_formula('=A10 + A11'); $worksheet->repeat_formula('A1', $formula, undef, qw/A10/, 'A11', #! Bad. qw/A11/, 'A12' #! Bad. ); However, the actual substitution yields "=A12 + A11": s/A10/A11/; changes =A10 + A11 to =A11 + A11 s/A11/A12/; changes =A11 + A11 to =A12 + A11 # !! The solution here would be to reverse the order of the substitutions or to start with a stored formula that won't yield a false match such as "=X10 + Y11": my $formula = $worksheet->store_formula('=X10 + Y11'); $worksheet->repeat_formula('A1', $formula, undef, qw/X10/, 'A11', qw/Y11/, 'A12' ); If you think that you have a problem related to a false match you can check the tokens that you are substituting against as follows. my $formula = $worksheet->store_formula('=A1*5+4'); print "@$formula\n"; See also the "repeat.pl" program in the "examples" directory of the distro. write_comment($row, $column, $string, ...) The "write_comment()" method is used to add a comment to a cell. A cell comment is indi- cated in Excel by a small red triangle in the upper right-hand corner of the cell. Moving the cursor over the red triangle will reveal the comment. The following example shows how to add a comment to a cell: $worksheet->write (2, 2, 'Hello'); $worksheet->write_comment(2, 2, 'This is a comment.'); As usual you can replace the $row and $column parameters with an "A1" cell reference. See the note about "Cell notation". $worksheet->write ('C3', 'Hello'); $worksheet->write_comment('C3', 'This is a comment.'); On systems with "perl 5.8" and later the "write_comment()" method will also handle strings in "UTF-8" format. $worksheet->write_comment('C3', "\x{263a}"); # Smiley $worksheet->write_comment('C4', 'Comment ca va?'); In addition to the basic 3 argument form of "write_comment()" you can pass in several optional key/value pairs to control the format of the comment. For example: $worksheet->write_comment('C3', 'Hello', visible => 1, author => 'Perl'); Most of these options are quite specific and in general the default comment behaviour will be all that you need. However, should you need greater control over the format of the cell comment the following options are available: encoding author author_encoding visible x_scale width y_scale height color start_cell start_row start_col x_offset y_offset Option: encoding This option is used to indicate that the comment string is encoded as "UTF-16BE". my $comment = pack 'n', 0x263a; # UTF-16BE Smiley symbol $worksheet->write_comment('C3', $comment, encoding => 1); If you wish to use Unicode characters in the comment string then the preferred method is to use perl 5.8 and "UTF-8" strings, see "UNICODE IN EXCEL". Option: author This option is used to indicate who the author of the comment is. Excel displays the author of the comment in the status bar at the bottom of the worksheet. This is usu- ally of interest in corporate environments where several people might review and pro- vide comments to a workbook. $worksheet->write_comment('C3', 'Atonement', author => 'Ian McEwan'); Option: author_encoding This option is used to indicate that the author string is encoded as "UTF-16BE". Option: visible This option is used to make a cell comment visible when the worksheet is opened. The default behaviour in Excel is that comments are initially hidden. However, it is also possible in Excel to make individual or all comments visible. In Spreadsheet::WriteEx- cel individual comments can be made visible as follows: $worksheet->write_comment('C3', 'Hello', visible => 1); It is possible to make all comments in a worksheet visible using the "show_comments()" worksheet method (see below). Alternatively, if all of the cell comments have been made visible you can hide individual comments: $worksheet->write_comment('C3', 'Hello', visible => 0); Option: x_scale This option is used to set the width of the cell comment box as a factor of the default width. $worksheet->write_comment('C3', 'Hello', x_scale => 2); $worksheet->write_comment('C4', 'Hello', x_scale => 4.2); Option: width This option is used to set the width of the cell comment box explicitly in pixels. $worksheet->write_comment('C3', 'Hello', width => 200); Option: y_scale This option is used to set the height of the cell comment box as a factor of the default height. $worksheet->write_comment('C3', 'Hello', y_scale => 2); $worksheet->write_comment('C4', 'Hello', y_scale => 4.2); Option: height This option is used to set the height of the cell comment box explicitly in pixels. $worksheet->write_comment('C3', 'Hello', height => 200); Option: color This option is used to set the background colour of cell comment box. You can use one of the named colours recognised by Spreadsheet::WriteExcel or a colour index. See "COLOURS IN EXCEL". $worksheet->write_comment('C3', 'Hello', color => 'green'); $worksheet->write_comment('C4', 'Hello', color => 0x35); # Orange Option: start_cell This option is used to set the cell in which the comment will appear. By default Excel displays comments one cell to the right and one cell above the cell to which the com- ment relates. However, you can change this behaviour if you wish. In the following example the comment which would appear by default in cell "D2" is moved to "E2". $worksheet->write_comment('C3', 'Hello', start_cell => 'E2'); Option: start_row This option is used to set the row in which the comment will appear. See the "start_cell" option above. The row is zero indexed. $worksheet->write_comment('C3', 'Hello', start_row => 0); Option: start_col This option is used to set the column in which the comment will appear. See the "start_cell" option above. The column is zero indexed. $worksheet->write_comment('C3', 'Hello', start_col => 4); Option: x_offset This option is used to change the x offset, in pixels, of a comment within a cell: $worksheet->write_comment('C3', $comment, x_offset => 30); Option: y_offset This option is used to change the y offset, in pixels, of a comment within a cell: $worksheet->write_comment('C3', $comment, x_offset => 30); You can apply as many of these options as you require. Note about row height and comments. If you specify the height of a row that contains a comment then Spreadsheet::WriteExcel will adjust the height of the comment to maintain the default or user specified dimensions. However, the height of a row can also be adjusted automatically by Excel if the text wrap property is set or large fonts are used in the cell. This means that the height of the row is unknown to WriteExcel at run time and thus the comment box is stretched with the row. Use the "set_row()" method to specify the row height explicitly and avoid this problem. show_comments() This method is used to make all cell comments visible when a worksheet is opened. Individual comments can be made visible using the "visible" parameter of the "write_com- ment" method (see above): $worksheet->write_comment('C3', 'Hello', visible => 1); If all of the cell comments have been made visible you can hide individual comments as follows: $worksheet->write_comment('C3', 'Hello', visible => 0); add_write_handler($re, $code_ref) This method is used to extend the Spreadsheet::WriteExcel write() method to handle user defined data. If you refer to the section on "write()" above you will see that it acts as an alias for several more specific "write_*" methods. However, it doesn't always act in exactly the way that you would like it to. One solution is to filter the input data yourself and call the appropriate "write_*" method. Another approach is to use the "add_write_handler()" method to add your own auto- mated behaviour to "write()". The "add_write_handler()" method take two arguments, $re, a regular expression to match incoming data and $code_ref a callback function to handle the matched data: $worksheet->add_write_handler(qr/^\d\d\d\d$/, \&my_write); (In the these examples the "qr" operator is used to quote the regular expression strings, see perlop for more details). The method is used as follows. say you wished to write 7 digit ID numbers as a string so that any leading zeros were preserved*, you could do something like the following: $worksheet->add_write_handler(qr/^\d{7}$/, \&write_my_id); sub write_my_id { my $worksheet = shift; return $worksheet->write_string(@_); } * You could also use the "keep_leading_zeros()" method for this. Then if you call "write()" with an appropriate string it will be handled automatically: # Writes 0000000. It would normally be written as a number; 0. $worksheet->write('A1', '0000000'); The callback function will receive a reference to the calling worksheet and all of the other arguments that were passed to "write()". The callback will see an @_ argument list that looks like the following: $_[0] A ref to the calling worksheet. * $_[1] Zero based row number. $_[2] Zero based column number. $_[3] A number or string or token. $_[4] A format ref if any. $_[5] Any other arguments. ... * It is good style to shift this off the list so the @_ is the same as the argument list seen by write(). Your callback should "return()" the return value of the "write_*" method that was called or "undef" to indicate that you rejected the match and want "write()" to continue as nor- mal. So for example if you wished to apply the previous filter only to ID values that occur in the first column you could modify your callback function as follows: sub write_my_id { my $worksheet = shift; my $col = $_[1]; if ($col == 0) { return $worksheet->write_string(@_); } else { # Reject the match and return control to write() return undef; } } Now, you will get different behaviour for the first column and other columns: $worksheet->write('A1', '0000000'); # Writes 0000000 $worksheet->write('B1', '0000000'); # Writes 0 You may add more than one handler in which case they will be called in the order that they were added. Note, the "add_write_handler()" method is particularly suited for handling dates. See the "write_handler 1-4" programs in the "examples" directory for further examples. insert_image($row, $col, $filename, $x, $y, $scale_x, $scale_y) This method can be used to insert a image into a worksheet. The image can be in PNG or BMP format. The $x, $y, $scale_x and $scale_y parameters are optional. $worksheet1->insert_image('A1', 'perl.bmp'); $worksheet2->insert_image('A1', '../images/perl.bmp'); $worksheet3->insert_image('A1', '.c:\images\perl.bmp'); The parameters $x and $y can be used to specify an offset from the top left hand corner of the cell specified by $row and $col. The offset values are in pixels. $worksheet1->insert_image('A1', 'perl.bmp', 32, 10); The default width of a cell is 63 pixels. The default height of a cell is 17 pixels. The pixels offsets can be calculated using the following relationships: Wp = int(12We) if We < 1 Wp = int(7We +5) if We >= 1 Hp = int(4/3He) where: We is the cell width in Excels units Wp is width in pixels He is the cell height in Excels units Hp is height in pixels The offsets can be greater than the width or height of the underlying cell. This can be occasionally useful if you wish to align two or more images relative to the same cell. The parameters $scale_x and $scale_y can be used to scale the inserted image horizontally and vertically: # Scale the inserted image: width x 2.0, height x 0.8 $worksheet->insert_image('A1', 'perl.bmp', 0, 0, 2, 0.8); See also the "images.pl" program in the "examples" directory of the distro. Note: you must call "set_row()" or "set_column()" before "insert_image()" if you wish to change the default dimensions of any of the rows or columns that the image occupies. The height of a row can also change if you use a font that is larger than the default. This in turn will affect the scaling of your image. To avoid this you should explicitly set the height of the row using "set_row()" if it contains a font size that will change the row height. BMP images must be 24 bit, true colour, bitmaps. In general it is best to avoid BMP images since they aren't compressed. The older "insert_bitmap()" method is still supported but deprecated. embed_chart($row, $col, $filename, $x, $y, $scale_x, $scale_y) This method can be used to insert a chart into a worksheet. The chart must first be extracted from an existing Excel file. See the separate "Charts" documentation. Here is an example: $worksheet->embed_chart('B2', 'sales_chart.bin'); The $x, $y, $scale_x and $scale_y parameters are optional. The parameters $x and $y can be used to specify an offset from the top left hand corner of the cell specified by $row and $col. The offset values are in pixels. See the "insert_image" method above for more information on sizes. $worksheet1->embed_chart('B2', 'sales_chart.bin', 3, 3); The parameters $scale_x and $scale_y can be used to scale the inserted image horizontally and vertically: # Scale the width by 120% and the height by 150% $worksheet->embed_chart('B2', 'sales_chart.bin', 0, 0, 1.2, 1.5); The easiest way to calculate the required scaling is to create a test chart worksheet with Spreadsheet::WriteExcel. Then open the file, select the chart and drag the corner to get the required size. While holding down the mouse the scale of the resized chart is shown to the left of the formula bar. See also the example programs in the "charts" directory of the distro. Note: you must call "set_row()" or "set_column()" before "embed_chart()" if you wish to change the default dimensions of any of the rows or columns that the chart occupies. The height of a row can also change if you use a font that is larger than the default. This in turn will affect the scaling of your chart. To avoid this you should explicitly set the height of the row using "set_row()" if it contains a font size that will change the row height. get_name() The "get_name()" method is used to retrieve the name of a worksheet. For example: foreach my $sheet ($workbook->sheets()) { print $sheet->get_name(); } For reasons related to the design of Spreadsheet::WriteExcel and to the internals of Excel there is no "set_name()" method. The only way to set the worksheet name is via the "add_worksheet()" method. activate() The "activate()" method is used to specify which worksheet is initially visible in a multi-sheet workbook: $worksheet1 = $workbook->add_worksheet('To'); $worksheet2 = $workbook->add_worksheet('the'); $worksheet3 = $workbook->add_worksheet('wind'); $worksheet3->activate(); This is similar to the Excel VBA activate method. More than one worksheet can be selected via the "select()" method, see below, however only one worksheet can be active. The default active worksheet is the first worksheet. select() The "select()" method is used to indicate that a worksheet is selected in a multi-sheet workbook: $worksheet1->activate(); $worksheet2->select(); $worksheet3->select(); A selected worksheet has its tab highlighted. Selecting worksheets is a way of grouping them together so that, for example, several worksheets could be printed in one go. A work- sheet that has been activated via the "activate()" method will also appear as selected. hide() The "hide()" method is used to hide a worksheet: $worksheet2->hide(); You may wish to hide a worksheet in order to avoid confusing a user with intermediate data or calculations. A hidden worksheet can not be activated or selected so this method is mutually exclusive with the "activate()" and "select()" methods. In addition, since the first worksheet will default to being the active worksheet, you cannot hide the first worksheet without acti- vating another sheet: $worksheet2->activate(); $worksheet1->hide(); set_first_sheet() The "activate()" method determines which worksheet is initially selected. However, if there are a large number of worksheets the selected worksheet may not appear on the screen. To avoid this you can select which is the leftmost visible worksheet using "set_first_sheet()": for (1..20) { $workbook->add_worksheet; } $worksheet21 = $workbook->add_worksheet(); $worksheet22 = $workbook->add_worksheet(); $worksheet21->set_first_sheet(); $worksheet22->activate(); This method is not required very often. The default value is the first worksheet. protect($password) The "protect()" method is used to protect a worksheet from modification: $worksheet->protect(); It can be turned off in Excel via the "Tools->Protection->Unprotect Sheet" menu command. The "protect()" method also has the effect of enabling a cell's "locked" and "hidden" properties if they have been set. A "locked" cell cannot be edited. A "hidden" cell will display the results of a formula but not the formula itself. In Excel a cell's locked property is on by default. # Set some format properties my $unlocked = $workbook->add_format(locked => 0); my $hidden = $workbook->add_format(hidden => 1); # Enable worksheet protection $worksheet->protect(); # This cell cannot be edited, it is locked by default $worksheet->write('A1', '=1+2'); # This cell can be edited $worksheet->write('A2', '=1+2', $unlocked); # The formula in this cell isn't visible $worksheet->write('A3', '=1+2', $hidden); See also the "set_locked" and "set_hidden" format methods in "CELL FORMATTING". You can optionally add a password to the worksheet protection: $worksheet->protect('drowssap'); Note, the worksheet level password in Excel provides very weak protection. It does not encrypt your data in any way and it is very easy to deactivate. Therefore, do not use the above method if you wish to protect sensitive data or calculations. However, before you get worried, Excel's own workbook level password protection does provide strong encryption in Excel 97+. For technical reasons this will never be supported by "Spreadsheet::WriteEx- cel". set_selection($first_row, $first_col, $last_row, $last_col) This method can be used to specify which cell or cells are selected in a worksheet. The most common requirement is to select a single cell, in which case $last_row and $last_col can be omitted. The active cell within a selected range is determined by the order in which $first and $last are specified. It is also possible to specify a cell or a range using A1 notation. See the note about "Cell notation". Examples: $worksheet1->set_selection(3, 3); # 1. Cell D4. $worksheet2->set_selection(3, 3, 6, 6); # 2. Cells D4 to G7. $worksheet3->set_selection(6, 6, 3, 3); # 3. Cells G7 to D4. $worksheet4->set_selection('D4'); # Same as 1. $worksheet5->set_selection('D4:G7'); # Same as 2. $worksheet6->set_selection('G7:D4'); # Same as 3. The default cell selections is (0, 0), 'A1'. set_row($row, $height, $format, $hidden, $level, $collapsed) This method can be used to change the default properties of a row. All parameters apart from $row are optional. The most common use for this method is to change the height of a row: $worksheet->set_row(0, 20); # Row 1 height set to 20 If you wish to set the format without changing the height you can pass "undef" as the height parameter: $worksheet->set_row(0, undef, $format); The $format parameter will be applied to any cells in the row that don't have a format. For example $worksheet->set_row(0, undef, $format1); # Set the format for row 1 $worksheet->write('A1', 'Hello'); # Defaults to $format1 $worksheet->write('B1', 'Hello', $format2); # Keeps $format2 If you wish to define a row format in this way you should call the method before any calls to "write()". Calling it afterwards will overwrite any format that was previously speci- fied. The $hidden parameter should be set to 1 if you wish to hide a row. This can be used, for example, to hide intermediary steps in a complicated calculation: $worksheet->set_row(0, 20, $format, 1); $worksheet->set_row(1, undef, undef, 1); The $level parameter is used to set the outline level of the row. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent rows with the same outline level are grouped together into a single outline. The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed): $worksheet->set_row(1, undef, undef, 0, 1); $worksheet->set_row(2, undef, undef, 0, 1); The $hidden parameter can also be used to hide collapsed outlined rows when used in con- junction with the $level parameter. $worksheet->set_row(1, undef, undef, 1, 1); $worksheet->set_row(2, undef, undef, 1, 1); For collapsed outlines you should also indicate which row has the collapsed "+" symbol using the optional $collapsed parameter. $worksheet->set_row(3, undef, undef, 0, 0, 1); For a more complete example see the "outline.pl" and "outline_collapsed.pl" programs in the examples directory of the distro. Excel allows up to 7 outline levels. Therefore the $level parameter should be in the range "0 <= $level <= 7". set_column($first_col, $last_col, $width, $format, $hidden, $level, $collapsed) This method can be used to change the default properties of a single column or a range of columns. All parameters apart from $first_col and $last_col are optional. If "set_column()" is applied to a single column the value of $first_col and $last_col should be the same. In the case where $last_col is zero it is set to the same value as $first_col. It is also possible, and generally clearer, to specify a column range using the form of A1 notation used for columns. See the note about "Cell notation". Examples: $worksheet->set_column(0, 0, 20); # Column A width set to 20 $worksheet->set_column(1, 3, 30); # Columns B-D width set to 30 $worksheet->set_column('E:E', 20); # Column E width set to 20 $worksheet->set_column('F:H', 30); # Columns F-H width set to 30 The width corresponds to the column width value that is specified in Excel. It is approxi- mately equal to the length of a string in the default font of Arial 10. Unfortunately, there is no way to specify "AutoFit" for a column in the Excel file format. This feature is only available at runtime from within Excel. As usual the $format parameter is optional, for additional information, see "CELL FORMAT- TING". If you wish to set the format without changing the width you can pass "undef" as the width parameter: $worksheet->set_column(0, 0, undef, $format); The $format parameter will be applied to any cells in the column that don't have a for- mat. For example $worksheet->set_column('A:A', undef, $format1); # Set format for col 1 $worksheet->write('A1', 'Hello'); # Defaults to $format1 $worksheet->write('A2', 'Hello', $format2); # Keeps $format2 If you wish to define a column format in this way you should call the method before any calls to "write()". If you call it afterwards it won't have any effect. A default row format takes precedence over a default column format $worksheet->set_row(0, undef, $format1); # Set format for row 1 $worksheet->set_column('A:A', undef, $format2); # Set format for col 1 $worksheet->write('A1', 'Hello'); # Defaults to $format1 $worksheet->write('A2', 'Hello'); # Defaults to $format2 The $hidden parameter should be set to 1 if you wish to hide a column. This can be used, for example, to hide intermediary steps in a complicated calculation: $worksheet->set_column('D:D', 20, $format, 1); $worksheet->set_column('E:E', undef, undef, 1); The $level parameter is used to set the outline level of the column. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent columns with the same outline level are grouped together into a single outline. The following example sets an outline level of 1 for columns B to G: $worksheet->set_column('B:G', undef, undef, 0, 1); The $hidden parameter can also be used to hide collapsed outlined columns when used in conjunction with the $level parameter. $worksheet->set_column('B:G', undef, undef, 1, 1); For collapsed outlines you should also indicate which row has the collapsed "+" symbol using the optional $collapsed parameter. $worksheet->set_column('H:H', undef, undef, 0, 0, 1); For a more complete example see the "outline.pl" and "outline_collapsed.pl" programs in the examples directory of the distro. Excel allows up to 7 outline levels. Therefore the $level parameter should be in the range "0 <= $level <= 7". outline_settings($visible, $symbols_below, $symbols_right, $auto_style) The "outline_settings()" method is used to control the appearance of outlines in Excel. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". The $visible parameter is used to control whether or not outlines are visible. Setting this parameter to 0 will cause all outlines on the worksheet to be hidden. They can be unhidden in Excel by means of the "Show Outline Symbols" command button. The default set- ting is 1 for visible outlines. $worksheet->outline_settings(0); The $symbols_below parameter is used to control whether the row outline symbol will appear above or below the outline level bar. The default setting is 1 for symbols to appear below the outline level bar. The "symbols_right" parameter is used to control whether the column outline symbol will appear to the left or the right of the outline level bar. The default setting is 1 for symbols to appear to the right of the outline level bar. The $auto_style parameter is used to control whether the automatic outline generator in Excel uses automatic styles when creating an outline. This has no effect on a file gener- ated by "Spreadsheet::WriteExcel" but it does have an effect on how the worksheet behaves after it is created. The default setting is 0 for "Automatic Styles" to be turned off. The default settings for all of these parameters correspond to Excel's default parameters. The worksheet parameters controlled by "outline_settings()" are rarely used. freeze_panes($row, $col, $top_row, $left_col) This method can be used to divide a worksheet into horizontal or vertical regions known as panes and to also "freeze" these panes so that the splitter bars are not visible. This is the same as the "Window->Freeze Panes" menu command in Excel The parameters $row and $col are used to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. Therefore to freeze the first row of a worksheet it is necessary to specify the split at row 2 (which is 1 as the zero-based index). This might lead you to think that you are using a 1 based index but this is not the case. You can set one of the $row and $col parameters as zero if you do not want either a verti- cal or horizontal split. Examples: $worksheet->freeze_panes(1, 0); # Freeze the first row $worksheet->freeze_panes('A2'); # Same using A1 notation $worksheet->freeze_panes(0, 1); # Freeze the first column $worksheet->freeze_panes('B1'); # Same using A1 notation $worksheet->freeze_panes(1, 2); # Freeze first row and first 2 columns $worksheet->freeze_panes('C2'); # Same using A1 notation The parameters $top_row and $left_col are optional. They are used to specify the top-most or left-most visible row or column in the scrolling region of the panes. For example to freeze the first row and to have the scrolling region begin at row twenty: $worksheet->freeze_panes(1, 0, 20, 0); You cannot use A1 notation for the $top_row and $left_col parameters. See also the "panes.pl" program in the "examples" directory of the distribution. split_panes($y, $x, $top_row, $left_col) This method can be used to divide a worksheet into horizontal or vertical regions known as panes. This method is different from the "freeze_panes()" method in that the splits between the panes will be visible to the user and each pane will have its own scroll bars. The parameters $y and $x are used to specify the vertical and horizontal position of the split. The units for $y and $x are the same as those used by Excel to specify row height and column width. However, the vertical and horizontal units are different from each other. Therefore you must specify the $y and $x parameters in terms of the row heights and column widths that you have set or the default values which are 12.75 for a row and 8.43 for a column. You can set one of the $y and $x parameters as zero if you do not want either a vertical or horizontal split. The parameters $top_row and $left_col are optional. They are used to specify the top-most or left-most visible row or column in the bottom-right pane. Example: $worksheet->split_panes(12.75, 0, 1, 0); # First row $worksheet->split_panes(0, 8.43, 0, 1); # First column $worksheet->split_panes(12.75, 8.43, 1, 1); # First row and column You cannot use A1 notation with this method. See also the "freeze_panes()" method and the "panes.pl" program in the "examples" direc- tory of the distribution. Note: This "split_panes()" method was called "thaw_panes()" in older versions. The older name is still available for backwards compatiblity. merge_range($first_row, $first_col, $last_row, $last_col, $token, $format, $utf_16_be) Merging cells can be achieved by setting the "merge" property of a Format object, see "CELL FORMATTING". However, this only allows simple Excel5 style horizontal merging which Excel refers to as "center across selection". The "merge_range()" method allows you to do Excel97+ style formatting where the cells can contain other types of alignment in addition to the merging: my $format = $workbook->add_format( border => 6, valign => 'vcenter', align => 'center', ); $worksheet->merge_range('B3:D4', 'Vertical and horizontal', $format); WARNING. The format object that is used with a "merge_range()" method call is marked internally as being associated with a merged range. It is a fatal error to use a merged format in a non-merged cell. Instead you should use separate formats for merged and non- merged cells. This restriction will be removed in a future release. The $utf_16_be parameter is optional, see below. "merge_range()" writes its $token argument using the worksheet "write()" method. Therefore it will handle numbers, strings, formulas or urls as required. Setting the "merge" property of the format isn't required when you are using "merge_range()". In fact using it will exclude the use of any other horizontal alignment option. On systems with "perl 5.8" and later the "merge_range()" method will also handle strings in "UTF-8" format. $worksheet->merge_range('B3:D4', "\x{263a}", $format); # Smiley On earlier Perl systems your can specify "UTF-16BE" worksheet names using an additional optional parameter: my $str = pack 'n', 0x263a; $worksheet->merge_range('B3:D4', $str, $format, 1); # Smiley The full possibilities of this method are shown in the "merge3.pl" to "merge6.pl" programs in the "examples" directory of the distribution. set_zoom($scale) Set the worksheet zoom factor in the range "10 <= $scale <= 400": $worksheet1->set_zoom(50); $worksheet2->set_zoom(75); $worksheet3->set_zoom(300); $worksheet4->set_zoom(400); The default zoom factor is 100. You cannot zoom to "Selection" because it is calculated by Excel at run-time. Note, "set_zoom()" does not affect the scale of the printed page. For that you should use "set_print_scale()". right_to_left() The "right_to_left()" method is used to change the default direction of the worksheet from left-to-right, with the A1 cell in the top left, to right-to-left, with the he A1 cell in the top right. $worksheet->right_to_left(); This is useful when creating Arabic, Hebrew or other near or far eastern worksheets that use right-to-left as the default direction. hide_zero() The "hide_zero()" method is used to hide any zero values that appear in cells. $worksheet->hide_zero(); In Excel this option is found under Tools->Options->View. set_tab_color() The "set_tab_color()" method is used to change the colour of the worksheet tab. This fea- ture is only available in Excel 2002 and later. You can use one of the standard colour names provided by the Format object or a colour index. See "COLOURS IN EXCEL" and the "set_custom_color()" method. $worksheet1->set_tab_color('red'); $worksheet2->set_tab_color(0x0C); See the "tab_colors.pl" program in the examples directory of the distro. autofilter($first_row, $first_col, $last_row, $last_col) This method allows an autofilter to be added to a worksheet. An autofilter is a way of adding drop down lists to the headers of a 2D range of worksheet data. This is turn allow users to filter the data based on simple criteria so that some data is highlighted and some is hidden. To add an autofilter to a worksheet: $worksheet->autofilter(0, 0, 10, 3); $worksheet->autofilter('A1:D11'); # Same as above in A1 notation. Filter conditions can be applied using the "filter_column()" method. See the "autofilter.pl" program in the examples directory of the distro for a more detailed example. filter_column($column, $expression) The "filter_column" method can be used to filter columns in a autofilter range based on simple conditions. NOTE: It isn't sufficient to just specify the filter condition. You must also hide any rows that don't match the filter condition. Rows are hidden using the "set_row()" "visi- ble" parameter. "Spreadsheet::WriteExcel" cannot do this automatically since it isn't part of the file format. See the "autofilter.pl" program in the examples directory of the dis- tro for an example. The conditions for the filter are specified using simple expressions: $worksheet->filter_column('A', 'x > 2000'); $worksheet->filter_column('B', 'x > 2000 and x < 5000'); The $column parameter can either be a zero indexed column number or a string column name. The following operators are available: Operator Synonyms == = eq =~ != <> ne != > < >= <= and && or || The operator synonyms are just syntactic sugar to make you more comfortable using the expressions. It is important to remember that the expressions will be interpreted by Excel and not by perl. An expression can comprise a single statement or two statements separated by the "and" and "or" operators. For example: 'x < 2000' 'x > 2000' 'x == 2000' 'x > 2000 and x < 5000' 'x == 2000 or x == 5000' Filtering of blank or non-blank data can be achieved by using a value of "Blanks" or "Non- Blanks" in the expression: 'x == Blanks' 'x == NonBlanks' Top 10 style filters can be specified using a expression like the following: Top|Bottom 1-500 Items|% For example: 'Top 10 Items' 'Bottom 5 Items' 'Top 25 %' 'Bottom 50 %' Excel also allows some simple string matching operations: 'x =~ b*' # begins with b 'x !~ b*' # doesn't begin with b 'x =~ *b' # ends with b 'x !~ *b' # doesn't end with b 'x =~ *b*' # contains b 'x !~ *b*' # doesn't contains b You can also use "*" to match any character or number and "?" to match any single charac- ter or number. No other regular expression quantifier is supported by Excel's filters. Excel's regular expression characters can be escaped using "~". The placeholder variable "x" in the above examples can be replaced by any simple string. The actual placeholder name is ignored internally so the following are all equivalent: 'x < 2000' 'col < 2000' 'Price < 2000' Also, note that a filter condition can only be applied to a column in a range specified by the "autofilter()" Worksheet method. See the "autofilter.pl" program in the examples directory of the distro for a more detailed example. PAGE SET-UP METHODS Page set-up methods affect the way that a worksheet looks when it is printed. They control features such as page headers and footers and margins. These methods are really just stan- dard worksheet methods. They are documented here in a separate section for the sake of clarity. The following methods are available for page set-up: set_landscape() set_portrait() set_page_view() set_paper() center_horizontally() center_vertically() set_margins() set_header() set_footer() repeat_rows() repeat_columns() hide_gridlines() print_row_col_headers() print_area() print_across() fit_to_pages() set_start_page() set_print_scale() set_h_pagebreaks() set_v_pagebreaks() A common requirement when working with Spreadsheet::WriteExcel is to apply the same page set-up features to all of the worksheets in a workbook. To do this you can use the "sheets()" method of the "workbook" class to access the array of worksheets in a workbook: foreach $worksheet ($workbook->sheets()) { $worksheet->set_landscape(); } set_landscape() This method is used to set the orientation of a worksheet's printed page to landscape: $worksheet->set_landscape(); # Landscape mode set_portrait() This method is used to set the orientation of a worksheet's printed page to portrait. The default worksheet orientation is portrait, so you won't generally need to call this method. $worksheet->set_portrait(); # Portrait mode set_page_view() This method is used to display the worksheet in "Page View" mode. This is currently only supported by Mac Excel, where it is the default. $worksheet->set_page_view(); set_paper($index) This method is used to set the paper format for the printed output of a worksheet. The following paper styles are available: Index Paper format Paper size ===== ============ ========== 0 Printer default - 1 Letter 8 1/2 x 11 in 2 Letter Small 8 1/2 x 11 in 3 Tabloid 11 x 17 in 4 Ledger 17 x 11 in 5 Legal 8 1/2 x 14 in 6 Statement 5 1/2 x 8 1/2 in 7 Executive 7 1/4 x 10 1/2 in 8 A3 297 x 420 mm 9 A4 210 x 297 mm 10 A4 Small 210 x 297 mm 11 A5 148 x 210 mm 12 B4 250 x 354 mm 13 B5 182 x 257 mm 14 Folio 8 1/2 x 13 in 15 Quarto 215 x 275 mm 16 - 10x14 in 17 - 11x17 in 18 Note 8 1/2 x 11 in 19 Envelope 9 3 7/8 x 8 7/8 20 Envelope 10 4 1/8 x 9 1/2 21 Envelope 11 4 1/2 x 10 3/8 22 Envelope 12 4 3/4 x 11 23 Envelope 14 5 x 11 1/2 24 C size sheet - 25 D size sheet - 26 E size sheet - 27 Envelope DL 110 x 220 mm 28 Envelope C3 324 x 458 mm 29 Envelope C4 229 x 324 mm 30 Envelope C5 162 x 229 mm 31 Envelope C6 114 x 162 mm 32 Envelope C65 114 x 229 mm 33 Envelope B4 250 x 353 mm 34 Envelope B5 176 x 250 mm 35 Envelope B6 176 x 125 mm 36 Envelope 110 x 230 mm 37 Monarch 3.875 x 7.5 in 38 Envelope 3 5/8 x 6 1/2 in 39 Fanfold 14 7/8 x 11 in 40 German Std Fanfold 8 1/2 x 12 in 41 German Legal Fanfold 8 1/2 x 13 in Note, it is likely that not all of these paper types will be available to the end user since it will depend on the paper formats that the user's printer supports. Therefore, it is best to stick to standard paper types. $worksheet->set_paper(1); # US Letter $worksheet->set_paper(9); # A4 If you do not specify a paper type the worksheet will print using the printer's default paper. center_horizontally() Center the worksheet data horizontally between the margins on the printed page: $worksheet->center_horizontally(); center_vertically() Center the worksheet data vertically between the margins on the printed page: $worksheet->center_vertically(); set_margins($inches) There are several methods available for setting the worksheet margins on the printed page: set_margins() # Set all margins to the same value set_margins_LR() # Set left and right margins to the same value set_margins_TB() # Set top and bottom margins to the same value set_margin_left(); # Set left margin set_margin_right(); # Set right margin set_margin_top(); # Set top margin set_margin_bottom(); # Set bottom margin All of these methods take a distance in inches as a parameter. Note: 1 inch = 25.4mm. ;-) The default left and right margin is 0.75 inch. The default top and bottom margin is 1.00 inch. set_header($string, $margin) Headers and footers are generated using a $string which is a combination of plain text and control characters. The $margin parameter is optional. The available control character are: Control Category Description ======= ======== =========== &L Justification Left &C Center &R Right &P Information Page number &N Total number of pages &D Date &T Time &F File name &A Worksheet name &Z Workbook path &fontsize Font Font size &"font,style" Font name and style &U Single underline &E Double underline &S Strikethrough &X Superscript &Y Subscript && Miscellaneous Literal ampersand & Text in headers and footers can be justified (aligned) to the left, center and right by prefixing the text with the control characters &L, &C and &R. For example (with ASCII art representation of the results): $worksheet->set_header('&LHello'); --------------------------------------------------------------- | | | Hello | | | $worksheet->set_header('&CHello'); --------------------------------------------------------------- | | | Hello | | | $worksheet->set_header('&RHello'); --------------------------------------------------------------- | | | Hello | | | For simple text, if you do not specify any justification the text will be centred. How- ever, you must prefix the text with &C if you specify a font name or any other formatting: $worksheet->set_header('Hello'); --------------------------------------------------------------- | | | Hello | | | You can have text in each of the justification regions: $worksheet->set_header('&LCiao&CBello&RCielo'); --------------------------------------------------------------- | | | Ciao Bello Cielo | | | The information control characters act as variables that Excel will update as the workbook or worksheet changes. Times and dates are in the users default format: $worksheet->set_header('&CPage &P of &N'); --------------------------------------------------------------- | | | Page 1 of 6 | | | $worksheet->set_header('&CUpdated at &T'); --------------------------------------------------------------- | | | Updated at 12:30 PM | | | You can specify the font size of a section of the text by prefixing it with the control character &n where "n" is the font size: $worksheet1->set_header('&C&30Hello Big' ); $worksheet2->set_header('&C&10Hello Small'); You can specify the font of a section of the text by prefixing it with the control sequence "&"font,style"" where "fontname" is a font name such as "Courier New" or "Times New Roman" and "style" is one of the standard Windows font descriptions: "Regular", "Italic", "Bold" or "Bold Italic": $worksheet1->set_header('&C&"Courier New,Italic"Hello'); $worksheet2->set_header('&C&"Courier New,Bold Italic"Hello'); $worksheet3->set_header('&C&"Times New Roman,Regular"Hello'); It is possible to combine all of these features together to create sophisticated headers and footers. As an aid to setting up complicated headers and footers you can record a page set-up as a macro in Excel and look at the format strings that VBA produces. Remember how- ever that VBA uses two double quotes "" to indicate a single double quote. For the last example above the equivalent VBA code looks like this: .LeftHeader = "" .CenterHeader = "&""Times New Roman,Regular""Hello" .RightHeader = "" To include a single literal ampersand "&" in a header or footer you should use a double ampersand "&&": $worksheet1->set_header('&CCuriouser && Curiouser - Attorneys at Law'); As stated above the margin parameter is optional. As with the other margins the value should be in inches. The default header and footer margin is 0.50 inch. The header and footer margin size can be set as follows: $worksheet->set_header('&CHello', 0.75); The header and footer margins are independent of the top and bottom margins. Note, the header or footer string must be less than 255 characters. Strings longer than this will not be written and a warning will be generated. On systems with "perl 5.8" and later the "set_header()" method can also handle Unicode strings in "UTF-8" format. $worksheet->set_header("&C\x{263a}") See, also the "headers.pl" program in the "examples" directory of the distribution. set_footer() The syntax of the "set_footer()" method is the same as "set_header()", see above. repeat_rows($first_row, $last_row) Set the number of rows to repeat at the top of each printed page. For large Excel documents it is often desirable to have the first row or rows of the work- sheet print out at the top of each page. This can be achieved by using the "repeat_rows()" method. The parameters $first_row and $last_row are zero based. The $last_row parameter is optional if you only wish to specify one row: $worksheet1->repeat_rows(0); # Repeat the first row $worksheet2->repeat_rows(0, 1); # Repeat the first two rows repeat_columns($first_col, $last_col) Set the columns to repeat at the left hand side of each printed page. For large Excel documents it is often desirable to have the first column or columns of the worksheet print out at the left hand side of each page. This can be achieved by using the "repeat_columns()" method. The parameters $first_column and $last_column are zero based. The $last_column parameter is optional if you only wish to specify one column. You can also specify the columns using A1 column notation, see the note about "Cell notation". $worksheet1->repeat_columns(0); # Repeat the first column $worksheet2->repeat_columns(0, 1); # Repeat the first two columns $worksheet3->repeat_columns('A:A'); # Repeat the first column $worksheet4->repeat_columns('A:B'); # Repeat the first two columns hide_gridlines($option) This method is used to hide the gridlines on the screen and printed page. Gridlines are the lines that divide the cells on a worksheet. Screen and printed gridlines are turned on by default in an Excel worksheet. If you have defined your own cell borders you may wish to hide the default gridlines. $worksheet->hide_gridlines(); The following values of $option are valid: 0 : Don't hide gridlines 1 : Hide printed gridlines only 2 : Hide screen and printed gridlines If you don't supply an argument or use "undef" the default option is 1, i.e. only the printed gridlines are hidden. print_row_col_headers() Set the option to print the row and column headers on the printed page. An Excel worksheet looks something like the following; ------------------------------------------ | | A | B | C | D | ... ------------------------------------------ | 1 | | | | | ... | 2 | | | | | ... | 3 | | | | | ... | 4 | | | | | ... |...| ... | ... | ... | ... | ... The headers are the letters and numbers at the top and the left of the worksheet. Since these headers serve mainly as a indication of position on the worksheet they generally do not appear on the printed page. If you wish to have them printed you can use the "print_row_col_headers()" method : $worksheet->print_row_col_headers(); Do not confuse these headers with page headers as described in the "set_header()" section above. print_area($first_row, $first_col, $last_row, $last_col) This method is used to specify the area of the worksheet that will be printed. All four parameters must be specified. You can also use A1 notation, see the note about "Cell nota- tion". $worksheet1->print_area('A1:H20'); # Cells A1 to H20 $worksheet2->print_area(0, 0, 19, 7); # The same $worksheet2->print_area('A:H'); # Columns A to H if rows have data print_across() The "print_across" method is used to change the default print direction. This is referred to by Excel as the sheet "page order". $worksheet->print_across(); The default page order is shown below for a worksheet that extends over 4 pages. The order is called "down then across": [1] [3] [2] [4] However, by using the "print_across" method the print order will be changed to "across then down": [1] [2] [3] [4] fit_to_pages($width, $height) The "fit_to_pages()" method is used to fit the printed area to a specific number of pages both vertically and horizontally. If the printed area exceeds the specified number of pages it will be scaled down to fit. This guarantees that the printed area will always appear on the specified number of pages even if the page size or margins change. $worksheet1->fit_to_pages(1, 1); # Fit to 1x1 pages $worksheet2->fit_to_pages(2, 1); # Fit to 2x1 pages $worksheet3->fit_to_pages(1, 2); # Fit to 1x2 pages The print area can be defined using the "print_area()" method as described above. A common requirement is to fit the printed output to n pages wide but have the height be as long as necessary. To achieve this set the $height to zero or leave it blank: $worksheet1->fit_to_pages(1, 0); # 1 page wide and as long as necessary $worksheet2->fit_to_pages(1); # The same Note that although it is valid to use both "fit_to_pages()" and "set_print_scale()" on the same worksheet only one of these options can be active at a time. The last method call made will set the active option. Note that "fit_to_pages()" will override any manual page breaks that are defined in the worksheet. set_start_page($start_page) The "set_start_page()" method is used to set the number of the starting page when the worksheet is printed out. The default value is 1. $worksheet->set_start_page(2); set_print_scale($scale) Set the scale factor of the printed page. Scale factors in the range "10 <= $scale <= 400" are valid: $worksheet1->set_print_scale(50); $worksheet2->set_print_scale(75); $worksheet3->set_print_scale(300); $worksheet4->set_print_scale(400); The default scale factor is 100. Note, "set_print_scale()" does not affect the scale of the visible page in Excel. For that you should use "set_zoom()". Note also that although it is valid to use both "fit_to_pages()" and "set_print_scale()" on the same worksheet only one of these options can be active at a time. The last method call made will set the active option. set_h_pagebreaks(@breaks) Add horizontal page breaks to a worksheet. A page break causes all the data that follows it to be printed on the next page. Horizontal page breaks act between rows. To create a page break between rows 20 and 21 you must specify the break at row 21. However in zero index notation this is actually row 20. So you can pretend for a small w |