利用perl 制作漂亮的xls
1,需要的工具:
use Spreadsheet::Read;
use Excel::Writer::XLSX;
2,设置添加格字的格式
my $format1 = $workbook->add_format( valign => 'vcenter',align => 'center',bg_color => 'red',color => 'green' );
3,write
$worksheet->write( 1,1,'try fromat',$format1 );
注意,内容是单引号内的,格式直接加$符号。
可以多设置几个
use Spreadsheet::Read; use Excel::Writer::XLSX; #write my $workbook = Excel::Writer::XLSX->new('b.xlsx'); my $worksheet = $workbook->add_worksheet(); my $format1 = $workbook->add_format( valign => 'vcenter',color => 'green' ); $worksheet->write( 1,$format1 ); $workbook->close();
参考文献:
Spreadsheet::WriteExcel 和 Spreadsheet::Read 对 excel 文件的读写
http://deepfuture.iteye.com/blog/725612如何处理excel中的特殊字符
http://bbs.chinaunix.net/thread-4130875-1-4.html求助,处理excel表格处理中文字符
http://bbs.chinaunix.net/thread-4131951-1-4.htmlJohn McNamara > Excel-Writer-XLSX-0.76 > Excel::Writer::XLSX
http://search.cpan.org/~jmcnamara/Excel-Writer-XLSX-0.76/lib/Excel/Writer/XLSX.pm
- NAME
- VERSION
- SYNOPSIS
- DESCRIPTION
- Excel::Writer::XLSX and Spreadsheet::WriteExcel
- QUICK START
- WORKBOOK METHODS
- WORKSHEET METHODS
- Cell notation
- @L_502_34@
- write_number( $row,$number,$format )
- write_string( $row,$string,$format )
- write_rich_string( $row,$format,...,$cell_format )
- keep_leading_zeros()
- write_blank( $row,$format )
- write_row( $row,$array_ref,$format )
- write_col( $row,$format )
- write_date_time( $row,$col,$date_string,$format )
- write_url( $row,$url,$label )
- write_formula( $row,$formula,$value )
- write_array_formula($first_row,$first_col,$last_row,$last_col,$value)
- store_formula( $formula )
- repeat_formula( $row,$format )
- write_comment( $row,... )
- show_comments()
- set_comments_author()
- add_write_handler( $re,$code_ref )
- insert_image( $row,$filename,$x,$y,$x_scale,$y_scale )
- insert_chart( $row,$chart,$y_scale )
- insert_shape( $row,$shape,$y_scale )
- insert_button( $row,{ %properties })
- data_validation()
- conditional_formatting()
- add_sparkline()
- add_table()
- get_name()
- activate()
- select()
- hide()
- set_first_sheet()
- protect( $password,\%options )
- set_selection( $first_row,$last_col )
- set_row( $row,$height,$hidden,$level,$collapsed )
- set_column( $first_col,$width,$collapsed )
- set_default_row( $height,$hide_unused_rows )
- outline_settings( $visible,$symbols_below,$symbols_right,$auto_style )
- freeze_panes( $row,$top_row,$left_col )
- split_panes( $y,$left_col )
- merge_range( $first_row,$format )
- merge_range_type( $type,$first_row,... )
- set_zoom( $scale )
- right_to_left()
- hide_zero()
- set_tab_color()
- autofilter( $first_row,$last_col )
- filter_column( $column,$expression )
- filter_column_list( $column,@matches )
- convert_date_time( $date_string )
- PAGE SET-UP METHODS
- set_landscape()
- set_portrait()
- set_page_view()
- set_paper( $index )
- center_horizontally()
- center_vertically()
- set_margins( $inches )
- set_header( $string,$margin )
- set_footer( $string,$margin )
- repeat_rows( $first_row,$last_row )
- repeat_columns( $first_col,$last_col )
- hide_gridlines( $option )
- print_row_col_headers()
- print_area( $first_row,$last_col )
- print_across()
- fit_to_pages( $width,$height )
- set_start_page( $start_page )
- set_print_scale( $scale )
- set_h_pagebreaks( @breaks )
- set_v_pagebreaks( @breaks )
- CELL FORMATTING
- FORMAT METHODS
- set_format_properties( %properties )
- set_font( $fontname )
- set_size()
- set_color()
- set_bold()
- set_italic()
- set_underline()
- set_font_strikeout()
- set_font_script()
- set_font_outline()
- set_font_shadow()
- set_num_format()
- set_locked()
- set_hidden()
- set_align()
- set_center_across()
- set_text_wrap()
- set_rotation()
- set_indent()
- set_shrink()
- set_text_justlast()
- set_pattern()
- set_bg_color()
- set_fg_color()
- set_border()
- set_border_color()
- copy( $format )
- UNICODE IN EXCEL
- COLOURS IN EXCEL
- DATES AND TIME IN EXCEL
- OUTLINES AND GROUPING IN EXCEL
- DATA VALIDATION IN EXCEL
- CONDITIONAL FORMATTING IN EXCEL
- conditional_formatting( $row,... } )
- type
- type => 'cell'
- criteria
- value
- format
- minimum
- maximum
- type => 'date'
- type => 'time_period'
- type => 'text'
- type => 'average'
- type => 'duplicate'
- type => 'unique'
- type => 'top'
- type => 'bottom'
- type => 'blanks'
- type => 'no_blanks'
- type => 'errors'
- type => 'no_errors'
- type => '2_color_scale'
- type => '3_color_scale'
- type => 'data_bar'
- type => 'formula'
- min_type,mid_type,max_type
- min_value,mid_value,max_value
- min_color,mid_color,max_color,bar_color
- Conditional Formatting Examples
- SPARKLINES IN EXCEL
- TABLES IN EXCEL
- FORMULAS AND FUNCTIONS IN EXCEL
- EXAMPLES
- LIMITATIONS
- Compatibility with Spreadsheet::WriteExcel
- REQUIREMENTS
- SPEED AND MEMORY USAGE
- DOWNLOADING
- INSTALLATION
- DIAGNOSTICS
- WRITING EXCEL FILES
- READING EXCEL FILES
- BUGS
- TO DO
- REPOSITORY
- MAILING LIST
- DONATIONS and SPONSORSHIP
- SEE ALSO
- ACKNOWLEDGMENTS
- DISCLAIMER OF WARRANTY
- LICENSE
- AUTHOR
- COPYRIGHT
NAME 

Excel::Writer::XLSX - Create a new file in the Excel 2007+ XLSX format.
VERSION 

This document refers to version 0.76 of Excel::Writer::XLSX,released December 31,2013.
SYNOPSIS 

To write a string,a formatted string,a number and a formula to the first worksheet in an Excel workbook called perl.xlsx:
use Excel::Writer::XLSX; # Create a new Excel workbook my $workbook = Excel::Writer::XLSX->new( 'perl.xlsx' ); # Add a worksheet $worksheet = $workbook->add_worksheet(); # Add and define a format $format = add_format(); $format->set_bold(); set_color( 'red' ); set_align( 'center' ); # Write a formatted and unformatted string,row and column notation. $col = $row = 0; $worksheet->write( $row, $col, 'Hi Excel!',102); font-weight:bold">$format ); $worksheet->write( 1,0)">'Hi Excel!' ); # Write a number and a formula using A1 notation $worksheet->write( 'A3', 1.2345 ); 'A4',0)">'=SIN(PI()/4)' );
DESCRIPTION 

The Excel::Writer::XLSX
module can be used to create an Excel file in the 2007+ XLSX format.
The XLSX format is the Office Open XML (OOXML) format used by Excel 2007 and later.
Multiple worksheets can be added to a workbook and formatting can be applied to cells. Text,numbers,and formulas can be written to the cells.
This module cannot,as yet,be used to write to an existing Excel XLSX file.
Excel::Writer::XLSX and Spreadsheet::WriteExcel 

Excel::Writer::XLSX
uses the same interface as the Spreadsheet::WriteExcel module which produces an Excel file in binary XLS format.
Excel::Writer::XLSX supports all of the features of Spreadsheet::WriteExcel and in some cases has more functionality. For more details see "Compatibility with Spreadsheet::WriteExcel".
The main advantage of the XLSX format over the XLS format is that it allows a larger number of rows and columns in a worksheet. The XLSX file format also produces much smaller files than the XLS file format.
QUICK START 

Excel::Writer::XLSX tries to provide an interface to as many of Excel's features as possible. As a result there is a lot of documentation to accompany the interface and it can be difficult at first glance to see what it important and what is not. So for those of you who prefer to assemble Ikea furniture first and then read the instructions,here are three easy steps:
1. Create a new Excel workbook (i.e. file) using new()
.
2. Add a worksheet to the new workbook using add_worksheet()
.
3. Write to the worksheet using write()
.
Like this:
use Excel::Writer::XLSX; # Step 0 my 'perl.xlsx' ); # Step 1 add_worksheet(); # Step 2 'A1',0)">'Hi Excel!' ); # Step 3
This will create an Excel file called perl.xlsx
with a single worksheet and the text 'Hi Excel!'
in the relevant cell. And that's it. Okay,so there is actually a zeroth step as well,but use module
goes without saying. There are many examples that come with the distribution and which you can use to get you started. See "EXAMPLES".
Those of you who read the instructions first and assemble the furniture afterwards will know how to proceed. ;-)
WORKBOOK METHODS 

The Excel::Writer::XLSX module provides an object oriented interface to a new Excel workbook. The following methods are available through a new workbook.
new() add_worksheet() add_format() add_chart() add_shape() add_vba_project() close() set_properties() define_name() set_tempdir() set_custom_color() sheets() set_1904() set_optimization()
If you are unfamiliar with object oriented interfaces or the way that they are implemented in Perl have a look at perlobj
and perltoot
in the main Perl documentation.
new()
A new Excel workbook is created using the new()
constructor which accepts either a filename or a filehandle as a parameter. The following example creates a new Excel file based on a filename:
my $workbook = Excel::Writer::XLSX->'filename.xlsx' ); my add_worksheet(); 0,0)">'Hi Excel!' );
Here are some other examples of using new()
with filenames:
$workbook1 = Excel::Writer::XLSX->new( $filename ); my $workbook2 = Excel::Writer::XLSX->'/tmp/filename.xlsx' ); my $workbook3 = Excel::Writer::XLSX->"c:\\tmp\\filename.xlsx" ); my $workbook4 = Excel::Writer::XLSX->'c:\tmp\filename.xlsx' );
The last two examples demonstrates how to create a file on DOS or Windows where it is necessary to either escape the directory separator \
or to use single quotes to ensure that it isn't interpolated. For more information see perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?
.
It is recommended that the filename uses the extension .xlsx
rather than .xls
since the latter causes an Excel warning when used with the XLSX format.
The new()
constructor returns a Excel::Writer::XLSX object that you can use to add worksheets and store data. It should be noted that although my
is not specifically required it defines the scope of the new workbook variable and,in the majority of cases,ensures that the workbook is closed properly without explicitly calling the close()
method.
If the file cannot be created,due to file permissions or some other reason, new
will return undef
. Therefore,it is good practice to check the return value of new
before proceeding. As usual the Perl variable $!
will be set if there is a file creation error. You will also see one of the warning messages detailed in"DIAGNOSTICS":
'protected.xlsx' ); die "Problems creating new Excel file: $!" unless defined $workbook;
You can also pass a valid filehandle to the new()
constructor. For example in a CGI program you could do something like this:
binmode( STDOUT ); my new( \*STDOUT );
The requirement for binmode()
is explained below.
See also,the cgi.pl
program in the examples
directory of the distro.
In mod_perl
programs where you will have to do something like the following:
# mod_perl 1 ... tie *XLSX,0)">'Apache'; binmode( XLSX ); my new( \*XLSX ); ... # mod_perl 2 ... tie *XLSX => $r; # Tie to the Apache::RequestRec object binmode( *XLSX ); my new( \*XLSX ); ...
See also,the mod_perl1.pl
and mod_perl2.pl
programs in the examples
directory of the distro.
Filehandles can also be useful if you want to stream an Excel file over a socket or if you want to store an Excel file in a scalar.
For example here is a way to write an Excel file to a scalar:
#!/usr/bin/perl -w use strict; use Excel::Writer::XLSX; open my $fh,0)">'>', \my $str or die "Failed to open filehandle: $!"; my $fh ); my add_worksheet(); 'Hi Excel!' ); $workbook->close(); # The Excel file in now in $str. Remember to binmode() the output # filehandle before printing it. binmode STDOUT; print $str;
See also the write_to_scalar.pl
and filehandle.pl
programs in the examples
directory of the distro.
Note about the requirement for binmode()
. An Excel file is comprised of binary data. Therefore,if you are using a filehandle you should ensure that youbinmode()
it prior to passing it to new()
.You should do this regardless of whether you are on a Windows platform or not.
You don't have to worry about binmode()
if you are using filenames instead of filehandles. Excel::Writer::XLSX performs the binmode()
internally when it converts the filename to a filehandle. For more information about binmode()
see perlfunc
and perlopentut
in the main Perl documentation.
add_worksheet( $sheetname )
At least one worksheet should be added to a new workbook. A worksheet is used to write data into cells:
$worksheet1 = add_worksheet(); # Sheet1 $worksheet2 = add_worksheet( 'Foglio2' ); # Foglio2 $worksheet3 = 'Data' ); # Data $worksheet4 = # Sheet4
If $sheetname
is not specified the default Excel convention will be followed,i.e. Sheet1,Sheet2,etc.
The worksheet name must be a valid Excel worksheet name,i.e. it cannot contain any of the following characters, [ ] : * ? / \
and it must be less than 32 characters. In addition,you cannot use the same,case insensitive, $sheetname
for more than one worksheet.
add_format( %properties )
The add_format()
method can be used to create new Format objects which are used to apply formatting to a cell. You can either define the properties at creation time via a hash of property values or later via method calls.
$format1 = add_format( %props ); # Set properties at creation $format2 = add_format(); # Set properties later
See the "CELL FORMATTING" section for more details about Format properties and how to set them.
add_chart( %properties )
This method is use to create a new chart either as a standalone worksheet (the default) or as an embeddable object that can be inserted into a worksheet via the insert_chart()
Worksheet method.
$chart = add_chart( type => 'column' );
The properties that can be set are:
type (required) subtype (optional) name (optional) embedded (optional)
-
type
This is a required parameter. It defines the type of chart that will be created.
'line' );
The available types are:
area bar column line pie scatter stock
-
subtype
Used to define a chart subtype where available.
'bar', subtype => 'stacked' );
See the Excel::Writer::XLSX::Chart documentation for a list of available chart subtypes.
-
name
Set the name for the chart sheet. The name property is optional and if it isn't supplied will default to
Chart1 .. n
. The name must be a valid Excel worksheet name. Seeadd_worksheet()
for more details on valid sheet names. Thename
property can be omitted for embedded charts.'line', name => 'Results Chart' );
-
embedded
Specifies that the Chart object will be inserted in a worksheet via the
insert_chart()
Worksheet method. It is an error to try insert a Chart that doesn't have this flag set.=> 1 ); # Configure the chart. ... # Insert the chart into the a worksheet. $worksheet->insert_chart( 'E2',102); font-weight:bold">$chart );
See Excel::Writer::XLSX::Chart for details on how to configure the chart object once it is created. See also the chart_*.pl
programs in the examples directory of the distro.
add_shape( %properties )
The add_shape()
method can be used to create new shapes that may be inserted into a worksheet.
You can either define the properties at creation time via a hash of property values or later via method calls.
# Set properties at creation. $plus = add_shape( type => 'plus', id => 3, width => $pw, height => $ph ); # Default rectangle shape. Set properties later. $rect = add_shape();
See Excel::Writer::XLSX::Shape for details on how to configure the shape object once it is created.
See also the shape*.pl
programs in the examples directory of the distro.
add_vba_project( 'vbaProject.bin' )
The add_vba_project()
method can be used to add macros or functions to an Excel::Writer::XLSX file using a binary VBA project file that has been extracted from an existing Excel xlsm
file.
'file.xlsm' ); add_vba_project( './vbaProject.bin' );
The supplied extract_vba
utility can be used to extract the required vbaProject.bin
file from an existing Excel file:
$ extract_vba file.xlsm Extracted 'vbaProject.bin' successfully
Macros can be tied to buttons using the worksheet insert_button()
method (see the "WORKSHEET METHODS" section for details):
insert_button( 'C2', { macro => 'my_macro' } );
Note,Excel uses the file extension xlsm
instead of xlsx
for files that contain macros. It is advisable to follow the same convention.
See also the macros.pl
example file.
close()
In general your Excel file will be closed automatically when your program ends or when the Workbook object goes out of scope,however the close()
method can be used to explicitly close an Excel file.
$workbook->close();
An explicit close()
is required if the file must be closed prior to performing some external action on it such as copying it,reading its size or attaching it to an email.
In addition, close()
may be required to prevent perl's garbage collector from disposing of the Workbook,Worksheet and Format objects in the wrong order. Situations where this can occur are:
- If
my()
was not used to declare the scope of a workbook variable created usingnew()
. - If the
new()
,add_worksheet()
oradd_format()
methods are called in subroutines.
The reason for this is that Excel::Writer::XLSX relies on Perl's DESTROY
mechanism to trigger destructor methods in a specific sequence. This may not happen in cases where the Workbook,Worksheet and Format variables are not lexically scoped or where they have different lexical scopes.
In general,if you create a file with a size of 0 bytes or you fail to create a file you need to call close()
.
The return value of close()
is the same as that returned by perl when it closes the file created by new()
. This allows you to handle error conditions in the usual way:
$workbook->close() or die "Error closing file: $!";
set_properties()
The set_properties
method can be used to set the document properties of the Excel file created by Excel::Writer::XLSX
. These properties are visible when you use the Office Button -> Prepare -> Properties
option in Excel and are also available to external applications that read or index windows files.
The properties should be passed in hash format as follows:
set_properties( title => 'This is an example spreadsheet', author => 'John McNamara', comments => 'Created with Perl and Excel::Writer::XLSX', );
The properties that can be set are:
title subject author manager company category keywords comments status
See also the properties.pl
program in the examples directory of the distro.
define_name()
This method is used to defined a name that can be used to represent a value,a single cell or a range of cells in a workbook.
For example to set a global/workbook name:
# Global/workbook names. define_name( 'Exchange_rate',0)">'=0.96' ); 'Sales', '=Sheet1!$G$1:$H$10' );
It is also possible to define a local/worksheet name by prefixing the name with the sheet name using the Syntax sheetname!definedname
:
# Local/worksheet name. 'Sheet2!Sales', '=Sheet2!$G$1:$G$10' );
If the sheet name contains spaces or special characters you must enclose it in single quotes like in Excel:
"'New Data'!Sales",0)">'=Sheet2!$G$1:$G$10' );
See the defined_name.pl program in the examples dir of the distro.
Refer to the following to see Excel's Syntax rules for defined names: http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010147120.aspx#BMsyntax_rules_for_names
set_tempdir()
Excel::Writer::XLSX
stores worksheet data in temporary files prior to assembling the final workbook.
The File::Temp
module is used to create these temporary files. File::Temp uses File::Spec
to determine an appropriate location for these files such as /tmp
or c:\windows\temp
. You can find out which directory is used on your system as follows:
perl -MFile::Spec -le "print File::Spec->tmpdir()"
If the default temporary file directory isn't accessible to your application,or doesn't contain enough space,you can specify an alternative location using theset_tempdir()
method:
set_tempdir( '/tmp/writeexcel' ); 'c:\windows\temp\writeexcel' );
The directory for the temporary file must exist, set_tempdir()
will not create a new directory.
"COLOURS IN EXCEL".
The default named colours use the following indices:
8 => black 9 => white 10 => red 11 => lime 12 => blue 13 => yellow 14 => magenta 15 => cyan 16 => brown 17 => green 18 => navy 20 => purple 22 => silver 23 => gray 33 => pink 53 => orange
A new colour is set using its RGB (red green blue) components. The $red
, $green
and $blue
values must be in the range 0..255. You can determine the required values in Excel using the Tools->Options->Colors->Modify
dialog.
The set_custom_color()
workbook method can also be used with a HTML style #rrggbb
hex value:
set_custom_color( 40,255)">255, 102,255)">0 ); # Orange 0xFF,255)">0x66,255)">0x00 ); # Same thing '#FF6600' ); # Same thing my $font = add_format( color => 40 ); # Modified colour
The return value from set_custom_color()
is the index of the colour that was changed:
$ferrari = 216,255)">12,255)">12 ); my add_format( bg_color => $ferrari, pattern => => 1 );
Note,In the XLSX format the color palette isn't actually confined to 53 unique colors. The Excel::Writer::XLSX module will be extended at a later stage to support the newer,semi-infinite,palette.
for $worksheet ( sheets() ) {
print get_name();
}
You can also specify a slice list to return one or more worksheet objects:
sheets( 0 );
'Hello' );
Or since the return value from sheets()
is a reference to a worksheet object you can write the above example as:
0 )->write( 'Hello' );
The following example returns the first and last worksheet in a workbook:
-1 ) ) {
# Do something
}
Array slices are explained in the perldata
manpage.
set_1904()
Excel stores dates as real numbers where the integer part stores the number of days since the epoch and the fractional part stores the percentage of the day. The epoch can be either 1900 or 1904. Excel for Windows uses 1900 and Excel for Macintosh uses 1904. However,Excel on either platform will convert automatically between one system and the other.
Excel::Writer::XLSX stores dates in the 1900 format by default. If you wish to change this you can call the set_1904()
workbook method. You can query the current value by calling the get_1904()
workbook method. This returns 0 for 1900 and 1 for 1904.
See also "DATES AND TIME IN EXCEL" for more information about working with Excel's date system.
In general you probably won't need to use set_1904()
.
set_optimization()
The set_optimization()
method is used to turn on optimizations in the Excel::Writer::XLSX module. Currently there is only one optimization available and that is to reduce memory usage.
set_optimization();
See "SPEED AND MEMORY USAGE" for more background information.
Note,that with this optimization turned on a row of data is written and then discarded when a cell in a new row is added via one of the Worksheet write_*()
methods. As such data should be written in sequential row order once the optimization is turned on.
This method must be called before any calls to add_worksheet()
.
WORKSHEET METHODS 
A new worksheet is created by calling the add_worksheet()
method from a workbook object:
add_worksheet();
The following methods are available through a new worksheet:
write()
write_number()
write_string()
write_rich_string()
keep_leading_zeros()
write_blank()
write_row()
write_col()
write_date_time()
write_url()
write_url_range()
write_formula()
write_comment()
show_comments()
set_comments_author()
add_write_handler()
insert_image()
insert_chart()
insert_shape()
insert_button()
data_validation()
conditional_formatting()
add_sparkline()
add_table()
get_name()
activate()
select()
hide()
set_first_sheet()
protect()
set_selection()
set_row()
set_default_row()
set_column()
outline_settings()
freeze_panes()
split_panes()
merge_range()
merge_range_type()
set_zoom()
right_to_left()
hide_zero()
set_tab_color()
autofilter()
filter_column()
filter_column_list()
Cell notation
Excel::Writer::XLSX supports two forms of notation to designate the position of cells: Row-column notation and A1 notation.
Row-column notation uses a zero based index for both row and column while A1 notation uses the standard Excel alphanumeric sequence of column letter and 1-based row. For example:
(0) # The top left cell in row-column notation.
('A1') # The top left cell in A1 notation.
(1999,255)">29) # Row-column notation.
('AD2000') # The same cell in A1 notation.
Row-column notation is useful if you are referring to cells programmatically:
for my $i ( 0 .. 9 ) {
$i,0)">'Hello' ); # Cells A1 to A10
}
A1 notation is useful for setting up a worksheet manually and for working with formulas:
'H1',255)">200 );
'H2',0)">'=H1+1' );
In formulas and applicable methods you can also use the A:A
column notation:
'=SUM(B:B)' );
The Excel::Writer::XLSX::Utility
module that is included in the distro contains helper functions for dealing with A1 notation,for example:
use Excel::Writer::XLSX::Utility;
( $col ) = xl_cell_to_rowcol( 'C2' ); # (1,2)
$str = xl_rowcol_to_cell( 2 ); # C2
For 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.
Note: in Excel it is also possible to use a R1C1 notation. This is not supported by Excel::Writer::XLSX.
write_col()
The general rule is that if the data looks like a something then a something is written. Here are some examples in both row-column and A1 notation:
# Same as:
'Hello' ); # write_string()
'One' ); 2,255)">2 ); # write_number()
3.00001 ); 4,0)">"" ); # write_blank()
5,0)">'' ); 6, undef ); 7,255)">0 ); 8,0)">'http://www.perl.com/' ); # write_url()
'A9',0)">'ftp://ftp.cpan.org/' ); 'A10',0)">'internal:Sheet1!A1' ); 'A11',0)">'external:c:\foo.xlsx' ); 'A12',0)">'=A3 + 3*A4' ); # write_formula()
'A13',0)">'=SIN(PI()/4)' ); 'A14', \@array ); # write_row()
'A15', [\@array] ); # write_col()
# And if the keep_leading_zeros property is set:
'A16',0)">'2' ); 'A17',0)">'02' ); 'A18',0)">'00002' ); # write_string()
# Write an array formula. Not available in Spreadsheet::WriteExcel.
'A19',0)">'{=SUM(A1:B1*A2:B2)}' ); # write_formula()
The "looks like" rule is defined by regular expressions:
write_number()
if $token
is a number based on the following regex: $token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
.
write_string()
if keep_leading_zeros()
is set and $token
is an integer with leading zeros based on the following regex: $token =~ /^0\d+$/
.
write_blank()
if $token
is undef or a blank string: undef
, ""
or ''
.
write_url()
if $token
is a http,https,ftp or mailto URL based on the following regexes: $token =~ m|^[fh]tt?ps?://|
or $token =~ m|^mailto:|
.
write_url()
if $token
is an internal or external sheet reference based on the following regex: $token =~ m[^(in|ex)ternal:]
.
write_formula()
if the first character of $token
is "="
.
write_array_formula()
if the $token
matches /^{=.*}$/
.
write_row()
if $token
is an array ref.
write_col()
if $token
is an array ref of array refs.
write_string()
if none of the prevIoUs conditions apply.
The $format
parameter is optional. It should be a valid Format object,see "CELL FORMATTING":
'center' );
'Hello',102); font-weight:bold">$format ); # Formatted string
The write() method will ignore empty strings or undef
tokens unless a format is also supplied. As such you needn't worry about special handling for empty orundef
values in your data. See also the write_blank()
method.
One problem with the write()
method is that occasionally data looks like a number but you don't want it treated as a number. For example,zip codes or ID numbers often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. You can change this default behavIoUr by using the keep_leading_zeros()
method. While this property is in place any integers with leading zeros will be treated as strings and the zeros will be preserved. See the keep_leading_zeros()
section for a full discussion of this issue.
You can also add your own data handlers to the write()
method using add_write_handler()
.
The write()
method will also handle Unicode strings in UTF-8
format.
The write
methods return:
0 for success.
-1 for insufficient number of arguments.
-2 for row or column out of bounds.
-3 for string too long.
write_number( 123456 );
write_number( 'A2',255)">2.3451 );
See the note about "Cell notation". The $format
parameter is optional.
In general it is sufficient to use the write()
method.
Note: some versions of Excel 2007 do not display the calculated values of formulas written by Excel::Writer::XLSX. Applying all available Service Packs to Excel should fix this.
write_string( 'Your text here' );
write_string( 'or here' );
The maximum string size is 32767 characters. However the maximum string segment that Excel can display in a cell is 1000. All 32767 characters can be displayed in the formula bar.
The $format
parameter is optional.
The write()
method will also handle strings in UTF-8
format. See also the unicode_*.pl
programs in the examples directory of the distro.
In general it is sufficient to use the write()
method. However,you may sometimes wish to use the write_string()
method to write data that looks like a number but that you don't want treated as a number. For example,zip codes or phone numbers:
# Write as a plain string
'01209' );
However,if the user edits this string Excel may convert it back to a number. To get around this you can use the Excel text format @
:
# Format as a string. Doesn't change to a number when edited
my add_format( num_format => '@' );
'01209',102); font-weight:bold">$format1 );
See also the note about "Cell notation".
bold and this is italic" you would use the following:
$bold = add_format( bold => 1 );
my $italic = add_format( italic => 1 );
write_rich_string( 'This is ',102); font-weight:bold">$bold,0)">'bold',0)">' and this is ',102); font-weight:bold">$italic,0)">'italic' );
The basic rule is to break the string into fragments and put a $format
object before the fragment that you want to format. For example:
# Unformatted string.
'This is an example string'
# Break it into fragments.
'This is an ',0)">'example',0)">' string'
# Add formatting before the fragments you want formatted.
$format,131); font-style:italic"># In Excel::Writer::XLSX.
' string' );
String fragments that don't have a format are given a default format. So for example when writing the string "Some bold text" you would use the first example below but it would be equivalent to the second:
# With default formatting:
my $bold = add_format( bold => 'Some ',0)">' text' );
# Or more explicitly:
my $default = add_format();
$default,0)">' text' );
As with Excel,only the font properties of the format such as font name,style,size,underline,color and effects are applied to the string fragments. Other features such as border,background,text wrap and alignment must be applied to the cell.
The write_rich_string()
method allows you to do this by using the last argument as a cell format (if it is a format object). The following example centers a rich string in the cell:
add_format( bold => $center = add_format( align => 'A5',0)">'bold text',0)">' centered',102); font-weight:bold">$center );
See the rich_strings.pl
example in the distro for more examples.
add_format( bold => add_format( italic => $red = add_format( color => 'red' );
my $blue = 'blue' );
my add_format( align => 'center' );
my $super = add_format( font_script => 1 );
# Write some strings with multiple formats.
'italic' );
$red,0)">'red',102); font-weight:bold">$blue,0)">'blue' );
$center );
'A7',0)">'j = k',102); font-weight:bold">$super,0)">'(n-1)',102); font-weight:bold">$center );

