phpgroupware-cvs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Phpgroupware-cvs] property/inc/excel Format.php, 1.1 BIFFwriter.php, 1


From: sigurdne
Subject: [Phpgroupware-cvs] property/inc/excel Format.php, 1.1 BIFFwriter.php, 1.1 WriteExcel.html, 1.1 Parser.php, 1.1 OLEwriter.php, 1.1 test.php, 1.1 Workbook.php, 1.1 Worksheet.php, 1.1 thanks, 1.1
Date: Wed, 9 Nov 2005 23:46:00 +0100

Update of property/inc/excel

Added Files:
     Branch: MAIN
            Format.php 
            BIFFwriter.php 
            WriteExcel.html 
            Parser.php 
            OLEwriter.php 
            test.php 
            Workbook.php 
            Worksheet.php 
            thanks 

Log Message:
no message

====================================================
Index: Format.php
<?php
/*
*  Module written/ported by Xavier Noguer <address@hidden>
*
*  The majority of this is _NOT_ my code.  I simply ported it from the
*  PERL Spreadsheet::WriteExcel module.
*
*  The author of the Spreadsheet::WriteExcel module is John McNamara
*  <address@hidden>
*
*  I _DO_ maintain this code, and John McNamara has nothing to do with the
*  porting of this code to PHP.  Any questions directly related to this
*  class library should be directed to me.
*
*  License Information:
*
*    Spreadsheet::WriteExcel:  A library for generating Excel Spreadsheets
*    Copyright (C) 2002 Xavier Noguer address@hidden
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/**
* Class for generating Excel XF records (formats)
*
* @author Xavier Noguer <address@hidden>
* @package Spreadsheet_WriteExcel
*/

class Format
{
  /**
  * Constructor
  *
  * @access public
  * @param integer $index the XF index for the format.
  * @param array   $properties array with properties to be set on 
initialization.
  */
    function Format($index = 0,$properties =  array())
    {
        $this->xf_index       = $index;

        $this->font_index     = 0;
        $this->font           = 'Arial';
        $this->size           = 10;
        $this->bold           = 0x0190;
        $this->_italic        = 0;
        $this->color          = 0x7FFF;
        $this->_underline     = 0;
        $this->font_strikeout = 0;
        $this->font_outline   = 0;
        $this->font_shadow    = 0;
        $this->font_script    = 0;
        $this->font_family    = 0;
        $this->font_charset   = 0;

        $this->_num_format    = 0;

        $this->hidden         = 0;
        $this->locked         = 1;

        $this->_text_h_align  = 0;
        $this->_text_wrap     = 0;
        $this->text_v_align   = 2;
        $this->text_justlast  = 0;
        $this->rotation       = 0;

        $this->fg_color       = 0x40;
        $this->bg_color       = 0x41;

        $this->pattern        = 0;

        $this->bottom         = 0;
        $this->top            = 0;
        $this->left           = 0;
        $this->right          = 0;

        $this->bottom_color   = 0x40;
        $this->top_color      = 0x40;
        $this->left_color     = 0x40;
        $this->right_color    = 0x40;

        // Set properties passed to Workbook::add_format()
        foreach($properties as $property => $value)
        {
            if(method_exists($this,"set_$property"))
            {
                $aux = 'set_'.$property;
                $this->$aux($value);
            }
        }
    }

    /**
    * Generate an Excel BIFF XF record (style or cell).
    *
    * @param string $style The type of the XF record ('style' or 'cell').
    * @return string The XF record
    */
    function get_xf($style)
    {
        // Set the type of the XF record and some of the attributes.
        if ($style == "style") {
            $style = 0xFFF5;
        }
        else {
            $style   = $this->locked;
            $style  |= $this->hidden << 1;
        }

        // Flags to indicate if attributes have been set.
        $atr_num     = ($this->_num_format != 0)?1:0;
        $atr_fnt     = ($this->font_index != 0)?1:0;
        $atr_alc     = ($this->_text_wrap)?1:0;
        $atr_bdr     = ($this->bottom   ||
                        $this->top      ||
                        $this->left     ||
                        $this->right)?1:0;
        $atr_pat     = (($this->fg_color != 0x40) ||
                        ($this->bg_color != 0x41) ||
                        $this->pattern)?1:0;
        $atr_prot    = 0;

        // Zero the default border colour if the border has not been set.
        if ($this->bottom == 0) {
            $this->bottom_color = 0;
            }
        if ($this->top  == 0) {
            $this->top_color = 0;
            }
        if ($this->right == 0) {
            $this->right_color = 0;
            }
        if ($this->left == 0) {
            $this->left_color = 0;
            }

        $record         = 0x00E0;              // Record identifier
        $length         = 0x0010;              // Number of bytes to follow

        $ifnt           = $this->font_index;   // Index to FONT record
        $ifmt           = $this->_num_format;  // Index to FORMAT record

        $align          = $this->_text_h_align;       // Alignment
        $align         |= $this->_text_wrap    << 3;
        $align         |= $this->text_v_align  << 4;
        $align         |= $this->text_justlast << 7;
        $align         |= $this->rotation      << 8;
        $align         |= $atr_num                << 10;
        $align         |= $atr_fnt                << 11;
        $align         |= $atr_alc                << 12;
        $align         |= $atr_bdr                << 13;
        $align         |= $atr_pat                << 14;
        $align         |= $atr_prot               << 15;

        $icv            = $this->fg_color;           // fg and bg pattern colors
        $icv           |= $this->bg_color      << 7;

        $fill           = $this->pattern;            // Fill and border line 
style
        $fill          |= $this->bottom        << 6;
        $fill          |= $this->bottom_color  << 9;

        $border1        = $this->top;                // Border line style and 
color
        $border1       |= $this->left          << 3;
        $border1       |= $this->right         << 6;
        $border1       |= $this->top_color     << 9;

        $border2        = $this->left_color;         // Border color
        $border2       |= $this->right_color   << 7;

        $header      = pack("vv",       $record, $length);
        $data        = pack("vvvvvvvv", $ifnt, $ifmt, $style, $align,
                                        $icv, $fill,
                                        $border1, $border2);
        return($header.$data);
    }

    /**
    * Generate an Excel BIFF FONT record.
    *
    * @see Workbook::_store_all_fonts()
    * @return string The FONT record
    */
    function get_font()
    {
        $dyHeight   = $this->size * 20;    // Height of font (1/20 of a point)
        $icv        = $this->color;        // Index to color palette
        $bls        = $this->bold;         // Bold style
        $sss        = $this->font_script;  // Superscript/subscript
        $uls        = $this->_underline;   // Underline
        $bFamily    = $this->font_family;  // Font family
        $bCharSet   = $this->font_charset; // Character set
        $rgch       = $this->font;         // Font name

        $cch        = strlen($rgch);       // Length of font name
        $record     = 0x31;                // Record identifier
        $length     = 0x0F + $cch;         // Record length
        $reserved   = 0x00;                // Reserved
        $grbit      = 0x00;                // Font attributes
        if ($this->_italic) {
            $grbit     |= 0x02;
        }
        if ($this->font_strikeout) {
            $grbit     |= 0x08;
        }
        if ($this->font_outline) {
            $grbit     |= 0x10;
        }
        if ($this->font_shadow) {
            $grbit     |= 0x20;
        }

        $header  = pack("vv",         $record, $length);
        $data    = pack("vvvvvCCCCC", $dyHeight, $grbit, $icv, $bls,
                                      $sss, $uls, $bFamily,
                                      $bCharSet, $reserved, $cch);
        return($header . $data. $this->font);
    }

    /**
    * Returns a unique hash key for a font. Used by Workbook->_store_all_fonts()
    *
    * The elements that form the key are arranged to increase the probability of
    * generating a unique key. Elements that hold a large range of numbers
    * (eg. _color) are placed between two binary elements such as _italic
    *
    * @return string A key for this font
    */
    function get_font_key()
    {
        $key  = "$this->font$this->size";
        $key .= "$this->font_script$this->_underline";
        $key .= "$this->font_strikeout$this->bold$this->font_outline";
        $key .= "$this->font_family$this->font_charset";
        $key .= "$this->font_shadow$this->color$this->_italic";
        $key  = str_replace(" ","_",$key);
        return ($key);
    }

    /**
    * Returns the index used by Worksheet->_XF()
    *
    * @return integer The index for the XF record
    */
    function get_xf_index()
    {
        return($this->xf_index);
    }

    /**
    * Used in conjunction with the set_xxx_color methods to convert a color
    * string into a number. Color range is 0..63 but we will restrict it
    * to 8..63 to comply with Gnumeric. Colors 0..7 are repeated in 8..15.
    *
    * @param string $name_color name of the color (i.e.: 'blue', 'red', etc..). 
Optional.
    * @return integer The color index
    */
    function _get_color($name_color = '')
    {
        $colors = array(
                        'aqua'    => 0x0F,
                        'cyan'    => 0x0F,
                        'black'   => 0x08,
                        'blue'    => 0x0C,
                        'brown'   => 0x10,
                        'magenta' => 0x0E,
                        'fuchsia' => 0x0E,
                        'gray'    => 0x17,
                        'grey'    => 0x17,
                        'green'   => 0x11,
                        'lime'    => 0x0B,
                        'navy'    => 0x12,
                        'orange'  => 0x35,
                        'purple'  => 0x14,
                        'red'     => 0x0A,
                        'silver'  => 0x16,
                        'white'   => 0x09,
                        'yellow'  => 0x0D
                       );

        // Return the default color, 0x7FFF, if undef,
        if($name_color == '') {
            return(0x7FFF);
        }

        // or the color string converted to an integer,
        if(isset($colors[$name_color])) {
            return($colors[$name_color]);
        }

        // or the default color if string is unrecognised,
        if(preg_match("/\D/",$name_color)) {
            return(0x7FFF);
        }

        // or an index < 8 mapped into the correct range,
        if($name_color < 8) {
            return($name_color + 8);
        }

        // or the default color if arg is outside range,
        if($name_color > 63) {
            return(0x7FFF);
        }

        // or an integer in the valid range
        return($name_color);
    }

    /**
    * Set cell alignment.
    *
    * @access public
    * @param string $location alignment for the cell ('left', 'right', etc...).
    */
    function set_align($location)
    {
        if (preg_match("/\d/",$location)) {
            return;                      // Ignore numbers
        }

        $location = strtolower($location);

        if ($location == 'left')
            $this->_text_h_align = 1;
        if ($location == 'centre')
            $this->_text_h_align = 2;
        if ($location == 'center')
            $this->_text_h_align = 2;
        if ($location == 'right')
            $this->_text_h_align = 3;
        if ($location == 'fill')
            $this->_text_h_align = 4;
        if ($location == 'justify')
            $this->_text_h_align = 5;
        if ($location == 'merge')
            $this->_text_h_align = 6;
        if ($location == 'equal_space') // For T.K.
            $this->_text_h_align = 7;
        if ($location == 'top')
            $this->text_v_align = 0;
        if ($location == 'vcentre')
            $this->text_v_align = 1;
        if ($location == 'vcenter')
            $this->text_v_align = 1;
        if ($location == 'bottom')
            $this->text_v_align = 2;
        if ($location == 'vjustify')
            $this->text_v_align = 3;
        if ($location == 'vequal_space') // For T.K.
            $this->text_v_align = 4;
    }

    /**
    * This is an alias for the unintuitive set_align('merge')
    *
    * @access public
    */
    function set_merge()
    {
        $this->set_align('merge');
    }

    /**
    * Bold has a range 0x64..0x3E8.
    * 0x190 is normal. 0x2BC is bold.
    *
    * @access public
    * @param integer $weight Weight for the text, 0 maps to 0x190, 1 maps to 
0x2BC.
                             It's Optional, default is 1 (bold).
    */
    function set_bold($weight = 1)
    {
        if($weight == 1) {
            $weight = 0x2BC;  // Bold text
        }
        if($weight == 0) {
            $weight = 0x190;  // Normal text
        }
        if($weight <  0x064) {
            $weight = 0x190;  // Lower bound
        }
        if($weight >  0x3E8) {
            $weight = 0x190;  // Upper bound
        }
        $this->bold = $weight;
    }


    /************************************
    * FUNCTIONS FOR SETTING CELLS BORDERS
    */

    /**
    * Sets the bottom border of the cell
    *
    * @access public
    * @param integer $style style of the cell border. 1 => thin, 2 => thick.
    */
    function set_bottom($style)
    {
        $this->bottom = $style;
    }

    /**
    * Sets the top border of the cell
    *
    * @access public
    * @param integer $style style of the cell top border. 1 => thin, 2 => thick.
    */
    function set_top($style)
    {
        $this->top = $style;
    }

    /**
    * Sets the left border of the cell
    *
    * @access public
    * @param integer $style style of the cell left border. 1 => thin, 2 => 
thick.
    */
    function set_left($style)
    {
        $this->left = $style;
    }

    /**
    * Sets the right border of the cell
    *
    * @access public
    * @param integer $style style of the cell right border. 1 => thin, 2 => 
thick.
    */
    function set_right($style)
    {
        $this->right = $style;
    }


    /**
    * Set cells borders to the same style
    *
    * @access public
    * @param integer $style style to apply for all cell borders. 1 => thin, 2 
=> thick.
    */
    function set_border($style)
    {
        $this->set_bottom($style);
        $this->set_top($style);
        $this->set_left($style);
        $this->set_right($style);
    }


    /*******************************************
    * FUNCTIONS FOR SETTING CELLS BORDERS COLORS
    */

    /**
    * Sets all the cell's borders to the same color
    *
    * @access public
    * @param mixed $color The color we are setting. Either a string (like 
'blue'),
    *                     or an integer (like 0x41).
    */
    function set_border_color($color)
    {
        $this->set_bottom_color($color);
        $this->set_top_color($color);
        $this->set_left_color($color);
        $this->set_right_color($color);
    }

    /**
    * Sets the cell's bottom border color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (range 
is [8...63]).
    */
    function set_bottom_color($color)
    {
        $value = $this->_get_color($color);
        $this->bottom_color = $value;
    }

    /**
    * Sets the cell's top border color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (range 
is [8...63]).
    */
    function set_top_color($color)
    {
        $value = $this->_get_color($color);
        $this->top_color = $value;
    }

    /**
    * Sets the cell's left border color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (like 
0x41).
    */
    function set_left_color($color)
    {
        $value = $this->_get_color($color);
        $this->left_color = $value;
    }

    /**
    * Sets the cell's right border color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (like 
0x41).
    */
    function set_right_color($color)
    {
        $value = $this->_get_color($color);
        $this->right_color = $value;
    }


    /**
    * Sets the cell's foreground color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (like 
0x41).
    */
    function set_fg_color($color)
    {
        $value = $this->_get_color($color);
        $this->fg_color = $value;
    }

    /**
    * Sets the cell's background color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (like 
0x41).
    */
    function set_bg_color($color)
    {
        $value = $this->_get_color($color);
        $this->bg_color = $value;
    }

    /**
    * Sets the cell's color
    *
    * @access public
    * @param mixed $color either a string (like 'blue'), or an integer (like 
0x41).
    */
    function set_color($color)
    {
        $value = $this->_get_color($color);
        $this->color = $value;
    }

    /**
    * Sets the pattern attribute of a cell
    *
    * @access public
    * @param integer $arg Optional. Defaults to 1.
    */
    function set_pattern($arg = 1)
    {
        $this->pattern = $arg;
    }

    /**
    * Sets the underline of the text
    *
    * @access public
    * @param integer $underline The value for underline. Possible values are:
    *                          1 => underline, 2 => double underline.
    */
    function set_underline($underline)
    {
        $this->_underline = $underline;
    }

    /**
    * Sets the font style as italic
    *
    * @access public
    */
    function set_italic()
    {
        $this->_italic = 1;
    }

    /**
    * Sets the font size
    *
    * @access public
    * @param integer $size The font size (in pixels I think).
    */
    function set_size($size)
    {
        $this->size = $size;
    }

    /**
    * Sets the num format
    *
    * @access public
    * @param integer $num_format The num format.
    */
    function set_num_format($num_format)
    {
        $this->_num_format = $num_format;
    }

    /**
    * Sets text wrapping
    *
    * @access public
    * @param integer $text_wrap Optional. 0 => no text wrapping, 1 => text 
wrapping.
    *                           Defaults to 1.
    */
    function set_text_wrap($text_wrap = 1)
    {
        $this->_text_wrap = $text_wrap;
    }
}
?>

====================================================
Index: BIFFwriter.php
<?php
/*
*  Module written/ported by Xavier Noguer <address@hidden>
*
*  The majority of this is _NOT_ my code.  I simply ported it from the
*  PERL Spreadsheet::WriteExcel module.
*
*  The author of the Spreadsheet::WriteExcel module is John McNamara
*  <address@hidden>
*
*  I _DO_ maintain this code, and John McNamara has nothing to do with the
*  porting of this code to PHP.  Any questions directly related to this
*  class library should be directed to me.
*
*  License Information:
*
*    Spreadsheet::WriteExcel:  A library for generating Excel Spreadsheets
*    Copyright (C) 2002 Xavier Noguer address@hidden
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/**
* Class for writing Excel BIFF records.
*
* From "MICROSOFT EXCEL BINARY FILE FORMAT" by Mark O'Brien (Microsoft 
Corporation):
*
* BIFF (BInary File Format) is the file format in which Excel documents are
* saved on disk.  A BIFF file is a complete description of an Excel document.
* BIFF files consist of sequences of variable-length records. There are many
* different types of BIFF records.  For example, one record type describes a
* formula entered into a cell; one describes the size and location of a
* window into a document; another describes a picture format.
*
* @author Xavier Noguer <address@hidden>
* @package Spreadsheet_WriteExcel
*/

class BIFFWriter
{
    var $_BIFF_version = 0x0500;

/**
* Constructor
*
* @access public
*/
    function BIFFwriter()
    {
        // The byte order of this architecture. 0 => little endian, 1 => big 
endian
        $this->_byte_order = '';
        // The string containing the data of the BIFF stream
        $this->_data       = '';
        // Should be the same as strlen($this->_data)
        $this->_datasize   = 0;
        // The maximun length for a BIFF record. See _add_continue()
        $this->_limit      = 2080;
        // Set the byte order
        $this->_set_byte_order();
    }

/**
* Determine the byte order and store it as class data to avoid
* recalculating it for each call to new().
*
* @access private
*/
    function _set_byte_order()
    {
        if ($this->_byte_order == '')
        {
            // Check if "pack" gives the required IEEE 64bit float
            $teststr = pack("d", 1.2345);
            $number  = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 
0x3F);
            if ($number == $teststr) {
                $byte_order = 0;    // Little Endian
            }
            elseif ($number == strrev($teststr)){
                $byte_order = 1;    // Big Endian
            }
            else {
                // Give up. I'll fix this in a later version.
                die("Required floating point format not supported ".
                    "on this platform. See the portability section ".
                    "of the documentation."
                   );
            }
        }
        $this->_byte_order = $byte_order;
    }

/**
* General storage function
*
* @param string $data binary data to prepend
* @access private
*/
    function _prepend($data)
    {
        if (strlen($data) > $this->_limit) {
            $data = $this->_add_continue($data);
        }
        $this->_data      = $data.$this->_data;
        $this->_datasize += strlen($data);
    }

/**
* General storage function
*
* @param string $data binary data to append
* @access private
*/
    function _append($data)
    {
        if (strlen($data) > $this->_limit) {
            $data = $this->_add_continue($data);
        }
        $this->_data      = $this->_data.$data;
        $this->_datasize += strlen($data);
    }

/**
* Writes Excel BOF record to indicate the beginning of a stream or
* sub-stream in the BIFF file.
*
* @param  integer $type type of BIFF file to write: 0x0005 Workbook, 0x0010 
Worksheet.
* @access private
*/
    function _store_bof($type)
    {
        $record  = 0x0809;        // Record identifier
        $length  = 0x0008;        // Number of bytes to follow
        $version = $this->_BIFF_version;

        // According to the SDK $build and $year should be set to zero.
        // However, this throws a warning in Excel 5. So, use these
        // magic numbers.
        $build   = 0x096C;
        $year    = 0x07C9;

        $header  = pack("vv",   $record, $length);
        $data    = pack("vvvv", $version, $type, $build, $year);
        $this->_prepend($header.$data);
    }

/**
* Writes Excel EOF record to indicate the end of a BIFF stream.
*
* @access private
*/
    function _store_eof()
    {
        $record    = 0x000A;   // Record identifier
        $length    = 0x0000;   // Number of bytes to follow
        $header    = pack("vv", $record, $length);
        $this->_append($header);
    }

/**
* Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
* Excel 97 the limit is 8228 bytes. Records that are longer than these limits
* must be split up into CONTINUE blocks.
*
* This function takes a long BIFF record and inserts CONTINUE records as
* necessary.
*
* @param  string  $data The original binary data to be written
* @return string        A very convenient string of continue blocks
* @access private
*/
    function _add_continue($data)
    {
        $limit      = $this->_limit;
        $record     = 0x003C;         // Record identifier

        // The first 2080/8224 bytes remain intact. However, we have to change
        // the length field of the record.
        $tmp = substr($data, 0, 2).pack("v", $limit-4).substr($data, 4, $limit 
- 4);

        $header = pack("vv", $record, $limit);  // Headers for continue records

        // Retrieve chunks of 2080/8224 bytes +4 for the header.
        for($i = $limit; $i < strlen($data) - $limit; $i += $limit)
        {
            $tmp .= $header;
            $tmp .= substr($data, $i, $limit);
        }

        // Retrieve the last chunk of data
        $header  = pack("vv", $record, strlen($data) - $i);
        $tmp    .= $header;
        $tmp    .= substr($data,$i,strlen($data) - $i);

        return($tmp);
    }
}
?>

====================================================
Index: WriteExcel.html
<html><head><title>Spreadsheet::WriteExcel - Write to a cross-platform Excel 
binary file.</title>

<link rev="made" href="mailto:";>
<style type="text/css">



   <!--

   pre  {
        font-family : courier new, sans-serif;
        font-size : 10pt;
        color : #0066cc;
   }

   CODE  {
        font-family : courier new, sans-serif;
        font-size : 10pt;
        color : #0066cc;
   }


   -->
</style></head>




<body>


<!-- INDEX BEGIN -->

<ul>

        <li><a href="#NAME">NAME</a></li>
        <li><a href="#VERSION">VERSION</a></li>
        <li><a href="#SYNOPSIS">SYNOPSIS</a></li>
        <li><a href="#DESCRIPTION">DESCRIPTION</a></li>
        <li><a href="#QUICK_START">QUICK START</a></li>
        <li><a href="#WORKBOOK_METHODS">WORKBOOK METHODS</a></li>
        <ul>

        <code>
                <li><a href="#new_">new()</a></li>
                <li><a href="#close_">close()</a></li>
                <li><a href="#set_tempdir_">set_tempdir()</a></li>
                <li><a 
href="#add_worksheet_sheetname_">add_worksheet($sheetname)</a></li>
                <li><a 
href="#add_chart_ext_chart_data_char">add_chart_ext($chart_data, 
$chartname)</a></li>
                <li><a 
href="#add_format_properties_">add_format(%properties)</a></li>
                <li><a 
href="#set_custom_color_index_red_">set_custom_color($index, $red, $green, 
$blue)</a></li>
                <li><a href="#sheets_0_1_">sheets(0, 1, ...)</a></li>
                <li><a href="#set_1904_">set_1904()</a></li>
                <li><a 
href="#set_codepage_codepage_">set_codepage($codepage)</a></li>
        </code>
        </ul>

        <li><a href="#WORKSHEET_METHODS">WORKSHEET METHODS</a></li>
        <ul>

        <code>
                <li><a href="#Cell_notation">Cell notation</a></li>
                <li><a href="#write_row_column_token_fo">write($row, $column, 
$token, $format)</a></li>
                <li><a href="#write_number_row_column_num">write_number($row, 
$column, $number, $format)</a></li>
                <li><a href="#write_string_row_column_str">write_string($row, 
$column, $string, $format)</a></li>
                <li><a href="#write_unicode_row_column_st">write_unicode($row, 
$column, $string, $format)</a></li>
                <li><a 
href="#write_unicode_le_row_column_">write_unicode_le($row, $column, $string, 
$format)</a></li>
                <li><a href="#keep_leading_zeros_">keep_leading_zeros()</a></li>
                <li><a href="#write_blank_row_column_form">write_blank($row, 
$column, $format)</a></li>
                <li><a href="#write_row_row_column_array_">write_row($row, 
$column, $array_ref, $format)</a></li>
                <li><a href="#write_col_row_column_array_">write_col($row, 
$column, $array_ref, $format)</a></li>
                <li><a 
href="#write_date_time_row_col_dat">write_date_time($row, $col, $date_string, 
$format)</a></li>
                <li><a href="#write_url_row_col_url_str">write_url($row, $col, 
$url, $string, $format)</a></li>
                <li><a 
href="#write_url_range_row1_col1_r">write_url_range($row1, $col1, $row2, $col2, 
$url, $string, $format)</a></li>
                <li><a href="#write_formula_row_column_fo">write_formula($row, 
$column, $formula, $format)</a></li>
                <li><a 
href="#store_formula_formula_">store_formula($formula)</a></li>
                <li><a href="#repeat_formula_row_col_form">repeat_formula($row, 
$col, $formula, $format, ($pattern =&gt; $replace, ...))</a></li>
                <li><a href="#write_comment_row_column_st">write_comment($row, 
$column, $string)</a></li>
                <li><a 
href="#add_write_handler_re_code_ref">add_write_handler($re, $code_ref)</a></li>
                <li><a href="#insert_bitmap_row_col_filen">insert_bitmap($row, 
$col, $filename, $x, $y, $scale_x, $scale_y)</a></li>
                <li><a href="#get_name_">get_name()</a></li>
                <li><a href="#activate_">activate()</a></li>
                <li><a href="#select_">select()</a></li>
                <li><a href="#set_first_sheet_">set_first_sheet()</a></li>
                <li><a href="#protect_password_">protect($password)</a></li>
                <li><a 
href="#set_selection_first_row_first">set_selection($first_row, $first_col, 
$last_row, $last_col)</a></li>
                <li><a href="#set_row_row_height_format_">set_row($row, 
$height, $format, $hidden, $level)</a></li>
                <li><a 
href="#set_column_first_col_last_col">set_column($first_col, $last_col, $width, 
$format, $hidden, $level)</a></li>
                <li><a 
href="#outline_settings_visible_symb">outline_settings($visible, 
$symbols_below, $symbols_right, $auto_style)</a></li>
                <li><a href="#freeze_panes_row_col_top_ro">freeze_panes($row, 
$col, $top_row, $left_col)</a></li>
                <li><a href="#thaw_panes_y_x_top_row_le">thaw_panes($y, $x, 
$top_row, $left_col)</a></li>
                <li><a 
href="#merge_range_first_row_first_c">merge_range($first_row, $first_col, 
$last_row, $last_col, $token, $format)</a></li>
                <li><a href="#set_zoom_scale_">set_zoom($scale)</a></li>
        </code>
        </ul>

        <li><a href="#PAGE_SET_UP_METHODS">PAGE SET-UP METHODS</a></li>
        <ul>

        <code>
                <li><a href="#set_landscape_">set_landscape()</a></li>
                <li><a href="#set_portrait_">set_portrait()</a></li>
                <li><a href="#set_paper_index_">set_paper($index)</a></li>
                <li><a 
href="#center_horizontally_">center_horizontally()</a></li>
                <li><a href="#center_vertically_">center_vertically()</a></li>
                <li><a href="#set_margins_inches_">set_margins($inches)</a></li>
                <li><a href="#set_header_string_margin_">set_header($string, 
$margin)</a></li>
                <li><a href="#set_footer_">set_footer()</a></li>
                <li><a 
href="#repeat_rows_first_row_last_ro">repeat_rows($first_row, 
$last_row)</a></li>
                <li><a 
href="#repeat_columns_first_col_last">repeat_columns($first_col, 
$last_col)</a></li>
                <li><a 
href="#hide_gridlines_option_">hide_gridlines($option)</a></li>
                <li><a 
href="#print_row_col_headers_">print_row_col_headers()</a></li>
                <li><a 
href="#print_area_first_row_first_co">print_area($first_row, $first_col, 
$last_row, $last_col)</a></li>
                <li><a href="#fit_to_pages_width_height_">fit_to_pages($width, 
$height)</a></li>
                <li><a 
href="#set_print_scale_scale_">set_print_scale($scale)</a></li>
                <li><a 
href="#set_h_pagebreaks_breaks_">set_h_pagebreaks(@breaks)</a></li>
                <li><a 
href="#set_v_pagebreaks_breaks_">set_v_pagebreaks(@breaks)</a></li>
        </code>
        </ul>

        <li><a href="#CELL_FORMATTING">CELL FORMATTING</a></li>
        <ul>

                <li><a href="#Creating_and_using_a_Format_obje">Creating and 
using a Format object</a></li>
                <li><a href="#Format_methods_and_Format_proper">Format methods 
and Format properties</a></li>
                <li><a href="#Working_with_formats">Working with 
formats</a></li>
        </ul>

        <li><a href="#FORMAT_METHODS">FORMAT METHODS</a></li>
        <ul>

        <code>
                <li><a 
href="#set_properties_properties_">set_properties(%properties)</a></li>
                <li><a href="#set_font_fontname_">set_font($fontname)</a></li>
                <li><a href="#set_size_">set_size()</a></li>
                <li><a href="#set_color_">set_color()</a></li>
                <li><a href="#set_bold_">set_bold()</a></li>
                <li><a href="#set_italic_">set_italic()</a></li>
                <li><a href="#set_underline_">set_underline()</a></li>
                <li><a href="#set_font_strikeout_">set_font_strikeout()</a></li>
                <li><a href="#set_font_script_">set_font_script()</a></li>
                <li><a href="#set_font_outline_">set_font_outline()</a></li>
                <li><a href="#set_font_shadow_">set_font_shadow()</a></li>
                <li><a href="#set_num_format_">set_num_format()</a></li>
                <li><a href="#set_locked_">set_locked()</a></li>
                <li><a href="#set_hidden_">set_hidden()</a></li>
                <li><a href="#set_align_">set_align()</a></li>
                <li><a href="#set_center_across_">set_center_across()</a></li>
                <li><a href="#set_text_wrap_">set_text_wrap()</a></li>
                <li><a href="#set_rotation_">set_rotation()</a></li>
                <li><a href="#set_indent_">set_indent()</a></li>
                <li><a href="#set_shrink_">set_shrink()</a></li>
                <li><a href="#set_text_justlast_">set_text_justlast()</a></li>
                <li><a href="#set_pattern_">set_pattern()</a></li>
                <li><a href="#set_bg_color_">set_bg_color()</a></li>
                <li><a href="#set_fg_color_">set_fg_color()</a></li>
                <li><a href="#set_border_">set_border()</a></li>
                <li><a href="#set_border_color_">set_border_color()</a></li>
                <li><a href="#copy_format_">copy($format)</a></li>
        </code>
        </ul>

        <li><a href="#COLOURS_IN_EXCEL">COLOURS IN EXCEL</a></li>
        <li><a href="#DATES_IN_EXCEL">DATES IN EXCEL</a></li>
        <li><a href="#OUTLINES_AND_GROUPING_IN_EXCEL">OUTLINES AND GROUPING IN 
EXCEL</a></li>
        <li><a href="#FORMULAS_AND_FUNCTIONS_IN_EXCEL">FORMULAS AND FUNCTIONS 
IN EXCEL</a></li>
        <ul>

                <li><a href="#Caveats">Caveats</a></li>
                <li><a href="#Introduction">Introduction</a></li>
                <li><a href="#Improving_performance_when_worki">Improving 
performance when working with formulas</a></li>
        </ul>

        <li><a href="#EXAMPLES">EXAMPLES</a></li>
        <ul>

        <code>
                <li><a href="#Example_1">Example 1</a></li>
                <li><a href="#Example_2">Example 2</a></li>
                <li><a href="#Example_3">Example 3</a></li>
                <li><a href="#Example_4">Example 4</a></li>
                <li><a href="#Example_5">Example 5</a></li>
                <li><a href="#Additional_Examples">Additional Examples</a></li>
        </code>
        </ul>

        <li><a href="#LIMITATIONS">LIMITATIONS</a></li>
        <li><a href="#DOWNLOADING">DOWNLOADING</a></li>
        <li><a href="#REQUIREMENTS">REQUIREMENTS</a></li>
        <li><a href="#INSTALLATION">INSTALLATION</a></li>
        <li><a href="#PORTABILITY">PORTABILITY</a></li>
        <li><a href="#DIAGNOSTICS">DIAGNOSTICS</a></li>
        <li><a href="#THE_EXCEL_BINARY_FORMAT">THE EXCEL BINARY FORMAT</a></li>
        <li><a href="#WRITING_EXCEL_FILES">WRITING EXCEL FILES</a></li>
        <li><a href="#READING_EXCEL_FILES">READING EXCEL FILES</a></li>
        <li><a href="#Warning_about_XML_Parser_and_Pe">Warning about 
XML::Parser and Perl 5.6</a></li>
        <li><a href="#BUGS">BUGS</a></li>
        <li><a href="#TO_DO">TO DO</a></li>
        <li><a href="#MAILING_LIST">MAILING LIST</a></li>
        <li><a href="#SEE_ALSO">SEE ALSO</a></li>
        <li><a href="#ACKNOWLEDGEMENTS">ACKNOWLEDGEMENTS</a></li>
        <li><a href="#AUTHOR">AUTHOR</a></li>
        <li><a href="#COPYRIGHT">COPYRIGHT</a></li>
</ul>
<!-- INDEX END -->

<hr>
<p>
</p><h1><a name="NAME">NAME</a></h1>
<p>
Spreadsheet::WriteExcel - Write to a cross-platform Excel binary file.

</p>
<p>
</p><hr>
<h1><a name="VERSION">VERSION</a></h1>
<p>
This document refers to version 2.13 of Spreadsheet::WriteExcel, released
April 20, 2005.

</p>
<p>
</p><hr>
<h1><a name="SYNOPSIS">SYNOPSIS</a></h1>
<p>
To write a string, a formatted string, a number and a formula to the first
worksheet in an Excel workbook called perl.xls:

</p>
<p>
</p><pre>    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    # Create a new Excel workbook
    my $workbook = Spreadsheet::WriteExcel-&gt;new("perl.xls");
</pre>
<p></p>
<p>
</p><pre>    # Add a worksheet
    $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    #  Add and define a format
    $format = $workbook-&gt;add_format(); # Add a format
    $format-&gt;set_bold();
    $format-&gt;set_color('red');
    $format-&gt;set_align('center');
</pre>
<p></p>
<p>
</p><pre>    # Write a formatted and unformatted string, row and column 
notation.
    $col = $row = 0;
    $worksheet-&gt;write($row, $col, "Hi Excel!", $format);
    $worksheet-&gt;write(1,    $col, "Hi Excel!");
</pre>
<p></p>
<p>
</p><pre>    # Write a number and a formula using A1 notation
    $worksheet-&gt;write('A3', 1.2345);
    $worksheet-&gt;write('A4', '=SIN(PI()/4)');
</pre>
<p></p>
<p>
</p><hr>
<h1><a name="DESCRIPTION">DESCRIPTION</a></h1>
<p>
The Spreadsheet::WriteExcel module can be used to create a cross-platform
Excel binary file. Multiple worksheets can be added to a workbook and
formatting can be applied to cells. Text, numbers, formulas, hyperlinks and
images can be written to the cells.

</p>
<p>
The Excel file produced by this module is compatible with 97, 2000, 2002
and 2003.

</p>
<p>
The module will work on the majority of Windows, UNIX and Macintosh
platforms. Generated files are also compatible with the Linux/UNIX
spreadsheet applications Gnumeric and OpenOffice.org.

</p>
<p>
This module cannot be used to write to an existing Excel file.

</p>
<p>
</p><hr>
<h1><a name="QUICK_START">QUICK START</a></h1>
<p>
Spreadsheet::WriteExcel tries to provide an interface to as many of Excel's
features as possible. As a result there is a lot of documentation to
accompany the interface and it can be difficult at first glance to see what
it important and what is not. So for those of you who prefer to assemble
Ikea furniture first and then read the instructions, here are three easy
steps:

</p>
<p>
1. Create a new Excel <em>workbook</em> (i.e. file) using <code>new()</code>.

</p>
<p>
2. Add a <em>worksheet</em> to the new workbook using 
<code>add_worksheet()</code>.

</p>
<p>
3. Write to the worksheet using <code>write()</code>.

</p>
<p>
Like this:

</p>
<p>
</p><pre>    use Spreadsheet::WriteExcel;                             # Step 0
</pre>
<p></p>
<p>
</p><pre>    my $workbook = Spreadsheet::WriteExcel-&gt;new("perl.xls"); # Step 
1
    $worksheet   = $workbook-&gt;add_worksheet();               # Step 2
    $worksheet-&gt;write('A1', "Hi Excel!");                    # Step 3
</pre>
<p></p>
<p>
This will create an Excel file called <code>perl.xls</code> with a single 
worksheet and the text <code>"Hi Excel!"</code> in the relevant cell. And 
that's it. Okay, so there is actually a zeroth
step as well, but <code>use module</code> goes without saying. There are also 
more than 40 examples that come with
the distribution and which you can use to get you started. See <a 
href="#EXAMPLES">EXAMPLES</a>.

</p>
<p>
Those of you who read the instructions first and assemble the furniture
afterwards will know how to proceed. ;-)

</p>
<p>
</p><hr>
<h1><a name="WORKBOOK_METHODS">WORKBOOK METHODS</a></h1>
<p>
The Spreadsheet::WriteExcel module provides an object oriented interface to
a new Excel workbook. The following methods are available through a new
workbook.

</p>
<p>
</p><pre>    new()
    close()
    set_tempdir()
    add_worksheet()
    add_format()
    set_custom_color()
    sheets()
    set_1904()
    set_codepage()
</pre>
<p></p>
<p>
If you are unfamiliar with object oriented interfaces or the way that they
are implemented in Perl have a look at <code>perlobj</code> and 
<code>perltoot</code> in the main Perl documentation.

</p>
<p>
</p><hr>
<h2><a name="new_">new()</a></h2>
<p>
A new Excel workbook is created using the <code>new()</code> constructor which 
accepts either a filename or a filehandle as a parameter.
The following example creates a new Excel file based on a filename:

</p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new('filename.xls');
    my $worksheet = $workbook-&gt;add_worksheet();
    $worksheet-&gt;write(0, 0, "Hi Excel!");
</pre>
<p></p>
<p>
Here are some other examples of using <code>new()</code> with filenames:

</p>
<p>
</p><pre>    my $workbook1 = Spreadsheet::WriteExcel-&gt;new($filename);
    my $workbook2 = Spreadsheet::WriteExcel-&gt;new("/tmp/filename.xls");
    my $workbook3 = Spreadsheet::WriteExcel-&gt;new("c:\\tmp\\filename.xls");
    my $workbook4 = Spreadsheet::WriteExcel-&gt;new('c:\tmp\filename.xls');
</pre>
<p></p>
<p>
The last two examples demonstrates how to create a file on DOS or Windows
where it is necessary to either escape the directory separator <code>\</code> 
or to use single quotes to ensure that it isn't interpolated. For more
information see <code>perlfaq5: Why can't I use "C:\temp\foo" in DOS 
paths?</code>.

</p>
<p>
The <code>new()</code> constructor returns a Spreadsheet::WriteExcel object 
that you can use to
add worksheets and store data. It should be noted that although <code>my</code> 
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 <code>close()</code> method.

</p>
<p>
If the file cannot be created, due to file permissions or some other
reason,  <code>new</code> will return <code>undef</code>. Therefore, it is good 
practice to check the return value of <code>new</code> before proceeding. As 
usual the Perl variable <code>$!</code> will be set if there is a file creation 
error. You will also see one of the
warning messages detailed in <a href="#DIAGNOSTICS">DIAGNOSTICS</a>:

</p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new('protected.xls');
    die "Problems creating new Excel file: $!" unless defined $workbook;
</pre>
<p></p>
<p>
You can also pass a valid filehandle to the <code>new()</code> constructor. For 
example in a CGI program you could do something like this:

</p>
<p>
</p><pre>    binmode(STDOUT);
    my $workbook  = Spreadsheet::WriteExcel-&gt;new(\*STDOUT);
</pre>
<p></p>
<p>
The requirement for <code>binmode()</code> is explained below.

</p>
<p>
For CGI programs you can also use the special Perl filename <code>'-'</code> 
which will redirect the output to STDOUT:

</p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new('-');
</pre>
<p></p>
<p>
See also, the <code>cgi.pl</code> program in the <code>examples</code> 
directory of the distro.

</p>
<p>
However, this special case will not work in <code>mod_perl</code> programs 
where you will have to do something like the following:

</p>
<p>
</p><pre>    # mod_perl 1
    ...
    tie *XLS, 'Apache';
    binmode(XLS);
    my $workbook  = Spreadsheet::WriteExcel-&gt;new(\*XLS);
    ...
</pre>
<p></p>
<p>
</p><pre>    # mod_perl 2
    ...
    tie *XLS =&gt; $r;  # Tie to the Apache::RequestRec object
    binmode(*XLS);
    my $workbook  = Spreadsheet::WriteExcel-&gt;new(\*XLS);
    ...
</pre>
<p></p>
<p>
See also, the <code>mod_perl1.pl</code> and <code>mod_perl2.pl</code> programs 
in the <code>examples</code> directory of the distro.

</p>
<p>
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.

</p>
<p>
For example here is a way to write an Excel file to a scalar with <code>perl 
5.8</code>:

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    # Requires perl 5.8 or later
    open my $fh, '&gt;', \my $str or die "Failed to open filehandle: $!";
</pre>
<p></p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new($fh);
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(0, 0,  "Hi Excel!");
</pre>
<p></p>
<p>
</p><pre>    $workbook-&gt;close();
</pre>
<p></p>
<p>
</p><pre>    # The Excel file in now in $str. Remember to binmode() the output
    # filehandle before printing it.
    binmode STDOUT;
    print $str;
</pre>
<p></p>
<p>
See also the <code>write_to_scalar.pl</code> and <code>filehandle.pl</code> 
programs in the <code>examples</code> directory of the distro.

</p>
<p>
<strong>Note about the requirement for</strong>  <code>binmode()</code>: An 
Excel file is comprised of binary data. Therefore, if you are using a
filehandle you should ensure that you <code>binmode()</code> it prior to 
passing it to <code>new()</code>.You should do this regardless of whether you 
are on a Windows platform or
not. This applies especially to users of perl 5.8 on systems where utf8 is
likely to be in operation such as RedHat Linux 9. If your program, either
intentionally or not, writes UTF8 data to a filehandle that is passed to 
<code>new()</code> it will corrupt the Excel file that is created.

</p>
<p>
You don't have to worry about <code>binmode()</code> if you are using filenames 
instead of filehandles. Spreadsheet::WriteExcel
performs the <code>binmode()</code> internally when it converts the filename to 
a filehandle. For more
information about <code>binmode()</code> see <code>perlfunc</code> and 
<code>perlopentut</code> in the main Perl documentation.

</p>
<p>
</p><hr>
<h2><a name="close_">close()</a></h2>
<p>
The <code>close()</code> method can be used to explicitly close an Excel file.

</p>
<p>
</p><pre>    $workbook-&gt;close();
</pre>
<p></p>
<p>
An explicit <code>close()</code> 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.

</p>
<p>
In addition, <code>close()</code> 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:

</p>
<ul>
<li>
<p>
If <code>my()</code> was not used to declare the scope of a workbook variable 
created using <code>new()</code>.

</p>
</li><li>
<p>
If the <code>new()</code>, <code>add_worksheet()</code> or 
<code>add_format()</code> methods are called in subroutines.

</p>
</li></ul>
<p>
The reason for this is that Spreadsheet::WriteExcel relies on Perl's 
<code>DESTROY</code> 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.

</p>
<p>
In general, if you create a file with a size of 0 bytes or you fail to
create a file you need to call <code>close()</code>.

</p>
<p>
The return value of <code>close()</code> is the same as that returned by perl 
when it closes the file created by <code>new()</code>. This allows you to 
handle error conditions in the usual way:

</p>
<p>
</p><pre>    $workbook-&gt;close() or die "Error closing file: $!";
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_tempdir_">set_tempdir()</a></h2>
<p>
For speed and efficiency <code>Spreadsheet::WriteExcel</code> stores worksheet 
data in temporary files prior to assembling the final
workbook.

</p>
<p>
If Spreadsheet::WriteExcel is unable to create these temporary files it
will store the required data in memory. This can be slow for large files.

</p>
<p>
The problem occurs mainly with IIS on Windows although it could feasibly
occur on Unix systems as well. The problem generally occurs because the
default temp file directory is defined as <code>C:/</code> or some other 
directory that IIS doesn't provide write access to.

</p>
<p>
To check if this might be a problem on a particular system you can run a
simple test program with <code>-w</code> or <code>use warnings</code>. This 
will generate a warning if the module cannot create the required
temporary files:

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new("test.xls");
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
To avoid this problem the <code>set_tempdir()</code> method can be used to 
specify a directory that is accessible for the
creation of temporary files.

</p>
<p>
The <code>File::Temp</code> module is used to create the temporary files. 
File::Temp uses <code>File::Spec</code> to determine an appropriate location 
for these files such as <code>/tmp</code> or <code>c:\windows\temp</code>. You 
can find out which directory is used on your system as follows:

</p>
<p>
</p><pre>    perl -MFile::Spec -le "print File::Spec-&gt;tmpdir"
</pre>
<p></p>
<p>
Even if the default temporary file directory is accessible you may wish to
specify an alternative location for security or maintenance reasons:

</p>
<p>
</p><pre>    $workbook-&gt;set_tempdir('/tmp/writeexcel');
    $workbook-&gt;set_tempdir('c:\windows\temp\writeexcel');
</pre>
<p></p>
<p>
The directory for the temporary file must exist, <code>set_tempdir()</code> 
will not create a new directory.

</p>
<p>
One disadvantage of using the <code>set_tempdir()</code> method is that on some 
Windows systems it will limit you to approximately
800 concurrent tempfiles. This means that a single program running on one
of these systems will be limited to creating a total of 800 workbook and
worksheet objects. You can run multiple, non-concurrent programs to work
around this if necessary.

</p>
<p>
</p><hr>
<h2><a name="add_worksheet_sheetname_">add_worksheet($sheetname)</a></h2>
<p>
At least one worksheet should be added to a new workbook. A worksheet is
used to write data into cells:

</p>
<p>
</p><pre>    $worksheet1 = $workbook-&gt;add_worksheet();           # Sheet1
    $worksheet2 = $workbook-&gt;add_worksheet('Foglio2');  # Foglio2
    $worksheet3 = $workbook-&gt;add_worksheet('Data');     # Data
    $worksheet4 = $workbook-&gt;add_worksheet();           # Sheet4
</pre>
<p></p>
<p>
If <code>$sheetname</code> is not specified the default Excel convention will 
be followed, i.e.
Sheet1, Sheet2, etc.

</p>
<p>
The worksheet name must be a valid Excel worksheet name, i.e. it cannot
contain any of the following characters, <code>[ ] : * ? / \</code> and it must 
be less than 32 characters. In addition, you cannot use the
same, case insensitive, <code>$sheetname</code> for more than one worksheet.

</p>
<p>
On systems with <code>perl 5.8</code> and later the 
<code>add_worksheet()</code> method will also handle strings in Perl's 
<code>utf8</code> format.

</p>
<p>
</p><pre>    $worksheet5 = $workbook-&gt;add_worksheet("\x{263a}"); # Smiley
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="add_chart_ext_chart_data_char">add_chart_ext($chart_data, 
$chartname)</a></h2>
<p>
This method is use to include externally generated charts in a
Spreadsheet::WriteExcel file.

</p>
<p>
</p><pre>    my $chart = $workbook-&gt;add_chart_ext('chart01.bin', 'Chart1');
</pre>
<p></p>
<p>
This feature is new and would be best described as experimental. Read 
<code>charts.txt</code> in the charts directory of the distro for a full 
explanation.

</p>
<p>
</p><hr>
<h2><a name="add_format_properties_">add_format(%properties)</a></h2>
<p>
The <code>add_format()</code> 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.

</p>
<p>
</p><pre>    $format1 = $workbook-&gt;add_format(%props); # Set properties at 
creation
    $format2 = $workbook-&gt;add_format();       # Set properties later
</pre>
<p></p>
<p>
See the <a href="#CELL_FORMATTING">CELL FORMATTING</a> section for more details 
about Format properties and how to set them.

</p>
<p>
</p><hr>
<h2><a name="set_custom_color_index_red_">set_custom_color($index, $red, 
$green, $blue)</a></h2>
<p>
The <code>set_custom_color()</code> method can be used to override one of the 
built-in palette values with a
more suitable colour.

</p>
<p>
The value for <code>$index</code> should be in the range 8..63, see <a 
href="#COLOURS_IN_EXCEL">COLOURS IN EXCEL</a>.

</p>
<p>
The default named colours use the following indices:

</p>
<p>
</p><pre>     8   =&gt;   black
     9   =&gt;   white
    10   =&gt;   red
    11   =&gt;   lime
    12   =&gt;   blue
    13   =&gt;   yellow
    14   =&gt;   magenta
    15   =&gt;   cyan
    16   =&gt;   brown
    17   =&gt;   green
    18   =&gt;   navy
    20   =&gt;   purple
    22   =&gt;   silver
    23   =&gt;   gray
    53   =&gt;   orange
</pre>
<p></p>
<p>
A new colour is set using its RGB (red green blue) components. The 
<code>$red</code>, <code>$green</code> and <code>$blue</code> values must be in 
the range 0..255. You can determine the required values
in Excel using the <code>Tools-&gt;Options-&gt;Colors-&gt;Modify</code> dialog.

</p>
<p>
The <code>set_custom_color()</code> workbook method can also be used with a 
HTML style <code>#rrggbb</code> hex value:

</p>
<p>
</p><pre>    $workbook-&gt;set_custom_color(40, 255,  102,  0   ); # Orange
    $workbook-&gt;set_custom_color(40, 0xFF, 0x66, 0x00); # Same thing
    $workbook-&gt;set_custom_color(40, '#FF6600'       ); # Same thing
</pre>
<p></p>
<p>
</p><pre>    my $font = $workbook-&gt;add_format(color =&gt; 40); # Use the 
modified colour
</pre>
<p></p>
<p>
The return value from <code>set_custom_color()</code> is the index of the 
colour that was changed:

</p>
<p>
</p><pre>    my $ferrari = $workbook-&gt;set_custom_color(40, 216, 12, 12);
</pre>
<p></p>
<p>
</p><pre>    my $format  = $workbook-&gt;add_format(
                                        bg_color =&gt; $ferrari,
                                        pattern  =&gt; 1,
                                        border   =&gt; 1
                                      );
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="sheets_0_1_">sheets(0, 1, ...)</a></h2>
<p>
The <code>sheets()</code> method returns a list, or a sliced list, of the 
worksheets in a workbook.

</p>
<p>
If no arguments are passed the method returns a list of all the worksheets
in the workbook. This is useful if you want to repeat an operation on each
worksheet:

</p>
<p>
</p><pre>    foreach $worksheet ($workbook-&gt;sheets()) {
       print $worksheet-&gt;get_name();
    }
</pre>
<p></p>
<p>
You can also specify a slice list to return one or more worksheet objects:

</p>
<p>
</p><pre>    $worksheet = $workbook-&gt;sheets(0);
    $worksheet-&gt;write('A1', "Hello");
</pre>
<p></p>
<p>
Or since return value from <code>sheets()</code> is a reference to a worksheet 
object you can write the above example as:

</p>
<p>
</p><pre>    $workbook-&gt;sheets(0)-&gt;write('A1', "Hello");
</pre>
<p></p>
<p>
The following example returns the first and last worksheet in a workbook:

</p>
<p>
</p><pre>    foreach $worksheet ($workbook-&gt;sheets(0, -1)) {
       # Do something
    }
</pre>
<p></p>
<p>
Array slices are explained in the perldata manpage.

</p>
<p>
</p><hr>
<h2><a name="set_1904_">set_1904()</a></h2>
<p>
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.

</p>
<p>
Spreadsheet::WriteExcel stores dates in the 1900 format by default. If you
wish to change this you can call the <code>set_1904()</code> workbook method. 
You can query the current value by calling the <code>get_1904()</code> workbook 
method. This returns 0 for 1900 and 1 for 1904.

</p>
<p>
See also <a href="#DATES_IN_EXCEL">DATES IN EXCEL</a> for more information 
about working with Excel's date system.

</p>
<p>
In general you probably won't need to use <code>set_1904()</code>.

</p>
<p>
</p><hr>
<h2><a name="set_codepage_codepage_">set_codepage($codepage)</a></h2>
<p>
The default code page or character set used by Spreadsheet::WriteExcel is
ANSI. This is also the default used by Excel for Windows. Occasionally
however it may be necessary to change the code page via the 
<code>set_codepage()</code> method.

</p>
<p>
Changing the code page may be required if your are using
Spreadsheet::WriteExcel on the Macintosh and you are using characters
outside the ASCII 128 character set:

</p>
<p>
</p><pre>    $workbook-&gt;set_codepage(1); # ANSI, MS Windows
    $workbook-&gt;set_codepage(2); # Apple Macintosh
</pre>
<p></p>
<p>
The <code>set_codepage()</code> method is rarely required.

</p>
<p>
</p><hr>
<h1><a name="WORKSHEET_METHODS">WORKSHEET METHODS</a></h1>
<p>
A new worksheet is created by calling the <code>add_worksheet()</code> method 
from a workbook object:

</p>
<p>
</p><pre>    $worksheet1 = $workbook-&gt;add_worksheet();
    $worksheet2 = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
The following methods are available through a new worksheet:

</p>
<p>
</p><pre>    write()
    write_number()
    write_string()
    write_unicode()
    write_unicode_le()
    keep_leading_zeros()
    write_blank()
    write_row()
    write_col()
    write_url()
    write_url_range()
    write_formula()
    store_formula()
    repeat_formula()
    add_write_handler()
    insert_bitmap()
    get_name()
    activate()
    select()
    set_first_sheet()
    protect()
    set_selection()
    set_row()
    set_column()
    outline_settings()
    freeze_panes()
    thaw_panes()
    merge_range()
    set_zoom()
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="Cell_notation">Cell notation</a></h2>
<p>
Spreadsheet::WriteExcel supports two forms of notation to designate the
position of cells: Row-column notation and A1 notation.

</p>
<p>
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:

</p>
<p>
</p><pre>    (0, 0)      # The top left cell in row-column notation.
    ('A1')      # The top left cell in A1 notation.
</pre>
<p></p>
<p>
</p><pre>    (1999, 29)  # Row-column notation.
    ('AD2000')  # The same cell in A1 notation.
</pre>
<p></p>
<p>
Row-column notation is useful if you are referring to cells
programmatically:

</p>
<p>
</p><pre>    for my $i (0 .. 9) {
        $worksheet-&gt;write($i, 0, 'Hello'); # Cells A1 to A10
    }
</pre>
<p></p>
<p>
A1 notation is useful for setting up a worksheet manually and for working
with formulas:

</p>
<p>
</p><pre>    $worksheet-&gt;write('H1', 200);
    $worksheet-&gt;write('H2', '=H1+1');
</pre>
<p></p>
<p>
In formulas and applicable methods you can also use the <code>A:A</code> column 
notation:

</p>
<p>
</p><pre>    $worksheet-&gt;write('A1', '=SUM(B:B)');
</pre>
<p></p>
<p>
The <code>Spreadsheet::WriteExcel::Utility</code> module that is included in 
the distro contains helper functions for dealing
with A1 notation, for example:

</p>
<p>
</p><pre>    use Spreadsheet::WriteExcel::Utility;
</pre>
<p></p>
<p>
</p><pre>    ($row, $col)    = xl_cell_to_rowcol('C2');  # (1, 2)
    $str            = xl_rowcol_to_cell(1, 2);  # C2
</pre>
<p></p>
<p>
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.

</p>
<p>
Note: in Excel it is also possible to use a R1C1 notation. This is not
supported by Spreadsheet::WriteExcel.

</p>
<p>
</p><hr>
<h2><a name="write_row_column_token_fo">write($row, $column, $token, 
$format)</a></h2>
<p>
Excel makes a distinction between data types such as strings, numbers,
blanks, formulas and hyperlinks. To simplify the process of writing data
the <code>write()</code> method acts as a general alias for several more 
specific methods:

</p>
<p>
</p><pre>    write_string()
    write_number()
    write_blank()
    write_formula()
    write_url()
    write_row()
    write_col()
</pre>
<p></p>
<p>
The general rule is that if the data looks like a <em>something</em> then a 
<em>something</em> is written. Here are some examples in both row-column and A1 
notation:

</p>
<p>
</p><pre>                                                      # Same as:
    $worksheet-&gt;write(0, 0, "Hello"                ); # write_string()
    $worksheet-&gt;write(1, 0, 'One'                  ); # write_string()
    $worksheet-&gt;write(2, 0,  2                     ); # write_number()
    $worksheet-&gt;write(3, 0,  3.00001               ); # write_number()
    $worksheet-&gt;write(4, 0,  ""                    ); # write_blank()
    $worksheet-&gt;write(5, 0,  ''                    ); # write_blank()
    $worksheet-&gt;write(6, 0,  undef                 ); # write_blank()
    $worksheet-&gt;write(7, 0                         ); # write_blank()
    $worksheet-&gt;write(8, 0,  'http://www.perl.com/'); # write_url()
    $worksheet-&gt;write('A9',  'ftp://ftp.cpan.org/' ); # write_url()
    $worksheet-&gt;write('A10', 'internal:Sheet1!A1'  ); # write_url()
    $worksheet-&gt;write('A11', 'external:c:\foo.xls' ); # write_url()
    $worksheet-&gt;write('A12', '=A3 + 3*A4'          ); # write_formula()
    $worksheet-&gt;write('A13', '=SIN(PI()/4)'        ); # write_formula()
    $worksheet-&gt;write('A14', address@hidden               ); # write_row()
    $worksheet-&gt;write('A15', address@hidden             ); # write_col()
</pre>
<p></p>
<p>
</p><pre>    # And if the keep_leading_zeros property is set:
    $worksheet-&gt;write('A16,  2                     ); # write_number()
    $worksheet-&gt;write('A17,  02                    ); # write_string()
    $worksheet-&gt;write('A18,  00002                 ); # write_string()
</pre>
<p></p>
<p>
The "looks like" rule is defined by regular expressions:

</p>
<p>
<code>write_number()</code> if <code>$token</code> is a number based on the 
following regex: <code>$token =~ 
/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/</code>.

</p>
<p>
<code>write_string()</code> if <code>keep_leading_zeros()</code> is set and 
<code>$token</code> is an integer with leading zeros based on the following 
regex: <code>$token =~ /^0\d+$/</code>.

</p>
<p>
<code>write_blank()</code> if <code>$token</code> is undef or a blank string: 
<code>undef</code>, <code>""</code> or <code>''</code>.

</p>
<p>
<code>write_url()</code> if <code>$token</code> is a http, https, ftp or mailto 
URL based on the following regexes: <code>$token =~ m|^[fh]tt?ps?://|</code> or 
 <code>$token =~ m|^mailto:|</code>.

</p>
<p>
<code>write_url()</code> if <code>$token</code> is an internal or external 
sheet reference based on the following regex: <code>$token =~ 
m[^(in|ex)ternal:]</code>.

</p>
<p>
<code>write_formula()</code> if the first character of <code>$token</code> is 
<code>"="</code>.

</p>
<p>
<code>write_row()</code> if <code>$token</code> is an array ref.

</p>
<p>
<code>write_col()</code> if <code>$token</code> is an array ref of array refs.

</p>
<p>
<code>write_string()</code> if none of the previous conditions apply.

</p>
<p>
The <code>$format</code> parameter is optional. It should be a valid Format 
object, see <a href="#CELL_FORMATTING">CELL FORMATTING</a>:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_bold();
    $format-&gt;set_color('red');
    $format-&gt;set_align('center');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(4, 0, "Hello", $format ); # Formatted string
</pre>
<p></p>
<p>
The <code>write()</code> method will ignore empty strings or <code>undef</code> 
tokens unless a format is also supplied. As such you needn't worry about
special handling for empty or <code>undef</code> values in your data. See also 
the <code>write_blank()</code> method.

</p>
<p>
One problem with the <code>write()</code> 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
<code>zero(s)</code> will be stripped. You can change this default
behaviour by using the <code>keep_leading_zeros()</code> 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 
<code>keep_leading_zeros()</code> section for a full discussion of this issue.

</p>
<p>
You can also add your own data handlers to the <code>write()</code> method 
using <code>add_write_handler()</code>.

</p>
<p>
On systems with <code>perl 5.8</code> and later the <code>write()</code> method 
will also handle Unicode strings in Perl's <code>utf8</code> format.

</p>
<p>
The <code>write</code> methods return:

</p>
<p>
</p><pre>    0 for success.
   -1 for insufficient number of arguments.
   -2 for row or column out of bounds.
   -3 for string too long.
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="write_number_row_column_num">write_number($row, $column, $number, 
$format)</a></h2>
<p>
Write an integer or a float to the cell specified by <code>$row</code> and 
<code>$column</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;write_number(0, 0,  123456);
    $worksheet-&gt;write_number('A2',  2.3451);
</pre>
<p></p>
<p>
See the note about <a href="#Cell_notation">Cell notation</a>. The 
<code>$format</code> parameter is optional.

</p>
<p>
In general it is sufficient to use the <code>write()</code> method.

</p>
<p>
</p><hr>
<h2><a name="write_string_row_column_str">write_string($row, $column, $string, 
$format)</a></h2>
<p>
Write a string to the cell specified by <code>$row</code> and 
<code>$column</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;write_string(0, 0, "Your text here" );
    $worksheet-&gt;write_string('A2', "or here" );
</pre>
<p></p>
<p>
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.

</p>
<p>
The <code>$format</code> parameter is optional.

</p>
<p>
On systems with <code>perl 5.8</code> and later the <code>write()</code> method 
will also handle strings in Perl's <code>utf8</code> format. With older perls 
you can also write Unicode in <code>UTF16</code> format via the 
<code>write_unicode()</code> method. See also the <code>unicode_*.pl</code> 
programs in the examples directory of the distro.

</p>
<p>
In general it is sufficient to use the <code>write()</code> method. However, 
you may sometimes wish to use the <code>write_string()</code> 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:

</p>
<p>
</p><pre>    # Write as a plain string
    $worksheet-&gt;write_string('A1', '01209');
</pre>
<p></p>
<p>
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 <code>@</code>:

</p>
<p>
</p><pre>    # Format as a string. Doesn't change to a number when edited
    my $format1 = $workbook-&gt;add_format(num_format =&gt; '@');
    $worksheet-&gt;write_string('A2', '01209', $format1);
</pre>
<p></p>
<p>
See also the note about <a href="#Cell_notation">Cell notation</a>.

</p>
<p>
</p><hr>
<h2><a name="write_unicode_row_column_st">write_unicode($row, $column, $string, 
$format)</a></h2>
<p>
This method is used to write Unicode strings to a cell in Excel. It is
functionally the same as the <code>write_string()</code> method except that the 
string should be in UTF-16 Unicode format.

</p>
<p>
<strong>Note</strong>: on systems with <code>perl 5.8</code> and later the 
<code>write()</code> and <code>write_string()</code>methods will also handle 
strings in Perl's <code>utf8</code> format. With older perls you must use the 
<code>write_unicode()</code> method.

</p>
<p>
The Unicode format required by Excel is UTF-16. Additionally 
<code>Spreadsheet::WriteExcel</code> requires that the 16-bit characters are in 
big-endian order. This is
generally referred to as UTF-16BE. To write UTF-16 strings in little-endian
format use the <code>write_unicode_le()</code> method.

</p>
<p>
The following is a simple example showing how to write some Unicode
strings:

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
    use Unicode::Map();
</pre>
<p></p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new('unicode.xls');
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    # Increase the column width for clarity
    $worksheet-&gt;set_column('A:A', 25);
</pre>
<p></p>
<p>
</p><pre>    # Write a Unicode character
    #
    my $smiley = pack "n", 0x263a;
</pre>
<p></p>
<p>
</p><pre>    # Increase the font size for legibility.
    my $big_font = $workbook-&gt;add_format(size =&gt; 72);
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_unicode('A3', $smiley, $big_font);
</pre>
<p></p>
<p>
</p><pre>    # Write a phrase in Cyrillic using a hex-encoded string
    #
    my $uni_str = pack "H*", "042d0442043e0020044404400430043704300020043d" .
                             "043000200440044304410441043a043e043c0021";
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_unicode('A5', $uni_str);
</pre>
<p></p>
<p>
</p><pre>    # Map a string to UTF-16BE using an external module.
    #
    my $map   = Unicode::Map-&gt;new("ISO-8859-1");
    my $utf16 = $map-&gt;to_unicode("Hello world!");
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_unicode('A7', $utf16);
</pre>
<p></p>
<p>
The following is an example of creating an Excel file with some Japanese
text. You will need to have a Unicode font installed, such as <code>Arial 
Unicode MS</code>, to view the results:

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new('unicode.xls');
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    # It is only required to specify a Unicode font via add_format() if
    # you are using Excel 97. For Excel 2000+ the text will display
    # with the default font (if you have Unicode fonts installed).
    #
    my $uni_font  = $workbook-&gt;add_format(font =&gt; 'Arial Unicode MS');
</pre>
<p></p>
<p>
</p><pre>    my $kanji     = pack 'n*', 0x65e5, 0x672c;
    my $katakana  = pack 'n*', 0xff86, 0xff8e, 0xff9d;
    my $hiragana  = pack 'n*', 0x306b, 0x307b, 0x3093;
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_unicode('A1', $kanji,    $uni_font);
    $worksheet-&gt;write_unicode('A2', $katakana, $uni_font);
    $worksheet-&gt;write_unicode('A3', $hiragana, $uni_font);
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write('B1', 'Kanji');
    $worksheet-&gt;write('B2', 'Katakana');
    $worksheet-&gt;write('B3', 'Hiragana');
</pre>
<p></p>
<p>
Note: You can convert ascii encodings to the required UTF-16BE format using
one of the many Unicode modules on CPAN. For example <code>Unicode::Map</code> 
and <code>Unicode::String</code>: <a 
href="http://search.cpan.org/author/MSCHWARTZ/Unicode-Map-0.112/Map.pm";>http://search.cpan.org/author/MSCHWARTZ/Unicode-Map-0.112/Map.pm</a>
and <a 
href="http://search.cpan.org/author/GAAS/Unicode-String-2.06/String.pm";>http://search.cpan.org/author/GAAS/Unicode-String-2.06/String.pm</a>


</p>
<p>
For a full list of the Perl Unicode modules see: <a 
href="http://search.cpan.org/search?query=unicode&amp;mode=all";>http://search.cpan.org/search?query=unicode&amp;mode=all</a>


</p>
<p>
See also the <code>unicode_*.pl</code> programs in the examples directory of 
the distro.

</p>
<p>
</p><hr>
<h2><a name="write_unicode_le_row_column_">write_unicode_le($row, $column, 
$string, $format)</a></h2>
<p>
This method is the same as <code>write_unicode()</code> except that the string 
should be 16-bit characters in little-endian format.
This is generally referred to as UTF-16LE.

</p>
<p>
UTF-16 data can be changed from little-endian to big-endian format (and
vice-versa) as follows:

</p>
<p>
</p><pre>    $utf16 = pack "n*", unpack "v*", $utf16;
</pre>
<p></p>
<p>
Note, it is slightly faster to write little-endian data via
<code>write_unicode_le()</code> than it is to write big-endian data via
<code>write_unicode().</code>

</p>
<p>
</p><hr>
<h2><a name="keep_leading_zeros_">keep_leading_zeros()</a></h2>
<p>
This method changes the default handling of integers with leading zeros
when using the <code>write()</code> method.

</p>
<p>
The <code>write()</code> 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 <code>write_number()</code>. One problem with this approach is that 
occasionally data looks like a
number but you don't want it treated as a number.

</p>
<p>
Zip codes and ID numbers, for example, often start with a leading zero. If
you write this data as a number then the leading <code>zero(s)</code> will
be stripped. This is the also the default behaviour when you enter data
manually in Excel.

</p>
<p>
To get around this you can use one of three options. Write a formatted
number, write the number as a string or use the 
<code>keep_leading_zeros()</code> method to change the default behaviour of 
<code>write()</code>:

</p>
<p>
</p><pre>    # Implicitly write a number, the leading zero is removed: 1209
    $worksheet-&gt;write('A1', '01209');
</pre>
<p></p>
<p>
</p><pre>    # Write a zero padded number using a format: 01209
    my $format1 = $workbook-&gt;add_format(num_format =&gt; '00000');
    $worksheet-&gt;write('A2', '01209', $format1);
</pre>
<p></p>
<p>
</p><pre>    # Write explicitly as a string: 01209
    $worksheet-&gt;write_string('A3', '01209');
</pre>
<p></p>
<p>
</p><pre>    # Write implicitly as a string: 01209
    $worksheet-&gt;keep_leading_zeros();
    $worksheet-&gt;write('A4', '01209');
</pre>
<p></p>
<p>
The above code would generate a worksheet that looked like the following:

</p>
<p>
</p><pre>     -----------------------------------------------------------
    |   |     A     |     B     |     C     |     D     | ...
     -----------------------------------------------------------
    | 1 |      1209 |           |           |           | ...
    | 2 |     01209 |           |           |           | ...
    | 3 | 01209     |           |           |           | ...
    | 4 | 01209     |           |           |           | ...
</pre>
<p></p>
<p>
The examples are on different sides of the cells due to the fact that Excel
displays strings with a left justification and numbers with a right
justification by default. You can change this by using a format to justify
the data, see <a href="#CELL_FORMATTING">CELL FORMATTING</a>.

</p>
<p>
It should be noted that if the user edits the data in examples <code>A3</code> 
and <code>A4</code> the strings will revert back to numbers. Again this is 
Excel's default
behaviour. To avoid this you can use the text format <code>@</code>:

</p>
<p>
</p><pre>    # Format as a string (01209)
    my $format2 = $workbook-&gt;add_format(num_format =&gt; '@');
    $worksheet-&gt;write_string('A5', '01209', $format2);
</pre>
<p></p>
<p>
The <code>keep_leading_zeros()</code> property is off by default. The 
<code>keep_leading_zeros()</code> method takes 0 or 1 as an argument. It 
defaults to 1 if an argument isn't
specified:

</p>
<p>
</p><pre>    $worksheet-&gt;keep_leading_zeros();  # Set on
    $worksheet-&gt;keep_leading_zeros(1); # Set on
    $worksheet-&gt;keep_leading_zeros(0); # Set off
</pre>
<p></p>
<p>
See also the <code>add_write_handler()</code> method.

</p>
<p>
</p><hr>
<h2><a name="write_blank_row_column_form">write_blank($row, $column, 
$format)</a></h2>
<p>
Write a blank cell specified by <code>$row</code> and <code>$column</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;write_blank(0, 0, $format);
</pre>
<p></p>
<p>
This method is used to add formatting to a cell which doesn't contain a
string or number value.

</p>
<p>
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.

</p>
<p>
As such, if you write an empty cell without formatting it is ignored:

</p>
<p>
</p><pre>    $worksheet-&gt;write('A1',  undef, $format); # write_blank()
    $worksheet-&gt;write('A2',  undef         ); # Ignored
</pre>
<p></p>
<p>
This seemingly uninteresting fact means that you can write arrays of data
without special treatment for undef or empty string values.

</p>
<p>
See the note about <a href="#Cell_notation">Cell notation</a>.

</p>
<p>
</p><hr>
<h2><a name="write_row_row_column_array_">write_row($row, $column, $array_ref, 
$format)</a></h2>
<p>
The <code>write_row()</code> method can be used to write a 1D or 2D array of 
data in one go. This is
useful for converting the results of a database query into an Excel
worksheet. You must pass a reference to the array of data rather than the
array itself. The <code>write()</code> method is then called for each element 
of the data. For example:

</p>
<p>
</p><pre>    @array      = ('awk', 'gawk', 'mawk');
    $array_ref  = address@hidden;
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_row(0, 0, $array_ref);
</pre>
<p></p>
<p>
</p><pre>    # The above example is equivalent to:
    $worksheet-&gt;write(0, 0, $array[0]);
    $worksheet-&gt;write(0, 1, $array[1]);
    $worksheet-&gt;write(0, 2, $array[2]);
</pre>
<p></p>
<p>
Note: For convenience the <code>write()</code> method behaves in the same way 
as <code>write_row()</code> if it is passed an array reference. Therefore the 
following two method
calls are equivalent:

</p>
<p>
</p><pre>    $worksheet-&gt;write_row('A1', $array_ref); # Write a row of data
    $worksheet-&gt;write(    'A1', $array_ref); # Same thing
</pre>
<p></p>
<p>
As with all of the write methods the <code>$format</code> parameter is 
optional. If a format is specified it is applied to all the
elements of the data array.

</p>
<p>
Array references within the data will be treated as columns. This allows
you to write 2D arrays of data in one go. For example:

</p>
<p>
</p><pre>    @eec =  (
                ['maggie', 'milly', 'molly', 'may'  ],
                [13,       14,      15,      16     ],
                ['shell',  'star',  'crab',  'stone']
            );
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_row('A1', address@hidden);
</pre>
<p></p>
<p>
Would produce a worksheet as follows:

</p>
<p>
</p><pre>     -----------------------------------------------------------
    |   |    A    |    B    |    C    |    D    |    E    | ...
     -----------------------------------------------------------
    | 1 | maggie  | 13      | shell   | ...     |  ...    | ...
    | 2 | milly   | 14      | star    | ...     |  ...    | ...
    | 3 | molly   | 15      | crab    | ...     |  ...    | ...
    | 4 | may     | 16      | stone   | ...     |  ...    | ...
    | 5 | ...     | ...     | ...     | ...     |  ...    | ...
    | 6 | ...     | ...     | ...     | ...     |  ...    | ...
</pre>
<p></p>
<p>
To write the data in a row-column order refer to the <code>write_col()</code> 
method below.

</p>
<p>
Any <code>undef</code> 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.

</p>
<p>
To find out more about array references refer to <code>perlref</code> and 
<code>perlreftut</code> in the main Perl documentation. To find out more about 
2D arrays or "lists
of lists" refer to <code>perllol</code>.

</p>
<p>
The <code>write_row()</code> 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 <code>write()</code> method above.

</p>
<p>
See also the <code>write_arrays.pl</code> program in the <code>examples</code> 
directory of the distro.

</p>
<p>
The <code>write_row()</code> method allows the following idiomatic conversion 
of a text file to an Excel
file:

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new('file.xls');
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    open INPUT, "file.txt" or die "Couldn't open file: $!";
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write($.-1, 0, [split]) while &lt;INPUT&gt;;
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="write_col_row_column_array_">write_col($row, $column, $array_ref, 
$format)</a></h2>
<p>
The <code>write_col()</code> method can be used to write a 1D or 2D array of 
data in one go. This is
useful for converting the results of a database query into an Excel
worksheet. You must pass a reference to the array of data rather than the
array itself. The <code>write()</code> method is then called for each element 
of the data. For example:

</p>
<p>
</p><pre>    @array      = ('awk', 'gawk', 'mawk');
    $array_ref  = address@hidden;
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_col(0, 0, $array_ref);
</pre>
<p></p>
<p>
</p><pre>    # The above example is equivalent to:
    $worksheet-&gt;write(0, 0, $array[0]);
    $worksheet-&gt;write(1, 0, $array[1]);
    $worksheet-&gt;write(2, 0, $array[2]);
</pre>
<p></p>
<p>
As with all of the write methods the <code>$format</code> parameter is 
optional. If a format is specified it is applied to all the
elements of the data array.

</p>
<p>
Array references within the data will be treated as rows. This allows you
to write 2D arrays of data in one go. For example:

</p>
<p>
</p><pre>    @eec =  (
                ['maggie', 'milly', 'molly', 'may'  ],
                [13,       14,      15,      16     ],
                ['shell',  'star',  'crab',  'stone']
            );
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_col('A1', address@hidden);
</pre>
<p></p>
<p>
Would produce a worksheet as follows:

</p>
<p>
</p><pre>     -----------------------------------------------------------
    |   |    A    |    B    |    C    |    D    |    E    | ...
     -----------------------------------------------------------
    | 1 | maggie  | milly   | molly   | may     |  ...    | ...
    | 2 | 13      | 14      | 15      | 16      |  ...    | ...
    | 3 | shell   | star    | crab    | stone   |  ...    | ...
    | 4 | ...     | ...     | ...     | ...     |  ...    | ...
    | 5 | ...     | ...     | ...     | ...     |  ...    | ...
    | 6 | ...     | ...     | ...     | ...     |  ...    | ...
</pre>
<p></p>
<p>
To write the data in a column-row order refer to the <code>write_row()</code> 
method above.

</p>
<p>
Any <code>undef</code> 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.

</p>
<p>
As noted above the <code>write()</code> method can be used as a synonym for 
<code>write_row()</code> and <code>write_row()</code> handles nested array refs 
as columns. Therefore, the following two method
calls are equivalent although the more explicit call to 
<code>write_col()</code> would be preferable for maintainability:

</p>
<p>
</p><pre>    $worksheet-&gt;write_col('A1', $array_ref    ); # Write a column 
of data
    $worksheet-&gt;write(    'A1', [ $array_ref ]); # Same thing
</pre>
<p></p>
<p>
To find out more about array references refer to <code>perlref</code> and 
<code>perlreftut</code> in the main Perl documentation. To find out more about 
2D arrays or "lists
of lists" refer to <code>perllol</code>.

</p>
<p>
The <code>write_col()</code> 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 <code>write()</code> method above.

</p>
<p>
See also the <code>write_arrays.pl</code> program in the <code>examples</code> 
directory of the distro.

</p>
<p>
</p><hr>
<h2><a name="write_date_time_row_col_dat">write_date_time($row, $col, 
$date_string, $format)</a></h2>
<p>
The <code>write_date_time()</code> method can be used to write a date or time 
to the cell specified by <code>$row</code> and <code>$column</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;write_date_time('A1', '2004-05-13T23:20', 
$date_format);
</pre>
<p></p>
<p>
The <code>$date_string</code> should be in the following format:

</p>
<p>
</p><pre>    yyyy-mm-ddThh:mm:ss.sss
</pre>
<p></p>
<p>
This conforms to am ISO8601 date but it should be noted that the full range
of ISO8601 formats are not supported.

</p>
<p>
The following variations on the <code>$date_string</code> parameter are 
permitted:

</p>
<p>
</p><pre>    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
</pre>
<p></p>
<p>
Note that the <code>T</code> is required in all cases.

</p>
<p>
A date should always have a <code>$format</code>, otherwise it will appear as a 
number, see <a href="#DATES_IN_EXCEL">DATES IN EXCEL</a> and <a 
href="#CELL_FORMATTING">CELL FORMATTING</a>. Here is a typical example:

</p>
<p>
</p><pre>    my $date_format = $workbook-&gt;add_format(num_format =&gt; 
'mm/dd/yy');
    $worksheet-&gt;write_date_time('A1', '2004-05-13T23:20', $date_format);
</pre>
<p></p>
<p>
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.

</p>
<p>
See also the date_time.pl program in the <code>examples</code> directory of the 
distro.

</p>
<p>
</p><hr>
<h2><a name="write_url_row_col_url_str">write_url($row, $col, $url, $string, 
$format)</a></h2>
<p>
Write a hyperlink to a URL in the cell specified by <code>$row</code> and 
<code>$column</code>. The hyperlink is comprised of two elements: the visible 
label and the
invisible link. The visible label is the same as the link unless an
alternative string is specified. The parameters <code>$string</code> and the 
<code>$format</code> are optional and their position is interchangeable.

</p>
<p>
The label is written using the <code>write_string()</code> method. Therefore 
the 255 characters string limit applies to the label: the
URL can be any length.

</p>
<p>
There are four web style URI's supported: <code>http://</code>, 
<code>https://</code>, <code>ftp://</code> and  <code>mailto:</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;write_url(0, 0,  'ftp://www.perl.org/'              
    );
    $worksheet-&gt;write_url(1, 0,  'http://www.perl.com/', 'Perl home'    );
    $worksheet-&gt;write_url('A3',  'http://www.perl.com/', $format        );
    $worksheet-&gt;write_url('A4',  'http://www.perl.com/', 'Perl', $format);
    $worksheet-&gt;write_url('A5',  'mailto:address@hidden'            );
</pre>
<p></p>
<p>
There are two local URIs supported: <code>internal:</code> and 
<code>external:</code>. These are used for hyperlinks to internal worksheet 
references or
external workbook and worksheet references:

</p>
<p>
</p><pre>    $worksheet-&gt;write_url('A6',  'internal:Sheet2!A1'               
    );
    $worksheet-&gt;write_url('A7',  'internal:Sheet2!A1',   $format        );
    $worksheet-&gt;write_url('A8',  'internal:Sheet2!A1:B2'                );
    $worksheet-&gt;write_url('A9',  q{internal:'Sales Data'!A1}            );
    $worksheet-&gt;write_url('A10', 'external:c:\temp\foo.xls'             );
    $worksheet-&gt;write_url('A11', 'external:c:\temp\foo.xls#Sheet2!A1'   );
    $worksheet-&gt;write_url('A12', 'external:..\..\..\foo.xls'            );
    $worksheet-&gt;write_url('A13', 'external:..\..\..\foo.xls#Sheet2!A1'  );
    $worksheet-&gt;write_url('A13', 'external:\\\\NETWORK\share\foo.xls'   );
</pre>
<p></p>
<p>
All of the these URI types are recognised by the <code>write()</code> method, 
see above.

</p>
<p>
Worksheet references are typically of the form <code>Sheet1!A1</code>. You can 
also refer to a worksheet range using the standard Excel
notation: <code>Sheet1!A1:B2</code>.

</p>
<p>
In external links the workbook and worksheet name must be separated by the 
<code>#</code> character: <code>external:Workbook.xls#Sheet1!A1'</code>.

</p>
<p>
You can also link to a named range in the target worksheet. For example say
you have a named range called <code>my_name</code> in the workbook 
<code>c:\temp\foo.xls</code> you could link to it as follows:

</p>
<p>
</p><pre>    $worksheet-&gt;write_url('A14', 
'external:c:\temp\foo.xls#my_name');
</pre>
<p></p>
<p>
Note, you cannot currently create named ranges with 
<code>Spreadsheet::WriteExcel</code>.

</p>
<p>
Excel requires that worksheet names containing spaces or non alphanumeric
characters are single quoted as follows <code>'Sales Data'!A1</code>. If you 
need to do this in a single quoted string then you can either
escape the single quotes <code>\'</code> or use the quote operator 
<code>q{}</code> as described in <code>perlop</code> in the main Perl 
documentation.

</p>
<p>
Links to network files are also supported. MS/Novell Network files normally
begin with two back slashes as follows <code>\\NETWORK\etc</code>. In order to 
generate this in a single or double quoted string you will
have to escape the backslashes,  <code>'\\\\NETWORK\etc'</code>.

</p>
<p>
If you are using double quote strings then you should be careful to escape
anything that looks like a metacharacter. For more information see 
<code>perlfaq5: Why can't I use "C:\temp\foo" in DOS paths?</code>.

</p>
<p>
Finally, you can avoid most of these quoting problems by using forward
slashes. These are translated internally to backslashes:

</p>
<p>
</p><pre>    $worksheet-&gt;write_url('A14', "external:c:/temp/foo.xls"         
    );
    $worksheet-&gt;write_url('A15', 'external://NETWORK/share/foo.xls'     );
</pre>
<p></p>
<p>
See also, the note about <a href="#Cell_notation">Cell notation</a>.

</p>
<p>
</p><hr>
<h2><a name="write_url_range_row1_col1_r">write_url_range($row1, $col1, $row2, 
$col2, $url, $string, $format)</a></h2>
<p>
This method is essentially the same as the <code>write_url()</code> method 
described above. The main difference is that you can specify a link
for a range of cells:

</p>
<p>
</p><pre>    $worksheet-&gt;write_url(0, 0, 0, 3, 'ftp://www.perl.org/'         
     );
    $worksheet-&gt;write_url(1, 0, 0, 3, 'http://www.perl.com/', 'Perl home');
    $worksheet-&gt;write_url('A3:D3',    'internal:Sheet2!A1'               );
    $worksheet-&gt;write_url('A4:D4',    'external:c:\temp\foo.xls'         );
</pre>
<p></p>
<p>
This method is generally only required when used in conjunction with merged
cells. See the <code>merge_range()</code> method and the <code>merge</code> 
property of a Format object, <a href="#CELL_FORMATTING">CELL FORMATTING</a>.

</p>
<p>
There is no way to force this behaviour through the <code>write()</code> method.

</p>
<p>
The parameters <code>$string</code> and the <code>$format</code> are optional 
and their position is interchangeable. However, they are
applied only to the first cell in the range.

</p>
<p>
See also, the note about <a href="#Cell_notation">Cell notation</a>.

</p>
<p>
</p><hr>
<h2><a name="write_formula_row_column_fo">write_formula($row, $column, 
$formula, $format)</a></h2>
<p>
Write a formula or function to the cell specified by <code>$row</code> and 
<code>$column</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;write_formula(0, 0, '=$B$3 + B4'  );
    $worksheet-&gt;write_formula(1, 0, '=SIN(PI()/4)');
    $worksheet-&gt;write_formula(2, 0, '=SUM(B1:B5)' );
    $worksheet-&gt;write_formula('A4', '=IF(A3&gt;1,"Yes", "No")'   );
    $worksheet-&gt;write_formula('A5', '=AVERAGE(1, 2, 3, 4)'    );
    $worksheet-&gt;write_formula('A6', '=DATEVALUE("1-Jan-2001")');
</pre>
<p></p>
<p>
See the note about <a href="#Cell_notation">Cell notation</a>. For more 
information about writing Excel formulas see <a 
href="#FORMULAS_AND_FUNCTIONS_IN_EXCEL">FORMULAS AND FUNCTIONS IN EXCEL</a>



</p>
<p>
See also the section "Improving performance when working with formulas" and
the <code>store_formula()</code> and <code>repeat_formula()</code> methods.

</p>
<p>
</p><hr>
<h2><a name="store_formula_formula_">store_formula($formula)</a></h2>
<p>
The <code>store_formula()</code> method is used in conjunction with 
<code>repeat_formula()</code> to speed up the generation of repeated formulas. 
See "Improving performance
when working with formulas" in <a 
href="#FORMULAS_AND_FUNCTIONS_IN_EXCEL">FORMULAS AND FUNCTIONS IN EXCEL</a>.

</p>
<p>
The <code>store_formula()</code> method pre-parses a textual representation of 
a formula and stores it for
use at a later stage by the <code>repeat_formula()</code> method.

</p>
<p>
<code>store_formula()</code> carries the same speed penalty as 
<code>write_formula()</code>. However, in practice it will be used less 
frequently.

</p>
<p>
The return value of this method is a scalar that can be thought of as a
reference to a formula.

</p>
<p>
</p><pre>    my $sin = $worksheet-&gt;store_formula('=SIN(A1)');
    my $cos = $worksheet-&gt;store_formula('=COS(A1)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;repeat_formula('B1', $sin, $format, 'A1', 'A2');
    $worksheet-&gt;repeat_formula('C1', $cos, $format, 'A1', 'A2');
</pre>
<p></p>
<p>
Although <code>store_formula()</code> is a worksheet method the return value 
can be used in any worksheet:

</p>
<p>
</p><pre>    my $now = $worksheet-&gt;store_formula('=NOW()');
</pre>
<p></p>
<p>
</p><pre>    $worksheet1-&gt;repeat_formula('B1', $now);
    $worksheet2-&gt;repeat_formula('B1', $now);
    $worksheet3-&gt;repeat_formula('B1', $now);
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="repeat_formula_row_col_form">repeat_formula($row, $col, $formula, 
$format, ($pattern =&gt; $replace, ...))</a></h2>
<p>
The <code>repeat_formula()</code> method is used in conjunction with 
<code>store_formula()</code> to speed up the generation of repeated formulas. 
See "Improving performance
when working with formulas" in <a 
href="#FORMULAS_AND_FUNCTIONS_IN_EXCEL">FORMULAS AND FUNCTIONS IN EXCEL</a>.

</p>
<p>
In many respects <code>repeat_formula()</code> behaves like 
<code>write_formula()</code> except that it is significantly faster.

</p>
<p>
The <code>repeat_formula()</code> method creates a new formula based on the 
pre-parsed tokens returned by <code>store_formula()</code>. The new formula is 
generated by substituting <code>$pattern</code>, <code>$replace</code> pairs in 
the stored formula:

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=A1 * 3 + 50');
</pre>
<p></p>
<p>
</p><pre>    for my $row (0..99) {
        $worksheet-&gt;repeat_formula($row, 1, $formula, $format, 'A1', 
'A'.($row +1));
    }
</pre>
<p></p>
<p>
It should be noted that <code>repeat_formula()</code> doesn't modify the 
tokens. In the above example the substitution is always
made against the original token, <code>A1</code>, which doesn't change.

</p>
<p>
As usual, you can use <code>undef</code> if you don't wish to specify a 
<code>$format</code>:

</p>
<p>
</p><pre>    $worksheet-&gt;repeat_formula('B2', $formula, $format, 'A1', 'A2');
    $worksheet-&gt;repeat_formula('B3', $formula, undef,   'A1', 'A3');
</pre>
<p></p>
<p>
The substitutions are made from left to right and you can use as many 
<code>$pattern</code>, <code>$replace</code> pairs as you need. However, each 
substitution is made only once:

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=A1 + A1');
</pre>
<p></p>
<p>
</p><pre>    # Gives '=B1 + A1'
    $worksheet-&gt;repeat_formula('B1', $formula, undef, 'A1', 'B1');
</pre>
<p></p>
<p>
</p><pre>    # Gives '=B1 + B1'
    $worksheet-&gt;repeat_formula('B2', $formula, undef, ('A1', 'B1') x 2);
</pre>
<p></p>
<p>
Since the <code>$pattern</code> is interpolated each time that it is used it is 
worth using the <code>qr</code> operator to quote the pattern. The 
<code>qr</code> operator is explained in the <code>perlop</code> man page.

</p>
<p>
</p><pre>    $worksheet-&gt;repeat_formula('B1', $formula, $format, qr/A1/, 
'A2');
</pre>
<p></p>
<p>
Care should be taken with the values that are substituted. The formula
returned by <code>repeat_formula()</code> contains several other tokens in 
addition to those in the formula and these
might also match the pattern that you are trying to replace. In particular
you should avoid substituting a single 0, 1, 2 or 3.

</p>
<p>
You should also be careful to avoid false matches. For example the
following snippet is meant to change the stored formula in steps from <code>=A1 
+ SIN(A1)</code> to <code>=A10 + SIN(A10)</code>.

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=A1 + SIN(A1)');
</pre>
<p></p>
<p>
</p><pre>    for my $row (1 .. 10) {
        $worksheet-&gt;repeat_formula($row -1, 1, $formula, undef,
                                    qw/A1/, 'A' . $row,   #! Bad.
                                    qw/A1/, 'A' . $row    #! Bad.
                                  );
    }
</pre>
<p></p>
<p>
However it contains a bug. In the last iteration of the loop when 
<code>$row</code> is 10 the following substitutions will occur:

</p>
<p>
</p><pre>    s/A1/A10/;    changes    =A1 + SIN(A1)     to    =A10 + SIN(A1)
    s/A1/A10/;    changes    =A10 + SIN(A1)    to    =A100 + SIN(A1) # !!
</pre>
<p></p>
<p>
The solution in this case is to use a more explicit match such as 
<code>qw/^A1$/</code>:

</p>
<p>
</p><pre>        $worksheet-&gt;repeat_formula($row -1, 1, $formula, undef,
                                    qw/^A1$/, 'A' . $row,
                                    qw/^A1$/, 'A' . $row
                                  );
</pre>
<p></p>
<p>
Another similar problem occurs due to the fact that substitutions are made
in order. For example the following snippet is meant to change the stored
formula from <code>=A10 + A11</code>  to <code>=A11 + A12</code>:

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=A10 + A11');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;repeat_formula('A1', $formula, undef,
                                qw/A10/, 'A11',   #! Bad.
                                qw/A11/, 'A12'    #! Bad.
                              );
</pre>
<p></p>
<p>
However, the actual substitution yields <code>=A12 + A11</code>:

</p>
<p>
</p><pre>    s/A10/A11/;    changes    =A10 + A11    to    =A11 + A11
    s/A11/A12/;    changes    =A11 + A11    to    =A12 + A11 # !!
</pre>
<p></p>
<p>
The solution here would be to reverse the order of the substitutions or to
start with a stored formula that won't yield a false match such as <code>=X10 + 
Y11</code>:

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=X10 + Y11');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;repeat_formula('A1', $formula, undef,
                                qw/X10/, 'A11',
                                qw/Y11/, 'A12'
                              );
</pre>
<p></p>
<p>
If you think that you have a problem related to a false match you can check
the tokens that you are substituting against as follows.

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=A1*5+4');
    print "@$formula\n";
</pre>
<p></p>
<p>
See also the <code>repeat.pl</code> program in the <code>examples</code> 
directory of the distro.

</p>
<p>
</p><hr>
<h2><a name="write_comment_row_column_st">write_comment($row, $column, 
$string)</a></h2>
<p>
<strong>NOTE: this method is not available in this release. Use the 1.xx 
versions of this module if you need this feature</strong>.

</p>
<p>
The <code>write_comment()</code> method is used to add a comment to a cell. A 
cell comment is indicated in
Excel by a small red triangle in the upper right-hand corner of the cell.
Moving the cursor over the red triangle will cause the comment to appear.

</p>
<p>
The following example shows how to add a comment to a cell:

</p>
<p>
</p><pre>    $worksheet-&gt;write("C3", "Hello");
    $worksheet-&gt;write_comment("C3", "This is a comment.");
</pre>
<p></p>
<p>
The cell comment can be up to 30,000 characters in length.

</p>
<p>
</p><hr>
<h2><a name="add_write_handler_re_code_ref">add_write_handler($re, 
$code_ref)</a></h2>
<p>
This method is used to extend the Spreadsheet::WriteExcel
<code>write()</code> method to handle user defined data.

</p>
<p>
If you refer to the section on <code>write()</code> above you will see that it 
acts as an alias for several more specific <code>write_*</code> methods. 
However, it doesn't always act in exactly the way that you would
like it to.

</p>
<p>
One solution is to filter the input data yourself and call the appropriate 
<code>write_*</code> method. Another approach is to use the 
<code>add_write_handler()</code> method to add your own automated behaviour to 
<code>write()</code>.

</p>
<p>
The <code>add_write_handler()</code> method take two arguments, 
<code>$re</code>, a regular expression to match incoming data and 
<code>$code_ref</code> a callback function to handle the matched data:

</p>
<p>
</p><pre>    $worksheet-&gt;add_write_handler(qr/^\d\d\d\d$/, \&amp;my_write);
</pre>
<p></p>
<p>
(In the these examples the <code>qr</code> operator is used to quote the 
regular expression strings, see <em>perlop</em> for more details).

</p>
<p>
The method is use 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:

</p>
<p>
</p><pre>    $worksheet-&gt;add_write_handler(qr/^\d{7}$/, \&amp;write_my_id);
</pre>
<p></p>
<p>
</p><pre>    sub write_my_id {
        my $worksheet = shift;
        return $worksheet-&gt;write_string(@_);
    }
</pre>
<p></p>
<p>
* You could also use the <code>keep_leading_zeros()</code> method for this.

</p>
<p>
Then if you call <code>write()</code> with an appropriate string it will be 
handled automatically:

</p>
<p>
</p><pre>    # Writes 0000000. It would normally be written as a number; 0.
    $worksheet-&gt;write('A1', '0000000');
</pre>
<p></p>
<p>
The callback function will receive a reference to the calling worksheet and
all of the other arguments that were passed to <code>write()</code>. The 
callback will see an <code>@_</code> argument list that looks like the 
following:

</p>
<p>
</p><pre>    $_[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 argruments.
    ...
</pre>
<p></p>
<p>
</p><pre>    *  It is good style to shift this off the list so the @_ is the 
same
       as the argument list seen by write().
</pre>
<p></p>
<p>
Your callback should <code>return()</code> the return value of the 
<code>write_*</code> method that was called or <code>undef</code> to indicate 
that you rejected the match and want <code>write()</code> to continue as normal.

</p>
<p>
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:

</p>
<p>
</p><pre>    sub write_my_id {
        my $worksheet = shift;
        my $col       = $_[1];
</pre>
<p></p>
<p>
</p><pre>        if ($col == 0) {
            return $worksheet-&gt;write_string(@_);
        }
        else {
            # Reject the match and return control to write()
            return undef;
        }
    }
</pre>
<p></p>
<p>
Now, you will get different behaviour for the first column and other
columns:

</p>
<p>
</p><pre>    $worksheet-&gt;write('A1', '0000000'); # Writes 0000000
    $worksheet-&gt;write('B1', '0000000'); # Writes 0
</pre>
<p></p>
<p>
You may add more than one handler in which case they will be called in the
order that they were added.

</p>
<p>
Note, the <code>add_write_handler()</code> method is particularly suited for 
handling dates.

</p>
<p>
See the <code>write_handler 1-4</code> programs in the <code>examples</code> 
directory for further examples.

</p>
<p>
</p><hr>
<h2><a name="insert_bitmap_row_col_filen">insert_bitmap($row, $col, $filename, 
$x, $y, $scale_x, $scale_y)</a></h2>
<p>
This method can be used to insert a bitmap into a worksheet. The bitmap
must be a 24 bit, true colour, bitmap. No other format is supported. The 
<code>$x</code>, <code>$y</code>, <code>$scale_x</code> and 
<code>$scale_y</code> parameters are optional.

</p>
<p>
</p><pre>    $worksheet1-&gt;insert_bitmap('A1', 'perl.bmp');
    $worksheet2-&gt;insert_bitmap('A1', '../images/perl.bmp');
    $worksheet3-&gt;insert_bitmap('A1', '.c:\images\perl.bmp');
</pre>
<p></p>
<p>
Note: you must call <code>set_row()</code> or <code>set_column()</code> before 
<code>insert_bitmap()</code> if you wish to change the default dimensions of 
any of the rows or columns
that the images 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 <code>set_row()</code> if it contains a font size that will change 
the row height.

</p>
<p>
The parameters <code>$x</code> and <code>$y</code> can be used to specify an 
offset from the top left hand corner of the cell
specified by <code>$row</code> and <code>$col</code>. The offset values are in 
pixels.

</p>
<p>
</p><pre>    $worksheet1-&gt;insert_bitmap('A1', 'perl.bmp', 32, 10);
</pre>
<p></p>
<p>
The default width of a cell is 63 pixels. The default height of a cell is
17 pixels. The pixels offsets can be calculated using the following
relationships:

</p>
<p>
</p><pre>    Wp = int(12We)   if We &lt;  1
    Wp = int(7We +5) if We &gt;= 1
    Hp = int(4/3He)
</pre>
<p></p>
<p>
</p><pre>    where:
    We is the cell width in Excels units
    Wp is width in pixels
    He is the cell height in Excels units
    Hp is height in pixels
</pre>
<p></p>
<p>
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.

</p>
<p>
The parameters <code>$scale_x</code> and <code>$scale_y</code> can be used to 
scale the inserted image horizontally and vertically:

</p>
<p>
</p><pre>    # Scale the inserted image: width x 2.0, height x 0.8
    $worksheet-&gt;insert_bitmap('A1', 'perl.bmp', 0, 0, 2, 0.8);
</pre>
<p></p>
<p>
Note: although Excel allows you to import several graphics formats such as
gif, jpeg, png and eps these are converted internally into a proprietary
format. One of the few non-proprietary formats that Excel supports is 24
bit, true colour, bitmaps. Therefore if you wish to use images in any other
format you must first use an external application such as the ImageMagick 
<em>convert</em> utility to convert them to 24 bit bitmaps.

</p>
<p>
</p><pre>    convert test.png test.bmp
</pre>
<p></p>
<p>
A later release will support the use of file handles and pre-encoded bitmap
strings.

</p>
<p>
See also the <code>images.pl</code> program in the <code>examples</code> 
directory of the distro.

</p>
<p>
</p><hr>
<h2><a name="get_name_">get_name()</a></h2>
<p>
The <code>get_name()</code> method is used to retrieve the name of a worksheet. 
For example:

</p>
<p>
</p><pre>    foreach my $sheet ($workbook-&gt;sheets()) {
        print $sheet-&gt;get_name();
    }
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="activate_">activate()</a></h2>
<p>
The <code>activate()</code> method is used to specify which worksheet is 
initially visible in a
multi-sheet workbook:

</p>
<p>
</p><pre>    $worksheet1 = $workbook-&gt;add_worksheet('To');
    $worksheet2 = $workbook-&gt;add_worksheet('the');
    $worksheet3 = $workbook-&gt;add_worksheet('wind');
</pre>
<p></p>
<p>
</p><pre>    $worksheet3-&gt;activate();
</pre>
<p></p>
<p>
This is similar to the Excel VBA activate method. More than one worksheet
can be selected via the <code>select()</code> method, however only one 
worksheet can be active. The default value is the
first worksheet.

</p>
<p>
</p><hr>
<h2><a name="select_">select()</a></h2>
<p>
The <code>select()</code> method is used to indicate that a worksheet is 
selected in a multi-sheet
workbook:

</p>
<p>
</p><pre>    $worksheet1-&gt;activate();
    $worksheet2-&gt;select();
    $worksheet3-&gt;select();
</pre>
<p></p>
<p>
A selected worksheet has its tab highlighted. Selecting worksheets is a way
of grouping them together so that, for example, several worksheets could be
printed in one go. A worksheet that has been activated via the 
<code>activate()</code> method will also appear as selected. You probably won't 
need to use the <code>select()</code> method very often.

</p>
<p>
</p><hr>
<h2><a name="set_first_sheet_">set_first_sheet()</a></h2>
<p>
The <code>activate()</code> 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 <code>set_first_sheet()</code>:

</p>
<p>
</p><pre>    for (1..20) {
        $workbook-&gt;add_worksheet;
    }
</pre>
<p></p>
<p>
</p><pre>    $worksheet21 = $workbook-&gt;add_worksheet();
    $worksheet22 = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    $worksheet21-&gt;set_first_sheet();
    $worksheet22-&gt;activate();
</pre>
<p></p>
<p>
This method is not required very often. The default value is the first
worksheet.

</p>
<p>
</p><hr>
<h2><a name="protect_password_">protect($password)</a></h2>
<p>
The <code>protect()</code> method is used to protect a worksheet from 
modification:

</p>
<p>
</p><pre>    $worksheet-&gt;protect();
</pre>
<p></p>
<p>
It can be turned off in Excel via the <code>Tools-&gt;Protection-&gt;Unprotect 
Sheet</code> menu command.

</p>
<p>
The <code>protect()</code> method also has the effect of enabling a cell's 
<code>locked</code> and <code>hidden</code> properties if they have been set. A 
"locked" cell cannot be edited. A
"hidden" cell will display the results of a formula but not the formula
itself. In Excel a cell's locked property is on by default.

</p>
<p>
</p><pre>    # Set some format properties
    my $unlocked  = $workbook-&gt;add_format(locked =&gt; 0);
    my $hidden    = $workbook-&gt;add_format(hidden =&gt; 1);
</pre>
<p></p>
<p>
</p><pre>    # Enable worksheet protection
    $worksheet-&gt;protect();
</pre>
<p></p>
<p>
</p><pre>    # This cell cannot be edited, it is locked by default
    $worksheet-&gt;write('A1', '=1+2');
</pre>
<p></p>
<p>
</p><pre>    # This cell can be edited
    $worksheet-&gt;write('A2', '=1+2', $unlocked);
</pre>
<p></p>
<p>
</p><pre>    # The formula in this cell isn't visible
    $worksheet-&gt;write('A3', '=1+2', $hidden);
</pre>
<p></p>
<p>
See also the <code>set_locked</code> and <code>set_hidden</code> format methods 
in <a href="#CELL_FORMATTING">CELL FORMATTING</a>.

</p>
<p>
You can optionally add a password to the worksheet protection:

</p>
<p>
</p><pre>    $worksheet-&gt;protect('drowssap');
</pre>
<p></p>
<p>
Note, the worksheet level password in Excel provides very weak protection.
It does not encrypt your data in any way and it is very easy to deactivate.
Therefore, do not use the above method if you wish to protect sensitive
data or calculations. However, before you get worried, Excel's own workbook
level password protection does provide strong encryption in Excel 97+. For
technical reasons this will never be supported by 
<code>Spreadsheet::WriteExcel</code>.

</p>
<p>
</p><hr>
<h2><a name="set_selection_first_row_first">set_selection($first_row, 
$first_col, $last_row, $last_col)</a></h2>
<p>
This method can be used to specify which cell or cells are selected in a
worksheet. The most common requirement is to select a single cell, in which
case <code>$last_row</code> and <code>$last_col</code> can be omitted. The 
active cell within a selected range is determined by
the order in which <code>$first</code> and <code>$last</code> are specified. It 
is also possible to specify a cell or a range using A1
notation. See the note about <a href="#Cell_notation">Cell notation</a>.

</p>
<p>
Examples:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_selection(3, 3);       # 1. Cell D4.
    $worksheet2-&gt;set_selection(3, 3, 6, 6); # 2. Cells D4 to G7.
    $worksheet3-&gt;set_selection(6, 6, 3, 3); # 3. Cells G7 to D4.
    $worksheet4-&gt;set_selection('D4');       # Same as 1.
    $worksheet5-&gt;set_selection('D4:G7');    # Same as 2.
    $worksheet6-&gt;set_selection('G7:D4');    # Same as 3.
</pre>
<p></p>
<p>
The default cell selections is (0, 0), 'A1'.

</p>
<p>
</p><hr>
<h2><a name="set_row_row_height_format_">set_row($row, $height, $format, 
$hidden, $level)</a></h2>
<p>
This method can be used to change the default properties of a row. All
parameters apart from <code>$row</code> are optional.

</p>
<p>
The most common use for this method is to change the height of a row:

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(0, 20); # Row 1 height set to 20
</pre>
<p></p>
<p>
If you wish to set the format without changing the height you can pass 
<code>undef</code> as the height parameter:

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(0, undef, $format);
</pre>
<p></p>
<p>
The <code>$format</code> parameter will be applied to any cells in the row that 
don't have a format.
For example

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(0, undef, $format1);    # Set the format 
for row 1
    $worksheet-&gt;write('A1', "Hello");           # Defaults to $format1
    $worksheet-&gt;write('B1', "Hello", $format2); # Keeps $format2
</pre>
<p></p>
<p>
If you wish to define a row format in this way you should call the method
before any calls to <code>write()</code>. Calling it afterwards will overwrite 
any format that was previously
specified.

</p>
<p>
The <code>$hidden</code> parameter should be set to 1 if you wish to hide a 
row. This can be used,
for example, to hide intermediary steps in a complicated calculation:

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(0, 20,    $format, 1);
    $worksheet-&gt;set_row(1, undef, undef,   1);
</pre>
<p></p>
<p>
The <code>$level</code> parameter is used to set the outline level of the row. 
Outlines are
described in <a href="#OUTLINES_AND_GROUPING_IN_EXCEL">OUTLINES AND GROUPING IN 
EXCEL</a>. Adjacent rows with the same outline level are grouped together into a
single outline.

</p>
<p>
The following example sets an outline level of 1 for rows 1 and 2
(zero-indexed):

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(1, undef, undef, 0, 1);
    $worksheet-&gt;set_row(2, undef, undef, 0, 1);
</pre>
<p></p>
<p>
The <code>$hidden</code> parameter can also be used to collapse outlined rows 
when used in
conjunction with the <code>$level</code> parameter.

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(1, undef, undef, 1, 1);
    $worksheet-&gt;set_row(2, undef, undef, 1, 1);
</pre>
<p></p>
<p>
Excel allows up to 7 outline levels. Therefore the <code>$level</code> 
parameter should be in the range <code>0 &lt;= $level &lt;= 7</code>.

</p>
<p>
</p><hr>
<h2><a name="set_column_first_col_last_col">set_column($first_col, $last_col, 
$width, $format, $hidden, $level)</a></h2>
<p>
This method can be used to change the default properties of a single column
or a range of columns. All parameters apart from <code>$first_col</code> and 
<code>$last_col</code> are optional.

</p>
<p>
If <code>set_column()</code> is applied to a single column the value of 
<code>$first_col</code> and <code>$last_col</code> should be the same. It is 
also possible to specify a column range using the
form of A1 notation used for columns. See the note about <a 
href="#Cell_notation">Cell notation</a>.

</p>
<p>
Examples:

</p>
<p>
</p><pre>    $worksheet-&gt;set_column(0, 0,  20); # Column  A   width set to 20
    $worksheet-&gt;set_column(1, 3,  30); # Columns B-D width set to 30
    $worksheet-&gt;set_column('E:E', 20); # Column  E   width set to 20
    $worksheet-&gt;set_column('F:H', 30); # Columns F-H width set to 30
</pre>
<p></p>
<p>
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
Arial 10. Unfortunately, there is no way to specify "AutoFit" for a column
in the Excel file format. This feature is only available at runtime from
within Excel.

</p>
<p>
As usual the <code>$format</code> parameter is optional, for additional 
information, see <a href="#CELL_FORMATTING">CELL FORMATTING</a>. If you wish to 
set the format without changing the width you can pass <code>undef</code> as 
the width parameter:

</p>
<p>
</p><pre>    $worksheet-&gt;set_column(0, 0, undef, $format);
</pre>
<p></p>
<p>
The <code>$format</code> parameter will be applied to any cells in the column 
that don't have a
format. For example

</p>
<p>
</p><pre>    $worksheet-&gt;set_column('A:A', undef, $format1); # Set format 
for col 1
    $worksheet-&gt;write('A1', "Hello");               # Defaults to $format1
    $worksheet-&gt;write('A2', "Hello", $format2);     # Keeps $format2
</pre>
<p></p>
<p>
If you wish to define a column format in this way you should call the
method before any calls to <code>write()</code>. If you call it afterwards it 
won't have any effect.

</p>
<p>
A default row format takes precedence over a default column format

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(0, undef,        $format1); # Set format 
for row 1
    $worksheet-&gt;set_column('A:A', undef, $format2); # Set format for col 1
    $worksheet-&gt;write('A1', "Hello");               # Defaults to $format1
    $worksheet-&gt;write('A2', "Hello");               # Defaults to $format2
</pre>
<p></p>
<p>
The <code>$hidden</code> parameter should be set to 1 if you wish to hide a 
column. This can be
used, for example, to hide intermediary steps in a complicated calculation:

</p>
<p>
</p><pre>    $worksheet-&gt;set_column('D:D', 20,    $format, 1);
    $worksheet-&gt;set_column('E:E', undef, undef,   1);
</pre>
<p></p>
<p>
The <code>$level</code> parameter is used to set the outline level of the 
column. Outlines are
described in <a href="#OUTLINES_AND_GROUPING_IN_EXCEL">OUTLINES AND GROUPING IN 
EXCEL</a>. Adjacent columns with the same outline level are grouped together 
into a
single outline.

</p>
<p>
The following example sets an outline level of 1 for columns B to G:

</p>
<p>
</p><pre>    $worksheet-&gt;set_column('B:G', undef, undef, 0, 1);
</pre>
<p></p>
<p>
The <code>$hidden</code> parameter can also be used to collapse outlined 
columns when used in
conjunction with the <code>$level</code> parameter.

</p>
<p>
</p><pre>    $worksheet-&gt;set_column('B:G', undef, undef, 1, 1);
</pre>
<p></p>
<p>
Excel allows up to 7 outline levels. Therefore the <code>$level</code> 
parameter should be in the range <code>0 &lt;= $level &lt;= 7</code>.

</p>
<p>
</p><hr>
<h2><a name="outline_settings_visible_symb">outline_settings($visible, 
$symbols_below, $symbols_right, $auto_style)</a></h2>
<p>
The <code>outline_settings()</code> method is used to control the appearance of 
outlines in Excel. Outlines are
described in <a href="#OUTLINES_AND_GROUPING_IN_EXCEL">OUTLINES AND GROUPING IN 
EXCEL</a>.

</p>
<p>
The <code>$visible</code> 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.

</p>
<p>
</p><pre>    $worksheet-&gt;outline_settings(0);
</pre>
<p></p>
<p>
The <code>$symbols_below</code> 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.

</p>
<p>
The <code>symbols_right</code> 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.

</p>
<p>
The <code>$auto_style</code> 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 <code>Spreadsheet::WriteExcel</code> 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.

</p>
<p>
The default settings for all of these parameters correspond to Excel's
default parameters.

</p>
<p>
The worksheet parameters controlled by <code>outline_settings()</code> are 
rarely used.

</p>
<p>
</p><hr>
<h2><a name="freeze_panes_row_col_top_ro">freeze_panes($row, $col, $top_row, 
$left_col)</a></h2>
<p>
This method can be used to divide a worksheet into horizontal or vertical
regions known as panes and to also "freeze" these panes so that the
splitter bars are not visible. This is the same as the <code>Window-&gt;Freeze 
Panes</code> menu command in Excel

</p>
<p>
The parameters <code>$row</code> and <code>$col</code> 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.

</p>
<p>
You can set one of the <code>$row</code> and <code>$col</code> parameters as 
zero if you do not want either a vertical or horizontal
split.

</p>
<p>
Examples:

</p>
<p>
</p><pre>    $worksheet-&gt;freeze_panes(1, 0); # Freeze the first row
    $worksheet-&gt;freeze_panes('A2'); # Same using A1 notation
    $worksheet-&gt;freeze_panes(0, 1); # Freeze the first column
    $worksheet-&gt;freeze_panes('B1'); # Same using A1 notation
    $worksheet-&gt;freeze_panes(1, 2); # Freeze first row and first 2 columns
    $worksheet-&gt;freeze_panes('C2'); # Same using A1 notation
</pre>
<p></p>
<p>
The parameters <code>$top_row</code> and <code>$left_col</code> 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:

</p>
<p>
</p><pre>    $worksheet-&gt;freeze_panes(1, 0, 20, 0);
</pre>
<p></p>
<p>
You cannot use A1 notation for the <code>$top_row</code> and 
<code>$left_col</code> parameters.

</p>
<p>
See also the <code>panes.pl</code> program in the <code>examples</code> 
directory of the distribution.

</p>
<p>
</p><hr>
<h2><a name="thaw_panes_y_x_top_row_le">thaw_panes($y, $x, $top_row, 
$left_col)</a></h2>
<p>
This method can be used to divide a worksheet into horizontal or vertical
regions known as panes. This method is different from the 
<code>freeze_panes()</code> method in that the splits between the panes will be 
visible to the user and
each pane will have its own scroll bars.

</p>
<p>
The parameters <code>$y</code> and <code>$x</code> are used to specify the 
vertical and horizontal position of the split. The
units for <code>$y</code> and <code>$x</code> are the same as those used by 
Excel to specify row height and column width.
However, the vertical and horizontal units are different from each other.
Therefore you must specify the <code>$y</code> and <code>$x</code> parameters 
in terms of the row heights and column widths that you have set
or the default values which are <code>12.75</code> for a row and  
<code>8.43</code> for a column.

</p>
<p>
You can set one of the <code>$y</code> and <code>$x</code> parameters as zero 
if you do not want either a vertical or horizontal
split. The parameters <code>$top_row</code> and <code>$left_col</code> are 
optional. They are used to specify the top-most or left-most visible
row or column in the bottom-right pane.

</p>
<p>
Example:

</p>
<p>
</p><pre>    $worksheet-&gt;thaw_panes(12.75, 0,    1, 0); # First row
    $worksheet-&gt;thaw_panes(0,     8.43, 0, 1); # First column
    $worksheet-&gt;thaw_panes(12.75, 8.43, 1, 1); # First row and column
</pre>
<p></p>
<p>
You cannot use A1 notation with this method.

</p>
<p>
See also the <code>freeze_panes()</code> method and the <code>panes.pl</code> 
program in the <code>examples</code> directory of the distribution.

</p>
<p>
</p><hr>
<h2><a name="merge_range_first_row_first_c">merge_range($first_row, $first_col, 
$last_row, $last_col, $token, $format)</a></h2>
<p>
Merging cells is generally achieved by setting the <code>merge</code> property 
of a Format object, see <a href="#CELL_FORMATTING">CELL FORMATTING</a>. 
However, this only allows simple Excel5 style horizontal merging which
Excel refers to as "center across selection".

</p>
<p>
The <code>merge_range()</code> method allows you to do Excel97+ style 
formatting where the cells can
contain other types of alignment in addition to the merging:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format(
                                        border  =&gt; 6,
                                        valign  =&gt; 'vcenter',
                                        align   =&gt; 'center',
                                      );
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;merge_range('B3:D4', 'Vertical and horizontal', 
$format);
</pre>
<p></p>
<p>
<strong>WARNING</strong>. The format object that is used with a 
<code>merge_range()</code> method call is marked internally as being associated 
with a merged range.
It is a fatal error to use a merged format in a non-merged cell. Instead
you should use separate formats for merged and non-merged cells. This
restriction will be removed in a future release.

</p>
<p>
<code>merge_range()</code> writes its <code>$token</code> argument using the 
worksheet <code>write()</code> method. Therefore it will handle numbers, 
strings, formulas or urls as
required.

</p>
<p>
Setting the <code>merge</code> property of the format isn't required when you 
are using <code>merge_range()</code>. In fact using it will exclude the use of 
any other horizontal alignment
option.

</p>
<p>
The full possibilities of this method are shown in the <code>merge3.pl</code>, 
<code>merge4.pl</code> and <code>merge5.pl</code> programs in the 
<code>examples</code> directory of the distribution.

</p>
<p>
</p><hr>
<h2><a name="set_zoom_scale_">set_zoom($scale)</a></h2>
<p>
Set the worksheet zoom factor in the range <code>10 &lt;= $scale &lt;= 
400</code>:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_zoom(50);
    $worksheet2-&gt;set_zoom(75);
    $worksheet3-&gt;set_zoom(300);
    $worksheet4-&gt;set_zoom(400);
</pre>
<p></p>
<p>
The default zoom factor is 100. You cannot zoom to "Selection" because it
is calculated by Excel at run-time.

</p>
<p>
Note, <code>set_zoom()</code> does not affect the scale of the printed page. 
For that you should use <code>set_print_scale()</code>.

</p>
<p>
</p><hr>
<h1><a name="PAGE_SET_UP_METHODS">PAGE SET-UP METHODS</a></h1>
<p>
Page set-up methods affect the way that a worksheet looks when it is
printed. They control features such as page headers and footers and
margins. These methods are really just standard worksheet methods. They are
documented here in a separate section for the sake of clarity.

</p>
<p>
The following methods are available for page set-up:

</p>
<p>
</p><pre>    set_landscape()
    set_portrait()
    set_paper()
    center_horizontally()
    center_vertically()
    set_margins()
    set_header()
    set_footer()
    repeat_rows()
    repeat_columns()
    hide_gridlines()
    print_row_col_headers()
    print_area()
    fit_to_pages()
    set_print_scale()
    set_h_pagebreaks()
    set_v_pagebreaks()
</pre>
<p></p>
<p>
A common requirement when working with Spreadsheet::WriteExcel is to apply
the same page set-up features to all of the worksheets in a workbook. To do
this you can use the <code>sheets()</code> method of the <code>workbook</code> 
class to access the array of worksheets in a workbook:

</p>
<p>
</p><pre>    foreach $worksheet ($workbook-&gt;sheets()) {
       $worksheet-&gt;set_landscape();
    }
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_landscape_">set_landscape()</a></h2>
<p>
This method is used to set the orientation of a worksheet's printed page to
landscape:

</p>
<p>
</p><pre>    $worksheet-&gt;set_landscape(); # Landscape mode
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_portrait_">set_portrait()</a></h2>
<p>
This method is used to set the orientation of a worksheet's printed page to
portrait. The default worksheet orientation is portrait, so you won't
generally need to call this method.

</p>
<p>
</p><pre>    $worksheet-&gt;set_portrait(); # Portrait mode
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_paper_index_">set_paper($index)</a></h2>
<p>
This method is used to set the paper format for the printed output of a
worksheet. The following paper styles are available:

</p>
<p>
</p><pre>    Index   Paper format            Paper size
    =====   ============            ==========
      0     Printer default         -
      1     Letter                  8 1/2 x 11 in
      2     Letter Small            8 1/2 x 11 in
      3     Tabloid                 11 x 17 in
      4     Ledger                  17 x 11 in
      5     Legal                   8 1/2 x 14 in
      6     Statement               5 1/2 x 8 1/2 in
      7     Executive               7 1/4 x 10 1/2 in
      8     A3                      297 x 420 mm
      9     A4                      210 x 297 mm
     10     A4 Small                210 x 297 mm
     11     A5                      148 x 210 mm
     12     B4                      250 x 354 mm
     13     B5                      182 x 257 mm
     14     Folio                   8 1/2 x 13 in
     15     Quarto                  215 x 275 mm
     16     -                       10x14 in
     17     -                       11x17 in
     18     Note                    8 1/2 x 11 in
     19     Envelope  9             3 7/8 x 8 7/8
     20     Envelope 10             4 1/8 x 9 1/2
     21     Envelope 11             4 1/2 x 10 3/8
     22     Envelope 12             4 3/4 x 11
     23     Envelope 14             5 x 11 1/2
     24     C size sheet            -
     25     D size sheet            -
     26     E size sheet            -
     27     Envelope DL             110 x 220 mm
     28     Envelope C3             324 x 458 mm
     29     Envelope C4             229 x 324 mm
     30     Envelope C5             162 x 229 mm
     31     Envelope C6             114 x 162 mm
     32     Envelope C65            114 x 229 mm
     33     Envelope B4             250 x 353 mm
     34     Envelope B5             176 x 250 mm
     35     Envelope B6             176 x 125 mm
     36     Envelope                110 x 230 mm
     37     Monarch                 3.875 x 7.5 in
     38     Envelope                3 5/8 x 6 1/2 in
     39     Fanfold                 14 7/8 x 11 in
     40     German Std Fanfold      8 1/2 x 12 in
     41     German Legal Fanfold    8 1/2 x 13 in
</pre>
<p></p>
<p>
Note, it is likely that not all of these paper types will be available to
the end user since it will depend on the paper formats that the user's
printer supports. Therefore, it is best to stick to standard paper types.

</p>
<p>
</p><pre>    $worksheet-&gt;set_paper(1); # US Letter
    $worksheet-&gt;set_paper(9); # A4
</pre>
<p></p>
<p>
If you do not specify a paper type the worksheet will print using the
printer's default paper.

</p>
<p>
</p><hr>
<h2><a name="center_horizontally_">center_horizontally()</a></h2>
<p>
Center the worksheet data horizontally between the margins on the printed
page:

</p>
<p>
</p><pre>    $worksheet-&gt;center_horizontally();
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="center_vertically_">center_vertically()</a></h2>
<p>
Center the worksheet data vertically between the margins on the printed
page:

</p>
<p>
</p><pre>    $worksheet-&gt;center_vertically();
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_margins_inches_">set_margins($inches)</a></h2>
<p>
There are several methods available for setting the worksheet margins on
the printed page:

</p>
<p>
</p><pre>    set_margins()        # Set all margins to the same value
    set_margins_LR()     # Set left and right margins to the same value
    set_margins_TB()     # Set top and bottom margins to the same value
    set_margin_left();   # Set left margin
    set_margin_right();  # Set right margin
    set_margin_top();    # Set top margin
    set_margin_bottom(); # Set bottom margin
</pre>
<p></p>
<p>
All of these methods take a distance in inches as a parameter. Note: 1 inch
= 25.4mm. ;-) The default left and right margin is 0.75 inch. The default
top and bottom margin is 1.00 inch.

</p>
<p>
</p><hr>
<h2><a name="set_header_string_margin_">set_header($string, $margin)</a></h2>
<p>
Headers and footers are generated using a <code>$string</code> which is a 
combination of plain text and control characters. The <code>$margin</code> 
parameter is optional.

</p>
<p>
The available control character are:

</p>
<p>
</p><pre>    Control             Category            Description
    =======             ========            ===========
    &amp;L                  Justification       Left
    &amp;C                                      Center
    &amp;R                                      Right
</pre>
<p></p>
<p>
</p><pre>    &amp;P                  Information         Page number
    &amp;N                                      Total number of pages
    &amp;D                                      Date
    &amp;T                                      Time
    &amp;F                                      File name
    &amp;A                                      Worksheet name
    &amp;Z                                      Workbook path
</pre>
<p></p>
<p>
</p><pre>    &amp;fontsize           Font                Font size
    &amp;"font,style"                           Font name and style
    &amp;U                                      Single underline
    &amp;E                                      Double underline
    &amp;S                                      Strikethrough
    &amp;X                                      Superscript
    &amp;Y                                      Subscript
</pre>
<p></p>
<p>
</p><pre>    &amp;&amp;                  Miscellaneous       Literal ampersand 
&amp;
</pre>
<p></p>
<p>
Text in headers and footers can be justified (aligned) to the left, center
and right by prefixing the text with the control characters 
<code>&amp;L</code>, <code>&amp;C</code> and <code>&amp;R</code>.

</p>
<p>
For example (with ASCII art representation of the results):

</p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;LHello');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    | Hello                                                         |
    |                                                               |
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;CHello');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    |                          Hello                                |
    |                                                               |
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;RHello');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    |                                                         Hello |
    |                                                               |
</pre>
<p></p>
<p>
For simple text, if you do not specify any justification the text will be
centred. However, you must prefix the text with <code>&amp;C</code> if you 
specify a font name or any other formatting:

</p>
<p>
</p><pre>    $worksheet-&gt;set_header('Hello');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    |                          Hello                                |
    |                                                               |
</pre>
<p></p>
<p>
You can have text in each of the justification regions:

</p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;LCiao&amp;CBello&amp;RCielo');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    | Ciao                     Bello                          Cielo |
    |                                                               |
</pre>
<p></p>
<p>
The information control characters act as variables that Excel will update
as the workbook or worksheet changes. Times and dates are in the users
default format:

</p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;CPage &amp;P of &amp;N');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    |                        Page 1 of 6                            |
    |                                                               |
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;CUpdated at &amp;T');
</pre>
<p></p>
<p>
</p><pre>     ---------------------------------------------------------------
    |                                                               |
    |                    Updated at 12:30 PM                        |
    |                                                               |
</pre>
<p></p>
<p>
You can specify the font size of a section of the text by prefixing it with
the control character <code>&amp;n</code> where <code>n</code> is the font size:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_header('&amp;C&amp;30Hello Big'  );
    $worksheet2-&gt;set_header('&amp;C&amp;10Hello Small');
</pre>
<p></p>
<p>
You can specify the font of a section of the text by prefixing it with the
control sequence <code>&amp;"font,style"</code> where <code>fontname</code> is 
a font name such as "Courier New" or "Times New Roman" and <code>style</code> 
is one of the standard Windows font descriptions: "Regular", "Italic",
"Bold" or "Bold Italic":

</p>
<p>
</p><pre>    $worksheet1-&gt;set_header('&amp;C&amp;"Courier New,Italic"Hello');
    $worksheet2-&gt;set_header('&amp;C&amp;"Courier New,Bold Italic"Hello');
    $worksheet3-&gt;set_header('&amp;C&amp;"Times New Roman,Regular"Hello');
</pre>
<p></p>
<p>
It is possible to combine all of these features together to create
sophisticated headers and footers. As an aid to setting up complicated
headers and footers you can record a page set-up as a macro in Excel and
look at the format strings that VBA produces. Remember however that VBA
uses two double quotes <code>""</code> to indicate a single double quote. For 
the last example above the
equivalent VBA code looks like this:

</p>
<p>
</p><pre>    .LeftHeader   = ""
    .CenterHeader = "&amp;""Times New Roman,Regular""Hello"
    .RightHeader  = ""
</pre>
<p></p>
<p>
To include a single literal ampersand <code>&amp;</code> in a header or footer 
you should use a double ampersand <code>&amp;&amp;</code>:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_header('&amp;CCuriouser &amp;&amp; Curiouser - 
Attorneys at Law');
</pre>
<p></p>
<p>
As stated above the margin parameter is optional. As with the other margins
the value should be in inches. The default header and footer margin is 0.50
inch. The header and footer margin size can be set as follows:

</p>
<p>
</p><pre>    $worksheet-&gt;set_header('&amp;CHello', 0.75);
</pre>
<p></p>
<p>
The header and footer margins are independent of the top and bottom
margins.

</p>
<p>
Note, the header or footer string must be less than 255 characters. Strings
longer than this will not be written and a warning will be generated.

</p>
<p>
On systems with <code>perl 5.8</code> and later the <code>set_header()</code> 
method can also handle Unicode strings in Perl's <code>utf8</code> format.

</p>
<p>
</p><pre>    $worksheet-&gt;set_header("&amp;C\x{263a}")
</pre>
<p></p>
<p>
See, also the <code>headers.pl</code> program in the <code>examples</code> 
directory of the distribution.

</p>
<p>
</p><hr>
<h2><a name="set_footer_">set_footer()</a></h2>
<p>
The syntax of the <code>set_footer()</code> method is the same as 
<code>set_header()</code>, see above.

</p>
<p>
</p><hr>
<h2><a name="repeat_rows_first_row_last_ro">repeat_rows($first_row, 
$last_row)</a></h2>
<p>
Set the number of rows to repeat at the top of each printed page.

</p>
<p>
For large Excel documents it is often desirable to have the first row or
rows of the worksheet print out at the top of each page. This can be
achieved by using the <code>repeat_rows()</code> method. The parameters 
<code>$first_row</code> and <code>$last_row</code> are zero based. The 
<code>$last_row</code> parameter is optional if you only wish to specify one 
row:

</p>
<p>
</p><pre>    $worksheet1-&gt;repeat_rows(0);    # Repeat the first row
    $worksheet2-&gt;repeat_rows(0, 1); # Repeat the first two rows
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="repeat_columns_first_col_last">repeat_columns($first_col, 
$last_col)</a></h2>
<p>
Set the columns to repeat at the left hand side of each printed page.

</p>
<p>
For large Excel documents it is often desirable to have the first column or
columns of the worksheet print out at the left hand side of each page. This
can be achieved by using the <code>repeat_columns()</code> method. The 
parameters <code>$first_column</code> and <code>$last_column</code> are zero 
based. The <code>$last_column</code> parameter is optional if you only wish to 
specify one column. You can also
specify the columns using A1 column notation, see the note about <a 
href="#Cell_notation">Cell notation</a>.

</p>
<p>
</p><pre>    $worksheet1-&gt;repeat_columns(0);     # Repeat the first column
    $worksheet2-&gt;repeat_columns(0, 1);  # Repeat the first two columns
    $worksheet3-&gt;repeat_columns('A:A'); # Repeat the first column
    $worksheet4-&gt;repeat_columns('A:B'); # Repeat the first two columns
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="hide_gridlines_option_">hide_gridlines($option)</a></h2>
<p>
This method is used to hide the gridlines on the screen and printed page.
Gridlines are the lines that divide the cells on a worksheet. Screen and
printed gridlines are turned on by default in an Excel worksheet. If you
have defined your own cell borders you may wish to hide the default
gridlines.

</p>
<p>
</p><pre>    $worksheet-&gt;hide_gridlines();
</pre>
<p></p>
<p>
The following values of <code>$option</code> are valid:

</p>
<p>
</p><pre>    0 : Don't hide gridlines
    1 : Hide printed gridlines only
    2 : Hide screen and printed gridlines
</pre>
<p></p>
<p>
If you don't supply an argument or use <code>undef</code> the default option is 
1, i.e. only the printed gridlines are hidden.

</p>
<p>
</p><hr>
<h2><a name="print_row_col_headers_">print_row_col_headers()</a></h2>
<p>
Set the option to print the row and column headers on the printed page.

</p>
<p>
An Excel worksheet looks something like the following;

</p>
<p>
</p><pre>     ------------------------------------------
    |   |   A   |   B   |   C   |   D   |  ...
     ------------------------------------------
    | 1 |       |       |       |       |  ...
    | 2 |       |       |       |       |  ...
    | 3 |       |       |       |       |  ...
    | 4 |       |       |       |       |  ...
    |...|  ...  |  ...  |  ...  |  ...  |  ...
</pre>
<p></p>
<p>
The headers are the letters and numbers at the top and the left of the
worksheet. Since these headers serve mainly as a indication of position on
the worksheet they generally do not appear on the printed page. If you wish
to have them printed you can use the <code>print_row_col_headers()</code> 
method :

</p>
<p>
</p><pre>    $worksheet-&gt;print_row_col_headers();
</pre>
<p></p>
<p>
Do not confuse these headers with page headers as described in the 
<code>set_header()</code> section above.

</p>
<p>
</p><hr>
<h2><a name="print_area_first_row_first_co">print_area($first_row, $first_col, 
$last_row, $last_col)</a></h2>
<p>
This method is used to specify the area of the worksheet that will be
printed. All four parameters must be specified. You can also use A1
notation, see the note about <a href="#Cell_notation">Cell notation</a>.

</p>
<p>
</p><pre>    $worksheet1-&gt;print_area("A1:H20");    # Cells A1 to H20
    $worksheet2-&gt;print_area(0, 0, 19, 7); # The same
    $worksheet2-&gt;print_area('A:H');       # Columns A to H if rows have data
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="fit_to_pages_width_height_">fit_to_pages($width, $height)</a></h2>
<p>
The <code>fit_to_pages()</code> method is used to fit the printed area to a 
specific number of pages both
vertically and horizontally. If the printed area exceeds the specified
number of pages it will be scaled down to fit. This guarantees that the
printed area will always appear on the specified number of pages even if
the page size or margins change.

</p>
<p>
</p><pre>    $worksheet1-&gt;fit_to_pages(1, 1); # Fit to 1x1 pages
    $worksheet2-&gt;fit_to_pages(2, 1); # Fit to 2x1 pages
    $worksheet3-&gt;fit_to_pages(1, 2); # Fit to 1x2 pages
</pre>
<p></p>
<p>
The print area can be defined using the <code>print_area()</code> method as 
described above.

</p>
<p>
A common requirement is to fit the printed output to <em>n</em> pages wide but 
have the height be as long as necessary. To achieve this set
the <code>$height</code> to zero or leave it blank:

</p>
<p>
</p><pre>    $worksheet1-&gt;fit_to_pages(1, 0); # 1 page wide and as long as 
necessary
    $worksheet2-&gt;fit_to_pages(1);    # The same
</pre>
<p></p>
<p>
Note that although it is valid to use both <code>fit_to_pages()</code> and 
<code>set_print_scale()</code> on the same worksheet only one of these options 
can be active at a time.
The last method call made will set the active option.

</p>
<p>
Note that <code>fit_to_pages()</code> will override any manual page breaks that 
are defined in the worksheet.

</p>
<p>
</p><hr>
<h2><a name="set_print_scale_scale_">set_print_scale($scale)</a></h2>
<p>
Set the scale factor of the printed page. Scale factors in the range <code>10 
&lt;= $scale &lt;= 400</code> are valid:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_print_scale(50);
    $worksheet2-&gt;set_print_scale(75);
    $worksheet3-&gt;set_print_scale(300);
    $worksheet4-&gt;set_print_scale(400);
</pre>
<p></p>
<p>
The default scale factor is 100. Note, <code>set_print_scale()</code> does not 
affect the scale of the visible page in Excel. For that you should
use <code>set_zoom()</code>.

</p>
<p>
Note also that although it is valid to use both <code>fit_to_pages()</code> and 
<code>set_print_scale()</code> on the same worksheet only one of these options 
can be active at a time.
The last method call made will set the active option.

</p>
<p>
</p><hr>
<h2><a name="set_h_pagebreaks_breaks_">set_h_pagebreaks(@breaks)</a></h2>
<p>
Add horizontal page breaks to a worksheet. A page break causes all the data
that follows it to be printed on the next page. Horizontal page breaks act
between rows. To create a page break between rows 20 and 21 you must
specify the break at row 21. However in zero index notation this is
actually row 20. So you can pretend for a small while that you are using 1
index notation:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_h_pagebreaks(20); # Break between row 20 and 21
</pre>
<p></p>
<p>
The <code>set_h_pagebreaks()</code> method will accept a list of page breaks 
and you can call it more than
once:

</p>
<p>
</p><pre>    $worksheet2-&gt;set_h_pagebreaks( 20,  40,  60,  80, 100); # Add 
breaks
    $worksheet2-&gt;set_h_pagebreaks(120, 140, 160, 180, 200); # Add some more
</pre>
<p></p>
<p>
Note: If you specify the "fit to page" option via the 
<code>fit_to_pages()</code> method it will override all manual page breaks.

</p>
<p>
There is a silent limitation of about 1000 horizontal page breaks per
worksheet in line with an Excel internal limitation.

</p>
<p>
</p><hr>
<h2><a name="set_v_pagebreaks_breaks_">set_v_pagebreaks(@breaks)</a></h2>
<p>
Add vertical page breaks to a worksheet. A page break causes all the data
that follows it to be printed on the next page. Vertical page breaks act
between columns. To create a page break between columns 20 and 21 you must
specify the break at column 21. However in zero index notation this is
actually column 20. So you can pretend for a small while that you are using
1 index notation:

</p>
<p>
</p><pre>    $worksheet1-&gt;set_v_pagebreaks(20); # Break between column 20 
and 21
</pre>
<p></p>
<p>
The <code>set_v_pagebreaks()</code> method will accept a list of page breaks 
and you can call it more than
once:

</p>
<p>
</p><pre>    $worksheet2-&gt;set_v_pagebreaks( 20,  40,  60,  80, 100); # Add 
breaks
    $worksheet2-&gt;set_v_pagebreaks(120, 140, 160, 180, 200); # Add some more
</pre>
<p></p>
<p>
Note: If you specify the "fit to page" option via the 
<code>fit_to_pages()</code> method it will override all manual page breaks.

</p>
<p>
</p><hr>
<h1><a name="CELL_FORMATTING">CELL FORMATTING</a></h1>
<p>
This section describes the methods and properties that are available for
formatting cells in Excel. The properties of a cell that can be formatted
include: fonts, colours, patterns, borders, alignment and number
formatting.

</p>
<p>
</p><hr>
<h2><a name="Creating_and_using_a_Format_obje">Creating and using a Format 
object</a></h2>
<p>
Cell formatting is defined through a Format object. Format objects are
created by calling the workbook <code>add_format()</code> method as follows:

</p>
<p>
</p><pre>    my $format1 = $workbook-&gt;add_format();       # Set properties 
later
    my $format2 = $workbook-&gt;add_format(%props); # Set at creation
</pre>
<p></p>
<p>
The format object holds all the formatting properties that can be applied
to a cell, a row or a column. The process of setting these properties is
discussed in the next section.

</p>
<p>
Once a Format object has been constructed and it properties have been set
it can be passed as an argument to the worksheet <code>write</code> methods as 
follows:

</p>
<p>
</p><pre>    $worksheet-&gt;write(0, 0, "One", $format);
    $worksheet-&gt;write_string(1, 0, "Two", $format);
    $worksheet-&gt;write_number(2, 0, 3, $format);
    $worksheet-&gt;write_blank(3, 0, $format);
</pre>
<p></p>
<p>
Formats can also be passed to the worksheet <code>set_row()</code> and 
<code>set_column()</code> methods to define the default property for a row or 
column.

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(0, 15, $format);
    $worksheet-&gt;set_column(0, 0, 15, $format);
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="Format_methods_and_Format_proper">Format methods and Format 
properties</a></h2>
<p>
The following table shows the Excel format categories, the formatting
properties that can be applied and the equivalent object method:

</p>
<p>
</p><pre>    Category   Description       Property        Method Name
    --------   -----------       --------        -----------
    Font       Font type         font            set_font()
               Font size         size            set_size()
               Font color        color           set_color()
               Bold              bold            set_bold()
               Italic            italic          set_italic()
               Underline         underline       set_underline()
               Strikeout         font_strikeout  set_font_strikeout()
               Super/Subscript   font_script     set_font_script()
               Outline           font_outline    set_font_outline()
               Shadow            font_shadow     set_font_shadow()
</pre>
<p></p>
<p>
</p><pre>    Number     Numeric format    num_format      set_num_format()
</pre>
<p></p>
<p>
</p><pre>    Protection Lock cells        locked          set_locked()
               Hide formulas     hidden          set_hidden()
</pre>
<p></p>
<p>
</p><pre>    Alignment  Horizontal align  align           set_align()
               Vertical align    valign          set_align()
               Rotation          rotation        set_rotation()
               Text wrap         text_wrap       set_text_wrap()
               Justify last      text_justlast   set_text_justlast()
               Center across     center_across   set_center_across()
               Indentation       indent          set_indent()
               Shrink to fit     shrink          set_shrink()
</pre>
<p></p>
<p>
</p><pre>    Pattern    Cell pattern      pattern         set_pattern()
               Background color  bg_color        set_bg_color()
               Foreground color  fg_color        set_fg_color()
</pre>
<p></p>
<p>
</p><pre>    Border     Cell border       border          set_border()
               Bottom border     bottom          set_bottom()
               Top border        top             set_top()
               Left border       left            set_left()
               Right border      right           set_right()
               Border color      border_color    set_border_color()
               Bottom color      bottom_color    set_bottom_color()
               Top color         top_color       set_top_color()
               Left color        left_color      set_left_color()
               Right color       right_color     set_right_color()
</pre>
<p></p>
<p>
There are two ways of setting Format properties: by using the object method
interface or by setting the property directly. For example, a typical use
of the method interface would be as follows:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_bold();
    $format-&gt;set_color('red');
</pre>
<p></p>
<p>
By comparison the properties can be set directly by passing a hash of
properties to the Format constructor:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format(bold =&gt; 1, color =&gt; 
'red');
</pre>
<p></p>
<p>
or after the Format has been constructed by means of the 
<code>set_properties()</code> method as follows:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_properties(bold =&gt; 1, color =&gt; 'red');
</pre>
<p></p>
<p>
You can also store the properties in one or more named hashes and pass them
to the required method:

</p>
<p>
</p><pre>    my %font    = (
                    font  =&gt; 'Arial',
                    size  =&gt; 12,
                    color =&gt; 'blue',
                    bold  =&gt; 1,
                  );
</pre>
<p></p>
<p>
</p><pre>    my %shading = (
                    bg_color =&gt; 'green',
                    pattern  =&gt; 1,
                  );
</pre>
<p></p>
<p>
</p><pre>    my $format1 = $workbook-&gt;add_format(%font);           # Font 
only
    my $format2 = $workbook-&gt;add_format(%font, %shading); # Font and shading
</pre>
<p></p>
<p>
The provision of two ways of setting properties might lead you to wonder
which is the best way. The answer depends on the amount of formatting that
will be required in your program. Initially, Spreadsheet::WriteExcel only
allowed individual Format properties to be set via the appropriate method.
While this was sufficient for most circumstances it proved very cumbersome
in programs that required a large amount of formatting. In addition the
mechanism for reusing properties between Format objects was complicated.

</p>
<p>
As a result the Perl/Tk style of adding properties was added to, hopefully,
facilitate developers who need to define a lot of formatting. In fact the
Tk style of defining properties is also supported:

</p>
<p>
</p><pre>    my %font    = (
                    -font      =&gt; 'Arial',
                    -size      =&gt; 12,
                    -color     =&gt; 'blue',
                    -bold      =&gt; 1,
                  );
</pre>
<p></p>
<p>
An additional advantage of working with hashes of properties is that it
allows you to share formatting between workbook objects

</p>
<p>
You can also create a format "on the fly" and pass it directly to a write
method as follows:

</p>
<p>
</p><pre>    $worksheet-&gt;write('A1', "Title", $workbook-&gt;add_format(bold 
=&gt; 1));
</pre>
<p></p>
<p>
This corresponds to an "anonymous" format in the Perl sense of anonymous
data or subs.

</p>
<p>
</p><hr>
<h2><a name="Working_with_formats">Working with formats</a></h2>
<p>
The default format is Arial 10 with all other properties off.

</p>
<p>
Each unique format in Spreadsheet::WriteExcel must have a corresponding
Format object. It isn't possible to use a Format with a
<code>write()</code> method and then redefine the Format for use at a later
stage. This is because a Format is applied to a cell not in its current
state but in its final state. Consider the following example:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_bold();
    $format-&gt;set_color('red');
    $worksheet-&gt;write('A1', "Cell A1", $format);
    $format-&gt;set_color('green');
    $worksheet-&gt;write('B1', "Cell B1", $format);
</pre>
<p></p>
<p>
Cell A1 is assigned the Format <code>$format</code> which is initially set to 
the colour red. However, the colour is
subsequently set to green. When Excel displays Cell A1 it will display the
final state of the Format which in this case will be the colour green.

</p>
<p>
In general a method call without an argument will turn a property on, for
example:

</p>
<p>
</p><pre>    my $format1 = $workbook-&gt;add_format();
    $format1-&gt;set_bold();  # Turns bold on
    $format1-&gt;set_bold(1); # Also turns bold on
    $format1-&gt;set_bold(0); # Turns bold off
</pre>
<p></p>
<p>
</p><hr>
<h1><a name="FORMAT_METHODS">FORMAT METHODS</a></h1>
<p>
The Format object methods are described in more detail in the following
sections. In addition, there is a Perl program called <code>formats.pl</code> 
in the <code>examples</code> directory of the WriteExcel distribution. This 
program creates an Excel
workbook called <code>formats.xls</code> which contains examples of almost all 
the format types.

</p>
<p>
The following Format methods are available:

</p>
<p>
</p><pre>    set_font()
    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_align()
    set_rotation()
    set_text_wrap()
    set_text_justlast()
    set_center_across()
    set_indent()
    set_shrink()
    set_pattern()
    set_bg_color()
    set_fg_color()
    set_border()
    set_bottom()
    set_top()
    set_left()
    set_right()
    set_border_color()
    set_bottom_color()
    set_top_color()
    set_left_color()
    set_right_color()
</pre>
<p></p>
<p>
The above methods can also be applied directly as properties. For example 
<code>$worksheet-&gt;set_bold()</code> is equivalent to 
<code>set_properties(bold =&gt; 1)</code>.

</p>
<p>
</p><hr>
<h2><a name="set_properties_properties_">set_properties(%properties)</a></h2>
<p>
The properties of an existing Format object can be set by means of 
<code>set_properties()</code>:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_properties(bold =&gt; 1, color =&gt; 'red');
</pre>
<p></p>
<p>
You can also store the properties in one or more named hashes and pass them
to the <code>set_properties()</code> method:

</p>
<p>
</p><pre>    my %font    = (
                    font  =&gt; 'Arial',
                    size  =&gt; 12,
                    color =&gt; 'blue',
                    bold  =&gt; 1,
                  );
</pre>
<p></p>
<p>
</p><pre>    my $format = $workbook-&gt;set_properties(%font);
</pre>
<p></p>
<p>
This method can be used as an alternative to setting the properties with 
<code>add_format()</code> or the specific format methods that are detailed in 
the following sections.

</p>
<p>
</p><hr>
<h2><a name="set_font_fontname_">set_font($fontname)</a></h2>
<p>
</p><pre>    Default state:      Font is Arial
    Default action:     None
    Valid args:         Any valid font name
</pre>
<p></p>
<p>
Specify the font used:

</p>
<p>
</p><pre>    $format-&gt;set_font('Times New Roman');
</pre>
<p></p>
<p>
Excel can only display fonts that are installed on the system that it is
running on. Therefore it is best to use the fonts that come as standard
such as 'Arial', 'Times New Roman' and 'Courier New'. See also the Fonts
worksheet created by formats.pl

</p>
<p>
</p><hr>
<h2><a name="set_size_">set_size()</a></h2>
<p>
</p><pre>    Default state:      Font size is 10
    Default action:     Set font size to 1
    Valid args:         Integer values from 1 to as big as your screen.
</pre>
<p></p>
<p>
Set the font size. Excel adjusts the height of a row to accommodate the
largest font size in the row. You can also explicitly specify the height of
a row using the <code>set_row()</code> worksheet method.

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_size(30);
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_color_">set_color()</a></h2>
<p>
</p><pre>    Default state:      Excels default color, usually black
    Default action:     Set the default color
    Valid args:         Integers from 8..63 or the following strings:
                        'black'
                        'blue'
                        'brown'
                        'cyan'
                        'gray'
                        'green'
                        'lime'
                        'magenta'
                        'navy'
                        'orange'
                        'purple'
                        'red'
                        'silver'
                        'white'
                        'yellow'
</pre>
<p></p>
<p>
Set the font colour. The <code>set_color()</code> method is used as follows:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_color('red');
    $worksheet-&gt;write(0, 0, "wheelbarrow", $format);
</pre>
<p></p>
<p>
Note: The <code>set_color()</code> method is used to set the colour of the font 
in a cell. To set the colour
of a cell use the <code>set_bg_color()</code> and <code>set_pattern()</code> 
methods.

</p>
<p>
For additional examples see the 'Named colors' and 'Standard colors'
worksheets created by formats.pl in the examples directory.

</p>
<p>
See also <a href="#COLOURS_IN_EXCEL">COLOURS IN EXCEL</a>.

</p>
<p>
</p><hr>
<h2><a name="set_bold_">set_bold()</a></h2>
<p>
</p><pre>    Default state:      bold is off
    Default action:     Turn bold on
    Valid args:         0, 1 [1]
</pre>
<p></p>
<p>
Set the bold property of the font:

</p>
<p>
</p><pre>    $format-&gt;set_bold();  # Turn bold on
</pre>
<p></p>
<p>
[1] Actually, values in the range 100..1000 are also valid. 400 is normal,
700 is bold and 1000 is very bold indeed. It is probably best to set the
value to 1 and use normal bold.

</p>
<p>
</p><hr>
<h2><a name="set_italic_">set_italic()</a></h2>
<p>
</p><pre>    Default state:      Italic is off
    Default action:     Turn italic on
    Valid args:         0, 1
</pre>
<p></p>
<p>
Set the italic property of the font:

</p>
<p>
</p><pre>    $format-&gt;set_italic();  # Turn italic on
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_underline_">set_underline()</a></h2>
<p>
</p><pre>    Default state:      Underline is off
    Default action:     Turn on single underline
    Valid args:         0  = No underline
                        1  = Single underline
                        2  = Double underline
                        33 = Single accounting underline
                        34 = Double accounting underline
</pre>
<p></p>
<p>
Set the underline property of the font.

</p>
<p>
</p><pre>    $format-&gt;set_underline();   # Single underline
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_font_strikeout_">set_font_strikeout()</a></h2>
<p>
</p><pre>    Default state:      Strikeout is off
    Default action:     Turn strikeout on
    Valid args:         0, 1
</pre>
<p></p>
<p>
Set the strikeout property of the font.

</p>
<p>
</p><hr>
<h2><a name="set_font_script_">set_font_script()</a></h2>
<p>
</p><pre>    Default state:      Super/Subscript is off
    Default action:     Turn Superscript on
    Valid args:         0  = Normal
                        1  = Superscript
                        2  = Subscript
</pre>
<p></p>
<p>
Set the superscript/subscript property of the font. This format is
currently not very useful.

</p>
<p>
</p><hr>
<h2><a name="set_font_outline_">set_font_outline()</a></h2>
<p>
</p><pre>    Default state:      Outline is off
    Default action:     Turn outline on
    Valid args:         0, 1
</pre>
<p></p>
<p>
Macintosh only.

</p>
<p>
</p><hr>
<h2><a name="set_font_shadow_">set_font_shadow()</a></h2>
<p>
</p><pre>    Default state:      Shadow is off
    Default action:     Turn shadow on
    Valid args:         0, 1
</pre>
<p></p>
<p>
Macintosh only.

</p>
<p>
</p><hr>
<h2><a name="set_num_format_">set_num_format()</a></h2>
<p>
</p><pre>    Default state:      General format
    Default action:     Format index 1
    Valid args:         See the following table
</pre>
<p></p>
<p>
This method is used to define the numerical format of a number in Excel. It
controls whether a number is displayed as an integer, a floating point
number, a date, a currency value or some other user defined format.

</p>
<p>
The numerical format of a cell can be specified by using a format string or
an index to one of Excel's built-in formats:

</p>
<p>
</p><pre>    my $format1 = $workbook-&gt;add_format();
    my $format2 = $workbook-&gt;add_format();
    $format1-&gt;set_num_format('d mmm yyyy'); # Format string
    $format2-&gt;set_num_format(0x0f);         # Format index
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(0, 0, 36892.521, $format1);      # 1 Jan 2001
    $worksheet-&gt;write(0, 0, 36892.521, $format2);      # 1-Jan-01
</pre>
<p></p>
<p>
Using format strings you can define very sophisticated formatting of
numbers.

</p>
<p>
</p><pre>    $format01-&gt;set_num_format('0.000');
    $worksheet-&gt;write(0,  0, 3.1415926, $format01);    # 3.142
</pre>
<p></p>
<p>
</p><pre>    $format02-&gt;set_num_format('#,##0');
    $worksheet-&gt;write(1,  0, 1234.56,   $format02);    # 1,235
</pre>
<p></p>
<p>
</p><pre>    $format03-&gt;set_num_format('#,##0.00');
    $worksheet-&gt;write(2,  0, 1234.56,   $format03);    # 1,234.56
</pre>
<p></p>
<p>
</p><pre>    $format04-&gt;set_num_format('$0.00');
    $worksheet-&gt;write(3,  0, 49.99,     $format04);    # $49.99
</pre>
<p></p>
<p>
</p><pre>    $format05-&gt;set_num_format('�0.00');
    $worksheet-&gt;write(4,  0, 49.99,     $format05);    # �49.99
</pre>
<p></p>
<p>
</p><pre>    $format06-&gt;set_num_format('�0.00');
    $worksheet-&gt;write(5,  0, 49.99,     $format06);    # �49.99
</pre>
<p></p>
<p>
</p><pre>    $format07-&gt;set_num_format('mm/dd/yy');
    $worksheet-&gt;write(6,  0, 36892.521, $format07);    # 01/01/01
</pre>
<p></p>
<p>
</p><pre>    $format08-&gt;set_num_format('mmm d yyyy');
    $worksheet-&gt;write(7,  0, 36892.521, $format08);    # Jan 1 2001
</pre>
<p></p>
<p>
</p><pre>    $format09-&gt;set_num_format('d mmmm yyyy');
    $worksheet-&gt;write(8,  0, 36892.521, $format09);    # 1 January 2001
</pre>
<p></p>
<p>
</p><pre>    $format10-&gt;set_num_format('dd/mm/yyyy hh:mm AM/PM');
    $worksheet-&gt;write(9,  0, 36892.521, $format10);    # 01/01/2001 12:30 AM
</pre>
<p></p>
<p>
</p><pre>    $format11-&gt;set_num_format('0 "dollar and" .00 "cents"');
    $worksheet-&gt;write(10, 0, 1.87,      $format11);    # 1 dollar and .87 
cents
</pre>
<p></p>
<p>
</p><pre>    # Conditional formatting
    $format12-&gt;set_num_format('[Green]General;[Red]-General;General');
    $worksheet-&gt;write(11, 0, 123,       $format12);    # &gt; 0 Green
    $worksheet-&gt;write(12, 0, -45,       $format12);    # &lt; 0 Red
    $worksheet-&gt;write(13, 0, 0,         $format12);    # = 0 Default colour
</pre>
<p></p>
<p>
</p><pre>    # Zip code
    $format13-&gt;set_num_format('00000');
    $worksheet-&gt;write(14, 0, '01209',   $format13);
</pre>
<p></p>
<p>
The number system used for dates is described in <a 
href="#DATES_IN_EXCEL">DATES IN EXCEL</a>.

</p>
<p>
The colour format should have one of the following values:

</p>
<p>
</p><pre>    [Black] [Blue] [Cyan] [Green] [Magenta] [Red] [White] [Yellow]
</pre>
<p></p>
<p>
Alternatively you can specify the colour based on a colour index as
follows: <code>[Color n]</code>, where n is a standard Excel colour index - 7. 
See the 'Standard colors'
worksheet created by formats.pl.

</p>
<p>
For more information refer to the documentation on formatting in the 
<code>doc</code> directory of the Spreadsheet::WriteExcel distro, the Excel 
on-line help or
to the tutorial at: <a 
href="http://support.microsoft.com/support/Excel/Content/Formats/default.asp";>http://support.microsoft.com/support/Excel/Content/Formats/default.asp</a>
and <a 
href="http://support.microsoft.com/support/Excel/Content/Formats/codes.asp";>http://support.microsoft.com/support/Excel/Content/Formats/codes.asp</a>


</p>
<p>
You should ensure that the format string is valid in Excel prior to using
it in WriteExcel.

</p>
<p>
Excel's built-in formats are shown in the following table:

</p>
<p>
</p><pre>    Index   Index   Format String
    0       0x00    General
    1       0x01    0
    2       0x02    0.00
    3       0x03    #,##0
    4       0x04    #,##0.00
    5       0x05    ($#,##0_);($#,##0)
    6       0x06    ($#,##0_);[Red]($#,##0)
    7       0x07    ($#,##0.00_);($#,##0.00)
    8       0x08    ($#,##0.00_);[Red]($#,##0.00)
    9       0x09    0%
    10      0x0a    0.00%
    11      0x0b    0.00E+00
    12      0x0c    # ?/?
    13      0x0d    # ??/??
    14      0x0e    m/d/yy
    15      0x0f    d-mmm-yy
    16      0x10    d-mmm
    17      0x11    mmm-yy
    18      0x12    h:mm AM/PM
    19      0x13    h:mm:ss AM/PM
    20      0x14    h:mm
    21      0x15    h:mm:ss
    22      0x16    m/d/yy h:mm
    ..      ....    ...........
    37      0x25    (#,##0_);(#,##0)
    38      0x26    (#,##0_);[Red](#,##0)
    39      0x27    (#,##0.00_);(#,##0.00)
    40      0x28    (#,##0.00_);[Red](#,##0.00)
    41      0x29    _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
    42      0x2a    _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)
    43      0x2b    _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
    44      0x2c    _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
    45      0x2d    mm:ss
    46      0x2e    [h]:mm:ss
    47      0x2f    mm:ss.0
    48      0x30    ##0.0E+0
    49      0x31    @
</pre>
<p></p>
<p>
For examples of these formatting codes see the 'Numerical formats'
worksheet created by formats.pl. See also the number_formats1.html and the
number_formats2.html documents in the <code>doc</code> directory of the distro.

</p>
<p>
Note 1. Numeric formats 23 to 36 are not documented by Microsoft and may
differ in international versions.

</p>
<p>
Note 2. In Excel 5 the dollar sign appears as a dollar sign. In Excel
97-2000 it appears as the defined local currency symbol.

</p>
<p>
Note 3. The red negative numeric formats display slightly differently in
Excel 5 and Excel 97-2000.

</p>
<p>
</p><hr>
<h2><a name="set_locked_">set_locked()</a></h2>
<p>
</p><pre>    Default state:      Cell locking is on
    Default action:     Turn locking on
    Valid args:         0, 1
</pre>
<p></p>
<p>
This property can be used to prevent modification of a cells contents.
Following Excel's convention, cell locking is turned on by default.
However, it only has an effect if the worksheet has been protected, see the
worksheet <code>protect()</code> method.

</p>
<p>
</p><pre>    my $locked  = $workbook-&gt;add_format();
    $locked-&gt;set_locked(1); # A non-op
</pre>
<p></p>
<p>
</p><pre>    my $unlocked = $workbook-&gt;add_format();
    $locked-&gt;set_locked(0);
</pre>
<p></p>
<p>
</p><pre>    # Enable worksheet protection
    $worksheet-&gt;protect();
</pre>
<p></p>
<p>
</p><pre>    # This cell cannot be edited.
    $worksheet-&gt;write('A1', '=1+2', $locked);
</pre>
<p></p>
<p>
</p><pre>    # This cell can be edited.
    $worksheet-&gt;write('A2', '=1+2', $unlocked);
</pre>
<p></p>
<p>
Note: This offers weak protection even with a password, see the note in
relation to the <code>protect()</code> method.

</p>
<p>
</p><hr>
<h2><a name="set_hidden_">set_hidden()</a></h2>
<p>
</p><pre>    Default state:      Formula hiding is off
    Default action:     Turn hiding on
    Valid args:         0, 1
</pre>
<p></p>
<p>
This property is used to hide a formula while still displaying its result.
This is generally used to hide complex calculations from end users who are
only interested in the result. It only has an effect if the worksheet has
been protected, see the worksheet <code>protect()</code> method.

</p>
<p>
</p><pre>    my $hidden = $workbook-&gt;add_format();
    $hidden-&gt;set_hidden();
</pre>
<p></p>
<p>
</p><pre>    # Enable worksheet protection
    $worksheet-&gt;protect();
</pre>
<p></p>
<p>
</p><pre>    # The formula in this cell isn't visible
    $worksheet-&gt;write('A1', '=1+2', $hidden);
</pre>
<p></p>
<p>
Note: This offers weak protection even with a password, see the note in
relation to the <code>protect()</code> method.

</p>
<p>
</p><hr>
<h2><a name="set_align_">set_align()</a></h2>
<p>
</p><pre>    Default state:      Alignment is off
    Default action:     Left alignment
    Valid args:         'left'              Horizontal
                        'center'
                        'right'
                        'fill'
                        'justify'
                        'center_across'
</pre>
<p></p>
<p>
</p><pre>                        'top'               Vertical
                        'vcenter'
                        'bottom'
                        'vjustify'
</pre>
<p></p>
<p>
This method is used to set the horizontal and vertical text alignment
within a cell. Vertical and horizontal alignments can be combined. The
method is used as follows:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_align('center');
    $format-&gt;set_align('vcenter');
    $worksheet-&gt;set_row(0, 30);
    $worksheet-&gt;write(0, 0, "X", $format);
</pre>
<p></p>
<p>
Text can be aligned across two or more adjacent cells using the 
<code>center_across</code> property. However, for genuine merged cells it is 
better to use the <code>merge_range()</code> worksheet method.

</p>
<p>
The <code>vjustify</code> (vertical justify) option can be used to provide 
automatic text wrapping in
a cell. The height of the cell will be adjusted to accommodate the wrapped
text. To specify where the text wraps use the <code>set_text_wrap()</code> 
method.

</p>
<p>
For further examples see the 'Alignment' worksheet created by formats.pl.

</p>
<p>
</p><hr>
<h2><a name="set_center_across_">set_center_across()</a></h2>
<p>
</p><pre>    Default state:      Center across selection is off
    Default action:     Turn center across on
    Valid args:         1
</pre>
<p></p>
<p>
Text can be aligned across two or more adjacent cells using the 
<code>set_center_across()</code> method. This is an alias for the 
<code>set_align('center_across')</code> method call.

</p>
<p>
Only one cell should contain the text, the other cells should be blank:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_center_across();
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(1, 1, 'Center across selection', $format);
    $worksheet-&gt;write_blank(1, 2, $format);
</pre>
<p></p>
<p>
See also the <code>merge1.pl</code> to <code>merge5.pl</code> programs in the 
<code>examples</code> directory and the <code>merge_range()</code> method.

</p>
<p>
</p><hr>
<h2><a name="set_text_wrap_">set_text_wrap()</a></h2>
<p>
</p><pre>    Default state:      Text wrap is off
    Default action:     Turn text wrap on
    Valid args:         0, 1
</pre>
<p></p>
<p>
Here is an example using the text wrap property, the escape character 
<code>\n</code> is used to indicate the end of line:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_text_wrap();
    $worksheet-&gt;write(0, 0, "It's\na bum\nwrap", $format);
</pre>
<p></p>
<p>
Excel will adjust the height of the row to accommodate the wrapped text. A
similar effect can be obtained without newlines using the 
<code>set_align('vjustify')</code> method. See the <code>textwrap.pl</code> 
program in the <code>examples</code> directory.

</p>
<p>
</p><hr>
<h2><a name="set_rotation_">set_rotation()</a></h2>
<p>
</p><pre>    Default state:      Text rotation is off
    Default action:     None
    Valid args:         Integers in the range -90 to 90 and 270
</pre>
<p></p>
<p>
Set the rotation of the text in a cell. The rotation can be any angle in
the range -90 to 90 degrees.

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_rotation(30);
    $worksheet-&gt;write(0, 0, "This text is rotated", $format);
</pre>
<p></p>
<p>
The angle 270 is also supported. This indicates text where the letters run
from top to bottom.

</p>
<p>
</p><hr>
<h2><a name="set_indent_">set_indent()</a></h2>
<p>
</p><pre>    Default state:      Text indentation is off
    Default action:     Indent text 1 level
    Valid args:         Positive integers
</pre>
<p></p>
<p>
This method can be used to indent text. The argument, which should be an
integer, is taken as the level of indentation:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_indent(2);
    $worksheet-&gt;write(0, 0, "This text is indented", $format);
</pre>
<p></p>
<p>
Indentation is a horizontal alignment property. It will override any other
horizontal properties but it can be used in conjunction with vertical
properties.

</p>
<p>
</p><hr>
<h2><a name="set_shrink_">set_shrink()</a></h2>
<p>
</p><pre>    Default state:      Text shrinking is off
    Default action:     Turn "shrink to fit" on
    Valid args:         1
</pre>
<p></p>
<p>
This method can be used to shrink text so that it fits in a cell.

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
    $format-&gt;set_shrink();
    $worksheet-&gt;write(0, 0, "Honey, I shrunk the text!", $format);
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="set_text_justlast_">set_text_justlast()</a></h2>
<p>
</p><pre>    Default state:      Justify last is off
    Default action:     Turn justify last on
    Valid args:         0, 1
</pre>
<p></p>
<p>
Only applies to Far Eastern versions of Excel.

</p>
<p>
</p><hr>
<h2><a name="set_pattern_">set_pattern()</a></h2>
<p>
</p><pre>    Default state:      Pattern is off
    Default action:     Solid fill is on
    Valid args:         0 .. 18
</pre>
<p></p>
<p>
Set the background pattern of a cell.

</p>
<p>
Examples of the available patterns are shown in the 'Patterns' worksheet
created by formats.pl. However, it is unlikely that you will ever need
anything other than Pattern 1 which is a solid fill of the background
color.

</p>
<p>
</p><hr>
<h2><a name="set_bg_color_">set_bg_color()</a></h2>
<p>
</p><pre>    Default state:      Color is off
    Default action:     Solid fill.
    Valid args:         See set_color()
</pre>
<p></p>
<p>
The <code>set_bg_color()</code> method can be used to set the background colour 
of a pattern. Patterns are
defined via the <code>set_pattern()</code> method. If a pattern hasn't been 
defined then a solid fill pattern is used
as the default.

</p>
<p>
Here is an example of how to set up a solid fill in a cell:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format();
</pre>
<p></p>
<p>
</p><pre>    $format-&gt;set_pattern(); # This is optional when using a solid 
fill
</pre>
<p></p>
<p>
</p><pre>    $format-&gt;set_bg_color('green');
    $worksheet-&gt;write('A1', 'Ray', $format);
</pre>
<p></p>
<p>
For further examples see the 'Patterns' worksheet created by formats.pl.

</p>
<p>
</p><hr>
<h2><a name="set_fg_color_">set_fg_color()</a></h2>
<p>
</p><pre>    Default state:      Color is off
    Default action:     Solid fill.
    Valid args:         See set_color()
</pre>
<p></p>
<p>
The <code>set_fg_color()</code> method can be used to set the foreground colour 
of a pattern.

</p>
<p>
For further examples see the 'Patterns' worksheet created by formats.pl.

</p>
<p>
</p><hr>
<h2><a name="set_border_">set_border()</a></h2>
<p>
</p><pre>    Also applies to:    set_bottom()
                        set_top()
                        set_left()
                        set_right()
</pre>
<p></p>
<p>
</p><pre>    Default state:      Border is off
    Default action:     Set border type 1
    Valid args:         0 No border
                        1 Thin single border
                        2 Medium single border
                        3 Dashed border
                        4 Dotted border
                        5 Thick single border
                        6 Double line border
                        7 Hair border
</pre>
<p></p>
<p>
A cell border is comprised of a border on the bottom, top, left and right.
These can be set to the same value using <code>set_border()</code> or 
individually using the relevant method calls shown above. Examples of
the available border styles are shown in the 'Borders' worksheet created by
formats.pl.

</p>
<p>
</p><hr>
<h2><a name="set_border_color_">set_border_color()</a></h2>
<p>
</p><pre>    Also applies to:    set_bottom_color()
                        set_top_color()
                        set_left_color()
                        set_right_color()
</pre>
<p></p>
<p>
</p><pre>    Default state:      Color is off
    Default action:     Undefined
    Valid args:         See set_color()
</pre>
<p></p>
<p>
Set the colour of the cell borders. A cell border is comprised of a border
on the bottom, top, left and right. These can be set to the same colour
using <code>set_border_color()</code> or individually using the relevant method 
calls shown above. Examples of
the border styles and colours are shown in the 'Borders' worksheet created
by formats.pl.

</p>
<p>
</p><hr>
<h2><a name="copy_format_">copy($format)</a></h2>
<p>
This method is used to copy all of the properties from one Format object to
another:

</p>
<p>
</p><pre>    my $lorry1 = $workbook-&gt;add_format();
    $lorry1-&gt;set_bold();
    $lorry1-&gt;set_italic();
    $lorry1-&gt;set_color('red');    # lorry1 is bold, italic and red
</pre>
<p></p>
<p>
</p><pre>    my $lorry2 = $workbook-&gt;add_format();
    $lorry2-&gt;copy($lorry1);
    $lorry2-&gt;set_color('yellow'); # lorry2 is bold, italic and yellow
</pre>
<p></p>
<p>
The <code>copy()</code> method is only useful if you are using the method 
interface to Format
properties. It generally isn't required if you are setting Format
properties directly using hashes.

</p>
<p>
Note: this is not a copy constructor, both objects must exist prior to
copying.

</p>
<p>
</p><hr>
<h1><a name="COLOURS_IN_EXCEL">COLOURS IN EXCEL</a></h1>
<p>
Excel provides a colour palette of 56 colours. In Spreadsheet::WriteExcel
these colours are accessed via their palette index in the range 8..63. This
index is used to set the colour of fonts, cell patterns and cell borders.
For example:

</p>
<p>
</p><pre>    my $format = $workbook-&gt;add_format(
                                        color =&gt; 12, # index for blue
                                        font  =&gt; 'Arial',
                                        size  =&gt; 12,
                                        bold  =&gt; 1,
                                     );
</pre>
<p></p>
<p>
The most commonly used colours can also be accessed by name. The name acts
as a simple alias for the colour index:

</p>
<p>
</p><pre>    black     =&gt;    8
    blue      =&gt;   12
    brown     =&gt;   16
    cyan      =&gt;   15
    gray      =&gt;   23
    green     =&gt;   17
    lime      =&gt;   11
    magenta   =&gt;   14
    navy      =&gt;   18
    orange    =&gt;   53
    purple    =&gt;   20
    red       =&gt;   10
    silver    =&gt;   22
    white     =&gt;    9
    yellow    =&gt;   13
</pre>
<p></p>
<p>
For example:

</p>
<p>
</p><pre>    my $font = $workbook-&gt;add_format(color =&gt; 'red');
</pre>
<p></p>
<p>
Users of VBA in Excel should note that the equivalent colour indices are in
the range 1..56 instead of 8..63.

</p>
<p>
If the default palette does not provide a required colour you can override
one of the built-in values. This is achieved by using the 
<code>set_custom_color()</code> workbook method to adjust the RGB (red green 
blue) components of the
colour:

</p>
<p>
</p><pre>    my $ferrari = $workbook-&gt;set_custom_color(40, 216, 12, 12);
</pre>
<p></p>
<p>
</p><pre>    my $format  = $workbook-&gt;add_format(
                                        bg_color =&gt; $ferrari,
                                        pattern  =&gt; 1,
                                        border   =&gt; 1
                                      );
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write_blank('A1', $format);
</pre>
<p></p>
<p>
The default Excel 97 colour palette is shown in <code>palette.html</code> in 
the <code>doc</code> directory of the distro. You can generate an Excel version 
of the palette
using <code>colors.pl</code> in the <code>examples</code> directory.

</p>
<p>
A comparison of the colour components in the Excel 5 and Excel 97+ colour
palettes is shown in <code>rgb5-97.txt</code> in the <code>doc</code> directory.

</p>
<p>
You may also find the following links helpful:

</p>
<p>
A detailed look at Excel's colour palette: <a 
href="http://www.geocities.com/davemcritchie/excel/colors.htm";>http://www.geocities.com/davemcritchie/excel/colors.htm</a>


</p>
<p>
A decimal RGB chart: <a 
href="http://www.hypersolutions.org/pages/rgbdec.html";>http://www.hypersolutions.org/pages/rgbdec.html</a>


</p>
<p>
A hex RGB chart: : <a 
href="http://www.hypersolutions.org/pages/rgbhex.html";>http://www.hypersolutions.org/pages/rgbhex.html</a>


</p>
<p>
</p><hr>
<h1><a name="DATES_IN_EXCEL">DATES IN EXCEL</a></h1>
<p>
Dates and times in Excel are represented by real numbers, for example "Jan
1 2001 12:30 AM" is represented by the number 36892.521.

</p>
<p>
The integer part of the number stores the number of days since the epoch
and the fractional part stores the percentage of the day.

</p>
<p>
The epoch can be either 1900 or 1904. Excel for Windows uses 1900 and Excel
for Macintosh uses 1904. The epochs are:

</p>
<p>
</p><pre>    1900: 0 January 1900 i.e. 31 December 1899
    1904: 1 January 1904
</pre>
<p></p>
<p>
By default Spreadsheet::WriteExcel uses the Windows/1900 format although it
generally isn't an issue since Excel on Windows and the Macintosh will
convert automatically between one system and the other. To use the 1904
epoch you must use the <code>set_1904()</code> workbook method.

</p>
<p>
There are two things to note about the 1900 date format. The first is that
the epoch starts on 0 January 1900. The second is that the year 1900 is
erroneously but deliberately treated as a leap year. Therefore you must add
an extra day to dates after 28 February 1900. The reason for this anomaly
is explained at <a 
href="http://support.microsoft.com/support/kb/articles/Q181/3/70.asp";>http://support.microsoft.com/support/kb/articles/Q181/3/70.asp</a>


</p>
<p>
A date or time in Excel is like any other number. To display the number as
a date you must apply a number format to it. Refer to the 
<code>set_num_format()</code> method above:

</p>
<p>
</p><pre>    $format-&gt;set_num_format('mmm d yyyy hh:mm AM/PM');
    $worksheet-&gt;write('A1', 36892.521 , $format); # Jan 1 2001 12:30 AM
</pre>
<p></p>
<p>
You can also use the <code>write_date_time()</code> worksheet method to write 
dates in ISO8601 date format.

</p>
<p>
</p><pre>    $worksheet-&gt;write_date_time('A2', '2001-01-01T12:20', format);
</pre>
<p></p>
<p>
See the <code>write_date_time()</code> section of the documentation for more 
details.

</p>
<p>
See also the <code>Spreadsheet::WriteExcel::Utility</code> module that is 
included in the distro and which includes date handling
functions and the DateTime::Format::Excel module, <a 
href="http://search.cpan.org/search?dist=DateTime-Format-Excel";>http://search.cpan.org/search?dist=DateTime-Format-Excel</a>
which is part of the DateTime project and which deals specifically with
converting dates and times to and from Excel's format.

</p>
<p>
</p><hr>
<h1><a name="OUTLINES_AND_GROUPING_IN_EXCEL">OUTLINES AND GROUPING IN 
EXCEL</a></h1>
<p>
Excel allows you to group rows or columns so that they can be hidden or
displayed with a single mouse click. This feature is referred to as
outlines.

</p>
<p>
Outlines can reduce complex data down to a few salient sub-totals or
summaries.

</p>
<p>
This feature is best viewed in Excel but the following is an ASCII
representation of what a worksheet with three outlines might look like.
Rows 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at level
1. The lines at the left hand side are called outline level bars.

</p>
<p>
</p><pre>            ------------------------------------------
     1 2 3 |   |   A   |   B   |   C   |   D   |  ...
            ------------------------------------------
      _    | 1 |   A   |       |       |       |  ...
     |  _  | 2 |   B   |       |       |       |  ...
     | |   | 3 |  (C)  |       |       |       |  ...
     | |   | 4 |  (D)  |       |       |       |  ...
     | -   | 5 |   E   |       |       |       |  ...
     |  _  | 6 |   F   |       |       |       |  ...
     | |   | 7 |  (G)  |       |       |       |  ...
     | |   | 8 |  (H)  |       |       |       |  ...
     | -   | 9 |   I   |       |       |       |  ...
     -     | . |  ...  |  ...  |  ...  |  ...  |  ...
</pre>
<p></p>
<p>
Clicking the minus sign on each of the level 2 outlines will collapse and
hide the data as shown in the next figure. The minus sign changes to a plus
sign to indicate that the data in the outline is hidden.

</p>
<p>
</p><pre>            ------------------------------------------
     1 2 3 |   |   A   |   B   |   C   |   D   |  ...
            ------------------------------------------
      _    | 1 |   A   |       |       |       |  ...
     |     | 2 |   B   |       |       |       |  ...
     | +   | 5 |   E   |       |       |       |  ...
     |     | 6 |   F   |       |       |       |  ...
     | +   | 9 |   I   |       |       |       |  ...
     -     | . |  ...  |  ...  |  ...  |  ...  |  ...
</pre>
<p></p>
<p>
Clicking on the minus sign on the level 1 outline will collapse the
remaining rows as follows:

</p>
<p>
</p><pre>            ------------------------------------------
     1 2 3 |   |   A   |   B   |   C   |   D   |  ...
            ------------------------------------------
           | 1 |   A   |       |       |       |  ...
     +     | . |  ...  |  ...  |  ...  |  ...  |  ...
</pre>
<p></p>
<p>
Grouping in <code>Spreadsheet::WriteExcel</code> is achieved by setting the 
outline level via the <code>set_row()</code> and <code>set_column()</code> 
worksheet methods:

</p>
<p>
</p><pre>    set_row($row, $height, $format, $hidden, $level)
    set_column($first_col, $last_col, $width, $format, $hidden, $level)
</pre>
<p></p>
<p>
The following example sets an outline level of 1 for rows 1 and 2
(zero-indexed) and columns B to G. The parameters <code>$height</code> and 
<code>$XF</code> are assigned default values since they are undefined:

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(1, undef, undef, 0, 1);
    $worksheet-&gt;set_row(2, undef, undef, 0, 1);
    $worksheet-&gt;set_column('B:G', undef, undef, 0, 1);
</pre>
<p></p>
<p>
Excel allows up to 7 outline levels. Therefore the <code>$level</code> 
parameter should be in the range <code>0 &lt;= $level &lt;= 7</code>.

</p>
<p>
Rows and columns can be collapsed by setting the <code>$hidden</code> flag:

</p>
<p>
</p><pre>    $worksheet-&gt;set_row(1, undef, undef, 1, 1);
    $worksheet-&gt;set_row(2, undef, undef, 1, 1);
    $worksheet-&gt;set_column('B:G', undef, undef, 1, 1);
</pre>
<p></p>
<p>
For a more complete example see the <code>outline.pl</code> program in the 
examples directory of the distro.

</p>
<p>
Some additional outline properties can be set via the 
<code>outline_settings()</code> worksheet method, see above.

</p>
<p>
</p><hr>
<h1><a name="FORMULAS_AND_FUNCTIONS_IN_EXCEL">FORMULAS AND FUNCTIONS IN 
EXCEL</a></h1>
<p>
</p><hr>
<h2><a name="Caveats">Caveats</a></h2>
<p>
The first thing to note is that there are still some outstanding issues
with the implementation of formulas and functions:

</p>
<p>
</p><pre>    1. Writing a formula is much slower than writing the equivalent 
string.
    2. You cannot use array constants, i.e. {1;2;3}, in functions.
    3. Unary minus isn't supported.
    4. Whitespace is not preserved around operators.
    5. Named ranges are not supported.
    6. Array formulas are not supported.
</pre>
<p></p>
<p>
However, these constraints will be removed in future versions. They are
here because of a trade-off between features and time. Also, it is possible
to work around issue 1 using the <code>store_formula()</code> and 
<code>repeat_formula()</code> methods as described later in this section.

</p>
<p>
</p><hr>
<h2><a name="Introduction">Introduction</a></h2>
<p>
The following is a brief introduction to formulas and functions in Excel
and Spreadsheet::WriteExcel.

</p>
<p>
A formula is a string that begins with an equals sign:

</p>
<p>
</p><pre>    '=A1+B1'
    '=AVERAGE(1, 2, 3)'
</pre>
<p></p>
<p>
The formula can contain numbers, strings, boolean values, cell references,
cell ranges and functions. Named ranges are not supported. Formulas should
be written as they appear in Excel, that is cells and functions must be in
uppercase.

</p>
<p>
Cells in Excel are referenced using the A1 notation system where the column
is designated by a letter and the row by a number. Columns range from A to
IV i.e. 0 to 255, rows range from 1 to 65536. The 
<code>Spreadsheet::WriteExcel::Utility</code> module that is included in the 
distro contains helper functions for dealing
with A1 notation, for example:

</p>
<p>
</p><pre>    use Spreadsheet::WriteExcel::Utility;
</pre>
<p></p>
<p>
</p><pre>    ($row, $col) = xl_cell_to_rowcol('C2');  # (1, 2)
    $str         = xl_rowcol_to_cell(1, 2);  # C2
</pre>
<p></p>
<p>
The Excel <code>$</code> 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.

</p>
<p>
</p><pre>    '=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
</pre>
<p></p>
<p>
Formulas can also refer to cells in other worksheets of the current
workbook. For example:

</p>
<p>
</p><pre>    '=Sheet2!A1'
    '=Sheet2!A1:A5'
    '=Sheet2:Sheet3!A1'
    '=Sheet2:Sheet3!A1:A5'
    q{='Test Data'!A1}
    q{='Test Data1:Test Data2'!A1}
</pre>
<p></p>
<p>
The sheet reference and the cell reference are separated by  <code>!</code> the 
exclamation mark symbol. If worksheet names contain spaces, commas o
parentheses then Excel requires that the name is enclosed in single quotes
as shown in the last two examples above. In order to avoid using a lot of
escape characters you can use the quote operator <code>q{}</code> to protect 
the quotes. See <code>perlop</code> in the main Perl documentation. Only valid 
sheet names that have been added
using the <code>add_worksheet()</code> method can be used in formulas. You 
cannot reference external workbooks.

</p>
<p>
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:

</p>
<p>
</p><pre>    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)   # Not yet supported
       %      Percent (Not modulus)     13%      # Not supported, [1]
</pre>
<p></p>
<p>
</p><pre>    Comparison operators:
    =====================
    Operator  Meaning                   Example
        =     Equal to                  A1 =  B1 # Equivalent to ==
        &lt;&gt;    Not equal to              A1 &lt;&gt; B1 # Equivalent to !=
        &gt;     Greater than              A1 &gt;  B1
        &lt;     Less than                 A1 &lt;  B1
        &gt;=    Greater than or equal to  A1 &gt;= B1
        &lt;=    Less than or equal to     A1 &lt;= B1
</pre>
<p></p>
<p>
</p><pre>    String operator:
    ================
    Operator  Meaning                   Example
        &amp;     Concatenation             "Hello " &amp; "World!" # [2]
</pre>
<p></p>
<p>
</p><pre>    Reference operators:
    ====================
    Operator  Meaning                   Example
        :     Range operator            A1:A4               # [3]
        ,     Union operator            SUM(1, 2+2, B3)     # [4]
</pre>
<p></p>
<p>
</p><pre>    Notes:
    [1]: You can get a percentage with formatting and modulus with MOD().
    [2]: Equivalent to ("Hello " . "World!") in Perl.
    [3]: This range is equivalent to cells A1, A2, A3 and A4.
    [4]: The comma behaves like the list separator in Perl.
</pre>
<p></p>
<p>
The range and comma operators can have different symbols in non-English
versions of Excel. These will be supported in a later version of
Spreadsheet::WriteExcel. European users of Excel take note:

</p>
<p>
</p><pre>    $worksheet-&gt;write('A1', '=SUM(1; 2; 3)'); # Wrong!!
    $worksheet-&gt;write('A1', '=SUM(1, 2, 3)'); # Okay
</pre>
<p></p>
<p>
The following table lists all of the core functions supported by Excel 5
and Spreadsheet::WriteExcel. Any additional functions that are available
through the "Analysis ToolPak" or other add-ins are not supported. These
functions have all been tested to verify that they work.

</p>
<p>
</p><pre>    ABS           DB            INDIRECT      NORMINV       SLN
    ACOS          DCOUNT        INFO          NORMSDIST     SLOPE
    ACOSH         DCOUNTA       INT           NORMSINV      SMALL
    ADDRESS       DDB           INTERCEPT     NOT           SQRT
    AND           DEGREES       IPMT          NOW           STANDARDIZE
    AREAS         DEVSQ         IRR           NPER          STDEV
    ASIN          DGET          ISBLANK       NPV           STDEVP
    ASINH         DMAX          ISERR         ODD           STEYX
    ATAN          DMIN          ISERROR       OFFSET        SUBSTITUTE
    ATAN2         DOLLAR        ISLOGICAL     OR            SUBTOTAL
    ATANH         DPRODUCT      ISNA          PEARSON       SUM
    AVEDEV        DSTDEV        ISNONTEXT     PERCENTILE    SUMIF
    AVERAGE       DSTDEVP       ISNUMBER      PERCENTRANK   SUMPRODUCT
    BETADIST      DSUM          ISREF         PERMUT        SUMSQ
    BETAINV       DVAR          ISTEXT        PI            SUMX2MY2
    BINOMDIST     DVARP         KURT          PMT           SUMX2PY2
    CALL          ERROR.TYPE    LARGE         POISSON       SUMXMY2
    CEILING       EVEN          LEFT          POWER         SYD
    CELL          EXACT         LEN           PPMT          T
    CHAR          EXP           LINEST        PROB          TAN
    CHIDIST       EXPONDIST     LN            PRODUCT       TANH
    CHIINV        FACT          LOG           PROPER        TDIST
    CHITEST       FALSE         LOG10         PV            TEXT
    CHOOSE        FDIST         LOGEST        QUARTILE      TIME
    CLEAN         FIND          LOGINV        RADIANS       TIMEVALUE
    CODE          FINV          LOGNORMDIST   RAND          TINV
    COLUMN        FISHER        LOOKUP        RANK          TODAY
    COLUMNS       FISHERINV     LOWER         RATE          TRANSPOSE
    COMBIN        FIXED         MATCH         REGISTER.ID   TREND
    CONCATENATE   FLOOR         MAX           REPLACE       TRIM
    CONFIDENCE    FORECAST      MDETERM       REPT          TRIMMEAN
    CORREL        FREQUENCY     MEDIAN        RIGHT         TRUE
    COS           FTEST         MID           ROMAN         TRUNC
    COSH          FV            MIN           ROUND         TTEST
    COUNT         GAMMADIST     MINUTE        ROUNDDOWN     TYPE
    COUNTA        GAMMAINV      MINVERSE      ROUNDUP       UPPER
    COUNTBLANK    GAMMALN       MIRR          ROW           VALUE
    COUNTIF       GEOMEAN       MMULT         ROWS          VAR
    COVAR         GROWTH        MOD           RSQ           VARP
    CRITBINOM     HARMEAN       MODE          SEARCH        VDB
    DATE          HLOOKUP       MONTH         SECOND        VLOOKUP
    DATEVALUE     HOUR          N             SIGN          WEEKDAY
    DAVERAGE      HYPGEOMDIST   NA            SIN           WEIBULL
    DAY           IF            NEGBINOMDIST  SINH          YEAR
    DAYS360       INDEX         NORMDIST      SKEW          ZTEST
</pre>
<p></p>
<p>
You can also modify the module to support function names in the following
languages: German, French, Spanish, Portuguese, Dutch, Finnish, Italian and
Swedish. See the <code>function_locale.pl</code> program in the 
<code>examples</code> directory of the distro.

</p>
<p>
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
links: <a 
href="http://msdn.microsoft.com/library/default.asp?URL=/library/officedev/office97/s88f2.htm";>http://msdn.microsoft.com/library/default.asp?URL=/library/officedev/office97/s88f2.htm</a>
and <a 
href="http://msdn.microsoft.com/library/default.asp?URL=/library/en-us/office97/s992f.htm";>http://msdn.microsoft.com/library/default.asp?URL=/library/en-us/office97/s992f.htm</a>


</p>
<p>
If your formula doesn't work in Spreadsheet::WriteExcel try the following:

</p>
<p>
</p><pre>    1. Verify that the formula works in Excel (or Gnumeric or 
OpenOffice.org).
    2. Ensure that it isn't on the Caveats list shown above.
    3. Ensure that cell references and formula names are in uppercase.
    4. Ensure that you are using ':' as the range operator, A1:A4.
    5. Ensure that you are using ',' as the union operator, SUM(1,2,3).
    6. Ensure that the function is in the above table.
</pre>
<p></p>
<p>
If you go through steps 1-6 and you still have a problem, mail me.

</p>
<p>
</p><hr>
<h2><a name="Improving_performance_when_worki">Improving performance when 
working with formulas</a></h2>
<p>
Writing a large number of formulas with Spreadsheet::WriteExcel can be
slow. This is due to the fact that each formula has to be parsed and with
the current implementation this is computationally expensive.

</p>
<p>
However, in a lot of cases the formulas that you write will be quite
similar, for example:

</p>
<p>
</p><pre>    $worksheet-&gt;write_formula('B1',    '=A1 * 3 + 50',    $format);
    $worksheet-&gt;write_formula('B2',    '=A2 * 3 + 50',    $format);
    ...
    ...
    $worksheet-&gt;write_formula('B99',   '=A999 * 3 + 50',  $format);
    $worksheet-&gt;write_formula('B1000', '=A1000 * 3 + 50', $format);
</pre>
<p></p>
<p>
In this example the cell reference changes in iterations from <code>A1</code> 
to <code>A1000</code>. The parser treats this variable as a <em>token</em> and 
arranges it according to predefined rules. However, since the parser is
oblivious to the value of the token, it is essentially performing the same
calculation 1000 times. This is inefficient.

</p>
<p>
The way to avoid this inefficiency and thereby speed up the writing of
formulas is to parse the formula once and then repeatedly substitute
similar tokens.

</p>
<p>
A formula can be parsed and stored via the <code>store_formula()</code> 
worksheet method. You can then use the <code>repeat_formula()</code> method to 
substitute <code>$pattern</code>, <code>$replace</code> pairs in the stored 
formula:

</p>
<p>
</p><pre>    my $formula = $worksheet-&gt;store_formula('=A1 * 3 + 50');
</pre>
<p></p>
<p>
</p><pre>    for my $row (0..999) {
        $worksheet-&gt;repeat_formula($row, 1, $formula, $format, 'A1', 
'A'.($row +1));
    }
</pre>
<p></p>
<p>
On an arbitrary test machine this method was 10 times faster than the brute
force method shown above.

</p>
<p>
For more information about how Spreadsheet::WriteExcel parses and stores
formulas see the <code>Spreadsheet::WriteExcel::Formula</code> man page.

</p>
<p>
It should be noted however that the overall speed of direct formula parsing
will be improved in a future version.

</p>
<p>
</p><hr>
<h1><a name="EXAMPLES">EXAMPLES</a></h1>
<p>
</p><hr>
<h2><a name="Example_1">Example 1</a></h2>
<p>
The following example shows some of the basic features of
Spreadsheet::WriteExcel.

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    # Create a new workbook called simple.xls and add a worksheet
    my $workbook  = Spreadsheet::WriteExcel-&gt;new("simple.xls");
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    # The general syntax is write($row, $column, $token). Note that 
row and
    # column are zero indexed
</pre>
<p></p>
<p>
</p><pre>    # Write some text
    $worksheet-&gt;write(0, 0,  "Hi Excel!");
</pre>
<p></p>
<p>
</p><pre>    # Write some numbers
    $worksheet-&gt;write(2, 0,  3);          # Writes 3
    $worksheet-&gt;write(3, 0,  3.00000);    # Writes 3
    $worksheet-&gt;write(4, 0,  3.00001);    # Writes 3.00001
    $worksheet-&gt;write(5, 0,  3.14159);    # TeX revision no.?
</pre>
<p></p>
<p>
</p><pre>    # Write some formulas
    $worksheet-&gt;write(7, 0,  '=A3 + A6');
    $worksheet-&gt;write(8, 0,  '=IF(A5&gt;3,"Yes", "No")');
</pre>
<p></p>
<p>
</p><pre>    # Write a hyperlink
    $worksheet-&gt;write(10, 0, '<a 
href="http://www.perl.com/";>http://www.perl.com/</a>');
</pre>
<p></p>

<br><center><img src="WriteExcel_files/simple" alt="The output from 
simple.pl"></center>

<p>
</p><hr>
<h2><a name="Example_2">Example 2</a></h2>
<p>
The following is a general example which demonstrates some features of
working with multiple worksheets.

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    # Create a new Excel workbook
    my $workbook = Spreadsheet::WriteExcel-&gt;new("regions.xls");
</pre>
<p></p>
<p>
</p><pre>    # Add some worksheets
    my $north = $workbook-&gt;add_worksheet("North");
    my $south = $workbook-&gt;add_worksheet("South");
    my $east  = $workbook-&gt;add_worksheet("East");
    my $west  = $workbook-&gt;add_worksheet("West");
</pre>
<p></p>
<p>
</p><pre>    # Add a Format
    my $format = $workbook-&gt;add_format();
    $format-&gt;set_bold();
    $format-&gt;set_color('blue');
</pre>
<p></p>
<p>
</p><pre>    # Add a caption to each worksheet
    foreach my $worksheet ($workbook-&gt;sheets()) {
        $worksheet-&gt;write(0, 0, "Sales", $format);
    }
</pre>
<p></p>
<p>
</p><pre>    # Write some data
    $north-&gt;write(0, 1, 200000);
    $south-&gt;write(0, 1, 100000);
    $east-&gt;write (0, 1, 150000);
    $west-&gt;write (0, 1, 100000);
</pre>
<p></p>
<p>
</p><pre>    # Set the active worksheet
    $south-&gt;activate();
</pre>
<p></p>
<p>
</p><pre>    # Set the width of the first column
    $south-&gt;set_column(0, 0, 20);
</pre>
<p></p>
<p>
</p><pre>    # Set the active cell
    $south-&gt;set_selection(0, 1);
</pre>
<p></p>

<br><center><img src="WriteExcel_files/regions" alt="The output from 
regions.pl"></center>

<p>
</p><hr>
<h2><a name="Example_3">Example 3</a></h2>
<p>
This example shows how to use a conditional numerical format with colours
to indicate if a share price has gone up or down.

</p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    # Create a new workbook and add a worksheet
    my $workbook  = Spreadsheet::WriteExcel-&gt;new("stocks.xls");
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    # Set the column width for columns 1, 2, 3 and 4
    $worksheet-&gt;set_column(0, 3, 15);
</pre>
<p></p>
<p>
</p><pre>    # Create a format for the column headings
    my $header = $workbook-&gt;add_format();
    $header-&gt;set_bold();
    $header-&gt;set_size(12);
    $header-&gt;set_color('blue');
</pre>
<p></p>
<p>
</p><pre>    # Create a format for the stock price
    my $f_price = $workbook-&gt;add_format();
    $f_price-&gt;set_align('left');
    $f_price-&gt;set_num_format('$0.00');
</pre>
<p></p>
<p>
</p><pre>    # Create a format for the stock volume
    my $f_volume = $workbook-&gt;add_format();
    $f_volume-&gt;set_align('left');
    $f_volume-&gt;set_num_format('#,##0');
</pre>
<p></p>
<p>
</p><pre>    # Create a format for the price change. This is an example of a
    # conditional format. The number is formatted as a percentage. If it is
    # positive it is formatted in green, if it is negative it is formatted
    # in red and if it is zero it is formatted as the default font colour
    # (in this case black). Note: the [Green] format produces an unappealing
    # lime green. Try [Color 10] instead for a dark green.
    #
    my $f_change = $workbook-&gt;add_format();
    $f_change-&gt;set_align('left');
    $f_change-&gt;set_num_format('[Green]0.0%;[Red]-0.0%;0.0%');
</pre>
<p></p>
<p>
</p><pre>    # Write out the data
    $worksheet-&gt;write(0, 0, 'Company',$header);
    $worksheet-&gt;write(0, 1, 'Price',  $header);
    $worksheet-&gt;write(0, 2, 'Volume', $header);
    $worksheet-&gt;write(0, 3, 'Change', $header);
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(1, 0, 'Damage Inc.'       );
    $worksheet-&gt;write(1, 1, 30.25,    $f_price ); # $30.25
    $worksheet-&gt;write(1, 2, 1234567,  $f_volume); # 1,234,567
    $worksheet-&gt;write(1, 3, 0.085,    $f_change); # 8.5% in green
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(2, 0, 'Dump Corp.'        );
    $worksheet-&gt;write(2, 1, 1.56,     $f_price ); # $1.56
    $worksheet-&gt;write(2, 2, 7564,     $f_volume); # 7,564
    $worksheet-&gt;write(2, 3, -0.015,   $f_change); # -1.5% in red
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(3, 0, 'Rev Ltd.'          );
    $worksheet-&gt;write(3, 1, 0.13,     $f_price ); # $0.13
    $worksheet-&gt;write(3, 2, 321,      $f_volume); # 321
    $worksheet-&gt;write(3, 3, 0,        $f_change); # 0 in the font color 
(black)
</pre>
<p></p>

<br><center><img src="WriteExcel_files/stocks" alt="The output from 
stocks.pl"></center>

<p>
</p><hr>
<h2><a name="Example_4">Example 4</a></h2>
<p>
The following is a simple example of using functions.

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    # Create a new workbook and add a worksheet
    my $workbook  = Spreadsheet::WriteExcel-&gt;new("stats.xls");
    my $worksheet = $workbook-&gt;add_worksheet('Test data');
</pre>
<p></p>
<p>
</p><pre>    # Set the column width for columns 1
    $worksheet-&gt;set_column(0, 0, 20);
</pre>
<p></p>
<p>
</p><pre>    # Create a format for the headings
    my $format = $workbook-&gt;add_format();
    $format-&gt;set_bold();
</pre>
<p></p>
<p>
</p><pre>    # Write the sample data
    $worksheet-&gt;write(0, 0, 'Sample', $format);
    $worksheet-&gt;write(0, 1, 1);
    $worksheet-&gt;write(0, 2, 2);
    $worksheet-&gt;write(0, 3, 3);
    $worksheet-&gt;write(0, 4, 4);
    $worksheet-&gt;write(0, 5, 5);
    $worksheet-&gt;write(0, 6, 6);
    $worksheet-&gt;write(0, 7, 7);
    $worksheet-&gt;write(0, 8, 8);
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(1, 0, 'Length', $format);
    $worksheet-&gt;write(1, 1, 25.4);
    $worksheet-&gt;write(1, 2, 25.4);
    $worksheet-&gt;write(1, 3, 24.8);
    $worksheet-&gt;write(1, 4, 25.0);
    $worksheet-&gt;write(1, 5, 25.3);
    $worksheet-&gt;write(1, 6, 24.9);
    $worksheet-&gt;write(1, 7, 25.2);
    $worksheet-&gt;write(1, 8, 24.8);
</pre>
<p></p>
<p>
</p><pre>    # Write some statistical functions
    $worksheet-&gt;write(4,  0, 'Count', $format);
    $worksheet-&gt;write(4,  1, '=COUNT(B1:I1)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(5,  0, 'Sum', $format);
    $worksheet-&gt;write(5,  1, '=SUM(B2:I2)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(6,  0, 'Average', $format);
    $worksheet-&gt;write(6,  1, '=AVERAGE(B2:I2)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(7,  0, 'Min', $format);
    $worksheet-&gt;write(7,  1, '=MIN(B2:I2)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(8,  0, 'Max', $format);
    $worksheet-&gt;write(8,  1, '=MAX(B2:I2)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(9,  0, 'Standard Deviation', $format);
    $worksheet-&gt;write(9,  1, '=STDEV(B2:I2)');
</pre>
<p></p>
<p>
</p><pre>    $worksheet-&gt;write(10, 0, 'Kurtosis', $format);
    $worksheet-&gt;write(10, 1, '=KURT(B2:I2)');
</pre>
<p></p>

<br><center><img src="WriteExcel_files/stats" alt="The output from 
stats.pl"></center>

<p>
</p><hr>
<h2><a name="Example_5">Example 5</a></h2>
<p>
The following example converts a tab separated file called <code>tab.txt</code> 
into an Excel file called <code>tab.xls</code>.

</p>
<p>
</p><pre>    #!/usr/bin/perl -w
</pre>
<p></p>
<p>
</p><pre>    use strict;
    use Spreadsheet::WriteExcel;
</pre>
<p></p>
<p>
</p><pre>    open (TABFILE, "tab.txt") or die "tab.txt: $!";
</pre>
<p></p>
<p>
</p><pre>    my $workbook  = Spreadsheet::WriteExcel-&gt;new("tab.xls");
    my $worksheet = $workbook-&gt;add_worksheet();
</pre>
<p></p>
<p>
</p><pre>    # Row and column are zero indexed
    my $row = 0;
</pre>
<p></p>
<p>
</p><pre>    while (&lt;TABFILE&gt;) {
        chomp;
        # Split on single tab
        my @Fld = split('\t', $_);
</pre>
<p></p>
<p>
</p><pre>        my $col = 0;
        foreach my $token (@Fld) {
            $worksheet-&gt;write($row, $col, $token);
            $col++;
        }
        $row++;
    }
</pre>
<p></p>
<p>
</p><hr>
<h2><a name="Additional_Examples">Additional Examples</a></h2>
<p>
If you performed a normal installation the following examples files should
have been copied to your <code>~site/Spreadsheet/WriteExcel/examples</code> 
directory:

</p>
<p>
The following is a description of the example files that are provided with
Spreadsheet::WriteExcel. They are intended to demonstrate the different
features and options of the module.

</p>
<p>
</p><pre>    Getting started
    ===============
    bug_report.pl           A template for submitting bug reports.
    demo.pl                 Creates a demo of some of the features.
    formats.pl              Creates a demo of the available formatting.
    regions.pl              Demonstrates multiple worksheets.
    simple.pl               An example of some of the basic features.
    stats.pl                Basic formulas and functions.
</pre>
<p></p>
<p>
</p><pre>    Advanced
    ========
    bigfile.pl              Write past the 7MB limit with OLE::Storage_Lite.
    cgi.pl                  A simple CGI program.
    chess.pl                An example of formatting using properties.
    colors.pl               Demo of the colour palette and named colours.
    copyformat.pl           Example of copying a cell format.
    diag_border.pl          A simple example of diagonal cell borders.
    easter_egg.pl           Expose the Excel97 flight simulator. A must see.
    filehandle.pl           Examples of working with filehandles.
    headers.pl              Examples of worksheet headers and footers.
    hyperlink1.pl           Shows how to create web hyperlinks.
    hyperlink2.pl           Examples of internal and external hyperlinks.
    images.pl               Adding bitmap images to worksheets.
    indent.pl               An example of cell indentation.
    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.
    mod_perl1.pl            A simple mod_perl 1 program.
    mod_perl2.pl            A simple mod_perl 2 program.
    outline.pl              An example of outlines and grouping.
    panes.pl                An examples of how to create panes.
    protection.pl           Example of cell locking and formula hiding.
    hide_sheet.pl           Simple example of hiding a worksheet.
    repeat.pl               Example of writing repeated formulas.
    sales.pl                An example of a simple sales spreadsheet.
    sendmail.pl             Send an Excel email attachment using Mail::Sender.
    stats_ext.pl            Same as stats.pl with external references.
    stocks.pl               Demonstrates conditional formatting.
    textwrap.pl             Demonstrates text wrapping options.
    win32ole.pl             A sample Win32::OLE example for comparison.
    write_arrays.pl         Example of writing 1D or 2D arrays of data.
    write_to_scalar.pl      Example of writing an Excel file to a Perl scalar.
    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.
</pre>
<p></p>
<p>
</p><pre>    Unicode
    =======
    unicode.pl              Simple example of using Unicode UTF16 strings.
    unicode_japan.pl        Write Japanese Unicode strings using UTF16.
    unicode_cyrillic.pl     Write Russian cyrillic strings using UTF8.
    unicode_list.pl         List the chars in a Unicode font.
    unicode_2022_jp.pl      Japanese: ISO-2022-JP to utf8 in perl 5.8.
    unicode_8859_11.pl      Thai:     ISO-8859_11 to utf8 in perl 5.8.
    unicode_8859_7.pl       Greek:    ISO-8859_7  to utf8 in perl 5.8.
    unicode_big5.pl         Chinese:  BIG5        to utf8 in perl 5.8.
    unicode_cp1251.pl       Russian:  CP1251      to utf8 in perl 5.8.
    unicode_cp1256.pl       Arabic:   CP1256      to utf8 in perl 5.8.
    unicode_koi8r.pl        Russian:  KOI8-R      to utf8 in perl 5.8.
    unicode_polish_utf8.pl  Polish :  UTF8        to utf8 in perl 5.8.
    unicode_shift_jis.pl    Japanese: Shift JIS   to utf8 in perl 5.8.
</pre>
<p></p>
<p>
</p><pre>    Utility
    =======
    csv2xls.pl              Program to convert a CSV file to an Excel file.
    datecalc1.pl            Convert Unix/Perl time to Excel time.
    datecalc2.pl            Calculate an Excel date using Date::Calc.
    lecxe.pl                Convert Excel to WriteExcel using Win32::OLE.
    tab2xls.pl              Program to convert a tab separated file to xls.
</pre>
<p></p>
<p>
</p><pre>    Developer
    =========
    convertA1.pl            Helper functions for dealing with A1 notation.
    function_locale.pl      Add non-English function names to Formula.pm.
    writeA1.pl              Example of how to extend the module.
</pre>
<p></p>
<p>
</p><hr>
<h1><a name="LIMITATIONS">LIMITATIONS</a></h1>
<p>
The following limits are imposed by Excel:

</p>
<p>
</p><pre>    Description                          Limit
    -----------------------------------  ------
    Maximum number of chars in a string  32767
    Maximum number of columns            256
    Maximum number of rows               65536
    Maximum chars in a sheet name        31
    Maximum chars in a header/footer     254
</pre>
<p></p>
<p>
The minimum file size is 6K due to the OLE overhead. The maximum file size
is approximately 7MB (7087104 bytes) of BIFF data. This can be extended by
using Takanori Kawai's OLE::Storage_Lite module <a 
href="http://search.cpan.org/search?dist=OLE-Storage_Lite";>http://search.cpan.org/search?dist=OLE-Storage_Lite</a>
see the <code>bigfile.pl</code> example in the <code>examples</code> directory 
of the distro.

</p>
<p>
</p><hr>
<h1><a name="DOWNLOADING">DOWNLOADING</a></h1>
<p>
The latest version of this module is always available at: <a 
href="http://search.cpan.org/search?dist=Spreadsheet-WriteExcel/";>http://search.cpan.org/search?dist=Spreadsheet-WriteExcel/</a>


</p>
<p>
</p><hr>
<h1><a name="REQUIREMENTS">REQUIREMENTS</a></h1>
<p>
This module requires Perl 5.005 (or later), Parse::RecDescent and
File::Temp:

</p>
<p>
</p><pre>    <a 
href="http://search.cpan.org/search?dist=Parse-RecDescent/";>http://search.cpan.org/search?dist=Parse-RecDescent/</a>
    <a 
href="http://search.cpan.org/search?dist=File-Temp/";>http://search.cpan.org/search?dist=File-Temp/</a>
</pre>
<p></p>
<p>
</p><hr>
<h1><a name="INSTALLATION">INSTALLATION</a></h1>
<p>
See the INSTALL or install.html docs that come with the distribution or:

</p>
<p>
<a 
href="http://search.cpan.org/doc/JMCNAMARA/Spreadsheet-WriteExcel-2.11/WriteExcel/doc/install.html";>http://search.cpan.org/doc/JMCNAMARA/Spreadsheet-WriteExcel-2.11/WriteExcel/doc/install.html</a>


</p>
<p>
</p><hr>
<h1><a name="PORTABILITY">PORTABILITY</a></h1>
<p>
Spreadsheet::WriteExcel will work on the majority of Windows, UNIX and
Macintosh platforms. Specifically, the module will work on any system where
perl packs floats in the 64 bit IEEE format. The float must also be in
little-endian format but it will be reversed if necessary. Thus:

</p>
<p>
</p><pre>    print join(" ", map { sprintf "%#02x", $_ } unpack("C*", pack "d", 
1.2345)), "\n";
</pre>
<p></p>
<p>
should give (or in reverse order):

</p>
<p>
</p><pre>    0x8d 0x97 0x6e 0x12 0x83 0xc0 0xf3 0x3f
</pre>
<p></p>
<p>
In general, if you don't know whether your system supports a 64 bit IEEE
float or not, it probably does. If your system doesn't, WriteExcel will 
<code>croak()</code> with the message given in the <a 
href="#DIAGNOSTICS">DIAGNOSTICS</a> section. You can check which platforms the 
module has been tested on at the
CPAN testers site: <a 
href="http://testers.cpan.org/search?request=dist&amp;dist=Spreadsheet-WriteExcel";>http://testers.cpan.org/search?request=dist&amp;dist=Spreadsheet-WriteExcel</a>


</p>
<p>
</p><hr>
<h1><a name="DIAGNOSTICS">DIAGNOSTICS</a></h1>
<dl>
<dt><a name="item_Filename">Filename required by 
Spreadsheet::WriteExcel-&gt;new()</a></dt><dd>
<p>
A filename must be given in the constructor.

</p>
</dd><dt><a name="item_Can">Can't open filename. It may be in use or 
protected.</a></dt><dd>
<p>
The file cannot be opened for writing. The directory that you are writing
to may be protected or the file may be in use by another program.

</p>
</dd><dt><a name="item_Unable">Unable to create tmp files via 
File::Temp::tempfile()...</a></dt><dd>
<p>
This is a <code>-w</code> warning. You will see it if you are using 
Spreadsheet::WriteExcel in an
environment where temporary files cannot be created, in which case all data
will be stored in memory. The warning is for information only: it does not
affect creation but it will affect the speed of execution for large files.
See the <code>set_tempdir</code> workbook method.

</p>
</dd><dt><a name="item_Maximum">Maximum file size, 7087104, 
exceeded.</a></dt><dd>
<p>
The current OLE implementation only supports a maximum BIFF file of this
size. This limit can be extended, see the <a 
href="#LIMITATIONS">LIMITATIONS</a> section.

</p>
</dd><dt>Can't locate Parse/RecDescent.pm in @INC ...</dt><dd>
<p>
Spreadsheet::WriteExcel requires the Parse::RecDescent module. Download it
from CPAN: <a 
href="http://search.cpan.org/search?dist=Parse-RecDescent";>http://search.cpan.org/search?dist=Parse-RecDescent</a>


</p>
</dd><dt><a name="item_Couldn">Couldn't parse formula ...</a></dt><dd>
<p>
There are a large number of warnings which relate to badly formed formulas
and functions. See the <a href="#FORMULAS_AND_FUNCTIONS_IN_EXCEL">FORMULAS AND 
FUNCTIONS IN EXCEL</a> section for suggestions on how to avoid these errors. 
You should also check
the formula in Excel to ensure that it is valid.

</p>
</dd><dt><a name="item_Required">Required floating point format not supported 
on this platform.</a></dt><dd>
<p>
Operating system doesn't support 64 bit IEEE float or it is byte-ordered in
a way unknown to WriteExcel.

</p>
</dd><dt><a name="item__file_xls_">'file.xls' cannot be accessed. The file may 
be read-only ...</a></dt><dd>
<p>
You may sometimes encounter the following error when trying to open a file
in Excel: "file.xls cannot be accessed. The file may be read-only, or you
may be trying to access a read-only location. Or, the server the document
is stored on may not be responding."

</p>
<p>
This error generally means that the Excel file has been corrupted. There
are two likely causes of this: the file was FTPed in ASCII mode instead of
binary mode or else the file was created with UTF8 data returned by an XML
parser. See <a href="#WORKING_WITH_XML">WORKING WITH XML</a> for further 
details.

</p>
</dd></dl>
<p>
</p><hr>
<h1><a name="THE_EXCEL_BINARY_FORMAT">THE EXCEL BINARY FORMAT</a></h1>
<p>
The following is some general information about the Excel binary format for
anyone who may be interested.

</p>
<p>
Excel data is stored in the "Binary Interchange File Format" (BIFF) file
format. Details of this format are given in the Excel SDK, the "Excel
Developer's Kit" from Microsoft Press. It is also included in the MSDN CD
library but is no longer available on the MSDN website. Versions of the
BIFF documentation are available at www.wotsit.org, <a 
href="http://www.wotsit.org/search.asp?page=2&amp;s=database";>http://www.wotsit.org/search.asp?page=2&amp;s=database</a>


</p>
<p>
Charles Wybble has collected together almost all of the available
information about the Excel file format. See "The Chicago Project" at <a 
href="http://chicago.sourceforge.net/devel/";>http://chicago.sourceforge.net/devel/</a>


</p>
<p>
Daniel Rentz of OpenOffice.org has also written a detailed description of
the Excel workbook records, see <a 
href="http://sc.openoffice.org/excelfileformat.pdf";>http://sc.openoffice.org/excelfileformat.pdf</a>


</p>
<p>
The BIFF portion of the Excel file is comprised of contiguous binary
records that have different functions and that hold different types of
data. Each BIFF record is comprised of the following three parts:

</p>
<p>
</p><pre>        Record name;   Hex identifier, length = 2 bytes
        Record length; Length of following data, length = 2 bytes
        Record data;   Data, length = variable
</pre>
<p></p>
<p>
The BIFF data is stored along with other data in an OLE Compound File. This
is a structured storage which acts like a file system within a file. A
Compound File is comprised of storages and streams which, to follow the
file system analogy, are like directories and files.

</p>
<p>
The documentation for the OLE::Storage module, <a 
href="http://user.cs.tu-berlin.de/%7Eschwartz/pmh/guide.html";>http://user.cs.tu-berlin.de/~schwartz/pmh/guide.html</a>
, contains one of the few descriptions of the OLE Compound File in the
public domain. The Digital Imaging Group have also detailed the OLE format
in the JPEG2000 specification: see Appendix A of <a 
href="http://www.i3a.org/pdf/wg1n1017.pdf";>http://www.i3a.org/pdf/wg1n1017.pdf</a>


</p>
<p>
For a open source implementation of the OLE library see the 'cole' library
at <a href="http://atena.com/libole2.php";>http://atena.com/libole2.php</a>

</p>
<p>
The source code for the Excel plugin of the Gnumeric spreadsheet also
contains information relevant to the Excel BIFF format and the OLE
container, <a 
href="http://www.gnome.org/projects/gnumeric/";>http://www.gnome.org/projects/gnumeric/</a>
and <a 
href="ftp://ftp.ximian.com/pub/ximian-source/";>ftp://ftp.ximian.com/pub/ximian-source/</a>


</p>
<p>
In addition the source code for OpenOffice.org is available at <a 
href="http://www.openoffice.org/";>http://www.openoffice.org/</a>

</p>
<p>
An article describing Spreadsheet::WriteExcel and how it works appears in
Issue #19 of The Perl Journal, <a 
href="http://www.samag.com/documents/s=1272/sam05030004/";>http://www.samag.com/documents/s=1272/sam05030004/</a>
It is reproduced, by kind permission, in the <code>doc</code> directory of the 
distro.

</p>
<p>
Please note that the provision of this information does not constitute an
invitation to start hacking at the BIFF or OLE file formats. There are more
interesting ways to waste your time. ;-)

</p>
<p>
</p><hr>
<h1><a name="WRITING_EXCEL_FILES">WRITING EXCEL FILES</a></h1>
<p>
Depending on your requirements, background and general sensibilities you
may prefer one of the following methods of getting data into Excel:

</p>
<ul>
<li><a name="item_Win32">Win32::OLE module and office automation</a>
<p>
This requires a Windows platform and an installed copy of Excel. This is
the most powerful and complete method for interfacing with Excel. See <a 
href="http://www.activestate.com/ASPN/Reference/Products/ActivePerl-5.6/faq/Windows/ActivePerl-Winfaq12.html";>http://www.activestate.com/ASPN/Reference/Products/ActivePerl-5.6/faq/Windows/ActivePerl-Winfaq12.html</a>
and <a 
href="http://www.activestate.com/ASPN/Reference/Products/ActivePerl-5.6/site/lib/Win32/OLE.html";>http://www.activestate.com/ASPN/Reference/Products/ActivePerl-5.6/site/lib/Win32/OLE.html</a>
If your main platform is UNIX but you have the resources to set up a
separate Win32/MSOffice server, you can convert office documents to text,
postscript or PDF using Win32::OLE. For a demonstration of how to do this
using Perl see Docserver: <a 
href="http://search.cpan.org/search?mode=module&amp;query=docserver";>http://search.cpan.org/search?mode=module&amp;query=docserver</a>


</p>
</li><li><a name="item_CSV">CSV, comma separated variables or text</a>
<p>
If the file extension is <code>csv</code>, Excel will open and convert this 
format automatically. Generating a valid
CSV file isn't as easy as it seems. Have a look at the DBD::RAM, DBD::CSV,
Text::xSV and Text::CSV_XS modules.

</p>
</li><li><a name="item_DBI">DBI with DBD::ADO or DBD::ODBC</a>
<p>
Excel files contain an internal index table that allows them to act like a
database file. Using one of the standard Perl database modules you can
connect to an Excel file as a database.

</p>
</li><li><a name="item_DBD">DBD::Excel</a>
<p>
You can also access Spreadsheet::WriteExcel using the standard DBI
interface via Takanori Kawai's DBD::Excel module <a 
href="http://search.cpan.org/dist/DBD-Excel";>http://search.cpan.org/dist/DBD-Excel</a>


</p>
</li><li><a name="item_Spreadsheet">Spreadsheet::WriteExcelXML</a>
<p>
This module allows you to create an Excel XML file using the same interface
as Spreadsheet::WriteExcel. See: <a 
href="http://search.cpan.org/dist/Spreadsheet-WriteExcelXML";>http://search.cpan.org/dist/Spreadsheet-WriteExcelXML</a>


</p>
</li><li><a name="item_Excel">Excel::Template</a>
<p>
This module allows you to create an Excel file from an XML template in a
manner similar to HTML::Template. See <a 
href="http://search.cpan.org/dist/Excel-Template/";>http://search.cpan.org/dist/Excel-Template/</a>


</p>
</li><li><a name="item_Spreadsheet">Spreadsheet::WriteExcel::FromXML</a>
<p>
This module allows you to turn a simple XML file into an Excel file using
Spreadsheet::WriteExcel as a backend. The format of the XML file is defined
by a supplied DTD: <a 
href="http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromXML";>http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromXML</a>


</p>
</li><li><a name="item_Spreadsheet">Spreadsheet::WriteExcel::Simple</a>
<p>
This provides an easier interface to Spreadsheet::WriteExcel: <a 
href="http://search.cpan.org/dist/Spreadsheet-WriteExcel-Simple";>http://search.cpan.org/dist/Spreadsheet-WriteExcel-Simple</a>


</p>
</li><li><a name="item_Spreadsheet">Spreadsheet::WriteExcel::FromDB</a>
<p>
This is a useful module for creating Excel files directly from a DB table:
<a 
href="http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromDB";>http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromDB</a>


</p>
</li><li><a name="item_HTML">HTML tables</a>
<p>
This is an easy way of adding formatting via a text based format.

</p>
</li><li><a name="item_XML">XML or HTML</a>
<p>
The Excel XML and HTML file specification are available from <a 
href="http://msdn.microsoft.com/library/officedev/ofxml2k/ofxml2k.htm";>http://msdn.microsoft.com/library/officedev/ofxml2k/ofxml2k.htm</a>


</p>
</li></ul>
<p>
For other Perl-Excel modules try the following search: <a 
href="http://search.cpan.org/search?mode=module&amp;query=excel";>http://search.cpan.org/search?mode=module&amp;query=excel</a>


</p>
<p>
</p><hr>
<h1><a name="READING_EXCEL_FILES">READING EXCEL FILES</a></h1>
<p>
To read data from Excel files try:

</p>
<ul>
<li><a name="item_Spreadsheet">Spreadsheet::ParseExcel</a>
<p>
This uses the OLE::Storage-Lite module to extract data from an Excel file.
<a 
href="http://search.cpan.org/dist/Spreadsheet-ParseExcel";>http://search.cpan.org/dist/Spreadsheet-ParseExcel</a>


</p>
</li><li><a name="item_Spreadsheet">Spreadsheet::ParseExcel_XLHTML</a>
<p>
This module uses Spreadsheet::ParseExcel's interface but uses xlHtml (see
below) to do the conversion: <a 
href="http://search.cpan.org/dist/Spreadsheet-ParseExcel_XLHTML";>http://search.cpan.org/dist/Spreadsheet-ParseExcel_XLHTML</a>
Spreadsheet::ParseExcel_XLHTML

</p>
</li><li><a name="item_xlHtml">xlHtml</a>
<p>
This is an open source "Excel to HTML Converter" C/C++ project at <a 
href="http://www.xlhtml.org/";>http://www.xlhtml.org/</a> See also, the OLE
Filters Project at <a 
href="http://atena.com/libole2.php";>http://atena.com/libole2.php</a>

</p>
</li><li><a name="item_DBD">DBD::Excel (reading)</a>
<p>
You can also access Spreadsheet::ParseExcel using the standard DBI
interface via Takanori Kawai's DBD::Excel module <a 
href="http://search.cpan.org/dist/DBD-Excel";>http://search.cpan.org/dist/DBD-Excel</a>


</p>
</li><li><a name="item_Win32">Win32::OLE module and office automation 
(reading)</a>
<p>
See, the section <a href="#WRITING_EXCEL_FILES">WRITING EXCEL FILES</a>.

</p>
</li><li><a name="item_HTML">HTML tables (reading)</a>
<p>
If the files are saved from Excel in a HTML format the data can be accessed
using HTML::TableExtract <a 
href="http://search.cpan.org/dist/HTML-TableExtract";>http://search.cpan.org/dist/HTML-TableExtract</a>


</p>
</li><li><a name="item_DBI">DBI with DBD::ADO or DBD::ODBC.</a>
<p>
See, the section <a href="#WRITING_EXCEL_FILES">WRITING EXCEL FILES</a>.

</p>
</li><li><a name="item_XML">XML::Excel</a>
<p>
Converts Excel files to XML using Spreadsheet::ParseExcel <a 
href="http://search.cpan.org/dist/XML-Excel.";>http://search.cpan.org/dist/XML-Excel.</a>


</p>
</li><li><a name="item_OLE">OLE::Storage, aka LAOLA</a>
<p>
This is a Perl interface to OLE file formats. In particular, the distro
contains an Excel to HTML converter called Herbert, <a 
href="http://user.cs.tu-berlin.de/%7Eschwartz/pmh/";>http://user.cs.tu-berlin.de/~schwartz/pmh/</a>
This has been superseded by the Spreadsheet::ParseExcel module.

</p>
</li></ul>
<p>
For other Perl-Excel modules try the following search: <a 
href="http://search.cpan.org/search?mode=module&amp;query=excel";>http://search.cpan.org/search?mode=module&amp;query=excel</a>


</p>
<p>
If you wish to view Excel files on a UNIX/Linux platform check out the
excellent Gnumeric spreadsheet application at <a 
href="http://www.gnome.org/projects/gnumeric/";>http://www.gnome.org/projects/gnumeric/</a>
or OpenOffice.org at <a 
href="http://www.openoffice.org/";>http://www.openoffice.org/</a>

</p>
<p>
If you wish to view Excel files on a Windows platform which doesn't have
Excel installed you can use the free Microsoft Excel Viewer <a 
href="http://office.microsoft.com/downloads/2000/xlviewer.aspx";>http://office.microsoft.com/downloads/2000/xlviewer.aspx</a>


</p>
<p>
</p><hr>
<h1><a name="Warning_about_XML_Parser_and_Pe">Warning about XML::Parser and 
Perl 5.6</a></h1>
<p>
You must be careful when using Spreadsheet::WriteExcel in conjunction with
Perl 5.6 and XML::Parser (and other XML parsers) due to the fact that the
data returned by the parser is generally in UTF8 format.

</p>
<p>
When UTF8 strings are added to Spreadsheet::WriteExcel's internal data it
causes the generated Excel file to become corrupt.

</p>
<p>
Note, this doesn't affect Perl 5.005 (which doesn't try to handle UTF8) or
5.8 (which handles it correctly).

</p>
<p>
To avoid this problem you should upgrade to Perl 5.8, if possible, or else
you should convert the output data from XML::Parser to ASCII or ISO-8859-1
using one of the following methods:

</p>
<p>
</p><pre>    $new_str = pack 'C*', unpack 'U*', $utf8_str;
</pre>
<p></p>
<p>
</p><pre>    use Unicode::MapUTF8 'from_utf8';
    $new_str = from_utf8({-str =&gt; $utf8_str, -charset =&gt; 'ISO-8859-1'});
</pre>
<p></p>
<p>
</p><hr>
<h1><a name="BUGS">BUGS</a></h1>
<p>
Formulas are formulae.

</p>
<p>
This version of the module doesn't support the <code>write_comment()</code>
method. This will be fixed soon.

</p>
<p>
XML and UTF8 data on Perl 5.6 can cause Excel files created by
Spreadsheet::WriteExcel to become corrupt. See <a 
href="#Warning_about_XML_Parser_and_Pe">Warning about XML::Parser and Perl 
5.6</a> for further details.

</p>
<p>
The format object that is used with a <code>merge_range()</code> method call is 
marked internally as being associated with a merged range.It
is a fatal error to use a merged format in a non-merged cell. The current
workaround is to use separate formats for merged and non-merged cell. This
restriction will be removed in a future release.

</p>
<p>
Nested formulas sometimes aren't parsed correctly and give a result of
"#VALUE". If you come across a formula that parses like this, let
me know.

</p>
<p>
Spreadsheet::ParseExcel: All formulas created by Spreadsheet::WriteExcel
are read as having a value of zero. This is because Spreadsheet::WriteExcel
only stores the formula and not the calculated result.

</p>
<p>
OpenOffice.org: Some formatting is not displayed correctly.

</p>
<p>
Gnumeric: Some formatting is not displayed correctly. URLs are not
displayed as links. Page setup can cause Gnumeric to crash.

</p>
<p>
The lack of a portable way of writing a little-endian 64 bit IEEE float.
There is beta code available to fix this. Let me know if you wish to test
it on your platform.

</p>
<p>
If you wish to submit a bug report run the <code>bug_report.pl</code> program 
in the <code>examples</code> directory of the distro.

</p>
<p>
</p><hr>
<h1><a name="TO_DO">TO DO</a></h1>
<p>
The roadmap is as follows:

</p>
<ul>
<li><a name="item_Add">Add write_comment().</a>
</li><li><a name="item_Add">Add AutoFilters.</a>
</li></ul>
<p>
Also, here are some of the most requested features that probably won't get
added:

</p>
<ul>
<li><a name="item_Macros">Macros.</a>
<p>
This would solve some other problems neatly. However, the format of Excel
macros isn't documented.

</p>
</li><li><a name="item_Some">Some feature that you really need. ;-)</a>
</li></ul>
<p>
If there is some feature of an Excel file that you really, really need then
you should use Win32::OLE with Excel on Windows. If you are on Unix you
could consider connecting to a Windows server via Docserver or SOAP, see <a 
href="#WRITING_EXCEL_FILES">WRITING EXCEL FILES</a>.

</p>
<p>
</p><hr>
<h1><a name="MAILING_LIST">MAILING LIST</a></h1>
<p>
There is a Google group for discussing and asking questions about
Spreadsheet::WriteExcel: <a 
href="http://groups-beta.google.com/group/spreadsheet-writeexcel/";>http://groups-beta.google.com/group/spreadsheet-writeexcel/</a>
</p><p>
<table style="border: 1px solid rgb(170, 0, 51); font-size: small;" 
align="center">
  <tbody><tr>
    <td rowspan="3">
     <img src="WriteExcel_files/groups_medium" alt="Google Groups" height="58" 
width="150">
    </td>
    <td colspan="2" align="center"><b>Subscribe to 
Spreadsheet::WriteExcel</b></td>
  </tr>
  <form 
action="http://groups-beta.google.com/group/spreadsheet-writeexcel/boxsubscribe";></form>
  <tr>
    <td>Email: <input name="email" type="text"></td>
    <td>
      <table style="border: 2px outset rgb(255, 204, 51); padding: 2px; 
background-color: rgb(255, 204, 51);">
      <tbody><tr>
        <td>
         <input name="sub" value="Subscribe" type="submit">
        </td>
      </tr>
      </tbody></table>
    </td>
  </tr>

  <tr><td colspan="2" align="center">
   <a href="http://groups-beta.google.com/group/spreadsheet-writeexcel";>Browse 
Archives</a> at
    <a href="http://groups-beta.google.com/";>groups-beta.google.com</a>
  </td></tr>
</tbody></table>

</p><p>
Alternatively you can keep up to date with future releases by subscribing
at: <a 
href="http://freshmeat.net/projects/writeexcel/";>http://freshmeat.net/projects/writeexcel/</a>


</p>
<p>
</p><hr>
<h1><a name="SEE_ALSO">SEE ALSO</a></h1>
<p>
Spreadsheet::ParseExcel: <a 
href="http://search.cpan.org/dist/Spreadsheet-ParseExcel";>http://search.cpan.org/dist/Spreadsheet-ParseExcel</a>


</p>
<p>
Spreadsheet-WriteExcel-FromXML: <a 
href="http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromXML";>http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromXML</a>


</p>
<p>
Spreadsheet::WriteExcel::FromDB: <a 
href="http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromDB";>http://search.cpan.org/dist/Spreadsheet-WriteExcel-FromDB</a>


</p>
<p>
Excel::Template: <a 
href="http://search.cpan.org/%7Erkinyon/Excel-Template/";>http://search.cpan.org/~rkinyon/Excel-Template/</a>


</p>
<p>
DateTime::Format::Excel: <a 
href="http://search.cpan.org/dist/DateTime-Format-Excel";>http://search.cpan.org/dist/DateTime-Format-Excel</a>


</p>
<p>
"Reading and writing Excel files with Perl" by Teodor Zlatanov, atIBM
developerWorks: <a 
href="http://www-106.ibm.com/developerworks/library/l-pexcel/";>http://www-106.ibm.com/developerworks/library/l-pexcel/</a>


</p>
<p>
"Excel-Dateien mit Perl erstellen - Controller im Gl�ck" by Peter
Dintelmann and Christian Kirsch in the German Unix/web journal iX: <a 
href="http://www.heise.de/ix/artikel/2001/06/175/";>http://www.heise.de/ix/artikel/2001/06/175/</a>


</p>
<p>
"Spreadsheet::WriteExcel" in The Perl Journal: <a 
href="http://www.samag.com/documents/s=1272/sam05030004/";>http://www.samag.com/documents/s=1272/sam05030004/</a>


</p>
<p>
Spreadsheet::WriteExcel documentation in Japanese by Takanori Kawai. <a 
href="http://member.nifty.ne.jp/hippo2000/perltips/Spreadsheet/WriteExcel.htm";>http://member.nifty.ne.jp/hippo2000/perltips/Spreadsheet/WriteExcel.htm</a>


</p>
<p>
Oesterly user brushes with fame: <a 
href="http://oesterly.com/releases/12102000.html";>http://oesterly.com/releases/12102000.html</a>


</p>
<p>
</p><hr>
<h1><a name="ACKNOWLEDGEMENTS">ACKNOWLEDGEMENTS</a></h1>
<p>
The following people contributed to the debugging and testing of
Spreadsheet::WriteExcel:

</p>
<p>
Alexander Farber, Andre de Bruin, address@hidden, Artur Silveira da Cunha,
Borgar Olsen, Brian White, Bob Mackay, Cedric Bouvier, Chad Johnson, CPAN
testers, Damyan Ivanov, Daniel Berger, Daniel Gardner, Dmitry Kochurov,
Eric Frazier, Ernesto Baschny, Felipe P�rez Galiana, Gordon Simpson, Hanc
Pavel, Harold Bamford, James Holmes, James Wilkinson, Johan Ekenberg,
Johann Hanne, Jonathan Scott Duff, J.C. Wren, Kenneth Stacey, Keith Miller,
Kyle Krom, Marc Rosenthal, Markus Schmitz, Michael Braig, Michael
Buschauer, Mike Blazer, Michael Erickson, Michael W J West, Ning Xie, Paul
J. Falbe, Paul Medynski, Peter Dintelmann, Pierre Laplante, Praveen Kotha,
Reto Badertscher, Rich Sorden, Shane Ashby, Shenyu Zheng, Stephan Loescher,
Steve Sapovits, Sven Passig, Svetoslav Marinov, Tamas Gulacsi, Troy
Daniels, Vahe Sarkissian.

</p>
<p>
The following people contributed patches, examples or Excel information:

</p>
<p>
Andrew Benham, Bill Young, Cedric Bouvier, Charles Wybble, Daniel Rentz,
David Robins, Franco Venturi, Ian Penman, John Heitmann, Jon Guy, Kyle R.
Burton, Pierre-Jean Vouette, Rubio, Marco Geri, Mark Fowler, Matisse Enzer,
Sam Kington, Takanori Kawai, Tom O'Sullivan.

</p>
<p>
Many thanks to Ron McKelvey, Ronzo Consulting for Siemens, who sponsored
the development of the formula caching routines.

</p>
<p>
Additional thanks to Takanori Kawai for translating the documentation into
Japanese.

</p>
<p>
Gunnar Wolf maintains the Debian distro.

</p>
<p>
Thanks to Damian Conway for the excellent Parse::RecDescent.

</p>
<p>
Thanks to Tim Jenness for File::Temp.

</p>
<p>
Thanks to Michael Meeks and Jody Goldberg for their work on Gnumeric.

</p>
<p>
</p><hr>
<h1><a name="AUTHOR">AUTHOR</a></h1>
<p>
John McNamara <a href="mailto:address@hidden";>address@hidden</a>

</p>
<p>
</p><pre>    Imagine a court of one: the queen a young mother,
    Unhappy, alone all day with her firstborn child
    And her new baby in a squalid apartment
</pre>
<p></p>
<p>
</p><pre>    Of too few rooms, a different race from her neighbors.
    She tells the child she's going to kill herself.
    She broods, she rages. Hoping to distract her,
</pre>
<p></p>
<p>
</p><pre>    The child cuts capers, he sings, he does imitations
    Of different people in the building, he jokes,
    He feels if he keeps her alive until the father
</pre>
<p></p>
<p>
</p><pre>    Gets home from work, they'll be okay till morning.
    It's laughter versus the bedroom and the pills.
    What is he in his efforts but a courtier?
</pre>
<p></p>
<p>
</p><pre>        -- Robert Pinsky
</pre>
<p></p>
<p>
</p><hr>
<h1><a name="COPYRIGHT">COPYRIGHT</a></h1>
<p>
� MM-MMV, John McNamara.

</p>
<p>
All Rights Reserved. This module is free software. It may be used,
redistributed and/or modified under the same terms as Perl itself.

</p>

    <br><br>
    <center>
    <a href="http://www.opencube.com/";>DHTML Menu / JavaScript Menu Powered By 
OpenCube</a><br><br>
    </center>
</body></html>

====================================================
Index: Parser.php
<?php
/**
*  Class for parsing Excel formulas
*
*  License Information:
*
*    Spreadsheet::WriteExcel:  A library for generating Excel Spreadsheets
*    Copyright (C) 2002 Xavier Noguer address@hidden
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/**
* @const ADD token identifier for character "+"
*/
define('ADD',"+");

/**
* @const SUB token identifier for character "-"
*/
define('SUB',"-");

/**
* @const EQUAL token identifier for character "="
*/
define('EQUAL',"=");

/**
* @const MUL token identifier for character "*"
*/
define('MUL',"*");

/**
* @const DIV token identifier for character "/"
*/
define('DIV',"/");

/**
* @const OPEN token identifier for character "("
*/
define('OPEN',"(");

/**
* @const CLOSE token identifier for character ")"
*/
define('CLOSE',")");

/**
* @const COMA token identifier for character ","
*/
define('COMA',",");

/**
* Class for parsing Excel formulas
*
* @author Xavier Noguer <address@hidden>
* @package Spreadsheet_WriteExcel
*/
class Parser
  {
/**
* The class constructor
*
* @param integer $byte_order The byte order (Little endian or Big endian) of 
the architecture
                             (optional). 1 => big endian, 0 (default) => little 
endian.
*/
  function Parser($byte_order = 0)
    {
    $this->_current_char  = 0;        // The index of the character we are 
currently looking at.
    $this->_current_token = '';       // The token we are working on.
    $this->_formula       = "";       // The formula to parse.
    $this->_lookahead     = '';       // The character ahead of the current 
char.
    $this->_parse_tree    = '';       // The parse tree to be generated.
    $this->_initialize_hashes();      // Initialize the hashes: ptg's and 
function's ptg's
    $this->_byte_order = $byte_order; // Little Endian or Big Endian
    $this->_func_args  = 0;           // Number of arguments for the current 
function
    $this->_volatile   = 0;
    }

/**
* Initialize the ptg and function hashes.
*/
  function _initialize_hashes()
    {
    // The Excel ptg indices
    $this->ptg = array(
        'ptgExp'       => 0x01,
        'ptgTbl'       => 0x02,
        'ptgAdd'       => 0x03,
        'ptgSub'       => 0x04,
        'ptgMul'       => 0x05,
        'ptgDiv'       => 0x06,
        'ptgPower'     => 0x07,
        'ptgConcat'    => 0x08,
        'ptgLT'        => 0x09,
        'ptgLE'        => 0x0A,
        'ptgEQ'        => 0x0B,
        'ptgGE'        => 0x0C,
        'ptgGT'        => 0x0D,
        'ptgNE'        => 0x0E,
        'ptgIsect'     => 0x0F,
        'ptgUnion'     => 0x10,
        'ptgRange'     => 0x11,
        'ptgUplus'     => 0x12,
        'ptgUminus'    => 0x13,
        'ptgPercent'   => 0x14,
        'ptgParen'     => 0x15,
        'ptgMissArg'   => 0x16,
        'ptgStr'       => 0x17,
        'ptgAttr'      => 0x19,
        'ptgSheet'     => 0x1A,
        'ptgEndSheet'  => 0x1B,
        'ptgErr'       => 0x1C,
        'ptgBool'      => 0x1D,
        'ptgInt'       => 0x1E,
        'ptgNum'       => 0x1F,
        'ptgArray'     => 0x20,
        'ptgFunc'      => 0x21,
        'ptgFuncVar'   => 0x22,
        'ptgName'      => 0x23,
        'ptgRef'       => 0x24,
        'ptgArea'      => 0x25,
        'ptgMemArea'   => 0x26,
        'ptgMemErr'    => 0x27,
        'ptgMemNoMem'  => 0x28,
        'ptgMemFunc'   => 0x29,
        'ptgRefErr'    => 0x2A,
        'ptgAreaErr'   => 0x2B,
        'ptgRefN'      => 0x2C,
        'ptgAreaN'     => 0x2D,
        'ptgMemAreaN'  => 0x2E,
        'ptgMemNoMemN' => 0x2F,
        'ptgNameX'     => 0x39,
        'ptgRef3d'     => 0x3A,
        'ptgArea3d'    => 0x3B,
        'ptgRefErr3d'  => 0x3C,
        'ptgAreaErr3d' => 0x3D,
        'ptgArrayV'    => 0x40,
        'ptgFuncV'     => 0x41,
        'ptgFuncVarV'  => 0x42,
        'ptgNameV'     => 0x43,
        'ptgRefV'      => 0x44,
        'ptgAreaV'     => 0x45,
        'ptgMemAreaV'  => 0x46,
        'ptgMemErrV'   => 0x47,
        'ptgMemNoMemV' => 0x48,
        'ptgMemFuncV'  => 0x49,
        'ptgRefErrV'   => 0x4A,
        'ptgAreaErrV'  => 0x4B,
        'ptgRefNV'     => 0x4C,
        'ptgAreaNV'    => 0x4D,
        'ptgMemAreaNV' => 0x4E,
        'ptgMemNoMemN' => 0x4F,
        'ptgFuncCEV'   => 0x58,
        'ptgNameXV'    => 0x59,
        'ptgRef3dV'    => 0x5A,
        'ptgArea3dV'   => 0x5B,
        'ptgRefErr3dV' => 0x5C,
        'ptgAreaErr3d' => 0x5D,
        'ptgArrayA'    => 0x60,
        'ptgFuncA'     => 0x61,
        'ptgFuncVarA'  => 0x62,
        'ptgNameA'     => 0x63,
        'ptgRefA'      => 0x64,
        'ptgAreaA'     => 0x65,
        'ptgMemAreaA'  => 0x66,
        'ptgMemErrA'   => 0x67,
        'ptgMemNoMemA' => 0x68,
        'ptgMemFuncA'  => 0x69,
        'ptgRefErrA'   => 0x6A,
        'ptgAreaErrA'  => 0x6B,
        'ptgRefNA'     => 0x6C,
        'ptgAreaNA'    => 0x6D,
        'ptgMemAreaNA' => 0x6E,
        'ptgMemNoMemN' => 0x6F,
        'ptgFuncCEA'   => 0x78,
        'ptgNameXA'    => 0x79,
        'ptgRef3dA'    => 0x7A,
        'ptgArea3dA'   => 0x7B,
        'ptgRefErr3dA' => 0x7C,
        'ptgAreaErr3d' => 0x7D
        );

    // Thanks to Michael Meeks and Gnumeric for the initial arg values.
    //
    // The following hash was generated by "function_locale.pl" in the distro.
    // Refer to function_locale.pl for non-English function names.
    //
    // The array elements are as follow:
    // ptg:   The Excel function ptg code.
    // args:  The number of arguments that the function takes:
    //           >=0 is a fixed number of arguments.
    //           -1  is a variable  number of arguments.
    // class: The reference, value or array class of the function args.
    // vol:   The function is volatile.
    //
    $this->_functions = array(
          // function                  ptg  args  class  vol
          'COUNT'           => array(   0,   -1,    0,    0 ),
          'IF'              => array(   1,   -1,    1,    0 ),
          'ISNA'            => array(   2,    1,    1,    0 ),
          'ISERROR'         => array(   3,    1,    1,    0 ),
          'SUM'             => array(   4,   -1,    0,    0 ),
          'AVERAGE'         => array(   5,   -1,    0,    0 ),
          'MIN'             => array(   6,   -1,    0,    0 ),
          'MAX'             => array(   7,   -1,    0,    0 ),
          'ROW'             => array(   8,   -1,    0,    0 ),
          'COLUMN'          => array(   9,   -1,    0,    0 ),
          'NA'              => array(  10,    0,    0,    0 ),
          'NPV'             => array(  11,   -1,    1,    0 ),
          'STDEV'           => array(  12,   -1,    0,    0 ),
          'DOLLAR'          => array(  13,   -1,    1,    0 ),
          'FIXED'           => array(  14,   -1,    1,    0 ),
          'SIN'             => array(  15,    1,    1,    0 ),
          'COS'             => array(  16,    1,    1,    0 ),
          'TAN'             => array(  17,    1,    1,    0 ),
          'ATAN'            => array(  18,    1,    1,    0 ),
          'PI'              => array(  19,    0,    1,    0 ),
          'SQRT'            => array(  20,    1,    1,    0 ),
          'EXP'             => array(  21,    1,    1,    0 ),
          'LN'              => array(  22,    1,    1,    0 ),
          'LOG10'           => array(  23,    1,    1,    0 ),
          'ABS'             => array(  24,    1,    1,    0 ),
          'INT'             => array(  25,    1,    1,    0 ),
          'SIGN'            => array(  26,    1,    1,    0 ),
          'ROUND'           => array(  27,    2,    1,    0 ),
          'LOOKUP'          => array(  28,   -1,    0,    0 ),
          'INDEX'           => array(  29,   -1,    0,    1 ),
          'REPT'            => array(  30,    2,    1,    0 ),
          'MID'             => array(  31,    3,    1,    0 ),
          'LEN'             => array(  32,    1,    1,    0 ),
          'VALUE'           => array(  33,    1,    1,    0 ),
          'TRUE'            => array(  34,    0,    1,    0 ),
          'FALSE'           => array(  35,    0,    1,    0 ),
          'AND'             => array(  36,   -1,    0,    0 ),
          'OR'              => array(  37,   -1,    0,    0 ),
          'NOT'             => array(  38,    1,    1,    0 ),
          'MOD'             => array(  39,    2,    1,    0 ),
          'DCOUNT'          => array(  40,    3,    0,    0 ),
          'DSUM'            => array(  41,    3,    0,    0 ),
          'DAVERAGE'        => array(  42,    3,    0,    0 ),
          'DMIN'            => array(  43,    3,    0,    0 ),
          'DMAX'            => array(  44,    3,    0,    0 ),
          'DSTDEV'          => array(  45,    3,    0,    0 ),
          'VAR'             => array(  46,   -1,    0,    0 ),
          'DVAR'            => array(  47,    3,    0,    0 ),
          'TEXT'            => array(  48,    2,    1,    0 ),
          'LINEST'          => array(  49,   -1,    0,    0 ),
          'TREND'           => array(  50,   -1,    0,    0 ),
          'LOGEST'          => array(  51,   -1,    0,    0 ),
          'GROWTH'          => array(  52,   -1,    0,    0 ),
          'PV'              => array(  56,   -1,    1,    0 ),
          'FV'              => array(  57,   -1,    1,    0 ),
          'NPER'            => array(  58,   -1,    1,    0 ),
          'PMT'             => array(  59,   -1,    1,    0 ),
          'RATE'            => array(  60,   -1,    1,    0 ),
          'MIRR'            => array(  61,    3,    0,    0 ),
          'IRR'             => array(  62,   -1,    0,    0 ),
          'RAND'            => array(  63,    0,    1,    1 ),
          'MATCH'           => array(  64,   -1,    0,    0 ),
          'DATE'            => array(  65,    3,    1,    0 ),
          'TIME'            => array(  66,    3,    1,    0 ),
          'DAY'             => array(  67,    1,    1,    0 ),
          'MONTH'           => array(  68,    1,    1,    0 ),
          'YEAR'            => array(  69,    1,    1,    0 ),
          'WEEKDAY'         => array(  70,   -1,    1,    0 ),
          'HOUR'            => array(  71,    1,    1,    0 ),
          'MINUTE'          => array(  72,    1,    1,    0 ),
          'SECOND'          => array(  73,    1,    1,    0 ),
          'NOW'             => array(  74,    0,    1,    1 ),
          'AREAS'           => array(  75,    1,    0,    1 ),
          'ROWS'            => array(  76,    1,    0,    1 ),
          'COLUMNS'         => array(  77,    1,    0,    1 ),
          'OFFSET'          => array(  78,   -1,    0,    1 ),
          'SEARCH'          => array(  82,   -1,    1,    0 ),
          'TRANSPOSE'       => array(  83,    1,    1,    0 ),
          'TYPE'            => array(  86,    1,    1,    0 ),
          'ATAN2'           => array(  97,    2,    1,    0 ),
          'ASIN'            => array(  98,    1,    1,    0 ),
          'ACOS'            => array(  99,    1,    1,    0 ),
          'CHOOSE'          => array( 100,   -1,    1,    0 ),
          'HLOOKUP'         => array( 101,   -1,    0,    0 ),
          'VLOOKUP'         => array( 102,   -1,    0,    0 ),
          'ISREF'           => array( 105,    1,    0,    0 ),
          'LOG'             => array( 109,   -1,    1,    0 ),
          'CHAR'            => array( 111,    1,    1,    0 ),
          'LOWER'           => array( 112,    1,    1,    0 ),
          'UPPER'           => array( 113,    1,    1,    0 ),
          'PROPER'          => array( 114,    1,    1,    0 ),
          'LEFT'            => array( 115,   -1,    1,    0 ),
          'RIGHT'           => array( 116,   -1,    1,    0 ),
          'EXACT'           => array( 117,    2,    1,    0 ),
          'TRIM'            => array( 118,    1,    1,    0 ),
          'REPLACE'         => array( 119,    4,    1,    0 ),
          'SUBSTITUTE'      => array( 120,   -1,    1,    0 ),
          'CODE'            => array( 121,    1,    1,    0 ),
          'FIND'            => array( 124,   -1,    1,    0 ),
          'CELL'            => array( 125,   -1,    0,    1 ),
          'ISERR'           => array( 126,    1,    1,    0 ),
          'ISTEXT'          => array( 127,    1,    1,    0 ),
          'ISNUMBER'        => array( 128,    1,    1,    0 ),
          'ISBLANK'         => array( 129,    1,    1,    0 ),
          'T'               => array( 130,    1,    0,    0 ),
          'N'               => array( 131,    1,    0,    0 ),
          'DATEVALUE'       => array( 140,    1,    1,    0 ),
          'TIMEVALUE'       => array( 141,    1,    1,    0 ),
          'SLN'             => array( 142,    3,    1,    0 ),
          'SYD'             => array( 143,    4,    1,    0 ),
          'DDB'             => array( 144,   -1,    1,    0 ),
          'INDIRECT'        => array( 148,   -1,    1,    1 ),
          'CALL'            => array( 150,   -1,    1,    0 ),
          'CLEAN'           => array( 162,    1,    1,    0 ),
          'MDETERM'         => array( 163,    1,    2,    0 ),
          'MINVERSE'        => array( 164,    1,    2,    0 ),
          'MMULT'           => array( 165,    2,    2,    0 ),
          'IPMT'            => array( 167,   -1,    1,    0 ),
          'PPMT'            => array( 168,   -1,    1,    0 ),
          'COUNTA'          => array( 169,   -1,    0,    0 ),
          'PRODUCT'         => array( 183,   -1,    0,    0 ),
          'FACT'            => array( 184,    1,    1,    0 ),
          'DPRODUCT'        => array( 189,    3,    0,    0 ),
          'ISNONTEXT'       => array( 190,    1,    1,    0 ),
          'STDEVP'          => array( 193,   -1,    0,    0 ),
          'VARP'            => array( 194,   -1,    0,    0 ),
          'DSTDEVP'         => array( 195,    3,    0,    0 ),
          'DVARP'           => array( 196,    3,    0,    0 ),
          'TRUNC'           => array( 197,   -1,    1,    0 ),
          'ISLOGICAL'       => array( 198,    1,    1,    0 ),
          'DCOUNTA'         => array( 199,    3,    0,    0 ),
          'ROUNDUP'         => array( 212,    2,    1,    0 ),
          'ROUNDDOWN'       => array( 213,    2,    1,    0 ),
          'RANK'            => array( 216,   -1,    0,    0 ),
          'ADDRESS'         => array( 219,   -1,    1,    0 ),
          'DAYS360'         => array( 220,   -1,    1,    0 ),
          'TODAY'           => array( 221,    0,    1,    1 ),
          'VDB'             => array( 222,   -1,    1,    0 ),
          'MEDIAN'          => array( 227,   -1,    0,    0 ),
          'SUMPRODUCT'      => array( 228,   -1,    2,    0 ),
          'SINH'            => array( 229,    1,    1,    0 ),
          'COSH'            => array( 230,    1,    1,    0 ),
          'TANH'            => array( 231,    1,    1,    0 ),
          'ASINH'           => array( 232,    1,    1,    0 ),
          'ACOSH'           => array( 233,    1,    1,    0 ),
          'ATANH'           => array( 234,    1,    1,    0 ),
          'DGET'            => array( 235,    3,    0,    0 ),
          'INFO'            => array( 244,    1,    1,    1 ),
          'DB'              => array( 247,   -1,    1,    0 ),
          'FREQUENCY'       => array( 252,    2,    0,    0 ),
          'ERROR.TYPE'      => array( 261,    1,    1,    0 ),
          'REGISTER.ID'     => array( 267,   -1,    1,    0 ),
          'AVEDEV'          => array( 269,   -1,    0,    0 ),
          'BETADIST'        => array( 270,   -1,    1,    0 ),
          'GAMMALN'         => array( 271,    1,    1,    0 ),
          'BETAINV'         => array( 272,   -1,    1,    0 ),
          'BINOMDIST'       => array( 273,    4,    1,    0 ),
          'CHIDIST'         => array( 274,    2,    1,    0 ),
          'CHIINV'          => array( 275,    2,    1,    0 ),
          'COMBIN'          => array( 276,    2,    1,    0 ),
          'CONFIDENCE'      => array( 277,    3,    1,    0 ),
          'CRITBINOM'       => array( 278,    3,    1,    0 ),
          'EVEN'            => array( 279,    1,    1,    0 ),
          'EXPONDIST'       => array( 280,    3,    1,    0 ),
          'FDIST'           => array( 281,    3,    1,    0 ),
          'FINV'            => array( 282,    3,    1,    0 ),
          'FISHER'          => array( 283,    1,    1,    0 ),
          'FISHERINV'       => array( 284,    1,    1,    0 ),
          'FLOOR'           => array( 285,    2,    1,    0 ),
          'GAMMADIST'       => array( 286,    4,    1,    0 ),
          'GAMMAINV'        => array( 287,    3,    1,    0 ),
          'CEILING'         => array( 288,    2,    1,    0 ),
          'HYPGEOMDIST'     => array( 289,    4,    1,    0 ),
          'LOGNORMDIST'     => array( 290,    3,    1,    0 ),
          'LOGINV'          => array( 291,    3,    1,    0 ),
          'NEGBINOMDIST'    => array( 292,    3,    1,    0 ),
          'NORMDIST'        => array( 293,    4,    1,    0 ),
          'NORMSDIST'       => array( 294,    1,    1,    0 ),
          'NORMINV'         => array( 295,    3,    1,    0 ),
          'NORMSINV'        => array( 296,    1,    1,    0 ),
          'STANDARDIZE'     => array( 297,    3,    1,    0 ),
          'ODD'             => array( 298,    1,    1,    0 ),
          'PERMUT'          => array( 299,    2,    1,    0 ),
          'POISSON'         => array( 300,    3,    1,    0 ),
          'TDIST'           => array( 301,    3,    1,    0 ),
          'WEIBULL'         => array( 302,    4,    1,    0 ),
          'SUMXMY2'         => array( 303,    2,    2,    0 ),
          'SUMX2MY2'        => array( 304,    2,    2,    0 ),
          'SUMX2PY2'        => array( 305,    2,    2,    0 ),
          'CHITEST'         => array( 306,    2,    2,    0 ),
          'CORREL'          => array( 307,    2,    2,    0 ),
          'COVAR'           => array( 308,    2,    2,    0 ),
          'FORECAST'        => array( 309,    3,    2,    0 ),
          'FTEST'           => array( 310,    2,    2,    0 ),
          'INTERCEPT'       => array( 311,    2,    2,    0 ),
          'PEARSON'         => array( 312,    2,    2,    0 ),
          'RSQ'             => array( 313,    2,    2,    0 ),
          'STEYX'           => array( 314,    2,    2,    0 ),
          'SLOPE'           => array( 315,    2,    2,    0 ),
          'TTEST'           => array( 316,    4,    2,    0 ),
          'PROB'            => array( 317,   -1,    2,    0 ),
          'DEVSQ'           => array( 318,   -1,    0,    0 ),
          'GEOMEAN'         => array( 319,   -1,    0,    0 ),
          'HARMEAN'         => array( 320,   -1,    0,    0 ),
          'SUMSQ'           => array( 321,   -1,    0,    0 ),
          'KURT'            => array( 322,   -1,    0,    0 ),
          'SKEW'            => array( 323,   -1,    0,    0 ),
          'ZTEST'           => array( 324,   -1,    0,    0 ),
          'LARGE'           => array( 325,    2,    0,    0 ),
          'SMALL'           => array( 326,    2,    0,    0 ),
          'QUARTILE'        => array( 327,    2,    0,    0 ),
          'PERCENTILE'      => array( 328,    2,    0,    0 ),
          'PERCENTRANK'     => array( 329,   -1,    0,    0 ),
          'MODE'            => array( 330,   -1,    2,    0 ),
          'TRIMMEAN'        => array( 331,    2,    0,    0 ),
          'TINV'            => array( 332,    2,    1,    0 ),
          'CONCATENATE'     => array( 336,   -1,    1,    0 ),
          'POWER'           => array( 337,    2,    1,    0 ),
          'RADIANS'         => array( 342,    1,    1,    0 ),
          'DEGREES'         => array( 343,    1,    1,    0 ),
          'SUBTOTAL'        => array( 344,   -1,    0,    0 ),
          'SUMIF'           => array( 345,   -1,    0,    0 ),
          'COUNTIF'         => array( 346,    2,    0,    0 ),
          'COUNTBLANK'      => array( 347,    1,    0,    0 ),
          'ROMAN'           => array( 354,   -1,    1,    0 )
          );
    }

/**
* Convert a token to the proper ptg value.
*
* @param mixed $token The token to convert.
*/
  function _convert($token)
    {
    if(is_numeric($token))
        {
        return($this->_convert_number($token));
        }
    // match references like A1
    elseif(preg_match("/^([A-I]?[A-Z])(\d+)$/",$token))
        {
        return($this->_convert_ref2d($token));
        }
    // match ranges like A1:B2
    elseif(preg_match("/^([A-I]?[A-Z])(\d+)\:([A-I]?[A-Z])(\d+)$/",$token))
        {
        return($this->_convert_range2d($token));
        }
    // match ranges like A1..B2
    elseif(preg_match("/^([A-I]?[A-Z])(\d+)\.\.([A-I]?[A-Z])(\d+)$/",$token))
        {
        return($this->_convert_range2d($token));
        }
    elseif(isset($this->ptg[$token])) // operators (including parentheses)
        {
        return(pack("C", $this->ptg[$token]));
        }
    elseif(preg_match("/[A-Z0-9À-Ü\.]+/",$token))
        {
        return($this->_convert_function($token,$this->_func_args));
        }
    // if it's an argument, ignore the token (the argument remains)
    elseif($token == 'arg')
        {
        $this->_func_args++;
        return('');
        }
    die("Unknown token $token");
    }

/**
* Convert a number token to ptgInt or ptgNum
*
* @param mixed $num an integer or double for conersion to its ptg value
*/
  function _convert_number($num)
    {
    // Integer in the range 0..2**16-1
    if ((preg_match("/^\d+$/",$num)) and ($num <= 65535)) {
        return pack("Cv", $this->ptg['ptgInt'], $num);
        }
    else // A float
        {
        if($this->_byte_order) // if it's Big Endian
            {
            $num = strrev($num);
            }
        return pack("Cd", $this->ptg['ptgNum'], $num);
        }
    }

/**
* Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
* args that it takes.
*
* @param string  $token    The name of the function for convertion to ptg value.
* @param integer $num_args The number of arguments the function recieves.
*/
  function _convert_function($token, $num_args)
    {
    $this->_func_args = 0; // re initialize the number of arguments
    $args     = $this->_functions[$token][1];
    $volatile = $this->_functions[$token][3];

    if($volatile) {
        $this->_volatile = 1;
        }
    // Fixed number of args eg. TIME($i,$j,$k).
    if ($args >= 0)
        {
        return(pack("Cv", $this->ptg['ptgFuncV'], 
$this->_functions[$token][0]));
        }
    // Variable number of args eg. SUM($i,$j,$k, ..).
    if ($args == -1) {
        return(pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, 
$this->_functions[$token][0]));
        }
    }

/**
* Convert an Excel range such as A1:D4 to a ptgRefV.
*
* @param string $range An Excel range in the A1:A2 or A1..A2 format.
*/
  function _convert_range2d($range)
    {
    $class = 2; // as far as I know, this is magick.

    // Split the range into 2 cell refs
    if(preg_match("/^([A-I]?[A-Z])(\d+)\:([A-I]?[A-Z])(\d+)$/",$range)) {
        list($cell1, $cell2) = split(':', $range);
        }
    elseif(preg_match("/^([A-I]?[A-Z])(\d+)\.\.([A-I]?[A-Z])(\d+)$/",$range)) {
        list($cell1, $cell2) = split('\.\.', $range);
        }
    else {
        die("Unknown range separator");
        }

    // Convert the cell references
    list($row1, $col1) = $this->_cell_to_packed_rowcol($cell1);
    list($row2, $col2) = $this->_cell_to_packed_rowcol($cell2);

    // The ptg value depends on the class of the ptg.
    if ($class == 0) {
        $ptgArea = pack("C", $this->ptg['ptgArea']);
        }
    elseif ($class == 1) {
        $ptgArea = pack("C", $this->ptg['ptgAreaV']);
        }
    elseif ($class == 2) {
        $ptgArea = pack("C", $this->ptg['ptgAreaA']);
        }
    else{
        die("Unknown class ");
        }

    return($ptgArea . $row1 . $row2 . $col1. $col2);
    }

/**
* Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
*
* @param string $cell An Excel cell reference
*/
  function _convert_ref2d($cell)
    {
    $class = 2; // as far as I know, this is magick.

    // Convert the cell reference
    list($row, $col) = $this->_cell_to_packed_rowcol($cell);

    // The ptg value depends on the class of the ptg.
    if ($class == 0) {
        $ptgRef = pack("C", $this->ptg['ptgRef']);
        }
    elseif ($class == 1) {
        $ptgRef = pack("C", $this->ptg['ptgRefV']);
        }
    elseif ($class == 2) {
        $ptgRef = pack("C", $this->ptg['ptgRefA']);
        }
    else{
        die("Unknown class ");
        }
    return $ptgRef.$row.$col;
    }

/**
* pack() row and column into the required 3 byte format.
*
* @param string $cell The Excel cell reference to be packed
*/
  function _cell_to_packed_rowcol($cell)
    {
    list($row, $col, $row_rel, $col_rel) = $this->_cell_to_rowcol($cell);
    if ($col >= 256) {
        die("Column in: $cell greater than 255 ");
        }
    if ($row >= 16384) {
        die("Row in: $cell greater than 16384 ");
        }

    // Set the high bits to indicate if row or col are relative.
    $row    |= $col_rel << 14;
    $row    |= $row_rel << 15;

    $row     = pack('v', $row);
    $col     = pack('C', $col);

    return (array($row, $col));
    }

/**
* Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
* indexed row and column number. Also returns two boolean values to indicate
* whether the row or column are relative references.
*
* @param string $cell The Excel cell reference in A1 format.
*/
  function _cell_to_rowcol($cell)
    {
    preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match);
    // return absolute column if there is a $ in the ref
    $col_rel = empty($match[1]) ? 1 : 0;
    $col_ref = $match[2];
    $row_rel = empty($match[3]) ? 1 : 0;
    $row     = $match[4];

    // Convert base26 column string to a number.
    $expn   = strlen($col_ref) - 1;
    $col    = 0;
    for($i=0; $i < strlen($col_ref); $i++)
    {
        $col += (ord($col_ref{$i}) - ord('A') + 1) * pow(26, $expn);
        $expn--;
    }

    // Convert 1-index to zero-index
    $row--;
    $col--;

    return(array($row, $col, $row_rel, $col_rel));
    }

/**
* Advance to the next valid token.
*/
  function _advance()
    {
    $i = $this->_current_char;
    // eat up white spaces
    if($i < strlen($this->_formula))
        {
        while($this->_formula{$i} == " ")
            {
            $i++;
            }
        if($i < strlen($this->_formula) - 1)
            {
            $this->_lookahead = $this->_formula{$i+1};
            }
        $token = "";
        }
    while($i < strlen($this->_formula))
        {
        $token .= $this->_formula{$i};
        if($this->_match($token) != '')
            {
            if($i < strlen($this->_formula) - 1)
                {
                $this->_lookahead = $this->_formula{$i+1};
                }
            $this->_current_char = $i + 1;
            $this->_current_token = $token;
            return(1);
            }
        $this->_lookahead = $this->_formula{$i+2};
        $i++;
        }
    //die("Lexical error ".$this->_current_char);
    }

/**
* Checks if it's a valid token.
*
* @param mixed $token The token to check.
*/
  function _match($token)
    {
    switch($token)
        {
        case ADD:
            return($token);
            break;
        case SUB:
            return($token);
            break;
        case MUL:
            return($token);
            break;
        case DIV:
            return($token);
            break;
        case OPEN:
            return($token);
            break;
        case CLOSE:
            return($token);
            break;
        case COMA:
            return($token);
            break;
        default:
            // if it's a reference
            if(eregi("^[A-I]?[A-Z][0-9]+$",$token) and
               !ereg("[0-9]",$this->_lookahead) and
               ($this->_lookahead != ':') and ($this->_lookahead != '.'))
                {
                return($token);
                }
            // if it's a range (A1:A2)
            elseif(eregi("^[A-I]?[A-Z][0-9]+:[A-I]?[A-Z][0-9]+$",$token) and
                   !ereg("[0-9]",$this->_lookahead))
                {
                return($token);
                }
            // if it's a range (A1..A2)
            elseif(eregi("^[A-I]?[A-Z][0-9]+\.\.[A-I]?[A-Z][0-9]+$",$token) and
                   !ereg("[0-9]",$this->_lookahead))
                {
                return($token);
                }
            elseif(is_numeric($token) and !is_numeric($token.$this->_lookahead))
                {
                return($token);
                }
            // if it's a function call
            elseif(eregi("^[A-Z0-9À-Ü\.]+$",$token) and ($this->_lookahead == 
"("))

                {
                return($token);
                }
            return '';
        }
    }

/**
* The parsing method. It parses a formula.
*
* @access public
* @param string $formula The formula to parse, without the initial equal sign 
(=).
*/
  function parse($formula)
    {
    $this->_current_char = 0;
    $this->_formula      = $formula;
    $this->_lookahead    = $formula{1};
    $this->_advance();
    $this->_parse_tree   = $this->_expression();
    }

/**
* It parses a expression. It assumes the following rule:
* Expr -> Term [("+" | "-") Term]
*
* @return mixed The parsed ptg'd tree
*/
  function _expression()
    {
    $result = $this->_term();
    while ($this->_current_token == ADD or $this->_current_token == SUB)
        {
        if ($this->_current_token == ADD)
            {
            $this->_advance();
            $result = $this->_create_tree('ptgAdd', $result, $this->_term());
            }
        else
            {
            $this->_advance();
            $result = $this->_create_tree('ptgSub', $result, $this->_term());
            }
        }
    return $result;
    }

/**
* This function just introduces a ptgParen element in the tree, so that Excel
* doesn't get confused when working with a parenthesized formula afterwards.
*
* @see _fact
* @return mixed The parsed ptg'd tree
*/
  function _parenthesized_expression()
    {
    $result = $this->_create_tree('ptgParen', $this->_expression(), '');
    return($result);
    }

/**
* It parses a term. It assumes the following rule:
* Term -> Fact [("*" | "/") Fact]
*
* @return mixed The parsed ptg'd tree
*/
  function _term()
    {
    $result = $this->_fact();
    while ($this->_current_token == MUL || $this->_current_token == DIV)
        {
        if ($this->_current_token == MUL)
            {
            $this->_advance();
            $result = $this->_create_tree('ptgMul', $result, $this->_fact());
            }
        else
            {
            $this->_advance();
            $result = $this->_create_tree('ptgDiv', $result, $this->_fact());
            }
        }
    return($result);
    }

/**
* It parses a factor. It assumes the following rule:
* Fact -> ( Expr )
*       | CellRef
*       | CellRange
*       | Number
*       | Function
*
* @return mixed The parsed ptg'd tree
*/
  function _fact()
    {
    if ($this->_current_token == OPEN)
        {
        $this->_advance();         // eat the "("
        $result = $this->_parenthesized_expression();//$this->_expression();

        if ($this->_current_token != CLOSE) {
            die("')' token expected.");
            }
        $this->_advance();         // eat the ")"
        return($result);
        }
    // if it's a reference
    if (eregi("^[A-I]?[A-Z][0-9]+$",$this->_current_token))
        {
        $result = $this->_create_tree($this->_current_token, '', '');
        $this->_advance();
        return($result);
        }
    // if it's a range
    elseif 
(eregi("^[A-I]?[A-Z][0-9]+:[A-I]?[A-Z][0-9]+$",$this->_current_token) or
            
eregi("^[A-I]?[A-Z][0-9]+\.\.[A-I]?[A-Z][0-9]+$",$this->_current_token))
        {
        $result = $this->_current_token;
        $this->_advance();
        return($result);
        }
    elseif (is_numeric($this->_current_token))
        {
        $result = $this->_create_tree($this->_current_token, '', '');
        $this->_advance();
        return($result);
        }
    // if it's a function call
    elseif (eregi("^[A-Z0-9À-Ü\.]+$",$this->_current_token))
        {
        $result = $this->_func();
        return($result);
        }
    die("Sintactic error: ".$this->_current_token.", lookahead: ".
        $this->_lookahead.", current char: ".$this->_current_char);
    }

/**
* It parses a function call. It assumes the following rule:
* Func -> ( Expr [,Expr]* )
*
*/
  function _func()
    {
    $num_args = 0; // number of arguments received
    $function = $this->_current_token;
    $this->_advance();
    $this->_advance();         // eat the "("
    while($this->_current_token != ')')
        {
        if($num_args > 0)
            {
            if($this->_current_token == COMA) {
                $this->_advance();  // eat the ","
                }
            else {
                die("Sintactic error: coma expected $num_args");
                }
            $result = $this->_create_tree('arg', $result, $this->_expression());
            }
        else {
            $result = $this->_create_tree('arg', '', $this->_expression());
            }
        $num_args++;
        }
    $args = $this->_functions[$function][1];
    // If fixed number of args eg. TIME($i,$j,$k). Check that the number of 
args is valid.
    if (($args >= 0) and ($args != $num_args))
        {
        die("Incorrect number of arguments in function $function() ");
        }

    $result = $this->_create_tree($function, $result, '');
    $this->_advance();         // eat the ")"
    return($result);
    }

/**
* Creates a tree. In fact an array which may have one or two arrays (sub-trees)
* as elements.
*
* @param mixed $value The value of this node.
* @param mixed $left  The left array (sub-tree) or a final node.
* @param mixed $right The right array (sub-tree) or a final node.
*/
  function _create_tree($value, $left, $right)
    {
    return array('value' => $value, 'left' => $left, 'right' => $right);
    }

/**
* Builds a string containing the tree in reverse polish notation (What you
* would use in a HP calculator stack).
* The following tree:
*
*    +
*   / \
*  2   3
*
* produces: "23+"
*
* The following tree:
*
*    +
*   / \
*  3   *
*     / \
*    6   A1
*
* produces: "36A1*+"
*
* In fact all operands, functions, references, etc... are written as ptg's
*
* @access public
* @param array $tree The optional tree to convert.
*/
  function to_reverse_polish($tree = array())
    {
    $polish = ""; // the string we are going to return
    if (empty($tree)) // If it's the first call use _parse_tree
        {
        $tree = $this->_parse_tree;
        }
    if (is_array($tree['left']))
        {
        $polish .= $this->to_reverse_polish($tree['left']);
        }
    elseif($tree['left'] != '') // It's a final node
        {
        $polish .= $this->_convert($tree['left']); //$tree['left'];
        }
    if (is_array($tree['right']))
        {
        $polish .= $this->to_reverse_polish($tree['right']);
        }
    elseif($tree['right'] != '') // It's a final node
        {
        $polish .= $this->_convert($tree['right']);
        }
    $polish .= $this->_convert($tree['value']);
    return $polish;
    }
  }
?>

====================================================
Index: OLEwriter.php
<?php
/*
*  Module written/ported by Xavier Noguer <address@hidden>
*
*  The majority of this is _NOT_ my code.  I simply ported it from the
*  PERL Spreadsheet::WriteExcel module.
*
*  The author of the Spreadsheet::WriteExcel module is John McNamara
*  <address@hidden>
*
*  I _DO_ maintain this code, and John McNamara has nothing to do with the
*  porting of this code to PHP.  Any questions directly related to this
*  class library should be directed to me.
*
*  License Information:
*
*    Spreadsheet::WriteExcel:  A library for generating Excel Spreadsheets
*    Copyright (C) 2002 Xavier Noguer address@hidden
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/**
* Class for creating OLE streams for Excel Spreadsheets
*
* @author Xavier Noguer <address@hidden>
* @package Spreadsheet_WriteExcel
*/
class OLEwriter
{
    /**
    * Filename for the OLE stream
    * @var string
    * @see _initialize()
    */
    var $_OLEfilename;

    /**
    * Filehandle for the OLE stream
    * @var resource
    */
    var $_filehandle;

    /**
    * Name of the temporal file in case OLE stream goes to stdout
    * @var string
    */
    var $_tmp_filename;

    /**
    * Variable for preventing closing two times
    * @var integer
    */
    var $_fileclosed;

    /**
    * Size of the data to be written to the OLE stream
    * @var integer
    */
    var $_biffsize;

    /**
    * Real data size to be written to the OLE stream
    * @var integer
    */
    var $_booksize;

    /**
    * Number of big blocks in the OLE stream
    * @var integer
    */
    var $_big_blocks;

    /**
    * Number of list blocks in the OLE stream
    * @var integer
    */
    var $_list_blocks;

    /**
    * Number of big blocks in the OLE stream
    * @var integer
    */
    var $_root_start;

    /**
    * Class for creating an OLEwriter
    *
    * @param string $OLEfilename the name of the file for the OLE stream
    */
    function OLEwriter($OLEfilename)
    {
        $this->_OLEfilename  = $OLEfilename;
        $this->_filehandle   = "";
        $this->_tmp_filename = "";
        $this->_fileclosed   = 0;
        //$this->_size_allowed = 0;
        $this->_biffsize     = 0;
        $this->_booksize     = 0;
        $this->_big_blocks   = 0;
        $this->_list_blocks  = 0;
        $this->_root_start   = 0;
        //$this->_block_count  = 4;
        $this->_initialize();
    }

/**
* Check for a valid filename and store the filehandle.
* Filehandle "-" writes to STDOUT
*/
    function _initialize()
    {
        $OLEfile = $this->_OLEfilename;

        if(($OLEfile == '-') or ($OLEfile == ''))
        {
            $this->_tmp_filename = tempnam("/tmp", "OLEwriter");
            $fh = fopen($this->_tmp_filename,"wb");
            if ($fh == false) {
                die("Can't create temporary file.");
            }
        }
        else
        {
            // Create a new file, open for writing (in binmode)
            $fh = fopen($OLEfile,"wb");
            if ($fh == false) {
                die("Can't open $OLEfile. It may be in use or protected.");
            }
        }

        // Store filehandle
        $this->_filehandle = $fh;
    }


    /**
    * Set the size of the data to be written to the OLE stream.
    * The maximun size comes from this:
    *   $big_blocks = (109 depot block x (128 -1 marker word)
    *                 - (1 x end words)) = 13842
    *   $maxsize    = $big_blocks * 512 bytes = 7087104
    *
    * @access public
    * @see Workbook::store_OLE_file()
    * @param integer $biffsize The size of the data to be written to the OLE 
stream
    * @return integer 1 for success
    */
    function set_size($biffsize)
    {
        $maxsize = 7087104; // TODO: extend max size

        if ($biffsize > $maxsize) {
            die("Maximum file size, $maxsize, exceeded.");
        }

        $this->_biffsize = $biffsize;
        // Set the min file size to 4k to avoid having to use small blocks
        if ($biffsize > 4096) {
            $this->_booksize = $biffsize;
        }
        else {
            $this->_booksize = 4096;
        }
        //$this->_size_allowed = 1;
        return(1);
    }


    /**
    * Calculate various sizes needed for the OLE stream
    */
    function _calculate_sizes()
    {
        $datasize = $this->_booksize;
        if ($datasize % 512 == 0) {
            $this->_big_blocks = $datasize/512;
        }
        else {
            $this->_big_blocks = floor($datasize/512) + 1;
        }
        // There are 127 list blocks and 1 marker blocks for each big block
        // depot + 1 end of chain block
        $this->_list_blocks = floor(($this->_big_blocks)/127) + 1;
        $this->_root_start  = $this->_big_blocks;
    }

    /**
    * Write root entry, big block list and close the filehandle.
    * This routine is used to explicitly close the open filehandle without
    * having to wait for DESTROY.
    *
    * @access public
    * @see Workbook::store_OLE_file()
    */
    function close()
    {
        //return if not $this->{_size_allowed};
        $this->_write_padding();
        $this->_write_property_storage();
        $this->_write_big_block_depot();
        // Close the filehandle
        fclose($this->_filehandle);
        if(($this->_OLEfilename == '-') or ($this->_OLEfilename == ''))
        {
            $fh = fopen($this->_tmp_filename, "rb");
            if ($fh == false) {
                die("Can't read temporary file.");
            }
            fpassthru($fh);
            // Delete the temporary file.
            @unlink($this->_tmp_filename);
        }
        $this->_fileclosed = 1;
    }


    /**
    * Write BIFF data to OLE file.
    *
    * @param string $data string of bytes to be written
    */
    function write($data) //por ahora sólo a STDOUT
    {
        fwrite($this->_filehandle,$data,strlen($data));
    }


    /**
    * Write OLE header block.
    */
    function write_header()
    {
        $this->_calculate_sizes();
        $root_start      = $this->_root_start;
        $num_lists       = $this->_list_blocks;
        $id              = pack("nnnn", 0xD0CF, 0x11E0, 0xA1B1, 0x1AE1);
        $unknown1        = pack("VVVV", 0x00, 0x00, 0x00, 0x00);
        $unknown2        = pack("vv",   0x3E, 0x03);
        $unknown3        = pack("v",    -2);
        $unknown4        = pack("v",    0x09);
        $unknown5        = pack("VVV",  0x06, 0x00, 0x00);
        $num_bbd_blocks  = pack("V",    $num_lists);
        $root_startblock = pack("V",    $root_start);
        $unknown6        = pack("VV",   0x00, 0x1000);
        $sbd_startblock  = pack("V",    -2);
        $unknown7        = pack("VVV",  0x00, -2 ,0x00);
        $unused          = pack("V",    -1);

        fwrite($this->_filehandle,$id);
        fwrite($this->_filehandle,$unknown1);
        fwrite($this->_filehandle,$unknown2);
        fwrite($this->_filehandle,$unknown3);
        fwrite($this->_filehandle,$unknown4);
        fwrite($this->_filehandle,$unknown5);
        fwrite($this->_filehandle,$num_bbd_blocks);
        fwrite($this->_filehandle,$root_startblock);
        fwrite($this->_filehandle,$unknown6);
        fwrite($this->_filehandle,$sbd_startblock);
        fwrite($this->_filehandle,$unknown7);

        for($i=1; $i <= $num_lists; $i++)
        {
            $root_start++;
            fwrite($this->_filehandle,pack("V",$root_start));
        }
        for($i = $num_lists; $i <=108; $i++)
        {
            fwrite($this->_filehandle,$unused);
        }
    }


    /**
    * Write big block depot.
    */
    function _write_big_block_depot()
    {
        $num_blocks   = $this->_big_blocks;
        $num_lists    = $this->_list_blocks;
        $total_blocks = $num_lists *128;
        $used_blocks  = $num_blocks + $num_lists +2;

        $marker       = pack("V", -3);
        $end_of_chain = pack("V", -2);
        $unused       = pack("V", -1);

        for($i=1; $i < $num_blocks; $i++)
        {
            fwrite($this->_filehandle,pack("V",$i));
        }
        fwrite($this->_filehandle,$end_of_chain);
        fwrite($this->_filehandle,$end_of_chain);
        for($i=0; $i < $num_lists; $i++)
        {
            fwrite($this->_filehandle,$marker);
        }
        for($i=$used_blocks; $i <= $total_blocks; $i++)
        {
            fwrite($this->_filehandle,$unused);
        }
    }

/**
* Write property storage. TODO: add summary sheets
*/
    function _write_property_storage()
    {
        //$rootsize = -2;
        /***************  name         type   dir start size */
        $this->_write_pps("Root Entry", 0x05,   1,   -2, 0x00);
        $this->_write_pps("Book",       0x02,  -1, 0x00, $this->_booksize);
        $this->_write_pps('',           0x00,  -1, 0x00, 0x0000);
        $this->_write_pps('',           0x00,  -1, 0x00, 0x0000);
    }

/**
* Write property sheet in property storage
*
* @param string  $name  name of the property storage.
* @param integer $type  type of the property storage.
* @param integer $dir   dir of the property storage.
* @param integer $start start of the property storage.
* @param integer $size  size of the property storage.
* @access private
*/
    function _write_pps($name,$type,$dir,$start,$size)
    {
        $length  = 0;
        $rawname = '';

        if ($name != '')
        {
            $name = $name . "\0";
            for($i=0;$i<strlen($name);$i++)
            {
                // Simulate a Unicode string
                $rawname .= pack("H*",dechex(ord($name{$i}))).pack("C",0);
            }
            $length = strlen($name) * 2;
        }

        $zero            = pack("C",  0);
        $pps_sizeofname  = pack("v",  $length);    // 0x40
        $pps_type        = pack("v",  $type);      // 0x42
        $pps_prev        = pack("V",  -1);         // 0x44
        $pps_next        = pack("V",  -1);         // 0x48
        $pps_dir         = pack("V",  $dir);       // 0x4c

        $unknown1        = pack("V",  0);

        $pps_ts1s        = pack("V",  0);          // 0x64
        $pps_ts1d        = pack("V",  0);          // 0x68
        $pps_ts2s        = pack("V",  0);          // 0x6c
        $pps_ts2d        = pack("V",  0);          // 0x70
        $pps_sb          = pack("V",  $start);     // 0x74
        $pps_size        = pack("V",  $size);      // 0x78


        fwrite($this->_filehandle,$rawname);
        for($i=0; $i < (64 -$length); $i++) {
            fwrite($this->_filehandle,$zero);
        }
        fwrite($this->_filehandle,$pps_sizeofname);
        fwrite($this->_filehandle,$pps_type);
        fwrite($this->_filehandle,$pps_prev);
        fwrite($this->_filehandle,$pps_next);
        fwrite($this->_filehandle,$pps_dir);
        for($i=0; $i < 5; $i++) {
            fwrite($this->_filehandle,$unknown1);
        }
        fwrite($this->_filehandle,$pps_ts1s);
        fwrite($this->_filehandle,$pps_ts1d);
        fwrite($this->_filehandle,$pps_ts2d);
        fwrite($this->_filehandle,$pps_ts2d);
        fwrite($this->_filehandle,$pps_sb);
        fwrite($this->_filehandle,$pps_size);
        fwrite($this->_filehandle,$unknown1);
    }

    /**
    * Pad the end of the file
    */
    function _write_padding()
    {
        $biffsize = $this->_biffsize;
        if ($biffsize < 4096) {
            $min_size = 4096;
        }
        else {
            $min_size = 512;
        }
        if ($biffsize % $min_size != 0)
        {
            $padding  = $min_size - ($biffsize % $min_size);
            for($i=0; $i < $padding; $i++) {
                fwrite($this->_filehandle,"\0");
            }
        }
    }
}
?>

====================================================
Index: test.php
<?php
  //require_once('OLEwriter.php');
  //require_once('BIFFwriter.php');
  require_once('Worksheet.php');
  require_once('Workbook.php');

  function HeaderingExcel($filename) {
      header("Content-type: application/vnd.ms-excel");
      header("Content-Disposition: attachment; filename=$filename" );
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
      header("Pragma: public");
      }

  // HTTP headers
  HeaderingExcel('test.xls');

  // Creating a workbook
  $workbook = new Workbook("-");
  // Creating the first worksheet
  $worksheet1 =& $workbook->add_worksheet('First One');
  $worksheet1->set_column(1, 1, 40);
  $worksheet1->set_row(1, 20);
  $worksheet1->write_string(1, 1, "This worksheet's name is 
".$worksheet1->get_name());
  
$worksheet1->write(2,1,"http://www.phpclasses.org/browse.html/package/767.html";);
  $worksheet1->write_number(3, 0, 11);
  $worksheet1->write_number(3, 1, 1);
  $worksheet1->write_string(3, 2, "by four is");
  $worksheet1->write_formula(3, 3, "=A4 * (2 + 2)");
  //$worksheet1->write_formula(3, 3, "= SUM(A4:B4)");
  $worksheet1->write(5, 4, "= POWER(2,3)");
  $worksheet1->write(4, 4, "= SUM(5, 5, 5)");
  //$worksheet1->write_formula(4, 4, "= LN(2.71428)");
  //$worksheet1->write_formula(5, 4, "= SIN(PI()/2)");

  // Creating the second worksheet
  $worksheet2 =& $workbook->add_worksheet();

  // Format for the headings
  $formatot =& $workbook->add_format();
  $formatot->set_size(10);
  $formatot->set_align('center');
  $formatot->set_color('white');
  $formatot->set_pattern();
  $formatot->set_fg_color('magenta');

  $worksheet2->set_column(0,0,15);
  $worksheet2->set_column(1,2,30);
  $worksheet2->set_column(3,3,15);
  $worksheet2->set_column(4,4,10);

  $worksheet2->write_string(1,0,"Id",$formatot);
  $worksheet2->write_string(1,1,"Name",$formatot);
  $worksheet2->write_string(1,2,"Adress",$formatot);
  $worksheet2->write_string(1,3,"Phone Number",$formatot);
  $worksheet2->write_string(1,4,"Salary",$formatot);

  $worksheet2->write(3,0,"22222222-2");
  $worksheet2->write(3,1,"John Smith");
  $worksheet2->write(3,2,"Main Street 100");
  $worksheet2->write(3,3,"02-5551234");
  $worksheet2->write(3,4,100);
  $worksheet2->write(4,0,"11111111-1");
  $worksheet2->write(4,1,"Juan Perez");
  $worksheet2->write(4,2,"Los Paltos 200");
  $worksheet2->write(4,3,"03-5552345");
  $worksheet2->write(4,4,110);
  // if you are writing a very long worksheet, you may want to use
  // write_xxx() functions, instead of write() for performance reasons.
  $worksheet2->write_string(5,0,"11111111-1");
  $worksheet2->write_string(5,1,"Another Guy");
  $worksheet2->write_string(5,2,"Somewhere 300");
  $worksheet2->write_string(5,3,"03-5553456");
  $worksheet2->write(5,4,108);


  // Calculate some statistics
  $worksheet2->write(7, 0, "Average Salary:");
  $worksheet2->write_formula(7, 4, "= AVERAGE(E4:E6)");
  $worksheet2->write(8, 0, "Minimum Salary:");
  $worksheet2->write_formula(8, 4, "= MIN(E4:E6)");
  $worksheet2->write(9, 0, "Maximum Salary:");
  $worksheet2->write_formula(9, 4, "= MAX(E4:E6)");

  //$worksheet2->insert_bitmap(0, 0, "some.bmp",10,10);

  $workbook->close();
?>

====================================================
Index: Workbook.php
<?php
/*
*  Module written/ported by Xavier Noguer <address@hidden>
*
*  The majority of this is _NOT_ my code.  I simply ported it from the
*  PERL Spreadsheet::WriteExcel module.
*
*  The author of the Spreadsheet::WriteExcel module is John McNamara
*  <address@hidden>
*
*  I _DO_ maintain this code, and John McNamara has nothing to do with the
*  porting of this code to PHP.  Any questions directly related to this
*  class library should be directed to me.
*
*  License Information:
*
*    Spreadsheet::WriteExcel:  A library for generating Excel Spreadsheets
*    Copyright (C) 2002 Xavier Noguer address@hidden
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

require_once('Format.php');
require_once('OLEwriter.php');
require_once('BIFFwriter.php');

/**
* Class for generating Excel Spreadsheets
*
* @author Xavier Noguer <address@hidden>
* @package Spreadsheet_WriteExcel
*/

//class Workbook extends BIFFwriter
class excel extends BIFFwriter
{
    /**
    * Class constructor
    *
    * @param string filename for storing the workbook. "-" for writing to 
stdout.
    */
    function excel($filename)
    {
        $this->BIFFwriter(); // It needs to call its parent's constructor 
explicitly

        $this->_filename         = $filename;
        $this->parser            = new Parser($this->_byte_order);
        $this->_1904             = 0;
        $this->activesheet       = 0;
        $this->firstsheet        = 0;
        $this->selected          = 0;
        $this->xf_index          = 16; // 15 style XF's and 1 cell XF.
        $this->_fileclosed       = 0;
        $this->_biffsize         = 0;
        $this->sheetname         = "Sheet";
        $this->tmp_format        = new Format();
        $this->worksheets        = array();
        $this->sheetnames        = array();
        $this->formats           = array();
        $this->palette           = array();

        // Add the default format for hyperlinks
        $this->url_format =& $this->add_format(array('color' => 'blue', 
'underline' => 1));

        // Check for a filename
        //if ($this->_filename == '') {
        //    die('Filename required by Spreadsheet::WriteExcel->new()');
        //}

        # Warn if tmpfiles can't be used.
        //$this->tmpfile_warning();
        $this->_set_palette_xl97();
    }

    /**
    * Calls finalization methods and explicitly close the OLEwriter file
    * handle.
    */
    function close()
    {
        if ($this->_fileclosed) { // Prevent close() from being called twice.
            return;
        }
        $this->store_workbook();
        $this->_fileclosed = 1;
    }


    /**
    * An accessor for the _worksheets[] array
    * Returns an array of the worksheet objects in a workbook
    *
    * @return array
    */
    function sheets()
    {
        return($this->worksheets());
    }

    /**
    * An accessor for the _worksheets[] array.
    *
    * @return array
    */
    function worksheets()
    {
        return($this->worksheets);
    }

    /**
    * Add a new worksheet to the Excel workbook.
    * TODO: Add accessor for $this->{_sheetname} for international Excel 
versions.
    *
    * @access public
    * @param string $name the optional name of the worksheet
    * @return &object reference to a worksheet object
    */
    function &add_worksheet($name = '')
    {
        $index     = count($this->worksheets);
        $sheetname = $this->sheetname;

        if($name == '') {
            $name = $sheetname.($index+1);
        }

        // Check that sheetname is <= 31 chars (Excel limit).
        if(strlen($name) > 31) {
            die("Sheetname $name must be <= 31 chars");
        }

        // Check that the worksheet name doesn't already exist: a fatal Excel 
error.
        for($i=0; $i < count($this->worksheets); $i++)
        {
            if($name == $this->worksheets[$i]->get_name()) {
                die("Worksheet '$name' already exists");
            }
        }

        $worksheet = new Worksheet($name,$index,$this->activesheet,
                                   $this->firstsheet,$this->url_format,
                                   $this->parser);
        $this->worksheets[$index] = &$worksheet;      // Store ref for iterator
        $this->sheetnames[$index] = $name;            // Store EXTERNSHEET names
        //$this->parser->set_ext_sheet($name,$index); // Store names in 
Formula.php
        return($worksheet);
    }

    /**
    * DEPRECATED!! Use add_worksheet instead
    *
    * @access public
    * @deprecated Use add_worksheet instead
    * @param string $name the optional name of the worksheet
    * @return &object reference to a worksheet object
    */
    function &addworksheet($name = '')
    {
        return($this->add_worksheet($name));
    }

    /**
    * Add a new format to the Excel workbook. This adds an XF record and
    * a FONT record. Also, pass any properties to the Format constructor.
    *
    * @access public
    * @param array $properties array with properties for initializing the 
format (see Format.php)
    * @return &object reference to an XF format
    */
    function &add_format($properties = array())
    {
        $format = new Format($this->xf_index,$properties);
        $this->xf_index += 1;
        $this->formats[] = &$format;
        return($format);
    }

    /**
    * DEPRECATED!! Use add_format instead
    *
    * @access public
    * @deprecated Use add_format instead
    * @param array $properties array with properties for initializing the 
format (see Format.php)
    * @return &object reference to an XF format
    */
    function &addformat($properties = array())
    {
         return($this->add_format($properties));
    }


    /**
    * Change the RGB components of the elements in the colour palette.
    *
    * @access public
    * @param integer $index colour index
    * @param integer $red   red RGB value [0-255]
    * @param integer $green green RGB value [0-255]
    * @param integer $blue  blue RGB value [0-255]
    * @return integer The palette index for the custom color
    */
    function set_custom_color($index,$red,$green,$blue)
    {
        // Match a HTML #xxyyzz style parameter
        /*if (defined $_[1] and $_[1] =~ /^#(\w\w)(\w\w)(\w\w)/ ) {
            @_ = ($_[0], hex $1, hex $2, hex $3);
        }*/

        // Check that the colour index is the right range
        if ($index < 8 or $index > 64) {
            die("Color index $index outside range: 8 <= index <= 64");
        }

        // Check that the colour components are in the right range
        if ( ($red   < 0 or $red   > 255) ||
             ($green < 0 or $green > 255) ||
             ($blue  < 0 or $blue  > 255) )
        {
            die("Color component outside range: 0 <= color <= 255");
        }

        $index -= 8; // Adjust colour index (wingless dragonfly)

        // Set the RGB value
        $this->palette[$index] = array($red, $green, $blue, 0);
        return($index + 8);
    }

    /**
    * Sets the colour palette to the Excel 97+ default.
    */
    function _set_palette_xl97()
    {
        $this->palette = array(
                           array(0x00, 0x00, 0x00, 0x00),   // 8
                           array(0xff, 0xff, 0xff, 0x00),   // 9
                           array(0xff, 0x00, 0x00, 0x00),   // 10
                           array(0x00, 0xff, 0x00, 0x00),   // 11
                           array(0x00, 0x00, 0xff, 0x00),   // 12
                           array(0xff, 0xff, 0x00, 0x00),   // 13
                           array(0xff, 0x00, 0xff, 0x00),   // 14
                           array(0x00, 0xff, 0xff, 0x00),   // 15
                           array(0x80, 0x00, 0x00, 0x00),   // 16
                           array(0x00, 0x80, 0x00, 0x00),   // 17
                           array(0x00, 0x00, 0x80, 0x00),   // 18
                           array(0x80, 0x80, 0x00, 0x00),   // 19
                           array(0x80, 0x00, 0x80, 0x00),   // 20
                           array(0x00, 0x80, 0x80, 0x00),   // 21
                           array(0xc0, 0xc0, 0xc0, 0x00),   // 22
                           array(0x80, 0x80, 0x80, 0x00),   // 23
                           array(0x99, 0x99, 0xff, 0x00),   // 24
                           array(0x99, 0x33, 0x66, 0x00),   // 25
                           array(0xff, 0xff, 0xcc, 0x00),   // 26
                           array(0xcc, 0xff, 0xff, 0x00),   // 27
                           array(0x66, 0x00, 0x66, 0x00),   // 28
                           array(0xff, 0x80, 0x80, 0x00),   // 29
                           array(0x00, 0x66, 0xcc, 0x00),   // 30
                           array(0xcc, 0xcc, 0xff, 0x00),   // 31
                           array(0x00, 0x00, 0x80, 0x00),   // 32
                           array(0xff, 0x00, 0xff, 0x00),   // 33
                           array(0xff, 0xff, 0x00, 0x00),   // 34
                           array(0x00, 0xff, 0xff, 0x00),   // 35
                           array(0x80, 0x00, 0x80, 0x00),   // 36
                           array(0x80, 0x00, 0x00, 0x00),   // 37
                           array(0x00, 0x80, 0x80, 0x00),   // 38
                           array(0x00, 0x00, 0xff, 0x00),   // 39
                           array(0x00, 0xcc, 0xff, 0x00),   // 40
                           array(0xcc, 0xff, 0xff, 0x00),   // 41
                           array(0xcc, 0xff, 0xcc, 0x00),   // 42
                           array(0xff, 0xff, 0x99, 0x00),   // 43
                           array(0x99, 0xcc, 0xff, 0x00),   // 44
                           array(0xff, 0x99, 0xcc, 0x00),   // 45
                           array(0xcc, 0x99, 0xff, 0x00),   // 46
                           array(0xff, 0xcc, 0x99, 0x00),   // 47
                           array(0x33, 0x66, 0xff, 0x00),   // 48
                           array(0x33, 0xcc, 0xcc, 0x00),   // 49
                           array(0x99, 0xcc, 0x00, 0x00),   // 50
                           array(0xff, 0xcc, 0x00, 0x00),   // 51
                           array(0xff, 0x99, 0x00, 0x00),   // 52
                           array(0xff, 0x66, 0x00, 0x00),   // 53
                           array(0x66, 0x66, 0x99, 0x00),   // 54
                           array(0x96, 0x96, 0x96, 0x00),   // 55
                           array(0x00, 0x33, 0x66, 0x00),   // 56
                           array(0x33, 0x99, 0x66, 0x00),   // 57
                           array(0x00, 0x33, 0x00, 0x00),   // 58
                           array(0x33, 0x33, 0x00, 0x00),   // 59
                           array(0x99, 0x33, 0x00, 0x00),   // 60
                           array(0x99, 0x33, 0x66, 0x00),   // 61
                           array(0x33, 0x33, 0x99, 0x00),   // 62
                           array(0x33, 0x33, 0x33, 0x00),   // 63
                         );
    }


    
###############################################################################
    #
    # _tmpfile_warning()
    #
    # Check that tmp files can be created for use in Worksheet.pm. A CGI, 
mod_perl
    # or IIS might not have permission to create tmp files. The test is here 
rather
    # than in Worksheet.pm so that only one warning is given.
    #
    /*sub _tmpfile_warning {

        my $fh = IO::File->new_tmpfile();

        if ((not defined $fh) && ($^W)) {
            carp("Unable to create tmp files via IO::File->new_tmpfile(). " .
                 "Storing data in memory")
    }
    }*/

    /**
    * Assemble worksheets into a workbook and send the BIFF data to an OLE
    * storage.
    */
    function store_workbook()
    {
        // Ensure that at least one worksheet has been selected.
        if ($this->activesheet == 0) {
            $this->worksheets[0]->selected = 1;
        }

        // Calculate the number of selected worksheet tabs and call the 
finalization
        // methods for each worksheet
        for($i=0; $i < count($this->worksheets); $i++)
        {
            if($this->worksheets[$i]->selected)
              $this->selected++;
            $this->worksheets[$i]->close($this->sheetnames);
        }

        // Add Workbook globals
        $this->_store_bof(0x0005);
        $this->_store_externs();    // For print area and repeat rows
        $this->_store_names();      // For print area and repeat rows
        $this->_store_window1();
        $this->_store_1904();
        $this->_store_all_fonts();
        $this->_store_all_num_formats();
        $this->_store_all_xfs();
        $this->_store_all_styles();
        $this->_store_palette();
        $this->_calc_sheet_offsets();

        // Add BOUNDSHEET records
        for($i=0; $i < count($this->worksheets); $i++) {
            
$this->_store_boundsheet($this->worksheets[$i]->name,$this->worksheets[$i]->offset);
        }

        // End Workbook globals
        $this->_store_eof();

        // Store the workbook in an OLE container
        $this->_store_OLE_file();
    }

    /**
    * Store the workbook in an OLE container if the total size of the workbook 
data
    * is less than ~ 7MB.
    */
    function _store_OLE_file()
    {
        $OLE  = new OLEwriter($this->_filename);
        // Write Worksheet data if data <~ 7MB
        if ($OLE->set_size($this->_biffsize))
        {
            $OLE->write_header();
            $OLE->write($this->_data);
            foreach($this->worksheets as $sheet)
            {
                while ($tmp = $sheet->get_data()) {
                    $OLE->write($tmp);
                }
            }
        }
        $OLE->close();
    }

    /**
    * Calculate offsets for Worksheet BOF records.
    */
    function _calc_sheet_offsets()
    {
        $BOF     = 11;
        $EOF     = 4;
        $offset  = $this->_datasize;
        for($i=0; $i < count($this->worksheets); $i++) {
            $offset += $BOF + strlen($this->worksheets[$i]->name);
        }
        $offset += $EOF;
        for($i=0; $i < count($this->worksheets); $i++) {
            $this->worksheets[$i]->offset = $offset;
            $offset += $this->worksheets[$i]->_datasize;
        }
        $this->_biffsize = $offset;
    }

    /**
    * Store the Excel FONT records.
    */
    function _store_all_fonts()
    {
        // tmp_format is added by new(). We use this to write the default XF's
        $format = $this->tmp_format;
        $font   = $format->get_font();

        // Note: Fonts are 0-indexed. According to the SDK there is no index 4,
        // so the following fonts are 0, 1, 2, 3, 5
        //
        for($i=1; $i <= 5; $i++){
            $this->_append($font);
        }

        // Iterate through the XF objects and write a FONT record if it isn't 
the
        // same as the default FONT and if it hasn't already been used.
        //
        $fonts = array();
        $index = 6;                  // The first user defined FONT

        $key = $format->get_font_key(); // The default font from _tmp_format
        $fonts[$key] = 0;               // Index of the default font

        for($i=0; $i < count($this->formats); $i++) {
            $key = $this->formats[$i]->get_font_key();
            if (isset($fonts[$key])) {
                // FONT has already been used
                $this->formats[$i]->font_index = $fonts[$key];
            }
            else {
                // Add a new FONT record
                $fonts[$key]        = $index;
                $this->formats[$i]->font_index = $index;
                $index++;
                $font = $this->formats[$i]->get_font();
                $this->_append($font);
            }
        }
    }

    /**
    * Store user defined numerical formats i.e. FORMAT records
    */
    function _store_all_num_formats()
    {
        // Leaning num_format syndrome
        $hash_num_formats = array();
        $num_formats      = array();
        $index = 164;

        // Iterate through the XF objects and write a FORMAT record if it isn't 
a
        // built-in format type and if the FORMAT string hasn't already been 
used.
        //
        for($i=0; $i < count($this->formats); $i++)
        {
            $num_format = $this->formats[$i]->_num_format;

            // Check if $num_format is an index to a built-in format.
            // Also check for a string of zeros, which is a valid format string
            // but would evaluate to zero.
            //
            if (!preg_match("/^0+\d/",$num_format))
            {
                if (preg_match("/^\d+$/",$num_format)) { // built-in format
                    continue;
                }
            }

            if (isset($hash_num_formats[$num_format])) {
                // FORMAT has already been used
                $this->formats[$i]->_num_format = 
$hash_num_formats[$num_format];
            }
            else
            {
                // Add a new FORMAT
                $hash_num_formats[$num_format]  = $index;
                $this->formats[$i]->_num_format = $index;
                array_push($num_formats,$num_format);
                $index++;
            }
        }

        // Write the new FORMAT records starting from 0xA4
        $index = 164;
        foreach ($num_formats as $num_format)
        {
            $this->_store_num_format($num_format,$index);
            $index++;
        }
    }

    /**
    * Write all XF records.
    */
    function _store_all_xfs()
    {
        // tmp_format is added by the constructor. We use this to write the 
default XF's
        // The default font index is 0
        //
        $format = $this->tmp_format;
        for ($i=0; $i <= 14; $i++)
        {
            $xf = $format->get_xf('style'); // Style XF
            $this->_append($xf);
        }

        $xf = $format->get_xf('cell');      // Cell XF
        $this->_append($xf);

        // User defined XFs
        for($i=0; $i < count($this->formats); $i++)
        {
            $xf = $this->formats[$i]->get_xf('cell');
            $this->_append($xf);
        }
    }

    /**
    * Write all STYLE records.
    */
    function _store_all_styles()
    {
        $this->_store_style();
    }

    /**
    * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes 
for
    * the NAME records.
    */
    function _store_externs()
    {
        // Create EXTERNCOUNT with number of worksheets
        $this->_store_externcount(count($this->worksheets));

        // Create EXTERNSHEET for each worksheet
        foreach ($this->sheetnames as $sheetname) {
            $this->_store_externsheet($sheetname);
        }
    }

    /**
    * Write the NAME record to define the print area and the repeat rows and 
cols.
    */
    function _store_names()
    {
        // Create the print area NAME records
        foreach ($this->worksheets as $worksheet)
        {
            // Write a Name record if the print area has been defined
            if (isset($worksheet->_print_rowmin))
            {
                $this->store_name_short(
                    $worksheet->index,
                    0x06, // NAME type
                    $worksheet->_print_rowmin,
                    $worksheet->_print_rowmax,
                    $worksheet->_print_colmin,
                    $worksheet->_print_colmax
                    );
            }
        }

        // Create the print title NAME records
        foreach ($this->worksheets as $worksheet)
        {
            $rowmin = $worksheet->_title_rowmin;
            $rowmax = $worksheet->_title_rowmax;
            $colmin = $worksheet->_title_colmin;
            $colmax = $worksheet->_title_colmax;

            // Determine if row + col, row, col or nothing has been defined
            // and write the appropriate record
            //
            if (isset($rowmin) && isset($colmin))
            {
                // Row and column titles have been defined.
                // Row title has been defined.
                $this->store_name_long(
                    $worksheet->index,
                    0x07, // NAME type
                    $rowmin,
                    $rowmax,
                    $colmin,
                    $colmax
                    );
            }
            elseif (isset($rowmin))
            {
                // Row title has been defined.
                $this->store_name_short(
                    $worksheet->index,
                    0x07, // NAME type
                    $rowmin,
                    $rowmax,
                    0x00,
                    0xff
                    );
            }
            elseif (isset($colmin))
            {
                // Column title has been defined.
                $this->store_name_short(
                    $worksheet->index,
                    0x07, // NAME type
                    0x0000,
                    0x3fff,
                    $colmin,
                    $colmax
                    );
            }
            else {
                // Print title hasn't been defined.
            }
        }
    }




    
/******************************************************************************
    *
    * BIFF RECORDS
    *
    */

    /**
    * Write Excel BIFF WINDOW1 record.
    */
    function _store_window1()
    {
        $record    = 0x003D;                 // Record identifier
        $length    = 0x0012;                 // Number of bytes to follow

        $xWn       = 0x0000;                 // Horizontal position of window
        $yWn       = 0x0000;                 // Vertical position of window
        $dxWn      = 0x25BC;                 // Width of window
        $dyWn      = 0x1572;                 // Height of window

        $grbit     = 0x0038;                 // Option flags
        $ctabsel   = $this->selected;        // Number of workbook tabs selected
        $wTabRatio = 0x0258;                 // Tab to scrollbar ratio

        $itabFirst = $this->firstsheet;   // 1st displayed worksheet
        $itabCur   = $this->activesheet;  // Active worksheet

        $header    = pack("vv",        $record, $length);
        $data      = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn,
                                       $grbit,
                                       $itabCur, $itabFirst,
                                       $ctabsel, $wTabRatio);
        $this->_append($header.$data);
    }

    /**
    * Writes Excel BIFF BOUNDSHEET record.
    *
    * @param string  $sheetname Worksheet name
    * @param integer $offset    Location of worksheet BOF
    */
    function _store_boundsheet($sheetname,$offset)
    {
        $record    = 0x0085;                    // Record identifier
        $length    = 0x07 + strlen($sheetname); // Number of bytes to follow

        $grbit     = 0x0000;                    // Sheet identifier
        $cch       = strlen($sheetname);        // Length of sheet name

        $header    = pack("vv",  $record, $length);
        $data      = pack("VvC", $offset, $grbit, $cch);
        $this->_append($header.$data.$sheetname);
    }

    /**
    * Write Excel BIFF STYLE records.
    */
    function _store_style()
    {
        $record    = 0x0293;   // Record identifier
        $length    = 0x0004;   // Bytes to follow

        $ixfe      = 0x8000;   // Index to style XF
        $BuiltIn   = 0x00;     // Built-in style
        $iLevel    = 0xff;     // Outline style level

        $header    = pack("vv",  $record, $length);
        $data      = pack("vCC", $ixfe, $BuiltIn, $iLevel);
        $this->_append($header.$data);
    }


    /**
    * Writes Excel FORMAT record for non "built-in" numerical formats.
    *
    * @param string  $format Custom format string
    * @param integer $ifmt   Format index code
    */
    function _store_num_format($format,$ifmt)
    {
        $record    = 0x041E;                      // Record identifier
        $length    = 0x03 + strlen($format);      // Number of bytes to follow

        $cch       = strlen($format);             // Length of format string

        $header    = pack("vv", $record, $length);
        $data      = pack("vC", $ifmt, $cch);
        $this->_append($header.$data.$format);
    }

    /**
    * Write Excel 1904 record to indicate the date system in use.
    */
    function _store_1904()
    {
        $record    = 0x0022;         // Record identifier
        $length    = 0x0002;         // Bytes to follow

        $f1904     = $this->_1904;   // Flag for 1904 date system

        $header    = pack("vv", $record, $length);
        $data      = pack("v", $f1904);
        $this->_append($header.$data);
    }


    /**
    * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
    * references in the workbook.
    *
    * Excel only stores references to external sheets that are used in NAME.
    * The workbook NAME record is required to define the print area and the 
repeat
    * rows and columns.
    *
    * A similar method is used in Worksheet.php for a slightly different 
purpose.
    *
    * @param integer $cxals Number of external references
    */
    function _store_externcount($cxals)
    {
        $record   = 0x0016;          // Record identifier
        $length   = 0x0002;          // Number of bytes to follow

        $header   = pack("vv", $record, $length);
        $data     = pack("v",  $cxals);
        $this->_append($header.$data);
    }


    /**
    * Writes the Excel BIFF EXTERNSHEET record. These references are used by
    * formulas. NAME record is required to define the print area and the repeat
    * rows and columns.
    *
    * A similar method is used in Worksheet.php for a slightly different 
purpose.
    *
    * @param string $sheetname Worksheet name
    */
    function _store_externsheet($sheetname)
    {
        $record      = 0x0017;                     // Record identifier
        $length      = 0x02 + strlen($sheetname);  // Number of bytes to follow

        $cch         = strlen($sheetname);         // Length of sheet name
        $rgch        = 0x03;                       // Filename encoding

        $header      = pack("vv",  $record, $length);
        $data        = pack("CC", $cch, $rgch);
        $this->_append($header.$data.$sheetname);
    }


    /**
    * Store the NAME record in the short format that is used for storing the 
print
    * area, repeat rows only and repeat columns only.
    *
    * @param integer $index  Sheet index
    * @param integer $type   Built-in name type
    * @param integer $rowmin Start row
    * @param integer $rowmax End row
    * @param integer $colmin Start colum
    * @param integer $colmax End column
    */
    function store_name_short($index,$type,$rowmin,$rowmax,$colmin,$colmax)
    {
        $record          = 0x0018;       // Record identifier
        $length          = 0x0024;       // Number of bytes to follow

        $grbit           = 0x0020;       // Option flags
        $chKey           = 0x00;         // Keyboard shortcut
        $cch             = 0x01;         // Length of text name
        $cce             = 0x0015;       // Length of text definition
        $ixals           = $index + 1;   // Sheet index
        $itab            = $ixals;       // Equal to ixals
        $cchCustMenu     = 0x00;         // Length of cust menu text
        $cchDescription  = 0x00;         // Length of description text
        $cchHelptopic    = 0x00;         // Length of help topic text
        $cchStatustext   = 0x00;         // Length of status bar text
        $rgch            = $type;        // Built-in name type

        $unknown03       = 0x3b;
        $unknown04       = 0xffff-$index;
        $unknown05       = 0x0000;
        $unknown06       = 0x0000;
        $unknown07       = 0x1087;
        $unknown08       = 0x8005;

        $header             = pack("vv", $record, $length);
        $data               = pack("v", $grbit);
        $data              .= pack("C", $chKey);
        $data              .= pack("C", $cch);
        $data              .= pack("v", $cce);
        $data              .= pack("v", $ixals);
        $data              .= pack("v", $itab);
        $data              .= pack("C", $cchCustMenu);
        $data              .= pack("C", $cchDescription);
        $data              .= pack("C", $cchHelptopic);
        $data              .= pack("C", $cchStatustext);
        $data              .= pack("C", $rgch);
        $data              .= pack("C", $unknown03);
        $data              .= pack("v", $unknown04);
        $data              .= pack("v", $unknown05);
        $data              .= pack("v", $unknown06);
        $data              .= pack("v", $unknown07);
        $data              .= pack("v", $unknown08);
        $data              .= pack("v", $index);
        $data              .= pack("v", $index);
        $data              .= pack("v", $rowmin);
        $data              .= pack("v", $rowmax);
        $data              .= pack("C", $colmin);
        $data              .= pack("C", $colmax);
        $this->_append($header.$data);
    }


    /**
    * Store the NAME record in the long format that is used for storing the 
repeat
    * rows and columns when both are specified. This share a lot of code with
    * _store_name_short() but we use a separate method to keep the code clean.
    * Code abstraction for reuse can be carried too far, and I should know. ;-)
    *
    * @param integer $index Sheet index
    * @param integer $type  Built-in name type
    * @param integer $rowmin Start row
    * @param integer $rowmax End row
    * @param integer $colmin Start colum
    * @param integer $colmax End column
    */
    function store_name_long($index,$type,$rowmin,$rowmax,$colmin,$colmax)
    {
        $record          = 0x0018;       // Record identifier
        $length          = 0x003d;       // Number of bytes to follow
        $grbit           = 0x0020;       // Option flags
        $chKey           = 0x00;         // Keyboard shortcut
        $cch             = 0x01;         // Length of text name
        $cce             = 0x002e;       // Length of text definition
        $ixals           = $index + 1;   // Sheet index
        $itab            = $ixals;       // Equal to ixals
        $cchCustMenu     = 0x00;         // Length of cust menu text
        $cchDescription  = 0x00;         // Length of description text
        $cchHelptopic    = 0x00;         // Length of help topic text
        $cchStatustext   = 0x00;         // Length of status bar text
        $rgch            = $type;        // Built-in name type

        $unknown01       = 0x29;
        $unknown02       = 0x002b;
        $unknown03       = 0x3b;
        $unknown04       = 0xffff-$index;
        $unknown05       = 0x0000;
        $unknown06       = 0x0000;
        $unknown07       = 0x1087;
        $unknown08       = 0x8008;

        $header             = pack("vv",  $record, $length);
        $data               = pack("v", $grbit);
        $data              .= pack("C", $chKey);
        $data              .= pack("C", $cch);
        $data              .= pack("v", $cce);
        $data              .= pack("v", $ixals);
        $data              .= pack("v", $itab);
        $data              .= pack("C", $cchCustMenu);
        $data              .= pack("C", $cchDescription);
        $data              .= pack("C", $cchHelptopic);
        $data              .= pack("C", $cchStatustext);
        $data              .= pack("C", $rgch);
        $data              .= pack("C", $unknown01);
        $data              .= pack("v", $unknown02);
        // Column definition
        $data              .= pack("C", $unknown03);
        $data              .= pack("v", $unknown04);
        $data              .= pack("v", $unknown05);
        $data              .= pack("v", $unknown06);
        $data              .= pack("v", $unknown07);
        $data              .= pack("v", $unknown08);
        $data              .= pack("v", $index);
        $data              .= pack("v", $index);
        $data              .= pack("v", 0x0000);
        $data              .= pack("v", 0x3fff);
        $data              .= pack("C", $colmin);
        $data              .= pack("C", $colmax);
        // Row definition
        $data              .= pack("C", $unknown03);
        $data              .= pack("v", $unknown04);
        $data              .= pack("v", $unknown05);
        $data              .= pack("v", $unknown06);
        $data              .= pack("v", $unknown07);
        $data              .= pack("v", $unknown08);
        $data              .= pack("v", $index);
        $data              .= pack("v", $index);
        $data              .= pack("v", $rowmin);
        $data              .= pack("v", $rowmax);
        $data              .= pack("C", 0x00);
        $data              .= pack("C", 0xff);
        // End of data
        $data              .= pack("C", 0x10);
        $this->_append($header.$data);
    }


    /**
    * Stores the PALETTE biff record.
    */
    function _store_palette()
    {
        $aref            = $this->palette;

        $record          = 0x0092;                 // Record identifier
        $length          = 2 + 4 * count($aref);   // Number of bytes to follow
        $ccv             =         count($aref);   // Number of RGB values to 
follow
        $data = '';                                // The RGB data

        // Pack the RGB data
        foreach($aref as $color)
        {
            foreach($color as $byte) {
                $data .= pack("C",$byte);
            }
        }

        $header = pack("vvv",  $record, $length, $ccv);
        $this->_append($header.$data);
    }
}
?>

====================================================
Index: Worksheet.php
<?php
/*
*  Module written/ported by Xavier Noguer <address@hidden>
*
*  The majority of this is _NOT_ my code.  I simply ported it from the
*  PERL Spreadsheet::WriteExcel module.
*
*  The author of the Spreadsheet::WriteExcel module is John McNamara
*  <address@hidden>
*
*  I _DO_ maintain this code, and John McNamara has nothing to do with the
*  porting of this code to PHP.  Any questions directly related to this
*  class library should be directed to me.
*
*  License Information:
*
*    Spreadsheet::WriteExcel:  A library for generating Excel Spreadsheets
*    Copyright (C) 2002 Xavier Noguer address@hidden
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

require_once('Parser.php');
require_once('BIFFwriter.php');

/**
* Class for generating Excel Spreadsheets
*
* @author Xavier Noguer <address@hidden>
* @package Spreadsheet_WriteExcel
*/

class Worksheet extends BIFFwriter
{

    /**
    * Constructor
    *
    * @param string  $name         The name of the new worksheet
    * @param integer $index        The index of the new worksheet
    * @param mixed   &$activesheet The current activesheet of the workbook we 
belong to
    * @param mixed   &$firstsheet  The first worksheet in the workbook we 
belong to
    * @param mixed   &$url_format  The default format for hyperlinks
    * @param mixed   &$parser      The formula parser created for the Workbook
    */
    function 
Worksheet($name,$index,&$activesheet,&$firstsheet,&$url_format,&$parser)
    {
        $this->BIFFwriter();     // It needs to call its parent's constructor 
explicitly
        $rowmax                = 65536; // 16384 in Excel 5
        $colmax                = 256;
        $strmax                = 255;

        $this->name            = $name;
        $this->index           = $index;
        $this->activesheet     = &$activesheet;
        $this->firstsheet      = &$firstsheet;
        $this->_url_format     = $url_format;
        $this->_parser         = &$parser;

        $this->ext_sheets      = array();
        $this->_using_tmpfile  = 1;
        $this->_filehandle     = "";
        $this->fileclosed      = 0;
        $this->offset          = 0;
        $this->xls_rowmax      = $rowmax;
        $this->xls_colmax      = $colmax;
        $this->xls_strmax      = $strmax;
        $this->dim_rowmin      = $rowmax +1;
        $this->dim_rowmax      = 0;
        $this->dim_colmin      = $colmax +1;
        $this->dim_colmax      = 0;
        $this->colinfo         = array();
        $this->_selection      = array(0,0,0,0);
        $this->_panes          = array();
        $this->_active_pane    = 3;
        $this->_frozen         = 0;
        $this->selected        = 0;

        $this->_paper_size      = 0x0;
        $this->_orientation     = 0x1;
        $this->_header          = '';
        $this->_footer          = '';
        $this->_hcenter         = 0;
        $this->_vcenter         = 0;
        $this->_margin_head     = 0.50;
        $this->_margin_foot     = 0.50;
        $this->_margin_left     = 0.75;
        $this->_margin_right    = 0.75;
        $this->_margin_top      = 1.00;
        $this->_margin_bottom   = 1.00;

        $this->_title_rowmin    = NULL;
        $this->_title_rowmax    = NULL;
        $this->_title_colmin    = NULL;
        $this->_title_colmax    = NULL;
        $this->_print_rowmin    = NULL;
        $this->_print_rowmax    = NULL;
        $this->_print_colmin    = NULL;
        $this->_print_colmax    = NULL;

        $this->_print_gridlines = 1;
        $this->_print_headers   = 0;

        $this->_fit_page        = 0;
        $this->_fit_width       = 0;
        $this->_fit_height      = 0;

        $this->_hbreaks         = array();
        $this->_vbreaks         = array();

        $this->_protect         = 0;
        $this->_password        = NULL;

        $this->col_sizes        = array();
        $this->row_sizes        = array();

        $this->_zoom            = 100;
        $this->_print_scale     = 100;

        $this->_initialize();
    }

    /**
    * Open a tmp file to store the majority of the Worksheet data. If this 
fails,
    * for example due to write permissions, store the data in memory. This can 
be
    * slow for large files.
    */
    function _initialize()
    {
        // Open tmp file for storing Worksheet data
        $fh = tmpfile();
        if ( $fh) {
            // Store filehandle
            $this->_filehandle = $fh;
        }
        else {
            // If tmpfile() fails store data in memory
            $this->_using_tmpfile = 0;
        }
    }

    /**
    * Add data to the beginning of the workbook (note the reverse order)
    * and to the end of the workbook.
    *
    * @access public
    * @see Workbook::store_workbook()
    * @param array $sheetnames The array of sheetnames from the Workbook this
    *                          worksheet belongs to
    */
    function close($sheetnames)
    {
        $num_sheets = count($sheetnames);

        /***********************************************
        * Prepend in reverse order!!
        */

        // Prepend the sheet dimensions
        $this->_store_dimensions();

        // Prepend the sheet password
        $this->_store_password();

        // Prepend the sheet protection
        $this->_store_protect();

        // Prepend the page setup
        $this->_store_setup();

        // Prepend the bottom margin
        $this->_store_margin_bottom();

        // Prepend the top margin
        $this->_store_margin_top();

        // Prepend the right margin
        $this->_store_margin_right();

        // Prepend the left margin
        $this->_store_margin_left();

        // Prepend the page vertical centering
        $this->store_vcenter();

        // Prepend the page horizontal centering
        $this->store_hcenter();

        // Prepend the page footer
        $this->store_footer();

        // Prepend the page header
        $this->store_header();

        // Prepend the vertical page breaks
        $this->_store_vbreak();

        // Prepend the horizontal page breaks
        $this->_store_hbreak();

        // Prepend WSBOOL
        $this->_store_wsbool();

        // Prepend GRIDSET
        $this->_store_gridset();

        // Prepend PRINTGRIDLINES
        $this->_store_print_gridlines();

        // Prepend PRINTHEADERS
        $this->_store_print_headers();

        // Prepend EXTERNSHEET references
        for ($i = $num_sheets; $i > 0; $i--) {
            $sheetname = $sheetnames[$i-1];
            $this->_store_externsheet($sheetname);
        }

        // Prepend the EXTERNCOUNT of external references.
        $this->_store_externcount($num_sheets);

        // Prepend the COLINFO records if they exist
        if (!empty($this->colinfo)){
            for($i=0; $i < count($this->colinfo); $i++)
            {
                $this->_store_colinfo($this->colinfo[$i]);
            }
            $this->_store_defcol();
        }

        // Prepend the BOF record
        $this->_store_bof(0x0010);

        /*
        * End of prepend. Read upwards from here.
        ***********************************************/

        // Append
        $this->_store_window2();
        $this->_store_zoom();
        if(!empty($this->_panes))
          $this->_store_panes($this->_panes);
        $this->_store_selection($this->_selection);
        $this->_store_eof();
    }

    /**
    * Retrieve the worksheet name. This is usefull when creating worksheets
    * without a name.
    *
    * @access public
    * @return string The worksheet's name
    */
    function get_name()
    {
        return($this->name);
    }

    /**
    * Retrieves data from memory in one chunk, or from disk in $buffer
    * sized chunks.
    *
    * @return string The data
    */
    function get_data()
    {
        $buffer = 4096;

        // Return data stored in memory
        if (isset($this->_data)) {
            $tmp   = $this->_data;
            unset($this->_data);
            $fh    = $this->_filehandle;
            if ($this->_using_tmpfile) {
                fseek($fh, 0);
            }
            return($tmp);
        }
        // Return data stored on disk
        if ($this->_using_tmpfile) {
            if ($tmp = fread($this->_filehandle, $buffer)) {
                return($tmp);
            }
        }

        // No data to return
        return('');
    }

    /**
    * Set this worksheet as a selected worksheet, i.e. the worksheet has its tab
    * highlighted.
    *
    * @access public
    */
    function select()
    {
        $this->selected = 1;
    }

    /**
    * Set this worksheet as the active worksheet, i.e. the worksheet that is
    * displayed when the workbook is opened. Also set it as selected.
    *
    * @access public
    */
    function activate()
    {
        $this->selected = 1;
        $this->activesheet =& $this->index;
    }

    /**
    * Set this worksheet as the first visible sheet. This is necessary
    * when there are a large number of worksheets and the activated
    * worksheet is not visible on the screen.
    *
    * @access public
    */
    function set_first_sheet()
    {
        $this->firstsheet = $this->index;
    }

    /**
    * Set the worksheet protection flag to prevent accidental modification and 
to
    * hide formulas if the locked and hidden format properties have been set.
    *
    * @access public
    * @param string $password The password to use for protecting the sheet.
    */
    function protect($password)
    {
        $this->_protect   = 1;
        $this->_password  = $this->_encode_password($password);
    }

    /**
    * Set the width of a single column or a range of columns.
    *
    * @access public
    * @see _store_colinfo()
    * @param integer $firstcol first column on the range
    * @param integer $lastcol  last column on the range
    * @param integer $width    width to set
    * @param mixed   $format   The optional XF format to apply to the columns
    * @param integer $hidden   The optional hidden atribute
    */
    function set_column($firstcol, $lastcol, $width, $format = 0, $hidden = 0)
    {
        $this->colinfo[] = array($firstcol, $lastcol, $width, $format, $hidden);

        // Set width to zero if column is hidden
        $width = ($hidden) ? 0 : $width;

        for($col = $firstcol; $col <= $lastcol; $col++) {
            $this->col_sizes[$col] = $width;
        }
    }

    /**
    * Set which cell or cells are selected in a worksheet
    *
    * @access public
    * @param integer $first_row    first row in the selected quadrant
    * @param integer $first_column first column in the selected quadrant
    * @param integer $last_row     last row in the selected quadrant
    * @param integer $last_column  last column in the selected quadrant
    * @see _store_selection()
    */
    function set_selection($first_row,$first_column,$last_row,$last_column)
    {
        $this->_selection = 
array($first_row,$first_column,$last_row,$last_column);
    }

    /**
    * Set panes and mark them as frozen.
    *
    * @access public
    * @param array $panes This is the only parameter received and is composed 
of the following:
    *                     0 => Vertical split position,
    *                     1 => Horizontal split position
    *                     2 => Top row visible
    *                     3 => Leftmost column visible
    *                     4 => Active pane
    */
    function freeze_panes($panes)
    {
        $this->_frozen = 1;
        $this->_panes  = $panes;
    }

    /**
    * Set panes and mark them as unfrozen.
    *
    * @access public
    * @param array $panes This is the only parameter received and is composed 
of the following:
    *                     0 => Vertical split position,
    *                     1 => Horizontal split position
    *                     2 => Top row visible
    *                     3 => Leftmost column visible
    *                     4 => Active pane
    */
    function thaw_panes($panes)
    {
        $this->_frozen = 0;
        $this->_panes  = $panes;
    }

    /**
    * Set the page orientation as portrait.
    *
    * @access public
    */
    function set_portrait()
    {
        $this->_orientation = 1;
    }

    /**
    * Set the page orientation as landscape.
    *
    * @access public
    */
    function set_landscape()
    {
        $this->_orientation = 0;
    }

    /**
    * Set the paper type. Ex. 1 = US Letter, 9 = A4
    *
    * @access public
    * @param integer $size The type of paper size to use
    */
    function set_paper($size = 0)
    {
        $this->_paper_size = $size;
    }


    /**
    * Set the page header caption and optional margin.
    *
    * @access public
    * @param string $string The header text
    * @param float  $margin optional head margin in inches.
    */
    function set_header($string,$margin = 0.50)
    {
        if (strlen($string) >= 255) {
            //carp 'Header string must be less than 255 characters';
            return;
        }
        $this->_header      = $string;
        $this->_margin_head = $margin;
    }

    /**
    * Set the page footer caption and optional margin.
    *
    * @access public
    * @param string $string The footer text
    * @param float  $margin optional foot margin in inches.
    */
    function set_footer($string,$margin = 0.50)
    {
        if (strlen($string) >= 255) {
            //carp 'Footer string must be less than 255 characters';
            return;
        }
        $this->_footer      = $string;
        $this->_margin_foot = $margin;
    }

    /**
    * Center the page horinzontally.
    *
    * @access public
    * @param integer $center the optional value for centering. Defaults to 1 
(center).
    */
    function center_horizontally($center = 1)
    {
        $this->_hcenter = $center;
    }

    /**
    * Center the page horinzontally.
    *
    * @access public
    * @param integer $center the optional value for centering. Defaults to 1 
(center).
    */
    function center_vertically($center = 1)
    {
        $this->_vcenter = $center;
    }

    /**
    * Set all the page margins to the same value in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margins($margin)
    {
        $this->set_margin_left($margin);
        $this->set_margin_right($margin);
        $this->set_margin_top($margin);
        $this->set_margin_bottom($margin);
    }

    /**
    * Set the left and right margins to the same value in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margins_LR($margin)
    {
        $this->set_margin_left($margin);
        $this->set_margin_right($margin);
    }

    /**
    * Set the top and bottom margins to the same value in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margins_TB($margin)
    {
        $this->set_margin_top($margin);
        $this->set_margin_bottom($margin);
    }

    /**
    * Set the left margin in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margin_left($margin = 0.75)
    {
        $this->_margin_left = $margin;
    }

    /**
    * Set the right margin in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margin_right($margin = 0.75)
    {
        $this->_margin_right = $margin;
    }

    /**
    * Set the top margin in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margin_top($margin = 1.00)
    {
        $this->_margin_top = $margin;
    }

    /**
    * Set the bottom margin in inches.
    *
    * @access public
    * @param float $margin The margin to set in inches
    */
    function set_margin_bottom($margin = 1.00)
    {
        $this->_margin_bottom = $margin;
    }

    /**
    * Set the rows to repeat at the top of each printed page. See also the
    * _store_name_xxxx() methods in Workbook.php
    *
    * @access public
    * @param integer $first_row First row to repeat
    * @param integer $last_row  Last row to repeat. Optional.
    */
    function repeat_rows($first_row, $last_row = NULL)
    {
        $this->_title_rowmin  = $first_row;
        if(isset($last_row)) { //Second row is optional
            $this->_title_rowmax  = $last_row;
        }
        else {
            $this->_title_rowmax  = $first_row;
        }
    }

    /**
    * Set the columns to repeat at the left hand side of each printed page.
    * See also the _store_names() methods in Workbook.php
    *
    * @access public
    * @param integer $first_col First column to repeat
    * @param integer $last_col  Last column to repeat. Optional.
    */
    function repeat_columns($first_col, $last_col = NULL)
    {
        $this->_title_colmin  = $first_col;
        if(isset($last_col)) { // Second col is optional
            $this->_title_colmax  = $last_col;
        }
        else {
            $this->_title_colmax  = $first_col;
        }
    }

    /**
    * Set the area of each worksheet that will be printed.
    *
    * @access public
    * @see Workbook::_store_names()
    * @param integer $first_row First row of the area to print
    * @param integer $first_col First column of the area to print
    * @param integer $last_row  Last row of the area to print
    * @param integer $last_col  Last column of the area to print
    */
    function print_area($first_row, $first_col, $last_row, $last_col)
    {
        $this->_print_rowmin  = $first_row;
        $this->_print_colmin  = $first_col;
        $this->_print_rowmax  = $last_row;
        $this->_print_colmax  = $last_col;
    }


    /**
    * Set the option to hide gridlines on the printed page.
    *
    * @access public
    * @see _store_print_gridlines(), _store_gridset()
    */
    function hide_gridlines()
    {
        $this->_print_gridlines = 0;
    }

    /**
    * Set the option to print the row and column headers on the printed page.
    * See also the _store_print_headers() method below.
    *
    * @access public
    * @see _store_print_headers()
    * @param integer $print Whether to print the headers or not. Defaults to 1 
(print).
    */
    function print_row_col_headers($print = 1)
    {
        $this->_print_headers = $print;
    }

    /**
    * Store the vertical and horizontal number of pages that will define the
    * maximum area printed. It doesn't seem to work with OpenOffice.
    *
    * @access public
    * @param  integer $width  Maximun width of printed area in pages
    * @param  integer $heigth Maximun heigth of printed area in pages
    * @see set_print_scale()
    */
    function fit_to_pages($width, $height)
    {
        $this->_fit_page      = 1;
        $this->_fit_width     = $width;
        $this->_fit_height    = $height;
    }

    /**
    * Store the horizontal page breaks on a worksheet (for printing).
    * The breaks represent the row after which the break is inserted.
    *
    * @access public
    * @param array $breaks Array containing the horizontal page breaks
    */
    function set_h_pagebreaks($breaks)
    {
        foreach($breaks as $break) {
            array_push($this->_hbreaks,$break);
        }
    }

    /**
    * Store the vertical page breaks on a worksheet (for printing).
    * The breaks represent the column after which the break is inserted.
    *
    * @access public
    * @param array $breaks Array containing the vertical page breaks
    */
    function set_v_pagebreaks($breaks)
    {
        foreach($breaks as $break) {
            array_push($this->_vbreaks,$break);
        }
    }


    /**
    * Set the worksheet zoom factor.
    *
    * @access public
    * @param integer $scale The zoom factor
    */
    function set_zoom($scale = 100)
    {
        // Confine the scale to Excel's range
        if ($scale < 10 or $scale > 400) {
            //carp "Zoom factor $scale outside range: 10 <= zoom <= 400";
            $scale = 100;
        }

        $this->_zoom = floor($scale);
    }

    /**
    * Set the scale factor for the printed page.
    * It turns off the "fit to page" option
    *
    * @access public
    * @param integer $scale The optional scale factor. Defaults to 100
    */
    function set_print_scale($scale = 100)
    {
        // Confine the scale to Excel's range
        if ($scale < 10 or $scale > 400)
        {
            // REPLACE THIS FOR A WARNING
            die("Print scale $scale outside range: 10 <= zoom <= 400");
            $scale = 100;
        }

        // Turn off "fit to page" option
        $this->_fit_page    = 0;

        $this->_print_scale = floor($scale);
    }

    /**
    * Map to the appropriate write method acording to the token recieved.
    *
    * @access public
    * @param integer $row    The row of the cell we are writing to
    * @param integer $col    The column of the cell we are writing to
    * @param mixed   $token  What we are writing
    * @param mixed   $format The optional format to apply to the cell
    */
    function write($row, $col, $token, $format = 0)
    {
        // Check for a cell reference in A1 notation and substitute row and 
column
        /*if ($_[0] =~ /^\D/) {
            @_ = $this->_substitute_cellref(@_);
    }*/

        /*
        # Match an array ref.
        if (ref $token eq "ARRAY") {
            return $this->write_row(@_);
    }*/

        // Match number
        if 
(preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/",$token)) {
            return $this->write_number($row,$col,$token,$format);
        }
        // Match http or ftp URL
        elseif (preg_match("/^[fh]tt?p:\/\//",$token)) {
            return $this->write_url($row, $col, $token, $format);
        }
        // Match mailto:
        elseif (preg_match("/^mailto:/",$token)) {
            return $this->write_url($row, $col, $token, $format);
        }
        // Match internal or external sheet link
        elseif (preg_match("/^(?:in|ex)ternal:/",$token)) {
            return $this->write_url($row, $col, $token, $format);
        }
        // Match formula
        elseif (preg_match("/^=/",$token)) {
            return $this->write_formula($row, $col, $token, $format);
        }
        // Match formula
        elseif (preg_match("/^@/",$token)) {
            return $this->write_formula($row, $col, $token, $format);
        }
        // Match blank
        elseif ($token == '') {
            return $this->write_blank($row,$col,$format);
        }
        // Default: match string
        else {
            return $this->write_string($row,$col,$token,$format);
        }
    }

    /**
    * Returns an index to the XF record in the workbook
    *
    * @param mixed $format The optional XF format
    * @return integer The XF record index
    */
    function _XF(&$format)
    {
        if($format != 0)
        {
            return($format->get_xf_index());
        }
        else
        {
            return(0x0F);
        }
    }


    
/******************************************************************************
    
*******************************************************************************
    *
    * Internal methods
    */


    /**
    * Store Worksheet data in memory using the parent's class append() or to a
    * temporary file, the default.
    *
    * @param string $data The binary data to append
    */
    function _append($data)
    {
        if ($this->_using_tmpfile)
        {
            // Add CONTINUE records if necessary
            if (strlen($data) > $this->_limit) {
                $data = $this->_add_continue($data);
            }
            fwrite($this->_filehandle,$data);
            $this->_datasize += strlen($data);
        }
        else {
            parent::_append($data);
        }
    }

    /**
    * Substitute an Excel cell reference in A1 notation for  zero based row and
    * column values in an argument list.
    *
    * Ex: ("A4", "Hello") is converted to (3, 0, "Hello").
    *
    * @param string $cell The cell reference. Or range of cells.
    * @return array
    */
    function _substitute_cellref($cell)
    {
        $cell = strtoupper($cell);

        // Convert a column range: 'A:A' or 'B:G'
        if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/",$cell,$match)) {
            list($no_use, $col1) =  $this->_cell_to_rowcol($match[1] .'1'); // 
Add a dummy row
            list($no_use, $col2) =  $this->_cell_to_rowcol($match[2] .'1'); // 
Add a dummy row
            return(array($col1, $col2));
        }

        // Convert a cell range: 'A1:B7'
        if 
(preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/",$cell,$match)) {
            list($row1, $col1) =  $this->_cell_to_rowcol($match[1]);
            list($row2, $col2) =  $this->_cell_to_rowcol($match[2]);
            return(array($row1, $col1, $row2, $col2));
        }

        // Convert a cell reference: 'A1' or 'AD2000'
        if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/",$cell)) {
            list($row1, $col1) =  $this->_cell_to_rowcol($match[1]);
            return(array($row1, $col1));
        }

        die("Unknown cell reference $cell ");
    }

    /**
    * Convert an Excel cell reference in A1 notation to a zero based row and 
column
    * reference; converts C1 to (0, 2).
    *
    * @param string $cell The cell reference.
    * @return array containing (row, column)
    */
    function _cell_to_rowcol($cell)
    {
        preg_match("/\$?([A-I]?[A-Z])\$?(\d+)/",$cell,$match);
        $col     = $match[1];
        $row     = $match[2];

        // Convert base26 column string to number
        $chars = split('', $col);
        $expn  = 0;
        $col   = 0;

        while ($chars) {
            $char = array_pop($chars);        // LS char first
            $col += (ord($char) -ord('A') +1) * pow(26,$expn);
            $expn++;
        }

        // Convert 1-index to zero-index
        $row--;
        $col--;

        return(array($row, $col));
    }

    /**
    * Based on the algorithm provided by Daniel Rentz of OpenOffice.
    *
    * @param string $plaintext The password to be encoded in plaintext.
    * @return string The encoded password
    */
    function _encode_password($plaintext)
    {
        $password = 0x0000;
        $i        = 1;       // char position

        // split the plain text password in its component characters
        $chars = preg_split('//', $plaintext, -1, PREG_SPLIT_NO_EMPTY);
        foreach($chars as $char)
        {
            $value     = ord($char) << $i;   // shifted ASCII value
            $bit_16    = $value & 0x8000;    // the bit 16
            $bit_16  >>= 15;                 // 0x0000 or 0x0001
            //$bit_17    = $value & 0x00010000;
            //$bit_17  >>= 15;
            $value    &= 0x7fff;             // first 15 bits
            $password ^= ($value | $bit_16);
            //$password ^= ($value | $bit_16 | $bit_17);
            $i++;
        }

        $password ^= strlen($plaintext);
        $password ^= 0xCE4B;

        return($password);
    }

    
/******************************************************************************
    
*******************************************************************************
    *
    * BIFF RECORDS
    */


    /**
    * Write a double to the specified row and column (zero indexed).
    * An integer can be written as a double. Excel will display an
    * integer. $format is optional.
    *
    * Returns  0 : normal termination
    *         -2 : row or column out of range
    *
    * @access public
    * @param integer $row    Zero indexed row
    * @param integer $col    Zero indexed column
    * @param float   $num    The number to write
    * @param mixed   $format The optional XF format
    */
    function write_number($row, $col, $num, $format = 0)
    {
        $record    = 0x0203;                 // Record identifier
        $length    = 0x000E;                 // Number of bytes to follow
        $xf        = $this->_XF($format);    // The cell format

        // Check that row and col are valid and store max and min values
        if ($row >= $this->xls_rowmax)
        {
            return(-2);
        }
        if ($col >= $this->xls_colmax)
        {
            return(-2);
        }
        if ($row <  $this->dim_rowmin)
        {
            $this->dim_rowmin = $row;
        }
        if ($row >  $this->dim_rowmax)
        {
            $this->dim_rowmax = $row;
        }
        if ($col <  $this->dim_colmin)
        {
            $this->dim_colmin = $col;
        }
        if ($col >  $this->dim_colmax)
        {
            $this->dim_colmax = $col;
        }

        $header    = pack("vv",  $record, $length);
        $data      = pack("vvv", $row, $col, $xf);
        $xl_double = pack("d",   $num);
        if ($this->_byte_order) // if it's Big Endian
        {
            $xl_double = strrev($xl_double);
        }

        $this->_append($header.$data.$xl_double);
        return(0);
    }

    /**
    * Write a string to the specified row and column (zero indexed).
    * NOTE: there is an Excel 5 defined limit of 255 characters.
    * $format is optional.
    * Returns  0 : normal termination
    *         -1 : insufficient number of arguments
    *         -2 : row or column out of range
    *         -3 : long string truncated to 255 chars
    *
    * @access public
    * @param integer $row    Zero indexed row
    * @param integer $col    Zero indexed column
    * @param string  $str    The string to write
    * @param mixed   $format The XF format for the cell
    */
    function write_string($row, $col, $str, $format = 0)
    {
        $strlen    = strlen($str);
        $record    = 0x0204;                   // Record identifier
        $length    = 0x0008 + $strlen;         // Bytes to follow
        $xf        = $this->_XF($format);      // The cell format

        $str_error = 0;

        // Check that row and col are valid and store max and min values
        if ($row >= $this->xls_rowmax)
        {
            return(-2);
        }
        if ($col >= $this->xls_colmax)
        {
            return(-2);
        }
        if ($row <  $this->dim_rowmin)
        {
            $this->dim_rowmin = $row;
        }
        if ($row >  $this->dim_rowmax)
        {
            $this->dim_rowmax = $row;
        }
        if ($col <  $this->dim_colmin)
        {
            $this->dim_colmin = $col;
        }
        if ($col >  $this->dim_colmax)
        {
            $this->dim_colmax = $col;
        }

        if ($strlen > $this->xls_strmax)  // LABEL must be < 255 chars
        {
            $str       = substr($str, 0, $this->xls_strmax);
            $length    = 0x0008 + $this->xls_strmax;
            $strlen    = $this->xls_strmax;
            $str_error = -3;
        }

        $header    = pack("vv",   $record, $length);
        $data      = pack("vvvv", $row, $col, $xf, $strlen);
        $this->_append($header.$data.$str);
        return($str_error);
    }

    /**
    * Writes a note associated with the cell given by the row and column.
    * NOTE records don't have a length limit.
    *
    * @access public
    * @param integer $row    Zero indexed row
    * @param integer $col    Zero indexed column
    * @param string  $note   The note to write
    */
    function write_note($row, $col, $note)
    {
        $note_length    = strlen($note);
        $record         = 0x001C;                // Record identifier
        $max_length     = 2048;                  // Maximun length for a NOTE 
record
        //$length      = 0x0006 + $note_length;    // Bytes to follow

        // Check that row and col are valid and store max and min values
        if ($row >= $this->xls_rowmax)
        {
            return(-2);
        }
        if ($col >= $this->xls_colmax)
        {
            return(-2);
        }
        if ($row <  $this->dim_rowmin)
        {
            $this->dim_rowmin = $row;
        }
        if ($row >  $this->dim_rowmax)
        {
            $this->dim_rowmax = $row;
        }
        if ($col <  $this->dim_colmin)
        {
            $this->dim_colmin = $col;
        }
        if ($col >  $this->dim_colmax)
        {
            $this->dim_colmax = $col;
        }

        // Length for this record is no more than 2048 + 6
        $length    = 0x0006 + min($note_length, 2048);
        $header    = pack("vv",   $record, $length);
        $data      = pack("vvv", $row, $col, $note_length);
        $this->_append($header.$data.substr($note, 0, 2048));

        for($i = $max_length; $i < $note_length; $i += $max_length)
        {
            $chunk  = substr($note, $i, $max_length);
            $length = 0x0006 + strlen($chunk);
            $header = pack("vv",   $record, $length);
            $data   = pack("vvv", -1, 0, strlen($chunk));
            $this->_append($header.$data.$chunk);
        }
        return(0);
    }

    /**
    * Write a blank cell to the specified row and column (zero indexed).
    * A blank cell is used to specify formatting without adding a string
    * or a number.
    *
    * A blank cell without a format serves no purpose. Therefore, we don't write
    * a BLANK record unless a format is specified. This is mainly an 
optimisation
    * for the write_row() and write_col() methods.
    *
    * Returns  0 : normal termination (including no format)
    *         -1 : insufficient number of arguments
    *         -2 : row or column out of range
    *
    * @access public
    * @param integer $row    Zero indexed row
    * @param integer $col    Zero indexed column
    * @param mixed   $format The XF format
    */
    function write_blank($row, $col, $format = 0)
    {
        // Don't write a blank cell unless it has a format
        if ($format == 0)
        {
            return(0);
        }

        $record    = 0x0201;                 // Record identifier
        $length    = 0x0006;                 // Number of bytes to follow
        $xf        = $this->_XF($format);    // The cell format

        // Check that row and col are valid and store max and min values
        if ($row >= $this->xls_rowmax)
        {
            return(-2);
        }
        if ($col >= $this->xls_colmax)
        {
            return(-2);
        }
        if ($row <  $this->dim_rowmin)
        {
            $this->dim_rowmin = $row;
        }
        if ($row >  $this->dim_rowmax)
        {
            $this->dim_rowmax = $row;
        }
        if ($col <  $this->dim_colmin)
        {
            $this->dim_colmin = $col;
        }
        if ($col >  $this->dim_colmax)
        {
            $this->dim_colmax = $col;
        }

        $header    = pack("vv",  $record, $length);
        $data      = pack("vvv", $row, $col, $xf);
        $this->_append($header.$data);
        return 0;
    }

    /**
    * Write a formula to the specified row and column (zero indexed).
    * The textual representation of the formula is passed to the parser in
    * Parser.php which returns a packed binary string.
    *
    * Returns  0 : normal termination
    *         -2 : row or column out of range
    *
    * @access public
    * @param integer $row     Zero indexed row
    * @param integer $col     Zero indexed column
    * @param string  $formula The formula text string
    * @param mixed   $format  The optional XF format
    */
    function write_formula($row, $col, $formula, $format = 0)
    {
        $record    = 0x0006;     // Record identifier

        // Excel normally stores the last calculated value of the formula in 
$num.
        // Clearly we are not in a position to calculate this a priori. Instead
        // we set $num to zero and set the option flags in $grbit to ensure
        // automatic calculation of the formula when the file is opened.
        //
        $xf        = $this->_XF($format); // The cell format
        $num       = 0x00;                // Current value of formula
        $grbit     = 0x03;                // Option flags
        $chn       = 0x0000;              // Must be zero


        // Check that row and col are valid and store max and min values
        if ($row >= $this->xls_rowmax)
        {
            return(-2);
        }
        if ($col >= $this->xls_colmax)
        {
            return(-2);
        }
        if ($row <  $this->dim_rowmin)
        {
            $this->dim_rowmin = $row;
        }
        if ($row >  $this->dim_rowmax)
        {
            $this->dim_rowmax = $row;
        }
        if ($col <  $this->dim_colmin)
        {
            $this->dim_colmin = $col;
        }
        if ($col >  $this->dim_colmax)
        {
            $this->dim_colmax = $col;
        }

        // Strip the '=' or '@' sign at the beginning of the formula string
        if (ereg("^=",$formula)) {
            $formula = preg_replace("/(^=)/","",$formula);
        }
        elseif(ereg("^@",$formula)) {
            $formula = preg_replace("/(^@)/","",$formula);
        }
        else {
            die("Unrecognised character for formula");
        }

        // Parse the formula using the parser in Parser.php
        //$tree      = new Parser($this->_byte_order);
        $this->_parser->parse($formula);
        //$tree->parse($formula);
        $formula = $this->_parser->to_reverse_polish();

        $formlen    = strlen($formula);    // Length of the binary string
        $length     = 0x16 + $formlen;     // Length of the record data

        $header    = pack("vv",      $record, $length);
        $data      = pack("vvvdvVv", $row, $col, $xf, $num,
                                     $grbit, $chn, $formlen);

        $this->_append($header.$data.$formula);
        return 0;
    }

    /**
    * Write a hyperlink. This is comprised of two elements: the visible label 
and
    * the invisible link. The visible label is the same as the link unless an
    * alternative string is specified. The label is written using the
    * write_string() method. Therefore the 255 characters string limit applies.
    * $string and $format are optional and their order is interchangeable.
    *
    * The hyperlink can be to a http, ftp, mail, internal sheet, or external
    * directory url.
    *
    * Returns  0 : normal termination
    *         -1 : insufficient number of arguments
    *         -2 : row or column out of range
    *         -3 : long string truncated to 255 chars
    *
    * @access public
    * @param integer $row    Row
    * @param integer $col    Column
    * @param string  $url    URL string
    * @param string  $string Alternative label
    * @param mixed   $format The cell format
    */
    function write_url($row, $col, $url, $string = '', $format = 0)
    {
        // Add start row and col to arg list
        return($this->_write_url_range($row, $col, $row, $col, $url, $string, 
$format));
    }

    /**
    * This is the more general form of write_url(). It allows a hyperlink to be
    * written to a range of cells. This function also decides the type of 
hyperlink
    * to be written. These are either, Web (http, ftp, mailto), Internal
    * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
    *
    * See also write_url() above for a general description and return values.
    *
    * @param integer $row1   Start row
    * @param integer $col1   Start column
    * @param integer $row2   End row
    * @param integer $col2   End column
    * @param string  $url    URL string
    * @param string  $string Alternative label
    * @param mixed   $format The cell format
    */

    function _write_url_range($row1, $col1, $row2, $col2, $url, $string = '', 
$format = 0)
    {
        // Check for internal/external sheet links or default to web link
        if (preg_match('[^internal:]', $url)) {
            return($this->_write_url_internal($row1, $col1, $row2, $col2, $url, 
$string, $format));
        }
        if (preg_match('[^external:]', $url)) {
            return($this->_write_url_external($row1, $col1, $row2, $col2, $url, 
$string, $format));
        }
        return($this->_write_url_web($row1, $col1, $row2, $col2, $url, $string, 
$format));
    }


    /**
    * Used to write http, ftp and mailto hyperlinks.
    * The link type ($options) is 0x03 is the same as absolute dir ref without
    * sheet. However it is differentiated by the $unknown2 data stream.
    *
    * @see write_url()
    * @param integer $row1   Start row
    * @param integer $col1   Start column
    * @param integer $row2   End row
    * @param integer $col2   End column
    * @param string  $url    URL string
    * @param string  $str    Alternative label
    * @param mixed   $format The cell format
    */
    function _write_url_web($row1, $col1, $row2, $col2, $url, $str, $format = 0)
    {
        $record      = 0x01B8;                       // Record identifier
        $length      = 0x00000;                      // Bytes to follow

        if($format == 0) {
            $format = $this->_url_format;
        }

        // Write the visible label using the write_string() method.
        if($str == '') {
            $str = $url;
        }
        $str_error = $this->write_string($row1, $col1, $str, $format);
        if ($str_error == -2) {
            return($str_error);
        }

        // Pack the undocumented parts of the hyperlink stream
        $unknown1    = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
        $unknown2    = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");

        // Pack the option flags
        $options     = pack("V", 0x03);

        // Convert URL to a null terminated wchar string
        $url         = join("\0", preg_split("''", $url, -1, 
PREG_SPLIT_NO_EMPTY));
        $url         = $url . "\0\0\0";

        // Pack the length of the URL
        $url_len     = pack("V", strlen($url));

        // Calculate the data length
        $length      = 0x34 + strlen($url);

        // Pack the header data
        $header      = pack("vv",   $record, $length);
        $data        = pack("vvvv", $row1, $row2, $col1, $col2);

        // Write the packed data
        $this->_append( $header. $data.
                        $unknown1. $options.
                        $unknown2. $url_len. $url);
        return($str_error);
    }

    /**
    * Used to write internal reference hyperlinks such as "Sheet1!A1".
    *
    * @see write_url()
    * @param integer $row1   Start row
    * @param integer $col1   Start column
    * @param integer $row2   End row
    * @param integer $col2   End column
    * @param string  $url    URL string
    * @param string  $str    Alternative label
    * @param mixed   $format The cell format
    */
    function _write_url_internal($row1, $col1, $row2, $col2, $url, $str, 
$format = 0)
    {
        $record      = 0x01B8;                       // Record identifier
        $length      = 0x00000;                      // Bytes to follow

        if ($format == 0) {
            $format = $this->_url_format;
        }

        // Strip URL type
        $url = preg_replace('s[^internal:]', '', $url);

        // Write the visible label
        if($str == '') {
            $str = $url;
        }
        $str_error = $this->write_string($row1, $col1, $str, $format);
        if ($str_error == -2) {
            return($str_error);
        }

        // Pack the undocumented parts of the hyperlink stream
        $unknown1    = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");

        // Pack the option flags
        $options     = pack("V", 0x08);

        // Convert the URL type and to a null terminated wchar string
        $url         = join("\0", preg_split("''", $url, -1, 
PREG_SPLIT_NO_EMPTY));
        $url         = $url . "\0\0\0";

        // Pack the length of the URL as chars (not wchars)
        $url_len     = pack("V", floor(strlen($url)/2));

        // Calculate the data length
        $length      = 0x24 + strlen($url);

        // Pack the header data
        $header      = pack("vv",   $record, $length);
        $data        = pack("vvvv", $row1, $row2, $col1, $col2);

        // Write the packed data
        $this->_append($header. $data.
                       $unknown1. $options.
                       $url_len. $url);
        return($str_error);
    }

    /**
    * Write links to external directory names such as 'c:\foo.xls',
    * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
    *
    * Note: Excel writes some relative links with the $dir_long string. We 
ignore
    * these cases for the sake of simpler code.
    *
    * @see write_url()
    * @param integer $row1   Start row
    * @param integer $col1   Start column
    * @param integer $row2   End row
    * @param integer $col2   End column
    * @param string  $url    URL string
    * @param string  $str    Alternative label
    * @param mixed   $format The cell format
    */
    function _write_url_external($row1, $col1, $row2, $col2, $url, $str, 
$format = 0)
    {
        // Network drives are different. We will handle them separately
        // MS/Novell network drives and shares start with \\
        if (preg_match('[^external:\\\\]', $url)) {
            return($this->_write_url_external_net($row1, $col1, $row2, $col2, 
$url, $str, $format));
        }

        $record      = 0x01B8;                       // Record identifier
        $length      = 0x00000;                      // Bytes to follow

        if ($format == 0) {
            $format = $this->_url_format;
        }

        // Strip URL type and change Unix dir separator to Dos style (if needed)
        //
        $url = preg_replace('[^external:]', '', $url);
        $url = preg_replace('[/]', "\\", $url);

        // Write the visible label
        if ($str == '') {
            $str = preg_replace('[\#]', ' - ', $url);
        }
        $str_error = $this->write_string($row1, $col1, $str, $format);
        if ($str_error == -2) {
            return($str_error);
        }

        // Determine if the link is relative or absolute:
        //   relative if link contains no dir separator, "somefile.xls"
        //   relative if link starts with up-dir, "..\..\somefile.xls"
        //   otherwise, absolute

        $absolute    = 0x02; // Bit mask
        if (!preg_match('[\\]', $url)) {
            $absolute    = 0x00;
        }
        if (preg_match('[^\.\.\\]', $url)) {
            $absolute    = 0x00;
        }

        // Determine if the link contains a sheet reference and change some of 
the
        // parameters accordingly.
        // Split the dir name and sheet name (if it exists)
        list($dir_long , $sheet) = split('/\#/', $url);
        $link_type               = 0x01 | $absolute;

        if (isset($sheet)) {
            $link_type |= 0x08;
            $sheet_len  = pack("V", strlen($sheet) + 0x01);
            $sheet      = join("\0", split('', $sheet));
            $sheet     .= "\0\0\0";
        }
        else {
            $sheet_len   = '';
            $sheet       = '';
        }

        // Pack the link type
        $link_type   = pack("V", $link_type);

        // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
        $up_count    = preg_match_all("/\.\.\\/", $dir_long, $useless);
        $up_count    = pack("v", $up_count);

        // Store the short dos dir name (null terminated)
        $dir_short   = preg_replace('/\.\.\\/', '', $dir_long) . "\0";

        // Store the long dir name as a wchar string (non-null terminated)
        $dir_long       = join("\0", split('', $dir_long));
        $dir_long       = $dir_long . "\0";

        // Pack the lengths of the dir strings
        $dir_short_len = pack("V", strlen($dir_short)      );
        $dir_long_len  = pack("V", strlen($dir_long)       );
        $stream_len    = pack("V", strlen($dir_long) + 0x06);

        // Pack the undocumented parts of the hyperlink stream
        $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000'       
);
        $unknown2 = pack("H*",'0303000000000000C000000000000046'               
);
        $unknown3 = 
pack("H*",'FFFFADDE000000000000000000000000000000000000000');
        $unknown4 = pack("v",  0x03                                            
);

        // Pack the main data stream
        $data        = pack("vvvv", $row1, $row2, $col1, $col2) .
                          $unknown1     .
                          $link_type    .
                          $unknown2     .
                          $up_count     .
                          $dir_short_len.
                          $dir_short    .
                          $unknown3     .
                          $stream_len   .
                          $dir_long_len .
                          $unknown4     .
                          $dir_long     .
                          $sheet_len    .
                          $sheet        ;

        // Pack the header data
        $length   = strlen($data);
        $header   = pack("vv", $record, $length);

        // Write the packed data
        $this->_append($header. $data);
        return($str_error);
    }


    /*
    
###############################################################################
    #
    # write_url_xxx($row1, $col1, $row2, $col2, $url, $string, $format)
    #
    # Write links to external MS/Novell network drives and shares such as
    # '//NETWORK/share/foo.xls' and '//NETWORK/share/foo.xls#Sheet1!A1'.
    #
    # See also write_url() above for a general description and return values.
    #
    sub _write_url_external_net {

        my $this    = shift;

        my $record      = 0x01B8;                       # Record identifier
        my $length      = 0x00000;                      # Bytes to follow

        my $row1        = $_[0];                        # Start row
        my $col1        = $_[1];                        # Start column
        my $row2        = $_[2];                        # End row
        my $col2        = $_[3];                        # End column
        my $url         = $_[4];                        # URL string
        my $str         = $_[5];                        # Alternative label
        my $xf          = $_[6] || $this->{_url_format};# The cell format


        # Strip URL type and change Unix dir separator to Dos style (if needed)
        #
        $url            =~ s[^external:][];
        $url            =~ s[/][\\]g;


        # Write the visible label
        ($str = $url)   =~ s[\#][ - ] unless defined $str;
        my $str_error   = $this->write_string($row1, $col1, $str, $xf);
        return $str_error if $str_error == -2;


        # Determine if the link contains a sheet reference and change some of 
the
        # parameters accordingly.
        # Split the dir name and sheet name (if it exists)
        #
        my ($dir_long , $sheet) = split /\#/, $url;
        my $link_type           = 0x0103; # Always absolute
        my $sheet_len;

        if (defined $sheet) {
            $link_type |= 0x08;
            $sheet_len  = pack("V", length($sheet) + 0x01);
            $sheet      = join("\0", split('', $sheet));
            $sheet     .= "\0\0\0";
    }
        else {
            $sheet_len   = '';
            $sheet       = '';
    }

        # Pack the link type
        $link_type      = pack("V", $link_type);


        # Make the string null terminated
        $dir_long       = $dir_long . "\0";


        # Pack the lengths of the dir string
        my $dir_long_len  = pack("V", length $dir_long);


        # Store the long dir name as a wchar string (non-null terminated)
        $dir_long       = join("\0", split('', $dir_long));
        $dir_long       = $dir_long . "\0";


        # Pack the undocumented part of the hyperlink stream
        my $unknown1    = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000');


        # Pack the main data stream
        my $data        = pack("vvvv", $row1, $row2, $col1, $col2) .
                          $unknown1     .
                          $link_type    .
                          $dir_long_len .
                          $dir_long     .
                          $sheet_len    .
                          $sheet        ;


        # Pack the header data
        $length         = length $data;
        my $header      = pack("vv",   $record, $length);


        # Write the packed data
        $this->_append( $header, $data);

        return $str_error;
}*/

    /**
    * This method is used to set the height and XF format for a row.
    * Writes the  BIFF record ROW.
    *
    * @access public
    * @param integer $row    The row to set
    * @param integer $height Height we are giving to the row.
    *                        Use NULL to set XF without setting height
    * @param mixed   $format XF format we are giving to the row
    */
    function set_row($row, $height, $format = 0)
    {
        $record      = 0x0208;               // Record identifier
        $length      = 0x0010;               // Number of bytes to follow

        $colMic      = 0x0000;               // First defined column
        $colMac      = 0x0000;               // Last defined column
        $irwMac      = 0x0000;               // Used by Excel to optimise 
loading
        $reserved    = 0x0000;               // Reserved
        $grbit       = 0x01C0;               // Option flags. (monkey) see $1 do
        $ixfe        = $this->_XF($format); // XF index

        // Use set_row($row, NULL, $XF) to set XF without setting height
        if ($height != NULL) {
            $miyRw = $height * 20;  // row height
        }
        else {
            $miyRw = 0xff;          // default row height is 256
        }

        $header   = pack("vv",       $record, $length);
        $data     = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
                                     $irwMac,$reserved, $grbit, $ixfe);
        $this->_append($header.$data);
    }

    /**
    * Writes Excel DIMENSIONS to define the area in which there is data.
    */
    function _store_dimensions()
    {
        $record    = 0x0000;               // Record identifier
        $length    = 0x000A;               // Number of bytes to follow
        $row_min   = $this->dim_rowmin;    // First row
        $row_max   = $this->dim_rowmax;    // Last row plus 1
        $col_min   = $this->dim_colmin;    // First column
        $col_max   = $this->dim_colmax;    // Last column plus 1
        $reserved  = 0x0000;               // Reserved by Excel

        $header    = pack("vv",    $record, $length);
        $data      = pack("vvvvv", $row_min, $row_max,
                                   $col_min, $col_max, $reserved);
        $this->_prepend($header.$data);
    }

    /**
    * Write BIFF record Window2.
    */
    function _store_window2()
    {
        $record         = 0x023E;     // Record identifier
        $length         = 0x000A;     // Number of bytes to follow

        $grbit          = 0x00B6;     // Option flags
        $rwTop          = 0x0000;     // Top row visible in window
        $colLeft        = 0x0000;     // Leftmost column visible in window
        $rgbHdr         = 0x00000000; // Row/column heading and gridline color

        // The options flags that comprise $grbit
        $fDspFmla       = 0;                     // 0 - bit
        $fDspGrid       = 1;                     // 1
        $fDspRwCol      = 1;                     // 2
        $fFrozen        = $this->_frozen;        // 3
        $fDspZeros      = 1;                     // 4
        $fDefaultHdr    = 1;                     // 5
        $fArabic        = 0;                     // 6
        $fDspGuts       = 1;                     // 7
        $fFrozenNoSplit = 0;                     // 0 - bit
        $fSelected      = $this->selected;       // 1
        $fPaged         = 1;                     // 2

        $grbit             = $fDspFmla;
        $grbit            |= $fDspGrid       << 1;
        $grbit            |= $fDspRwCol      << 2;
        $grbit            |= $fFrozen        << 3;
        $grbit            |= $fDspZeros      << 4;
        $grbit            |= $fDefaultHdr    << 5;
        $grbit            |= $fArabic        << 6;
        $grbit            |= $fDspGuts       << 7;
        $grbit            |= $fFrozenNoSplit << 8;
        $grbit            |= $fSelected      << 9;
        $grbit            |= $fPaged         << 10;

        $header  = pack("vv",   $record, $length);
        $data    = pack("vvvV", $grbit, $rwTop, $colLeft, $rgbHdr);
        $this->_append($header.$data);
    }

    /**
    * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
    */
    function _store_defcol()
    {
        $record   = 0x0055;      // Record identifier
        $length   = 0x0002;      // Number of bytes to follow
        $colwidth = 0x0008;      // Default column width

        $header   = pack("vv", $record, $length);
        $data     = pack("v",  $colwidth);
        $this->_prepend($header.$data);
    }

    /**
    * Write BIFF record COLINFO to define column widths
    *
    * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
    * length record.
    *
    * @param array $col_array This is the only parameter received and is 
composed of the following:
    *                0 => First formatted column,
    *                1 => Last formatted column,
    *                2 => Col width (8.43 is Excel default),
    *                3 => The optional XF format of the column,
    *                4 => Option flags.
    */
    function _store_colinfo($col_array)
    {
        if(isset($col_array[0])) {
            $colFirst = $col_array[0];
        }
        if(isset($col_array[1])) {
            $colLast = $col_array[1];
        }
        if(isset($col_array[2])) {
            $coldx = $col_array[2];
        }
        else {
            $coldx = 8.43;
        }
        if(isset($col_array[3])) {
            $format = $col_array[3];
        }
        else {
            $format = 0;
        }
        if(isset($col_array[4])) {
            $grbit = $col_array[4];
        }
        else {
            $grbit = 0;
        }
        $record   = 0x007D;          // Record identifier
        $length   = 0x000B;          // Number of bytes to follow

        $coldx   += 0.72;            // Fudge. Excel subtracts 0.72 !?
        $coldx   *= 256;             // Convert to units of 1/256 of a char

        $ixfe     = $this->_XF($format);
        $reserved = 0x00;            // Reserved

        $header   = pack("vv",     $record, $length);
        $data     = pack("vvvvvC", $colFirst, $colLast, $coldx,
                                   $ixfe, $grbit, $reserved);
        $this->_prepend($header.$data);
    }

    /**
    * Write BIFF record SELECTION.
    *
    * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast)
    * @see set_selection()
    */
    function _store_selection($array)
    {
        list($rwFirst,$colFirst,$rwLast,$colLast) = $array;
        $record   = 0x001D;                  // Record identifier
        $length   = 0x000F;                  // Number of bytes to follow

        $pnn      = $this->_active_pane;     // Pane position
        $rwAct    = $rwFirst;                // Active row
        $colAct   = $colFirst;               // Active column
        $irefAct  = 0;                       // Active cell ref
        $cref     = 1;                       // Number of refs

        if (!isset($rwLast)) {
            $rwLast   = $rwFirst;       // Last  row in reference
        }
        if (!isset($colLast)) {
            $colLast  = $colFirst;      // Last  col in reference
        }

        // Swap last row/col for first row/col as necessary
        if ($rwFirst > $rwLast)
        {
            list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
        }

        if ($colFirst > $colLast)
        {
            list($colFirst, $colLast) = array($colLast, $colFirst);
        }

        $header   = pack("vv",         $record, $length);
        $data     = pack("CvvvvvvCC",  $pnn, $rwAct, $colAct,
                                       $irefAct, $cref,
                                       $rwFirst, $rwLast,
                                       $colFirst, $colLast);
        $this->_append($header.$data);
    }


    /**
    * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
    * references in a worksheet.
    *
    * Excel only stores references to external sheets that are used in formulas.
    * For simplicity we store references to all the sheets in the workbook
    * regardless of whether they are used or not. This reduces the overall
    * complexity and eliminates the need for a two way dialogue between the 
formula
    * parser the worksheet objects.
    *
    * @param integer $count The number of external sheet references in this 
worksheet
    */
    function _store_externcount($count)
    {
        $record   = 0x0016;          // Record identifier
        $length   = 0x0002;          // Number of bytes to follow

        $header   = pack("vv", $record, $length);
        $data     = pack("v",  $count);
        $this->_prepend($header.$data);
    }

    /**
    * Writes the Excel BIFF EXTERNSHEET record. These references are used by
    * formulas. A formula references a sheet name via an index. Since we store a
    * reference to all of the external worksheets the EXTERNSHEET index is the 
same
    * as the worksheet index.
    *
    * @param string $sheetname The name of a external worksheet
    */
    function _store_externsheet($sheetname)
    {
        $record    = 0x0017;         // Record identifier

        // References to the current sheet are encoded differently to 
references to
        // external sheets.
        //
        if ($this->name == $sheetname) {
            $sheetname = '';
            $length    = 0x02;  // The following 2 bytes
            $cch       = 1;     // The following byte
            $rgch      = 0x02;  // Self reference
        }
        else {
            $length    = 0x02 + strlen($sheetname);
            $cch       = strlen($sheetname);
            $rgch      = 0x03;  // Reference to a sheet in the current workbook
        }

        $header     = pack("vv",  $record, $length);
        $data       = pack("CC", $cch, $rgch);
        $this->_prepend($header.$data.$sheetname);
    }

    /**
    * Writes the Excel BIFF PANE record.
    * The panes can either be frozen or thawed (unfrozen).
    * Frozen panes are specified in terms of an integer number of rows and 
columns.
    * Thawed panes are specified in terms of Excel's units for rows and columns.
    *
    * @param array $panes This is the only parameter received and is composed 
of the following:
    *                     0 => Vertical split position,
    *                     1 => Horizontal split position
    *                     2 => Top row visible
    *                     3 => Leftmost column visible
    *                     4 => Active pane
    */
    function _store_panes($panes)
    {
        $y       = $panes[0];
        $x       = $panes[1];
        $rwTop   = $panes[2];
        $colLeft = $panes[3];
        if(count($panes) > 4) { // if Active pane was received
            $pnnAct = $panes[4];
        }
        else {
            $pnnAct = NULL;
        }
        $record  = 0x0041;       // Record identifier
        $length  = 0x000A;       // Number of bytes to follow

        // Code specific to frozen or thawed panes.
        if ($this->_frozen) {
            // Set default values for $rwTop and $colLeft
            if(!isset($rwTop)) {
                $rwTop   = $y;
            }
            if(!isset($colLeft)) {
                $colLeft = $x;
            }
        }
        else {
            // Set default values for $rwTop and $colLeft
            if(!isset($rwTop)) {
                $rwTop   = 0;
            }
            if(!isset($colLeft)) {
                $colLeft = 0;
            }

            // Convert Excel's row and column units to the internal units.
            // The default row height is 12.75
            // The default column width is 8.43
            // The following slope and intersection values were interpolated.
            //
            $y = 20*$y      + 255;
            $x = 113.879*$x + 390;
        }


        // Determine which pane should be active. There is also the undocumented
        // option to override this should it be necessary: may be removed later.
        //
        if (!isset($pnnAct))
        {
            if ($x != 0 and $y != 0)
                $pnnAct = 0; // Bottom right
            if ($x != 0 and $y == 0)
                $pnnAct = 1; // Top right
            if ($x == 0 and $y != 0)
                $pnnAct = 2; // Bottom left
            if ($x == 0 and $y == 0)
                $pnnAct = 3; // Top left
        }

        $this->_active_pane = $pnnAct; // Used in _store_selection

        $header     = pack("vv",    $record, $length);
        $data       = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
        $this->_append($header.$data);
    }

    /**
    * Store the page setup SETUP BIFF record.
    */
    function _store_setup()
    {
        $record       = 0x00A1;                  // Record identifier
        $length       = 0x0022;                  // Number of bytes to follow

        $iPaperSize   = $this->_paper_size;    // Paper size
        $iScale       = $this->_print_scale;   // Print scaling factor
        $iPageStart   = 0x01;                 // Starting page number
        $iFitWidth    = $this->_fit_width;    // Fit to number of pages wide
        $iFitHeight   = $this->_fit_height;   // Fit to number of pages high
        $grbit        = 0x00;                 // Option flags
        $iRes         = 0x0258;               // Print resolution
        $iVRes        = 0x0258;               // Vertical print resolution
        $numHdr       = $this->_margin_head;  // Header Margin
        $numFtr       = $this->_margin_foot;   // Footer Margin
        $iCopies      = 0x01;                 // Number of copies

        $fLeftToRight = 0x0;                     // Print over then down
        $fLandscape   = $this->_orientation;     // Page orientation
        $fNoPls       = 0x0;                     // Setup not read from printer
        $fNoColor     = 0x0;                     // Print black and white
        $fDraft       = 0x0;                     // Print draft quality
        $fNotes       = 0x0;                     // Print notes
        $fNoOrient    = 0x0;                     // Orientation not set
        $fUsePage     = 0x0;                     // Use custom starting page

        $grbit           = $fLeftToRight;
        $grbit          |= $fLandscape    << 1;
        $grbit          |= $fNoPls        << 2;
        $grbit          |= $fNoColor      << 3;
        $grbit          |= $fDraft        << 4;
        $grbit          |= $fNotes        << 5;
        $grbit          |= $fNoOrient     << 6;
        $grbit          |= $fUsePage      << 7;

        $numHdr = pack("d", $numHdr);
        $numFtr = pack("d", $numFtr);
        if ($this->_byte_order) // if it's Big Endian
        {
            $numHdr = strrev($numHdr);
            $numFtr = strrev($numFtr);
        }

        $header = pack("vv", $record, $length);
        $data1  = pack("vvvvvvvv", $iPaperSize,
                                   $iScale,
                                   $iPageStart,
                                   $iFitWidth,
                                   $iFitHeight,
                                   $grbit,
                                   $iRes,
                                   $iVRes);
        $data2  = $numHdr .$numFtr;
        $data3  = pack("v", $iCopies);
        $this->_prepend($header.$data1.$data2.$data3);
    }

    /**
    * Store the header caption BIFF record.
    */
    function store_header()
    {
        $record  = 0x0014;               // Record identifier

        $str     = $this->_header;        // header string
        $cch     = strlen($str);         // Length of header string
        $length  = 1 + $cch;             // Bytes to follow

        $header    = pack("vv",  $record, $length);
        $data      = pack("C",   $cch);

        $this->_append($header.$data.$str);
    }

    /**
    * Store the footer caption BIFF record.
    */
    function store_footer()
    {
        $record  = 0x0015;               // Record identifier

        $str     = $this->_footer;       // Footer string
        $cch     = strlen($str);         // Length of footer string
        $length  = 1 + $cch;             // Bytes to follow

        $header    = pack("vv",  $record, $length);
        $data      = pack("C",   $cch);

        $this->_append($header.$data.$str);
    }

    /**
    * Store the horizontal centering HCENTER BIFF record.
    */
    function store_hcenter()
    {
        $record   = 0x0083;              // Record identifier
        $length   = 0x0002;              // Bytes to follow

        $fHCenter = $this->_hcenter;      // Horizontal centering

        $header    = pack("vv",  $record, $length);
        $data      = pack("v",   $fHCenter);

        $this->_append($header.$data);
    }

    /**
    * Store the vertical centering VCENTER BIFF record.
    */
    function store_vcenter()
    {
        $record   = 0x0084;              // Record identifier
        $length   = 0x0002;              // Bytes to follow

        $fVCenter = $this->_vcenter;      // Horizontal centering

        $header    = pack("vv", $record, $length);
        $data      = pack("v", $fVCenter);
        $this->_append($header.$data);
    }

    /**
    * Store the LEFTMARGIN BIFF record.
    */
    function _store_margin_left()
    {
        $record  = 0x0026;                   // Record identifier
        $length  = 0x0008;                   // Bytes to follow

        $margin  = $this->_margin_left;       // Margin in inches

        $header    = pack("vv",  $record, $length);
        $data      = pack("d",   $margin);
        if ($this->_byte_order) // if it's Big Endian
        {
            $data = strrev($data);
        }

        $this->_append($header.$data);
    }

    /**
    * Store the RIGHTMARGIN BIFF record.
    */
    function _store_margin_right()
    {
        $record  = 0x0027;                   // Record identifier
        $length  = 0x0008;                   // Bytes to follow

        $margin  = $this->_margin_right;      // Margin in inches

        $header    = pack("vv",  $record, $length);
        $data      = pack("d",   $margin);
        if ($this->_byte_order) // if it's Big Endian
        {
            $data = strrev($data);
        }

        $this->_append($header.$data);
    }

    /**
    * Store the TOPMARGIN BIFF record.
    */
    function _store_margin_top()
    {
        $record  = 0x0028;                   // Record identifier
        $length  = 0x0008;                   // Bytes to follow

        $margin  = $this->_margin_top;        // Margin in inches

        $header    = pack("vv",  $record, $length);
        $data      = pack("d",   $margin);
        if ($this->_byte_order) // if it's Big Endian
        {
            $data = strrev($data);
        }

        $this->_append($header.$data);
    }

    /**
    * Store the BOTTOMMARGIN BIFF record.
    */
    function _store_margin_bottom()
    {
        $record  = 0x0029;                   // Record identifier
        $length  = 0x0008;                   // Bytes to follow

        $margin  = $this->_margin_bottom;     // Margin in inches

        $header    = pack("vv",  $record, $length);
        $data      = pack("d",   $margin);
        if ($this->_byte_order) // if it's Big Endian
        {
            $data = strrev($data);
        }

        $this->_append($header.$data);
    }

    /**
    * This is an Excel97/2000 method. It is required to perform more complicated
    * merging than the normal set_align('merge'). It merges the area given by
    * its arguments.
    *
    * @access public
    * @param integer $first_row First row of the area to merge
    * @param integer $first_col First column of the area to merge
    * @param integer $last_row  Last row of the area to merge
    * @param integer $last_col  Last column of the area to merge
    */
    function merge_cells($first_row, $first_col, $last_row, $last_col)
    {
        $record  = 0x00E5;                   // Record identifier
        $length  = 0x000A;                   // Bytes to follow
        $cref     = 1;                       // Number of refs

        // Swap last row/col for first row/col as necessary
        if ($first_row > $last_row) {
            list($first_row, $last_row) = array($last_row, $first_row);
        }

        if ($first_col > $last_col) {
            list($first_col, $last_col) = array($last_col, $first_col);
        }

        $header   = pack("vv",    $record, $length);
        $data     = pack("vvvvv", $cref, $first_row, $last_row,
                                  $first_col, $last_col);

        $this->_append($header.$data);
    }

    /**
    * Write the PRINTHEADERS BIFF record.
    */
    function _store_print_headers()
    {
        $record      = 0x002a;                   // Record identifier
        $length      = 0x0002;                   // Bytes to follow

        $fPrintRwCol = $this->_print_headers;     // Boolean flag

        $header      = pack("vv", $record, $length);
        $data        = pack("v", $fPrintRwCol);
        $this->_prepend($header.$data);
    }

    /**
    * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
    * GRIDSET record.
    */
    function _store_print_gridlines()
    {
        $record      = 0x002b;                    // Record identifier
        $length      = 0x0002;                    // Bytes to follow

        $fPrintGrid  = $this->_print_gridlines;    // Boolean flag

        $header      = pack("vv", $record, $length);
        $data        = pack("v", $fPrintGrid);
        $this->_prepend($header.$data);
    }

    /**
    * Write the GRIDSET BIFF record. Must be used in conjunction with the
    * PRINTGRIDLINES record.
    */
    function _store_gridset()
    {
        $record      = 0x0082;                        // Record identifier
        $length      = 0x0002;                        // Bytes to follow

        $fGridSet    = !($this->_print_gridlines);     // Boolean flag

        $header      = pack("vv",  $record, $length);
        $data        = pack("v",   $fGridSet);
        $this->_prepend($header.$data);
    }

    /**
    * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
    * with the SETUP record.
    */
    function _store_wsbool()
    {
        $record      = 0x0081;   // Record identifier
        $length      = 0x0002;   // Bytes to follow

        // The only option that is of interest is the flag for fit to page. So 
we
        // set all the options in one go.
        //
        if ($this->_fit_page) {
            $grbit = 0x05c1;
        }
        else {
            $grbit = 0x04c1;
        }

        $header      = pack("vv", $record, $length);
        $data        = pack("v",  $grbit);
        $this->_prepend($header.$data);
    }


    /**
    * Write the HORIZONTALPAGEBREAKS BIFF record.
    */
    function _store_hbreak()
    {
        // Return if the user hasn't specified pagebreaks
        if(empty($this->_hbreaks)) {
            return;
        }

        // Sort and filter array of page breaks
        $breaks = $this->_hbreaks;
        sort($breaks,SORT_NUMERIC);
        if($breaks[0] == 0) { // don't use first break if it's 0
            array_shift($breaks);
        }

        $record  = 0x001b;               // Record identifier
        $cbrk    = count($breaks);       // Number of page breaks
        $length  = ($cbrk + 1) * 2;      // Bytes to follow

        $header  = pack("vv", $record, $length);
        $data    = pack("v",  $cbrk);

        // Append each page break
        foreach($breaks as $break) {
            $data .= pack("v", $break);
        }

        $this->_prepend($header.$data);
    }


    /**
    * Write the VERTICALPAGEBREAKS BIFF record.
    */
    function _store_vbreak()
    {
        // Return if the user hasn't specified pagebreaks
        if(empty($this->_vbreaks)) {
            return;
        }

        // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
        // It is slightly higher in Excel 97/200, approx. 1026
        $breaks = array_slice($this->_vbreaks,0,1000);

        // Sort and filter array of page breaks
        sort($breaks,SORT_NUMERIC);
        if($breaks[0] == 0) { // don't use first break if it's 0
            array_shift($breaks);
        }

        $record  = 0x001a;               // Record identifier
        $cbrk    = count($breaks);       // Number of page breaks
        $length  = ($cbrk + 1) * 2;      // Bytes to follow

        $header  = pack("vv",  $record, $length);
        $data    = pack("v",   $cbrk);

        // Append each page break
        foreach ($breaks as $break) {
            $data .= pack("v", $break);
        }

        $this->_prepend($header.$data);
    }

    /**
    * Set the Biff PROTECT record to indicate that the worksheet is protected.
    */
    function _store_protect()
    {
        // Exit unless sheet protection has been specified
        if($this->_protect == 0) {
            return;
        }

        $record      = 0x0012;             // Record identifier
        $length      = 0x0002;             // Bytes to follow

        $fLock       = $this->_protect;    // Worksheet is protected

        $header      = pack("vv", $record, $length);
        $data        = pack("v",  $fLock);

        $this->_prepend($header.$data);
    }

    /**
    * Write the worksheet PASSWORD record.
    */
    function _store_password()
    {
        // Exit unless sheet protection and password have been specified
        if(($this->_protect == 0) or (!isset($this->_password))) {
            return;
        }

        $record      = 0x0013;               // Record identifier
        $length      = 0x0002;               // Bytes to follow

        $wPassword   = $this->_password;     // Encoded password

        $header      = pack("vv", $record, $length);
        $data        = pack("v",  $wPassword);

        $this->_prepend($header.$data);
    }

    /**
    * Insert a 24bit bitmap image in a worksheet. The main record required is
    * IMDATA but it must be proceeded by a OBJ record to define its position.
    *
    * @access public
    * @param integer $row     The row we are going to insert the bitmap into
    * @param integer $col     The column we are going to insert the bitmap into
    * @param string  $bitmap  The bitmap filename
    * @param integer $x       The horizontal position (offset) of the image 
inside the cell.
    * @param integer $y       The vertical position (offset) of the image 
inside the cell.
    * @param integer $scale_x The horizontal scale
    * @param integer $scale_y The vertical scale
    */
    function insert_bitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, 
$scale_y = 1)
    {
        list($width, $height, $size, $data) = $this->_process_bitmap($bitmap);

        // Scale the frame of the image.
        $width  *= $scale_x;
        $height *= $scale_y;

        // Calculate the vertices of the image and write the OBJ record
        $this->_position_image($col, $row, $x, $y, $width, $height);

        // Write the IMDATA record to store the bitmap data
        $record      = 0x007f;
        $length      = 8 + $size;
        $cf          = 0x09;
        $env         = 0x01;
        $lcb         = $size;

        $header      = pack("vvvvV", $record, $length, $cf, $env, $lcb);
        $this->_append($header.$data);
    }

    /**
    * Calculate the vertices that define the position of the image as required 
by
    * the OBJ record.
    *
    *         +------------+------------+
    *         |     A      |      B     |
    *   +-----+------------+------------+
    *   |     |(x1,y1)     |            |
    *   |  1  |(A1)._______|______      |
    *   |     |    |              |     |
    *   |     |    |              |     |
    *   +-----+----|    BITMAP    |-----+
    *   |     |    |              |     |
    *   |  2  |    |______________.     |
    *   |     |            |        (B2)|
    *   |     |            |     (x2,y2)|
    *   +---- +------------+------------+
    *
    * Example of a bitmap that covers some of the area from cell A1 to cell B2.
    *
    * Based on the width and height of the bitmap we need to calculate 8 vars:
    *     $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
    * The width and height of the cells are also variable and have to be taken 
into
    * account.
    * The values of $col_start and $row_start are passed in from the calling
    * function. The values of $col_end and $row_end are calculated by 
subtracting
    * the width and height of the bitmap from the width and height of the
    * underlying cells.
    * The vertices are expressed as a percentage of the underlying cell width as
    * follows (rhs values are in pixels):
    *
    *       x1 = X / W *1024
    *       y1 = Y / H *256
    *       x2 = (X-1) / W *1024
    *       y2 = (Y-1) / H *256
    *
    *       Where:  X is distance from the left side of the underlying cell
    *               Y is distance from the top of the underlying cell
    *               W is the width of the cell
    *               H is the height of the cell
    *
    * @note  the SDK incorrectly states that the height should be expressed as a
    *        percentage of 1024.
    * @param integer $col_start Col containing upper left corner of object
    * @param integer $row_start Row containing top left corner of object
    * @param integer $x1        Distance to left side of object
    * @param integer $y1        Distance to top of object
    * @param integer $width     Width of image frame
    * @param integer $height    Height of image frame
    */
    function _position_image($col_start, $row_start, $x1, $y1, $width, $height)
    {
        // Initialise end cell to the same as the start cell
        $col_end    = $col_start;  // Col containing lower right corner of 
object
        $row_end    = $row_start;  // Row containing bottom right corner of 
object

        // Zero the specified offset if greater than the cell dimensions
        if ($x1 >= $this->size_col($col_start))
        {
            $x1 = 0;
        }
        if ($y1 >= $this->size_row($row_start))
        {
            $y1 = 0;
        }

        $width      = $width  + $x1 -1;
        $height     = $height + $y1 -1;

        // Subtract the underlying cell widths to find the end cell of the image
        while ($width >= $this->size_col($col_end)) {
            $width -= $this->size_col($col_end);
            $col_end++;
        }

        // Subtract the underlying cell heights to find the end cell of the 
image
        while ($height >= $this->size_row($row_end)) {
            $height -= $this->size_row($row_end);
            $row_end++;
        }

        // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
        // with zero eight or width.
        //
        if ($this->size_col($col_start) == 0)
            return;
        if ($this->size_col($col_end)   == 0)
            return;
        if ($this->size_row($row_start) == 0)
            return;
        if ($this->size_row($row_end)   == 0)
            return;

        // Convert the pixel values to the percentage value expected by Excel
        $x1 = $x1     / $this->size_col($col_start)   * 1024;
        $y1 = $y1     / $this->size_row($row_start)   *  256;
        $x2 = $width  / $this->size_col($col_end)     * 1024; // Distance to 
right side of object
        $y2 = $height / $this->size_row($row_end)     *  256; // Distance to 
bottom of object

        $this->_store_obj_picture( $col_start, $x1,
                                  $row_start, $y1,
                                  $col_end, $x2,
                                  $row_end, $y2
                                );
    }

    /**
    * Convert the width of a cell from user's units to pixels. By interpolation
    * the relationship is: y = 7x +5. If the width hasn't been set by the user 
we
    * use the default value. If the col is hidden we use a value of zero.
    *
    * @param integer  $col The column
    * @return integer The width in pixels
    */
    function size_col($col)
    {
        // Look up the cell value to see if it has been changed
        if (isset($this->col_sizes[$col])) {
            if ($this->col_sizes[$col] == 0) {
                return(0);
            }
            else {
                return(floor(7 * $this->col_sizes[$col] + 5));
            }
        }
        else {
            return(64);
        }
    }

    /**
    * Convert the height of a cell from user's units to pixels. By interpolation
    * the relationship is: y = 4/3x. If the height hasn't been set by the user 
we
    * use the default value. If the row is hidden we use a value of zero. (Not
    * possible to hide row yet).
    *
    * @param integer $row The row
    * @return integer The width in pixels
    */
    function size_row($row)
    {
        // Look up the cell value to see if it has been changed
        if (isset($this->row_sizes[$row])) {
            if ($this->row_sizes[$row] == 0) {
                return(0);
            }
            else {
                return(floor(4/3 * $this->row_sizes[$row]));
            }
        }
        else {
            return(17);
        }
    }

    /**
    * Store the OBJ record that precedes an IMDATA record. This could be 
generalise
    * to support other Excel objects.
    *
    * @param integer $colL Column containing upper left corner of object
    * @param integer $dxL  Distance from left side of cell
    * @param integer $rwT  Row containing top left corner of object
    * @param integer $dyT  Distance from top of cell
    * @param integer $colR Column containing lower right corner of object
    * @param integer $dxR  Distance from right of cell
    * @param integer $rwB  Row containing bottom right corner of object
    * @param integer $dyB  Distance from bottom of cell
    */
    function _store_obj_picture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
    {
        $record      = 0x005d;   // Record identifier
        $length      = 0x003c;   // Bytes to follow

        $cObj        = 0x0001;   // Count of objects in file (set to 1)
        $OT          = 0x0008;   // Object type. 8 = Picture
        $id          = 0x0001;   // Object ID
        $grbit       = 0x0614;   // Option flags

        $cbMacro     = 0x0000;   // Length of FMLA structure
        $Reserved1   = 0x0000;   // Reserved
        $Reserved2   = 0x0000;   // Reserved

        $icvBack     = 0x09;     // Background colour
        $icvFore     = 0x09;     // Foreground colour
        $fls         = 0x00;     // Fill pattern
        $fAuto       = 0x00;     // Automatic fill
        $icv         = 0x08;     // Line colour
        $lns         = 0xff;     // Line style
        $lnw         = 0x01;     // Line weight
        $fAutoB      = 0x00;     // Automatic border
        $frs         = 0x0000;   // Frame style
        $cf          = 0x0009;   // Image format, 9 = bitmap
        $Reserved3   = 0x0000;   // Reserved
        $cbPictFmla  = 0x0000;   // Length of FMLA structure
        $Reserved4   = 0x0000;   // Reserved
        $grbit2      = 0x0001;   // Option flags
        $Reserved5   = 0x0000;   // Reserved


        $header      = pack("vv", $record, $length);
        $data        = pack("V", $cObj);
        $data       .= pack("v", $OT);
        $data       .= pack("v", $id);
        $data       .= pack("v", $grbit);
        $data       .= pack("v", $colL);
        $data       .= pack("v", $dxL);
        $data       .= pack("v", $rwT);
        $data       .= pack("v", $dyT);
        $data       .= pack("v", $colR);
        $data       .= pack("v", $dxR);
        $data       .= pack("v", $rwB);
        $data       .= pack("v", $dyB);
        $data       .= pack("v", $cbMacro);
        $data       .= pack("V", $Reserved1);
        $data       .= pack("v", $Reserved2);
        $data       .= pack("C", $icvBack);
        $data       .= pack("C", $icvFore);
        $data       .= pack("C", $fls);
        $data       .= pack("C", $fAuto);
        $data       .= pack("C", $icv);
        $data       .= pack("C", $lns);
        $data       .= pack("C", $lnw);
        $data       .= pack("C", $fAutoB);
        $data       .= pack("v", $frs);
        $data       .= pack("V", $cf);
        $data       .= pack("v", $Reserved3);
        $data       .= pack("v", $cbPictFmla);
        $data       .= pack("v", $Reserved4);
        $data       .= pack("v", $grbit2);
        $data       .= pack("V", $Reserved5);

        $this->_append($header.$data);
    }

    /**
    * Convert a 24 bit bitmap into the modified internal format used by Windows.
    * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
    * MSDN library.
    *
    * @param string $bitmap The bitmap to process
    * @return array Array with data and properties of the bitmap
    */
    function _process_bitmap($bitmap)
    {
        // Open file.
        $bmp_fd = fopen($bitmap,"rb");
        if (!$bmp_fd) {
            die("Couldn't import $bitmap");
        }

        // Slurp the file into a string.
        $data = fread($bmp_fd, filesize($bitmap));

        // Check that the file is big enough to be a bitmap.
        if (strlen($data) <= 0x36) {
            die("$bitmap doesn't contain enough data.\n");
        }

        // The first 2 bytes are used to identify the bitmap.
        $identity = unpack("A2", $data);
        if ($identity[''] != "BM") {
            die("$bitmap doesn't appear to be a valid bitmap image.\n");
        }

        // Remove bitmap data: ID.
        $data = substr($data, 2);

        // Read and remove the bitmap size. This is more reliable than reading
        // the data size at offset 0x22.
        //
        $size_array   = unpack("V", substr($data, 0, 4));
        $size   = $size_array[''];
        $data   = substr($data, 4);
        $size  -= 0x36; // Subtract size of bitmap header.
        $size  += 0x0C; // Add size of BIFF header.

        // Remove bitmap data: reserved, offset, header length.
        $data = substr($data, 12);

        // Read and remove the bitmap width and height. Verify the sizes.
        $width_and_height = unpack("V2", substr($data, 0, 8));
        $width  = $width_and_height[1];
        $height = $width_and_height[2];
        $data   = substr($data, 8);
        if ($width > 0xFFFF) {
            die("$bitmap: largest image width supported is 65k.\n");
        }
        if ($height > 0xFFFF) {
            die("$bitmap: largest image height supported is 65k.\n");
        }

        // Read and remove the bitmap planes and bpp data. Verify them.
        $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
        $data = substr($data, 4);
        if ($planes_and_bitcount[2] != 24) { // Bitcount
            die("$bitmap isn't a 24bit true color bitmap.\n");
        }
        if ($planes_and_bitcount[1] != 1) {
            die("$bitmap: only 1 plane supported in bitmap image.\n");
        }

        // Read and remove the bitmap compression. Verify compression.
        $compression = unpack("V", substr($data, 0, 4));
        $data = substr($data, 4);

        //$compression = 0;
        if ($compression[""] != 0) {
            die("$bitmap: compression not supported in bitmap image.\n");
        }

        // Remove bitmap data: data size, hres, vres, colours, imp. colours.
        $data = substr($data, 20);

        // Add the BITMAPCOREHEADER data
        $header  = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
        $data    = $header . $data;

        return (array($width, $height, $size, $data));
    }

    /**
    * Store the window zoom factor. This should be a reduced fraction but for
    * simplicity we will store all fractions with a numerator of 100.
    */
    function _store_zoom()
    {
        // If scale is 100 we don't need to write a record
        if ($this->_zoom == 100) {
            return;
        }

        $record      = 0x00A0;               // Record identifier
        $length      = 0x0004;               // Bytes to follow

        $header      = pack("vv", $record, $length);
        $data        = pack("vv", $this->_zoom, 100);
        $this->_append($header.$data);
    }
}
?>

====================================================
Index: thanks
Inmortalizing those who have contributed(*) to Spreadsheet_WriteExcel:
 Quentin Bennett
 Kenneth G. Chin
 Tomislav Goles


(*) According to my own personal definition of contribution.






reply via email to

[Prev in Thread] Current Thread [Next in Thread]