blob: 2ffcdc1a0b864d70e946e6e9e24cc88df4e8fb30 [file] [log] [blame]
yu.dongc33b3072024-08-21 23:14:49 -07001package Spreadsheet::WriteExcel;
2
3###############################################################################
4#
5# WriteExcel.
6#
7# Spreadsheet::WriteExcel - Write to a cross-platform Excel binary file.
8#
9# Copyright 2000-2010, John McNamara, jmcnamara@cpan.org
10#
11# Documentation after __END__
12#
13
14use Exporter;
15
16use strict;
17use Spreadsheet::WriteExcel::Workbook;
18
19
20
21use vars qw($VERSION @ISA);
22@ISA = qw(Spreadsheet::WriteExcel::Workbook Exporter);
23
24$VERSION = '2.37'; # The Life Pursuit
25
26
27
28###############################################################################
29#
30# new()
31#
32# Constructor. Wrapper for a Workbook object.
33# uses: Spreadsheet::WriteExcel::BIFFwriter
34# Spreadsheet::WriteExcel::Chart
35# Spreadsheet::WriteExcel::OLEwriter
36# Spreadsheet::WriteExcel::Workbook
37# Spreadsheet::WriteExcel::Worksheet
38# Spreadsheet::WriteExcel::Format
39# Spreadsheet::WriteExcel::Formula
40# Spreadsheet::WriteExcel::Properties
41#
42sub new {
43
44 my $class = shift;
45 my $self = Spreadsheet::WriteExcel::Workbook->new(@_);
46
47 # Check for file creation failures before re-blessing
48 bless $self, $class if defined $self;
49
50 return $self;
51}
52
53
541;
55
56
57__END__
58
59
60
61=head1 NAME
62
63Spreadsheet::WriteExcel - Write to a cross-platform Excel binary file.
64
65=head1 VERSION
66
67This document refers to version 2.37 of Spreadsheet::WriteExcel, released February 2, 2010.
68
69
70
71
72=head1 SYNOPSIS
73
74To write a string, a formatted string, a number and a formula to the first worksheet in an Excel workbook called perl.xls:
75
76 use Spreadsheet::WriteExcel;
77
78 # Create a new Excel workbook
79 my $workbook = Spreadsheet::WriteExcel->new('perl.xls');
80
81 # Add a worksheet
82 $worksheet = $workbook->add_worksheet();
83
84 # Add and define a format
85 $format = $workbook->add_format(); # Add a format
86 $format->set_bold();
87 $format->set_color('red');
88 $format->set_align('center');
89
90 # Write a formatted and unformatted string, row and column notation.
91 $col = $row = 0;
92 $worksheet->write($row, $col, 'Hi Excel!', $format);
93 $worksheet->write(1, $col, 'Hi Excel!');
94
95 # Write a number and a formula using A1 notation
96 $worksheet->write('A3', 1.2345);
97 $worksheet->write('A4', '=SIN(PI()/4)');
98
99
100
101
102=head1 DESCRIPTION
103
104The Spreadsheet::WriteExcel Perl 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, images and charts can be written to the cells.
105
106The file produced by this module is compatible with Excel 97, 2000, 2002, 2003 and 2007.
107
108The module will work on the majority of Windows, UNIX and Mac platforms. Generated files are also compatible with the Linux/UNIX spreadsheet applications Gnumeric and OpenOffice.org.
109
110This module cannot be used to write to an existing Excel file (See L<MODIFYING AND REWRITING EXCEL FILES>).
111
112
113
114
115=head1 QUICK START
116
117Spreadsheet::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:
118
1191. Create a new Excel I<workbook> (i.e. file) using C<new()>.
120
1212. Add a I<worksheet> to the new workbook using C<add_worksheet()>.
122
1233. Write to the worksheet using C<write()>.
124
125Like this:
126
127 use Spreadsheet::WriteExcel; # Step 0
128
129 my $workbook = Spreadsheet::WriteExcel->new('perl.xls'); # Step 1
130 $worksheet = $workbook->add_worksheet(); # Step 2
131 $worksheet->write('A1', 'Hi Excel!'); # Step 3
132
133This will create an Excel file called C<perl.xls> with a single worksheet and the text C<'Hi Excel!'> in the relevant cell. And that's it. Okay, so there is actually a zeroth step as well, but C<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 L<EXAMPLES>.
134
135Those of you who read the instructions first and assemble the furniture afterwards will know how to proceed. ;-)
136
137
138
139
140=head1 WORKBOOK METHODS
141
142The Spreadsheet::WriteExcel module provides an object oriented interface to a new Excel workbook. The following methods are available through a new workbook.
143
144 new()
145 add_worksheet()
146 add_format()
147 add_chart()
148 add_chart_ext()
149 close()
150 compatibility_mode()
151 set_properties()
152 define_name()
153 set_tempdir()
154 set_custom_color()
155 sheets()
156 set_1904()
157 set_codepage()
158
159If you are unfamiliar with object oriented interfaces or the way that they are implemented in Perl have a look at C<perlobj> and C<perltoot> in the main Perl documentation.
160
161
162
163
164=head2 new()
165
166A new Excel workbook is created using the C<new()> constructor which accepts either a filename or a filehandle as a parameter. The following example creates a new Excel file based on a filename:
167
168 my $workbook = Spreadsheet::WriteExcel->new('filename.xls');
169 my $worksheet = $workbook->add_worksheet();
170 $worksheet->write(0, 0, 'Hi Excel!');
171
172Here are some other examples of using C<new()> with filenames:
173
174 my $workbook1 = Spreadsheet::WriteExcel->new($filename);
175 my $workbook2 = Spreadsheet::WriteExcel->new('/tmp/filename.xls');
176 my $workbook3 = Spreadsheet::WriteExcel->new("c:\\tmp\\filename.xls");
177 my $workbook4 = Spreadsheet::WriteExcel->new('c:\tmp\filename.xls');
178
179The last two examples demonstrates how to create a file on DOS or Windows where it is necessary to either escape the directory separator C<\> or to use single quotes to ensure that it isn't interpolated. For more information see C<perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?>.
180
181The C<new()> constructor returns a Spreadsheet::WriteExcel object that you can use to add worksheets and store data. It should be noted that although C<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 C<close()> method.
182
183If the file cannot be created, due to file permissions or some other reason, C<new> will return C<undef>. Therefore, it is good practice to check the return value of C<new> before proceeding. As usual the Perl variable C<$!> will be set if there is a file creation error. You will also see one of the warning messages detailed in L<DIAGNOSTICS>:
184
185 my $workbook = Spreadsheet::WriteExcel->new('protected.xls');
186 die "Problems creating new Excel file: $!" unless defined $workbook;
187
188You can also pass a valid filehandle to the C<new()> constructor. For example in a CGI program you could do something like this:
189
190 binmode(STDOUT);
191 my $workbook = Spreadsheet::WriteExcel->new(\*STDOUT);
192
193The requirement for C<binmode()> is explained below.
194
195For CGI programs you can also use the special Perl filename C<'-'> which will redirect the output to STDOUT:
196
197 my $workbook = Spreadsheet::WriteExcel->new('-');
198
199See also, the C<cgi.pl> program in the C<examples> directory of the distro.
200
201However, this special case will not work in C<mod_perl> programs where you will have to do something like the following:
202
203 # mod_perl 1
204 ...
205 tie *XLS, 'Apache';
206 binmode(XLS);
207 my $workbook = Spreadsheet::WriteExcel->new(\*XLS);
208 ...
209
210 # mod_perl 2
211 ...
212 tie *XLS => $r; # Tie to the Apache::RequestRec object
213 binmode(*XLS);
214 my $workbook = Spreadsheet::WriteExcel->new(\*XLS);
215 ...
216
217See also, the C<mod_perl1.pl> and C<mod_perl2.pl> programs in the C<examples> directory of the distro.
218
219Filehandles 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.
220
221For example here is a way to write an Excel file to a scalar with C<perl 5.8>:
222
223 #!/usr/bin/perl -w
224
225 use strict;
226 use Spreadsheet::WriteExcel;
227
228 # Requires perl 5.8 or later
229 open my $fh, '>', \my $str or die "Failed to open filehandle: $!";
230
231 my $workbook = Spreadsheet::WriteExcel->new($fh);
232 my $worksheet = $workbook->add_worksheet();
233
234 $worksheet->write(0, 0, 'Hi Excel!');
235
236 $workbook->close();
237
238 # The Excel file in now in $str. Remember to binmode() the output
239 # filehandle before printing it.
240 binmode STDOUT;
241 print $str;
242
243See also the C<write_to_scalar.pl> and C<filehandle.pl> programs in the C<examples> directory of the distro.
244
245B<Note about the requirement for> C<binmode()>. An Excel file is comprised of binary data. Therefore, if you are using a filehandle you should ensure that you C<binmode()> it prior to passing it to C<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 C<UTF-8> is likely to be in operation such as RedHat Linux 9. If your program, either intentionally or not, writes C<UTF-8> data to a filehandle that is passed to C<new()> it will corrupt the Excel file that is created.
246
247You don't have to worry about C<binmode()> if you are using filenames instead of filehandles. Spreadsheet::WriteExcel performs the C<binmode()> internally when it converts the filename to a filehandle. For more information about C<binmode()> see C<perlfunc> and C<perlopentut> in the main Perl documentation.
248
249
250
251
252
253=head2 add_worksheet($sheetname, $utf_16_be)
254
255At least one worksheet should be added to a new workbook. A worksheet is used to write data into cells:
256
257 $worksheet1 = $workbook->add_worksheet(); # Sheet1
258 $worksheet2 = $workbook->add_worksheet('Foglio2'); # Foglio2
259 $worksheet3 = $workbook->add_worksheet('Data'); # Data
260 $worksheet4 = $workbook->add_worksheet(); # Sheet4
261
262If C<$sheetname> is not specified the default Excel convention will be followed, i.e. Sheet1, Sheet2, etc. The C<$utf_16_be> parameter is optional, see below.
263
264The worksheet name must be a valid Excel worksheet name, i.e. it cannot contain any of the following characters, C<[ ] : * ? / \> and it must be less than 32 characters. In addition, you cannot use the same, case insensitive, C<$sheetname> for more than one worksheet.
265
266On systems with C<perl 5.8> and later the C<add_worksheet()> method will also handle strings in C<UTF-8> format.
267
268 $worksheet = $workbook->add_worksheet("\x{263a}"); # Smiley
269
270On earlier Perl systems your can specify C<UTF-16BE> worksheet names using an additional optional parameter:
271
272 my $name = pack 'n', 0x263a;
273 $worksheet = $workbook->add_worksheet($name, 1); # Smiley
274
275
276
277
278=head2 add_format(%properties)
279
280The C<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.
281
282 $format1 = $workbook->add_format(%props); # Set properties at creation
283 $format2 = $workbook->add_format(); # Set properties later
284
285See the L<CELL FORMATTING> section for more details about Format properties and how to set them.
286
287
288
289
290=head2 add_chart(%properties)
291
292This method is use to create a new chart either as a standalone worksheet (the default) or as an embeddable object that can be inserted into a worksheet via the C<insert_chart()> Worksheet method.
293
294 my $chart = $workbook->add_chart( type => 'column' );
295
296The properties that can be set are:
297
298 type (required)
299 name (optional)
300 embedded (optional)
301
302=over
303
304=item * C<type>
305
306This is a required parameter. It defines the type of chart that will be created.
307
308 my $chart = $workbook->add_chart( type => 'line' );
309
310The available types are:
311
312 area
313 bar
314 column
315 line
316 pie
317 scatter
318 stock
319
320=item * C<name>
321
322Set the name for the chart sheet. The name property is optional and if it isn't supplied will default to C<Chart1 .. n>. The name must be a valid Excel worksheet name. See C<add_worksheet()> for more details on valid sheet names. The C<name> property can be omitted for embedded charts.
323
324 my $chart = $workbook->add_chart( type => 'line', name => 'Results Chart' );
325
326=item * C<embedded>
327
328Specifies that the Chart object will be inserted in a worksheet via the C<insert_chart()> Worksheet method. It is an error to try insert a Chart that doesn't have this flag set.
329
330 my $chart = $workbook->add_chart( type => 'line', embedded => 1 );
331
332 # Configure the chart.
333 ...
334
335 # Insert the chart into the a worksheet.
336 $worksheet->insert_chart( 'E2', $chart );
337
338=back
339
340See L<Spreadsheet::WriteExcel::Chart> for details on how to configure the chart object once it is created. See also the C<chart_*.pl> programs in the examples directory of the distro.
341
342
343
344
345=head2 add_chart_ext($chart_data, $chartname)
346
347This method is use to include externally generated charts in a Spreadsheet::WriteExcel file.
348
349 my $chart = $workbook->add_chart_ext('chart01.bin', 'Chart1');
350
351This feature is semi-deprecated in favour of the "native" charts created using C<add_chart()>. Read C<external_charts.txt> (or C<.pod>) in the external_charts directory of the distro for a full explanation.
352
353
354
355
356=head2 close()
357
358In general your Excel file will be closed automatically when your program ends or when the Workbook object goes out of scope, however the C<close()> method can be used to explicitly close an Excel file.
359
360 $workbook->close();
361
362An explicit C<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.
363
364In addition, C<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:
365
366=over 4
367
368=item *
369
370If C<my()> was not used to declare the scope of a workbook variable created using C<new()>.
371
372=item *
373
374If the C<new()>, C<add_worksheet()> or C<add_format()> methods are called in subroutines.
375
376=back
377
378The reason for this is that Spreadsheet::WriteExcel relies on Perl's C<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.
379
380In general, if you create a file with a size of 0 bytes or you fail to create a file you need to call C<close()>.
381
382The return value of C<close()> is the same as that returned by perl when it closes the file created by C<new()>. This allows you to handle error conditions in the usual way:
383
384 $workbook->close() or die "Error closing file: $!";
385
386
387
388
389=head2 compatibility_mode()
390
391This method is used to improve compatibility with third party applications that read Excel files.
392
393 $workbook->compatibility_mode();
394
395An 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.
396
397Spreadsheet::WriteExcel takes advantage of this fact to omit some records in order to minimise the amount of data stored in memory and to simplify and speed up the writing of files. However, some third party applications that read Excel files often expect certain records to be present. In "compatibility mode" Spreadsheet::WriteExcel writes these records and tries to be as close to an Excel generated file as possible.
398
399Applications that require C<compatibility_mode()> are Apache POI, Apple Numbers, and Quickoffice on Nokia, Palm and other devices. You should also use C<compatibility_mode()> if your Excel file will be used as an external data source by another Excel file.
400
401If you encounter other situations that require C<compatibility_mode()>, please let me know.
402
403It should be noted that C<compatibility_mode()> requires additional data to be stored in memory and additional processing. This incurs a memory and speed penalty and may not be suitable for very large files (>20MB).
404
405You must call C<compatibility_mode()> before calling C<add_worksheet()>.
406
407
408
409
410=head2 set_properties()
411
412The C<set_properties> method can be used to set the document properties of the Excel file created by C<Spreadsheet::WriteExcel>. These properties are visible when you use the C<< File->Properties >> menu option in Excel and are also available to external applications that read or index windows files.
413
414The properties should be passed as a hash of values as follows:
415
416 $workbook->set_properties(
417 title => 'This is an example spreadsheet',
418 author => 'John McNamara',
419 comments => 'Created with Perl and Spreadsheet::WriteExcel',
420 );
421
422The properties that can be set are:
423
424 title
425 subject
426 author
427 manager
428 company
429 category
430 keywords
431 comments
432
433User defined properties are not supported due to effort required.
434
435In perl 5.8+ you can also pass UTF-8 strings as properties. See L<UNICODE IN EXCEL>.
436
437 my $smiley = chr 0x263A;
438
439 $workbook->set_properties(
440 subject => "Happy now? $smiley",
441 );
442
443With older versions of perl you can use a module to convert a non-ASCII string to a binary representation of UTF-8 and then pass an additional C<utf8> flag to C<set_properties()>:
444
445 my $smiley = pack 'H*', 'E298BA';
446
447 $workbook->set_properties(
448 subject => "Happy now? $smiley",
449 utf8 => 1,
450 );
451
452Usually Spreadsheet::WriteExcel allows you to use UTF-16 with pre 5.8 versions of perl. However, document properties don't support UTF-16 for these type of strings.
453
454In order to promote the usefulness of Perl and the Spreadsheet::WriteExcel module consider adding a comment such as the following when using document properties:
455
456 $workbook->set_properties(
457 ...,
458 comments => 'Created with Perl and Spreadsheet::WriteExcel',
459 ...,
460 );
461
462This feature requires that the C<OLE::Storage_Lite> module is installed (which is usually the case for a standard Spreadsheet::WriteExcel installation). However, this also means that the resulting OLE document may B<possibly> be buggy for files less than 7MB since it hasn't been as rigorously tested in that domain. As a result of this C<set_properties> is currently incompatible with Gnumeric for files less than 7MB. This is being investigated. If you encounter any problems with this features let me know.
463
464For convenience it is possible to pass either a hash or hash ref of arguments to this method.
465
466See also the C<properties.pl> program in the examples directory of the distro.
467
468
469
470
471=head2 define_name()
472
473This method is used to defined a name that can be used to represent a value, a single cell or a range of cells in a workbook.
474
475 $workbook->define_name('Exchange_rate', '=0.96');
476 $workbook->define_name('Sales', '=Sheet1!$G$1:$H$10');
477 $workbook->define_name('Sheet2!Sales', '=Sheet2!$G$1:$G$10');
478
479See the defined_name.pl program in the examples dir of the distro.
480
481Note: This currently a beta feature. More documentation and examples will be added.
482
483
484
485
486=head2 set_tempdir()
487
488For speed and efficiency C<Spreadsheet::WriteExcel> stores worksheet data in temporary files prior to assembling the final workbook.
489
490If Spreadsheet::WriteExcel is unable to create these temporary files it will store the required data in memory. This can be slow for large files.
491
492The 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<C:/> or some other directory that IIS doesn't provide write access to.
493
494To check if this might be a problem on a particular system you can run a simple test program with C<-w> or C<use warnings>. This will generate a warning if the module cannot create the required temporary files:
495
496 #!/usr/bin/perl -w
497
498 use Spreadsheet::WriteExcel;
499
500 my $workbook = Spreadsheet::WriteExcel->new('test.xls');
501 my $worksheet = $workbook->add_worksheet();
502
503To avoid this problem the C<set_tempdir()> method can be used to specify a directory that is accessible for the creation of temporary files.
504
505The C<File::Temp> module is used to create the temporary files. File::Temp uses C<File::Spec> to determine an appropriate location for these files such as C</tmp> or C<c:\windows\temp>. You can find out which directory is used on your system as follows:
506
507 perl -MFile::Spec -le "print File::Spec->tmpdir"
508
509Even if the default temporary file directory is accessible you may wish to specify an alternative location for security or maintenance reasons:
510
511 $workbook->set_tempdir('/tmp/writeexcel');
512 $workbook->set_tempdir('c:\windows\temp\writeexcel');
513
514The directory for the temporary file must exist, C<set_tempdir()> will not create a new directory.
515
516One disadvantage of using the C<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.
517
518
519
520
521=head2 set_custom_color($index, $red, $green, $blue)
522
523The C<set_custom_color()> method can be used to override one of the built-in palette values with a more suitable colour.
524
525The value for C<$index> should be in the range 8..63, see L<COLOURS IN EXCEL>.
526
527The default named colours use the following indices:
528
529 8 => black
530 9 => white
531 10 => red
532 11 => lime
533 12 => blue
534 13 => yellow
535 14 => magenta
536 15 => cyan
537 16 => brown
538 17 => green
539 18 => navy
540 20 => purple
541 22 => silver
542 23 => gray
543 33 => pink
544 53 => orange
545
546A new colour is set using its RGB (red green blue) components. The C<$red>, C<$green> and C<$blue> values must be in the range 0..255. You can determine the required values in Excel using the C<Tools-E<gt>Options-E<gt>Colors-E<gt>Modify> dialog.
547
548The C<set_custom_color()> workbook method can also be used with a HTML style C<#rrggbb> hex value:
549
550 $workbook->set_custom_color(40, 255, 102, 0 ); # Orange
551 $workbook->set_custom_color(40, 0xFF, 0x66, 0x00); # Same thing
552 $workbook->set_custom_color(40, '#FF6600' ); # Same thing
553
554 my $font = $workbook->add_format(color => 40); # Use the modified colour
555
556The return value from C<set_custom_color()> is the index of the colour that was changed:
557
558 my $ferrari = $workbook->set_custom_color(40, 216, 12, 12);
559
560 my $format = $workbook->add_format(
561 bg_color => $ferrari,
562 pattern => 1,
563 border => 1
564 );
565
566
567
568
569=head2 sheets(0, 1, ...)
570
571The C<sheets()> method returns a list, or a sliced list, of the worksheets in a workbook.
572
573If no arguments are passed the method returns a list of all the worksheets in the workbook. This is useful if you want to repeat an operation on each worksheet:
574
575 foreach $worksheet ($workbook->sheets()) {
576 print $worksheet->get_name();
577 }
578
579
580You can also specify a slice list to return one or more worksheet objects:
581
582 $worksheet = $workbook->sheets(0);
583 $worksheet->write('A1', 'Hello');
584
585
586Or since return value from C<sheets()> is a reference to a worksheet object you can write the above example as:
587
588 $workbook->sheets(0)->write('A1', 'Hello');
589
590
591The following example returns the first and last worksheet in a workbook:
592
593 foreach $worksheet ($workbook->sheets(0, -1)) {
594 # Do something
595 }
596
597
598Array slices are explained in the perldata manpage.
599
600
601
602
603=head2 set_1904()
604
605Excel stores dates as real numbers where the integer part stores the number of days since the epoch and the fractional part stores the percentage of the day. The epoch can be either 1900 or 1904. Excel for Windows uses 1900 and Excel for Macintosh uses 1904. However, Excel on either platform will convert automatically between one system and the other.
606
607Spreadsheet::WriteExcel stores dates in the 1900 format by default. If you wish to change this you can call the C<set_1904()> workbook method. You can query the current value by calling the C<get_1904()> workbook method. This returns 0 for 1900 and 1 for 1904.
608
609See also L<DATES AND TIME IN EXCEL> for more information about working with Excel's date system.
610
611In general you probably won't need to use C<set_1904()>.
612
613
614
615
616=head2 set_codepage($codepage)
617
618The 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 C<set_codepage()> method.
619
620Changing 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:
621
622 $workbook->set_codepage(1); # ANSI, MS Windows
623 $workbook->set_codepage(2); # Apple Macintosh
624
625The C<set_codepage()> method is rarely required.
626
627
628
629
630=head1 WORKSHEET METHODS
631
632A new worksheet is created by calling the C<add_worksheet()> method from a workbook object:
633
634 $worksheet1 = $workbook->add_worksheet();
635 $worksheet2 = $workbook->add_worksheet();
636
637The following methods are available through a new worksheet:
638
639 write()
640 write_number()
641 write_string()
642 write_utf16be_string()
643 write_utf16le_string()
644 keep_leading_zeros()
645 write_blank()
646 write_row()
647 write_col()
648 write_date_time()
649 write_url()
650 write_url_range()
651 write_formula()
652 store_formula()
653 repeat_formula()
654 write_comment()
655 show_comments()
656 add_write_handler()
657 insert_image()
658 insert_chart()
659 data_validation()
660 get_name()
661 activate()
662 select()
663 hide()
664 set_first_sheet()
665 protect()
666 set_selection()
667 set_row()
668 set_column()
669 outline_settings()
670 freeze_panes()
671 split_panes()
672 merge_range()
673 set_zoom()
674 right_to_left()
675 hide_zero()
676 set_tab_color()
677 autofilter()
678
679
680
681
682=head2 Cell notation
683
684Spreadsheet::WriteExcel supports two forms of notation to designate the position of cells: Row-column notation and A1 notation.
685
686Row-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:
687
688 (0, 0) # The top left cell in row-column notation.
689 ('A1') # The top left cell in A1 notation.
690
691 (1999, 29) # Row-column notation.
692 ('AD2000') # The same cell in A1 notation.
693
694Row-column notation is useful if you are referring to cells programmatically:
695
696 for my $i (0 .. 9) {
697 $worksheet->write($i, 0, 'Hello'); # Cells A1 to A10
698 }
699
700A1 notation is useful for setting up a worksheet manually and for working with formulas:
701
702 $worksheet->write('H1', 200);
703 $worksheet->write('H2', '=H1+1');
704
705In formulas and applicable methods you can also use the C<A:A> column notation:
706
707 $worksheet->write('A1', '=SUM(B:B)');
708
709The C<Spreadsheet::WriteExcel::Utility> module that is included in the distro contains helper functions for dealing with A1 notation, for example:
710
711 use Spreadsheet::WriteExcel::Utility;
712
713 ($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
714 $str = xl_rowcol_to_cell(1, 2); # C2
715
716For simplicity, the parameter lists for the worksheet method calls in the following sections are given in terms of row-column notation. In all cases it is also possible to use A1 notation.
717
718Note: in Excel it is also possible to use a R1C1 notation. This is not supported by Spreadsheet::WriteExcel.
719
720
721
722
723=head2 write($row, $column, $token, $format)
724
725Excel makes a distinction between data types such as strings, numbers, blanks, formulas and hyperlinks. To simplify the process of writing data the C<write()> method acts as a general alias for several more specific methods:
726
727 write_string()
728 write_number()
729 write_blank()
730 write_formula()
731 write_url()
732 write_row()
733 write_col()
734
735The general rule is that if the data looks like a I<something> then a I<something> is written. Here are some examples in both row-column and A1 notation:
736
737 # Same as:
738 $worksheet->write(0, 0, 'Hello' ); # write_string()
739 $worksheet->write(1, 0, 'One' ); # write_string()
740 $worksheet->write(2, 0, 2 ); # write_number()
741 $worksheet->write(3, 0, 3.00001 ); # write_number()
742 $worksheet->write(4, 0, "" ); # write_blank()
743 $worksheet->write(5, 0, '' ); # write_blank()
744 $worksheet->write(6, 0, undef ); # write_blank()
745 $worksheet->write(7, 0 ); # write_blank()
746 $worksheet->write(8, 0, 'http://www.perl.com/'); # write_url()
747 $worksheet->write('A9', 'ftp://ftp.cpan.org/' ); # write_url()
748 $worksheet->write('A10', 'internal:Sheet1!A1' ); # write_url()
749 $worksheet->write('A11', 'external:c:\foo.xls' ); # write_url()
750 $worksheet->write('A12', '=A3 + 3*A4' ); # write_formula()
751 $worksheet->write('A13', '=SIN(PI()/4)' ); # write_formula()
752 $worksheet->write('A14', \@array ); # write_row()
753 $worksheet->write('A15', [\@array] ); # write_col()
754
755 # And if the keep_leading_zeros property is set:
756 $worksheet->write('A16, 2 ); # write_number()
757 $worksheet->write('A17, 02 ); # write_string()
758 $worksheet->write('A18, 00002 ); # write_string()
759
760
761The "looks like" rule is defined by regular expressions:
762
763C<write_number()> if C<$token> is a number based on the following regex: C<$token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/>.
764
765C<write_string()> if C<keep_leading_zeros()> is set and C<$token> is an integer with leading zeros based on the following regex: C<$token =~ /^0\d+$/>.
766
767C<write_blank()> if C<$token> is undef or a blank string: C<undef>, C<""> or C<''>.
768
769C<write_url()> if C<$token> is a http, https, ftp or mailto URL based on the following regexes: C<$token =~ m|^[fh]tt?ps?://|> or C<$token =~ m|^mailto:|>.
770
771C<write_url()> if C<$token> is an internal or external sheet reference based on the following regex: C<$token =~ m[^(in|ex)ternal:]>.
772
773C<write_formula()> if the first character of C<$token> is C<"=">.
774
775C<write_row()> if C<$token> is an array ref.
776
777C<write_col()> if C<$token> is an array ref of array refs.
778
779C<write_string()> if none of the previous conditions apply.
780
781The C<$format> parameter is optional. It should be a valid Format object, see L<CELL FORMATTING>:
782
783 my $format = $workbook->add_format();
784 $format->set_bold();
785 $format->set_color('red');
786 $format->set_align('center');
787
788 $worksheet->write(4, 0, 'Hello', $format); # Formatted string
789
790The write() method will ignore empty strings or C<undef> tokens unless a format is also supplied. As such you needn't worry about special handling for empty or C<undef> values in your data. See also the C<write_blank()> method.
791
792One problem with the C<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 C<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 C<keep_leading_zeros()> section for a full discussion of this issue.
793
794You can also add your own data handlers to the C<write()> method using C<add_write_handler()>.
795
796On systems with C<perl 5.8> and later the C<write()> method will also handle Unicode strings in C<UTF-8> format.
797
798The C<write> methods return:
799
800 0 for success.
801 -1 for insufficient number of arguments.
802 -2 for row or column out of bounds.
803 -3 for string too long.
804
805
806
807
808=head2 write_number($row, $column, $number, $format)
809
810Write an integer or a float to the cell specified by C<$row> and C<$column>:
811
812 $worksheet->write_number(0, 0, 123456);
813 $worksheet->write_number('A2', 2.3451);
814
815See the note about L<Cell notation>. The C<$format> parameter is optional.
816
817In general it is sufficient to use the C<write()> method.
818
819
820
821
822=head2 write_string($row, $column, $string, $format)
823
824Write a string to the cell specified by C<$row> and C<$column>:
825
826 $worksheet->write_string(0, 0, 'Your text here' );
827 $worksheet->write_string('A2', 'or here' );
828
829The 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.
830
831The C<$format> parameter is optional.
832
833On systems with C<perl 5.8> and later the C<write()> method will also handle strings in C<UTF-8> format. With older perls you can also write Unicode in C<UTF16> format via the C<write_utf16be_string()> method. See also the C<unicode_*.pl> programs in the examples directory of the distro.
834
835In general it is sufficient to use the C<write()> method. However, you may sometimes wish to use the C<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:
836
837 # Write as a plain string
838 $worksheet->write_string('A1', '01209');
839
840However, 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 C<@>:
841
842 # Format as a string. Doesn't change to a number when edited
843 my $format1 = $workbook->add_format(num_format => '@');
844 $worksheet->write_string('A2', '01209', $format1);
845
846See also the note about L<Cell notation>.
847
848
849
850
851=head2 write_utf16be_string($row, $column, $string, $format)
852
853This method is used to write C<UTF-16BE> strings to a cell in Excel. It is functionally the same as the C<write_string()> method except that the string should be in C<UTF-16BE> Unicode format. It is generally easier, when using Spreadsheet::WriteExcel, to write unicode strings in C<UTF-8> format, see L<UNICODE IN EXCEL>. The C<write_utf16be_string()> method is mainly of use in versions of perl prior to 5.8.
854
855
856The following is a simple example showing how to write some Unicode strings in C<UTF-16BE> format:
857
858 #!/usr/bin/perl -w
859
860
861 use strict;
862 use Spreadsheet::WriteExcel;
863 use Unicode::Map();
864
865 my $workbook = Spreadsheet::WriteExcel->new('utf_16_be.xls');
866 my $worksheet = $workbook->add_worksheet();
867
868 # Increase the column width for clarity
869 $worksheet->set_column('A:A', 25);
870
871
872 # Write a Unicode character
873 #
874 my $smiley = pack 'n', 0x263a;
875
876 # Increase the font size for legibility.
877 my $big_font = $workbook->add_format(size => 72);
878
879 $worksheet->write_utf16be_string('A3', $smiley, $big_font);
880
881
882
883 # Write a phrase in Cyrillic using a hex-encoded string
884 #
885 my $str = pack 'H*', '042d0442043e0020044404400430043704300020043d' .
886 '043000200440044304410441043a043e043c0021';
887
888 $worksheet->write_utf16be_string('A5', $str);
889
890
891
892 # Map a string to UTF-16BE using an external module.
893 #
894 my $map = Unicode::Map->new('ISO-8859-1');
895 my $utf16 = $map->to_unicode('Hello world!');
896
897 $worksheet->write_utf16be_string('A7', $utf16);
898
899You can convert ASCII encodings to the required C<UTF-16BE> format using one of the many Unicode modules on CPAN. For example C<Unicode::Map> and C<Unicode::String>: L<http://search.cpan.org/author/MSCHWARTZ/Unicode-Map/Map.pm> and L<http://search.cpan.org/author/GAAS/Unicode-String/String.pm>.
900
901For a full list of the Perl Unicode modules see: L<http://search.cpan.org/search?query=unicode&mode=all>.
902
903C<UTF-16BE> is the format most often returned by C<Perl> modules that generate C<UTF-16>. To write C<UTF-16> strings in little-endian format use the C<write_utf16be_string_le()> method below.
904
905The C<write_utf16be_string()> method was previously called C<write_unicode()>. That, overly general, name is still supported but deprecated.
906
907See also the C<unicode_*.pl> programs in the examples directory of the distro.
908
909
910
911
912=head2 write_utf16le_string($row, $column, $string, $format)
913
914This method is the same as C<write_utf16be()> except that the string should be 16-bit characters in little-endian format. This is generally referred to as C<UTF-16LE>. See L<UNICODE IN EXCEL>.
915
916C<UTF-16> data can be changed from little-endian to big-endian format (and vice-versa) as follows:
917
918 $utf16be = pack 'n*', unpack 'v*', $utf16le;
919
920
921
922
923=head2 keep_leading_zeros()
924
925This method changes the default handling of integers with leading zeros when using the C<write()> method.
926
927The C<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 C<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.
928
929Zip 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.
930
931To get around this you can use one of three options. Write a formatted number, write the number as a string or use the C<keep_leading_zeros()> method to change the default behaviour of C<write()>:
932
933 # Implicitly write a number, the leading zero is removed: 1209
934 $worksheet->write('A1', '01209');
935
936 # Write a zero padded number using a format: 01209
937 my $format1 = $workbook->add_format(num_format => '00000');
938 $worksheet->write('A2', '01209', $format1);
939
940 # Write explicitly as a string: 01209
941 $worksheet->write_string('A3', '01209');
942
943 # Write implicitly as a string: 01209
944 $worksheet->keep_leading_zeros();
945 $worksheet->write('A4', '01209');
946
947
948The above code would generate a worksheet that looked like the following:
949
950 -----------------------------------------------------------
951 | | A | B | C | D | ...
952 -----------------------------------------------------------
953 | 1 | 1209 | | | | ...
954 | 2 | 01209 | | | | ...
955 | 3 | 01209 | | | | ...
956 | 4 | 01209 | | | | ...
957
958
959The 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 L<CELL FORMATTING>.
960
961It should be noted that if the user edits the data in examples C<A3> and C<A4> the strings will revert back to numbers. Again this is Excel's default behaviour. To avoid this you can use the text format C<@>:
962
963 # Format as a string (01209)
964 my $format2 = $workbook->add_format(num_format => '@');
965 $worksheet->write_string('A5', '01209', $format2);
966
967The C<keep_leading_zeros()> property is off by default. The C<keep_leading_zeros()> method takes 0 or 1 as an argument. It defaults to 1 if an argument isn't specified:
968
969 $worksheet->keep_leading_zeros(); # Set on
970 $worksheet->keep_leading_zeros(1); # Set on
971 $worksheet->keep_leading_zeros(0); # Set off
972
973See also the C<add_write_handler()> method.
974
975
976=head2 write_blank($row, $column, $format)
977
978Write a blank cell specified by C<$row> and C<$column>:
979
980 $worksheet->write_blank(0, 0, $format);
981
982This method is used to add formatting to a cell which doesn't contain a string or number value.
983
984Excel 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.
985
986As such, if you write an empty cell without formatting it is ignored:
987
988 $worksheet->write('A1', undef, $format); # write_blank()
989 $worksheet->write('A2', undef ); # Ignored
990
991This seemingly uninteresting fact means that you can write arrays of data without special treatment for undef or empty string values.
992
993See the note about L<Cell notation>.
994
995
996
997
998=head2 write_row($row, $column, $array_ref, $format)
999
1000The C<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 C<write()> method is then called for each element of the data. For example:
1001
1002 @array = ('awk', 'gawk', 'mawk');
1003 $array_ref = \@array;
1004
1005 $worksheet->write_row(0, 0, $array_ref);
1006
1007 # The above example is equivalent to:
1008 $worksheet->write(0, 0, $array[0]);
1009 $worksheet->write(0, 1, $array[1]);
1010 $worksheet->write(0, 2, $array[2]);
1011
1012
1013Note: For convenience the C<write()> method behaves in the same way as C<write_row()> if it is passed an array reference. Therefore the following two method calls are equivalent:
1014
1015 $worksheet->write_row('A1', $array_ref); # Write a row of data
1016 $worksheet->write( 'A1', $array_ref); # Same thing
1017
1018As with all of the write methods the C<$format> parameter is optional. If a format is specified it is applied to all the elements of the data array.
1019
1020Array references within the data will be treated as columns. This allows you to write 2D arrays of data in one go. For example:
1021
1022 @eec = (
1023 ['maggie', 'milly', 'molly', 'may' ],
1024 [13, 14, 15, 16 ],
1025 ['shell', 'star', 'crab', 'stone']
1026 );
1027
1028 $worksheet->write_row('A1', \@eec);
1029
1030
1031Would produce a worksheet as follows:
1032
1033 -----------------------------------------------------------
1034 | | A | B | C | D | E | ...
1035 -----------------------------------------------------------
1036 | 1 | maggie | 13 | shell | ... | ... | ...
1037 | 2 | milly | 14 | star | ... | ... | ...
1038 | 3 | molly | 15 | crab | ... | ... | ...
1039 | 4 | may | 16 | stone | ... | ... | ...
1040 | 5 | ... | ... | ... | ... | ... | ...
1041 | 6 | ... | ... | ... | ... | ... | ...
1042
1043
1044To write the data in a row-column order refer to the C<write_col()> method below.
1045
1046Any C<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.
1047
1048To find out more about array references refer to C<perlref> and C<perlreftut> in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to C<perllol>.
1049
1050The C<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 C<write()> method above.
1051
1052See also the C<write_arrays.pl> program in the C<examples> directory of the distro.
1053
1054The C<write_row()> method allows the following idiomatic conversion of a text file to an Excel file:
1055
1056 #!/usr/bin/perl -w
1057
1058 use strict;
1059 use Spreadsheet::WriteExcel;
1060
1061 my $workbook = Spreadsheet::WriteExcel->new('file.xls');
1062 my $worksheet = $workbook->add_worksheet();
1063
1064 open INPUT, 'file.txt' or die "Couldn't open file: $!";
1065
1066 $worksheet->write($.-1, 0, [split]) while <INPUT>;
1067
1068
1069
1070
1071=head2 write_col($row, $column, $array_ref, $format)
1072
1073The C<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 C<write()> method is then called for each element of the data. For example:
1074
1075 @array = ('awk', 'gawk', 'mawk');
1076 $array_ref = \@array;
1077
1078 $worksheet->write_col(0, 0, $array_ref);
1079
1080 # The above example is equivalent to:
1081 $worksheet->write(0, 0, $array[0]);
1082 $worksheet->write(1, 0, $array[1]);
1083 $worksheet->write(2, 0, $array[2]);
1084
1085As with all of the write methods the C<$format> parameter is optional. If a format is specified it is applied to all the elements of the data array.
1086
1087Array references within the data will be treated as rows. This allows you to write 2D arrays of data in one go. For example:
1088
1089 @eec = (
1090 ['maggie', 'milly', 'molly', 'may' ],
1091 [13, 14, 15, 16 ],
1092 ['shell', 'star', 'crab', 'stone']
1093 );
1094
1095 $worksheet->write_col('A1', \@eec);
1096
1097
1098Would produce a worksheet as follows:
1099
1100 -----------------------------------------------------------
1101 | | A | B | C | D | E | ...
1102 -----------------------------------------------------------
1103 | 1 | maggie | milly | molly | may | ... | ...
1104 | 2 | 13 | 14 | 15 | 16 | ... | ...
1105 | 3 | shell | star | crab | stone | ... | ...
1106 | 4 | ... | ... | ... | ... | ... | ...
1107 | 5 | ... | ... | ... | ... | ... | ...
1108 | 6 | ... | ... | ... | ... | ... | ...
1109
1110
1111To write the data in a column-row order refer to the C<write_row()> method above.
1112
1113Any C<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.
1114
1115As noted above the C<write()> method can be used as a synonym for C<write_row()> and C<write_row()> handles nested array refs as columns. Therefore, the following two method calls are equivalent although the more explicit call to C<write_col()> would be preferable for maintainability:
1116
1117 $worksheet->write_col('A1', $array_ref ); # Write a column of data
1118 $worksheet->write( 'A1', [ $array_ref ]); # Same thing
1119
1120To find out more about array references refer to C<perlref> and C<perlreftut> in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to C<perllol>.
1121
1122The C<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 C<write()> method above.
1123
1124See also the C<write_arrays.pl> program in the C<examples> directory of the distro.
1125
1126
1127
1128
1129=head2 write_date_time($row, $col, $date_string, $format)
1130
1131The C<write_date_time()> method can be used to write a date or time to the cell specified by C<$row> and C<$column>:
1132
1133 $worksheet->write_date_time('A1', '2004-05-13T23:20', $date_format);
1134
1135The C<$date_string> should be in the following format:
1136
1137 yyyy-mm-ddThh:mm:ss.sss
1138
1139This conforms to an ISO8601 date but it should be noted that the full range of ISO8601 formats are not supported.
1140
1141The following variations on the C<$date_string> parameter are permitted:
1142
1143 yyyy-mm-ddThh:mm:ss.sss # Standard format
1144 yyyy-mm-ddT # No time
1145 Thh:mm:ss.sss # No date
1146 yyyy-mm-ddThh:mm:ss.sssZ # Additional Z (but not time zones)
1147 yyyy-mm-ddThh:mm:ss # No fractional seconds
1148 yyyy-mm-ddThh:mm # No seconds
1149
1150Note that the C<T> is required in all cases.
1151
1152A date should always have a C<$format>, otherwise it will appear as a number, see L<DATES AND TIME IN EXCEL> and L<CELL FORMATTING>. Here is a typical example:
1153
1154 my $date_format = $workbook->add_format(num_format => 'mm/dd/yy');
1155 $worksheet->write_date_time('A1', '2004-05-13T23:20', $date_format);
1156
1157Valid 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.
1158
1159See also the date_time.pl program in the C<examples> directory of the distro.
1160
1161
1162
1163
1164=head2 write_url($row, $col, $url, $label, $format)
1165
1166Write a hyperlink to a URL in the cell specified by C<$row> and C<$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 C<$label> and the C<$format> are optional and their position is interchangeable.
1167
1168The label is written using the C<write()> method. Therefore it is possible to write strings, numbers or formulas as labels.
1169
1170There are four web style URI's supported: C<http://>, C<https://>, C<ftp://> and C<mailto:>:
1171
1172 $worksheet->write_url(0, 0, 'ftp://www.perl.org/' );
1173 $worksheet->write_url(1, 0, 'http://www.perl.com/', 'Perl home' );
1174 $worksheet->write_url('A3', 'http://www.perl.com/', $format );
1175 $worksheet->write_url('A4', 'http://www.perl.com/', 'Perl', $format);
1176 $worksheet->write_url('A5', 'mailto:jmcnamara@cpan.org' );
1177
1178There are two local URIs supported: C<internal:> and C<external:>. These are used for hyperlinks to internal worksheet references or external workbook and worksheet references:
1179
1180 $worksheet->write_url('A6', 'internal:Sheet2!A1' );
1181 $worksheet->write_url('A7', 'internal:Sheet2!A1', $format );
1182 $worksheet->write_url('A8', 'internal:Sheet2!A1:B2' );
1183 $worksheet->write_url('A9', q{internal:'Sales Data'!A1} );
1184 $worksheet->write_url('A10', 'external:c:\temp\foo.xls' );
1185 $worksheet->write_url('A11', 'external:c:\temp\foo.xls#Sheet2!A1' );
1186 $worksheet->write_url('A12', 'external:..\..\..\foo.xls' );
1187 $worksheet->write_url('A13', 'external:..\..\..\foo.xls#Sheet2!A1' );
1188 $worksheet->write_url('A13', 'external:\\\\NETWORK\share\foo.xls' );
1189
1190All of the these URI types are recognised by the C<write()> method, see above.
1191
1192Worksheet references are typically of the form C<Sheet1!A1>. You can also refer to a worksheet range using the standard Excel notation: C<Sheet1!A1:B2>.
1193
1194In external links the workbook and worksheet name must be separated by the C<#> character: C<external:Workbook.xls#Sheet1!A1'>.
1195
1196You can also link to a named range in the target worksheet. For example say you have a named range called C<my_name> in the workbook C<c:\temp\foo.xls> you could link to it as follows:
1197
1198 $worksheet->write_url('A14', 'external:c:\temp\foo.xls#my_name');
1199
1200Note, you cannot currently create named ranges with C<Spreadsheet::WriteExcel>.
1201
1202Excel requires that worksheet names containing spaces or non alphanumeric characters are single quoted as follows C<'Sales Data'!A1>. If you need to do this in a single quoted string then you can either escape the single quotes C<\'> or use the quote operator C<q{}> as described in C<perlop> in the main Perl documentation.
1203
1204Links to network files are also supported. MS/Novell Network files normally begin with two back slashes as follows C<\\NETWORK\etc>. In order to generate this in a single or double quoted string you will have to escape the backslashes, C<'\\\\NETWORK\etc'>.
1205
1206If you are using double quote strings then you should be careful to escape anything that looks like a metacharacter. For more information see C<perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?>.
1207
1208Finally, you can avoid most of these quoting problems by using forward slashes. These are translated internally to backslashes:
1209
1210 $worksheet->write_url('A14', "external:c:/temp/foo.xls" );
1211 $worksheet->write_url('A15', 'external://NETWORK/share/foo.xls' );
1212
1213See also, the note about L<Cell notation>.
1214
1215
1216
1217
1218=head2 write_url_range($row1, $col1, $row2, $col2, $url, $string, $format)
1219
1220This method is essentially the same as the C<write_url()> method described above. The main difference is that you can specify a link for a range of cells:
1221
1222 $worksheet->write_url(0, 0, 0, 3, 'ftp://www.perl.org/' );
1223 $worksheet->write_url(1, 0, 0, 3, 'http://www.perl.com/', 'Perl home');
1224 $worksheet->write_url('A3:D3', 'internal:Sheet2!A1' );
1225 $worksheet->write_url('A4:D4', 'external:c:\temp\foo.xls' );
1226
1227
1228This method is generally only required when used in conjunction with merged cells. See the C<merge_range()> method and the C<merge> property of a Format object, L<CELL FORMATTING>.
1229
1230There is no way to force this behaviour through the C<write()> method.
1231
1232The parameters C<$string> and the C<$format> are optional and their position is interchangeable. However, they are applied only to the first cell in the range.
1233
1234See also, the note about L<Cell notation>.
1235
1236
1237
1238
1239=head2 write_formula($row, $column, $formula, $format, $value)
1240
1241Write a formula or function to the cell specified by C<$row> and C<$column>:
1242
1243 $worksheet->write_formula(0, 0, '=$B$3 + B4' );
1244 $worksheet->write_formula(1, 0, '=SIN(PI()/4)');
1245 $worksheet->write_formula(2, 0, '=SUM(B1:B5)' );
1246 $worksheet->write_formula('A4', '=IF(A3>1,"Yes", "No")' );
1247 $worksheet->write_formula('A5', '=AVERAGE(1, 2, 3, 4)' );
1248 $worksheet->write_formula('A6', '=DATEVALUE("1-Jan-2001")');
1249
1250See the note about L<Cell notation>. For more information about writing Excel formulas see L<FORMULAS AND FUNCTIONS IN EXCEL>
1251
1252See also the section "Improving performance when working with formulas" and the C<store_formula()> and C<repeat_formula()> methods.
1253
1254If 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 C<$value> is added at the end of the argument list:
1255
1256 $worksheet->write('A1', '=2+2', $format, 4);
1257
1258However, this probably isn't something that will ever need to do. If you do use this feature then do so with care.
1259
1260
1261
1262
1263=head2 store_formula($formula)
1264
1265The C<store_formula()> method is used in conjunction with C<repeat_formula()> to speed up the generation of repeated formulas. See "Improving performance when working with formulas" in L<FORMULAS AND FUNCTIONS IN EXCEL>.
1266
1267The C<store_formula()> method pre-parses a textual representation of a formula and stores it for use at a later stage by the C<repeat_formula()> method.
1268
1269C<store_formula()> carries the same speed penalty as C<write_formula()>. However, in practice it will be used less frequently.
1270
1271The return value of this method is a scalar that can be thought of as a reference to a formula.
1272
1273 my $sin = $worksheet->store_formula('=SIN(A1)');
1274 my $cos = $worksheet->store_formula('=COS(A1)');
1275
1276 $worksheet->repeat_formula('B1', $sin, $format, 'A1', 'A2');
1277 $worksheet->repeat_formula('C1', $cos, $format, 'A1', 'A2');
1278
1279Although C<store_formula()> is a worksheet method the return value can be used in any worksheet:
1280
1281 my $now = $worksheet->store_formula('=NOW()');
1282
1283 $worksheet1->repeat_formula('B1', $now);
1284 $worksheet2->repeat_formula('B1', $now);
1285 $worksheet3->repeat_formula('B1', $now);
1286
1287
1288
1289=head2 repeat_formula($row, $col, $formula, $format, ($pattern => $replace, ...))
1290
1291
1292The C<repeat_formula()> method is used in conjunction with C<store_formula()> to speed up the generation of repeated formulas. See "Improving performance when working with formulas" in L<FORMULAS AND FUNCTIONS IN EXCEL>.
1293
1294In many respects C<repeat_formula()> behaves like C<write_formula()> except that it is significantly faster.
1295
1296The C<repeat_formula()> method creates a new formula based on the pre-parsed tokens returned by C<store_formula()>. The new formula is generated by substituting C<$pattern>, C<$replace> pairs in the stored formula:
1297
1298 my $formula = $worksheet->store_formula('=A1 * 3 + 50');
1299
1300 for my $row (0..99) {
1301 $worksheet->repeat_formula($row, 1, $formula, $format, 'A1', 'A'.($row +1));
1302 }
1303
1304It should be noted that C<repeat_formula()> doesn't modify the tokens. In the above example the substitution is always made against the original token, C<A1>, which doesn't change.
1305
1306As usual, you can use C<undef> if you don't wish to specify a C<$format>:
1307
1308 $worksheet->repeat_formula('B2', $formula, $format, 'A1', 'A2');
1309 $worksheet->repeat_formula('B3', $formula, undef, 'A1', 'A3');
1310
1311The substitutions are made from left to right and you can use as many C<$pattern>, C<$replace> pairs as you need. However, each substitution is made only once:
1312
1313 my $formula = $worksheet->store_formula('=A1 + A1');
1314
1315 # Gives '=B1 + A1'
1316 $worksheet->repeat_formula('B1', $formula, undef, 'A1', 'B1');
1317
1318 # Gives '=B1 + B1'
1319 $worksheet->repeat_formula('B2', $formula, undef, ('A1', 'B1') x 2);
1320
1321Since the C<$pattern> is interpolated each time that it is used it is worth using the C<qr> operator to quote the pattern. The C<qr> operator is explained in the C<perlop> man page.
1322
1323 $worksheet->repeat_formula('B1', $formula, $format, qr/A1/, 'A2');
1324
1325Care should be taken with the values that are substituted. The formula returned by C<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.
1326
1327You should also be careful to avoid false matches. For example the following snippet is meant to change the stored formula in steps from C<=A1 + SIN(A1)> to C<=A10 + SIN(A10)>.
1328
1329 my $formula = $worksheet->store_formula('=A1 + SIN(A1)');
1330
1331 for my $row (1 .. 10) {
1332 $worksheet->repeat_formula($row -1, 1, $formula, undef,
1333 qw/A1/, 'A' . $row, #! Bad.
1334 qw/A1/, 'A' . $row #! Bad.
1335 );
1336 }
1337
1338However it contains a bug. In the last iteration of the loop when C<$row> is 10 the following substitutions will occur:
1339
1340 s/A1/A10/; changes =A1 + SIN(A1) to =A10 + SIN(A1)
1341 s/A1/A10/; changes =A10 + SIN(A1) to =A100 + SIN(A1) # !!
1342
1343The solution in this case is to use a more explicit match such as C<qw/^A1$/>:
1344
1345 $worksheet->repeat_formula($row -1, 1, $formula, undef,
1346 qw/^A1$/, 'A' . $row,
1347 qw/^A1$/, 'A' . $row
1348 );
1349
1350Another 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 C<=A10 + A11> to C<=A11 + A12>:
1351
1352 my $formula = $worksheet->store_formula('=A10 + A11');
1353
1354 $worksheet->repeat_formula('A1', $formula, undef,
1355 qw/A10/, 'A11', #! Bad.
1356 qw/A11/, 'A12' #! Bad.
1357 );
1358
1359However, the actual substitution yields C<=A12 + A11>:
1360
1361 s/A10/A11/; changes =A10 + A11 to =A11 + A11
1362 s/A11/A12/; changes =A11 + A11 to =A12 + A11 # !!
1363
1364The 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 C<=X10 + Y11>:
1365
1366 my $formula = $worksheet->store_formula('=X10 + Y11');
1367
1368 $worksheet->repeat_formula('A1', $formula, undef,
1369 qw/X10/, 'A11',
1370 qw/Y11/, 'A12'
1371 );
1372
1373
1374If you think that you have a problem related to a false match you can check the tokens that you are substituting against as follows.
1375
1376 my $formula = $worksheet->store_formula('=A1*5+4');
1377 print "@$formula\n";
1378
1379See also the C<repeat.pl> program in the C<examples> directory of the distro.
1380
1381
1382
1383
1384=head2 write_comment($row, $column, $string, ...)
1385
1386The C<write_comment()> method is used to add a comment to a cell. A cell comment is indicated 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.
1387
1388The following example shows how to add a comment to a cell:
1389
1390 $worksheet->write (2, 2, 'Hello');
1391 $worksheet->write_comment(2, 2, 'This is a comment.');
1392
1393As usual you can replace the C<$row> and C<$column> parameters with an C<A1> cell reference. See the note about L<Cell notation>.
1394
1395 $worksheet->write ('C3', 'Hello');
1396 $worksheet->write_comment('C3', 'This is a comment.');
1397
1398On systems with C<perl 5.8> and later the C<write_comment()> method will also handle strings in C<UTF-8> format.
1399
1400 $worksheet->write_comment('C3', "\x{263a}"); # Smiley
1401 $worksheet->write_comment('C4', 'Comment ca va?');
1402
1403In addition to the basic 3 argument form of C<write_comment()> you can pass in several optional key/value pairs to control the format of the comment. For example:
1404
1405 $worksheet->write_comment('C3', 'Hello', visible => 1, author => 'Perl');
1406
1407Most 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:
1408
1409 encoding
1410 author
1411 author_encoding
1412 visible
1413 x_scale
1414 width
1415 y_scale
1416 height
1417 color
1418 start_cell
1419 start_row
1420 start_col
1421 x_offset
1422 y_offset
1423
1424
1425=over 4
1426
1427=item Option: encoding
1428
1429This option is used to indicate that the comment string is encoded as C<UTF-16BE>.
1430
1431 my $comment = pack 'n', 0x263a; # UTF-16BE Smiley symbol
1432
1433 $worksheet->write_comment('C3', $comment, encoding => 1);
1434
1435If you wish to use Unicode characters in the comment string then the preferred method is to use perl 5.8 and C<UTF-8> strings, see L<UNICODE IN EXCEL>.
1436
1437
1438=item Option: author
1439
1440This 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 usually of interest in corporate environments where several people might review and provide comments to a workbook.
1441
1442 $worksheet->write_comment('C3', 'Atonement', author => 'Ian McEwan');
1443
1444
1445=item Option: author_encoding
1446
1447This option is used to indicate that the author string is encoded as C<UTF-16BE>.
1448
1449
1450=item Option: visible
1451
1452This 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::WriteExcel individual comments can be made visible as follows:
1453
1454 $worksheet->write_comment('C3', 'Hello', visible => 1);
1455
1456It is possible to make all comments in a worksheet visible using the C<show_comments()> worksheet method (see below). Alternatively, if all of the cell comments have been made visible you can hide individual comments:
1457
1458 $worksheet->write_comment('C3', 'Hello', visible => 0);
1459
1460
1461=item Option: x_scale
1462
1463This option is used to set the width of the cell comment box as a factor of the default width.
1464
1465 $worksheet->write_comment('C3', 'Hello', x_scale => 2);
1466 $worksheet->write_comment('C4', 'Hello', x_scale => 4.2);
1467
1468
1469=item Option: width
1470
1471This option is used to set the width of the cell comment box explicitly in pixels.
1472
1473 $worksheet->write_comment('C3', 'Hello', width => 200);
1474
1475
1476=item Option: y_scale
1477
1478This option is used to set the height of the cell comment box as a factor of the default height.
1479
1480 $worksheet->write_comment('C3', 'Hello', y_scale => 2);
1481 $worksheet->write_comment('C4', 'Hello', y_scale => 4.2);
1482
1483
1484=item Option: height
1485
1486This option is used to set the height of the cell comment box explicitly in pixels.
1487
1488 $worksheet->write_comment('C3', 'Hello', height => 200);
1489
1490
1491=item Option: color
1492
1493This 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 L<COLOURS IN EXCEL>.
1494
1495 $worksheet->write_comment('C3', 'Hello', color => 'green');
1496 $worksheet->write_comment('C4', 'Hello', color => 0x35); # Orange
1497
1498
1499=item Option: start_cell
1500
1501This 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 comment relates. However, you can change this behaviour if you wish. In the following example the comment which would appear by default in cell C<D2> is moved to C<E2>.
1502
1503 $worksheet->write_comment('C3', 'Hello', start_cell => 'E2');
1504
1505
1506=item Option: start_row
1507
1508This option is used to set the row in which the comment will appear. See the C<start_cell> option above. The row is zero indexed.
1509
1510 $worksheet->write_comment('C3', 'Hello', start_row => 0);
1511
1512
1513=item Option: start_col
1514
1515This option is used to set the column in which the comment will appear. See the C<start_cell> option above. The column is zero indexed.
1516
1517 $worksheet->write_comment('C3', 'Hello', start_col => 4);
1518
1519
1520=item Option: x_offset
1521
1522This option is used to change the x offset, in pixels, of a comment within a cell:
1523
1524 $worksheet->write_comment('C3', $comment, x_offset => 30);
1525
1526
1527=item Option: y_offset
1528
1529This option is used to change the y offset, in pixels, of a comment within a cell:
1530
1531 $worksheet->write_comment('C3', $comment, x_offset => 30);
1532
1533
1534=back
1535
1536You can apply as many of these options as you require.
1537
1538B<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 C<set_row()> method to specify the row height explicitly and avoid this problem.
1539
1540
1541=head2 show_comments()
1542
1543This method is used to make all cell comments visible when a worksheet is opened.
1544
1545Individual comments can be made visible using the C<visible> parameter of the C<write_comment> method (see above):
1546
1547 $worksheet->write_comment('C3', 'Hello', visible => 1);
1548
1549If all of the cell comments have been made visible you can hide individual comments as follows:
1550
1551 $worksheet->write_comment('C3', 'Hello', visible => 0);
1552
1553
1554
1555
1556=head2 add_write_handler($re, $code_ref)
1557
1558This method is used to extend the Spreadsheet::WriteExcel write() method to handle user defined data.
1559
1560If you refer to the section on C<write()> above you will see that it acts as an alias for several more specific C<write_*> methods. However, it doesn't always act in exactly the way that you would like it to.
1561
1562One solution is to filter the input data yourself and call the appropriate C<write_*> method. Another approach is to use the C<add_write_handler()> method to add your own automated behaviour to C<write()>.
1563
1564The C<add_write_handler()> method take two arguments, C<$re>, a regular expression to match incoming data and C<$code_ref> a callback function to handle the matched data:
1565
1566 $worksheet->add_write_handler(qr/^\d\d\d\d$/, \&my_write);
1567
1568(In the these examples the C<qr> operator is used to quote the regular expression strings, see L<perlop> for more details).
1569
1570The 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:
1571
1572 $worksheet->add_write_handler(qr/^\d{7}$/, \&write_my_id);
1573
1574
1575 sub write_my_id {
1576 my $worksheet = shift;
1577 return $worksheet->write_string(@_);
1578 }
1579
1580* You could also use the C<keep_leading_zeros()> method for this.
1581
1582Then if you call C<write()> with an appropriate string it will be handled automatically:
1583
1584 # Writes 0000000. It would normally be written as a number; 0.
1585 $worksheet->write('A1', '0000000');
1586
1587The callback function will receive a reference to the calling worksheet and all of the other arguments that were passed to C<write()>. The callback will see an C<@_> argument list that looks like the following:
1588
1589 $_[0] A ref to the calling worksheet. *
1590 $_[1] Zero based row number.
1591 $_[2] Zero based column number.
1592 $_[3] A number or string or token.
1593 $_[4] A format ref if any.
1594 $_[5] Any other arguments.
1595 ...
1596
1597 * It is good style to shift this off the list so the @_ is the same
1598 as the argument list seen by write().
1599
1600Your callback should C<return()> the return value of the C<write_*> method that was called or C<undef> to indicate that you rejected the match and want C<write()> to continue as normal.
1601
1602So 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:
1603
1604
1605 sub write_my_id {
1606 my $worksheet = shift;
1607 my $col = $_[1];
1608
1609 if ($col == 0) {
1610 return $worksheet->write_string(@_);
1611 }
1612 else {
1613 # Reject the match and return control to write()
1614 return undef;
1615 }
1616 }
1617
1618Now, you will get different behaviour for the first column and other columns:
1619
1620 $worksheet->write('A1', '0000000'); # Writes 0000000
1621 $worksheet->write('B1', '0000000'); # Writes 0
1622
1623
1624You may add more than one handler in which case they will be called in the order that they were added.
1625
1626Note, the C<add_write_handler()> method is particularly suited for handling dates.
1627
1628See the C<write_handler 1-4> programs in the C<examples> directory for further examples.
1629
1630
1631
1632
1633=head2 insert_image($row, $col, $filename, $x, $y, $scale_x, $scale_y)
1634
1635This method can be used to insert a image into a worksheet. The image can be in PNG, JPEG or BMP format. The C<$x>, C<$y>, C<$scale_x> and C<$scale_y> parameters are optional.
1636
1637 $worksheet1->insert_image('A1', 'perl.bmp');
1638 $worksheet2->insert_image('A1', '../images/perl.bmp');
1639 $worksheet3->insert_image('A1', '.c:\images\perl.bmp');
1640
1641The parameters C<$x> and C<$y> can be used to specify an offset from the top left hand corner of the cell specified by C<$row> and C<$col>. The offset values are in pixels.
1642
1643 $worksheet1->insert_image('A1', 'perl.bmp', 32, 10);
1644
1645The 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:
1646
1647 Wp = int(12We) if We < 1
1648 Wp = int(7We +5) if We >= 1
1649 Hp = int(4/3He)
1650
1651 where:
1652 We is the cell width in Excels units
1653 Wp is width in pixels
1654 He is the cell height in Excels units
1655 Hp is height in pixels
1656
1657The 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.
1658
1659The parameters C<$scale_x> and C<$scale_y> can be used to scale the inserted image horizontally and vertically:
1660
1661 # Scale the inserted image: width x 2.0, height x 0.8
1662 $worksheet->insert_image('A1', 'perl.bmp', 0, 0, 2, 0.8);
1663
1664See also the C<images.pl> program in the C<examples> directory of the distro.
1665
1666Note: you must call C<set_row()> or C<set_column()> before C<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 C<set_row()> if it contains a font size that will change the row height.
1667
1668
1669BMP images must be 24 bit, true colour, bitmaps. In general it is best to avoid BMP images since they aren't compressed. The older C<insert_bitmap()> method is still supported but deprecated.
1670
1671
1672
1673
1674=head2 insert_chart($row, $col, $chart, $x, $y, $scale_x, $scale_y)
1675
1676This method can be used to insert a Chart object into a worksheet. The Chart must be created by the C<add_chart()> Workbook method and it must have the C<embedded> option set.
1677
1678 my $chart = $workbook->add_chart( type => 'line', embedded => 1 );
1679
1680 # Configure the chart.
1681 ...
1682
1683 # Insert the chart into the a worksheet.
1684 $worksheet->insert_chart('E2', $chart);
1685
1686See C<add_chart()> for details on how to create the Chart object and L<Spreadsheet::WriteExcel::Chart> for details on how to configure it. See also the C<chart_*.pl> programs in the examples directory of the distro.
1687
1688The C<$x>, C<$y>, C<$scale_x> and C<$scale_y> parameters are optional.
1689
1690The parameters C<$x> and C<$y> can be used to specify an offset from the top left hand corner of the cell specified by C<$row> and C<$col>. The offset values are in pixels. See the C<insert_image> method above for more information on sizes.
1691
1692 $worksheet1->insert_chart('E2', $chart, 3, 3);
1693
1694The parameters C<$scale_x> and C<$scale_y> can be used to scale the inserted image horizontally and vertically:
1695
1696 # Scale the width by 120% and the height by 150%
1697 $worksheet->insert_chart('E2', $chart, 0, 0, 1.2, 1.5);
1698
1699The 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.
1700
1701Note: you must call C<set_row()> or C<set_column()> before C<insert_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 C<set_row()> if it contains a font size that will change the row height.
1702
1703
1704
1705
1706=head2 embed_chart($row, $col, $filename, $x, $y, $scale_x, $scale_y)
1707
1708This method can be used to insert a externally generated chart into a worksheet. The chart must first be extracted from an existing Excel file. This feature is semi-deprecated in favour of the "native" charts created using C<add_chart()>. Read C<external_charts.txt> (or C<.pod>) in the external_charts directory of the distro for a full explanation.
1709
1710Here is an example:
1711
1712 $worksheet->embed_chart('B2', 'sales_chart.bin');
1713
1714The C<$x>, C<$y>, C<$scale_x> and C<$scale_y> parameters are optional. See C<insert_chart()> above for details.
1715
1716
1717
1718
1719=head2 data_validation()
1720
1721The C<data_validation()> method is used to construct an Excel data validation or to limit the user input to a dropdown list of values.
1722
1723
1724 $worksheet->data_validation('B3',
1725 {
1726 validate => 'integer',
1727 criteria => '>',
1728 value => 100,
1729 });
1730
1731 $worksheet->data_validation('B5:B9',
1732 {
1733 validate => 'list',
1734 value => ['open', 'high', 'close'],
1735 });
1736
1737This method contains a lot of parameters and is described in detail in a separate section L<DATA VALIDATION IN EXCEL>.
1738
1739
1740See also the C<data_validate.pl> program in the examples directory of the distro
1741
1742
1743
1744
1745=head2 get_name()
1746
1747The C<get_name()> method is used to retrieve the name of a worksheet. For example:
1748
1749 foreach my $sheet ($workbook->sheets()) {
1750 print $sheet->get_name();
1751 }
1752
1753For reasons related to the design of Spreadsheet::WriteExcel and to the internals of Excel there is no C<set_name()> method. The only way to set the worksheet name is via the C<add_worksheet()> method.
1754
1755
1756
1757
1758=head2 activate()
1759
1760The C<activate()> method is used to specify which worksheet is initially visible in a multi-sheet workbook:
1761
1762 $worksheet1 = $workbook->add_worksheet('To');
1763 $worksheet2 = $workbook->add_worksheet('the');
1764 $worksheet3 = $workbook->add_worksheet('wind');
1765
1766 $worksheet3->activate();
1767
1768This is similar to the Excel VBA activate method. More than one worksheet can be selected via the C<select()> method, see below, however only one worksheet can be active.
1769
1770The default active worksheet is the first worksheet.
1771
1772
1773
1774
1775=head2 select()
1776
1777The C<select()> method is used to indicate that a worksheet is selected in a multi-sheet workbook:
1778
1779 $worksheet1->activate();
1780 $worksheet2->select();
1781 $worksheet3->select();
1782
1783A 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 worksheet that has been activated via the C<activate()> method will also appear as selected.
1784
1785
1786
1787
1788=head2 hide()
1789
1790The C<hide()> method is used to hide a worksheet:
1791
1792 $worksheet2->hide();
1793
1794You may wish to hide a worksheet in order to avoid confusing a user with intermediate data or calculations.
1795
1796A hidden worksheet can not be activated or selected so this method is mutually exclusive with the C<activate()> and C<select()> methods. In addition, since the first worksheet will default to being the active worksheet, you cannot hide the first worksheet without activating another sheet:
1797
1798 $worksheet2->activate();
1799 $worksheet1->hide();
1800
1801
1802
1803
1804=head2 set_first_sheet()
1805
1806The C<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 C<set_first_sheet()>:
1807
1808 for (1..20) {
1809 $workbook->add_worksheet;
1810 }
1811
1812 $worksheet21 = $workbook->add_worksheet();
1813 $worksheet22 = $workbook->add_worksheet();
1814
1815 $worksheet21->set_first_sheet();
1816 $worksheet22->activate();
1817
1818This method is not required very often. The default value is the first worksheet.
1819
1820
1821
1822
1823=head2 protect($password)
1824
1825The C<protect()> method is used to protect a worksheet from modification:
1826
1827 $worksheet->protect();
1828
1829It can be turned off in Excel via the C<Tools-E<gt>Protection-E<gt>Unprotect Sheet> menu command.
1830
1831The C<protect()> method also has the effect of enabling a cell's C<locked> and C<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.
1832
1833 # Set some format properties
1834 my $unlocked = $workbook->add_format(locked => 0);
1835 my $hidden = $workbook->add_format(hidden => 1);
1836
1837 # Enable worksheet protection
1838 $worksheet->protect();
1839
1840 # This cell cannot be edited, it is locked by default
1841 $worksheet->write('A1', '=1+2');
1842
1843 # This cell can be edited
1844 $worksheet->write('A2', '=1+2', $unlocked);
1845
1846 # The formula in this cell isn't visible
1847 $worksheet->write('A3', '=1+2', $hidden);
1848
1849See also the C<set_locked> and C<set_hidden> format methods in L<CELL FORMATTING>.
1850
1851You can optionally add a password to the worksheet protection:
1852
1853 $worksheet->protect('drowssap');
1854
1855Note, 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 C<Spreadsheet::WriteExcel>.
1856
1857
1858
1859
1860=head2 set_selection($first_row, $first_col, $last_row, $last_col)
1861
1862This 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 C<$last_row> and C<$last_col> can be omitted. The active cell within a selected range is determined by the order in which C<$first> and C<$last> are specified. It is also possible to specify a cell or a range using A1 notation. See the note about L<Cell notation>.
1863
1864Examples:
1865
1866 $worksheet1->set_selection(3, 3); # 1. Cell D4.
1867 $worksheet2->set_selection(3, 3, 6, 6); # 2. Cells D4 to G7.
1868 $worksheet3->set_selection(6, 6, 3, 3); # 3. Cells G7 to D4.
1869 $worksheet4->set_selection('D4'); # Same as 1.
1870 $worksheet5->set_selection('D4:G7'); # Same as 2.
1871 $worksheet6->set_selection('G7:D4'); # Same as 3.
1872
1873The default cell selections is (0, 0), 'A1'.
1874
1875
1876
1877
1878=head2 set_row($row, $height, $format, $hidden, $level, $collapsed)
1879
1880This method can be used to change the default properties of a row. All parameters apart from C<$row> are optional.
1881
1882The most common use for this method is to change the height of a row:
1883
1884 $worksheet->set_row(0, 20); # Row 1 height set to 20
1885
1886If you wish to set the format without changing the height you can pass C<undef> as the height parameter:
1887
1888 $worksheet->set_row(0, undef, $format);
1889
1890The C<$format> parameter will be applied to any cells in the row that don't have a format. For example
1891
1892 $worksheet->set_row(0, undef, $format1); # Set the format for row 1
1893 $worksheet->write('A1', 'Hello'); # Defaults to $format1
1894 $worksheet->write('B1', 'Hello', $format2); # Keeps $format2
1895
1896If you wish to define a row format in this way you should call the method before any calls to C<write()>. Calling it afterwards will overwrite any format that was previously specified.
1897
1898The C<$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:
1899
1900 $worksheet->set_row(0, 20, $format, 1);
1901 $worksheet->set_row(1, undef, undef, 1);
1902
1903The C<$level> parameter is used to set the outline level of the row. Outlines are described in L<OUTLINES AND GROUPING IN EXCEL>. Adjacent rows with the same outline level are grouped together into a single outline.
1904
1905The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed):
1906
1907 $worksheet->set_row(1, undef, undef, 0, 1);
1908 $worksheet->set_row(2, undef, undef, 0, 1);
1909
1910The C<$hidden> parameter can also be used to hide collapsed outlined rows when used in conjunction with the C<$level> parameter.
1911
1912 $worksheet->set_row(1, undef, undef, 1, 1);
1913 $worksheet->set_row(2, undef, undef, 1, 1);
1914
1915For collapsed outlines you should also indicate which row has the collapsed C<+> symbol using the optional C<$collapsed> parameter.
1916
1917 $worksheet->set_row(3, undef, undef, 0, 0, 1);
1918
1919For a more complete example see the C<outline.pl> and C<outline_collapsed.pl> programs in the examples directory of the distro.
1920
1921Excel allows up to 7 outline levels. Therefore the C<$level> parameter should be in the range C<0 E<lt>= $level E<lt>= 7>.
1922
1923
1924
1925
1926=head2 set_column($first_col, $last_col, $width, $format, $hidden, $level, $collapsed)
1927
1928This method can be used to change the default properties of a single column or a range of columns. All parameters apart from C<$first_col> and C<$last_col> are optional.
1929
1930If C<set_column()> is applied to a single column the value of C<$first_col> and C<$last_col> should be the same. In the case where C<$last_col> is zero it is set to the same value as C<$first_col>.
1931
1932It is also possible, and generally clearer, to specify a column range using the form of A1 notation used for columns. See the note about L<Cell notation>.
1933
1934Examples:
1935
1936 $worksheet->set_column(0, 0, 20); # Column A width set to 20
1937 $worksheet->set_column(1, 3, 30); # Columns B-D width set to 30
1938 $worksheet->set_column('E:E', 20); # Column E width set to 20
1939 $worksheet->set_column('F:H', 30); # Columns F-H width set to 30
1940
1941The width corresponds to the column width value that is specified in Excel. It is approximately 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.
1942
1943As usual the C<$format> parameter is optional, for additional information, see L<CELL FORMATTING>. If you wish to set the format without changing the width you can pass C<undef> as the width parameter:
1944
1945 $worksheet->set_column(0, 0, undef, $format);
1946
1947The C<$format> parameter will be applied to any cells in the column that don't have a format. For example
1948
1949 $worksheet->set_column('A:A', undef, $format1); # Set format for col 1
1950 $worksheet->write('A1', 'Hello'); # Defaults to $format1
1951 $worksheet->write('A2', 'Hello', $format2); # Keeps $format2
1952
1953If you wish to define a column format in this way you should call the method before any calls to C<write()>. If you call it afterwards it won't have any effect.
1954
1955A default row format takes precedence over a default column format
1956
1957 $worksheet->set_row(0, undef, $format1); # Set format for row 1
1958 $worksheet->set_column('A:A', undef, $format2); # Set format for col 1
1959 $worksheet->write('A1', 'Hello'); # Defaults to $format1
1960 $worksheet->write('A2', 'Hello'); # Defaults to $format2
1961
1962The C<$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:
1963
1964 $worksheet->set_column('D:D', 20, $format, 1);
1965 $worksheet->set_column('E:E', undef, undef, 1);
1966
1967The C<$level> parameter is used to set the outline level of the column. Outlines are described in L<OUTLINES AND GROUPING IN EXCEL>. Adjacent columns with the same outline level are grouped together into a single outline.
1968
1969The following example sets an outline level of 1 for columns B to G:
1970
1971 $worksheet->set_column('B:G', undef, undef, 0, 1);
1972
1973The C<$hidden> parameter can also be used to hide collapsed outlined columns when used in conjunction with the C<$level> parameter.
1974
1975 $worksheet->set_column('B:G', undef, undef, 1, 1);
1976
1977For collapsed outlines you should also indicate which row has the collapsed C<+> symbol using the optional C<$collapsed> parameter.
1978
1979 $worksheet->set_column('H:H', undef, undef, 0, 0, 1);
1980
1981For a more complete example see the C<outline.pl> and C<outline_collapsed.pl> programs in the examples directory of the distro.
1982
1983Excel allows up to 7 outline levels. Therefore the C<$level> parameter should be in the range C<0 E<lt>= $level E<lt>= 7>.
1984
1985
1986
1987
1988=head2 outline_settings($visible, $symbols_below, $symbols_right, $auto_style)
1989
1990The C<outline_settings()> method is used to control the appearance of outlines in Excel. Outlines are described in L<OUTLINES AND GROUPING IN EXCEL>.
1991
1992The C<$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 setting is 1 for visible outlines.
1993
1994 $worksheet->outline_settings(0);
1995
1996The C<$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.
1997
1998The C<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.
1999
2000The C<$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 generated by C<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.
2001
2002The default settings for all of these parameters correspond to Excel's default parameters.
2003
2004
2005The worksheet parameters controlled by C<outline_settings()> are rarely used.
2006
2007
2008
2009
2010=head2 freeze_panes($row, $col, $top_row, $left_col)
2011
2012This 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 C<Window-E<gt>Freeze Panes> menu command in Excel
2013
2014The parameters C<$row> and C<$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.
2015
2016You can set one of the C<$row> and C<$col> parameters as zero if you do not want either a vertical or horizontal split.
2017
2018Examples:
2019
2020 $worksheet->freeze_panes(1, 0); # Freeze the first row
2021 $worksheet->freeze_panes('A2'); # Same using A1 notation
2022 $worksheet->freeze_panes(0, 1); # Freeze the first column
2023 $worksheet->freeze_panes('B1'); # Same using A1 notation
2024 $worksheet->freeze_panes(1, 2); # Freeze first row and first 2 columns
2025 $worksheet->freeze_panes('C2'); # Same using A1 notation
2026
2027The parameters C<$top_row> and C<$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:
2028
2029 $worksheet->freeze_panes(1, 0, 20, 0);
2030
2031You cannot use A1 notation for the C<$top_row> and C<$left_col> parameters.
2032
2033
2034See also the C<panes.pl> program in the C<examples> directory of the distribution.
2035
2036
2037
2038
2039=head2 split_panes($y, $x, $top_row, $left_col)
2040
2041This method can be used to divide a worksheet into horizontal or vertical regions known as panes. This method is different from the C<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.
2042
2043The parameters C<$y> and C<$x> are used to specify the vertical and horizontal position of the split. The units for C<$y> and C<$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 C<$y> and C<$x> parameters in terms of the row heights and column widths that you have set or the default values which are C<12.75> for a row and C<8.43> for a column.
2044
2045You can set one of the C<$y> and C<$x> parameters as zero if you do not want either a vertical or horizontal split. The parameters C<$top_row> and C<$left_col> are optional. They are used to specify the top-most or left-most visible row or column in the bottom-right pane.
2046
2047Example:
2048
2049 $worksheet->split_panes(12.75, 0, 1, 0); # First row
2050 $worksheet->split_panes(0, 8.43, 0, 1); # First column
2051 $worksheet->split_panes(12.75, 8.43, 1, 1); # First row and column
2052
2053You cannot use A1 notation with this method.
2054
2055See also the C<freeze_panes()> method and the C<panes.pl> program in the C<examples> directory of the distribution.
2056
2057
2058Note: This C<split_panes()> method was called C<thaw_panes()> in older versions. The older name is still available for backwards compatibility.
2059
2060
2061
2062
2063=head2 merge_range($first_row, $first_col, $last_row, $last_col, $token, $format, $utf_16_be)
2064
2065Merging cells can be achieved by setting the C<merge> property of a Format object, see L<CELL FORMATTING>. However, this only allows simple Excel5 style horizontal merging which Excel refers to as "center across selection".
2066
2067The C<merge_range()> method allows you to do Excel97+ style formatting where the cells can contain other types of alignment in addition to the merging:
2068
2069 my $format = $workbook->add_format(
2070 border => 6,
2071 valign => 'vcenter',
2072 align => 'center',
2073 );
2074
2075 $worksheet->merge_range('B3:D4', 'Vertical and horizontal', $format);
2076
2077B<WARNING>. The format object that is used with a C<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.
2078
2079The C<$utf_16_be> parameter is optional, see below.
2080
2081C<merge_range()> writes its C<$token> argument using the worksheet C<write()> method. Therefore it will handle numbers, strings, formulas or urls as required.
2082
2083Setting the C<merge> property of the format isn't required when you are using C<merge_range()>. In fact using it will exclude the use of any other horizontal alignment option.
2084
2085On systems with C<perl 5.8> and later the C<merge_range()> method will also handle strings in C<UTF-8> format.
2086
2087 $worksheet->merge_range('B3:D4', "\x{263a}", $format); # Smiley
2088
2089On earlier Perl systems your can specify C<UTF-16BE> worksheet names using an additional optional parameter:
2090
2091 my $str = pack 'n', 0x263a;
2092 $worksheet->merge_range('B3:D4', $str, $format, 1); # Smiley
2093
2094The full possibilities of this method are shown in the C<merge3.pl> to C<merge6.pl> programs in the C<examples> directory of the distribution.
2095
2096
2097
2098
2099=head2 set_zoom($scale)
2100
2101Set the worksheet zoom factor in the range C<10 E<lt>= $scale E<lt>= 400>:
2102
2103 $worksheet1->set_zoom(50);
2104 $worksheet2->set_zoom(75);
2105 $worksheet3->set_zoom(300);
2106 $worksheet4->set_zoom(400);
2107
2108The default zoom factor is 100. You cannot zoom to "Selection" because it is calculated by Excel at run-time.
2109
2110Note, C<set_zoom()> does not affect the scale of the printed page. For that you should use C<set_print_scale()>.
2111
2112
2113
2114
2115=head2 right_to_left()
2116
2117The C<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.
2118
2119 $worksheet->right_to_left();
2120
2121This is useful when creating Arabic, Hebrew or other near or far eastern worksheets that use right-to-left as the default direction.
2122
2123
2124
2125
2126=head2 hide_zero()
2127
2128The C<hide_zero()> method is used to hide any zero values that appear in cells.
2129
2130 $worksheet->hide_zero();
2131
2132In Excel this option is found under Tools->Options->View.
2133
2134
2135
2136
2137=head2 set_tab_color()
2138
2139The C<set_tab_color()> method is used to change the colour of the worksheet tab. This feature 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 L<COLOURS IN EXCEL> and the C<set_custom_color()> method.
2140
2141 $worksheet1->set_tab_color('red');
2142 $worksheet2->set_tab_color(0x0C);
2143
2144See the C<tab_colors.pl> program in the examples directory of the distro.
2145
2146
2147
2148
2149=head2 autofilter($first_row, $first_col, $last_row, $last_col)
2150
2151This 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 shown and some is hidden.
2152
2153To add an autofilter to a worksheet:
2154
2155 $worksheet->autofilter(0, 0, 10, 3);
2156 $worksheet->autofilter('A1:D11'); # Same as above in A1 notation.
2157
2158Filter conditions can be applied using the C<filter_column()> method.
2159
2160See the C<autofilter.pl> program in the examples directory of the distro for a more detailed example.
2161
2162
2163
2164
2165=head2 filter_column($column, $expression)
2166
2167
2168The C<filter_column> method can be used to filter columns in a autofilter range based on simple conditions.
2169
2170B<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 C<set_row()> C<visible> parameter. C<Spreadsheet::WriteExcel> cannot do this automatically since it isn't part of the file format. See the C<autofilter.pl> program in the examples directory of the distro for an example.
2171
2172The conditions for the filter are specified using simple expressions:
2173
2174 $worksheet->filter_column('A', 'x > 2000');
2175 $worksheet->filter_column('B', 'x > 2000 and x < 5000');
2176
2177The C<$column> parameter can either be a zero indexed column number or a string column name.
2178
2179The following operators are available:
2180
2181 Operator Synonyms
2182 == = eq =~
2183 != <> ne !=
2184 >
2185 <
2186 >=
2187 <=
2188
2189 and &&
2190 or ||
2191
2192The 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.
2193
2194An expression can comprise a single statement or two statements separated by the C<and> and C<or> operators. For example:
2195
2196 'x < 2000'
2197 'x > 2000'
2198 'x == 2000'
2199 'x > 2000 and x < 5000'
2200 'x == 2000 or x == 5000'
2201
2202Filtering of blank or non-blank data can be achieved by using a value of C<Blanks> or C<NonBlanks> in the expression:
2203
2204 'x == Blanks'
2205 'x == NonBlanks'
2206
2207Top 10 style filters can be specified using a expression like the following:
2208
2209 Top|Bottom 1-500 Items|%
2210
2211For example:
2212
2213 'Top 10 Items'
2214 'Bottom 5 Items'
2215 'Top 25 %'
2216 'Bottom 50 %'
2217
2218Excel also allows some simple string matching operations:
2219
2220 'x =~ b*' # begins with b
2221 'x !~ b*' # doesn't begin with b
2222 'x =~ *b' # ends with b
2223 'x !~ *b' # doesn't end with b
2224 'x =~ *b*' # contains b
2225 'x !~ *b*' # doesn't contains b
2226
2227You can also use C<*> to match any character or number and C<?> to match any single character or number. No other regular expression quantifier is supported by Excel's filters. Excel's regular expression characters can be escaped using C<~>.
2228
2229The placeholder variable C<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:
2230
2231 'x < 2000'
2232 'col < 2000'
2233 'Price < 2000'
2234
2235Also, note that a filter condition can only be applied to a column in a range specified by the C<autofilter()> Worksheet method.
2236
2237See the C<autofilter.pl> program in the examples directory of the distro for a more detailed example.
2238
2239
2240
2241
2242=head1 PAGE SET-UP METHODS
2243
2244Page 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 standard worksheet methods. They are documented here in a separate section for the sake of clarity.
2245
2246The following methods are available for page set-up:
2247
2248 set_landscape()
2249 set_portrait()
2250 set_page_view()
2251 set_paper()
2252 center_horizontally()
2253 center_vertically()
2254 set_margins()
2255 set_header()
2256 set_footer()
2257 repeat_rows()
2258 repeat_columns()
2259 hide_gridlines()
2260 print_row_col_headers()
2261 print_area()
2262 print_across()
2263 fit_to_pages()
2264 set_start_page()
2265 set_print_scale()
2266 set_h_pagebreaks()
2267 set_v_pagebreaks()
2268
2269
2270A 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 C<sheets()> method of the C<workbook> class to access the array of worksheets in a workbook:
2271
2272 foreach $worksheet ($workbook->sheets()) {
2273 $worksheet->set_landscape();
2274 }
2275
2276
2277
2278
2279=head2 set_landscape()
2280
2281This method is used to set the orientation of a worksheet's printed page to landscape:
2282
2283 $worksheet->set_landscape(); # Landscape mode
2284
2285
2286
2287
2288=head2 set_portrait()
2289
2290This 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.
2291
2292 $worksheet->set_portrait(); # Portrait mode
2293
2294
2295
2296=head2 set_page_view()
2297
2298This method is used to display the worksheet in "Page View" mode. This is currently only supported by Mac Excel, where it is the default.
2299
2300 $worksheet->set_page_view();
2301
2302
2303
2304=head2 set_paper($index)
2305
2306This method is used to set the paper format for the printed output of a worksheet. The following paper styles are available:
2307
2308 Index Paper format Paper size
2309 ===== ============ ==========
2310 0 Printer default -
2311 1 Letter 8 1/2 x 11 in
2312 2 Letter Small 8 1/2 x 11 in
2313 3 Tabloid 11 x 17 in
2314 4 Ledger 17 x 11 in
2315 5 Legal 8 1/2 x 14 in
2316 6 Statement 5 1/2 x 8 1/2 in
2317 7 Executive 7 1/4 x 10 1/2 in
2318 8 A3 297 x 420 mm
2319 9 A4 210 x 297 mm
2320 10 A4 Small 210 x 297 mm
2321 11 A5 148 x 210 mm
2322 12 B4 250 x 354 mm
2323 13 B5 182 x 257 mm
2324 14 Folio 8 1/2 x 13 in
2325 15 Quarto 215 x 275 mm
2326 16 - 10x14 in
2327 17 - 11x17 in
2328 18 Note 8 1/2 x 11 in
2329 19 Envelope 9 3 7/8 x 8 7/8
2330 20 Envelope 10 4 1/8 x 9 1/2
2331 21 Envelope 11 4 1/2 x 10 3/8
2332 22 Envelope 12 4 3/4 x 11
2333 23 Envelope 14 5 x 11 1/2
2334 24 C size sheet -
2335 25 D size sheet -
2336 26 E size sheet -
2337 27 Envelope DL 110 x 220 mm
2338 28 Envelope C3 324 x 458 mm
2339 29 Envelope C4 229 x 324 mm
2340 30 Envelope C5 162 x 229 mm
2341 31 Envelope C6 114 x 162 mm
2342 32 Envelope C65 114 x 229 mm
2343 33 Envelope B4 250 x 353 mm
2344 34 Envelope B5 176 x 250 mm
2345 35 Envelope B6 176 x 125 mm
2346 36 Envelope 110 x 230 mm
2347 37 Monarch 3.875 x 7.5 in
2348 38 Envelope 3 5/8 x 6 1/2 in
2349 39 Fanfold 14 7/8 x 11 in
2350 40 German Std Fanfold 8 1/2 x 12 in
2351 41 German Legal Fanfold 8 1/2 x 13 in
2352
2353
2354Note, 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.
2355
2356 $worksheet->set_paper(1); # US Letter
2357 $worksheet->set_paper(9); # A4
2358
2359If you do not specify a paper type the worksheet will print using the printer's default paper.
2360
2361
2362
2363
2364=head2 center_horizontally()
2365
2366Center the worksheet data horizontally between the margins on the printed page:
2367
2368 $worksheet->center_horizontally();
2369
2370
2371
2372
2373=head2 center_vertically()
2374
2375Center the worksheet data vertically between the margins on the printed page:
2376
2377 $worksheet->center_vertically();
2378
2379
2380
2381
2382=head2 set_margins($inches)
2383
2384There are several methods available for setting the worksheet margins on the printed page:
2385
2386 set_margins() # Set all margins to the same value
2387 set_margins_LR() # Set left and right margins to the same value
2388 set_margins_TB() # Set top and bottom margins to the same value
2389 set_margin_left(); # Set left margin
2390 set_margin_right(); # Set right margin
2391 set_margin_top(); # Set top margin
2392 set_margin_bottom(); # Set bottom margin
2393
2394All 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.
2395
2396
2397
2398=head2 set_header($string, $margin)
2399
2400Headers and footers are generated using a C<$string> which is a combination of plain text and control characters. The C<$margin> parameter is optional.
2401
2402The available control character are:
2403
2404 Control Category Description
2405 ======= ======== ===========
2406 &L Justification Left
2407 &C Center
2408 &R Right
2409
2410 &P Information Page number
2411 &N Total number of pages
2412 &D Date
2413 &T Time
2414 &F File name
2415 &A Worksheet name
2416 &Z Workbook path
2417
2418 &fontsize Font Font size
2419 &"font,style" Font name and style
2420 &U Single underline
2421 &E Double underline
2422 &S Strikethrough
2423 &X Superscript
2424 &Y Subscript
2425
2426 && Miscellaneous Literal ampersand &
2427
2428
2429Text in headers and footers can be justified (aligned) to the left, center and right by prefixing the text with the control characters C<&L>, C<&C> and C<&R>.
2430
2431For example (with ASCII art representation of the results):
2432
2433 $worksheet->set_header('&LHello');
2434
2435 ---------------------------------------------------------------
2436 | |
2437 | Hello |
2438 | |
2439
2440
2441 $worksheet->set_header('&CHello');
2442
2443 ---------------------------------------------------------------
2444 | |
2445 | Hello |
2446 | |
2447
2448
2449 $worksheet->set_header('&RHello');
2450
2451 ---------------------------------------------------------------
2452 | |
2453 | Hello |
2454 | |
2455
2456
2457For simple text, if you do not specify any justification the text will be centred. However, you must prefix the text with C<&C> if you specify a font name or any other formatting:
2458
2459 $worksheet->set_header('Hello');
2460
2461 ---------------------------------------------------------------
2462 | |
2463 | Hello |
2464 | |
2465
2466
2467You can have text in each of the justification regions:
2468
2469 $worksheet->set_header('&LCiao&CBello&RCielo');
2470
2471 ---------------------------------------------------------------
2472 | |
2473 | Ciao Bello Cielo |
2474 | |
2475
2476
2477The 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:
2478
2479 $worksheet->set_header('&CPage &P of &N');
2480
2481 ---------------------------------------------------------------
2482 | |
2483 | Page 1 of 6 |
2484 | |
2485
2486
2487 $worksheet->set_header('&CUpdated at &T');
2488
2489 ---------------------------------------------------------------
2490 | |
2491 | Updated at 12:30 PM |
2492 | |
2493
2494
2495
2496You can specify the font size of a section of the text by prefixing it with the control character C<&n> where C<n> is the font size:
2497
2498 $worksheet1->set_header('&C&30Hello Big' );
2499 $worksheet2->set_header('&C&10Hello Small');
2500
2501You can specify the font of a section of the text by prefixing it with the control sequence C<&"font,style"> where C<fontname> is a font name such as "Courier New" or "Times New Roman" and C<style> is one of the standard Windows font descriptions: "Regular", "Italic", "Bold" or "Bold Italic":
2502
2503 $worksheet1->set_header('&C&"Courier New,Italic"Hello');
2504 $worksheet2->set_header('&C&"Courier New,Bold Italic"Hello');
2505 $worksheet3->set_header('&C&"Times New Roman,Regular"Hello');
2506
2507It 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 however that VBA uses two double quotes C<""> to indicate a single double quote. For the last example above the equivalent VBA code looks like this:
2508
2509 .LeftHeader = ""
2510 .CenterHeader = "&""Times New Roman,Regular""Hello"
2511 .RightHeader = ""
2512
2513
2514To include a single literal ampersand C<&> in a header or footer you should use a double ampersand C<&&>:
2515
2516 $worksheet1->set_header('&CCuriouser && Curiouser - Attorneys at Law');
2517
2518As 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:
2519
2520 $worksheet->set_header('&CHello', 0.75);
2521
2522The header and footer margins are independent of the top and bottom margins.
2523
2524Note, 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.
2525
2526On systems with C<perl 5.8> and later the C<set_header()> method can also handle Unicode strings in C<UTF-8> format.
2527
2528 $worksheet->set_header("&C\x{263a}")
2529
2530
2531See, also the C<headers.pl> program in the C<examples> directory of the distribution.
2532
2533
2534
2535
2536=head2 set_footer()
2537
2538The syntax of the C<set_footer()> method is the same as C<set_header()>, see above.
2539
2540
2541
2542
2543=head2 repeat_rows($first_row, $last_row)
2544
2545Set the number of rows to repeat at the top of each printed page.
2546
2547For large Excel documents it is often desirable to have the first row or rows of the worksheet print out at the top of each page. This can be achieved by using the C<repeat_rows()> method. The parameters C<$first_row> and C<$last_row> are zero based. The C<$last_row> parameter is optional if you only wish to specify one row:
2548
2549 $worksheet1->repeat_rows(0); # Repeat the first row
2550 $worksheet2->repeat_rows(0, 1); # Repeat the first two rows
2551
2552
2553
2554
2555=head2 repeat_columns($first_col, $last_col)
2556
2557Set the columns to repeat at the left hand side of each printed page.
2558
2559For 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 C<repeat_columns()> method. The parameters C<$first_column> and C<$last_column> are zero based. The C<$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 L<Cell notation>.
2560
2561 $worksheet1->repeat_columns(0); # Repeat the first column
2562 $worksheet2->repeat_columns(0, 1); # Repeat the first two columns
2563 $worksheet3->repeat_columns('A:A'); # Repeat the first column
2564 $worksheet4->repeat_columns('A:B'); # Repeat the first two columns
2565
2566
2567
2568
2569=head2 hide_gridlines($option)
2570
2571This 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.
2572
2573 $worksheet->hide_gridlines();
2574
2575The following values of C<$option> are valid:
2576
2577 0 : Don't hide gridlines
2578 1 : Hide printed gridlines only
2579 2 : Hide screen and printed gridlines
2580
2581If you don't supply an argument or use C<undef> the default option is 1, i.e. only the printed gridlines are hidden.
2582
2583
2584
2585
2586=head2 print_row_col_headers()
2587
2588Set the option to print the row and column headers on the printed page.
2589
2590An Excel worksheet looks something like the following;
2591
2592 ------------------------------------------
2593 | | A | B | C | D | ...
2594 ------------------------------------------
2595 | 1 | | | | | ...
2596 | 2 | | | | | ...
2597 | 3 | | | | | ...
2598 | 4 | | | | | ...
2599 |...| ... | ... | ... | ... | ...
2600
2601The 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 C<print_row_col_headers()> method :
2602
2603 $worksheet->print_row_col_headers();
2604
2605Do not confuse these headers with page headers as described in the C<set_header()> section above.
2606
2607
2608
2609
2610=head2 print_area($first_row, $first_col, $last_row, $last_col)
2611
2612This 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 L<Cell notation>.
2613
2614
2615 $worksheet1->print_area('A1:H20'); # Cells A1 to H20
2616 $worksheet2->print_area(0, 0, 19, 7); # The same
2617 $worksheet2->print_area('A:H'); # Columns A to H if rows have data
2618
2619
2620
2621
2622=head2 print_across()
2623
2624The C<print_across> method is used to change the default print direction. This is referred to by Excel as the sheet "page order".
2625
2626 $worksheet->print_across();
2627
2628The default page order is shown below for a worksheet that extends over 4 pages. The order is called "down then across":
2629
2630 [1] [3]
2631 [2] [4]
2632
2633However, by using the C<print_across> method the print order will be changed to "across then down":
2634
2635 [1] [2]
2636 [3] [4]
2637
2638
2639
2640
2641=head2 fit_to_pages($width, $height)
2642
2643The C<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.
2644
2645 $worksheet1->fit_to_pages(1, 1); # Fit to 1x1 pages
2646 $worksheet2->fit_to_pages(2, 1); # Fit to 2x1 pages
2647 $worksheet3->fit_to_pages(1, 2); # Fit to 1x2 pages
2648
2649The print area can be defined using the C<print_area()> method as described above.
2650
2651A common requirement is to fit the printed output to I<n> pages wide but have the height be as long as necessary. To achieve this set the C<$height> to zero or leave it blank:
2652
2653 $worksheet1->fit_to_pages(1, 0); # 1 page wide and as long as necessary
2654 $worksheet2->fit_to_pages(1); # The same
2655
2656
2657Note that although it is valid to use both C<fit_to_pages()> and C<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.
2658
2659Note that C<fit_to_pages()> will override any manual page breaks that are defined in the worksheet.
2660
2661
2662
2663
2664=head2 set_start_page($start_page)
2665
2666The C<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.
2667
2668 $worksheet->set_start_page(2);
2669
2670
2671
2672
2673=head2 set_print_scale($scale)
2674
2675Set the scale factor of the printed page. Scale factors in the range C<10 E<lt>= $scale E<lt>= 400> are valid:
2676
2677 $worksheet1->set_print_scale(50);
2678 $worksheet2->set_print_scale(75);
2679 $worksheet3->set_print_scale(300);
2680 $worksheet4->set_print_scale(400);
2681
2682The default scale factor is 100. Note, C<set_print_scale()> does not affect the scale of the visible page in Excel. For that you should use C<set_zoom()>.
2683
2684Note also that although it is valid to use both C<fit_to_pages()> and C<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.
2685
2686
2687
2688
2689=head2 set_h_pagebreaks(@breaks)
2690
2691Add 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 while that you are using 1 index notation:
2692
2693 $worksheet1->set_h_pagebreaks(20); # Break between row 20 and 21
2694
2695The C<set_h_pagebreaks()> method will accept a list of page breaks and you can call it more than once:
2696
2697 $worksheet2->set_h_pagebreaks( 20, 40, 60, 80, 100); # Add breaks
2698 $worksheet2->set_h_pagebreaks(120, 140, 160, 180, 200); # Add some more
2699
2700Note: If you specify the "fit to page" option via the C<fit_to_pages()> method it will override all manual page breaks.
2701
2702There is a silent limitation of about 1000 horizontal page breaks per worksheet in line with an Excel internal limitation.
2703
2704
2705
2706
2707=head2 set_v_pagebreaks(@breaks)
2708
2709Add vertical page breaks to a worksheet. A page break causes all the data that follows it to be printed on the next page. Vertical page breaks act between columns. To create a page break between columns 20 and 21 you must specify the break at column 21. However in zero index notation this is actually column 20. So you can pretend for a small while that you are using 1 index notation:
2710
2711 $worksheet1->set_v_pagebreaks(20); # Break between column 20 and 21
2712
2713The C<set_v_pagebreaks()> method will accept a list of page breaks and you can call it more than once:
2714
2715 $worksheet2->set_v_pagebreaks( 20, 40, 60, 80, 100); # Add breaks
2716 $worksheet2->set_v_pagebreaks(120, 140, 160, 180, 200); # Add some more
2717
2718Note: If you specify the "fit to page" option via the C<fit_to_pages()> method it will override all manual page breaks.
2719
2720
2721
2722
2723=head1 CELL FORMATTING
2724
2725This section describes the methods and properties that are available for formatting cells in Excel. The properties of a cell that can be formatted include: fonts, colours, patterns, borders, alignment and number formatting.
2726
2727
2728=head2 Creating and using a Format object
2729
2730Cell formatting is defined through a Format object. Format objects are created by calling the workbook C<add_format()> method as follows:
2731
2732 my $format1 = $workbook->add_format(); # Set properties later
2733 my $format2 = $workbook->add_format(%props); # Set at creation
2734
2735The format object holds all the formatting properties that can be applied to a cell, a row or a column. The process of setting these properties is discussed in the next section.
2736
2737Once a Format object has been constructed and it properties have been set it can be passed as an argument to the worksheet C<write> methods as follows:
2738
2739 $worksheet->write(0, 0, 'One', $format);
2740 $worksheet->write_string(1, 0, 'Two', $format);
2741 $worksheet->write_number(2, 0, 3, $format);
2742 $worksheet->write_blank(3, 0, $format);
2743
2744Formats can also be passed to the worksheet C<set_row()> and C<set_column()> methods to define the default property for a row or column.
2745
2746 $worksheet->set_row(0, 15, $format);
2747 $worksheet->set_column(0, 0, 15, $format);
2748
2749
2750
2751
2752=head2 Format methods and Format properties
2753
2754The following table shows the Excel format categories, the formatting properties that can be applied and the equivalent object method:
2755
2756
2757 Category Description Property Method Name
2758 -------- ----------- -------- -----------
2759 Font Font type font set_font()
2760 Font size size set_size()
2761 Font color color set_color()
2762 Bold bold set_bold()
2763 Italic italic set_italic()
2764 Underline underline set_underline()
2765 Strikeout font_strikeout set_font_strikeout()
2766 Super/Subscript font_script set_font_script()
2767 Outline font_outline set_font_outline()
2768 Shadow font_shadow set_font_shadow()
2769
2770 Number Numeric format num_format set_num_format()
2771
2772 Protection Lock cells locked set_locked()
2773 Hide formulas hidden set_hidden()
2774
2775 Alignment Horizontal align align set_align()
2776 Vertical align valign set_align()
2777 Rotation rotation set_rotation()
2778 Text wrap text_wrap set_text_wrap()
2779 Justify last text_justlast set_text_justlast()
2780 Center across center_across set_center_across()
2781 Indentation indent set_indent()
2782 Shrink to fit shrink set_shrink()
2783
2784 Pattern Cell pattern pattern set_pattern()
2785 Background color bg_color set_bg_color()
2786 Foreground color fg_color set_fg_color()
2787
2788 Border Cell border border set_border()
2789 Bottom border bottom set_bottom()
2790 Top border top set_top()
2791 Left border left set_left()
2792 Right border right set_right()
2793 Border color border_color set_border_color()
2794 Bottom color bottom_color set_bottom_color()
2795 Top color top_color set_top_color()
2796 Left color left_color set_left_color()
2797 Right color right_color set_right_color()
2798
2799There are two ways of setting Format properties: by using the object method interface or by setting the property directly. For example, a typical use of the method interface would be as follows:
2800
2801 my $format = $workbook->add_format();
2802 $format->set_bold();
2803 $format->set_color('red');
2804
2805By comparison the properties can be set directly by passing a hash of properties to the Format constructor:
2806
2807 my $format = $workbook->add_format(bold => 1, color => 'red');
2808
2809or after the Format has been constructed by means of the C<set_format_properties()> method as follows:
2810
2811 my $format = $workbook->add_format();
2812 $format->set_format_properties(bold => 1, color => 'red');
2813
2814You can also store the properties in one or more named hashes and pass them to the required method:
2815
2816 my %font = (
2817 font => 'Arial',
2818 size => 12,
2819 color => 'blue',
2820 bold => 1,
2821 );
2822
2823 my %shading = (
2824 bg_color => 'green',
2825 pattern => 1,
2826 );
2827
2828
2829 my $format1 = $workbook->add_format(%font); # Font only
2830 my $format2 = $workbook->add_format(%font, %shading); # Font and shading
2831
2832
2833The provision of two ways of setting properties might lead you to wonder which is the best way. The method mechanism may be better is you prefer setting properties via method calls (which the author did when they were code was first written) otherwise passing properties to the constructor has proved to be a little more flexible and self documenting in practice. An additional advantage of working with property hashes is that it allows you to share formatting between workbook objects as shown in the example above.
2834
2835The Perl/Tk style of adding properties is also supported:
2836
2837 my %font = (
2838 -font => 'Arial',
2839 -size => 12,
2840 -color => 'blue',
2841 -bold => 1,
2842 );
2843
2844
2845
2846
2847=head2 Working with formats
2848
2849The default format is Arial 10 with all other properties off.
2850
2851Each unique format in Spreadsheet::WriteExcel must have a corresponding Format object. It isn't possible to use a Format with a write() method and then redefine the Format for use at a later stage. This is because a Format is applied to a cell not in its current state but in its final state. Consider the following example:
2852
2853 my $format = $workbook->add_format();
2854 $format->set_bold();
2855 $format->set_color('red');
2856 $worksheet->write('A1', 'Cell A1', $format);
2857 $format->set_color('green');
2858 $worksheet->write('B1', 'Cell B1', $format);
2859
2860Cell A1 is assigned the Format C<$format> which is initially set to the colour red. However, the colour is subsequently set to green. When Excel displays Cell A1 it will display the final state of the Format which in this case will be the colour green.
2861
2862In general a method call without an argument will turn a property on, for example:
2863
2864 my $format1 = $workbook->add_format();
2865 $format1->set_bold(); # Turns bold on
2866 $format1->set_bold(1); # Also turns bold on
2867 $format1->set_bold(0); # Turns bold off
2868
2869
2870
2871
2872=head1 FORMAT METHODS
2873
2874The Format object methods are described in more detail in the following sections. In addition, there is a Perl program called C<formats.pl> in the C<examples> directory of the WriteExcel distribution. This program creates an Excel workbook called C<formats.xls> which contains examples of almost all the format types.
2875
2876The following Format methods are available:
2877
2878 set_font()
2879 set_size()
2880 set_color()
2881 set_bold()
2882 set_italic()
2883 set_underline()
2884 set_font_strikeout()
2885 set_font_script()
2886 set_font_outline()
2887 set_font_shadow()
2888 set_num_format()
2889 set_locked()
2890 set_hidden()
2891 set_align()
2892 set_rotation()
2893 set_text_wrap()
2894 set_text_justlast()
2895 set_center_across()
2896 set_indent()
2897 set_shrink()
2898 set_pattern()
2899 set_bg_color()
2900 set_fg_color()
2901 set_border()
2902 set_bottom()
2903 set_top()
2904 set_left()
2905 set_right()
2906 set_border_color()
2907 set_bottom_color()
2908 set_top_color()
2909 set_left_color()
2910 set_right_color()
2911
2912
2913The above methods can also be applied directly as properties. For example C<< $format->set_bold() >> is equivalent to C<< $workbook->add_format(bold => 1) >>.
2914
2915
2916=head2 set_format_properties(%properties)
2917
2918The properties of an existing Format object can be also be set by means of C<set_format_properties()>:
2919
2920 my $format = $workbook->add_format();
2921 $format->set_format_properties(bold => 1, color => 'red');
2922
2923However, this method is here mainly for legacy reasons. It is preferable to set the properties in the format constructor:
2924
2925 my $format = $workbook->add_format(bold => 1, color => 'red');
2926
2927
2928=head2 set_font($fontname)
2929
2930 Default state: Font is Arial
2931 Default action: None
2932 Valid args: Any valid font name
2933
2934Specify the font used:
2935
2936 $format->set_font('Times New Roman');
2937
2938Excel can only display fonts that are installed on the system that it is running on. Therefore it is best to use the fonts that come as standard such as 'Arial', 'Times New Roman' and 'Courier New'. See also the Fonts worksheet created by formats.pl
2939
2940
2941
2942
2943=head2 set_size()
2944
2945 Default state: Font size is 10
2946 Default action: Set font size to 1
2947 Valid args: Integer values from 1 to as big as your screen.
2948
2949
2950Set the font size. Excel adjusts the height of a row to accommodate the largest font size in the row. You can also explicitly specify the height of a row using the set_row() worksheet method.
2951
2952 my $format = $workbook->add_format();
2953 $format->set_size(30);
2954
2955
2956
2957
2958
2959=head2 set_color()
2960
2961 Default state: Excels default color, usually black
2962 Default action: Set the default color
2963 Valid args: Integers from 8..63 or the following strings:
2964 'black'
2965 'blue'
2966 'brown'
2967 'cyan'
2968 'gray'
2969 'green'
2970 'lime'
2971 'magenta'
2972 'navy'
2973 'orange'
2974 'pink'
2975 'purple'
2976 'red'
2977 'silver'
2978 'white'
2979 'yellow'
2980
2981Set the font colour. The C<set_color()> method is used as follows:
2982
2983 my $format = $workbook->add_format();
2984 $format->set_color('red');
2985 $worksheet->write(0, 0, 'wheelbarrow', $format);
2986
2987Note: The C<set_color()> method is used to set the colour of the font in a cell. To set the colour of a cell use the C<set_bg_color()> and C<set_pattern()> methods.
2988
2989For additional examples see the 'Named colors' and 'Standard colors' worksheets created by formats.pl in the examples directory.
2990
2991See also L<COLOURS IN EXCEL>.
2992
2993
2994
2995
2996=head2 set_bold()
2997
2998 Default state: bold is off
2999 Default action: Turn bold on
3000 Valid args: 0, 1 [1]
3001
3002Set the bold property of the font:
3003
3004 $format->set_bold(); # Turn bold on
3005
3006[1] Actually, values in the range 100..1000 are also valid. 400 is normal, 700 is bold and 1000 is very bold indeed. It is probably best to set the value to 1 and use normal bold.
3007
3008
3009
3010
3011=head2 set_italic()
3012
3013 Default state: Italic is off
3014 Default action: Turn italic on
3015 Valid args: 0, 1
3016
3017Set the italic property of the font:
3018
3019 $format->set_italic(); # Turn italic on
3020
3021
3022
3023
3024=head2 set_underline()
3025
3026 Default state: Underline is off
3027 Default action: Turn on single underline
3028 Valid args: 0 = No underline
3029 1 = Single underline
3030 2 = Double underline
3031 33 = Single accounting underline
3032 34 = Double accounting underline
3033
3034Set the underline property of the font.
3035
3036 $format->set_underline(); # Single underline
3037
3038
3039
3040
3041=head2 set_font_strikeout()
3042
3043 Default state: Strikeout is off
3044 Default action: Turn strikeout on
3045 Valid args: 0, 1
3046
3047Set the strikeout property of the font.
3048
3049
3050
3051
3052=head2 set_font_script()
3053
3054 Default state: Super/Subscript is off
3055 Default action: Turn Superscript on
3056 Valid args: 0 = Normal
3057 1 = Superscript
3058 2 = Subscript
3059
3060Set the superscript/subscript property of the font. This format is currently not very useful.
3061
3062
3063
3064
3065=head2 set_font_outline()
3066
3067 Default state: Outline is off
3068 Default action: Turn outline on
3069 Valid args: 0, 1
3070
3071Macintosh only.
3072
3073
3074
3075
3076=head2 set_font_shadow()
3077
3078 Default state: Shadow is off
3079 Default action: Turn shadow on
3080 Valid args: 0, 1
3081
3082Macintosh only.
3083
3084
3085
3086
3087=head2 set_num_format()
3088
3089 Default state: General format
3090 Default action: Format index 1
3091 Valid args: See the following table
3092
3093This method is used to define the numerical format of a number in Excel. It controls whether a number is displayed as an integer, a floating point number, a date, a currency value or some other user defined format.
3094
3095The numerical format of a cell can be specified by using a format string or an index to one of Excel's built-in formats:
3096
3097 my $format1 = $workbook->add_format();
3098 my $format2 = $workbook->add_format();
3099 $format1->set_num_format('d mmm yyyy'); # Format string
3100 $format2->set_num_format(0x0f); # Format index
3101
3102 $worksheet->write(0, 0, 36892.521, $format1); # 1 Jan 2001
3103 $worksheet->write(0, 0, 36892.521, $format2); # 1-Jan-01
3104
3105
3106Using format strings you can define very sophisticated formatting of numbers.
3107
3108 $format01->set_num_format('0.000');
3109 $worksheet->write(0, 0, 3.1415926, $format01); # 3.142
3110
3111 $format02->set_num_format('#,##0');
3112 $worksheet->write(1, 0, 1234.56, $format02); # 1,235
3113
3114 $format03->set_num_format('#,##0.00');
3115 $worksheet->write(2, 0, 1234.56, $format03); # 1,234.56
3116
3117 $format04->set_num_format('$0.00');
3118 $worksheet->write(3, 0, 49.99, $format04); # $49.99
3119
3120 # Note you can use other currency symbols such as the pound or yen as well.
3121 # Other currencies may require the use of Unicode.
3122
3123 $format07->set_num_format('mm/dd/yy');
3124 $worksheet->write(6, 0, 36892.521, $format07); # 01/01/01
3125
3126 $format08->set_num_format('mmm d yyyy');
3127 $worksheet->write(7, 0, 36892.521, $format08); # Jan 1 2001
3128
3129 $format09->set_num_format('d mmmm yyyy');
3130 $worksheet->write(8, 0, 36892.521, $format09); # 1 January 2001
3131
3132 $format10->set_num_format('dd/mm/yyyy hh:mm AM/PM');
3133 $worksheet->write(9, 0, 36892.521, $format10); # 01/01/2001 12:30 AM
3134
3135 $format11->set_num_format('0 "dollar and" .00 "cents"');
3136 $worksheet->write(10, 0, 1.87, $format11); # 1 dollar and .87 cents
3137
3138 # Conditional formatting
3139 $format12->set_num_format('[Green]General;[Red]-General;General');
3140 $worksheet->write(11, 0, 123, $format12); # > 0 Green
3141 $worksheet->write(12, 0, -45, $format12); # < 0 Red
3142 $worksheet->write(13, 0, 0, $format12); # = 0 Default colour
3143
3144 # Zip code
3145 $format13->set_num_format('00000');
3146 $worksheet->write(14, 0, '01209', $format13);
3147
3148
3149The number system used for dates is described in L<DATES AND TIME IN EXCEL>.
3150
3151The colour format should have one of the following values:
3152
3153 [Black] [Blue] [Cyan] [Green] [Magenta] [Red] [White] [Yellow]
3154
3155Alternatively you can specify the colour based on a colour index as follows: C<[Color n]>, where n is a standard Excel colour index - 7. See the 'Standard colors' worksheet created by formats.pl.
3156
3157For more information refer to the documentation on formatting in the C<docs> directory of the Spreadsheet::WriteExcel distro, the Excel on-line help or L<http://office.microsoft.com/en-gb/assistance/HP051995001033.aspx>.
3158
3159You should ensure that the format string is valid in Excel prior to using it in WriteExcel.
3160
3161Excel's built-in formats are shown in the following table:
3162
3163 Index Index Format String
3164 0 0x00 General
3165 1 0x01 0
3166 2 0x02 0.00
3167 3 0x03 #,##0
3168 4 0x04 #,##0.00
3169 5 0x05 ($#,##0_);($#,##0)
3170 6 0x06 ($#,##0_);[Red]($#,##0)
3171 7 0x07 ($#,##0.00_);($#,##0.00)
3172 8 0x08 ($#,##0.00_);[Red]($#,##0.00)
3173 9 0x09 0%
3174 10 0x0a 0.00%
3175 11 0x0b 0.00E+00
3176 12 0x0c # ?/?
3177 13 0x0d # ??/??
3178 14 0x0e m/d/yy
3179 15 0x0f d-mmm-yy
3180 16 0x10 d-mmm
3181 17 0x11 mmm-yy
3182 18 0x12 h:mm AM/PM
3183 19 0x13 h:mm:ss AM/PM
3184 20 0x14 h:mm
3185 21 0x15 h:mm:ss
3186 22 0x16 m/d/yy h:mm
3187 .. .... ...........
3188 37 0x25 (#,##0_);(#,##0)
3189 38 0x26 (#,##0_);[Red](#,##0)
3190 39 0x27 (#,##0.00_);(#,##0.00)
3191 40 0x28 (#,##0.00_);[Red](#,##0.00)
3192 41 0x29 _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
3193 42 0x2a _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)
3194 43 0x2b _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
3195 44 0x2c _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
3196 45 0x2d mm:ss
3197 46 0x2e [h]:mm:ss
3198 47 0x2f mm:ss.0
3199 48 0x30 ##0.0E+0
3200 49 0x31 @
3201
3202
3203For examples of these formatting codes see the 'Numerical formats' worksheet created by formats.pl. See also the number_formats1.html and the number_formats2.html documents in the C<docs> directory of the distro.
3204
3205Note 1. Numeric formats 23 to 36 are not documented by Microsoft and may differ in international versions.
3206
3207Note 2. In Excel 5 the dollar sign appears as a dollar sign. In Excel 97-2000 it appears as the defined local currency symbol.
3208
3209Note 3. The red negative numeric formats display slightly differently in Excel 5 and Excel 97-2000.
3210
3211
3212
3213
3214=head2 set_locked()
3215
3216 Default state: Cell locking is on
3217 Default action: Turn locking on
3218 Valid args: 0, 1
3219
3220This property can be used to prevent modification of a cells contents. Following Excel's convention, cell locking is turned on by default. However, it only has an effect if the worksheet has been protected, see the worksheet C<protect()> method.
3221
3222 my $locked = $workbook->add_format();
3223 $locked->set_locked(1); # A non-op
3224
3225 my $unlocked = $workbook->add_format();
3226 $locked->set_locked(0);
3227
3228 # Enable worksheet protection
3229 $worksheet->protect();
3230
3231 # This cell cannot be edited.
3232 $worksheet->write('A1', '=1+2', $locked);
3233
3234 # This cell can be edited.
3235 $worksheet->write('A2', '=1+2', $unlocked);
3236
3237Note: This offers weak protection even with a password, see the note in relation to the C<protect()> method.
3238
3239
3240
3241
3242=head2 set_hidden()
3243
3244 Default state: Formula hiding is off
3245 Default action: Turn hiding on
3246 Valid args: 0, 1
3247
3248This property is used to hide a formula while still displaying its result. This is generally used to hide complex calculations from end users who are only interested in the result. It only has an effect if the worksheet has been protected, see the worksheet C<protect()> method.
3249
3250 my $hidden = $workbook->add_format();
3251 $hidden->set_hidden();
3252
3253 # Enable worksheet protection
3254 $worksheet->protect();
3255
3256 # The formula in this cell isn't visible
3257 $worksheet->write('A1', '=1+2', $hidden);
3258
3259
3260Note: This offers weak protection even with a password, see the note in relation to the C<protect()> method.
3261
3262
3263
3264
3265=head2 set_align()
3266
3267 Default state: Alignment is off
3268 Default action: Left alignment
3269 Valid args: 'left' Horizontal
3270 'center'
3271 'right'
3272 'fill'
3273 'justify'
3274 'center_across'
3275
3276 'top' Vertical
3277 'vcenter'
3278 'bottom'
3279 'vjustify'
3280
3281This method is used to set the horizontal and vertical text alignment within a cell. Vertical and horizontal alignments can be combined. The method is used as follows:
3282
3283 my $format = $workbook->add_format();
3284 $format->set_align('center');
3285 $format->set_align('vcenter');
3286 $worksheet->set_row(0, 30);
3287 $worksheet->write(0, 0, 'X', $format);
3288
3289Text can be aligned across two or more adjacent cells using the C<center_across> property. However, for genuine merged cells it is better to use the C<merge_range()> worksheet method.
3290
3291The C<vjustify> (vertical justify) option can be used to provide automatic text wrapping in a cell. The height of the cell will be adjusted to accommodate the wrapped text. To specify where the text wraps use the C<set_text_wrap()> method.
3292
3293
3294For further examples see the 'Alignment' worksheet created by formats.pl.
3295
3296
3297
3298
3299=head2 set_center_across()
3300
3301 Default state: Center across selection is off
3302 Default action: Turn center across on
3303 Valid args: 1
3304
3305Text can be aligned across two or more adjacent cells using the C<set_center_across()> method. This is an alias for the C<set_align('center_across')> method call.
3306
3307Only one cell should contain the text, the other cells should be blank:
3308
3309 my $format = $workbook->add_format();
3310 $format->set_center_across();
3311
3312 $worksheet->write(1, 1, 'Center across selection', $format);
3313 $worksheet->write_blank(1, 2, $format);
3314
3315See also the C<merge1.pl> to C<merge6.pl> programs in the C<examples> directory and the C<merge_range()> method.
3316
3317
3318
3319=head2 set_text_wrap()
3320
3321 Default state: Text wrap is off
3322 Default action: Turn text wrap on
3323 Valid args: 0, 1
3324
3325
3326Here is an example using the text wrap property, the escape character C<\n> is used to indicate the end of line:
3327
3328 my $format = $workbook->add_format();
3329 $format->set_text_wrap();
3330 $worksheet->write(0, 0, "It's\na bum\nwrap", $format);
3331
3332Excel will adjust the height of the row to accommodate the wrapped text. A similar effect can be obtained without newlines using the C<set_align('vjustify')> method. See the C<textwrap.pl> program in the C<examples> directory.
3333
3334
3335
3336
3337=head2 set_rotation()
3338
3339 Default state: Text rotation is off
3340 Default action: None
3341 Valid args: Integers in the range -90 to 90 and 270
3342
3343Set the rotation of the text in a cell. The rotation can be any angle in the range -90 to 90 degrees.
3344
3345 my $format = $workbook->add_format();
3346 $format->set_rotation(30);
3347 $worksheet->write(0, 0, 'This text is rotated', $format);
3348
3349
3350The angle 270 is also supported. This indicates text where the letters run from top to bottom.
3351
3352
3353
3354=head2 set_indent()
3355
3356
3357 Default state: Text indentation is off
3358 Default action: Indent text 1 level
3359 Valid args: Positive integers
3360
3361
3362This method can be used to indent text. The argument, which should be an integer, is taken as the level of indentation:
3363
3364
3365 my $format = $workbook->add_format();
3366 $format->set_indent(2);
3367 $worksheet->write(0, 0, 'This text is indented', $format);
3368
3369
3370Indentation is a horizontal alignment property. It will override any other horizontal properties but it can be used in conjunction with vertical properties.
3371
3372
3373
3374
3375=head2 set_shrink()
3376
3377
3378 Default state: Text shrinking is off
3379 Default action: Turn "shrink to fit" on
3380 Valid args: 1
3381
3382
3383This method can be used to shrink text so that it fits in a cell.
3384
3385
3386 my $format = $workbook->add_format();
3387 $format->set_shrink();
3388 $worksheet->write(0, 0, 'Honey, I shrunk the text!', $format);
3389
3390
3391
3392
3393=head2 set_text_justlast()
3394
3395 Default state: Justify last is off
3396 Default action: Turn justify last on
3397 Valid args: 0, 1
3398
3399
3400Only applies to Far Eastern versions of Excel.
3401
3402
3403
3404
3405=head2 set_pattern()
3406
3407 Default state: Pattern is off
3408 Default action: Solid fill is on
3409 Valid args: 0 .. 18
3410
3411Set the background pattern of a cell.
3412
3413Examples of the available patterns are shown in the 'Patterns' worksheet created by formats.pl. However, it is unlikely that you will ever need anything other than Pattern 1 which is a solid fill of the background color.
3414
3415
3416
3417
3418=head2 set_bg_color()
3419
3420 Default state: Color is off
3421 Default action: Solid fill.
3422 Valid args: See set_color()
3423
3424The C<set_bg_color()> method can be used to set the background colour of a pattern. Patterns are defined via the C<set_pattern()> method. If a pattern hasn't been defined then a solid fill pattern is used as the default.
3425
3426Here is an example of how to set up a solid fill in a cell:
3427
3428 my $format = $workbook->add_format();
3429
3430 $format->set_pattern(); # This is optional when using a solid fill
3431
3432 $format->set_bg_color('green');
3433 $worksheet->write('A1', 'Ray', $format);
3434
3435For further examples see the 'Patterns' worksheet created by formats.pl.
3436
3437
3438
3439
3440=head2 set_fg_color()
3441
3442 Default state: Color is off
3443 Default action: Solid fill.
3444 Valid args: See set_color()
3445
3446
3447The C<set_fg_color()> method can be used to set the foreground colour of a pattern.
3448
3449For further examples see the 'Patterns' worksheet created by formats.pl.
3450
3451
3452
3453
3454=head2 set_border()
3455
3456 Also applies to: set_bottom()
3457 set_top()
3458 set_left()
3459 set_right()
3460
3461 Default state: Border is off
3462 Default action: Set border type 1
3463 Valid args: 0-13, See below.
3464
3465A cell border is comprised of a border on the bottom, top, left and right. These can be set to the same value using C<set_border()> or individually using the relevant method calls shown above.
3466
3467The following shows the border styles sorted by Spreadsheet::WriteExcel index number:
3468
3469 Index Name Weight Style
3470 ===== ============= ====== ===========
3471 0 None 0
3472 1 Continuous 1 -----------
3473 2 Continuous 2 -----------
3474 3 Dash 1 - - - - - -
3475 4 Dot 1 . . . . . .
3476 5 Continuous 3 -----------
3477 6 Double 3 ===========
3478 7 Continuous 0 -----------
3479 8 Dash 2 - - - - - -
3480 9 Dash Dot 1 - . - . - .
3481 10 Dash Dot 2 - . - . - .
3482 11 Dash Dot Dot 1 - . . - . .
3483 12 Dash Dot Dot 2 - . . - . .
3484 13 SlantDash Dot 2 / - . / - .
3485
3486
3487The following shows the borders sorted by style:
3488
3489 Name Weight Style Index
3490 ============= ====== =========== =====
3491 Continuous 0 ----------- 7
3492 Continuous 1 ----------- 1
3493 Continuous 2 ----------- 2
3494 Continuous 3 ----------- 5
3495 Dash 1 - - - - - - 3
3496 Dash 2 - - - - - - 8
3497 Dash Dot 1 - . - . - . 9
3498 Dash Dot 2 - . - . - . 10
3499 Dash Dot Dot 1 - . . - . . 11
3500 Dash Dot Dot 2 - . . - . . 12
3501 Dot 1 . . . . . . 4
3502 Double 3 =========== 6
3503 None 0 0
3504 SlantDash Dot 2 / - . / - . 13
3505
3506
3507The following shows the borders in the order shown in the Excel Dialog.
3508
3509 Index Style Index Style
3510 ===== ===== ===== =====
3511 0 None 12 - . . - . .
3512 7 ----------- 13 / - . / - .
3513 4 . . . . . . 10 - . - . - .
3514 11 - . . - . . 8 - - - - - -
3515 9 - . - . - . 2 -----------
3516 3 - - - - - - 5 -----------
3517 1 ----------- 6 ===========
3518
3519
3520Examples of the available border styles are shown in the 'Borders' worksheet created by formats.pl.
3521
3522
3523
3524
3525=head2 set_border_color()
3526
3527 Also applies to: set_bottom_color()
3528 set_top_color()
3529 set_left_color()
3530 set_right_color()
3531
3532 Default state: Color is off
3533 Default action: Undefined
3534 Valid args: See set_color()
3535
3536
3537Set the colour of the cell borders. A cell border is comprised of a border on the bottom, top, left and right. These can be set to the same colour using C<set_border_color()> or individually using the relevant method calls shown above. Examples of the border styles and colours are shown in the 'Borders' worksheet created by formats.pl.
3538
3539
3540
3541
3542
3543=head2 copy($format)
3544
3545
3546This method is used to copy all of the properties from one Format object to another:
3547
3548 my $lorry1 = $workbook->add_format();
3549 $lorry1->set_bold();
3550 $lorry1->set_italic();
3551 $lorry1->set_color('red'); # lorry1 is bold, italic and red
3552
3553 my $lorry2 = $workbook->add_format();
3554 $lorry2->copy($lorry1);
3555 $lorry2->set_color('yellow'); # lorry2 is bold, italic and yellow
3556
3557The C<copy()> method is only useful if you are using the method interface to Format properties. It generally isn't required if you are setting Format properties directly using hashes.
3558
3559
3560Note: this is not a copy constructor, both objects must exist prior to copying.
3561
3562
3563
3564
3565=head1 UNICODE IN EXCEL
3566
3567The following is a brief introduction to handling Unicode in C<Spreadsheet::WriteExcel>.
3568
3569I<For a more general introduction to Unicode handling in Perl see> L<perlunitut> and L<perluniintro>.
3570
3571When using Spreadsheet::WriteExcel the best and easiest way to write unicode strings to an Excel file is to use C<UTF-8> encoded strings and perl 5.8 (or later). Spreadsheet::WriteExcel also allows you to write unicode strings using older perls but it generally requires more work, as explained below.
3572
3573Internally, Excel encodes unicode data as C<UTF-16LE> (where LE means little-endian). If you are using perl 5.8+ then Spreadsheet::WriteExcel will convert C<UTF-8> strings to C<UTF-16LE> when required. No further intervention is required from the programmer, for example:
3574
3575 # perl 5.8+ example:
3576 my $smiley = "\x{263A}";
3577
3578 $worksheet->write('A1', 'Hello world'); # ASCII
3579 $worksheet->write('A2', $smiley); # UTF-8
3580
3581Spreadsheet::WriteExcel also lets you write unicode data as C<UTF-16>. Since the majority of CPAN modules default to C<UTF-16BE> (big-endian) Spreadsheet::WriteExcel also uses C<UTF-16BE> and converts it internally to C<UTF-16LE>:
3582
3583 # perl 5.005 example:
3584 my $smiley = pack 'n', 0x263A;
3585
3586 $worksheet->write ('A3', 'Hello world'); # ASCII
3587 $worksheet->write_utf16be_string('A4', $smiley); # UTF-16
3588
3589Although the above examples look similar there is an important difference. With C<uft8> and perl 5.8+ Spreadsheet::WriteExcel treats C<UTF-8> strings in exactly the same way as any other string. However, with C<UTF16> data we need to distinguish it from other strings either by calling a separate function or by passing an additional flag to indicate the data type.
3590
3591If you are dealing with non-ASCII characters that aren't in C<UTF-8> then perl 5.8+ provides useful tools in the guise of the C<Encode> module to help you to convert to the required format. For example:
3592
3593 use Encode 'decode';
3594
3595 my $string = 'some string with koi8-r characters';
3596 $string = decode('koi8-r', $string); # koi8-r to utf8
3597
3598Alternatively you can read data from an encoded file and convert it to C<UTF-8> as you read it in:
3599
3600
3601 my $file = 'unicode_koi8r.txt';
3602 open FH, '<:encoding(koi8-r)', $file or die "Couldn't open $file: $!\n";
3603
3604 my $row = 0;
3605 while (<FH>) {
3606 # Data read in is now in utf8 format.
3607 chomp;
3608 $worksheet->write($row++, 0, $_);
3609 }
3610
3611These methodologies are explained in more detail in L<perlunitut>, L<perluniintro> and L<perlunicode>.
3612
3613See also the C<unicode_*.pl> programs in the examples directory of the distro.
3614
3615
3616
3617
3618=head1 COLOURS IN EXCEL
3619
3620Excel provides a colour palette of 56 colours. In Spreadsheet::WriteExcel these colours are accessed via their palette index in the range 8..63. This index is used to set the colour of fonts, cell patterns and cell borders. For example:
3621
3622 my $format = $workbook->add_format(
3623 color => 12, # index for blue
3624 font => 'Arial',
3625 size => 12,
3626 bold => 1,
3627 );
3628
3629The most commonly used colours can also be accessed by name. The name acts as a simple alias for the colour index:
3630
3631 black => 8
3632 blue => 12
3633 brown => 16
3634 cyan => 15
3635 gray => 23
3636 green => 17
3637 lime => 11
3638 magenta => 14
3639 navy => 18
3640 orange => 53
3641 pink => 33
3642 purple => 20
3643 red => 10
3644 silver => 22
3645 white => 9
3646 yellow => 13
3647
3648For example:
3649
3650 my $font = $workbook->add_format(color => 'red');
3651
3652Users of VBA in Excel should note that the equivalent colour indices are in the range 1..56 instead of 8..63.
3653
3654If the default palette does not provide a required colour you can override one of the built-in values. This is achieved by using the C<set_custom_color()> workbook method to adjust the RGB (red green blue) components of the colour:
3655
3656 my $ferrari = $workbook->set_custom_color(40, 216, 12, 12);
3657
3658 my $format = $workbook->add_format(
3659 bg_color => $ferrari,
3660 pattern => 1,
3661 border => 1
3662 );
3663
3664 $worksheet->write_blank('A1', $format);
3665
3666The default Excel colour palette is shown in C<palette.html> in the C<docs> directory of the distro. You can generate an Excel version of the palette using C<colors.pl> in the C<examples> directory.
3667
3668
3669
3670
3671=head1 DATES AND TIME IN EXCEL
3672
3673There are two important things to understand about dates and times in Excel:
3674
3675=over 4
3676
3677=item 1 A date/time in Excel is a real number plus an Excel number format.
3678
3679=item 2 Spreadsheet::WriteExcel doesn't automatically convert date/time strings in C<write()> to an Excel date/time.
3680
3681=back
3682
3683These two points are explained in more detail below along with some suggestions on how to convert times and dates to the required format.
3684
3685
3686=head2 An Excel date/time is a number plus a format
3687
3688If you write a date string with C<write()> then all you will get is a string:
3689
3690 $worksheet->write('A1', '02/03/04'); # !! Writes a string not a date. !!
3691
3692Dates and times in Excel are represented by real numbers, for example "Jan 1 2001 12:30 AM" is represented by the number 36892.521.
3693
3694The integer part of the number stores the number of days since the epoch and the fractional part stores the percentage of the day.
3695
3696A date or time in Excel is just like any other number. To have the number display as a date you must apply an Excel number format to it. Here are some examples.
3697
3698 #!/usr/bin/perl -w
3699
3700 use strict;
3701 use Spreadsheet::WriteExcel;
3702
3703 my $workbook = Spreadsheet::WriteExcel->new('date_examples.xls');
3704 my $worksheet = $workbook->add_worksheet();
3705
3706 $worksheet->set_column('A:A', 30); # For extra visibility.
3707
3708 my $number = 39506.5;
3709
3710 $worksheet->write('A1', $number); # 39506.5
3711
3712 my $format2 = $workbook->add_format(num_format => 'dd/mm/yy');
3713 $worksheet->write('A2', $number , $format2); # 28/02/08
3714
3715 my $format3 = $workbook->add_format(num_format => 'mm/dd/yy');
3716 $worksheet->write('A3', $number , $format3); # 02/28/08
3717
3718 my $format4 = $workbook->add_format(num_format => 'd-m-yyyy');
3719 $worksheet->write('A4', $number , $format4); # 28-2-2008
3720
3721 my $format5 = $workbook->add_format(num_format => 'dd/mm/yy hh:mm');
3722 $worksheet->write('A5', $number , $format5); # 28/02/08 12:00
3723
3724 my $format6 = $workbook->add_format(num_format => 'd mmm yyyy');
3725 $worksheet->write('A6', $number , $format6); # 28 Feb 2008
3726
3727 my $format7 = $workbook->add_format(num_format => 'mmm d yyyy hh:mm AM/PM');
3728 $worksheet->write('A7', $number , $format7); # Feb 28 2008 12:00 PM
3729
3730
3731=head2 Spreadsheet::WriteExcel doesn't automatically convert date/time strings
3732
3733Spreadsheet::WriteExcel doesn't automatically convert input date strings into Excel's formatted date numbers due to the large number of possible date formats and also due to the possibility of misinterpretation.
3734
3735For example, does C<02/03/04> mean March 2 2004, February 3 2004 or even March 4 2002.
3736
3737Therefore, in order to handle dates you will have to convert them to numbers and apply an Excel format. Some methods for converting dates are listed in the next section.
3738
3739The most direct way is to convert your dates to the ISO8601 C<yyyy-mm-ddThh:mm:ss.sss> date format and use the C<write_date_time()> worksheet method:
3740
3741 $worksheet->write_date_time('A2', '2001-01-01T12:20', $format);
3742
3743See the C<write_date_time()> section of the documentation for more details.
3744
3745A general methodology for handling date strings with C<write_date_time()> is:
3746
3747 1. Identify incoming date/time strings with a regex.
3748 2. Extract the component parts of the date/time using the same regex.
3749 3. Convert the date/time to the ISO8601 format.
3750 4. Write the date/time using write_date_time() and a number format.
3751
3752Here is an example:
3753
3754 #!/usr/bin/perl -w
3755
3756 use strict;
3757 use Spreadsheet::WriteExcel;
3758
3759 my $workbook = Spreadsheet::WriteExcel->new('example.xls');
3760 my $worksheet = $workbook->add_worksheet();
3761
3762 # Set the default format for dates.
3763 my $date_format = $workbook->add_format(num_format => 'mmm d yyyy');
3764
3765 # Increase column width to improve visibility of data.
3766 $worksheet->set_column('A:C', 20);
3767
3768 # Simulate reading from a data source.
3769 my $row = 0;
3770
3771 while (<DATA>) {
3772 chomp;
3773
3774 my $col = 0;
3775 my @data = split ' ';
3776
3777 for my $item (@data) {
3778
3779 # Match dates in the following formats: d/m/yy, d/m/yyyy
3780 if ($item =~ qr[^(\d{1,2})/(\d{1,2})/(\d{4})$]) {
3781
3782 # Change to the date format required by write_date_time().
3783 my $date = sprintf "%4d-%02d-%02dT", $3, $2, $1;
3784
3785 $worksheet->write_date_time($row, $col++, $date, $date_format);
3786 }
3787 else {
3788 # Just plain data
3789 $worksheet->write($row, $col++, $item);
3790 }
3791 }
3792 $row++;
3793 }
3794
3795 __DATA__
3796 Item Cost Date
3797 Book 10 1/9/2007
3798 Beer 4 12/9/2007
3799 Bed 500 5/10/2007
3800
3801For a slightly more advanced solution you can modify the C<write()> method to handle date formats of your choice via the C<add_write_handler()> method. See the C<add_write_handler()> section of the docs and the write_handler3.pl and write_handler4.pl programs in the examples directory of the distro.
3802
3803
3804=head2 Converting dates and times to an Excel date or time
3805
3806The C<write_date_time()> method above is just one way of handling dates and times.
3807
3808The L<Spreadsheet::WriteExcel::Utility> module which is included in the distro has date/time handling functions:
3809
3810 use Spreadsheet::WriteExcel::Utility;
3811
3812 $date = xl_date_list(2002, 1, 1); # 37257
3813 $date = xl_parse_date("11 July 1997"); # 35622
3814 $time = xl_parse_time('3:21:36 PM'); # 0.64
3815 $date = xl_decode_date_EU("13 May 2002"); # 37389
3816
3817Note: some of these functions require additional CPAN modules.
3818
3819For date conversions using the CPAN C<DateTime> framework see L<DateTime::Format::Excel> L<http://search.cpan.org/search?dist=DateTime-Format-Excel>.
3820
3821
3822
3823
3824=head1 OUTLINES AND GROUPING IN EXCEL
3825
3826
3827Excel allows you to group rows or columns so that they can be hidden or displayed with a single mouse click. This feature is referred to as outlines.
3828
3829Outlines can reduce complex data down to a few salient sub-totals or summaries.
3830
3831This feature is best viewed in Excel but the following is an ASCII representation of what a worksheet with three outlines might look like. Rows 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at level 1. The lines at the left hand side are called outline level bars.
3832
3833
3834 ------------------------------------------
3835 1 2 3 | | A | B | C | D | ...
3836 ------------------------------------------
3837 _ | 1 | A | | | | ...
3838 | _ | 2 | B | | | | ...
3839 | | | 3 | (C) | | | | ...
3840 | | | 4 | (D) | | | | ...
3841 | - | 5 | E | | | | ...
3842 | _ | 6 | F | | | | ...
3843 | | | 7 | (G) | | | | ...
3844 | | | 8 | (H) | | | | ...
3845 | - | 9 | I | | | | ...
3846 - | . | ... | ... | ... | ... | ...
3847
3848
3849Clicking the minus sign on each of the level 2 outlines will collapse and hide the data as shown in the next figure. The minus sign changes to a plus sign to indicate that the data in the outline is hidden.
3850
3851 ------------------------------------------
3852 1 2 3 | | A | B | C | D | ...
3853 ------------------------------------------
3854 _ | 1 | A | | | | ...
3855 | | 2 | B | | | | ...
3856 | + | 5 | E | | | | ...
3857 | | 6 | F | | | | ...
3858 | + | 9 | I | | | | ...
3859 - | . | ... | ... | ... | ... | ...
3860
3861
3862Clicking on the minus sign on the level 1 outline will collapse the remaining rows as follows:
3863
3864 ------------------------------------------
3865 1 2 3 | | A | B | C | D | ...
3866 ------------------------------------------
3867 | 1 | A | | | | ...
3868 + | . | ... | ... | ... | ... | ...
3869
3870
3871Grouping in C<Spreadsheet::WriteExcel> is achieved by setting the outline level via the C<set_row()> and C<set_column()> worksheet methods:
3872
3873 set_row($row, $height, $format, $hidden, $level, $collapsed)
3874 set_column($first_col, $last_col, $width, $format, $hidden, $level, $collapsed)
3875
3876The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed) and columns B to G. The parameters C<$height> and C<$XF> are assigned default values since they are undefined:
3877
3878 $worksheet->set_row(1, undef, undef, 0, 1);
3879 $worksheet->set_row(2, undef, undef, 0, 1);
3880 $worksheet->set_column('B:G', undef, undef, 0, 1);
3881
3882Excel allows up to 7 outline levels. Therefore the C<$level> parameter should be in the range C<0 E<lt>= $level E<lt>= 7>.
3883
3884Rows and columns can be collapsed by setting the C<$hidden> flag for the hidden rows/columns and setting the C<$collapsed> flag for the row/column that has the collapsed C<+> symbol:
3885
3886 $worksheet->set_row(1, undef, undef, 1, 1);
3887 $worksheet->set_row(2, undef, undef, 1, 1);
3888 $worksheet->set_row(3, undef, undef, 0, 0, 1); # Collapsed flag.
3889
3890 $worksheet->set_column('B:G', undef, undef, 1, 1);
3891 $worksheet->set_column('H:H', undef, undef, 0, 0, 1); # Collapsed flag.
3892
3893Note: Setting the C<$collapsed> flag is particularly important for compatibility with OpenOffice.org and Gnumeric.
3894
3895For a more complete example see the C<outline.pl> and C<outline_collapsed.pl> programs in the examples directory of the distro.
3896
3897Some additional outline properties can be set via the C<outline_settings()> worksheet method, see above.
3898
3899
3900
3901
3902=head1 DATA VALIDATION IN EXCEL
3903
3904Data validation is a feature of Excel which allows you to restrict the data that a users enters in a cell and to display help and warning messages. It also allows you to restrict input to values in a drop down list.
3905
3906A typical use case might be to restrict data in a cell to integer values in a certain range, to provide a help message to indicate the required value and to issue a warning if the input data doesn't meet the stated criteria. In Spreadsheet::WriteExcel we could do that as follows:
3907
3908 $worksheet->data_validation('B3',
3909 {
3910 validate => 'integer',
3911 criteria => 'between',
3912 minimum => 1,
3913 maximum => 100,
3914 input_title => 'Input an integer:',
3915 input_message => 'Between 1 and 100',
3916 error_message => 'Sorry, try again.',
3917 });
3918
3919The above example would look like this in Excel: L<http://homepage.eircom.net/~jmcnamara/perl/data_validation.jpg>.
3920
3921=begin html
3922
3923<center>
3924<img src="http://homepage.eircom.net/~jmcnamara/perl/data_validation.jpg" alt="The output from the above example">
3925</center>
3926
3927=end html
3928
3929For more information on data validation see the following Microsoft support article "Description and examples of data validation in Excel": L<http://support.microsoft.com/kb/211485>.
3930
3931The following sections describe how to use the C<data_validation()> method and its various options.
3932
3933
3934=head2 data_validation($row, $col, { parameter => 'value', ... })
3935
3936The C<data_validation()> method is used to construct an Excel data validation.
3937
3938It can be applied to a single cell or a range of cells. You can pass 3 parameters such as C<($row, $col, {...})> or 5 parameters such as C<($first_row, $first_col, $last_row, $last_col, {...})>. You can also use C<A1> style notation. For example:
3939
3940 $worksheet->data_validation(0, 0, {...});
3941 $worksheet->data_validation(0, 0, 4, 1, {...});
3942
3943 # Which are the same as:
3944
3945 $worksheet->data_validation('A1', {...});
3946 $worksheet->data_validation('A1:B5', {...});
3947
3948See also the note about L<Cell notation> for more information.
3949
3950
3951The last parameter in C<data_validation()> must be a hash ref containing the parameters that describe the type and style of the data validation. The allowable parameters are:
3952
3953 validate
3954 criteria
3955 value | minimum | source
3956 maximum
3957 ignore_blank
3958 dropdown
3959
3960 input_title
3961 input_message
3962 show_input
3963
3964 error_title
3965 error_message
3966 error_type
3967 show_error
3968
3969These parameters are explained in the following sections. Most of the parameters are optional, however, you will generally require the three main options C<validate>, C<criteria> and C<value>.
3970
3971 $worksheet->data_validation('B3',
3972 {
3973 validate => 'integer',
3974 criteria => '>',
3975 value => 100,
3976 });
3977
3978The C<data_validation> method returns:
3979
3980 0 for success.
3981 -1 for insufficient number of arguments.
3982 -2 for row or column out of bounds.
3983 -3 for incorrect parameter or value.
3984
3985
3986=head2 validate
3987
3988This parameter is passed in a hash ref to C<data_validation()>.
3989
3990The C<validate> parameter is used to set the type of data that you wish to validate. It is always required and it has no default value. Allowable values are:
3991
3992 any
3993 integer
3994 decimal
3995 list
3996 date
3997 time
3998 length
3999 custom
4000
4001=over
4002
4003=item * B<any> is used to specify that the type of data is unrestricted. This is the same as not applying a data validation. It is only provided for completeness and isn't used very often in the context of Spreadsheet::WriteExcel.
4004
4005=item * B<integer> restricts the cell to integer values. Excel refers to this as 'whole number'.
4006
4007 validate => 'integer',
4008 criteria => '>',
4009 value => 100,
4010
4011=item * B<decimal> restricts the cell to decimal values.
4012
4013 validate => 'decimal',
4014 criteria => '>',
4015 value => 38.6,
4016
4017=item * B<list> restricts the cell to a set of user specified values. These can be passed in an array ref or as a cell range (named ranges aren't currently supported):
4018
4019 validate => 'list',
4020 value => ['open', 'high', 'close'],
4021 # Or like this:
4022 value => 'B1:B3',
4023
4024Excel requires that range references are only to cells on the same worksheet.
4025
4026=item * B<date> restricts the cell to date values. Dates in Excel are expressed as integer values but you can also pass an ISO860 style string as used in C<write_date_time()>. See also L<DATES AND TIME IN EXCEL> for more information about working with Excel's dates.
4027
4028 validate => 'date',
4029 criteria => '>',
4030 value => 39653, # 24 July 2008
4031 # Or like this:
4032 value => '2008-07-24T',
4033
4034=item * B<time> restricts the cell to time values. Times in Excel are expressed as decimal values but you can also pass an ISO860 style string as used in C<write_date_time()>. See also L<DATES AND TIME IN EXCEL> for more information about working with Excel's times.
4035
4036 validate => 'time',
4037 criteria => '>',
4038 value => 0.5, # Noon
4039 # Or like this:
4040 value => 'T12:00:00',
4041
4042=item * B<length> restricts the cell data based on an integer string length. Excel refers to this as 'Text length'.
4043
4044 validate => 'length',
4045 criteria => '>',
4046 value => 10,
4047
4048=item * B<custom> restricts the cell based on an external Excel formula that returns a C<TRUE/FALSE> value.
4049
4050 validate => 'custom',
4051 value => '=IF(A10>B10,TRUE,FALSE)',
4052
4053=back
4054
4055
4056=head2 criteria
4057
4058This parameter is passed in a hash ref to C<data_validation()>.
4059
4060The C<criteria> parameter is used to set the criteria by which the data in the cell is validated. It is almost always required except for the C<list> and C<custom> validate options. It has no default value. Allowable values are:
4061
4062 'between'
4063 'not between'
4064 'equal to' | '==' | '='
4065 'not equal to' | '!=' | '<>'
4066 'greater than' | '>'
4067 'less than' | '<'
4068 'greater than or equal to' | '>='
4069 'less than or equal to' | '<='
4070
4071You can either use Excel's textual description strings, in the first column above, or the more common operator alternatives. The following are equivalent:
4072
4073 validate => 'integer',
4074 criteria => 'greater than',
4075 value => 100,
4076
4077 validate => 'integer',
4078 criteria => '>',
4079 value => 100,
4080
4081The C<list> and C<custom> validate options don't require a C<criteria>. If you specify one it will be ignored.
4082
4083 validate => 'list',
4084 value => ['open', 'high', 'close'],
4085
4086 validate => 'custom',
4087 value => '=IF(A10>B10,TRUE,FALSE)',
4088
4089
4090=head2 value | minimum | source
4091
4092This parameter is passed in a hash ref to C<data_validation()>.
4093
4094The C<value> parameter is used to set the limiting value to which the C<criteria> is applied. It is always required and it has no default value. You can also use the synonyms C<minimum> or C<source> to make the validation a little clearer and closer to Excel's description of the parameter:
4095
4096 # Use 'value'
4097 validate => 'integer',
4098 criteria => '>',
4099 value => 100,
4100
4101 # Use 'minimum'
4102 validate => 'integer',
4103 criteria => 'between',
4104 minimum => 1,
4105 maximum => 100,
4106
4107 # Use 'source'
4108 validate => 'list',
4109 source => 'B1:B3',
4110
4111
4112=head2 maximum
4113
4114This parameter is passed in a hash ref to C<data_validation()>.
4115
4116The C<maximum> parameter is used to set the upper limiting value when the C<criteria> is either C<'between'> or C<'not between'>:
4117
4118 validate => 'integer',
4119 criteria => 'between',
4120 minimum => 1,
4121 maximum => 100,
4122
4123
4124=head2 ignore_blank
4125
4126This parameter is passed in a hash ref to C<data_validation()>.
4127
4128The C<ignore_blank> parameter is used to toggle on and off the 'Ignore blank' option in the Excel data validation dialog. When the option is on the data validation is not applied to blank data in the cell. It is on by default.
4129
4130 ignore_blank => 0, # Turn the option off
4131
4132
4133=head2 dropdown
4134
4135This parameter is passed in a hash ref to C<data_validation()>.
4136
4137The C<dropdown> parameter is used to toggle on and off the 'In-cell dropdown' option in the Excel data validation dialog. When the option is on a dropdown list will be shown for C<list> validations. It is on by default.
4138
4139 dropdown => 0, # Turn the option off
4140
4141
4142=head2 input_title
4143
4144This parameter is passed in a hash ref to C<data_validation()>.
4145
4146The C<input_title> parameter is used to set the title of the input message that is displayed when a cell is entered. It has no default value and is only displayed if the input message is displayed. See the C<input_message> parameter below.
4147
4148 input_title => 'This is the input title',
4149
4150The maximum title length is 32 characters. UTF8 strings are handled automatically in perl 5.8 and later.
4151
4152
4153=head2 input_message
4154
4155This parameter is passed in a hash ref to C<data_validation()>.
4156
4157The C<input_message> parameter is used to set the input message that is displayed when a cell is entered. It has no default value.
4158
4159 validate => 'integer',
4160 criteria => 'between',
4161 minimum => 1,
4162 maximum => 100,
4163 input_title => 'Enter the applied discount:',
4164 input_message => 'between 1 and 100',
4165
4166The message can be split over several lines using newlines, C<"\n"> in double quoted strings.
4167
4168 input_message => "This is\na test.",
4169
4170The maximum message length is 255 characters. UTF8 strings are handled automatically in perl 5.8 and later.
4171
4172
4173=head2 show_input
4174
4175This parameter is passed in a hash ref to C<data_validation()>.
4176
4177The C<show_input> parameter is used to toggle on and off the 'Show input message when cell is selected' option in the Excel data validation dialog. When the option is off an input message is not displayed even if it has been set using C<input_message>. It is on by default.
4178
4179 show_input => 0, # Turn the option off
4180
4181
4182=head2 error_title
4183
4184This parameter is passed in a hash ref to C<data_validation()>.
4185
4186The C<error_title> parameter is used to set the title of the error message that is displayed when the data validation criteria is not met. The default error title is 'Microsoft Excel'.
4187
4188 error_title => 'Input value is not valid',
4189
4190The maximum title length is 32 characters. UTF8 strings are handled automatically in perl 5.8 and later.
4191
4192
4193=head2 error_message
4194
4195This parameter is passed in a hash ref to C<data_validation()>.
4196
4197The C<error_message> parameter is used to set the error message that is displayed when a cell is entered. The default error message is "The value you entered is not valid.\nA user has restricted values that can be entered into the cell.".
4198
4199 validate => 'integer',
4200 criteria => 'between',
4201 minimum => 1,
4202 maximum => 100,
4203 error_title => 'Input value is not valid',
4204 error_message => 'It should be an integer between 1 and 100',
4205
4206The message can be split over several lines using newlines, C<"\n"> in double quoted strings.
4207
4208 input_message => "This is\na test.",
4209
4210The maximum message length is 255 characters. UTF8 strings are handled automatically in perl 5.8 and later.
4211
4212
4213=head2 error_type
4214
4215This parameter is passed in a hash ref to C<data_validation()>.
4216
4217The C<error_type> parameter is used to specify the type of error dialog that is displayed. There are 3 options:
4218
4219 'stop'
4220 'warning'
4221 'information'
4222
4223The default is C<'stop'>.
4224
4225
4226=head2 show_error
4227
4228This parameter is passed in a hash ref to C<data_validation()>.
4229
4230The C<show_error> parameter is used to toggle on and off the 'Show error alert after invalid data is entered' option in the Excel data validation dialog. When the option is off an error message is not displayed even if it has been set using C<error_message>. It is on by default.
4231
4232 show_error => 0, # Turn the option off
4233
4234=head2 Data Validation Examples
4235
4236Example 1. Limiting input to an integer greater than a fixed value.
4237
4238 $worksheet->data_validation('A1',
4239 {
4240 validate => 'integer',
4241 criteria => '>',
4242 value => 0,
4243 });
4244
4245Example 2. Limiting input to an integer greater than a fixed value where the value is referenced from a cell.
4246
4247 $worksheet->data_validation('A2',
4248 {
4249 validate => 'integer',
4250 criteria => '>',
4251 value => '=E3',
4252 });
4253
4254Example 3. Limiting input to a decimal in a fixed range.
4255
4256 $worksheet->data_validation('A3',
4257 {
4258 validate => 'decimal',
4259 criteria => 'between',
4260 minimum => 0.1,
4261 maximum => 0.5,
4262 });
4263
4264Example 4. Limiting input to a value in a dropdown list.
4265
4266 $worksheet->data_validation('A4',
4267 {
4268 validate => 'list',
4269 source => ['open', 'high', 'close'],
4270 });
4271
4272Example 5. Limiting input to a value in a dropdown list where the list is specified as a cell range.
4273
4274 $worksheet->data_validation('A5',
4275 {
4276 validate => 'list',
4277 source => '=E4:G4',
4278 });
4279
4280Example 6. Limiting input to a date in a fixed range.
4281
4282 $worksheet->data_validation('A6',
4283 {
4284 validate => 'date',
4285 criteria => 'between',
4286 minimum => '2008-01-01T',
4287 maximum => '2008-12-12T',
4288 });
4289
4290Example 7. Displaying a message when the cell is selected.
4291
4292 $worksheet->data_validation('A7',
4293 {
4294 validate => 'integer',
4295 criteria => 'between',
4296 minimum => 1,
4297 maximum => 100,
4298 input_title => 'Enter an integer:',
4299 input_message => 'between 1 and 100',
4300 });
4301
4302See also the C<data_validate.pl> program in the examples directory of the distro.
4303
4304
4305
4306
4307=head1 FORMULAS AND FUNCTIONS IN EXCEL
4308
4309
4310=head2 Caveats
4311
4312The first thing to note is that there are still some outstanding issues with the implementation of formulas and functions:
4313
4314 1. Writing a formula is much slower than writing the equivalent string.
4315 2. You cannot use array constants, i.e. {1;2;3}, in functions.
4316 3. Unary minus isn't supported.
4317 4. Whitespace is not preserved around operators.
4318 5. Named ranges are not supported.
4319 6. Array formulas are not supported.
4320
4321However, these constraints will be removed in future versions. They are here because of a trade-off between features and time. Also, it is possible to work around issue 1 using the C<store_formula()> and C<repeat_formula()> methods as described later in this section.
4322
4323
4324
4325=head2 Introduction
4326
4327The following is a brief introduction to formulas and functions in Excel and Spreadsheet::WriteExcel.
4328
4329A formula is a string that begins with an equals sign:
4330
4331 '=A1+B1'
4332 '=AVERAGE(1, 2, 3)'
4333
4334The formula can contain numbers, strings, boolean values, cell references, cell ranges and functions. Named ranges are not supported. Formulas should be written as they appear in Excel, that is cells and functions must be in uppercase.
4335
4336Cells in Excel are referenced using the A1 notation system where the column is designated by a letter and the row by a number. Columns range from A to IV i.e. 0 to 255, rows range from 1 to 65536. The C<Spreadsheet::WriteExcel::Utility> module that is included in the distro contains helper functions for dealing with A1 notation, for example:
4337
4338 use Spreadsheet::WriteExcel::Utility;
4339
4340 ($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
4341 $str = xl_rowcol_to_cell(1, 2); # C2
4342
4343The Excel C<$> notation in cell references is also supported. This allows you to specify whether a row or column is relative or absolute. This only has an effect if the cell is copied. The following examples show relative and absolute values.
4344
4345 '=A1' # Column and row are relative
4346 '=$A1' # Column is absolute and row is relative
4347 '=A$1' # Column is relative and row is absolute
4348 '=$A$1' # Column and row are absolute
4349
4350Formulas can also refer to cells in other worksheets of the current workbook. For example:
4351
4352 '=Sheet2!A1'
4353 '=Sheet2!A1:A5'
4354 '=Sheet2:Sheet3!A1'
4355 '=Sheet2:Sheet3!A1:A5'
4356 q{='Test Data'!A1}
4357 q{='Test Data1:Test Data2'!A1}
4358
4359The sheet reference and the cell reference are separated by C<!> the exclamation mark symbol. If worksheet names contain spaces, commas o parentheses then Excel requires that the name is enclosed in single quotes as shown in the last two examples above. In order to avoid using a lot of escape characters you can use the quote operator C<q{}> to protect the quotes. See C<perlop> in the main Perl documentation. Only valid sheet names that have been added using the C<add_worksheet()> method can be used in formulas. You cannot reference external workbooks.
4360
4361
4362The following table lists the operators that are available in Excel's formulas. The majority of the operators are the same as Perl's, differences are indicated:
4363
4364 Arithmetic operators:
4365 =====================
4366 Operator Meaning Example
4367 + Addition 1+2
4368 - Subtraction 2-1
4369 * Multiplication 2*3
4370 / Division 1/4
4371 ^ Exponentiation 2^3 # Equivalent to **
4372 - Unary minus -(1+2) # Not yet supported
4373 % Percent (Not modulus) 13% # Not supported, [1]
4374
4375
4376 Comparison operators:
4377 =====================
4378 Operator Meaning Example
4379 = Equal to A1 = B1 # Equivalent to ==
4380 <> Not equal to A1 <> B1 # Equivalent to !=
4381 > Greater than A1 > B1
4382 < Less than A1 < B1
4383 >= Greater than or equal to A1 >= B1
4384 <= Less than or equal to A1 <= B1
4385
4386
4387 String operator:
4388 ================
4389 Operator Meaning Example
4390 & Concatenation "Hello " & "World!" # [2]
4391
4392
4393 Reference operators:
4394 ====================
4395 Operator Meaning Example
4396 : Range operator A1:A4 # [3]
4397 , Union operator SUM(1, 2+2, B3) # [4]
4398
4399
4400 Notes:
4401 [1]: You can get a percentage with formatting and modulus with MOD().
4402 [2]: Equivalent to ("Hello " . "World!") in Perl.
4403 [3]: This range is equivalent to cells A1, A2, A3 and A4.
4404 [4]: The comma behaves like the list separator in Perl.
4405
4406The range and comma operators can have different symbols in non-English versions of Excel. These will be supported in a later version of Spreadsheet::WriteExcel. European users of Excel take note:
4407
4408 $worksheet->write('A1', '=SUM(1; 2; 3)'); # Wrong!!
4409 $worksheet->write('A1', '=SUM(1, 2, 3)'); # Okay
4410
4411The following table lists all of the core functions supported by Excel 5 and Spreadsheet::WriteExcel. Any additional functions that are available through the "Analysis ToolPak" or other add-ins are not supported. These functions have all been tested to verify that they work.
4412
4413 ABS DB INDIRECT NORMINV SLN
4414 ACOS DCOUNT INFO NORMSDIST SLOPE
4415 ACOSH DCOUNTA INT NORMSINV SMALL
4416 ADDRESS DDB INTERCEPT NOT SQRT
4417 AND DEGREES IPMT NOW STANDARDIZE
4418 AREAS DEVSQ IRR NPER STDEV
4419 ASIN DGET ISBLANK NPV STDEVP
4420 ASINH DMAX ISERR ODD STEYX
4421 ATAN DMIN ISERROR OFFSET SUBSTITUTE
4422 ATAN2 DOLLAR ISLOGICAL OR SUBTOTAL
4423 ATANH DPRODUCT ISNA PEARSON SUM
4424 AVEDEV DSTDEV ISNONTEXT PERCENTILE SUMIF
4425 AVERAGE DSTDEVP ISNUMBER PERCENTRANK SUMPRODUCT
4426 BETADIST DSUM ISREF PERMUT SUMSQ
4427 BETAINV DVAR ISTEXT PI SUMX2MY2
4428 BINOMDIST DVARP KURT PMT SUMX2PY2
4429 CALL ERROR.TYPE LARGE POISSON SUMXMY2
4430 CEILING EVEN LEFT POWER SYD
4431 CELL EXACT LEN PPMT T
4432 CHAR EXP LINEST PROB TAN
4433 CHIDIST EXPONDIST LN PRODUCT TANH
4434 CHIINV FACT LOG PROPER TDIST
4435 CHITEST FALSE LOG10 PV TEXT
4436 CHOOSE FDIST LOGEST QUARTILE TIME
4437 CLEAN FIND LOGINV RADIANS TIMEVALUE
4438 CODE FINV LOGNORMDIST RAND TINV
4439 COLUMN FISHER LOOKUP RANK TODAY
4440 COLUMNS FISHERINV LOWER RATE TRANSPOSE
4441 COMBIN FIXED MATCH REGISTER.ID TREND
4442 CONCATENATE FLOOR MAX REPLACE TRIM
4443 CONFIDENCE FORECAST MDETERM REPT TRIMMEAN
4444 CORREL FREQUENCY MEDIAN RIGHT TRUE
4445 COS FTEST MID ROMAN TRUNC
4446 COSH FV MIN ROUND TTEST
4447 COUNT GAMMADIST MINUTE ROUNDDOWN TYPE
4448 COUNTA GAMMAINV MINVERSE ROUNDUP UPPER
4449 COUNTBLANK GAMMALN MIRR ROW VALUE
4450 COUNTIF GEOMEAN MMULT ROWS VAR
4451 COVAR GROWTH MOD RSQ VARP
4452 CRITBINOM HARMEAN MODE SEARCH VDB
4453 DATE HLOOKUP MONTH SECOND VLOOKUP
4454 DATEVALUE HOUR N SIGN WEEKDAY
4455 DAVERAGE HYPGEOMDIST NA SIN WEIBULL
4456 DAY IF NEGBINOMDIST SINH YEAR
4457 DAYS360 INDEX NORMDIST SKEW ZTEST
4458
4459You can also modify the module to support function names in the following languages: German, French, Spanish, Portuguese, Dutch, Finnish, Italian and Swedish. See the C<function_locale.pl> program in the C<examples> directory of the distro.
4460
4461For a general introduction to Excel's formulas and an explanation of the syntax of the function refer to the Excel help files or the following: L<http://office.microsoft.com/en-us/assistance/CH062528031033.aspx>.
4462
4463If your formula doesn't work in Spreadsheet::WriteExcel try the following:
4464
4465 1. Verify that the formula works in Excel (or Gnumeric or OpenOffice.org).
4466 2. Ensure that it isn't on the Caveats list shown above.
4467 3. Ensure that cell references and formula names are in uppercase.
4468 4. Ensure that you are using ':' as the range operator, A1:A4.
4469 5. Ensure that you are using ',' as the union operator, SUM(1,2,3).
4470 6. Ensure that the function is in the above table.
4471
4472If you go through steps 1-6 and you still have a problem, mail me.
4473
4474
4475
4476
4477=head2 Improving performance when working with formulas
4478
4479Writing a large number of formulas with Spreadsheet::WriteExcel can be slow. This is due to the fact that each formula has to be parsed and with the current implementation this is computationally expensive.
4480
4481However, in a lot of cases the formulas that you write will be quite similar, for example:
4482
4483 $worksheet->write_formula('B1', '=A1 * 3 + 50', $format);
4484 $worksheet->write_formula('B2', '=A2 * 3 + 50', $format);
4485 ...
4486 ...
4487 $worksheet->write_formula('B99', '=A999 * 3 + 50', $format);
4488 $worksheet->write_formula('B1000', '=A1000 * 3 + 50', $format);
4489
4490In this example the cell reference changes in iterations from C<A1> to C<A1000>. The parser treats this variable as a I<token> and arranges it according to predefined rules. However, since the parser is oblivious to the value of the token, it is essentially performing the same calculation 1000 times. This is inefficient.
4491
4492The way to avoid this inefficiency and thereby speed up the writing of formulas is to parse the formula once and then repeatedly substitute similar tokens.
4493
4494A formula can be parsed and stored via the C<store_formula()> worksheet method. You can then use the C<repeat_formula()> method to substitute C<$pattern>, C<$replace> pairs in the stored formula:
4495
4496 my $formula = $worksheet->store_formula('=A1 * 3 + 50');
4497
4498 for my $row (0..999) {
4499 $worksheet->repeat_formula($row, 1, $formula, $format, 'A1', 'A'.($row +1));
4500 }
4501
4502On an arbitrary test machine this method was 10 times faster than the brute force method shown above.
4503
4504For more information about how Spreadsheet::WriteExcel parses and stores formulas see the C<Spreadsheet::WriteExcel::Formula> man page.
4505
4506It should be noted however that the overall speed of direct formula parsing will be improved in a future version.
4507
4508
4509
4510
4511=head1 EXAMPLES
4512
4513See L<Spreadsheet::WriteExcel::Examples> for a full list of examples.
4514
4515
4516=head2 Example 1
4517
4518The following example shows some of the basic features of Spreadsheet::WriteExcel.
4519
4520
4521 #!/usr/bin/perl -w
4522
4523 use strict;
4524 use Spreadsheet::WriteExcel;
4525
4526 # Create a new workbook called simple.xls and add a worksheet
4527 my $workbook = Spreadsheet::WriteExcel->new('simple.xls');
4528 my $worksheet = $workbook->add_worksheet();
4529
4530 # The general syntax is write($row, $column, $token). Note that row and
4531 # column are zero indexed
4532
4533 # Write some text
4534 $worksheet->write(0, 0, 'Hi Excel!');
4535
4536
4537 # Write some numbers
4538 $worksheet->write(2, 0, 3); # Writes 3
4539 $worksheet->write(3, 0, 3.00000); # Writes 3
4540 $worksheet->write(4, 0, 3.00001); # Writes 3.00001
4541 $worksheet->write(5, 0, 3.14159); # TeX revision no.?
4542
4543
4544 # Write some formulas
4545 $worksheet->write(7, 0, '=A3 + A6');
4546 $worksheet->write(8, 0, '=IF(A5>3,"Yes", "No")');
4547
4548
4549 # Write a hyperlink
4550 $worksheet->write(10, 0, 'http://www.perl.com/');
4551
4552
4553=begin html
4554
4555<p><center><img src="http://homepage.eircom.net/~jmcnamara/perl/images/a_simple.jpg" width="640" height="420" alt="Output from a_simple.pl" /></center></p>
4556
4557=end html
4558
4559
4560
4561
4562=head2 Example 2
4563
4564The following is a general example which demonstrates some features of working with multiple worksheets.
4565
4566 #!/usr/bin/perl -w
4567
4568 use strict;
4569 use Spreadsheet::WriteExcel;
4570
4571 # Create a new Excel workbook
4572 my $workbook = Spreadsheet::WriteExcel->new('regions.xls');
4573
4574 # Add some worksheets
4575 my $north = $workbook->add_worksheet('North');
4576 my $south = $workbook->add_worksheet('South');
4577 my $east = $workbook->add_worksheet('East');
4578 my $west = $workbook->add_worksheet('West');
4579
4580 # Add a Format
4581 my $format = $workbook->add_format();
4582 $format->set_bold();
4583 $format->set_color('blue');
4584
4585 # Add a caption to each worksheet
4586 foreach my $worksheet ($workbook->sheets()) {
4587 $worksheet->write(0, 0, 'Sales', $format);
4588 }
4589
4590 # Write some data
4591 $north->write(0, 1, 200000);
4592 $south->write(0, 1, 100000);
4593 $east->write (0, 1, 150000);
4594 $west->write (0, 1, 100000);
4595
4596 # Set the active worksheet
4597 $south->activate();
4598
4599 # Set the width of the first column
4600 $south->set_column(0, 0, 20);
4601
4602 # Set the active cell
4603 $south->set_selection(0, 1);
4604
4605
4606=begin html
4607
4608<p><center><img src="http://homepage.eircom.net/~jmcnamara/perl/images/regions.jpg" width="640" height="420" alt="Output from regions.pl" /></center></p>
4609
4610=end html
4611
4612
4613
4614
4615=head2 Example 3
4616
4617This example shows how to use a conditional numerical format with colours to indicate if a share price has gone up or down.
4618
4619 use strict;
4620 use Spreadsheet::WriteExcel;
4621
4622 # Create a new workbook and add a worksheet
4623 my $workbook = Spreadsheet::WriteExcel->new('stocks.xls');
4624 my $worksheet = $workbook->add_worksheet();
4625
4626 # Set the column width for columns 1, 2, 3 and 4
4627 $worksheet->set_column(0, 3, 15);
4628
4629
4630 # Create a format for the column headings
4631 my $header = $workbook->add_format();
4632 $header->set_bold();
4633 $header->set_size(12);
4634 $header->set_color('blue');
4635
4636
4637 # Create a format for the stock price
4638 my $f_price = $workbook->add_format();
4639 $f_price->set_align('left');
4640 $f_price->set_num_format('$0.00');
4641
4642
4643 # Create a format for the stock volume
4644 my $f_volume = $workbook->add_format();
4645 $f_volume->set_align('left');
4646 $f_volume->set_num_format('#,##0');
4647
4648
4649 # Create a format for the price change. This is an example of a
4650 # conditional format. The number is formatted as a percentage. If it is
4651 # positive it is formatted in green, if it is negative it is formatted
4652 # in red and if it is zero it is formatted as the default font colour
4653 # (in this case black). Note: the [Green] format produces an unappealing
4654 # lime green. Try [Color 10] instead for a dark green.
4655 #
4656 my $f_change = $workbook->add_format();
4657 $f_change->set_align('left');
4658 $f_change->set_num_format('[Green]0.0%;[Red]-0.0%;0.0%');
4659
4660
4661 # Write out the data
4662 $worksheet->write(0, 0, 'Company',$header);
4663 $worksheet->write(0, 1, 'Price', $header);
4664 $worksheet->write(0, 2, 'Volume', $header);
4665 $worksheet->write(0, 3, 'Change', $header);
4666
4667 $worksheet->write(1, 0, 'Damage Inc.' );
4668 $worksheet->write(1, 1, 30.25, $f_price ); # $30.25
4669 $worksheet->write(1, 2, 1234567, $f_volume); # 1,234,567
4670 $worksheet->write(1, 3, 0.085, $f_change); # 8.5% in green
4671
4672 $worksheet->write(2, 0, 'Dump Corp.' );
4673 $worksheet->write(2, 1, 1.56, $f_price ); # $1.56
4674 $worksheet->write(2, 2, 7564, $f_volume); # 7,564
4675 $worksheet->write(2, 3, -0.015, $f_change); # -1.5% in red
4676
4677 $worksheet->write(3, 0, 'Rev Ltd.' );
4678 $worksheet->write(3, 1, 0.13, $f_price ); # $0.13
4679 $worksheet->write(3, 2, 321, $f_volume); # 321
4680 $worksheet->write(3, 3, 0, $f_change); # 0 in the font color (black)
4681
4682
4683=begin html
4684
4685<p><center><img src="http://homepage.eircom.net/~jmcnamara/perl/images/stocks.jpg" width="640" height="420" alt="Output from stocks.pl" /></center></p>
4686
4687=end html
4688
4689
4690
4691
4692=head2 Example 4
4693
4694The following is a simple example of using functions.
4695
4696 #!/usr/bin/perl -w
4697
4698 use strict;
4699 use Spreadsheet::WriteExcel;
4700
4701 # Create a new workbook and add a worksheet
4702 my $workbook = Spreadsheet::WriteExcel->new('stats.xls');
4703 my $worksheet = $workbook->add_worksheet('Test data');
4704
4705 # Set the column width for columns 1
4706 $worksheet->set_column(0, 0, 20);
4707
4708
4709 # Create a format for the headings
4710 my $format = $workbook->add_format();
4711 $format->set_bold();
4712
4713
4714 # Write the sample data
4715 $worksheet->write(0, 0, 'Sample', $format);
4716 $worksheet->write(0, 1, 1);
4717 $worksheet->write(0, 2, 2);
4718 $worksheet->write(0, 3, 3);
4719 $worksheet->write(0, 4, 4);
4720 $worksheet->write(0, 5, 5);
4721 $worksheet->write(0, 6, 6);
4722 $worksheet->write(0, 7, 7);
4723 $worksheet->write(0, 8, 8);
4724
4725 $worksheet->write(1, 0, 'Length', $format);
4726 $worksheet->write(1, 1, 25.4);
4727 $worksheet->write(1, 2, 25.4);
4728 $worksheet->write(1, 3, 24.8);
4729 $worksheet->write(1, 4, 25.0);
4730 $worksheet->write(1, 5, 25.3);
4731 $worksheet->write(1, 6, 24.9);
4732 $worksheet->write(1, 7, 25.2);
4733 $worksheet->write(1, 8, 24.8);
4734
4735 # Write some statistical functions
4736 $worksheet->write(4, 0, 'Count', $format);
4737 $worksheet->write(4, 1, '=COUNT(B1:I1)');
4738
4739 $worksheet->write(5, 0, 'Sum', $format);
4740 $worksheet->write(5, 1, '=SUM(B2:I2)');
4741
4742 $worksheet->write(6, 0, 'Average', $format);
4743 $worksheet->write(6, 1, '=AVERAGE(B2:I2)');
4744
4745 $worksheet->write(7, 0, 'Min', $format);
4746 $worksheet->write(7, 1, '=MIN(B2:I2)');
4747
4748 $worksheet->write(8, 0, 'Max', $format);
4749 $worksheet->write(8, 1, '=MAX(B2:I2)');
4750
4751 $worksheet->write(9, 0, 'Standard Deviation', $format);
4752 $worksheet->write(9, 1, '=STDEV(B2:I2)');
4753
4754 $worksheet->write(10, 0, 'Kurtosis', $format);
4755 $worksheet->write(10, 1, '=KURT(B2:I2)');
4756
4757
4758=begin html
4759
4760<p><center><img src="http://homepage.eircom.net/~jmcnamara/perl/images/stats.jpg" width="640" height="420" alt="Output from stats.pl" /></center></p>
4761
4762=end html
4763
4764
4765
4766
4767=head2 Example 5
4768
4769The following example converts a tab separated file called C<tab.txt> into an Excel file called C<tab.xls>.
4770
4771 #!/usr/bin/perl -w
4772
4773 use strict;
4774 use Spreadsheet::WriteExcel;
4775
4776 open (TABFILE, 'tab.txt') or die "tab.txt: $!";
4777
4778 my $workbook = Spreadsheet::WriteExcel->new('tab.xls');
4779 my $worksheet = $workbook->add_worksheet();
4780
4781 # Row and column are zero indexed
4782 my $row = 0;
4783
4784 while (<TABFILE>) {
4785 chomp;
4786 # Split on single tab
4787 my @Fld = split('\t', $_);
4788
4789 my $col = 0;
4790 foreach my $token (@Fld) {
4791 $worksheet->write($row, $col, $token);
4792 $col++;
4793 }
4794 $row++;
4795 }
4796
4797
4798NOTE: This is a simple conversion program for illustrative purposes only. For converting a CSV or Tab separated or any other type of delimited text file to Excel I recommend the more rigorous csv2xls program that is part of H.Merijn Brand's Text::CSV_XS module distro.
4799
4800See the examples/csv2xls link here: L<http://search.cpan.org/~hmbrand/Text-CSV_XS/MANIFEST>.
4801
4802
4803
4804
4805=head2 Additional Examples
4806
4807The following is a description of the example files that are provided
4808in the standard Spreadsheet::WriteExcel distribution. They demonstrate the
4809different features and options of the module.
4810See L<Spreadsheet::WriteExcel::Examples> for more details.
4811
4812 Getting started
4813 ===============
4814 a_simple.pl A get started example with some basic features.
4815 demo.pl A demo of some of the available features.
4816 regions.pl A simple example of multiple worksheets.
4817 stats.pl Basic formulas and functions.
4818 formats.pl All the available formatting on several worksheets.
4819 bug_report.pl A template for submitting bug reports.
4820
4821
4822 Advanced
4823 ========
4824 autofilter.pl Examples of worksheet autofilters.
4825 autofit.pl Simulate Excel's autofit for column widths.
4826 bigfile.pl Write past the 7MB limit with OLE::Storage_Lite.
4827 cgi.pl A simple CGI program.
4828 chart_area.pl A demo of area style charts.
4829 chart_bar.pl A demo of bar (vertical histogram) style charts.
4830 chart_column.pl A demo of column (histogram) style charts.
4831 chart_line.pl A demo of line style charts.
4832 chart_pie.pl A demo of pie style charts.
4833 chart_scatter.pl A demo of scatter style charts.
4834 chart_stock.pl A demo of stock style charts.
4835 chess.pl An example of reusing formatting via properties.
4836 colors.pl A demo of the colour palette and named colours.
4837 comments1.pl Add comments to worksheet cells.
4838 comments2.pl Add comments with advanced options.
4839 copyformat.pl Example of copying a cell format.
4840 data_validate.pl An example of data validation and dropdown lists.
4841 date_time.pl Write dates and times with write_date_time().
4842 defined_name.pl Example of how to create defined names.
4843 diag_border.pl A simple example of diagonal cell borders.
4844 easter_egg.pl Expose the Excel97 flight simulator.
4845 filehandle.pl Examples of working with filehandles.
4846 formula_result.pl Formulas with user specified results.
4847 headers.pl Examples of worksheet headers and footers.
4848 hide_sheet.pl Simple example of hiding a worksheet.
4849 hyperlink1.pl Shows how to create web hyperlinks.
4850 hyperlink2.pl Examples of internal and external hyperlinks.
4851 images.pl Adding images to worksheets.
4852 indent.pl An example of cell indentation.
4853 merge1.pl A simple example of cell merging.
4854 merge2.pl A simple example of cell merging with formatting.
4855 merge3.pl Add hyperlinks to merged cells.
4856 merge4.pl An advanced example of merging with formatting.
4857 merge5.pl An advanced example of merging with formatting.
4858 merge6.pl An example of merging with Unicode strings.
4859 mod_perl1.pl A simple mod_perl 1 program.
4860 mod_perl2.pl A simple mod_perl 2 program.
4861 outline.pl An example of outlines and grouping.
4862 outline_collapsed.pl An example of collapsed outlines.
4863 panes.pl An examples of how to create panes.
4864 properties.pl Add document properties to a workbook.
4865 protection.pl Example of cell locking and formula hiding.
4866 repeat.pl Example of writing repeated formulas.
4867 right_to_left.pl Change default sheet direction to right to left.
4868 row_wrap.pl How to wrap data from one worksheet onto another.
4869 sales.pl An example of a simple sales spreadsheet.
4870 sendmail.pl Send an Excel email attachment using Mail::Sender.
4871 stats_ext.pl Same as stats.pl with external references.
4872 stocks.pl Demonstrates conditional formatting.
4873 tab_colors.pl Example of how to set worksheet tab colours.
4874 textwrap.pl Demonstrates text wrapping options.
4875 win32ole.pl A sample Win32::OLE example for comparison.
4876 write_arrays.pl Example of writing 1D or 2D arrays of data.
4877 write_handler1.pl Example of extending the write() method. Step 1.
4878 write_handler2.pl Example of extending the write() method. Step 2.
4879 write_handler3.pl Example of extending the write() method. Step 3.
4880 write_handler4.pl Example of extending the write() method. Step 4.
4881 write_to_scalar.pl Example of writing an Excel file to a Perl scalar.
4882
4883
4884 Unicode
4885 =======
4886 unicode_utf16.pl Simple example of using Unicode UTF16 strings.
4887 unicode_utf16_japan.pl Write Japanese Unicode strings using UTF-16.
4888 unicode_cyrillic.pl Write Russian Cyrillic strings using UTF-8.
4889 unicode_list.pl List the chars in a Unicode font.
4890 unicode_2022_jp.pl Japanese: ISO-2022-JP to utf8 in perl 5.8.
4891 unicode_8859_11.pl Thai: ISO-8859_11 to utf8 in perl 5.8.
4892 unicode_8859_7.pl Greek: ISO-8859_7 to utf8 in perl 5.8.
4893 unicode_big5.pl Chinese: BIG5 to utf8 in perl 5.8.
4894 unicode_cp1251.pl Russian: CP1251 to utf8 in perl 5.8.
4895 unicode_cp1256.pl Arabic: CP1256 to utf8 in perl 5.8.
4896 unicode_koi8r.pl Russian: KOI8-R to utf8 in perl 5.8.
4897 unicode_polish_utf8.pl Polish : UTF8 to utf8 in perl 5.8.
4898 unicode_shift_jis.pl Japanese: Shift JIS to utf8 in perl 5.8.
4899
4900
4901 Utility
4902 =======
4903 csv2xls.pl Program to convert a CSV file to an Excel file.
4904 tab2xls.pl Program to convert a tab separated file to xls.
4905 datecalc1.pl Convert Unix/Perl time to Excel time.
4906 datecalc2.pl Calculate an Excel date using Date::Calc.
4907 lecxe.pl Convert Excel to WriteExcel using Win32::OLE.
4908
4909
4910 Developer
4911 =========
4912 convertA1.pl Helper functions for dealing with A1 notation.
4913 function_locale.pl Add non-English function names to Formula.pm.
4914 writeA1.pl Example of how to extend the module.
4915
4916
4917
4918=head1 LIMITATIONS
4919
4920The following limits are imposed by Excel:
4921
4922 Description Limit
4923 ----------------------------------- ------
4924 Maximum number of chars in a string 32767
4925 Maximum number of columns 256
4926 Maximum number of rows 65536
4927 Maximum chars in a sheet name 31
4928 Maximum chars in a header/footer 254
4929
4930
4931The minimum file size is 6K due to the OLE overhead. The maximum file size is approximately 7MB (7087104 bytes) of BIFF data. This can be extended by installing Takanori Kawai's OLE::Storage_Lite module L<http://search.cpan.org/search?dist=OLE-Storage_Lite> see the C<bigfile.pl> example in the C<examples> directory of the distro.
4932
4933
4934
4935
4936=head1 DOWNLOADING
4937
4938The latest version of this module is always available at: L<http://search.cpan.org/search?dist=Spreadsheet-WriteExcel/>.
4939
4940
4941
4942
4943=head1 REQUIREMENTS
4944
4945This module requires Perl >= 5.005, Parse::RecDescent, File::Temp and OLE::Storage_Lite:
4946
4947 http://search.cpan.org/search?dist=Parse-RecDescent/ # For formulas.
4948 http://search.cpan.org/search?dist=File-Temp/ # For set_tempdir().
4949 http://search.cpan.org/search?dist=OLE-Storage_Lite/ # For files > 7MB.
4950
4951Note, these aren't strict requirements. Spreadsheet::WriteExcel will work without these modules if you don't use write_formula(), set_tempdir() or create files greater than 7MB. However, it is best to install them if possible and they will be installed automatically if you use a tool such as CPAN.pm or ppm.
4952
4953
4954=head1 INSTALLATION
4955
4956See the INSTALL or install.html docs that come with the distribution or: L<http://search.cpan.org/src/JMCNAMARA/Spreadsheet-WriteExcel-2.31/INSTALL>.
4957
4958
4959
4960
4961=head1 PORTABILITY
4962
4963Spreadsheet::WriteExcel will work on the majority of Windows, UNIX and Macintosh platforms. Specifically, the module will work on any system where perl packs floats in the 64 bit IEEE format. The float must also be in little-endian format but it will be reversed if necessary. Thus:
4964
4965 print join(' ', map { sprintf '%#02x', $_ } unpack('C*', pack 'd', 1.2345)), "\n";
4966
4967should give (or in reverse order):
4968
4969 0x8d 0x97 0x6e 0x12 0x83 0xc0 0xf3 0x3f
4970
4971In general, if you don't know whether your system supports a 64 bit IEEE float or not, it probably does. If your system doesn't, WriteExcel will C<croak()> with the message given in the L<DIAGNOSTICS> section. You can check which platforms the module has been tested on at the CPAN testers site: L<http://testers.cpan.org/search?request=dist&dist=Spreadsheet-WriteExcel>.
4972
4973
4974
4975
4976=head1 DIAGNOSTICS
4977
4978
4979=over 4
4980
4981=item Filename required by Spreadsheet::WriteExcel->new()
4982
4983A filename must be given in the constructor.
4984
4985=item Can't open filename. It may be in use or protected.
4986
4987The file cannot be opened for writing. The directory that you are writing to may be protected or the file may be in use by another program.
4988
4989=item Unable to create tmp files via File::Temp::tempfile()...
4990
4991This is a C<-w> warning. You will see it if you are using Spreadsheet::WriteExcel in an environment where temporary files cannot be created, in which case all data will be stored in memory. The warning is for information only: it does not affect creation but it will affect the speed of execution for large files. See the C<set_tempdir> workbook method.
4992
4993
4994=item Maximum file size, 7087104, exceeded.
4995
4996The current OLE implementation only supports a maximum BIFF file of this size. This limit can be extended, see the L<LIMITATIONS> section.
4997
4998=item Can't locate Parse/RecDescent.pm in @INC ...
4999
5000Spreadsheet::WriteExcel requires the Parse::RecDescent module. Download it from CPAN: L<http://search.cpan.org/search?dist=Parse-RecDescent>
5001
5002=item Couldn't parse formula ...
5003
5004There are a large number of warnings which relate to badly formed formulas and functions. See the L<FORMULAS AND FUNCTIONS IN EXCEL> section for suggestions on how to avoid these errors. You should also check the formula in Excel to ensure that it is valid.
5005
5006=item Required floating point format not supported on this platform.
5007
5008Operating system doesn't support 64 bit IEEE float or it is byte-ordered in a way unknown to WriteExcel.
5009
5010
5011=item 'file.xls' cannot be accessed. The file may be read-only ...
5012
5013You may sometimes encounter the following error when trying to open a file in Excel: "file.xls cannot be accessed. The file may be read-only, or you may be trying to access a read-only location. Or, the server the document is stored on may not be responding."
5014
5015This error generally means that the Excel file has been corrupted. There are two likely causes of this: the file was FTPed in ASCII mode instead of binary mode or else the file was created with C<UTF-8> data returned by an XML parser. See L<Warning about XML::Parser and perl 5.6> for further details.
5016
5017=back
5018
5019
5020
5021
5022=head1 THE EXCEL BINARY FORMAT
5023
5024The following is some general information about the Excel binary format for anyone who may be interested.
5025
5026Excel data is stored in the "Binary Interchange File Format" (BIFF) file format. Details of this format are given in "Excel 97-2007 Binary File Format Specification" L<http://www.microsoft.com/interop/docs/OfficeBinaryFormats.mspx>.
5027
5028Daniel Rentz of OpenOffice.org has also written a detailed description of the Excel workbook records, see L<http://sc.openoffice.org/excelfileformat.pdf>.
5029
5030Charles Wybble has collected together additional information about the Excel file format. See "The Chicago Project" at L<http://chicago.sourceforge.net/devel/>.
5031
5032The BIFF data is stored along with other data in an OLE Compound File. This is a structured storage which acts like a file system within a file. A Compound File is comprised of storages and streams which, to follow the file system analogy, are like directories and files.
5033
5034The OLE format is explained in the "Windows Compound Binary File Format Specification" L<http://www.microsoft.com/interop/docs/supportingtechnologies.mspx>
5035
5036The Digital Imaging Group have also detailed the OLE format in the JPEG2000 specification: see Appendix A of L<http://www.i3a.org/pdf/wg1n1017.pdf>.
5037
5038Please note that the provision of this information does not constitute an invitation to start hacking at the BIFF or OLE file formats. There are more interesting ways to waste your time. ;-)
5039
5040
5041
5042
5043=head1 WRITING EXCEL FILES
5044
5045Depending on your requirements, background and general sensibilities you may prefer one of the following methods of getting data into Excel:
5046
5047=over 4
5048
5049=item * Win32::OLE module and office automation
5050
5051This requires a Windows platform and an installed copy of Excel. This is the most powerful and complete method for interfacing with Excel. See L<http://www.activestate.com/ASPN/Reference/Products/ActivePerl-5.6/faq/Windows/ActivePerl-Winfaq12.html> and L<http://www.activestate.com/ASPN/Reference/Products/ActivePerl-5.6/site/lib/Win32/OLE.html>. If your main platform is UNIX but you have the resources to set up a separate Win32/MSOffice server, you can convert office documents to text, postscript or PDF using Win32::OLE. For a demonstration of how to do this using Perl see Docserver: L<http://search.cpan.org/search?mode=module&query=docserver>.
5052
5053=item * CSV, comma separated variables or text
5054
5055If the file extension is C<csv>, Excel will open and convert this format automatically. Generating a valid CSV file isn't as easy as it seems. Have a look at the DBD::RAM, DBD::CSV, Text::xSV and Text::CSV_XS modules.
5056
5057=item * DBI with DBD::ADO or DBD::ODBC
5058
5059Excel files contain an internal index table that allows them to act like a database file. Using one of the standard Perl database modules you can connect to an Excel file as a database.
5060
5061=item * DBD::Excel
5062
5063You can also access Spreadsheet::WriteExcel using the standard DBI interface via Takanori Kawai's DBD::Excel module L<http://search.cpan.org/dist/DBD-Excel>
5064
5065=item * Spreadsheet::WriteExcelXML
5066
5067This module allows you to create an Excel XML file using the same interface as Spreadsheet::WriteExcel. See: L<http://search.cpan.org/dist/Spreadsheet-WriteExcelXML>
5068
5069=item * Excel::Template
5070
5071This module allows you to create an Excel file from an XML template in a manner similar to HTML::Template. See L<http://search.cpan.org/dist/Excel-Template/>.
5072
5073=item * Spreadsheet::WriteExcel::FromXML
5074
5075This module allows you to turn a simple XML file into an Excel file using Spreadsheet::WriteExcel as a back-end. The format of the XML file is defined by a supplied DTD: L<http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromXML>.
5076
5077=item * Spreadsheet::WriteExcel::Simple
5078
5079This provides an easier interface to Spreadsheet::WriteExcel: L<http://search.cpan.org/dist/Spreadsheet-WriteExcel-Simple>.
5080
5081=item * Spreadsheet::WriteExcel::FromDB
5082
5083This is a useful module for creating Excel files directly from a DB table: L<http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromDB>.
5084
5085=item * HTML tables
5086
5087This is an easy way of adding formatting via a text based format.
5088
5089=item * XML or HTML
5090
5091The Excel XML and HTML file specification are available from L<http://msdn.microsoft.com/library/officedev/ofxml2k/ofxml2k.htm>.
5092
5093=back
5094
5095For other Perl-Excel modules try the following search: L<http://search.cpan.org/search?mode=module&query=excel>.
5096
5097
5098
5099
5100=head1 READING EXCEL FILES
5101
5102To read data from Excel files try:
5103
5104=over 4
5105
5106=item * Spreadsheet::ParseExcel
5107
5108This uses the OLE::Storage-Lite module to extract data from an Excel file. L<http://search.cpan.org/dist/Spreadsheet-ParseExcel>.
5109
5110=item * Spreadsheet::ParseExcel_XLHTML
5111
5112This module uses Spreadsheet::ParseExcel's interface but uses xlHtml (see below) to do the conversion: L<http://search.cpan.org/dist/Spreadsheet-ParseExcel_XLHTML>
5113Spreadsheet::ParseExcel_XLHTML
5114
5115=item * xlHtml
5116
5117This is an open source "Excel to HTML Converter" C/C++ project at L<http://chicago.sourceforge.net/xlhtml/>.
5118
5119=item * DBD::Excel (reading)
5120
5121You can also access Spreadsheet::ParseExcel using the standard DBI interface via Takanori Kawai's DBD::Excel module L<http://search.cpan.org/dist/DBD-Excel>.
5122
5123=item * Win32::OLE module and office automation (reading)
5124
5125See, the section L<WRITING EXCEL FILES>.
5126
5127=item * HTML tables (reading)
5128
5129If the files are saved from Excel in a HTML format the data can be accessed using HTML::TableExtract L<http://search.cpan.org/dist/HTML-TableExtract>.
5130
5131=item * DBI with DBD::ADO or DBD::ODBC.
5132
5133See, the section L<WRITING EXCEL FILES>.
5134
5135=item * XML::Excel
5136
5137Converts Excel files to XML using Spreadsheet::ParseExcel L<http://search.cpan.org/dist/XML-Excel>.
5138
5139=item * OLE::Storage, aka LAOLA
5140
5141This is a Perl interface to OLE file formats. In particular, the distro contains an Excel to HTML converter called Herbert, L<http://user.cs.tu-berlin.de/~schwartz/pmh/>. This has been superseded by the Spreadsheet::ParseExcel module.
5142
5143=back
5144
5145
5146For other Perl-Excel modules try the following search: L<http://search.cpan.org/search?mode=module&query=excel>.
5147
5148If you wish to view Excel files on a UNIX/Linux platform check out the excellent Gnumeric spreadsheet application at L<http://www.gnome.org/projects/gnumeric/> or OpenOffice.org at L<http://www.openoffice.org/>.
5149
5150If you wish to view Excel files on a Windows platform which doesn't have Excel installed you can use the free Microsoft Excel Viewer L<http://office.microsoft.com/downloads/2000/xlviewer.aspx>.
5151
5152
5153
5154
5155=head1 MODIFYING AND REWRITING EXCEL FILES
5156
5157An Excel file is a binary file within a binary file. It contains several interlinked checksums and changing even one byte can cause it to become corrupted.
5158
5159As such you cannot simply append or update an Excel file. The only way to achieve this is to read the entire file into memory, make the required changes or additions and then write the file out again.
5160
5161You can read and rewrite an Excel file using the Spreadsheet::ParseExcel::SaveParser module which is a wrapper around Spreadsheet::ParseExcel and Spreadsheet::WriteExcel. It is part of the Spreadsheet::ParseExcel package: L<http://search.cpan.org/search?dist=Spreadsheet-ParseExcel>.
5162
5163However, you can only rewrite the features that Spreadsheet::WriteExcel supports so macros, graphs and some other features in the original Excel file will be lost. Also, formulas aren't rewritten, only the result of a formula is written.
5164
5165Here is an example:
5166
5167 #!/usr/bin/perl -w
5168
5169 use strict;
5170 use Spreadsheet::ParseExcel;
5171 use Spreadsheet::ParseExcel::SaveParser;
5172
5173 # Open the template with SaveParser
5174 my $parser = new Spreadsheet::ParseExcel::SaveParser;
5175 my $template = $parser->Parse('template.xls');
5176
5177 my $sheet = 0;
5178 my $row = 0;
5179 my $col = 0;
5180
5181 # Get the format from the cell
5182 my $format = $template->{Worksheet}[$sheet]
5183 ->{Cells}[$row][$col]
5184 ->{FormatNo};
5185
5186 # Write data to some cells
5187 $template->AddCell(0, $row, $col, 1, $format);
5188 $template->AddCell(0, $row+1, $col, "Hello", $format);
5189
5190 # Add a new worksheet
5191 $template->AddWorksheet('New Data');
5192
5193 # The SaveParser SaveAs() method returns a reference to a
5194 # Spreadsheet::WriteExcel object. If you wish you can then
5195 # use this to access any of the methods that aren't
5196 # available from the SaveParser object. If you don't need
5197 # to do this just use SaveAs().
5198 #
5199 my $workbook;
5200
5201 {
5202 # SaveAs generates a lot of harmless warnings about unset
5203 # Worksheet properties. You can ignore them if you wish.
5204 local $^W = 0;
5205
5206 # Rewrite the file or save as a new file
5207 $workbook = $template->SaveAs('new.xls');
5208 }
5209
5210 # Use Spreadsheet::WriteExcel methods
5211 my $worksheet = $workbook->sheets(0);
5212
5213 $worksheet->write($row+2, $col, "World2");
5214
5215 $workbook->close();
5216
5217
5218
5219
5220=head1 Warning about XML::Parser and perl 5.6
5221
5222You must be careful when using Spreadsheet::WriteExcel in conjunction with perl 5.6 and XML::Parser (and other XML parsers) due to the fact that the data returned by the parser is generally in C<UTF-8> format.
5223
5224When C<UTF-8> strings are added to Spreadsheet::WriteExcel's internal data it causes the generated Excel file to become corrupt.
5225
5226Note, this doesn't affect perl 5.005 (which doesn't try to handle C<UTF-8>) or 5.8 (which handles it correctly).
5227
5228To avoid this problem you should upgrade to perl 5.8, if possible, or else you should convert the output data from XML::Parser to ASCII or ISO-8859-1 using one of the following methods:
5229
5230 $new_str = pack 'C*', unpack 'U*', $utf8_str;
5231
5232
5233 use Unicode::MapUTF8 'from_utf8';
5234 $new_str = from_utf8({-str => $utf8_str, -charset => 'ISO-8859-1'});
5235
5236
5237
5238
5239=head1 Warning about Office Service Pack 3
5240
5241If you have Office Service Pack 3 (SP3) installed you may see the following warning when you open a file created by Spreadsheet::WriteExcel:
5242
5243 "File Error: data may have been lost".
5244
5245This is usually caused by multiple instances of data in a cell.
5246
5247SP3 changed Excel's default behaviour when it encounters multiple data in a cell so that it issues a warning when the file is opened and it displays the first data that was written. Prior to SP3 it didn't issue a warning and displayed the last data written.
5248
5249For a longer discussion and some workarounds see the following: L<http://groups.google.com/group/spreadsheet-writeexcel/browse_thread/thread/3dcea40e6620af3a>.
5250
5251
5252
5253
5254=head1 BUGS
5255
5256Formulas are formulae.
5257
5258XML and C<UTF-8> data on perl 5.6 can cause Excel files created by Spreadsheet::WriteExcel to become corrupt. See L<Warning about XML::Parser and perl 5.6> for further details.
5259
5260The format object that is used with a C<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. The current workaround is to use separate formats for merged and non-merged cell. This restriction will be removed in a future release.
5261
5262Nested formulas sometimes aren't parsed correctly and give a result of "#VALUE". If you come across a formula that parses like this, let me know.
5263
5264Spreadsheet::ParseExcel: All formulas created by Spreadsheet::WriteExcel are read as having a value of zero. This is because Spreadsheet::WriteExcel only stores the formula and not the calculated result.
5265
5266OpenOffice.org: No known issues in this release.
5267
5268Gnumeric: No known issues in this release.
5269
5270If you wish to submit a bug report run the C<bug_report.pl> program in the C<examples> directory of the distro.
5271
5272
5273
5274
5275=head1 TO DO
5276
5277The roadmap is as follows:
5278
5279=over 4
5280
5281=item * Enhance named ranges.
5282
5283=back
5284
5285Also, here are some of the most requested features that probably won't get added:
5286
5287=over 4
5288
5289=item * Macros.
5290
5291This would solve some other problems neatly. However, the format of Excel macros isn't documented.
5292
5293=item * Some feature that you really need. ;-)
5294
5295
5296=back
5297
5298If there is some feature of an Excel file that you really, really need then you should use Win32::OLE with Excel on Windows. If you are on Unix you could consider connecting to a Windows server via Docserver or SOAP, see L<WRITING EXCEL FILES>.
5299
5300
5301
5302
5303=head1 REPOSITORY
5304
5305The Spreadsheet::WriteExcel source code in host on github: L<http://github.com/jmcnamara/spreadsheet-writeexcel>.
5306
5307
5308
5309
5310=head1 MAILING LIST
5311
5312There is a Google group for discussing and asking questions about Spreadsheet::WriteExcel. This is a good place to search to see if your question has been asked before: L<http://groups.google.com/group/spreadsheet-writeexcel>.
5313
5314=begin html
5315
5316<center>
5317<table style="background-color: #fff; padding: 5px;" cellspacing=0>
5318 <tr><td>
5319 <img src="http://groups.google.com/intl/en/images/logos/groups_logo_sm.gif"
5320 height=30 width=140 alt="Google Groups">
5321 </td></tr>
5322 <tr><td>
5323 <a href="http://groups.google.com/group/spreadsheet-writeexcel">Spreadsheet::WriteExcel</a>
5324 </td></tr>
5325</table>
5326</center>
5327
5328=end html
5329
5330
5331
5332Alternatively you can keep up to date with future releases by subscribing at:
5333L<http://freshmeat.net/projects/writeexcel/>.
5334
5335
5336
5337
5338=head1 DONATIONS
5339
5340If you'd care to donate to the Spreadsheet::WriteExcel project, you can do so via PayPal: L<http://tinyurl.com/7ayes>.
5341
5342
5343
5344
5345=head1 SEE ALSO
5346
5347Spreadsheet::ParseExcel: L<http://search.cpan.org/dist/Spreadsheet-ParseExcel>.
5348
5349Spreadsheet-WriteExcel-FromXML: L<http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromXML>.
5350
5351Spreadsheet::WriteExcel::FromDB: L<http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromDB>.
5352
5353Excel::Template: L<http://search.cpan.org/~rkinyon/Excel-Template/>.
5354
5355DateTime::Format::Excel: L<http://search.cpan.org/dist/DateTime-Format-Excel>.
5356
5357"Reading and writing Excel files with Perl" by Teodor Zlatanov, at IBM developerWorks: L<http://www-106.ibm.com/developerworks/library/l-pexcel/>.
5358
5359"Excel-Dateien mit Perl erstellen - Controller im Gluck" by Peter Dintelmann and Christian Kirsch in the German Unix/web journal iX: L<http://www.heise.de/ix/artikel/2001/06/175/>.
5360
5361Spreadsheet::WriteExcel documentation in Japanese by Takanori Kawai. L<http://member.nifty.ne.jp/hippo2000/perltips/Spreadsheet/WriteExcel.htm>.
5362
5363Oesterly user brushes with fame:
5364L<http://oesterly.com/releases/12102000.html>.
5365
5366The csv2xls program that is part of Text::CSV_XS:
5367L<http://search.cpan.org/~hmbrand/Text-CSV_XS/MANIFEST>.
5368
5369
5370
5371=head1 ACKNOWLEDGMENTS
5372
5373
5374The following people contributed to the debugging and testing of Spreadsheet::WriteExcel:
5375
5376Alexander Farber, Andre de Bruin, Arthur@ais, Artur Silveira da Cunha, Bob Rose, Borgar Olsen, Brian Foley, Brian White, Bob Mackay, Cedric Bouvier, Chad Johnson, CPAN testers, Damyan Ivanov, Daniel Berger, Daniel Gardner, Dmitry Kochurov, Eric Frazier, Ernesto Baschny, Felipe Perez Galiana, Gordon Simpson, Hanc Pavel, Harold Bamford, James Holmes, James Wilkinson, Johan Ekenberg, Johann Hanne, Jonathan Scott Duff, J.C. Wren, Kenneth Stacey, Keith Miller, Kyle Krom, Marc Rosenthal, Markus Schmitz, Michael Braig, Michael Buschauer, Mike Blazer, Michael Erickson, Michael W J West, Ning Xie, Paul J. Falbe, Paul Medynski, Peter Dintelmann, Pierre Laplante, Praveen Kotha, Reto Badertscher, Rich Sorden, Shane Ashby, Sharron McKenzie, Shenyu Zheng, Stephan Loescher, Steve Sapovits, Sven Passig, Svetoslav Marinov, Tamas Gulacsi, Troy Daniels, Vahe Sarkissian.
5377
5378The following people contributed patches, examples or Excel information:
5379
5380Andrew Benham, Bill Young, Cedric Bouvier, Charles Wybble, Daniel Rentz, David Robins, Franco Venturi, Guy Albertelli, Ian Penman, John Heitmann, Jon Guy, Kyle R. Burton, Pierre-Jean Vouette, Rubio, Marco Geri, Mark Fowler, Matisse Enzer, Sam Kington, Takanori Kawai, Tom O'Sullivan.
5381
5382Many thanks to Ron McKelvey, Ronzo Consulting for Siemens, who sponsored the development of the formula caching routines.
5383
5384Many thanks to Cassens Transport who sponsored the development of the embedded charts and autofilters.
5385
5386Additional thanks to Takanori Kawai for translating the documentation into Japanese.
5387
5388Gunnar Wolf maintains the Debian distro.
5389
5390Thanks to Damian Conway for the excellent Parse::RecDescent.
5391
5392Thanks to Tim Jenness for File::Temp.
5393
5394Thanks to Michael Meeks and Jody Goldberg for their work on Gnumeric.
5395
5396
5397
5398
5399=head1 DISCLAIMER OF WARRANTY
5400
5401Because this software is licensed free of charge, there is no warranty for the software, to the extent permitted by applicable law. Except when otherwise stated in writing the copyright holders and/or other parties provide the software "as is" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the software is with you. Should the software prove defective, you assume the cost of all necessary servicing, repair, or correction.
5402
5403In no event unless required by applicable law or agreed to in writing will any copyright holder, or any other party who may modify and/or redistribute the software as permitted by the above licence, be liable to you for damages, including any general, special, incidental, or consequential damages arising out of the use or inability to use the software (including but not limited to loss of data or data being rendered inaccurate or losses sustained by you or third parties or a failure of the software to operate with any other software), even if such holder or other party has been advised of the possibility of such damages.
5404
5405
5406
5407
5408=head1 LICENSE
5409
5410Either the Perl Artistic Licence L<http://dev.perl.org/licenses/artistic.html> or the GPL L<http://www.opensource.org/licenses/gpl-license.php>.
5411
5412
5413
5414
5415=head1 AUTHOR
5416
5417John McNamara jmcnamara@cpan.org
5418
5419 Another day in June, we'll pick eleven for football
5420 (Pick eleven for football)
5421 We're playing for our lives the referee gives us fuck all
5422 (Ref you're giving us fuck all)
5423 I saw you with the corner of my eye on the sidelines
5424 Your dark mascara bids me to historical deeds
5425
5426 -- Belle and Sebastian
5427
5428
5429
5430
5431=head1 COPYRIGHT
5432
5433Copyright MM-MMX, John McNamara.
5434
5435All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
5436