As with write_sting()
the maximum string size is 32767 characters. See also the note about keep_leading_zeros()
This method changes the default handling of integers with leading zeros when using the write()
method.
The write()
method uses regular expressions to determine what type of data to write to an Excel worksheet. If the data looks like a number it writes a number using write_number()
. One problem with this approach is that occasionally data looks like a number but you don't want it treated as a number.
Zip codes and ID numbers,for example,often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. This is the also the default behavIoUr when you enter data manually in Excel.
To get around this you can use one of three options. Write a formatted number,write the number as a string or use the keep_leading_zeros()
method to change the default behavIoUr of write()
:
# Implicitly write a number,the leading zero is removed: 1209
'01209' );
# Write a zero padded number using a format: 01209
my '00000' );
$format1 );
# Write explicitly as a string: 01209
# Write implicitly as a string: 01209
keep_leading_zeros();
'01209' );
The above code would generate a worksheet that looked like the following:
-----------------------------------------------------------
| | A | B | C | D | ...
-----------------------------------------------------------
| 1 | 1209 | | | | ...
| 2 | 01209 | | | | ...
| 3 | 01209 | | | | ...
| 4 | 01209 | | | | ...
The examples are on different sides of the cells due to the fact that Excel displays strings with a left justification and numbers with a right justification by default. You can change this by using a format to justify the data,153)" rel="nofollow">"CELL FORMATTING"
.
It should be noted that if the user edits the data in examples A3
and A4
the strings will revert back to numbers. Again this is Excel's default behavIoUr. To avoid this you can use the text format @
:
# Format as a string (01209)
my $format2 );
The keep_leading_zeros()
property is off by default. The keep_leading_zeros()
method takes 0 or 1 as an argument. It defaults to 1 if an argument isn't specified:
keep_leading_zeros(); # Set on
keep_leading_zeros( 1 ); 0 ); # Set off
See also the add_write_handler()
method.
write_blank( $format );
This method is used to add formatting to a cell which doesn't contain a string or number value.
Excel differentiates between an "Empty" cell and a "Blank" cell. An "Empty" cell is a cell which doesn't contain data whilst a "Blank" cell is a cell which doesn't contain data but does contain formatting. Excel stores "Blank" cells but ignores "Empty" cells.
As such,if you write an empty cell without formatting it is ignored:
undef, undef ); # Ignored
This seemingly uninteresting fact means that you can write arrays of data without special treatment for undef
or empty string values.
See the note about @array = ( 'awk',0)">'gawk',0)">'mawk' );
$array_ref = \@array;
write_row( $array_ref );
# The above example is equivalent to:
$array[0] );
1] );
2] );
Note: For convenience the write()
method behaves in the same way as write_row()
if it is passed an array reference. Therefore the following two method calls are equivalent:
write_row( $array_ref ); # Write a row of data
$worksheet->write( @H_285_3016@# Same thing
As with all of the write methods the $format
parameter is optional. If a format is specified it is applied to all the elements of the data array.
Array references within the data will be treated as columns. This allows you to write 2D arrays of data in one go. For example:
@eec = (
['maggie',0)">'milly',0)">'molly',0)">'may' ],
[13, 14, 15,255)">16 ],
['shell',0)">'star',0)">'crab',0)">'stone']
);
@eec );
Would produce a worksheet as follows:
-----------------------------------------------------------
| | A | B | C | D | E | ...
-----------------------------------------------------------
| 1 | maggie | 13 | shell | ... | ... | ...
| 2 | milly | 14 | star | ... | ... | ...
| 3 | molly | 15 | crab | ... | ... | ...
| 4 | may | 16 | stone | ... | ... | ...
| 5 | ... | ... | ... | ... | ... | ...
| 6 | ... | ... | ... | ... | ... | ...
To write the data in a row-column order refer to the write_col()
method below.
Any undef
values in the data will be ignored unless a format is applied to the data,in which case a formatted blank cell will be written. In either case the appropriate row or column value will still be incremented.
To find out more about array references refer to perlref
and perlreftut
in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to perllol
.
The write_row()
method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the write()
method above.
See also the write_arrays.pl
program in the examples
directory of the distro.
The write_row()
method allows the following idiomatic conversion of a text file to an Excel file:
#!/usr/bin/perl -w
use strict;
use Excel::Writer::XLSX;
my 'file.xlsx' );
my add_worksheet();
open INPUT,0)">'file.txt' or die "Couldn't open file: $!";
$worksheet->write( $. -[split] ) while <INPUT>;
write_col( 2] );
As with all of the write methods the $format
parameter is optional. If a format is specified it is applied to all the elements of the data array.
Array references within the data will be treated as rows. This allows you to write 2D arrays of data in one go. For example:
write_col( 1 | maggie | milly | molly | may | ... | ...
| 2 | 13 | 14 | 15 | 16 | ... | ...
| 3 | shell | star | crab | stone | ... | ...
| 4 | ... | ... | ... | ... | ... | ...
| 6 | ... | ... | ... | ... | ... | ...
To write the data in a column-row order refer to the write_row()
method above.
Any undef
values in the data will be ignored unless a format is applied to the data,in which case a formatted blank cell will be written. In either case the appropriate row or column value will still be incremented.
As noted above the write()
method can be used as a synonym for write_row()
and write_row()
handles nested array refs as columns. Therefore,the following two method calls are equivalent although the more explicit call to write_col()
would be preferable for maintainability:
$array_ref ); # Write a column of data
[ $array_ref ] ); # Same thing
To find out more about array references refer to perlref
and perlreftut
in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to perllol
.
The write_col()
method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the write()
method above.
See also the write_arrays.pl
program in the examples
directory of the distro.
write_date_time( '2004-05-13T23:20',102); font-weight:bold">$date_format );
The $date_string
should be in the following format:
yyyy-mm-ddThh:mm:ss.sss
This conforms to an ISO8601 date but it should be noted that the full range of ISO8601 formats are not supported.
The following variations on the $date_string
parameter are permitted:
yyyy-mm-ddThh:mm:ss.sss # Standard format
yyyy-mm-ddT # No time
Thh:mm:ss.sss # No date
yyyy-mm-ddThh:mm:ss.sssZ # Additional Z (but not time zones)
yyyy-mm-ddThh:mm:ss # No fractional seconds
yyyy-mm-ddThh:mm # No seconds
Note that the T
is required in all cases.
A date should always have a $format
,otherwise it will appear as a number,see "DATES AND TIME IN EXCEL" and "CELL FORMATTING". Here is a typical example:
$date_format = 'mm/dd/yy' );
$date_format );
Valid dates should be in the range 1900-01-01 to 9999-12-31,for the 1900 epoch and 1904-01-01 to 9999-12-31,for the 1904 epoch. As with Excel,dates outside these ranges will be written as a string.
See also the date_time.pl program in the examples
directory of the distro.
add_format( color => 'blue', underline => 1 );
Note,this behaviour is different from Spreadsheet::WriteExcel which provides a default hyperlink format if one isn't specified by the user.
There are four web style URI's supported: http://
, https://
, ftp://
and mailto:
:
write_url( 'ftp://www.perl.org/', write_url( 'mailto:jmcnamara@cpan.org',102); font-weight:bold">$format );
You can display an alternative string using the $label
parameter:
'Perl' );
If you wish to have some other cell data such as a number or a formula you can overwrite the cell using another call to write_*()
:
' );
# Overwrite the URL string with a formula. The cell is still a link.
write_formula( '=1+1',102); font-weight:bold">$format );
There are two local URIs supported: internal:
and external:
. These are used for hyperlinks to internal worksheet references or external workbook and worksheet references:
'A6',0)">'internal:Sheet2!A1', 'A8',0)">'internal:Sheet2!A1:B2', q{internal:'Sales Data'!A1},0)">'external:c:\temp\foo.xlsx',0)">'external:c:\foo.xlsx#Sheet2!A1', 'external:..\foo.xlsx', 'external:..\foo.xlsx#Sheet2!A1',0)">'external:\\\\NET\share\foo.xlsx',102); font-weight:bold">$format );
All of the these URI types are recognised by the write()
method,see above.
Worksheet references are typically of the form Sheet1!A1
. You can also refer to a worksheet range using the standard Excel notation: Sheet1!A1:B2
.
In external links the workbook and worksheet name must be separated by the #
character: external:Workbook.xlsx#Sheet1!A1'
.
You can also link to a named range in the target worksheet. For example say you have a named range called my_name
in the workbook c:\temp\foo.xlsx
you could link to it as follows:
'external:c:\temp\foo.xlsx#my_name' );
Excel requires that worksheet names containing spaces or non alphanumeric characters are single quoted as follows 'Sales Data'!A1
. If you need to do this in a single quoted string then you can either escape the single quotes \'
or use the quote operator q{}
as described in perlop
in the main Perl documentation.
Links to network files are also supported. MS/Novell Network files normally begin with two back slashes as follows \\NETWORK\etc
. In order to generate this in a single or double quoted string you will have to escape the backslashes, '\\\\NETWORK\etc'
.
If you are using double quote strings then you should be careful to escape anything that looks like a Metacharacter. For more information see perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?
.
Finally,you can avoid most of these quoting problems by using forward slashes. These are translated internally to backslashes:
"external:c:/temp/foo.xlsx" );
'external://NETWORK/share/foo.xlsx' );
Note: Excel::Writer::XLSX will escape the following characters in URLs as required by Excel: \s " < > \ [ ] ` ^ { }
unless the URL already contains %xx
style escapes. In which case it is assumed that the URL was escaped correctly by the user and will by passed directly to Excel.
See also,the note about write_formula( '=$B$3 + B4' );
'=SIN(PI()/4)' );
'=SUM(B1:B5)' );
'=IF(A3>1,"Yes","No")' );
'=AVERAGE(1,2,3,4)' );
'=DATEVALUE("1-Jan-2001")' );
Array formulas are also supported:
'{=SUM(A1:B1*A2:B2)}' );
See also the write_array_formula()
method below.
See the note about "Cell notation". For more information about writing Excel formulas see "FORMULAS AND FUNCTIONS IN EXCEL"
If required,it is also possible to specify the calculated value of the formula. This is occasionally necessary when working with non-Excel applications that don't calculate the value of the formula. The calculated $value
is added at the end of the argument list:
'=2+2',255)">4 );
However,this probably isn't something that you will ever need to do. If you do use this feature then do so with care.
write_array_formula('A1:A1',0)">'{=SUM(B1:C1*B2:C2)}');
It this case however it is easier to just use the write_formula()
or write()
methods:
# Same as above but more concise.
'{=SUM(B1:C1*B2:C2)}' );
'{=SUM(B1:C1*B2:C2)}' );
For array formulas that return a range of values you must specify the range that the return values will be written to:
write_array_formula( 'A1:A3', '{=TREND(C1:C3,B1:B3)}' );
write_array_formula( );
If required,B1:B3)}',255)">105 );
In addition,some early versions of Excel 2007 don't calculate the values of array formulas when they aren't supplied. Installing the latest Office Service Pack should fix this issue.
See also the array_formula.pl
program in the examples
directory of the distro.
Note: Array formulas are not supported by Spreadsheet::WriteExcel.
store_formula( $formula )
Deprecated. This is a Spreadsheet::WriteExcel method that is no longer required by Excel::Writer::XLSX. See below.
$worksheet->write ( 'Hello' );
write_comment( 'This is a comment.' );
As usual you can replace the $row
and $column
parameters with an A1
cell reference. See the note about "Cell notation".
$worksheet->write ( 'C3',0)">'Hello');
write_comment( 'This is a comment.' );
The write_comment()
method will also handle strings in UTF-8
format.
"\x{263a}" ); # Smiley
'C4',0)">'Comment ca va?' );
In addition to the basic 3 argument form of write_comment()
you can pass in several optional key/value pairs to control the format of the comment. For example:
=> => 'Perl' );
Most of these options are quite specific and in general the default comment behavIoUr will be all that you need. However,should you need greater control over the format of the cell comment the following options are available:
author
visible
x_scale
width
y_scale
height
color
start_cell
start_row
start_col
x_offset
y_offset
-
@L_977_301@
Option: author
-
This option is used to indicate who is the author of the cell comment. 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.
'Atonement',0)">'Ian McEwan' );
The default author for all cell comments can be set using the set_comments_author()
method (see below).
set_comments_author( 'Perl' );
-
@L_977_301@
Option: visible
-
This option is used to make a cell comment visible when the worksheet is opened. The default behavIoUr in Excel is that comments are initially hidden. However,it is also possible in Excel to make individual or all comments visible. In Excel::Writer::XLSX individual comments can be made visible as follows:
1 );
It is possible to make all comments in a worksheet visible using the show_comments()
worksheet method (see below). Alternatively,if all of the cell comments have been made visible you can hide individual comments:
0 );
-
@L_977_301@
Option: x_scale
-
This option is used to set the width of the cell comment Box as a factor of the default width.
=> 2 );
4.2 );
-
@L_977_301@
Option: width
-
This option is used to set the width of the cell comment Box explicitly in pixels.
=> 200 );
-
@L_977_301@
Option: y_scale
-
This option is used to set the height of the cell comment Box as a factor of the default height.
=> 4.2 );
-
@L_977_301@
Option: height
-
This option is used to set the height of the cell comment Box explicitly in pixels.
=> 200 );
-
@L_977_301@
Option: color
-
This option is used to set the background colour of cell comment Box. You can use one of the named colours recognised by Excel::Writer::XLSX or a colour index. See "COLOURS IN EXCEL".
=> 'green' );
=> 0x35 ); # Orange
-
@L_977_301@
Option: start_cell
-
This option is used to set the cell in which the comment will appear. By default Excel displays comments one cell to the right and one cell above the cell to which the comment relates. However,you can change this behavIoUr if you wish. In the following example the comment which would appear by default in cell D2
is moved to E2
.
=> 'E2' );
-
@L_977_301@
Option: start_row
-
This option is used to set the row in which the comment will appear. See the start_cell
option above. The row is zero indexed.
=> 0 );
-
@L_977_301@
Option: start_col
-
This option is used to set the column in which the comment will appear. See the start_cell
option above. The column is zero indexed.
=> 4 );
-
@L_977_301@
Option: x_offset
-
This option is used to change the x offset,in pixels,of a comment within a cell:
$comment, x_offset => 30 );
-
@L_977_301@
Option: y_offset
-
This option is used to change the y offset,129)">write_comment(30);
You can apply as many of these options as you require.
Note about using options that adjust the position of the cell comment such as start_cell,start_row,start_col,x_offset and y_offset: Excel only displays offset cell comments when they are displayed as "visible". Excel does not display hidden cells as moved when you mouse over them.
Note about row height and comments. If you specify the height of a row that contains a comment then Excel::Writer::XLSX 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 the module at run time and thus the comment Box is stretched with the row. Use the set_row()
method to specify the row height explicitly and avoid this problem.
show_comments()
This method is used to make all cell comments visible when a worksheet is opened.
show_comments();
Individual comments can be made visible using the visible
parameter of the write_comment
method (see above):
1 );
If all of the cell comments have been made visible you can hide individual comments as follows:
show_comments();
0 );
set_comments_author()
This method is used to set the default author of all cell comments.
'Perl' );
Individual comment authors can be set using the author
parameter of the write_comment
method (see above).
The default comment author is an empty string, ''
,if no author is specified.
add_write_handler( qr/^\d\d\d\d$/, \&my_write );
(In the these examples the qr
operator is used to quote the regular expression strings,see perlop for more details).
The method is used as follows. say you wished to write 7 digit ID numbers as a string so that any leading zeros were preserved*,you could do something like the following:
/^\d{7}$/, \&write_my_id );
sub write_my_id {
my $worksheet = shift;
return write_string( @_ );
}
* You could also use the keep_leading_zeros()
method for this.
Then if you call write()
with an appropriate string it will be handled automatically:
# Writes 0000000. It would normally be written as a number; 0.
'0000000' );
The callback function will receive a reference to the calling worksheet and all of the other arguments that were passed to write()
. The callback will see an @_
argument list that looks like the following:
$_[0] A ref to the calling worksheet. *
1] Zero based row number.
2] Zero based column number.
3] A number or string or token.
4] A format ref if any.
5] Any other arguments.
...
* It is good style to shift this off the list so the @_ is the same
as the argument list seen by write().
Your callback should return()
the return value of the write_*
method that was called or undef
to indicate that you rejected the match and want write()
to continue as normal.
So for example if you wished to apply the prevIoUs filter only to ID values that occur in the first column you could modify your callback function as follows:
sub write_my_id {
my $worksheet = shift;
my $col = 1];
if ( $col == 0 ) {
return @_ );
}
else {
# Reject the match and return control to write()
return undef;
}
}
Now,you will get different behavIoUr for the first column and other columns:
'0000000' ); # Writes 0000000
'B1',131); font-style:italic"># Writes 0
You may add more than one handler in which case they will be called in the order that they were added.
Note,the add_write_handler()
method is particularly suited for handling dates.
See the write_handler 1-4
programs in the examples
directory for further examples.
$worksheet1->insert_image( 'perl.bmp' );
$worksheet2->'../images/perl.bmp' );
$worksheet3->'.c:\images\perl.bmp' );
The parameters $x
and $y
can be used to specify an offset from the top left hand corner of the cell specified by $row
and $col
. The offset values are in pixels.
insert_image('perl.bmp',255)">32,255)">10);
The offsets can be greater than the width or height of the underlying cell. This can be occasionally useful if you wish to align two or more images relative to the same cell.
The parameters $x_scale
and $y_scale
can be used to scale the inserted image horizontally and vertically:
# Scale the inserted image: width x 2.0,height x 0.8
0.8 );
Note: you must call set_row()
or set_column()
before insert_image()
if you wish to change the default dimensions of any of the rows or columns that the image occupies. The height of a row can also change if you use a font that is larger than the default. This in turn will affect the scaling of your image. To avoid this you should explicitly set the height of the row using set_row()
if it contains a font size that will change the row height.
BMP images must be 24 bit,true colour,bitmaps. In general it is best to avoid BMP images since they aren't compressed.
$chart );
See add_chart()
for details on how to create the Chart object and Excel::Writer::XLSX::Chart for details on how to configure it. See also the chart_*.pl
programs in the examples directory of the distro.
The $x
, $x_scale
and $y_scale
parameters are optional.
The parameters $x
and $y
can be used to specify an offset from the top left hand corner of the cell specified by $row
and $col
. The offset values are in pixels.
$chart,255)">3 );
The parameters $x_scale
and $y_scale
can be used to scale the inserted chart horizontally and vertically:
# Scale the width by 120% and the height by 150%
1.2,255)">1.5 );
$shape = add_shape( name => 'My Shape', type => 'plus' );
# Configure the shape.
$shape->set_text('foo');
...
# Insert the shape into the a worksheet.
insert_shape( $shape );
See add_shape()
for details on how to create the Shape object and Excel::Writer::XLSX::Shape for details on how to configure it.
The $x
,255)">3 );
The parameters $x_scale
and $y_scale
can be used to scale the inserted shape horizontally and vertically:
$shape,255)">1.5 );
See also the shape*.pl
programs in the examples directory of the distro.
'file.xlsm' );
...
'./vbaProject.bin' );
'my_macro' } );
The properties of the button that can be set are:
macro
caption
width
height
x_scale
y_scale
x_offset
y_offset
-
@L_977_301@
Option: macro
-
This option is used to set the macro that the button will invoke when the user clicks on it. The macro should be included using the Workbookadd_vba_project()
method shown above.
'my_macro' } );
The default macro is ButtonX_Click
where X is the button number.
-
@L_977_301@
Option: caption
-
This option is used to set the caption on the button. The default is Button X
where X is the button number.
'my_macro', caption => 'Hello' } );
-
@L_977_301@
Option: width
-
This option is used to set the width of the button in pixels.
128 } );
The default button width is 64 pixels which is the width of a default cell.
-
@L_977_301@
Option: height
-
This option is used to set the height of the button in pixels.
40 } );
The default button height is 20 pixels which is the height of a default cell.
-
@L_977_301@
Option: x_scale
-
This option is used to set the width of the button as a factor of the default width.
2.0 );
-
@L_977_301@
Option: y_scale
-
This option is used to set the height of the button as a factor of the default height.
2.0 );
-
@L_977_301@
Option: x_offset
-
This option is used to change the x offset,of a button within a cell:
2 );
-
@L_977_301@
Option: y_offset
-
This option is used to change the y offset,of a comment within a cell.
Note: Button is the only Excel form element that is available in Excel::Writer::XLSX. Form elements represent a lot of work to implement and the underlying VML Syntax isn't very much fun.
data_validation()
The data_validation()
method is used to construct an Excel data validation or to limit the user input to a dropdown list of values.
data_validation('B3',
{
validate => 'integer',
criteria => => 100,
});
'B5:B9',0)">'list',
value => ['open',0)">'high',0)">'close'],
});
This method contains a lot of parameters and is described in detail in a separate section "DATA VALIDATION IN EXCEL".
See also the data_validate.pl
program in the examples directory of the distro
conditional_formatting()
The conditional_formatting()
method is used to add formatting to a cell or range of cells based on user defined criteria.
conditional_formatting( 'A1:J10',
{
type => 'cell',0)">'>=',255)">50,
format => $format1,
}
);
This method contains a lot of parameters and is described in detail in a separate section "CONDITIONAL FORMATTING IN EXCEL".
See also the conditional_format.pl
program in the examples directory of the distro
add_sparkline()
The add_sparkline()
worksheet method is used to add sparklines to a cell or a range of cells.
add_sparkline(
{
location => 'F2',
range => 'Sheet1!A2:E2',
type => 'column',
style => }
);
This method contains a lot of parameters and is described in detail in a separate section "SPARKLINES IN EXCEL".
See also the sparklines1.pl
and sparklines2.pl
example programs in the examples
directory of the distro.
Note: Sparklines are a feature of Excel 2010+ only. You can write them to an XLSX file that can be read by Excel 2007 but they won't be displayed.
add_table()
The add_table()
method is used to group a range of cells into an Excel Table.
add_table( 'B3:F7', { ... } );
This method contains a lot of parameters and is described in detail in a separate section "TABLES IN EXCEL".
See also the tables.pl
program in the examples directory of the distro
get_name()
The get_name()
method is used to retrieve the name of a worksheet. For example:
$sheet ( $sheet->get_name();
}
For reasons related to the design of Excel::Writer::XLSX and to the internals of Excel there is no set_name()
method. The only way to set the worksheet name is via the add_worksheet()
method.
activate()
The activate()
method is used to specify which worksheet is initially visible in a multi-sheet workbook:
'To' );
'the' );
'wind' );
activate();
This is similar to the Excel VBA activate method. More than one worksheet can be selected via the select()
method,see below,however only one worksheet can be active.
The default active worksheet is the first worksheet.
select()
The select()
method is used to indicate that a worksheet is selected in a multi-sheet workbook:
activate();
$worksheet2->select();
$worksheet3->select();
A selected worksheet has its tab highlighted. Selecting worksheets is a way of grouping them together so that,several worksheets could be printed in one go. A worksheet that has been activated via the activate()
method will also appear as selected.
hide()
The hide()
method is used to hide a worksheet:
hide();
You may wish to hide a worksheet in order to avoid confusing a user with intermediate data or calculations.
A hidden worksheet can not be activated or selected so this method is mutually exclusive with the activate()
and select()
methods. In addition,since the first worksheet will default to being the active worksheet,you cannot hide the first worksheet without activating another sheet:
hide();
set_first_sheet()
The activate()
method determines which worksheet is initially selected. However,if there are a large number of worksheets the selected worksheet may not appear on the screen. To avoid this you can select which is the leftmost visible worksheet using set_first_sheet()
:
for ( 1 .. 20 ) {
$workbook->add_worksheet;
}
$worksheet21 = $worksheet22 = $worksheet21->set_first_sheet();
$worksheet22->activate();
This method is not required very often. The default value is the first worksheet.
protect();
The protect()
method also has the effect of enabling a cell's locked
and hidden
properties if they have been set. A locked cell cannot be edited and this property is on by default for all cells. A hidden cell will display the results of a formula but not the formula itself.
See the protection.pl
program in the examples directory of the distro for an illustrative example and the set_locked
and set_hidden
format methods in "CELL FORMATTING".
You can optionally add a password to the worksheet protection:
protect( 'drowssap' );
Passing the empty string ''
is the same as turning on protection without a password.
Note,the worksheet level password in Excel provides very weak protection. It does not encrypt your data and is very easy to deactivate. Full workbook encryption is not supported by Excel::Writer::XLSX
since it requires a completely different file format and would take several man months to implement.
You can specify which worksheet elements you wish to protect by passing a hash_ref with any or all of the following keys:
# Default shown.
%options = (
objects => => => => => => => => => => => sort => => => => );
The default boolean values are shown above. Individual elements can be protected as follows:
'drowssap', { insert_rows => 1 } );
"Cell notation".
Examples:
set_selection( 3 ); # 1. Cell D4.
6 ); # 2. Cells D4 to G7.
3 ); # 3. Cells G7 to D4.
$worksheet4->set_selection( 'D4' ); # Same as 1.
$worksheet5->'D4:G7' ); # Same as 2.
$worksheet6->'G7:D4' ); # Same as 3.
The default cell selections is (0,0),'A1'.
set_row( 20 ); # Row 1 height set to 20
If you wish to set the format without changing the height you can pass undef
as the height parameter:
$format );
The $format
parameter will be applied to any cells in the row that don't have a format. For example
$format1 ); # Set the format for row 1
'Hello' ); # Defaults to $format1
$format2 ); # Keeps $format2
If you wish to define a row format in this way you should call the method before any calls to write()
. Calling it afterwards will overwrite any format that was previously specified.
The $hidden
parameter should be set to 1 if you wish to hide a row. This can be used,to hide intermediary steps in a complicated calculation:
20, 1 );
1 );
The $level
parameter is used to set the outline level of the row. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent rows with the same outline level are grouped together into a single outline.
The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed):
1 );
The $hidden
parameter can also be used to hide collapsed outlined rows when used in conjunction with the $level
parameter.
1 );
For collapsed outlines you should also indicate which row has the collapsed +
symbol using the optional $collapsed
parameter.
1 );
For a more complete example see the outline.pl
and outline_collapsed.pl
programs in the examples directory of the distro.
Excel allows up to 7 outline levels. Therefore the $level
parameter should be in the range 0 <= $level <= 7
.
set_column( # Column A width set to 20
30 ); # Columns B-D width set to 30
set_column( 'E:E',255)">20 ); # Column E width set to 20
'F:H',255)">30 ); # Columns F-H width set to 30
The 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 Calibri 11. Unfortunately,there is no way to specify "AutoFit" for a column in the Excel file format. This feature is only available at runtime from within Excel.
As usual the $format
parameter is optional,for additional information,153)" rel="nofollow">"CELL FORMATTING"
. If you wish to set the format without changing the width you can pass undef
as the width parameter:
$format );
The $format
parameter will be applied to any cells in the column that don't have a format. For example
'A:A',131); font-style:italic"># Set format for col 1
'Hello' ); $format2 ); # Keeps $format2
If you wish to define a column format in this way you should call the method before any calls to write()
. If you call it afterwards it won't have any effect.
A default row format takes precedence over a default column format
$format1 ); # Set format for row 1
$format2 ); # Defaults to $format2
The $hidden
parameter should be set to 1 if you wish to hide a column. This can be used,0)">'D:D',255)">1 );
The $level
parameter is used to set the outline level of the column. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent columns with the same outline level are grouped together into a single outline.
The following example sets an outline level of 1 for columns B to G:
'B:G',255)">1 );
The $hidden
parameter can also be used to hide collapsed outlined columns when used in conjunction with the $level
parameter.
'H:H',153); font-size:14px">set_default_row( 24 ); # Set the default row height to 24.
The option to hide unused rows is used by Excel as an optimisation so that the user can hide a large number of rows without generating a very large file with an entry for each hidden row.
set_default_row( undef,255)">1 );
See the hide_row_col.pl
example program.
"OUTLINES AND GROUPING IN EXCEL".
The $visible
parameter is used to control whether or not outlines are visible. Setting this parameter to 0 will cause all outlines on the worksheet to be hidden. They can be unhidden in Excel by means of the "Show Outline Symbols" command button. The default setting is 1 for visible outlines.
outline_settings( 0 );
The $symbols_below
parameter is used to control whether the row outline symbol will appear above or below the outline level bar. The default setting is 1 for symbols to appear below the outline level bar.
The $symbols_right
parameter is used to control whether the column outline symbol will appear to the left or the right of the outline level bar. The default setting is 1 for symbols to appear to the right of the outline level bar.
The $auto_style
parameter is used to control whether the automatic outline generator in Excel uses automatic styles when creating an outline. This has no effect on a file generated by Excel::Writer::XLSX
but it does have an effect on how the worksheet behaves after it is created. The default setting is 0 for "Automatic Styles" to be turned off.
The default settings for all of these parameters correspond to Excel's default parameters.
The worksheet parameters controlled by outline_settings()
are rarely used.
Window->Freeze Panes menu command in Excel
The parameters $row
and $col
are used to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. Therefore to freeze the first row of a worksheet it is necessary to specify the split at row 2 (which is 1 as the zero-based index). This might lead you to think that you are using a 1 based index but this is not the case.
You can set one of the $row
and $col
parameters as zero if you do not want either a vertical or horizontal split.
Examples:
freeze_panes( # Freeze the first row
freeze_panes( 'A2' ); # Same using A1 notation
# Freeze the first column
'B1' ); # Freeze first row and first 2 columns
# Same using A1 notation
The parameters $top_row
and $left_col
are optional. They are used to specify the top-most or left-most visible row or column in the scrolling region of the panes. For example to freeze the first row and to have the scrolling region begin at row twenty:
0 );
You cannot use A1 notation for the $top_row
and $left_col
parameters.
See also the panes.pl
program in the examples
directory of the distribution.
split_panes( ); # First row
8.43 ); # First column
# First row and column
You cannot use A1 notation with this method.
See also the freeze_panes()
method and the panes.pl
program in the examples
directory of the distribution.
add_format(
border => => 'vcenter',
align => 'center',
);
merge_range( 'B3:D4',0)">'Vertical and horizontal',102); font-weight:bold">$format );
merge_range()
writes its $token
argument using the worksheet write()
method. Therefore it will handle numbers,strings,formulas or urls as required. If you need to specify the required write_*()
method use the merge_range_type()
method,see below.
The full possibilities of this method are shown in the merge3.pl
to merge6.pl
programs in the examples
directory of the distribution.
required data into to a merged range. However,there may be times where this isn't what you require so as an alternative the merge_range_type ()
method allows you to specify the type of data you wish to write. For example:
merge_range_type( 'number',0)">'B2:C2',255)">123,102); font-weight:bold">$format1 );
'string',0)">'B4:C4',0)">'foo',102); font-weight:bold">$format2 );
'formula',0)">'B6:C6',0)">'=1+2',102); font-weight:bold">$format3 );
The $type
must be one of the following,which corresponds to a write_*()
method:
'number'
'string'
'formula'
'array_formula'
'blank'
'rich_string'
'date_time'
'url'
Any arguments after the range should be whatever the appropriate method accepts:
'rich_string',0)">'B8:C8',
$format4 );
Note,you must always pass a $format
object as an argument,even if it is a default format.
set_zoom( $scale )
Set the worksheet zoom factor in the range 10 <= $scale <= 400
:
set_zoom( 50 );
75 );
300 );
400 );
The default zoom factor is 100. You cannot zoom to "Selection" because it is calculated by Excel at run-time.
Note, set_zoom()
does not affect the scale of the printed page. For that you should use set_print_scale()
.
right_to_left()
The right_to_left()
method is used to change the default direction of the worksheet from left-to-right,with the A1 cell in the top left,to right-to-left,with the A1 cell in the top right.
right_to_left();
This is useful when creating Arabic,Hebrew or other near or far eastern worksheets that use right-to-left as the default direction.
hide_zero()
The hide_zero()
method is used to hide any zero values that appear in cells.
hide_zero();
In Excel this option is found under Tools->Options->View.
set_tab_color()
The set_tab_color()
method is used to change the colour of the worksheet tab. You can use one of the standard colour names provided by the Format object or a colour index. See "COLOURS IN EXCEL" and the set_custom_color()
method.
set_tab_color( set_tab_color( 0x0C );
See the tab_colors.pl
program in the examples directory of the distro.
autofilter( 10,255)">3 );
autofilter( 'A1:D11' ); # Same as above in A1 notation.
Filter conditions can be applied using the filter_column()
or filter_column_list()
method.
See the autofilter.pl
program in the examples directory of the distro for a more detailed example.
This parameter is passed in a hash ref to data_validation()
.
The 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'.
error_title => 'Input value is not valid',153); font-size:14px">error_message
This parameter is passed in a hash ref to data_validation()
.
The 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.".
=> => 'It should be an integer between 1 and 100',153); font-size:14px">error_type
This parameter is passed in a hash ref to data_validation()
.
The error_type
parameter is used to specify the type of error dialog that is displayed. There are 3 options:
'stop'
'warning'
'information'
The default is 'stop'
.
show_error
This parameter is passed in a hash ref to data_validation()
.
The 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 error_message
. It is on by default.
show_error => Data Validation Examples
Example 1. Limiting input to an integer greater than a fixed value.
=> });
Example 2. Limiting input to an integer greater than a fixed value where the value is referenced from a cell.
=> '=E3',
});
Example 3. Limiting input to a decimal in a fixed range.
0.1,
});
Example 4. Limiting input to a value in a dropdown list.
=> [});
Example 5. Limiting input to a value in a dropdown list where the list is specified as a cell range.
=> '=$E$4:$G$4',
});
Example 6. Limiting input to a date in a fixed range.
=> '2008-01-01T',
maximum => '2008-12-12T',
});
Example 7. Displaying a message when the cell is selected.
{
validate => => => => => 'Enter an integer:',
input_message => });
See also the data_validate.pl
program in the examples directory of the distro.
CONDITIONAL FORMATTING IN EXCEL 
Conditional formatting is a feature of Excel which allows you to apply a format to a cell or a range of cells based on a certain criteria.
For example the following criteria is used to highlight cells >= 50 in red in the conditional_format.pl
example from the distro:
# Write a conditional format over a range.
'B3:K12',
}
);

conditional_formatting( "Cell notation" for more information.
Using A1
style notation is is also possible to specify non-contiguous ranges,separated by a comma. For example:
'A1:D5,A8:D12', {...} );
The last parameter in conditional_formatting()
must be a hash ref containing the parameters that describe the type and style of the data validation. The main parameters are:
type
format
criteria
value
minimum
maximum
Other,less commonly used parameters are:
min_type
mid_type
max_type
min_value
mid_value
max_value
min_color
mid_color
max_color
bar_color
Additional parameters which are used for specific conditional format types are shown in the relevant sections below.
type
This parameter is passed in a hash ref to conditional_formatting()
.
The type
parameter is used to set the type of conditional formatting that you wish to apply. It is always required and it has no default value. Allowable type
values and their associated parameters are:
Type Parameters
==== ==========
cell criteria
value
minimum
maximum
date criteria
value
minimum
maximum
time_period criteria
text criteria
value
average criteria
duplicate (none)
unique (none)
top criteria
value
bottom criteria
value
blanks (none)
no_blanks (none)
errors (none)
no_errors (none)
2_color_scale (none)
3_color_scale (none)
data_bar (none)
formula criteria
All conditional formatting types have a format
parameter,see below. Other types and parameters such as icon sets will be added in time.
type => 'cell'
This is the most common conditional formatting type. It is used when a format is applied to a cell based on a simple criterion. For example:
$red_format,
}
);
Or,using the between
criteria:
'C1:C4',
minimum => => 30,102); font-weight:bold">$green_format,
}
);
criteria
The criteria
parameter is used to set the criteria by which the cell data will be evaluated. It has no default value. The most common criteria as applied to { type => 'cell' }
are:
value
The value
is generally used along with the criteria
parameter to set the rule by which the cell data will be evaluated.
type => 5
format => '$C$1',
format => format
The format
parameter is used to specify the format that will be applied to the cell when the conditional formatting criterion is met. The format is created using the add_format()
method in the same way as cell formats:
=> 5
format => }
);
The conditional format follows the same rules as in Excel: it is superimposed over the existing cell format and not all font and border properties can be modified. Font properties that can't be modified are font name,font size,superscript and subscript. The border property that cannot be modified is diagonal borders.
Excel specifies some default formats to be used with conditional formatting. You can replicate them using the following Excel::Writer::XLSX formats:
# Light red fill with dark red text.
my add_format(
bg_color => '#FFC7CE',
color => '#9C0006',
);
# Light yellow fill with dark yellow text.
my '#FFEB9C',0)">'#9C6500',131); font-style:italic"># Green fill with dark green text.
my '#C6EFCE',0)">'#006100',153); font-size:14px">minimum
The minimum
parameter is used to set the lower limiting value when the criteria
is either 'between'
or 'not between'
:
maximum
sheets()
is a reference to a worksheet object you can write the above example as:perldata
manpage.set_1904()
workbook method. You can query the current value by calling the get_1904()
workbook method. This returns 0 for 1900 and 1 for 1904.set_1904()
.set_optimization()
method is used to turn on optimizations in the Excel::Writer::XLSX module. Currently there is only one optimization available and that is to reduce memory usage.write_*()
methods. As such data should be written in sequential row order once the optimization is turned on.add_worksheet()
.add_worksheet()
method from a workbook object:A:A
column notation:Excel::Writer::XLSX::Utility
module that is included in the distro contains helper functions for dealing with A1 notation,for example:The general rule is that if the data looks like a something then a something is written. Here are some examples in both row-column and A1 notation:
# Same as: 'Hello' ); # write_string() 'One' ); 2,255)">2 ); # write_number() 3.00001 ); 4,0)">"" ); # write_blank() 5,0)">'' ); 6, undef ); 7,255)">0 ); 8,0)">'http://www.perl.com/' ); # write_url() 'A9',0)">'ftp://ftp.cpan.org/' ); 'A10',0)">'internal:Sheet1!A1' ); 'A11',0)">'external:c:\foo.xlsx' ); 'A12',0)">'=A3 + 3*A4' ); # write_formula() 'A13',0)">'=SIN(PI()/4)' ); 'A14', \@array ); # write_row() 'A15', [\@array] ); # write_col() # And if the keep_leading_zeros property is set: 'A16',0)">'2' ); 'A17',0)">'02' ); 'A18',0)">'00002' ); # write_string() # Write an array formula. Not available in Spreadsheet::WriteExcel. 'A19',0)">'{=SUM(A1:B1*A2:B2)}' ); # write_formula()
The "looks like" rule is defined by regular expressions:
write_number()
if $token
is a number based on the following regex: $token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
.
write_string()
if keep_leading_zeros()
is set and $token
is an integer with leading zeros based on the following regex: $token =~ /^0\d+$/
.
write_blank()
if $token
is undef or a blank string: undef
, ""
or ''
.
write_url()
if $token
is a http,https,ftp or mailto URL based on the following regexes: $token =~ m|^[fh]tt?ps?://|
or $token =~ m|^mailto:|
.
write_url()
if $token
is an internal or external sheet reference based on the following regex: $token =~ m[^(in|ex)ternal:]
.
write_formula()
if the first character of $token
is "="
.
write_array_formula()
if the $token
matches /^{=.*}$/
.
write_row()
if $token
is an array ref.
write_col()
if $token
is an array ref of array refs.
write_string()
if none of the prevIoUs conditions apply.
The $format
parameter is optional. It should be a valid Format object,see "CELL FORMATTING":
'center' ); 'Hello',102); font-weight:bold">$format ); # Formatted string
The write() method will ignore empty strings or undef
tokens unless a format is also supplied. As such you needn't worry about special handling for empty orundef
values in your data. See also the write_blank()
method.
One problem with the write()
method is that occasionally data looks like a number but you don't want it treated as a number. For example,zip codes or ID numbers often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. You can change this default behavIoUr by using the keep_leading_zeros()
method. While this property is in place any integers with leading zeros will be treated as strings and the zeros will be preserved. See the keep_leading_zeros()
section for a full discussion of this issue.
You can also add your own data handlers to the write()
method using add_write_handler()
.
The write()
method will also handle Unicode strings in UTF-8
format.
The write
methods return:
0 for success. -1 for insufficient number of arguments. -2 for row or column out of bounds. -3 for string too long.
write_number( 123456 );
write_number( 'A2',255)">2.3451 );
See the note about "Cell notation". The $format
parameter is optional.
In general it is sufficient to use the write()
method.
Note: some versions of Excel 2007 do not display the calculated values of formulas written by Excel::Writer::XLSX. Applying all available Service Packs to Excel should fix this.
write_string( 'Your text here' );
write_string( 'or here' );
The maximum string size is 32767 characters. However the maximum string segment that Excel can display in a cell is 1000. All 32767 characters can be displayed in the formula bar.
The $format
parameter is optional.
The write()
method will also handle strings in UTF-8
format. See also the unicode_*.pl
programs in the examples directory of the distro.
In general it is sufficient to use the write()
method. However,you may sometimes wish to use the write_string()
method to write data that looks like a number but that you don't want treated as a number. For example,zip codes or phone numbers:
# Write as a plain string
'01209' );
However,if the user edits this string Excel may convert it back to a number. To get around this you can use the Excel text format @
:
# Format as a string. Doesn't change to a number when edited
my add_format( num_format => '@' );
'01209',102); font-weight:bold">$format1 );
See also the note about "Cell notation".
bold and this is italic" you would use the following:
$bold = add_format( bold => 1 );
my $italic = add_format( italic => 1 );
write_rich_string( 'This is ',102); font-weight:bold">$bold,0)">'bold',0)">' and this is ',102); font-weight:bold">$italic,0)">'italic' );
The basic rule is to break the string into fragments and put a $format
object before the fragment that you want to format. For example:
# Unformatted string.
'This is an example string'
# Break it into fragments.
'This is an ',0)">'example',0)">' string'
# Add formatting before the fragments you want formatted.
$format,131); font-style:italic"># In Excel::Writer::XLSX.
' string' );
String fragments that don't have a format are given a default format. So for example when writing the string "Some bold text" you would use the first example below but it would be equivalent to the second:
# With default formatting:
my $bold = add_format( bold => 'Some ',0)">' text' );
# Or more explicitly:
my $default = add_format();
$default,0)">' text' );
As with Excel,only the font properties of the format such as font name,style,size,underline,color and effects are applied to the string fragments. Other features such as border,background,text wrap and alignment must be applied to the cell.
The write_rich_string()
method allows you to do this by using the last argument as a cell format (if it is a format object). The following example centers a rich string in the cell:
add_format( bold => $center = add_format( align => 'A5',0)">'bold text',0)">' centered',102); font-weight:bold">$center );
See the rich_strings.pl
example in the distro for more examples.
add_format( bold => add_format( italic => $red = add_format( color => 'red' );
my $blue = 'blue' );
my add_format( align => 'center' );
my $super = add_format( font_script => 1 );
# Write some strings with multiple formats.
'italic' );
$red,0)">'red',102); font-weight:bold">$blue,0)">'blue' );
$center );
'A7',0)">'j = k',102); font-weight:bold">$super,0)">'(n-1)',102); font-weight:bold">$center );

As with write_sting()
the maximum string size is 32767 characters. See also the note about keep_leading_zeros()
This method changes the default handling of integers with leading zeros when using the write()
method.
The write()
method uses regular expressions to determine what type of data to write to an Excel worksheet. If the data looks like a number it writes a number using write_number()
. One problem with this approach is that occasionally data looks like a number but you don't want it treated as a number.
Zip codes and ID numbers,for example,often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. This is the also the default behavIoUr when you enter data manually in Excel.
To get around this you can use one of three options. Write a formatted number,write the number as a string or use the keep_leading_zeros()
method to change the default behavIoUr of write()
:
# Implicitly write a number,the leading zero is removed: 1209
'01209' );
# Write a zero padded number using a format: 01209
my '00000' );
$format1 );
# Write explicitly as a string: 01209
# Write implicitly as a string: 01209
keep_leading_zeros();
'01209' );
The above code would generate a worksheet that looked like the following:
-----------------------------------------------------------
| | A | B | C | D | ...
-----------------------------------------------------------
| 1 | 1209 | | | | ...
| 2 | 01209 | | | | ...
| 3 | 01209 | | | | ...
| 4 | 01209 | | | | ...
The examples are on different sides of the cells due to the fact that Excel displays strings with a left justification and numbers with a right justification by default. You can change this by using a format to justify the data,153)" rel="nofollow">"CELL FORMATTING"
.
It should be noted that if the user edits the data in examples A3
and A4
the strings will revert back to numbers. Again this is Excel's default behavIoUr. To avoid this you can use the text format @
:
# Format as a string (01209)
my $format2 );
The keep_leading_zeros()
property is off by default. The keep_leading_zeros()
method takes 0 or 1 as an argument. It defaults to 1 if an argument isn't specified:
keep_leading_zeros(); # Set on
keep_leading_zeros( 1 ); 0 ); # Set off
See also the add_write_handler()
method.
write_blank( $format );
This method is used to add formatting to a cell which doesn't contain a string or number value.
Excel differentiates between an "Empty" cell and a "Blank" cell. An "Empty" cell is a cell which doesn't contain data whilst a "Blank" cell is a cell which doesn't contain data but does contain formatting. Excel stores "Blank" cells but ignores "Empty" cells.
As such,if you write an empty cell without formatting it is ignored:
undef, undef ); # Ignored
This seemingly uninteresting fact means that you can write arrays of data without special treatment for undef
or empty string values.
See the note about @array = ( 'awk',0)">'gawk',0)">'mawk' );
$array_ref = \@array;
write_row( $array_ref );
# The above example is equivalent to:
$array[0] );
1] );
2] );
Note: For convenience the write()
method behaves in the same way as write_row()
if it is passed an array reference. Therefore the following two method calls are equivalent:
write_row( $array_ref ); # Write a row of data
$worksheet->write( @H_285_3016@# Same thing
As with all of the write methods the $format
parameter is optional. If a format is specified it is applied to all the elements of the data array.
Array references within the data will be treated as columns. This allows you to write 2D arrays of data in one go. For example:
@eec = (
['maggie',0)">'milly',0)">'molly',0)">'may' ],
[13, 14, 15,255)">16 ],
['shell',0)">'star',0)">'crab',0)">'stone']
);
@eec );
Would produce a worksheet as follows:
-----------------------------------------------------------
| | A | B | C | D | E | ...
-----------------------------------------------------------
| 1 | maggie | 13 | shell | ... | ... | ...
| 2 | milly | 14 | star | ... | ... | ...
| 3 | molly | 15 | crab | ... | ... | ...
| 4 | may | 16 | stone | ... | ... | ...
| 5 | ... | ... | ... | ... | ... | ...
| 6 | ... | ... | ... | ... | ... | ...
To write the data in a row-column order refer to the write_col()
method below.
Any undef
values in the data will be ignored unless a format is applied to the data,in which case a formatted blank cell will be written. In either case the appropriate row or column value will still be incremented.
To find out more about array references refer to perlref
and perlreftut
in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to perllol
.
The write_row()
method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the write()
method above.
See also the write_arrays.pl
program in the examples
directory of the distro.
The write_row()
method allows the following idiomatic conversion of a text file to an Excel file:
#!/usr/bin/perl -w
use strict;
use Excel::Writer::XLSX;
my 'file.xlsx' );
my add_worksheet();
open INPUT,0)">'file.txt' or die "Couldn't open file: $!";
$worksheet->write( $. -[split] ) while <INPUT>;
write_col( 2] );
As with all of the write methods the $format
parameter is optional. If a format is specified it is applied to all the elements of the data array.
Array references within the data will be treated as rows. This allows you to write 2D arrays of data in one go. For example:
write_col( 1 | maggie | milly | molly | may | ... | ...
| 2 | 13 | 14 | 15 | 16 | ... | ...
| 3 | shell | star | crab | stone | ... | ...
| 4 | ... | ... | ... | ... | ... | ...
| 6 | ... | ... | ... | ... | ... | ...
To write the data in a column-row order refer to the write_row()
method above.
Any undef
values in the data will be ignored unless a format is applied to the data,in which case a formatted blank cell will be written. In either case the appropriate row or column value will still be incremented.
As noted above the write()
method can be used as a synonym for write_row()
and write_row()
handles nested array refs as columns. Therefore,the following two method calls are equivalent although the more explicit call to write_col()
would be preferable for maintainability:
$array_ref ); # Write a column of data
[ $array_ref ] ); # Same thing
To find out more about array references refer to perlref
and perlreftut
in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to perllol
.
The write_col()
method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the write()
method above.
See also the write_arrays.pl
program in the examples
directory of the distro.
write_date_time( '2004-05-13T23:20',102); font-weight:bold">$date_format );
The $date_string
should be in the following format:
yyyy-mm-ddThh:mm:ss.sss
This conforms to an ISO8601 date but it should be noted that the full range of ISO8601 formats are not supported.
The following variations on the $date_string
parameter are permitted:
yyyy-mm-ddThh:mm:ss.sss # Standard format
yyyy-mm-ddT # No time
Thh:mm:ss.sss # No date
yyyy-mm-ddThh:mm:ss.sssZ # Additional Z (but not time zones)
yyyy-mm-ddThh:mm:ss # No fractional seconds
yyyy-mm-ddThh:mm # No seconds
Note that the T
is required in all cases.
A date should always have a $format
,otherwise it will appear as a number,see "DATES AND TIME IN EXCEL" and "CELL FORMATTING". Here is a typical example:
$date_format = 'mm/dd/yy' );
$date_format );
Valid dates should be in the range 1900-01-01 to 9999-12-31,for the 1900 epoch and 1904-01-01 to 9999-12-31,for the 1904 epoch. As with Excel,dates outside these ranges will be written as a string.
See also the date_time.pl program in the examples
directory of the distro.
add_format( color => 'blue', underline => 1 );
Note,this behaviour is different from Spreadsheet::WriteExcel which provides a default hyperlink format if one isn't specified by the user.
There are four web style URI's supported: http://
, https://
, ftp://
and mailto:
:
write_url( 'ftp://www.perl.org/', write_url( 'mailto:jmcnamara@cpan.org',102); font-weight:bold">$format );
You can display an alternative string using the $label
parameter:
'Perl' );
If you wish to have some other cell data such as a number or a formula you can overwrite the cell using another call to write_*()
:
' );
# Overwrite the URL string with a formula. The cell is still a link.
write_formula( '=1+1',102); font-weight:bold">$format );
There are two local URIs supported: internal:
and external:
. These are used for hyperlinks to internal worksheet references or external workbook and worksheet references:
'A6',0)">'internal:Sheet2!A1', 'A8',0)">'internal:Sheet2!A1:B2', q{internal:'Sales Data'!A1},0)">'external:c:\temp\foo.xlsx',0)">'external:c:\foo.xlsx#Sheet2!A1', 'external:..\foo.xlsx', 'external:..\foo.xlsx#Sheet2!A1',0)">'external:\\\\NET\share\foo.xlsx',102); font-weight:bold">$format );
All of the these URI types are recognised by the write()
method,see above.
Worksheet references are typically of the form Sheet1!A1
. You can also refer to a worksheet range using the standard Excel notation: Sheet1!A1:B2
.
In external links the workbook and worksheet name must be separated by the #
character: external:Workbook.xlsx#Sheet1!A1'
.
You can also link to a named range in the target worksheet. For example say you have a named range called my_name
in the workbook c:\temp\foo.xlsx
you could link to it as follows:
'external:c:\temp\foo.xlsx#my_name' );
Excel requires that worksheet names containing spaces or non alphanumeric characters are single quoted as follows 'Sales Data'!A1
. If you need to do this in a single quoted string then you can either escape the single quotes \'
or use the quote operator q{}
as described in perlop
in the main Perl documentation.
Links to network files are also supported. MS/Novell Network files normally begin with two back slashes as follows \\NETWORK\etc
. In order to generate this in a single or double quoted string you will have to escape the backslashes, '\\\\NETWORK\etc'
.
If you are using double quote strings then you should be careful to escape anything that looks like a Metacharacter. For more information see perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?
.
Finally,you can avoid most of these quoting problems by using forward slashes. These are translated internally to backslashes:
"external:c:/temp/foo.xlsx" );
'external://NETWORK/share/foo.xlsx' );
Note: Excel::Writer::XLSX will escape the following characters in URLs as required by Excel: \s " < > \ [ ] ` ^ { }
unless the URL already contains %xx
style escapes. In which case it is assumed that the URL was escaped correctly by the user and will by passed directly to Excel.
See also,the note about write_formula( '=$B$3 + B4' );
'=SIN(PI()/4)' );
'=SUM(B1:B5)' );
'=IF(A3>1,"Yes","No")' );
'=AVERAGE(1,2,3,4)' );
'=DATEVALUE("1-Jan-2001")' );
Array formulas are also supported:
'{=SUM(A1:B1*A2:B2)}' );
See also the write_array_formula()
method below.
See the note about "Cell notation". For more information about writing Excel formulas see "FORMULAS AND FUNCTIONS IN EXCEL"
If required,it is also possible to specify the calculated value of the formula. This is occasionally necessary when working with non-Excel applications that don't calculate the value of the formula. The calculated $value
is added at the end of the argument list:
'=2+2',255)">4 );
However,this probably isn't something that you will ever need to do. If you do use this feature then do so with care.
write_array_formula('A1:A1',0)">'{=SUM(B1:C1*B2:C2)}');
It this case however it is easier to just use the write_formula()
or write()
methods:
# Same as above but more concise.
'{=SUM(B1:C1*B2:C2)}' );
'{=SUM(B1:C1*B2:C2)}' );
For array formulas that return a range of values you must specify the range that the return values will be written to:
write_array_formula( 'A1:A3', '{=TREND(C1:C3,B1:B3)}' );
write_array_formula( );
If required,B1:B3)}',255)">105 );
In addition,some early versions of Excel 2007 don't calculate the values of array formulas when they aren't supplied. Installing the latest Office Service Pack should fix this issue.
See also the array_formula.pl
program in the examples
directory of the distro.
Note: Array formulas are not supported by Spreadsheet::WriteExcel.
store_formula( $formula )
Deprecated. This is a Spreadsheet::WriteExcel method that is no longer required by Excel::Writer::XLSX. See below.
$worksheet->write ( 'Hello' );
write_comment( 'This is a comment.' );
As usual you can replace the $row
and $column
parameters with an A1
cell reference. See the note about "Cell notation".
$worksheet->write ( 'C3',0)">'Hello');
write_comment( 'This is a comment.' );
The write_comment()
method will also handle strings in UTF-8
format.
"\x{263a}" ); # Smiley
'C4',0)">'Comment ca va?' );
In addition to the basic 3 argument form of write_comment()
you can pass in several optional key/value pairs to control the format of the comment. For example:
=> => 'Perl' );
Most of these options are quite specific and in general the default comment behavIoUr will be all that you need. However,should you need greater control over the format of the cell comment the following options are available:
author
visible
x_scale
width
y_scale
height
color
start_cell
start_row
start_col
x_offset
y_offset
-
@L_977_301@
Option: author
-
This option is used to indicate who is the author of the cell comment. 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.
'Atonement',0)">'Ian McEwan' );
The default author for all cell comments can be set using the set_comments_author()
method (see below).
set_comments_author( 'Perl' );
-
@L_977_301@
Option: visible
-
This option is used to make a cell comment visible when the worksheet is opened. The default behavIoUr in Excel is that comments are initially hidden. However,it is also possible in Excel to make individual or all comments visible. In Excel::Writer::XLSX individual comments can be made visible as follows:
1 );
It is possible to make all comments in a worksheet visible using the show_comments()
worksheet method (see below). Alternatively,if all of the cell comments have been made visible you can hide individual comments:
0 );
-
@L_977_301@
Option: x_scale
-
This option is used to set the width of the cell comment Box as a factor of the default width.
=> 2 );
4.2 );
-
@L_977_301@
Option: width
-
This option is used to set the width of the cell comment Box explicitly in pixels.
=> 200 );
-
@L_977_301@
Option: y_scale
-
This option is used to set the height of the cell comment Box as a factor of the default height.
=> 4.2 );
-
@L_977_301@
Option: height
-
This option is used to set the height of the cell comment Box explicitly in pixels.
=> 200 );
-
@L_977_301@
Option: color
-
This option is used to set the background colour of cell comment Box. You can use one of the named colours recognised by Excel::Writer::XLSX or a colour index. See "COLOURS IN EXCEL".
=> 'green' );
=> 0x35 ); # Orange
-
@L_977_301@
Option: start_cell
-
This option is used to set the cell in which the comment will appear. By default Excel displays comments one cell to the right and one cell above the cell to which the comment relates. However,you can change this behavIoUr if you wish. In the following example the comment which would appear by default in cell D2
is moved to E2
.
=> 'E2' );
-
@L_977_301@
Option: start_row
-
This option is used to set the row in which the comment will appear. See the start_cell
option above. The row is zero indexed.
=> 0 );
-
@L_977_301@
Option: start_col
-
This option is used to set the column in which the comment will appear. See the start_cell
option above. The column is zero indexed.
=> 4 );
-
@L_977_301@
Option: x_offset
-
This option is used to change the x offset,in pixels,of a comment within a cell:
$comment, x_offset => 30 );
-
@L_977_301@
Option: y_offset
-
This option is used to change the y offset,129)">write_comment(30);
You can apply as many of these options as you require.
Note about using options that adjust the position of the cell comment such as start_cell,start_row,start_col,x_offset and y_offset: Excel only displays offset cell comments when they are displayed as "visible". Excel does not display hidden cells as moved when you mouse over them.
Note about row height and comments. If you specify the height of a row that contains a comment then Excel::Writer::XLSX 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 the module at run time and thus the comment Box is stretched with the row. Use the set_row()
method to specify the row height explicitly and avoid this problem.
show_comments()
This method is used to make all cell comments visible when a worksheet is opened.
show_comments();
Individual comments can be made visible using the visible
parameter of the write_comment
method (see above):
1 );
If all of the cell comments have been made visible you can hide individual comments as follows:
show_comments();
0 );
set_comments_author()
This method is used to set the default author of all cell comments.
'Perl' );
Individual comment authors can be set using the author
parameter of the write_comment
method (see above).
The default comment author is an empty string, ''
,if no author is specified.
add_write_handler( qr/^\d\d\d\d$/, \&my_write );
(In the these examples the qr
operator is used to quote the regular expression strings,see perlop for more details).
The method is used as follows. say you wished to write 7 digit ID numbers as a string so that any leading zeros were preserved*,you could do something like the following:
/^\d{7}$/, \&write_my_id );
sub write_my_id {
my $worksheet = shift;
return write_string( @_ );
}
* You could also use the keep_leading_zeros()
method for this.
Then if you call write()
with an appropriate string it will be handled automatically:
# Writes 0000000. It would normally be written as a number; 0.
'0000000' );
The callback function will receive a reference to the calling worksheet and all of the other arguments that were passed to write()
. The callback will see an @_
argument list that looks like the following:
$_[0] A ref to the calling worksheet. *
1] Zero based row number.
2] Zero based column number.
3] A number or string or token.
4] A format ref if any.
5] Any other arguments.
...
* It is good style to shift this off the list so the @_ is the same
as the argument list seen by write().
Your callback should return()
the return value of the write_*
method that was called or undef
to indicate that you rejected the match and want write()
to continue as normal.
So for example if you wished to apply the prevIoUs filter only to ID values that occur in the first column you could modify your callback function as follows:
sub write_my_id {
my $worksheet = shift;
my $col = 1];
if ( $col == 0 ) {
return @_ );
}
else {
# Reject the match and return control to write()
return undef;
}
}
Now,you will get different behavIoUr for the first column and other columns:
'0000000' ); # Writes 0000000
'B1',131); font-style:italic"># Writes 0
You may add more than one handler in which case they will be called in the order that they were added.
Note,the add_write_handler()
method is particularly suited for handling dates.
See the write_handler 1-4
programs in the examples
directory for further examples.
$worksheet1->insert_image( 'perl.bmp' );
$worksheet2->'../images/perl.bmp' );
$worksheet3->'.c:\images\perl.bmp' );
The parameters $x
and $y
can be used to specify an offset from the top left hand corner of the cell specified by $row
and $col
. The offset values are in pixels.
insert_image('perl.bmp',255)">32,255)">10);
The offsets can be greater than the width or height of the underlying cell. This can be occasionally useful if you wish to align two or more images relative to the same cell.
The parameters $x_scale
and $y_scale
can be used to scale the inserted image horizontally and vertically:
# Scale the inserted image: width x 2.0,height x 0.8
0.8 );
Note: you must call set_row()
or set_column()
before insert_image()
if you wish to change the default dimensions of any of the rows or columns that the image occupies. The height of a row can also change if you use a font that is larger than the default. This in turn will affect the scaling of your image. To avoid this you should explicitly set the height of the row using set_row()
if it contains a font size that will change the row height.
BMP images must be 24 bit,true colour,bitmaps. In general it is best to avoid BMP images since they aren't compressed.
$chart );
See add_chart()
for details on how to create the Chart object and Excel::Writer::XLSX::Chart for details on how to configure it. See also the chart_*.pl
programs in the examples directory of the distro.
The $x
, $x_scale
and $y_scale
parameters are optional.
The parameters $x
and $y
can be used to specify an offset from the top left hand corner of the cell specified by $row
and $col
. The offset values are in pixels.
$chart,255)">3 );
The parameters $x_scale
and $y_scale
can be used to scale the inserted chart horizontally and vertically:
# Scale the width by 120% and the height by 150%
1.2,255)">1.5 );
$shape = add_shape( name => 'My Shape', type => 'plus' );
# Configure the shape.
$shape->set_text('foo');
...
# Insert the shape into the a worksheet.
insert_shape( $shape );
See add_shape()
for details on how to create the Shape object and Excel::Writer::XLSX::Shape for details on how to configure it.
The $x
,255)">3 );
The parameters $x_scale
and $y_scale
can be used to scale the inserted shape horizontally and vertically:
$shape,255)">1.5 );
See also the shape*.pl
programs in the examples directory of the distro.
'file.xlsm' );
...
'./vbaProject.bin' );
'my_macro' } );
The properties of the button that can be set are:
macro
caption
width
height
x_scale
y_scale
x_offset
y_offset
-
@L_977_301@
Option: macro
-
This option is used to set the macro that the button will invoke when the user clicks on it. The macro should be included using the Workbookadd_vba_project()
method shown above.
'my_macro' } );
The default macro is ButtonX_Click
where X is the button number.
-
@L_977_301@
Option: caption
-
This option is used to set the caption on the button. The default is Button X
where X is the button number.
'my_macro', caption => 'Hello' } );
-
@L_977_301@
Option: width
-
This option is used to set the width of the button in pixels.
128 } );
The default button width is 64 pixels which is the width of a default cell.
-
@L_977_301@
Option: height
-
This option is used to set the height of the button in pixels.
40 } );
The default button height is 20 pixels which is the height of a default cell.
-
@L_977_301@
Option: x_scale
-
This option is used to set the width of the button as a factor of the default width.
2.0 );
-
@L_977_301@
Option: y_scale
-
This option is used to set the height of the button as a factor of the default height.
2.0 );
-
@L_977_301@
Option: x_offset
-
This option is used to change the x offset,of a button within a cell:
2 );
-
@L_977_301@
Option: y_offset
-
This option is used to change the y offset,of a comment within a cell.
Note: Button is the only Excel form element that is available in Excel::Writer::XLSX. Form elements represent a lot of work to implement and the underlying VML Syntax isn't very much fun.
data_validation()
The data_validation()
method is used to construct an Excel data validation or to limit the user input to a dropdown list of values.
data_validation('B3',
{
validate => 'integer',
criteria => => 100,
});
'B5:B9',0)">'list',
value => ['open',0)">'high',0)">'close'],
});
This method contains a lot of parameters and is described in detail in a separate section "DATA VALIDATION IN EXCEL".
See also the data_validate.pl
program in the examples directory of the distro
conditional_formatting()
The conditional_formatting()
method is used to add formatting to a cell or range of cells based on user defined criteria.
conditional_formatting( 'A1:J10',
{
type => 'cell',0)">'>=',255)">50,
format => $format1,
}
);
This method contains a lot of parameters and is described in detail in a separate section "CONDITIONAL FORMATTING IN EXCEL".
See also the conditional_format.pl
program in the examples directory of the distro
add_sparkline()
The add_sparkline()
worksheet method is used to add sparklines to a cell or a range of cells.
add_sparkline(
{
location => 'F2',
range => 'Sheet1!A2:E2',
type => 'column',
style => }
);
This method contains a lot of parameters and is described in detail in a separate section "SPARKLINES IN EXCEL".
See also the sparklines1.pl
and sparklines2.pl
example programs in the examples
directory of the distro.
Note: Sparklines are a feature of Excel 2010+ only. You can write them to an XLSX file that can be read by Excel 2007 but they won't be displayed.
add_table()
The add_table()
method is used to group a range of cells into an Excel Table.
add_table( 'B3:F7', { ... } );
This method contains a lot of parameters and is described in detail in a separate section "TABLES IN EXCEL".
See also the tables.pl
program in the examples directory of the distro
get_name()
The get_name()
method is used to retrieve the name of a worksheet. For example:
$sheet ( $sheet->get_name();
}
For reasons related to the design of Excel::Writer::XLSX and to the internals of Excel there is no set_name()
method. The only way to set the worksheet name is via the add_worksheet()
method.
activate()
The activate()
method is used to specify which worksheet is initially visible in a multi-sheet workbook:
'To' );
'the' );
'wind' );
activate();
This is similar to the Excel VBA activate method. More than one worksheet can be selected via the select()
method,see below,however only one worksheet can be active.
The default active worksheet is the first worksheet.
select()
The select()
method is used to indicate that a worksheet is selected in a multi-sheet workbook:
activate();
$worksheet2->select();
$worksheet3->select();
A selected worksheet has its tab highlighted. Selecting worksheets is a way of grouping them together so that,several worksheets could be printed in one go. A worksheet that has been activated via the activate()
method will also appear as selected.
hide()
The hide()
method is used to hide a worksheet:
hide();
You may wish to hide a worksheet in order to avoid confusing a user with intermediate data or calculations.
A hidden worksheet can not be activated or selected so this method is mutually exclusive with the activate()
and select()
methods. In addition,since the first worksheet will default to being the active worksheet,you cannot hide the first worksheet without activating another sheet:
hide();
set_first_sheet()
The activate()
method determines which worksheet is initially selected. However,if there are a large number of worksheets the selected worksheet may not appear on the screen. To avoid this you can select which is the leftmost visible worksheet using set_first_sheet()
:
for ( 1 .. 20 ) {
$workbook->add_worksheet;
}
$worksheet21 = $worksheet22 = $worksheet21->set_first_sheet();
$worksheet22->activate();
This method is not required very often. The default value is the first worksheet.
protect();
The protect()
method also has the effect of enabling a cell's locked
and hidden
properties if they have been set. A locked cell cannot be edited and this property is on by default for all cells. A hidden cell will display the results of a formula but not the formula itself.
See the protection.pl
program in the examples directory of the distro for an illustrative example and the set_locked
and set_hidden
format methods in "CELL FORMATTING".
You can optionally add a password to the worksheet protection:
protect( 'drowssap' );
Passing the empty string ''
is the same as turning on protection without a password.
Note,the worksheet level password in Excel provides very weak protection. It does not encrypt your data and is very easy to deactivate. Full workbook encryption is not supported by Excel::Writer::XLSX
since it requires a completely different file format and would take several man months to implement.
You can specify which worksheet elements you wish to protect by passing a hash_ref with any or all of the following keys:
# Default shown.
%options = (
objects => => => => => => => => => => => sort => => => => );
The default boolean values are shown above. Individual elements can be protected as follows:
'drowssap', { insert_rows => 1 } );
"Cell notation".
Examples:
set_selection( 3 ); # 1. Cell D4.
6 ); # 2. Cells D4 to G7.
3 ); # 3. Cells G7 to D4.
$worksheet4->set_selection( 'D4' ); # Same as 1.
$worksheet5->'D4:G7' ); # Same as 2.
$worksheet6->'G7:D4' ); # Same as 3.
The default cell selections is (0,0),'A1'.
set_row( 20 ); # Row 1 height set to 20
If you wish to set the format without changing the height you can pass undef
as the height parameter:
$format );
The $format
parameter will be applied to any cells in the row that don't have a format. For example
$format1 ); # Set the format for row 1
'Hello' ); # Defaults to $format1
$format2 ); # Keeps $format2
If you wish to define a row format in this way you should call the method before any calls to write()
. Calling it afterwards will overwrite any format that was previously specified.
The $hidden
parameter should be set to 1 if you wish to hide a row. This can be used,to hide intermediary steps in a complicated calculation:
20, 1 );
1 );
The $level
parameter is used to set the outline level of the row. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent rows with the same outline level are grouped together into a single outline.
The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed):
1 );
The $hidden
parameter can also be used to hide collapsed outlined rows when used in conjunction with the $level
parameter.
1 );
For collapsed outlines you should also indicate which row has the collapsed +
symbol using the optional $collapsed
parameter.
1 );
For a more complete example see the outline.pl
and outline_collapsed.pl
programs in the examples directory of the distro.
Excel allows up to 7 outline levels. Therefore the $level
parameter should be in the range 0 <= $level <= 7
.
set_column( # Column A width set to 20
30 ); # Columns B-D width set to 30
set_column( 'E:E',255)">20 ); # Column E width set to 20
'F:H',255)">30 ); # Columns F-H width set to 30
The 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 Calibri 11. Unfortunately,there is no way to specify "AutoFit" for a column in the Excel file format. This feature is only available at runtime from within Excel.
As usual the $format
parameter is optional,for additional information,153)" rel="nofollow">"CELL FORMATTING"
. If you wish to set the format without changing the width you can pass undef
as the width parameter:
$format );
The $format
parameter will be applied to any cells in the column that don't have a format. For example
'A:A',131); font-style:italic"># Set format for col 1
'Hello' ); $format2 ); # Keeps $format2
If you wish to define a column format in this way you should call the method before any calls to write()
. If you call it afterwards it won't have any effect.
A default row format takes precedence over a default column format
$format1 ); # Set format for row 1
$format2 ); # Defaults to $format2
The $hidden
parameter should be set to 1 if you wish to hide a column. This can be used,0)">'D:D',255)">1 );
The $level
parameter is used to set the outline level of the column. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent columns with the same outline level are grouped together into a single outline.
The following example sets an outline level of 1 for columns B to G:
'B:G',255)">1 );
The $hidden
parameter can also be used to hide collapsed outlined columns when used in conjunction with the $level
parameter.
'H:H',153); font-size:14px">set_default_row( 24 ); # Set the default row height to 24.
The option to hide unused rows is used by Excel as an optimisation so that the user can hide a large number of rows without generating a very large file with an entry for each hidden row.
set_default_row( undef,255)">1 );
See the hide_row_col.pl
example program.
"OUTLINES AND GROUPING IN EXCEL".
The $visible
parameter is used to control whether or not outlines are visible. Setting this parameter to 0 will cause all outlines on the worksheet to be hidden. They can be unhidden in Excel by means of the "Show Outline Symbols" command button. The default setting is 1 for visible outlines.
outline_settings( 0 );
The $symbols_below
parameter is used to control whether the row outline symbol will appear above or below the outline level bar. The default setting is 1 for symbols to appear below the outline level bar.
The $symbols_right
parameter is used to control whether the column outline symbol will appear to the left or the right of the outline level bar. The default setting is 1 for symbols to appear to the right of the outline level bar.
The $auto_style
parameter is used to control whether the automatic outline generator in Excel uses automatic styles when creating an outline. This has no effect on a file generated by Excel::Writer::XLSX
but it does have an effect on how the worksheet behaves after it is created. The default setting is 0 for "Automatic Styles" to be turned off.
The default settings for all of these parameters correspond to Excel's default parameters.
The worksheet parameters controlled by outline_settings()
are rarely used.
Window->Freeze Panes menu command in Excel
The parameters $row
and $col
are used to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. Therefore to freeze the first row of a worksheet it is necessary to specify the split at row 2 (which is 1 as the zero-based index). This might lead you to think that you are using a 1 based index but this is not the case.
You can set one of the $row
and $col
parameters as zero if you do not want either a vertical or horizontal split.
Examples:
freeze_panes( # Freeze the first row
freeze_panes( 'A2' ); # Same using A1 notation
# Freeze the first column
'B1' ); # Freeze first row and first 2 columns
# Same using A1 notation
The parameters $top_row
and $left_col
are optional. They are used to specify the top-most or left-most visible row or column in the scrolling region of the panes. For example to freeze the first row and to have the scrolling region begin at row twenty:
0 );
You cannot use A1 notation for the $top_row
and $left_col
parameters.
See also the panes.pl
program in the examples
directory of the distribution.
split_panes( ); # First row
8.43 ); # First column
# First row and column
You cannot use A1 notation with this method.
See also the freeze_panes()
method and the panes.pl
program in the examples
directory of the distribution.
add_format(
border => => 'vcenter',
align => 'center',
);
merge_range( 'B3:D4',0)">'Vertical and horizontal',102); font-weight:bold">$format );
merge_range()
writes its $token
argument using the worksheet write()
method. Therefore it will handle numbers,strings,formulas or urls as required. If you need to specify the required write_*()
method use the merge_range_type()
method,see below.
The full possibilities of this method are shown in the merge3.pl
to merge6.pl
programs in the examples
directory of the distribution.
required data into to a merged range. However,there may be times where this isn't what you require so as an alternative the merge_range_type ()
method allows you to specify the type of data you wish to write. For example:
merge_range_type( 'number',0)">'B2:C2',255)">123,102); font-weight:bold">$format1 );
'string',0)">'B4:C4',0)">'foo',102); font-weight:bold">$format2 );
'formula',0)">'B6:C6',0)">'=1+2',102); font-weight:bold">$format3 );
The $type
must be one of the following,which corresponds to a write_*()
method:
'number'
'string'
'formula'
'array_formula'
'blank'
'rich_string'
'date_time'
'url'
Any arguments after the range should be whatever the appropriate method accepts:
'rich_string',0)">'B8:C8',
$format4 );
Note,you must always pass a $format
object as an argument,even if it is a default format.
set_zoom( $scale )
Set the worksheet zoom factor in the range 10 <= $scale <= 400
:
set_zoom( 50 );
75 );
300 );
400 );
The default zoom factor is 100. You cannot zoom to "Selection" because it is calculated by Excel at run-time.
Note, set_zoom()
does not affect the scale of the printed page. For that you should use set_print_scale()
.
right_to_left()
The right_to_left()
method is used to change the default direction of the worksheet from left-to-right,with the A1 cell in the top left,to right-to-left,with the A1 cell in the top right.
right_to_left();
This is useful when creating Arabic,Hebrew or other near or far eastern worksheets that use right-to-left as the default direction.
hide_zero()
The hide_zero()
method is used to hide any zero values that appear in cells.
hide_zero();
In Excel this option is found under Tools->Options->View.
set_tab_color()
The set_tab_color()
method is used to change the colour of the worksheet tab. You can use one of the standard colour names provided by the Format object or a colour index. See "COLOURS IN EXCEL" and the set_custom_color()
method.
set_tab_color( set_tab_color( 0x0C );
See the tab_colors.pl
program in the examples directory of the distro.
autofilter( 10,255)">3 );
autofilter( 'A1:D11' ); # Same as above in A1 notation.
Filter conditions can be applied using the filter_column()
or filter_column_list()
method.
See the autofilter.pl
program in the examples directory of the distro for a more detailed example.
This parameter is passed in a hash ref to data_validation()
.
The 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'.
error_title => 'Input value is not valid',153); font-size:14px">error_message
This parameter is passed in a hash ref to data_validation()
.
The 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.".
=> => 'It should be an integer between 1 and 100',153); font-size:14px">error_type
This parameter is passed in a hash ref to data_validation()
.
The error_type
parameter is used to specify the type of error dialog that is displayed. There are 3 options:
'stop'
'warning'
'information'
The default is 'stop'
.
show_error
This parameter is passed in a hash ref to data_validation()
.
The 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 error_message
. It is on by default.
show_error => Data Validation Examples
Example 1. Limiting input to an integer greater than a fixed value.
=> });
Example 2. Limiting input to an integer greater than a fixed value where the value is referenced from a cell.
=> '=E3',
});
Example 3. Limiting input to a decimal in a fixed range.
0.1,
});
Example 4. Limiting input to a value in a dropdown list.
=> [});
Example 5. Limiting input to a value in a dropdown list where the list is specified as a cell range.
=> '=$E$4:$G$4',
});
Example 6. Limiting input to a date in a fixed range.
=> '2008-01-01T',
maximum => '2008-12-12T',
});
Example 7. Displaying a message when the cell is selected.
{
validate => => => => => 'Enter an integer:',
input_message => });
See also the data_validate.pl
program in the examples directory of the distro.
CONDITIONAL FORMATTING IN EXCEL 
Conditional formatting is a feature of Excel which allows you to apply a format to a cell or a range of cells based on a certain criteria.
For example the following criteria is used to highlight cells >= 50 in red in the conditional_format.pl
example from the distro:
# Write a conditional format over a range.
'B3:K12',
}
);

conditional_formatting( "Cell notation" for more information.
Using A1
style notation is is also possible to specify non-contiguous ranges,separated by a comma. For example:
'A1:D5,A8:D12', {...} );
The last parameter in conditional_formatting()
must be a hash ref containing the parameters that describe the type and style of the data validation. The main parameters are:
type
format
criteria
value
minimum
maximum
Other,less commonly used parameters are:
min_type
mid_type
max_type
min_value
mid_value
max_value
min_color
mid_color
max_color
bar_color
Additional parameters which are used for specific conditional format types are shown in the relevant sections below.
type
This parameter is passed in a hash ref to conditional_formatting()
.
The type
parameter is used to set the type of conditional formatting that you wish to apply. It is always required and it has no default value. Allowable type
values and their associated parameters are:
Type Parameters
==== ==========
cell criteria
value
minimum
maximum
date criteria
value
minimum
maximum
time_period criteria
text criteria
value
average criteria
duplicate (none)
unique (none)
top criteria
value
bottom criteria
value
blanks (none)
no_blanks (none)
errors (none)
no_errors (none)
2_color_scale (none)
3_color_scale (none)
data_bar (none)
formula criteria
All conditional formatting types have a format
parameter,see below. Other types and parameters such as icon sets will be added in time.
type => 'cell'
This is the most common conditional formatting type. It is used when a format is applied to a cell based on a simple criterion. For example:
$red_format,
}
);
Or,using the between
criteria:
'C1:C4',
minimum => => 30,102); font-weight:bold">$green_format,
}
);
criteria
The criteria
parameter is used to set the criteria by which the cell data will be evaluated. It has no default value. The most common criteria as applied to { type => 'cell' }
are:
value
The value
is generally used along with the criteria
parameter to set the rule by which the cell data will be evaluated.
type => 5
format => '$C$1',
format => format
$format
parameter is optional.write()
method.The maximum string size is 32767 characters. However the maximum string segment that Excel can display in a cell is 1000. All 32767 characters can be displayed in the formula bar.
The $format
parameter is optional.
The write()
method will also handle strings in UTF-8
format. See also the unicode_*.pl
programs in the examples directory of the distro.
In general it is sufficient to use the write()
method. However,you may sometimes wish to use the write_string()
method to write data that looks like a number but that you don't want treated as a number. For example,zip codes or phone numbers:
# Write as a plain string '01209' );
However,if the user edits this string Excel may convert it back to a number. To get around this you can use the Excel text format @
:
# Format as a string. Doesn't change to a number when edited my add_format( num_format => '@' ); '01209',102); font-weight:bold">$format1 );
See also the note about "Cell notation".
bold and this is italic" you would use the following:
$bold = add_format( bold => 1 );
my $italic = add_format( italic => 1 );
write_rich_string( 'This is ',102); font-weight:bold">$bold,0)">'bold',0)">' and this is ',102); font-weight:bold">$italic,0)">'italic' );
The basic rule is to break the string into fragments and put a $format
object before the fragment that you want to format. For example:
# Unformatted string.
'This is an example string'
# Break it into fragments.
'This is an ',0)">'example',0)">' string'
# Add formatting before the fragments you want formatted.
$format,131); font-style:italic"># In Excel::Writer::XLSX.
' string' );
String fragments that don't have a format are given a default format. So for example when writing the string "Some bold text" you would use the first example below but it would be equivalent to the second:
# With default formatting:
my $bold = add_format( bold => 'Some ',0)">' text' );
# Or more explicitly:
my $default = add_format();
$default,0)">' text' );
As with Excel,only the font properties of the format such as font name,style,size,underline,color and effects are applied to the string fragments. Other features such as border,background,text wrap and alignment must be applied to the cell.
The write_rich_string()
method allows you to do this by using the last argument as a cell format (if it is a format object). The following example centers a rich string in the cell:
add_format( bold => $center = add_format( align => 'A5',0)">'bold text',0)">' centered',102); font-weight:bold">$center );
See the rich_strings.pl
example in the distro for more examples.
add_format( bold => add_format( italic => $red = add_format( color => 'red' );
my $blue = 'blue' );
my add_format( align => 'center' );
my $super = add_format( font_script => 1 );
# Write some strings with multiple formats.
'italic' );
$red,0)">'red',102); font-weight:bold">$blue,0)">'blue' );
$center );
'A7',0)">'j = k',102); font-weight:bold">$super,0)">'(n-1)',102); font-weight:bold">$center );

As with write_sting()
the maximum string size is 32767 characters. See also the note about keep_leading_zeros()
$format
object before the fragment that you want to format. For example:write_rich_string()
method allows you to do this by using the last argument as a cell format (if it is a format object). The following example centers a rich string in the cell:rich_strings.pl
example in the distro for more examples.write_sting()
the maximum string size is 32767 characters. See also the note about keep_leading_zeros()This method changes the default handling of integers with leading zeros when using the write()
method.
The write()
method uses regular expressions to determine what type of data to write to an Excel worksheet. If the data looks like a number it writes a number using write_number()
. One problem with this approach is that occasionally data looks like a number but you don't want it treated as a number.
Zip codes and ID numbers,for example,often start with a leading zero. If you write this data as a number then the leading zero(s) will be stripped. This is the also the default behavIoUr when you enter data manually in Excel.
To get around this you can use one of three options. Write a formatted number,write the number as a string or use the keep_leading_zeros()
method to change the default behavIoUr of write()
:
# Implicitly write a number,the leading zero is removed: 1209 '01209' ); # Write a zero padded number using a format: 01209 my '00000' ); $format1 ); # Write explicitly as a string: 01209 # Write implicitly as a string: 01209 keep_leading_zeros(); '01209' );
The above code would generate a worksheet that looked like the following:
----------------------------------------------------------- | | A | B | C | D | ... ----------------------------------------------------------- | 1 | 1209 | | | | ... | 2 | 01209 | | | | ... | 3 | 01209 | | | | ... | 4 | 01209 | | | | ...
The examples are on different sides of the cells due to the fact that Excel displays strings with a left justification and numbers with a right justification by default. You can change this by using a format to justify the data,153)" rel="nofollow">"CELL FORMATTING"
.A3
and A4
the strings will revert back to numbers. Again this is Excel's default behavIoUr. To avoid this you can use the text format @
:keep_leading_zeros()
property is off by default. The keep_leading_zeros()
method takes 0 or 1 as an argument. It defaults to 1 if an argument isn't specified:add_write_handler()
method.This method is used to add formatting to a cell which doesn't contain a string or number value.
Excel differentiates between an "Empty" cell and a "Blank" cell. An "Empty" cell is a cell which doesn't contain data whilst a "Blank" cell is a cell which doesn't contain data but does contain formatting. Excel stores "Blank" cells but ignores "Empty" cells.
As such,if you write an empty cell without formatting it is ignored:
undef, undef ); # Ignored
This seemingly uninteresting fact means that you can write arrays of data without special treatment for undef
or empty string values.
See the note about @array = ( 'awk',0)">'gawk',0)">'mawk' );
$array_ref = \@array;
write_row( $array_ref );
# The above example is equivalent to:
$array[0] );
1] );
2] );
Note: For convenience the As with all of the write methods the Array references within the data will be treated as columns. This allows you to write 2D arrays of data in one go. For example: Would produce a worksheet as follows: To write the data in a row-column order refer to the Any To find out more about array references refer to The See also the The As with all of the write methods the Array references within the data will be treated as rows. This allows you to write 2D arrays of data in one go. For example: To write the data in a column-row order refer to the Any As noted above the To find out more about array references refer to The See also the The This conforms to an ISO8601 date but it should be noted that the full range of ISO8601 formats are not supported. The following variations on the Note that the A date should always have a Valid dates should be in the range 1900-01-01 to 9999-12-31,for the 1900 epoch and 1904-01-01 to 9999-12-31,for the 1904 epoch. As with Excel,dates outside these ranges will be written as a string. See also the date_time.pl program in the Note,this behaviour is different from Spreadsheet::WriteExcel which provides a default hyperlink format if one isn't specified by the user. There are four web style URI's supported: You can display an alternative string using the If you wish to have some other cell data such as a number or a formula you can overwrite the cell using another call to There are two local URIs supported: All of the these URI types are recognised by the Worksheet references are typically of the form In external links the workbook and worksheet name must be separated by the You can also link to a named range in the target worksheet. For example say you have a named range called Excel requires that worksheet names containing spaces or non alphanumeric characters are single quoted as follows Links to network files are also supported. MS/Novell Network files normally begin with two back slashes as follows If you are using double quote strings then you should be careful to escape anything that looks like a Metacharacter. For more information see Finally,you can avoid most of these quoting problems by using forward slashes. These are translated internally to backslashes: Note: Excel::Writer::XLSX will escape the following characters in URLs as required by Excel: See also,the note about write_formula( '=$B$3 + B4' );
'=SIN(PI()/4)' );
'=SUM(B1:B5)' );
'=IF(A3>1,"Yes","No")' );
'=AVERAGE(1,2,3,4)' );
'=DATEVALUE("1-Jan-2001")' );
Array formulas are also supported: See also the See the note about "Cell notation". For more information about writing Excel formulas see "FORMULAS AND FUNCTIONS IN EXCEL" If required,it is also possible to specify the calculated value of the formula. This is occasionally necessary when working with non-Excel applications that don't calculate the value of the formula. The calculated However,this probably isn't something that you will ever need to do. If you do use this feature then do so with care. It this case however it is easier to just use the For array formulas that return a range of values you must specify the range that the return values will be written to: If required,B1:B3)}',255)">105 );
In addition,some early versions of Excel 2007 don't calculate the values of array formulas when they aren't supplied. Installing the latest Office Service Pack should fix this issue. See also the Note: Array formulas are not supported by Spreadsheet::WriteExcel. Deprecated. This is a Spreadsheet::WriteExcel method that is no longer required by Excel::Writer::XLSX. See below. As usual you can replace the The In addition to the basic 3 argument form of Most of these options are quite specific and in general the default comment behavIoUr will be all that you need. However,should you need greater control over the format of the cell comment the following options are available: This option is used to indicate who is the author of the cell comment. 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. The default author for all cell comments can be set using the This option is used to make a cell comment visible when the worksheet is opened. The default behavIoUr in Excel is that comments are initially hidden. However,it is also possible in Excel to make individual or all comments visible. In Excel::Writer::XLSX individual comments can be made visible as follows: It is possible to make all comments in a worksheet visible using the This option is used to set the width of the cell comment Box as a factor of the default width. This option is used to set the width of the cell comment Box explicitly in pixels. This option is used to set the height of the cell comment Box as a factor of the default height. This option is used to set the height of the cell comment Box explicitly in pixels. This option is used to set the background colour of cell comment Box. You can use one of the named colours recognised by Excel::Writer::XLSX or a colour index. See "COLOURS IN EXCEL". This option is used to set the cell in which the comment will appear. By default Excel displays comments one cell to the right and one cell above the cell to which the comment relates. However,you can change this behavIoUr if you wish. In the following example the comment which would appear by default in cell This option is used to set the row in which the comment will appear. See the This option is used to set the column in which the comment will appear. See the This option is used to change the x offset,in pixels,of a comment within a cell: This option is used to change the y offset,129)">write_comment(30);
You can apply as many of these options as you require. Note about using options that adjust the position of the cell comment such as start_cell,start_row,start_col,x_offset and y_offset: Excel only displays offset cell comments when they are displayed as "visible". Excel does not display hidden cells as moved when you mouse over them. Note about row height and comments. If you specify the height of a row that contains a comment then Excel::Writer::XLSX 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 the module at run time and thus the comment Box is stretched with the row. Use the This method is used to make all cell comments visible when a worksheet is opened. Individual comments can be made visible using the If all of the cell comments have been made visible you can hide individual comments as follows: This method is used to set the default author of all cell comments. Individual comment authors can be set using the The default comment author is an empty string, (In the these examples the The method is used as follows. say you wished to write 7 digit ID numbers as a string so that any leading zeros were preserved*,you could do something like the following: * You could also use the Then if you call The callback function will receive a reference to the calling worksheet and all of the other arguments that were passed to Your callback should So for example if you wished to apply the prevIoUs filter only to ID values that occur in the first column you could modify your callback function as follows: Now,you will get different behavIoUr for the first column and other columns: You may add more than one handler in which case they will be called in the order that they were added. Note,the See the The parameters The offsets can be greater than the width or height of the underlying cell. This can be occasionally useful if you wish to align two or more images relative to the same cell. The parameters Note: you must call BMP images must be 24 bit,true colour,bitmaps. In general it is best to avoid BMP images since they aren't compressed. See The The parameters The parameters See The The parameters See also the The properties of the button that can be set are: This option is used to set the macro that the button will invoke when the user clicks on it. The macro should be included using the Workbook The default macro is This option is used to set the caption on the button. The default is This option is used to set the width of the button in pixels. The default button width is 64 pixels which is the width of a default cell. This option is used to set the height of the button in pixels. The default button height is 20 pixels which is the height of a default cell. This option is used to set the width of the button as a factor of the default width. This option is used to set the height of the button as a factor of the default height. This option is used to change the x offset,of a button within a cell: This option is used to change the y offset,of a comment within a cell. Note: Button is the only Excel form element that is available in Excel::Writer::XLSX. Form elements represent a lot of work to implement and the underlying VML Syntax isn't very much fun. The This method contains a lot of parameters and is described in detail in a separate section "DATA VALIDATION IN EXCEL". See also the The This method contains a lot of parameters and is described in detail in a separate section "CONDITIONAL FORMATTING IN EXCEL". See also the The This method contains a lot of parameters and is described in detail in a separate section "SPARKLINES IN EXCEL". See also the Note: Sparklines are a feature of Excel 2010+ only. You can write them to an XLSX file that can be read by Excel 2007 but they won't be displayed. The This method contains a lot of parameters and is described in detail in a separate section "TABLES IN EXCEL". See also the The For reasons related to the design of Excel::Writer::XLSX and to the internals of Excel there is no The This is similar to the Excel VBA activate method. More than one worksheet can be selected via the The default active worksheet is the first worksheet. The A selected worksheet has its tab highlighted. Selecting worksheets is a way of grouping them together so that,several worksheets could be printed in one go. A worksheet that has been activated via the The You may wish to hide a worksheet in order to avoid confusing a user with intermediate data or calculations. A hidden worksheet can not be activated or selected so this method is mutually exclusive with the The This method is not required very often. The default value is the first worksheet. The See the You can optionally add a password to the worksheet protection: Passing the empty string Note,the worksheet level password in Excel provides very weak protection. It does not encrypt your data and is very easy to deactivate. Full workbook encryption is not supported by You can specify which worksheet elements you wish to protect by passing a hash_ref with any or all of the following keys: The default boolean values are shown above. Individual elements can be protected as follows: Examples: The default cell selections is (0,0),'A1'. If you wish to set the format without changing the height you can pass The If you wish to define a row format in this way you should call the method before any calls to The The The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed): The For collapsed outlines you should also indicate which row has the collapsed For a more complete example see the Excel allows up to 7 outline levels. Therefore the The 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 Calibri 11. Unfortunately,there is no way to specify "AutoFit" for a column in the Excel file format. This feature is only available at runtime from within Excel. As usual the write()
method behaves in the same way as write_row()
if it is passed an array reference. Therefore the following two method calls are equivalent:write_row( $array_ref ); # Write a row of data
$worksheet->write( @H_285_3016@# Same thing
$format
parameter is optional. If a format is specified it is applied to all the elements of the data array.@eec = (
['maggie',0)">'milly',0)">'molly',0)">'may' ],
[13, 14, 15,255)">16 ],
['shell',0)">'star',0)">'crab',0)">'stone']
);
@eec );
-----------------------------------------------------------
| | A | B | C | D | E | ...
-----------------------------------------------------------
| 1 | maggie | 13 | shell | ... | ... | ...
| 2 | milly | 14 | star | ... | ... | ...
| 3 | molly | 15 | crab | ... | ... | ...
| 4 | may | 16 | stone | ... | ... | ...
| 5 | ... | ... | ... | ... | ... | ...
| 6 | ... | ... | ... | ... | ... | ...
write_col()
method below.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.perlref
and perlreftut
in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to perllol
.write_row()
method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the write()
method above.write_arrays.pl
program in the examples
directory of the distro.write_row()
method allows the following idiomatic conversion of a text file to an Excel file:#!/usr/bin/perl -w
use strict;
use Excel::Writer::XLSX;
my 'file.xlsx' );
my add_worksheet();
open INPUT,0)">'file.txt' or die "Couldn't open file: $!";
$worksheet->write( $. -[split] ) while <INPUT>;
write_col( 2] );
$format
parameter is optional. If a format is specified it is applied to all the elements of the data array.write_col( 1 | maggie | milly | molly | may | ... | ...
| 2 | 13 | 14 | 15 | 16 | ... | ...
| 3 | shell | star | crab | stone | ... | ...
| 4 | ... | ... | ... | ... | ... | ...
| 6 | ... | ... | ... | ... | ... | ...
write_row()
method above.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.write()
method can be used as a synonym for write_row()
and write_row()
handles nested array refs as columns. Therefore,the following two method calls are equivalent although the more explicit call to write_col()
would be preferable for maintainability:$array_ref ); # Write a column of data
[ $array_ref ] ); # Same thing
perlref
and perlreftut
in the main Perl documentation. To find out more about 2D arrays or "lists of lists" refer to perllol
.write_col()
method returns the first error encountered when writing the elements of the data or zero if no errors were encountered. See the return values described for the write()
method above.write_arrays.pl
program in the examples
directory of the distro.write_date_time( '2004-05-13T23:20',102); font-weight:bold">$date_format );
$date_string
should be in the following format: yyyy-mm-ddThh:mm:ss.sss
$date_string
parameter are permitted: yyyy-mm-ddThh:mm:ss.sss # Standard format
yyyy-mm-ddT # No time
Thh:mm:ss.sss # No date
yyyy-mm-ddThh:mm:ss.sssZ # Additional Z (but not time zones)
yyyy-mm-ddThh:mm:ss # No fractional seconds
yyyy-mm-ddThh:mm # No seconds
T
is required in all cases.$format
,otherwise it will appear as a number,see "DATES AND TIME IN EXCEL" and "CELL FORMATTING". Here is a typical example:$date_format = 'mm/dd/yy' );
$date_format );
examples
directory of the distro.add_format( color => 'blue', underline => 1 );
http://
, https://
, ftp://
and mailto:
:write_url( 'ftp://www.perl.org/', write_url( 'mailto:jmcnamara@cpan.org',102); font-weight:bold">$format );
$label
parameter:'Perl' );
write_*()
:' );
# Overwrite the URL string with a formula. The cell is still a link.
write_formula( '=1+1',102); font-weight:bold">$format );
internal:
and external:
. These are used for hyperlinks to internal worksheet references or external workbook and worksheet references:'A6',0)">'internal:Sheet2!A1', 'A8',0)">'internal:Sheet2!A1:B2', q{internal:'Sales Data'!A1},0)">'external:c:\temp\foo.xlsx',0)">'external:c:\foo.xlsx#Sheet2!A1', 'external:..\foo.xlsx', 'external:..\foo.xlsx#Sheet2!A1',0)">'external:\\\\NET\share\foo.xlsx',102); font-weight:bold">$format );
write()
method,see above.Sheet1!A1
. You can also refer to a worksheet range using the standard Excel notation: Sheet1!A1:B2
.#
character: external:Workbook.xlsx#Sheet1!A1'
.my_name
in the workbook c:\temp\foo.xlsx
you could link to it as follows:'external:c:\temp\foo.xlsx#my_name' );
'Sales Data'!A1
. If you need to do this in a single quoted string then you can either escape the single quotes \'
or use the quote operator q{}
as described in perlop
in the main Perl documentation.\\NETWORK\etc
. In order to generate this in a single or double quoted string you will have to escape the backslashes, '\\\\NETWORK\etc'
.perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?
."external:c:/temp/foo.xlsx" );
'external://NETWORK/share/foo.xlsx' );
\s " < > \ [ ] ` ^ { }
unless the URL already contains %xx
style escapes. In which case it is assumed that the URL was escaped correctly by the user and will by passed directly to Excel.'{=SUM(A1:B1*A2:B2)}' );
write_array_formula()
method below.$value
is added at the end of the argument list:'=2+2',255)">4 );
write_array_formula('A1:A1',0)">'{=SUM(B1:C1*B2:C2)}');
write_formula()
or write()
methods:# Same as above but more concise.
'{=SUM(B1:C1*B2:C2)}' );
'{=SUM(B1:C1*B2:C2)}' );
write_array_formula( 'A1:A3', '{=TREND(C1:C3,B1:B3)}' );
write_array_formula( );
array_formula.pl
program in the examples
directory of the distro.store_formula( $formula )
$worksheet->write ( 'Hello' );
write_comment( 'This is a comment.' );
$row
and $column
parameters with an A1
cell reference. See the note about "Cell notation".$worksheet->write ( 'C3',0)">'Hello');
write_comment( 'This is a comment.' );
write_comment()
method will also handle strings in UTF-8
format."\x{263a}" ); # Smiley
'C4',0)">'Comment ca va?' );
write_comment()
you can pass in several optional key/value pairs to control the format of the comment. For example:=> => 'Perl' );
author
visible
x_scale
width
y_scale
height
color
start_cell
start_row
start_col
x_offset
y_offset
'Atonement',0)">'Ian McEwan' );
set_comments_author()
method (see below).set_comments_author( 'Perl' );
1 );
show_comments()
worksheet method (see below). Alternatively,if all of the cell comments have been made visible you can hide individual comments:0 );
=> 2 );
4.2 );
=> 200 );
=> 4.2 );
=> 200 );
=> 'green' );
=> 0x35 ); # Orange
D2
is moved to E2
.=> 'E2' );
start_cell
option above. The row is zero indexed.=> 0 );
start_cell
option above. The column is zero indexed.=> 4 );
$comment, x_offset => 30 );
set_row()
method to specify the row height explicitly and avoid this problem.show_comments()
show_comments();
visible
parameter of the write_comment
method (see above):1 );
show_comments();
0 );
set_comments_author()
'Perl' );
author
parameter of the write_comment
method (see above).''
,if no author is specified.add_write_handler( qr/^\d\d\d\d$/, \&my_write );
qr
operator is used to quote the regular expression strings,see perlop for more details)./^\d{7}$/, \&write_my_id );
sub write_my_id {
my $worksheet = shift;
return write_string( @_ );
}
keep_leading_zeros()
method for this.write()
with an appropriate string it will be handled automatically:# Writes 0000000. It would normally be written as a number; 0.
'0000000' );
write()
. The callback will see an @_
argument list that looks like the following:$_[0] A ref to the calling worksheet. *
1] Zero based row number.
2] Zero based column number.
3] A number or string or token.
4] A format ref if any.
5] Any other arguments.
...
* It is good style to shift this off the list so the @_ is the same
as the argument list seen by write().
return()
the return value of the write_*
method that was called or undef
to indicate that you rejected the match and want write()
to continue as normal. sub write_my_id {
my $worksheet = shift;
my $col = 1];
if ( $col == 0 ) {
return @_ );
}
else {
# Reject the match and return control to write()
return undef;
}
}
'0000000' ); # Writes 0000000
'B1',131); font-style:italic"># Writes 0
add_write_handler()
method is particularly suited for handling dates.write_handler 1-4
programs in the examples
directory for further examples.$worksheet1->insert_image( 'perl.bmp' );
$worksheet2->'../images/perl.bmp' );
$worksheet3->'.c:\images\perl.bmp' );
$x
and $y
can be used to specify an offset from the top left hand corner of the cell specified by $row
and $col
. The offset values are in pixels.insert_image('perl.bmp',255)">32,255)">10);
$x_scale
and $y_scale
can be used to scale the inserted image horizontally and vertically:# Scale the inserted image: width x 2.0,height x 0.8
0.8 );
set_row()
or set_column()
before insert_image()
if you wish to change the default dimensions of any of the rows or columns that the image occupies. The height of a row can also change if you use a font that is larger than the default. This in turn will affect the scaling of your image. To avoid this you should explicitly set the height of the row using set_row()
if it contains a font size that will change the row height.$chart );
add_chart()
for details on how to create the Chart object and Excel::Writer::XLSX::Chart for details on how to configure it. See also the chart_*.pl
programs in the examples directory of the distro.$x
, $x_scale
and $y_scale
parameters are optional.$x
and $y
can be used to specify an offset from the top left hand corner of the cell specified by $row
and $col
. The offset values are in pixels.$chart,255)">3 );
$x_scale
and $y_scale
can be used to scale the inserted chart horizontally and vertically:# Scale the width by 120% and the height by 150%
1.2,255)">1.5 );
$shape = add_shape( name => 'My Shape', type => 'plus' );
# Configure the shape.
$shape->set_text('foo');
...
# Insert the shape into the a worksheet.
insert_shape( $shape );
add_shape()
for details on how to create the Shape object and Excel::Writer::XLSX::Shape for details on how to configure it.$x
,255)">3 );
$x_scale
and $y_scale
can be used to scale the inserted shape horizontally and vertically:$shape,255)">1.5 );
shape*.pl
programs in the examples directory of the distro.'file.xlsm' );
...
'./vbaProject.bin' );
'my_macro' } );
macro
caption
width
height
x_scale
y_scale
x_offset
y_offset
add_vba_project()
method shown above.'my_macro' } );
ButtonX_Click
where X is the button number.Button X
where X is the button number.'my_macro', caption => 'Hello' } );
128 } );
40 } );
2.0 );
2.0 );
2 );
data_validation()
data_validation()
method is used to construct an Excel data validation or to limit the user input to a dropdown list of values.data_validation('B3',
{
validate => 'integer',
criteria => => 100,
});
'B5:B9',0)">'list',
value => ['open',0)">'high',0)">'close'],
});
data_validate.pl
program in the examples directory of the distroconditional_formatting()
conditional_formatting()
method is used to add formatting to a cell or range of cells based on user defined criteria.conditional_formatting( 'A1:J10',
{
type => 'cell',0)">'>=',255)">50,
format => $format1,
}
);
conditional_format.pl
program in the examples directory of the distroadd_sparkline()
add_sparkline()
worksheet method is used to add sparklines to a cell or a range of cells.add_sparkline(
{
location => 'F2',
range => 'Sheet1!A2:E2',
type => 'column',
style => }
);
sparklines1.pl
and sparklines2.pl
example programs in the examples
directory of the distro.add_table()
add_table()
method is used to group a range of cells into an Excel Table.add_table( 'B3:F7', { ... } );
tables.pl
program in the examples directory of the distroget_name()
get_name()
method is used to retrieve the name of a worksheet. For example:$sheet ( $sheet->get_name();
}
set_name()
method. The only way to set the worksheet name is via the add_worksheet()
method.activate()
activate()
method is used to specify which worksheet is initially visible in a multi-sheet workbook:'To' );
'the' );
'wind' );
activate();
select()
method,see below,however only one worksheet can be active.select()
select()
method is used to indicate that a worksheet is selected in a multi-sheet workbook:activate();
$worksheet2->select();
$worksheet3->select();
activate()
method will also appear as selected.hide()
hide()
method is used to hide a worksheet:hide();
activate()
and 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:hide();
set_first_sheet()
activate()
method determines which worksheet is initially selected. However,if there are a large number of worksheets the selected worksheet may not appear on the screen. To avoid this you can select which is the leftmost visible worksheet using set_first_sheet()
: for ( 1 .. 20 ) {
$workbook->add_worksheet;
}
$worksheet21 = $worksheet22 = $worksheet21->set_first_sheet();
$worksheet22->activate();
protect();
protect()
method also has the effect of enabling a cell's locked
and hidden
properties if they have been set. A locked cell cannot be edited and this property is on by default for all cells. A hidden cell will display the results of a formula but not the formula itself.protection.pl
program in the examples directory of the distro for an illustrative example and the set_locked
and set_hidden
format methods in "CELL FORMATTING".protect( 'drowssap' );
''
is the same as turning on protection without a password.Excel::Writer::XLSX
since it requires a completely different file format and would take several man months to implement.# Default shown.
%options = (
objects => => => => => => => => => => => sort => => => => );
'drowssap', { insert_rows => 1 } );
"Cell notation".
set_selection( 3 ); # 1. Cell D4.
6 ); # 2. Cells D4 to G7.
3 ); # 3. Cells G7 to D4.
$worksheet4->set_selection( 'D4' ); # Same as 1.
$worksheet5->'D4:G7' ); # Same as 2.
$worksheet6->'G7:D4' ); # Same as 3.
set_row( 20 ); # Row 1 height set to 20
undef
as the height parameter:$format );
$format
parameter will be applied to any cells in the row that don't have a format. For example$format1 ); # Set the format for row 1
'Hello' ); # Defaults to $format1
$format2 ); # Keeps $format2
write()
. Calling it afterwards will overwrite any format that was previously specified.$hidden
parameter should be set to 1 if you wish to hide a row. This can be used,to hide intermediary steps in a complicated calculation:20, 1 );
1 );
$level
parameter is used to set the outline level of the row. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent rows with the same outline level are grouped together into a single outline.1 );
$hidden
parameter can also be used to hide collapsed outlined rows when used in conjunction with the $level
parameter.1 );
+
symbol using the optional $collapsed
parameter.1 );
outline.pl
and outline_collapsed.pl
programs in the examples directory of the distro.$level
parameter should be in the range 0 <= $level <= 7
.set_column( # Column A width set to 20
30 ); # Columns B-D width set to 30
set_column( 'E:E',255)">20 ); # Column E width set to 20
'F:H',255)">30 ); # Columns F-H width set to 30
$format
parameter is optional,for additional information,153)" rel="nofollow">"CELL FORMATTING"undef
as the width parameter:
$format );
The $format
parameter will be applied to any cells in the column that don't have a format. For example
'A:A',131); font-style:italic"># Set format for col 1 'Hello' ); $format2 ); # Keeps $format2
If you wish to define a column format in this way you should call the method before any calls to write()
. If you call it afterwards it won't have any effect.
A default row format takes precedence over a default column format
$format1 ); # Set format for row 1 $format2 ); # Defaults to $format2
The $hidden
parameter should be set to 1 if you wish to hide a column. This can be used,0)">'D:D',255)">1 );
The $level
parameter is used to set the outline level of the column. Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent columns with the same outline level are grouped together into a single outline.
The following example sets an outline level of 1 for columns B to G:
'B:G',255)">1 );
The $hidden
parameter can also be used to hide collapsed outlined columns when used in conjunction with the $level
parameter.
'H:H',153); font-size:14px">set_default_row( 24 ); # Set the default row height to 24.
The option to hide unused rows is used by Excel as an optimisation so that the user can hide a large number of rows without generating a very large file with an entry for each hidden row.
set_default_row( undef,255)">1 );
See the hide_row_col.pl
example program.
"OUTLINES AND GROUPING IN EXCEL".
The $visible
parameter is used to control whether or not outlines are visible. Setting this parameter to 0 will cause all outlines on the worksheet to be hidden. They can be unhidden in Excel by means of the "Show Outline Symbols" command button. The default setting is 1 for visible outlines.
outline_settings( 0 );
The $symbols_below
parameter is used to control whether the row outline symbol will appear above or below the outline level bar. The default setting is 1 for symbols to appear below the outline level bar.
The $symbols_right
parameter is used to control whether the column outline symbol will appear to the left or the right of the outline level bar. The default setting is 1 for symbols to appear to the right of the outline level bar.
The $auto_style
parameter is used to control whether the automatic outline generator in Excel uses automatic styles when creating an outline. This has no effect on a file generated by Excel::Writer::XLSX
but it does have an effect on how the worksheet behaves after it is created. The default setting is 0 for "Automatic Styles" to be turned off.
The default settings for all of these parameters correspond to Excel's default parameters.
The worksheet parameters controlled by outline_settings()
are rarely used.
Window->Freeze Panes menu command in Excel
The parameters $row
and $col
are used to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. Therefore to freeze the first row of a worksheet it is necessary to specify the split at row 2 (which is 1 as the zero-based index). This might lead you to think that you are using a 1 based index but this is not the case.
You can set one of the $row
and $col
parameters as zero if you do not want either a vertical or horizontal split.
Examples:
freeze_panes( # Freeze the first row
freeze_panes( 'A2' ); # Same using A1 notation
# Freeze the first column
'B1' ); # Freeze first row and first 2 columns
# Same using A1 notation
The parameters $top_row
and $left_col
are optional. They are used to specify the top-most or left-most visible row or column in the scrolling region of the panes. For example to freeze the first row and to have the scrolling region begin at row twenty:
0 );
You cannot use A1 notation for the $top_row
and $left_col
parameters.
See also the panes.pl
program in the examples
directory of the distribution.
split_panes( ); # First row
8.43 ); # First column
# First row and column
You cannot use A1 notation with this method.
See also the freeze_panes()
method and the panes.pl
program in the examples
directory of the distribution.
add_format(
border => => 'vcenter',
align => 'center',
);
merge_range( 'B3:D4',0)">'Vertical and horizontal',102); font-weight:bold">$format );
merge_range()
writes its $token
argument using the worksheet write()
method. Therefore it will handle numbers,strings,formulas or urls as required. If you need to specify the required write_*()
method use the merge_range_type()
method,see below.
The full possibilities of this method are shown in the merge3.pl
to merge6.pl
programs in the examples
directory of the distribution.
required data into to a merged range. However,there may be times where this isn't what you require so as an alternative the merge_range_type ()
method allows you to specify the type of data you wish to write. For example:
merge_range_type( 'number',0)">'B2:C2',255)">123,102); font-weight:bold">$format1 );
'string',0)">'B4:C4',0)">'foo',102); font-weight:bold">$format2 );
'formula',0)">'B6:C6',0)">'=1+2',102); font-weight:bold">$format3 );
The $type
must be one of the following,which corresponds to a write_*()
method:
'number'
'string'
'formula'
'array_formula'
'blank'
'rich_string'
'date_time'
'url'
Any arguments after the range should be whatever the appropriate method accepts:
'rich_string',0)">'B8:C8',
$format4 );
Note,you must always pass a $format
object as an argument,even if it is a default format.
set_zoom( $scale )
Set the worksheet zoom factor in the range 10 <= $scale <= 400
:
set_zoom( 50 );
75 );
300 );
400 );
The default zoom factor is 100. You cannot zoom to "Selection" because it is calculated by Excel at run-time.
Note, set_zoom()
does not affect the scale of the printed page. For that you should use set_print_scale()
.
right_to_left()
The right_to_left()
method is used to change the default direction of the worksheet from left-to-right,with the A1 cell in the top left,to right-to-left,with the A1 cell in the top right.
right_to_left();
This is useful when creating Arabic,Hebrew or other near or far eastern worksheets that use right-to-left as the default direction.
hide_zero()
The hide_zero()
method is used to hide any zero values that appear in cells.
hide_zero();
In Excel this option is found under Tools->Options->View.
set_tab_color()
The set_tab_color()
method is used to change the colour of the worksheet tab. You can use one of the standard colour names provided by the Format object or a colour index. See "COLOURS IN EXCEL" and the set_custom_color()
method.
set_tab_color( set_tab_color( 0x0C );
See the tab_colors.pl
program in the examples directory of the distro.
autofilter( 10,255)">3 );
autofilter( 'A1:D11' ); # Same as above in A1 notation.
Filter conditions can be applied using the filter_column()
or filter_column_list()
method.
See the autofilter.pl
program in the examples directory of the distro for a more detailed example.
This parameter is passed in a hash ref to data_validation()
.
The 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'.
error_title => 'Input value is not valid',153); font-size:14px">error_message
This parameter is passed in a hash ref to data_validation()
.
The 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.".
=> => 'It should be an integer between 1 and 100',153); font-size:14px">error_type
This parameter is passed in a hash ref to data_validation()
.
The error_type
parameter is used to specify the type of error dialog that is displayed. There are 3 options:
'stop'
'warning'
'information'
The default is 'stop'
.
show_error
This parameter is passed in a hash ref to data_validation()
.
The 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 error_message
. It is on by default.
show_error => Data Validation Examples
Example 1. Limiting input to an integer greater than a fixed value.
=> });
Example 2. Limiting input to an integer greater than a fixed value where the value is referenced from a cell.
=> '=E3',
});
Example 3. Limiting input to a decimal in a fixed range.
0.1,
});
Example 4. Limiting input to a value in a dropdown list.
=> [});
Example 5. Limiting input to a value in a dropdown list where the list is specified as a cell range.
=> '=$E$4:$G$4',
});
Example 6. Limiting input to a date in a fixed range.
=> '2008-01-01T',
maximum => '2008-12-12T',
});
Example 7. Displaying a message when the cell is selected.
{
validate => => => => => 'Enter an integer:',
input_message => });
See also the data_validate.pl
program in the examples directory of the distro.
CONDITIONAL FORMATTING IN EXCEL 
Conditional formatting is a feature of Excel which allows you to apply a format to a cell or a range of cells based on a certain criteria.
For example the following criteria is used to highlight cells >= 50 in red in the conditional_format.pl
example from the distro:
# Write a conditional format over a range.
'B3:K12',
}
);

conditional_formatting( "Cell notation" for more information.
Using A1
style notation is is also possible to specify non-contiguous ranges,separated by a comma. For example:
'A1:D5,A8:D12', {...} );
The last parameter in conditional_formatting()
must be a hash ref containing the parameters that describe the type and style of the data validation. The main parameters are:
type
format
criteria
value
minimum
maximum
Other,less commonly used parameters are:
min_type
mid_type
max_type
min_value
mid_value
max_value
min_color
mid_color
max_color
bar_color
Additional parameters which are used for specific conditional format types are shown in the relevant sections below.
type
This parameter is passed in a hash ref to conditional_formatting()
.
The type
parameter is used to set the type of conditional formatting that you wish to apply. It is always required and it has no default value. Allowable type
values and their associated parameters are:
Type Parameters
==== ==========
cell criteria
value
minimum
maximum
date criteria
value
minimum
maximum
time_period criteria
text criteria
value
average criteria
duplicate (none)
unique (none)
top criteria
value
bottom criteria
value
blanks (none)
no_blanks (none)
errors (none)
no_errors (none)
2_color_scale (none)
3_color_scale (none)
data_bar (none)
formula criteria
All conditional formatting types have a format
parameter,see below. Other types and parameters such as icon sets will be added in time.
type => 'cell'
This is the most common conditional formatting type. It is used when a format is applied to a cell based on a simple criterion. For example:
$red_format,
}
);
Or,using the between
criteria:
'C1:C4',
minimum => => 30,102); font-weight:bold">$green_format,
}
);
criteria
$row
and $col
are used to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. Therefore to freeze the first row of a worksheet it is necessary to specify the split at row 2 (which is 1 as the zero-based index). This might lead you to think that you are using a 1 based index but this is not the case.$row
and $col
parameters as zero if you do not want either a vertical or horizontal split.$top_row
and $left_col
are optional. They are used to specify the top-most or left-most visible row or column in the scrolling region of the panes. For example to freeze the first row and to have the scrolling region begin at row twenty:$top_row
and $left_col
parameters.panes.pl
program in the examples
directory of the distribution.You cannot use A1 notation with this method.
See also the freeze_panes()
method and the panes.pl
program in the examples
directory of the distribution.
add_format(
border => => 'vcenter',
align => 'center',
);
merge_range( 'B3:D4',0)">'Vertical and horizontal',102); font-weight:bold">$format );
merge_range()
writes its $token
argument using the worksheet write()
method. Therefore it will handle numbers,strings,formulas or urls as required. If you need to specify the required write_*()
method use the merge_range_type()
method,see below.
The full possibilities of this method are shown in the merge3.pl
to merge6.pl
programs in the examples
directory of the distribution.
required data into to a merged range. However,there may be times where this isn't what you require so as an alternative the merge_range_type ()
method allows you to specify the type of data you wish to write. For example:
merge_range_type( 'number',0)">'B2:C2',255)">123,102); font-weight:bold">$format1 );
'string',0)">'B4:C4',0)">'foo',102); font-weight:bold">$format2 );
'formula',0)">'B6:C6',0)">'=1+2',102); font-weight:bold">$format3 );
The $type
must be one of the following,which corresponds to a write_*()
method:
'number'
'string'
'formula'
'array_formula'
'blank'
'rich_string'
'date_time'
'url'
Any arguments after the range should be whatever the appropriate method accepts:
'rich_string',0)">'B8:C8',
$format4 );
Note,you must always pass a $format
object as an argument,even if it is a default format.
set_zoom( $scale )
Set the worksheet zoom factor in the range 10 <= $scale <= 400
:
set_zoom( 50 );
75 );
300 );
400 );
The default zoom factor is 100. You cannot zoom to "Selection" because it is calculated by Excel at run-time.
Note, set_zoom()
does not affect the scale of the printed page. For that you should use set_print_scale()
.
right_to_left()
The right_to_left()
method is used to change the default direction of the worksheet from left-to-right,with the A1 cell in the top left,to right-to-left,with the A1 cell in the top right.
right_to_left();
This is useful when creating Arabic,Hebrew or other near or far eastern worksheets that use right-to-left as the default direction.
hide_zero()
The hide_zero()
method is used to hide any zero values that appear in cells.
hide_zero();
In Excel this option is found under Tools->Options->View.
set_tab_color()
The set_tab_color()
method is used to change the colour of the worksheet tab. You can use one of the standard colour names provided by the Format object or a colour index. See "COLOURS IN EXCEL" and the set_custom_color()
method.
set_tab_color( set_tab_color( 0x0C );
See the tab_colors.pl
program in the examples directory of the distro.
autofilter( 10,255)">3 );
autofilter( 'A1:D11' ); # Same as above in A1 notation.
Filter conditions can be applied using the filter_column()
or filter_column_list()
method.
See the autofilter.pl
program in the examples directory of the distro for a more detailed example.
This parameter is passed in a hash ref to data_validation()
.
The 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'.
error_title => 'Input value is not valid',153); font-size:14px">error_message
This parameter is passed in a hash ref to data_validation()
.
The 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.".
=> => 'It should be an integer between 1 and 100',153); font-size:14px">error_type
merge_range()
writes its $token
argument using the worksheet write()
method. Therefore it will handle numbers,strings,formulas or urls as required. If you need to specify the required write_*()
method use the merge_range_type()
method,see below.merge3.pl
to merge6.pl
programs in the examples
directory of the distribution.merge_range_type ()
method allows you to specify the type of data you wish to write. For example:
merge_range_type( 'number',0)">'B2:C2',255)">123,102); font-weight:bold">$format1 ); 'string',0)">'B4:C4',0)">'foo',102); font-weight:bold">$format2 ); 'formula',0)">'B6:C6',0)">'=1+2',102); font-weight:bold">$format3 );
$type
must be one of the following,which corresponds to a write_*()
method:$format
object as an argument,even if it is a default format.10 <= $scale <= 400
:set_zoom()
does not affect the scale of the printed page. For that you should use set_print_scale()
.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 A1 cell in the top right.hide_zero()
method is used to hide any zero values that appear in cells.set_tab_color()
method is used to change the colour of the worksheet tab. You can use one of the standard colour names provided by the Format object or a colour index. See "COLOURS IN EXCEL" and the set_custom_color()
method.tab_colors.pl
program in the examples directory of the distro.Filter conditions can be applied using the filter_column()
or filter_column_list()
method.
See the autofilter.pl
program in the examples directory of the distro for a more detailed example.
This parameter is passed in a hash ref to data_validation()
.
The 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'.
error_title => 'Input value is not valid',153); font-size:14px">error_message
data_validation()
.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.".This parameter is passed in a hash ref to data_validation()
.
The error_type
parameter is used to specify the type of error dialog that is displayed. There are 3 options:
'stop' 'warning' 'information'
The default is 'stop'
.
show_error
This parameter is passed in a hash ref to data_validation()
.
The 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 error_message
. It is on by default.
show_error => Data Validation Examples
data_validate.pl
program in the examples directory of the distro.conditional_format.pl
example from the distro:A1
style notation is is also possible to specify non-contiguous ranges,separated by a comma. For example:conditional_formatting()
must be a hash ref containing the parameters that describe the type and style of the data validation. The main parameters are:conditional_formatting()
.type
parameter is used to set the type of conditional formatting that you wish to apply. It is always required and it has no default value. Allowable type
values and their associated parameters are:format
parameter,see below. Other types and parameters such as icon sets will be added in time.between
criteria:The criteria
parameter is used to set the criteria by which the cell data will be evaluated. It has no default value. The most common criteria as applied to { type => 'cell' }
are:
value
value
is generally used along with the criteria
parameter to set the rule by which the cell data will be evaluated.The format
parameter is used to specify the format that will be applied to the cell when the conditional formatting criterion is met. The format is created using the add_format()
method in the same way as cell formats:
=> 5 format => } );
The conditional format follows the same rules as in Excel: it is superimposed over the existing cell format and not all font and border properties can be modified. Font properties that can't be modified are font name,font size,superscript and subscript. The border property that cannot be modified is diagonal borders.
Excel specifies some default formats to be used with conditional formatting. You can replicate them using the following Excel::Writer::XLSX formats:
# Light red fill with dark red text. my add_format( bg_color => '#FFC7CE', color => '#9C0006', ); # Light yellow fill with dark yellow text. my '#FFEB9C',0)">'#9C6500',131); font-style:italic"># Green fill with dark green text. my '#C6EFCE',0)">'#006100',153); font-size:14px">minimum
minimum
parameter is used to set the lower limiting value when the criteria
is either 'between'
or 'not between'
:The maximum
parameter is used to set the upper limiting value when the criteria
is either 'between'
or 'not between'
. See the prevIoUs example.
type => 'date'
The date
type is the same as the cell
type and uses the same criteria and values. However it allows the value
, minimum
and maximum
properties to be specified in the ISO8601 yyyy-mm-ddThh:mm:ss.sss
date format which is detailed in the write_date_time()
method.
'A1:A4', value => '2011-01-01T',153); font-size:14px">type => 'time_period'The
time_period
type is used to specify Excel's "Dates Occurring" style conditional format.'time_period',0)">'yesterday', } );
The period is set in the criteria
and can have one of the following values:
criteria => => 'today',0)">'last 7 days',0)">'last week',0)">'this week',0)">'next week',0)">'last month',0)">'this month',0)">'next month'
type => 'text'
The text
type is used to specify Excel's "Specific Text" style conditional format. It is used to do simple string matching using the criteria
and value
parameters:
'text',0)">'containing', } );
The criteria
can have one of the following values:
criteria => 'not containing',0)">'begins with',0)">'ends with',
The value
parameter should be a string or single character.
type => 'average'
The average
type is used to specify Excel's "Average" style conditional format.
'average',0)">'above', } );
The type of average for the conditional format range is specified by the criteria
:
'below',0)">'equal or above',0)">'equal or below',0)">'1 std dev above',0)">'1 std dev below',0)">'2 std dev above',0)">'2 std dev below',0)">'3 std dev above',0)">'3 std dev below',153); font-size:14px">type => 'duplicate'The
duplicate
type is used to highlight duplicate cells in a range:'duplicate',153); font-size:14px">type => 'unique'The
unique
type is used to highlight unique cells in a range:'unique',153); font-size:14px">type => 'top'The
top
type is used to specify the topn
values by number or percentage in a range:'top', } );
The criteria
can be used to indicate that a percentage condition is required:
'%',153); font-size:14px">type => 'bottom'The
bottom
type is used to specify the bottomn
values by number or percentage in a range.It takes the same parameters as
top
,153); font-size:14px">type => 'blanks'The
blanks
type is used to highlight blank cells in a range:'blanks',153); font-size:14px">type => 'no_blanks'The
no_blanks
type is used to highlight non blank cells in a range:'no_blanks',153); font-size:14px">type => 'errors'The
errors
type is used to highlight error cells in a range:'errors',153); font-size:14px">type => 'no_errors'The
no_errors
type is used to highlight non error cells in a range:'no_errors',153); font-size:14px">type => '2_color_scale'The
2_color_scale
type is used to specify Excel's "2 Color Scale" style conditional format.'A1:A12', { type => '2_color_scale', } );
This conditional type can be modified with min_type
, max_type
, min_value
, max_value
, min_color
and max_color
,see below.
type => '3_color_scale'
The 3_color_scale
type is used to specify Excel's "3 Color Scale" style conditional format.
'3_color_scale',mid_type
,mid_value
,min_color
,mid_color
andmax_color
,153); font-size:14px">type => 'data_bar'The
data_bar
type is used to specify Excel's "Data Bar" style conditional format.'data_bar',max_value
andbar_color
,153); font-size:14px">type => 'formula'The
formula
type is used to specify a conditional format based on a user defined formula:'=$A$1 > 5', } );
The formula is specified in the criteria
.
{
type => => 'percent',
max_type => }
);
The available min/mid/max types are:
num
percent
percentile
formula
{
type => => => 90,153); font-size:14px">=> "#C5D9F1",
max_color => "#538ED5",
}
);
The color can be specifies as an Excel::Writer::XLSX color index or,more usefully,as a HTML style RGB hex number,as shown above.
Conditional Formatting Examples
Example 1. Highlight cells greater than an integer value.
'A1:F10',
}
);
Example 2. Highlight cells greater than a value in a reference cell.
'$H$1',
}
);
Example 3. Highlight cells greater than a certain date:
}
);
Example 4. Highlight cells with a date in the last seven days:
}
);
Example 5. Highlight cells with strings starting with the letter b
:
'b',
}
);
Example 6. Highlight cells that are 1 std deviation above the average for the range:
}
);
Example 7. Highlight duplicate cells in a range:
}
);
Example 8. Highlight unique cells in a range.
}
);
Example 9. Highlight the top 10 cells.
}
);
Example 10. Highlight blank cells.
}
);
See also the conditional_format.pl
example program in EXAMPLES
.
SPARKLINES IN EXCEL 
Sparklines are a feature of Excel 2010+ which allows you to add small charts to worksheet cells. These are useful for showing visual trends in data in a compact format.
In Excel::Writer::XLSX Sparklines can be added to cells using the add_sparkline()
worksheet method:
}
);

Note: Sparklines are a feature of Excel 2010+ only. You can write them to an XLSX file that can be read by Excel 2007 but they won't be displayed.
location (required)
range (required)
type
style
markers
negative_points
axis
reverse
Other,136); padding:1em"> high_point
low_point
first_point
last_point
max
min
empty_cells
show_hidden
date_axis
weight
series_color
negative_color
markers_color
first_color
last_color
high_color
low_color
These parameters are explained in the sections below:
location
This is the cell where the sparkline will be displayed:
location => 'F1'
The location
should be a single cell. (For multiple cells see "Grouped Sparklines" below).
To specify the location in row-column notation use the xl_rowcol_to_cell()
function from the Excel::Writer::XLSX::Utility module.
use Excel::Writer::XLSX::Utility ':rowcol';
...
location => 5 ),131); font-style:italic"># F1
range
This specifies the cell data range that the sparkline will plot:
'F1',0)">'A1:E1',
}
);
The range
should be a 2D array. (For 3D arrays of cells see "Grouped Sparklines" below).
If range
is not on the same worksheet you can specify its location using the usual Excel notation:
range => 'Sheet1!A1:E1',
If the worksheet contains spaces or special characters you should quote the worksheet name in the same way that Excel does:
range => q('Monthly Data'!A1:E1),
To specify the location in row-column notation use the xl_range()
or xl_range_formula()
functions from the ':rowcol';
...
range => xl_range( 4 ), # 'A1:E1'
range => xl_range_formula( 'Sheet1',131); font-style:italic"># 'Sheet1!A2:E2'
type
Specifies the type of sparkline. There are 3 available sparkline types:
line (default)
column
win_loss
For example:
{
location => => => }
style
Excel provides 36 built-in Sparkline styles in 6 groups of 6. The style
parameter can be used to replicate these and should be a corresponding number from 1 .. 36.
'Sheet2!A2:J2',
style => }
The style number starts in the top left of the style grid and runs left to right. The default style is 1. It is possible to override colour elements of the sparklines using the *_color
parameters below.
markers
Turn on the markers for line
style sparklines.
'Sheet2!A1:J1',
markers => }
Markers aren't shown in Excel for column
and win_loss
sparklines.
@L_466_502@
Highlight negative values in a sparkline range. This is usually required with win_loss
sparklines.
{
location => 'A21',
range => 'Sheet2!A3:J3',
type => 'win_loss',
negative_points => axis
Display a horizontal axis in the sparkline:
=> reverse
The color can be specifies as an Excel::Writer::XLSX color index or,more usefully,as a HTML style RGB hex number,as shown above.
Conditional Formatting Examples
Example 1. Highlight cells greater than an integer value.
'A1:F10', } );
Example 2. Highlight cells greater than a value in a reference cell.
'$H$1', } );
Example 3. Highlight cells greater than a certain date:
}
);
Example 4. Highlight cells with a date in the last seven days:
}
);
Example 5. Highlight cells with strings starting with the letter b
:
'b', } );
Example 6. Highlight cells that are 1 std deviation above the average for the range:
}
);
Example 7. Highlight duplicate cells in a range:
}
);
Example 8. Highlight unique cells in a range.
}
);
Example 9. Highlight the top 10 cells.
}
);
Example 10. Highlight blank cells.
}
);
See also the conditional_format.pl
example program in EXAMPLES
.
SPARKLINES IN EXCEL 

Sparklines are a feature of Excel 2010+ which allows you to add small charts to worksheet cells. These are useful for showing visual trends in data in a compact format.
In Excel::Writer::XLSX Sparklines can be added to cells using the add_sparkline()
worksheet method:
}
);
Note: Sparklines are a feature of Excel 2010+ only. You can write them to an XLSX file that can be read by Excel 2007 but they won't be displayed.
location (required)
range (required)
type
style
markers
negative_points
axis
reverse
Other,136); padding:1em"> high_point
low_point
first_point
last_point
max
min
empty_cells
show_hidden
date_axis
weight
series_color
negative_color
markers_color
first_color
last_color
high_color
low_color
These parameters are explained in the sections below:
location
This is the cell where the sparkline will be displayed:
location => 'F1'
The location
should be a single cell. (For multiple cells see "Grouped Sparklines" below).
To specify the location in row-column notation use the xl_rowcol_to_cell()
function from the Excel::Writer::XLSX::Utility module.
use Excel::Writer::XLSX::Utility ':rowcol';
...
location => 5 ),131); font-style:italic"># F1
range
This specifies the cell data range that the sparkline will plot:
'F1',0)">'A1:E1',
}
);
The range
should be a 2D array. (For 3D arrays of cells see "Grouped Sparklines" below).
If range
is not on the same worksheet you can specify its location using the usual Excel notation:
range => 'Sheet1!A1:E1',
If the worksheet contains spaces or special characters you should quote the worksheet name in the same way that Excel does:
range => q('Monthly Data'!A1:E1),
To specify the location in row-column notation use the xl_range()
or xl_range_formula()
functions from the ':rowcol';
...
range => xl_range( 4 ), # 'A1:E1'
range => xl_range_formula( 'Sheet1',131); font-style:italic"># 'Sheet1!A2:E2'
type
location
should be a single cell. (For multiple cells see "Grouped Sparklines" below).xl_rowcol_to_cell()
function from the Excel::Writer::XLSX::Utility module.range
should be a 2D array. (For 3D arrays of cells see "Grouped Sparklines" below).range
is not on the same worksheet you can specify its location using the usual Excel notation:xl_range()
or xl_range_formula()
functions from the ':rowcol';
...
range => xl_range( 4 ), # 'A1:E1'
range => xl_range_formula( 'Sheet1',131); font-style:italic"># 'Sheet1!A2:E2'
type
Specifies the type of sparkline. There are 3 available sparkline types:
line (default) column win_loss
For example:
{ location => => => }
style
Excel provides 36 built-in Sparkline styles in 6 groups of 6. The style
parameter can be used to replicate these and should be a corresponding number from 1 .. 36.
'Sheet2!A2:J2', style => }
The style number starts in the top left of the style grid and runs left to right. The default style is 1. It is possible to override colour elements of the sparklines using the *_color
parameters below.
markers
Turn on the markers for line
style sparklines.
'Sheet2!A1:J1', markers => }
Markers aren't shown in Excel for column
and win_loss
sparklines.
@L_466_502@
Highlight negative values in a sparkline range. This is usually required with win_loss
sparklines.
{ location => 'A21', range => 'Sheet2!A3:J3', type => 'win_loss', negative_points => axis
Plot the data from right-to-left instead of the default left-to-right:
'A24',0)">'Sheet2!A4:J4', reverse => weightAdjust the default line weight (thickness) for
line
style sparklines.weight => 0.25,The weight value should be one of the following values allowed by Excel:
0.250.5 0.75 1 1.25 2.25 3 4.25 6
high_point => => => => max => => - max => 'group',
See "Grouped Sparklines" below.
empty_cells
Define how empty cells are handled in a sparkline.
empty_cells => 'zero',
The available options are:
gaps : show empty cells as gaps (the default).
zero : plot empty cells as 0.
connect: Connect points with a line ("line" type sparklines only).
show_hidden
Plot data in hidden rows and columns:
show_hidden => date_axis
Specify an alternative date axis for the sparkline. This is useful if the data being plotted isn't at fixed width intervals:
{ location => 'F3', range => 'A3:E3', date_axis => 'A4:E4', }
The number of cells in the date range should correspond to the number of cells in the data range.
series_color
It is possible to override the colour of a sparkline style using the following parameters:
series_color negative_color markers_color first_color last_color high_color low_color
The color should be specified as a HTML style #rrggbb
hex value:
{ location => => => => '#E965E0',153); font-size:14px">Grouped SparklinesThe
add_sparkline()
worksheet method can be used multiple times to write as many sparklines as are required in a worksheet.However,it is sometimes necessary to group contiguous sparklines so that changes that are applied to one are applied to all. In Excel this is achieved by selecting a 3D range of cells for the data
range
and a 2D range of cells for thelocation
.In Excel::Writer::XLSX,you can simulate this by passing an array refs of values to
location
andrange
:{ location => [ 'A27', 'A28',0)">'A29' ], range => [ 'Sheet2!A5:J5',0)">'Sheet2!A6:J6',0)">'Sheet2!A7:J7' ],153); font-size:14px">Sparkline examplesSee the
sparklines1.pl
andsparklines2.pl
example programs in theexamples
directory of the distro.TABLES IN EXCEL
Tables in Excel are a way of grouping a range of cells into a single entity that has common formatting or that can be referenced from formulas. Tables can have column headers,autofilters,total rows,column formulas and default formatting.
For more information see "An Overview of Excel Tables" http://office.microsoft.com/en-us/excel-help/overview-of-excel-tables-HA010048546.aspx.
Note,tables don't work in Excel::Writer::XLSX when
set_optimization()
mode in on.{
%parameters } );The data range can be specified in 'A1' or 'row/col' notation (see also the note about "Cell notation" for more information):
'B3:F7'); add_table( 5 );
The last parameter in add_table()
should be a hash ref containing the parameters that describe the table options and data. The available parameters are:
data autofilter header_row banded_columns banded_rows first_column last_column style total_row columns name
The table parameters are detailed below. There are no required parameters and the hash ref isn't required if no options are specified.
data
The data
parameter can be used to specify the data in the cells of the table.
$data = [ [ 'Apples',255)">10000,255)">5000,255)">8000,255)">6000 ], [ 'Pears',255)">2000,255)">3000,255)">4000,255)">5000 ],0)">'Bananas',255)">6000,255)">6500,0)">'Oranges',255)">500,255)">300,255)">200,255)">700 ], ]; { data => $data } );
Table data can also be written separately,as an array or individual cells.
# These two statements are the same as the single statement above. 'B3:F7' ); 'B4',102); font-weight:bold">$data );
Writing the cell data separately is occasionally required when you need to control the write_*()
method used to populate the cells or if you wish to tweak the cell formatting.
The data
structure should be an array ref of array refs holding row data as shown above.
header_row
The header_row
parameter can be used to turn on or off the header row in the table. It is on by default.
'B4:F7', { header_row => 0 } ); # Turn header off.
The header row will contain default captions such as Column 1
, Column 2
,etc. These captions can be overridden using the columns
parameter below.
autofilter
The autofilter
parameter can be used to turn on or off the autofilter in the header row. It is on by default.
{ autofilter => # Turn autofilter off.
The autofilter
is only shown if the header_row
is on. Filters within the table are not supported.
banded_rows
The banded_rows
parameter can be used to used to create rows of alternating colour in the table. It is on by default.
{ banded_rows => 0 } );
banded_columns
The banded_columns
parameter can be used to used to create columns of alternating colour in the table. It is off by default.
{ banded_columns => first_columnThe
first_column
parameter can be used to highlight the first column of the table. The type of highlighting will depend on thestyle
of the table. It may be bold text or a different colour. It is off by default.{first_column => last_columnThe
last_column
parameter can be used to highlight the last column of the table. The type of highlighting will depend on thestyle
of the table. It may be bold text or a different colour. It is off by default.{last_column => styleThe
style
parameter can be used to set the style of the table. Standard Excel table format names should be used (with matching capitalisation):$worksheet11->add_table( { data => $data, style => 'Table Style Light 11', } );
The default table style is 'Table Style Medium 9'.
name
The name
parameter can be used to set the name of the table.
By default tables are named Table1
, Table2
,etc. If you override the table name you must ensure that it doesn't clash with an existing table name and that it follows Excel's requirements for table names.
{ name => 'SalesData' } );
If you need to know the name of the table,for example to use it in a formula,you can get it as follows:
$table = 'B3:F7' ); my $table_name = $table->{_name};
total_row
The total_row
parameter can be used to turn on the total row in the last row of a table. It is distinguished from the other rows by a different formatting and also with dropdown SUBTOTAL
functions.
{ total_row => 1 } );
The default total row doesn't have any captions or functions. These must by specified via the columns
parameter below.
columns
The columns
parameter can be used to set properties for columns within the table.
The sub-properties that can be set are:
header
formula
total_string
total_function
format
The column data must be specified as an array ref of hash refs. For example to override the default 'Column n' style table headers:
{ data => => [ { header => 'Product' }, { header => 'Quarter 1' },0)">'Quarter 2' },0)">'Quarter 3' },0)">'Quarter 4' }, ] } );
If you don't wish to specify properties for a specific column you pass an empty hash ref and the defaults will be applied:
... columns => [ { header => { }, # Defaults to 'Column 3'. { header => ] ...
Column formulas can by applied using the formula
column property:
$worksheet8->'B3:G7', { header => 'Year', formula => '=SUM(Table8[@[Quarter 1]:[Quarter 4]])' }, ] } );
The Excel 2007 [#This Row]
and Excel 2010 @
structural references are supported within the formula.
As stated above the total_row
table parameter turns on the "Total" row in the table but it doesn't populate it with any defaults. Total captions and functions must be specified via the columns
property and the total_string
and total_function
sub properties:
$worksheet10->'B3:F8', total_row => => [ { header => 'Product', total_string => 'Totals' },0)">'Quarter 1', total_function => 'sum' },0)">'Quarter 2',0)">'Quarter 3',0)">'Quarter 4', ] } );
The supported totals row SUBTOTAL
functions are:
average count_nums count max min std_dev sum var
User defined functions or formulas aren't supported.
Format can also be applied to columns:
$currency_format = '$#,##0' ); 'B3:D8', total_string => { header => => 'sum', format => $currency_format, }, ] } );
Standard Excel::Writer::XLSX format objects can be used. However,they should be limited to numerical formats. Overriding other table formatting may produce inconsistent results.
FORMULAS AND FUNCTIONS IN EXCEL 

Introduction
The following is a brief introduction to formulas and functions in Excel and Excel::Writer::XLSX.
A formula is a string that begins with an equals sign:
'=A1+B1' $str = 2 ); # C2
The Excel $
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.
'=A1' # Column and row are relative '=$A1' # Column is absolute and row is relative '=A$1' # Column is relative and row is absolute '=$A$1' # Column and row are absolute
Formulas can also refer to cells in other worksheets of the current workbook. For example:
'=Sheet2!A1' '=Sheet2!A1:A5' '=Sheet2:Sheet3!A1' '=Sheet2:Sheet3!A1:A5' q{='Test Data'!A1} q{='Test Data1:Test Data2'!A1}
The sheet reference and the cell reference are separated by !
the exclamation mark symbol. If worksheet names contain spaces,commas or 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 q{}
to protect the quotes. See perlop
in the main Perl documentation. Only valid sheet names that have been added using the add_worksheet()
method can be used in formulas. You cannot reference external workbooks.
The 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:
Arithmetic operators: ===================== Operator Meaning Example + Addition 1+2 - Subtraction 2-1 * Multiplication 2*3 / Division 1/4 ^ Exponentiation 2^3 # Equivalent to ** - Unary minus -(1+2) % Percent (Not modulus) 13% Comparison operators: ===================== Operator Meaning Example = Equal to A1 = B1 # Equivalent to == <> Not equal to A1 <> B1 # Equivalent to != > Greater than A1 > B1 < Less than A1 < B1 >= Greater than or equal to A1 >= B1 <= Less than or equal to A1 <= B1 String operator: ================ Operator Meaning Example & Concatenation "Hello " & "World!" # [1] Reference operators: ==================== Operator Meaning Example : Range operator A1:A4 # [2] , Union operator SUM(2+2, B3) # [3] Notes: [1]: Equivalent to "Hello " . "World!" in Perl. [2]: This range is equivalent to cells A1, A2, A3 and A4. [3]: The comma behaves like the list separator in Perl.
The range and comma operators can have different symbols in non-English versions of Excel. These may be supported in a later version of Excel::Writer::XLSX. In the meantime European users of Excel take note:
'=SUM(1; 2; 3)'); # Wrong!! '=SUM(1,3)'); # Okay
For 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:http://office.microsoft.com/en-us/assistance/CH062528031033.aspx.
If your formula doesn't work in Excel::Writer::XLSX try the following:
1. Verify that the formula works in Excel. 2. Ensure that cell references and formula names are in uppercase. 3. Ensure that you are using ':' as the range operator, A1:A4. 4. Ensure that you are using ',' as the union operator, 3). 5. If you verify that the formula works in Gnumeric, OpenOffice.org or LibreOffice, make sure to note items 2-4 above, since these applications are more flexible than Excel with formula Syntax.
EXAMPLES 

See Excel::Writer::XLSX::Examples for a full list of examples.
Example 1
The following example shows some of the basic features of Excel::Writer::XLSX.
#!/usr/bin/perl -w use strict; use Excel::Writer::XLSX; # Create a new workbook called simple.xlsx and add a worksheet my 'simple.xlsx' ); my # The general Syntax is write($row,$token). Note that row and # column are zero indexed # Write some text 'Hi Excel!' ); # Write some numbers 1.00000 ); 2.00001 ); 3.14159 ); # Write some formulas '=A3 + A6' ); '=IF(A5>3,"No")' ); # Write a hyperlink ' );
Example 2
The following is a general example which demonstrates some features of working with multiple worksheets.
'regions.xlsx' ); # Add some worksheets my $north = 'North' ); my $south = 'South' ); my $east = 'East' ); my $west = 'West' ); # Add a Format my 'blue' ); # Add a caption to each worksheet for my $format ); } # Write some data $north->write( 200000 ); $south->write( 100000 ); $east->write( 150000 ); $west->write( 100000 ); # Set the active worksheet $south->activate(); # Set the width of the first column # Set the active cell 1 );
Example 3
Example of how to add conditional formatting to an Excel::Writer::XLSX file. The example below highlights cells that have a value greater than or equal to 50 in red and cells below that value in green.
#!/usr/bin/perl use strict; use warnings; use Excel::Writer::XLSX; my 'conditional_format.xlsx' ); my add_worksheet(); # This example below highlights cells that have a value greater than or # equal to 50 in red and cells below that value in green. # Light red fill with dark red text. my ); # Green fill with dark green text. my # Some sample data to run the conditional formatting against. my $data = [ [ 34,255)">72,255)">38,255)">75,255)">48,255)">66,255)">84,255)">86 ], [ 24,255)">54,255)">62,255)">26,255)">59 ],255)">28,255)">79,255)">97,255)">85,255)">93,255)">22,255)">14 ],255)">27,255)">71,255)">17,255)">18,255)">29,255)">47 ],255)">88,255)">25,255)">33,255)">23,255)">67,255)">59,255)">47,255)">36 ],255)">88 ],255)">57,255)">37,255)">41,255)">48 ],255)">52,255)">78,255)">96,255)">81,255)">55 ],255)">70,255)">46,255)">36,255)">21 ], ]; my $caption = 'Cells with values >= 50 are in light red. ' . 'Values < 50 are in light green'; # Write the data. $caption ); $data ); } ); # Write another conditional format over the same range. '<',102); font-weight:bold">$format2, } );
Example 4
The following is a simple example of using functions.
# Create a new workbook and add a worksheet my 'stats.xlsx' ); my 'Test data' ); # Set the column width for columns 1 20 ); # Create a format for the headings my set_bold(); # Write the sample data 'Sample',255)">4 ); 5 ); 6 ); 7 ); 8 ); 'Length',255)">25.4 ); 24.8 ); 25.0 ); 25.3 ); 24.9 ); 25.2 ); 24.8 ); # Write some statistical functions 'Count',0)">'=COUNT(B1:I1)' ); 'Sum',0)">'=SUM(B2:I2)' ); 'Average',0)">'=AVERAGE(B2:I2)' ); 'Min',0)">'=MIN(B2:I2)' ); 'Max',0)">'=MAX(B2:I2)' ); 'Standard Deviation',0)">'=STDEV(B2:I2)' ); 'Kurtosis',0)">'=KURT(B2:I2)' );
Example 5
The following example converts a tab separated file called tab.txt
into an Excel file called tab.xlsx
.
#!/usr/bin/perl -w use strict; use Excel::Writer::XLSX; open( TABFILE,0)">'tab.txt' ) or die "tab.txt: $!"; my 'tab.xlsx' ); my # Row and column are zero indexed my <TABFILE> ) { chomp; # Split on single tab my @fields = split( '\t',102); font-weight:bold">$_ ); my $col = 0; for my $token ( @fields ) { $token ); $col++; } $row++; }
NOTE: 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.
See the examples/csv2xls link here: http://search.cpan.org/~hmbrand/Text-CSV_XS/MANIFEST.
Additional Examples
The following is a description of the example files that are provided in the standard Excel::Writer::XLSX distribution. They demonstrate the different features and options of the module. See Excel::Writer::XLSX::Examples for more details.
Getting started =============== a_simple.pl A simple demo of some of the features. bug_report.pl A template for submitting bug reports. demo.pl A demo of some of the available features. formats.pl All the available formatting on several worksheets. regions.pl A simple example of multiple worksheets. stats.pl Basic formulas and functions. Intermediate ============ autofilter.pl Examples of worksheet autofilters. array_formula.pl Examples of how to write array formulas. cgi.pl A simple CGI program. chart_area.pl A demo of area style charts. chart_bar.pl A demo of bar (vertical histogram) style charts. chart_column.pl A demo of column (histogram) style charts. chart_line.pl A demo of line style charts. chart_pie.pl A demo of pie style charts. chart_radar.pl A demo of radar style charts. chart_scatter.pl A demo of scatter style charts. chart_secondary_axis.pl A demo of a line chart with a secondary axis. chart_stock.pl A demo of stock style charts. chart_data_table.pl A demo of a chart with a data table on the axis. chart_data_tools.pl A demo of charts with data highlighting options. colors.pl A demo of the colour palette and named colours. comments1.pl Add comments to worksheet cells. comments2.pl Add comments with advanced options. conditional_format.pl Add conditional formats to a range of cells. data_validate.pl An example of data validation and dropdown lists. date_time.pl Write dates and times with write_date_time(). defined_name.pl Example of how to create defined names. diag_border.pl A simple example of diagonal cell borders. filehandle.pl Examples of working with filehandles. headers.pl Examples of worksheet headers and footers. hide_row_col.pl Example of hiding rows and columns. hide_sheet.pl Simple example of hiding a worksheet. hyperlink1.pl Shows how to create web hyperlinks. hyperlink2.pl Examples of internal and external hyperlinks. indent.pl An example of cell indentation. macros.pl An example of adding macros from an existing file. merge1.pl A simple example of cell merging. merge2.pl A simple example of cell merging with formatting. merge3.pl Add hyperlinks to merged cells. merge4.pl An advanced example of merging with formatting. merge5.pl An advanced example of merging with formatting. merge6.pl An example of merging with Unicode strings. mod_perl1.pl A simple mod_perl 1 program. mod_perl2.pl A simple mod_perl 2 program. panes.pl An examples of how to create panes. outline.pl An example of outlines and grouping. outline_collapsed.pl An example of collapsed outlines. protection.pl Example of cell locking and formula hiding. rich_strings.pl Example of strings with multiple formats. right_to_left.pl Change default sheet direction to right to left. sales.pl An example of a simple sales spreadsheet. shape1.pl Insert shapes in worksheet. shape2.pl Insert shapes in worksheet. With properties. shape3.pl Insert shapes in worksheet. Scaled. shape4.pl Insert shapes in worksheet. With modification. shape5.pl Insert shapes in worksheet. With connections. shape6.pl Insert shapes in worksheet. With connections. shape7.pl Insert shapes in worksheet. One to many connections. shape8.pl Insert shapes in worksheet. One to many connections. shape_all.pl Demo of all the available shape and connector types. sparklines1.pl Simple sparklines demo. sparklines2.pl Sparklines demo showing formatting options. stats_ext.pl Same as stats.pl with external references. stocks.pl Demonstrates conditional formatting. tab_colors.pl Example of how to set worksheet tab colours. tables.pl Add Excel tables to a worksheet. write_handler1.pl Example of extending the write() method. Step 1. write_handler2.pl Example of extending the write() method. Step 2. write_handler3.pl Example of extending the write() method. Step 3. write_handler4.pl Example of extending the write() method. Step 4. write_to_scalar.pl Example of writing an Excel file to a Perl scalar. Unicode ======= unicode_2022_jp.pl Japanese: ISO-2022-JP. unicode_8859_11.pl Thai: ISO-8859_11. unicode_8859_7.pl Greek: ISO-8859_7. unicode_big5.pl Chinese: BIG5. unicode_cp1251.pl Russian: CP1251. unicode_cp1256.pl Arabic: CP1256. unicode_cyrillic.pl Russian: Cyrillic. unicode_koi8r.pl Russian: KOI8-R. unicode_polish_utf8.pl Polish : UTF8. unicode_shift_jis.pl Japanese: Shift JIS.
LIMITATIONS 

The following limits are imposed by Excel 2007+:
Description Limit ----------------------------------- ------ Maximum number of chars in a string 767 Maximum number of columns 16,255)">384 Maximum number of rows 048,255)">576 Maximum chars in a sheet name 31 Maximum chars in a header/footer 254 Maximum characters in hyperlink 255 Maximum number of unique hyperlinks* 65,255)">530
* Per worksheet. Excel allows a greater number of non-unique hyperlinks if they are contiguous and can be grouped into a single range. This will be supported in a later version of Excel::Writer::XLSX if possible.
Compatibility with Spreadsheet::WriteExcel 

The Excel::Writer::XLSX
module is a drop-in replacement for Spreadsheet::WriteExcel
.
It supports all of the features of Spreadsheet::WriteExcel with some minor differences noted below.
Workbook Methods Support ================ ====== new() Yes add_worksheet() Yes add_format() Yes add_chart() Yes add_shape() Yes. Not in Spreadsheet::WriteExcel. add_vba_project() Yes. Not in Spreadsheet::WriteExcel. close() Yes set_properties() Yes define_name() Yes set_tempdir() Yes set_custom_color() Yes sheets() Yes set_1904() Yes set_optimization() Yes. Not required in Spreadsheet::WriteE