Spreadsheet_Excel_Writer
[ class tree: Spreadsheet_Excel_Writer ] [ index: Spreadsheet_Excel_Writer ] [ all elements ]

Source for file Workbook.php

Documentation is available at Workbook.php

  1. <?php
  2. /*
  3. *  Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
  4. *
  5. *  The majority of this is _NOT_ my code.  I simply ported it from the
  6. *  PERL Spreadsheet::WriteExcel module.
  7. *
  8. *  The author of the Spreadsheet::WriteExcel module is John McNamara 
  9. *  <jmcnamara@cpan.org>
  10. *
  11. *  I _DO_ maintain this code, and John McNamara has nothing to do with the
  12. *  porting of this code to PHP.  Any questions directly related to this
  13. *  class library should be directed to me.
  14. *
  15. *  License Information:
  16. *
  17. *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
  18. *    Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
  19. *
  20. *    This library is free software; you can redistribute it and/or
  21. *    modify it under the terms of the GNU Lesser General Public
  22. *    License as published by the Free Software Foundation; either
  23. *    version 2.1 of the License, or (at your option) any later version.
  24. *
  25. *    This library is distributed in the hope that it will be useful,
  26. *    but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  28. *    Lesser General Public License for more details.
  29. *
  30. *    You should have received a copy of the GNU Lesser General Public
  31. *    License along with this library; if not, write to the Free Software
  32. *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  33. */
  34.  
  35. require_once('Spreadsheet/Excel/Writer/Format.php');
  36. require_once('Spreadsheet/Excel/Writer/BIFFwriter.php');
  37. require_once('Spreadsheet/Excel/Writer/Worksheet.php');
  38. require_once('Spreadsheet/Excel/Writer/Parser.php');
  39. require_once('OLE/PPS/Root.php');
  40. require_once('OLE/PPS/File.php');
  41.  
  42. /**
  43. * Class for generating Excel Spreadsheets
  44. *
  45. @author   Xavier Noguer <xnoguer@rezebra.com>
  46. @category FileFormats
  47. @package  Spreadsheet_Excel_Writer
  48. */
  49.  
  50. {
  51.     /**
  52.     * Filename for the Workbook
  53.     * @var string 
  54.     */
  55.     var $_filename;
  56.  
  57.     /**
  58.     * Formula parser
  59.     * @var object Parser 
  60.     */
  61.     var $_parser;
  62.  
  63.     /**
  64.     * Flag for 1904 date system (0 => base date is 1900, 1 => base date is 1904)
  65.     * @var integer 
  66.     */
  67.     var $_1904;
  68.  
  69.     /**
  70.     * The active worksheet of the workbook (0 indexed)
  71.     * @var integer 
  72.     */
  73.     var $_activesheet;
  74.  
  75.     /**
  76.     * 1st displayed worksheet in the workbook (0 indexed)
  77.     * @var integer 
  78.     */
  79.     var $_firstsheet;
  80.  
  81.     /**
  82.     * Number of workbook tabs selected
  83.     * @var integer 
  84.     */
  85.     var $_selected;
  86.  
  87.     /**
  88.     * Index for creating adding new formats to the workbook
  89.     * @var integer 
  90.     */
  91.     var $_xf_index;
  92.  
  93.     /**
  94.     * Flag for preventing close from being called twice.
  95.     * @var integer 
  96.     * @see close()
  97.     */
  98.     var $_fileclosed;
  99.  
  100.     /**
  101.     * The BIFF file size for the workbook.
  102.     * @var integer 
  103.     * @see _calcSheetOffsets()
  104.     */
  105.     var $_biffsize;
  106.  
  107.     /**
  108.     * The default sheetname for all sheets created.
  109.     * @var string 
  110.     */
  111.     var $_sheetname;
  112.  
  113.     /**
  114.     * The default XF format.
  115.     * @var object Format 
  116.     */
  117.     var $_tmp_format;
  118.  
  119.     /**
  120.     * Array containing references to all of this workbook's worksheets
  121.     * @var array 
  122.     */
  123.     var $_worksheets;
  124.  
  125.     /**
  126.     * Array of sheetnames for creating the EXTERNSHEET records
  127.     * @var array 
  128.     */
  129.     var $_sheetnames;
  130.  
  131.     /**
  132.     * Array containing references to all of this workbook's formats
  133.     * @var array 
  134.     */
  135.     var $_formats;
  136.  
  137.     /**
  138.     * Array containing the colour palette
  139.     * @var array 
  140.     */
  141.     var $_palette;
  142.  
  143.     /**
  144.     * The default format for URLs.
  145.     * @var object Format 
  146.     */
  147.     var $_url_format;
  148.  
  149.     /**
  150.     * The codepage indicates the text encoding used for strings
  151.     * @var integer 
  152.     */
  153.     var $_codepage;
  154.  
  155.     /**
  156.     * The country code used for localization
  157.     * @var integer 
  158.     */
  159.     var $_country_code;
  160.  
  161.     /**
  162.     * The temporary dir for storing the OLE file
  163.     * @var string 
  164.     */
  165.     var $_tmp_dir;
  166.  
  167.     /**
  168.     * number of bytes for sizeinfo of strings
  169.     * @var integer 
  170.     */
  171.     var $_string_sizeinfo_size;
  172.  
  173.     /**
  174.     * Class constructor
  175.     *
  176.     * @param string filename for storing the workbook. "-" for writing to stdout.
  177.     * @access public
  178.     */
  179.     function Spreadsheet_Excel_Writer_Workbook($filename)
  180.     {
  181.         // It needs to call its parent's constructor explicitly
  182.         $this->Spreadsheet_Excel_Writer_BIFFwriter();
  183.     
  184.         $this->_filename         $filename;
  185.         $this->_parser           =new Spreadsheet_Excel_Writer_Parser($this->_byte_order$this->_BIFF_version);
  186.         $this->_1904             = 0;
  187.         $this->_activesheet      = 0;
  188.         $this->_firstsheet       = 0;
  189.         $this->_selected         = 0;
  190.         $this->_xf_index         = 16; // 15 style XF's and 1 cell XF.
  191.         $this->_fileclosed       = 0;
  192.         $this->_biffsize         = 0;
  193.         $this->_sheetname        "Sheet";
  194.         $this->_tmp_format       =new Spreadsheet_Excel_Writer_Format($this->_BIFF_version);
  195.         $this->_worksheets       = array();
  196.         $this->_sheetnames       = array();
  197.         $this->_formats          = array();
  198.         $this->_palette          = array();
  199.         $this->_codepage         = 0x04E4; // FIXME: should change for BIFF8
  200.         $this->_country_code     = -1;
  201.         $this->_string_sizeinfo  = 3;
  202.  
  203.         // Add the default format for hyperlinks
  204.         $this->_url_format =$this->addFormat(array('color' => 'blue''underline' => 1));
  205.         $this->_str_total       = 0;
  206.         $this->_str_unique      = 0;
  207.         $this->_str_table       = array();
  208.         $this->_setPaletteXl97();
  209.         $this->_tmp_dir         '';
  210.     }
  211.     
  212.     /**
  213.     * Calls finalization methods.
  214.     * This method should always be the last one to be called on every workbook
  215.     *
  216.     * @access public
  217.     * @return mixed true on success. PEAR_Error on failure
  218.     */
  219.     function close()
  220.     {
  221.         if ($this->_fileclosed// Prevent close() from being called twice.
  222.             return true;
  223.         }
  224.         $res $this->_storeWorkbook();
  225.         if ($this->isError($res)) {
  226.             return $this->raiseError($res->getMessage());
  227.         }
  228.         $this->_fileclosed = 1;
  229.         return true;
  230.     }
  231.  
  232.     /**
  233.     * An accessor for the _worksheets[] array
  234.     * Returns an array of the worksheet objects in a workbook
  235.     * It actually calls to worksheets()
  236.     *
  237.     * @access public
  238.     * @see worksheets()
  239.     * @return array 
  240.     */
  241.     function sheets()
  242.     {
  243.         return $this->worksheets();
  244.     }
  245.     
  246.     /**
  247.     * An accessor for the _worksheets[] array.
  248.     * Returns an array of the worksheet objects in a workbook
  249.     *
  250.     * @access public
  251.     * @return array 
  252.     */
  253.     function worksheets()
  254.     {
  255.         return $this->_worksheets;
  256.     }
  257.  
  258.     /**
  259.     * Sets the BIFF version.
  260.     * This method exists just to access experimental functionality
  261.     * from BIFF8. It will be deprecated !
  262.     * Only possible value is 8 (Excel 97/2000).
  263.     * For any other value it fails silently.
  264.     *
  265.     * @access public
  266.     * @param integer $version The BIFF version
  267.     */
  268.     function setVersion($version)
  269.     {
  270.         if ($version == 8// only accept version 8
  271.             $version = 0x0600;
  272.             $this->_BIFF_version $version;
  273.             // change BIFFwriter limit for CONTINUE records
  274.             $this->_limit = 8228;
  275.             $this->_tmp_format->_BIFF_version = $version;
  276.             $this->_url_format->_BIFF_version = $version;
  277.             $this->_parser->_BIFF_version = $version;
  278.             $total_worksheets count($this->_worksheets);
  279.             // change version for all worksheets too
  280.             for ($i = 0; $i $total_worksheets$i++{
  281.                 $this->_worksheets[$i]->_BIFF_version = $version;
  282.             }
  283.             $total_formats count($this->_formats);
  284.             // change version for all formats too
  285.             for ($i = 0; $i $total_formats$i++{
  286.                 $this->_formats[$i]->_BIFF_version = $version;
  287.             }
  288.         }
  289.     }
  290.  
  291.     /**
  292.     * Set the country identifier for the workbook
  293.     *
  294.     * @access public
  295.     * @param integer $code Is the international calling country code for the
  296.     *                       chosen country.
  297.     */
  298.     function setCountry($code)
  299.     {
  300.         $this->_country_code $code;
  301.     }
  302.  
  303.     /**
  304.     * Add a new worksheet to the Excel workbook.
  305.     * If no name is given the name of the worksheet will be Sheeti$i, with
  306.     * $i in [1..].
  307.     *
  308.     * @access public
  309.     * @param string $name the optional name of the worksheet
  310.     * @return mixed reference to a worksheet object on success, PEAR_Error
  311.     *                on failure
  312.     */
  313.     function &addWorksheet($name '')
  314.     {
  315.         $index     count($this->_worksheets);
  316.         $sheetname $this->_sheetname;
  317.     
  318.         if ($name == ''{
  319.             $name $sheetname.($index+1)
  320.         }
  321.     
  322.         // Check that sheetname is <= 31 chars (Excel limit).
  323.         if (strlen($name> 31{
  324.             return $this->raiseError("Sheetname $name must be <= 31 chars");
  325.         }
  326.     
  327.         // Check that the worksheet name doesn't already exist: a fatal Excel error.
  328.         $total_worksheets count($this->_worksheets);
  329.         for ($i=0; $i $total_worksheets$i++)
  330.         {
  331.             if ($name == $this->_worksheets[$i]->getName()) {
  332.                 return $this->raiseError("Worksheet '$name' already exists");
  333.             }
  334.         }
  335.     
  336.         $worksheet = new Spreadsheet_Excel_Writer_Worksheet($this->_BIFF_version,
  337.                                    $name$index,
  338.                                    $this->_activesheet$this->_firstsheet,
  339.                                    $this->_str_total$this->_str_unique,
  340.                                    $this->_str_table$this->_url_format,
  341.                                    $this->_parser);
  342.  
  343.         $this->_worksheets[$index&$worksheet;    // Store ref for iterator
  344.         $this->_sheetnames[$index$name;          // Store EXTERNSHEET names
  345.         $this->_parser->setExtSheet($name$index);  // Register worksheet name with parser
  346.         return $worksheet;
  347.     }
  348.     
  349.     /**
  350.     * Add a new format to the Excel workbook.
  351.     * Also, pass any properties to the Format constructor.
  352.     *
  353.     * @access public
  354.     * @param array $properties array with properties for initializing the format.
  355.     * @return &Spreadsheet_Excel_Writer_Format reference to an Excel Format
  356.     */
  357.     function &addFormat($properties = array())
  358.     {
  359.         $format = new Spreadsheet_Excel_Writer_Format($this->_BIFF_version$this->_xf_index,$properties);
  360.         $this->_xf_index += 1;
  361.         $this->_formats[&$format;
  362.         return $format;
  363.     }
  364.     
  365.     /**
  366.      * Create new validator.
  367.      *
  368.      * @access public
  369.      * @return &Spreadsheet_Excel_Writer_Validator reference to a Validator
  370.      */
  371.     function &addValidator()
  372.     {
  373.         include_once('Spreadsheet/Excel/Writer/Validator.php');
  374.         /* FIXME: check for successful inclusion*/
  375.         $valid = new Spreadsheet_Excel_Writer_Validator($this->_parser);
  376.         return $valid;
  377.     }
  378.  
  379.     /**
  380.     * Change the RGB components of the elements in the colour palette.
  381.     *
  382.     * @access public
  383.     * @param integer $index colour index
  384.     * @param integer $red   red RGB value [0-255]
  385.     * @param integer $green green RGB value [0-255]
  386.     * @param integer $blue  blue RGB value [0-255]
  387.     * @return integer The palette index for the custom color
  388.     */
  389.     function setCustomColor($index,$red,$green,$blue)
  390.     {
  391.         // Match a HTML #xxyyzz style parameter
  392.         /*if (defined $_[1] and $_[1] =~ /^#(\w\w)(\w\w)(\w\w)/ ) {
  393.             @_ = ($_[0], hex $1, hex $2, hex $3);
  394.         }*/
  395.     
  396.         // Check that the colour index is the right range
  397.         if ($index < 8 or $index > 64{
  398.             // TODO: assign real error codes
  399.             return $this->raiseError("Color index $index outside range: 8 <= index <= 64");
  400.         }
  401.     
  402.         // Check that the colour components are in the right range
  403.         if ( ($red   < 0 or $red   > 255or
  404.              ($green < 0 or $green > 255or
  405.              ($blue  < 0 or $blue  > 255) )  
  406.         {
  407.             return $this->raiseError("Color component outside range: 0 <= color <= 255");
  408.         }
  409.     
  410.         $index -= 8; // Adjust colour index (wingless dragonfly)
  411.         
  412.         // Set the RGB value
  413.         $this->_palette[$index= array($red$green$blue0);
  414.         return($index + 8);
  415.     }
  416.     
  417.     /**
  418.     * Sets the colour palette to the Excel 97+ default.
  419.     *
  420.     * @access private
  421.     */
  422.     function _setPaletteXl97()
  423.     {
  424.         $this->_palette = array(
  425.                            array(0x000x000x000x00),   // 8
  426.                            array(0xff0xff0xff0x00),   // 9
  427.                            array(0xff0x000x000x00),   // 10
  428.                            array(0x000xff0x000x00),   // 11
  429.                            array(0x000x000xff0x00),   // 12
  430.                            array(0xff0xff0x000x00),   // 13
  431.                            array(0xff0x000xff0x00),   // 14
  432.                            array(0x000xff0xff0x00),   // 15
  433.                            array(0x800x000x000x00),   // 16
  434.                            array(0x000x800x000x00),   // 17
  435.                            array(0x000x000x800x00),   // 18
  436.                            array(0x800x800x000x00),   // 19
  437.                            array(0x800x000x800x00),   // 20
  438.                            array(0x000x800x800x00),   // 21
  439.                            array(0xc00xc00xc00x00),   // 22
  440.                            array(0x800x800x800x00),   // 23
  441.                            array(0x990x990xff0x00),   // 24
  442.                            array(0x990x330x660x00),   // 25
  443.                            array(0xff0xff0xcc0x00),   // 26
  444.                            array(0xcc0xff0xff0x00),   // 27
  445.                            array(0x660x000x660x00),   // 28
  446.                            array(0xff0x800x800x00),   // 29
  447.                            array(0x000x660xcc0x00),   // 30
  448.                            array(0xcc0xcc0xff0x00),   // 31
  449.                            array(0x000x000x800x00),   // 32
  450.                            array(0xff0x000xff0x00),   // 33
  451.                            array(0xff0xff0x000x00),   // 34
  452.                            array(0x000xff0xff0x00),   // 35
  453.                            array(0x800x000x800x00),   // 36
  454.                            array(0x800x000x000x00),   // 37
  455.                            array(0x000x800x800x00),   // 38
  456.                            array(0x000x000xff0x00),   // 39
  457.                            array(0x000xcc0xff0x00),   // 40
  458.                            array(0xcc0xff0xff0x00),   // 41
  459.                            array(0xcc0xff0xcc0x00),   // 42
  460.                            array(0xff0xff0x990x00),   // 43
  461.                            array(0x990xcc0xff0x00),   // 44
  462.                            array(0xff0x990xcc0x00),   // 45
  463.                            array(0xcc0x990xff0x00),   // 46
  464.                            array(0xff0xcc0x990x00),   // 47
  465.                            array(0x330x660xff0x00),   // 48
  466.                            array(0x330xcc0xcc0x00),   // 49
  467.                            array(0x990xcc0x000x00),   // 50
  468.                            array(0xff0xcc0x000x00),   // 51
  469.                            array(0xff0x990x000x00),   // 52
  470.                            array(0xff0x660x000x00),   // 53
  471.                            array(0x660x660x990x00),   // 54
  472.                            array(0x960x960x960x00),   // 55
  473.                            array(0x000x330x660x00),   // 56
  474.                            array(0x330x990x660x00),   // 57
  475.                            array(0x000x330x000x00),   // 58
  476.                            array(0x330x330x000x00),   // 59
  477.                            array(0x990x330x000x00),   // 60
  478.                            array(0x990x330x660x00),   // 61
  479.                            array(0x330x330x990x00),   // 62
  480.                            array(0x330x330x330x00),   // 63
  481.                          );
  482.     }
  483.     
  484.     /**
  485.     * Assemble worksheets into a workbook and send the BIFF data to an OLE
  486.     * storage.
  487.     *
  488.     * @access private
  489.     * @return mixed true on success. PEAR_Error on failure
  490.     */
  491.     function _storeWorkbook()
  492.     {
  493.         // Ensure that at least one worksheet has been selected.
  494.         if ($this->_activesheet == 0{
  495.             $this->_worksheets[0]->selected = 1;
  496.         }
  497.     
  498.         // Calculate the number of selected worksheet tabs and call the finalization
  499.         // methods for each worksheet
  500.         $total_worksheets count($this->_worksheets);
  501.         for ($i=0; $i $total_worksheets$i++{
  502.             if ($this->_worksheets[$i]->selected{
  503.                 $this->_selected++;
  504.             }
  505.             $this->_worksheets[$i]->close($this->_sheetnames);
  506.         }
  507.     
  508.         // Add Workbook globals
  509.         $this->_storeBof(0x0005);
  510.         $this->_storeCodepage();
  511.         if ($this->_BIFF_version == 0x0600{
  512.             $this->_storeWindow1();
  513.         }
  514.         if ($this->_BIFF_version == 0x0500{
  515.             $this->_storeExterns();    // For print area and repeat rows
  516.         }
  517.         $this->_storeNames();      // For print area and repeat rows
  518.         if ($this->_BIFF_version == 0x0500{
  519.             $this->_storeWindow1();
  520.         }
  521.         $this->_storeDatemode();
  522.         $this->_storeAllFonts();
  523.         $this->_storeAllNumFormats();
  524.         $this->_storeAllXfs();
  525.         $this->_storeAllStyles();
  526.         $this->_storePalette();
  527.         $this->_calcSheetOffsets();
  528.     
  529.         // Add BOUNDSHEET records
  530.         for ($i=0; $i $total_worksheets$i++{
  531.             $this->_storeBoundsheet($this->_worksheets[$i]->name,$this->_worksheets[$i]->offset);
  532.         }
  533.  
  534.         if ($this->_country_code != -1{
  535.             $this->_storeCountry();
  536.         }
  537.  
  538.         if ($this->_BIFF_version == 0x0600{
  539.             //$this->_storeSupbookInternal();
  540.             /* TODO: store external SUPBOOK records and XCT and CRN records 
  541.             in case of external references for BIFF8 */
  542.             //$this->_storeExternsheetBiff8();
  543.             $this->_storeSharedStringsTable();
  544.         }
  545.  
  546.         // End Workbook globals
  547.         $this->_storeEof();
  548.     
  549.         // Store the workbook in an OLE container
  550.         $res $this->_storeOLEFile();
  551.         if ($this->isError($res)) {
  552.             return $this->raiseError($res->getMessage());
  553.         }
  554.         return true;
  555.     }
  556.     
  557.     /**
  558.     * Sets the temp dir used for storing the OLE file
  559.     *
  560.     * @access public
  561.     * @param string $dir The dir to be used as temp dir
  562.     * @return true if given dir is valid, false otherwise
  563.     */
  564.     function setTempDir($dir)
  565.     {
  566.         if (is_dir($dir)) {
  567.             $this->_tmp_dir $dir;
  568.             return true;
  569.         }
  570.         return false;
  571.     }
  572.  
  573.     /**
  574.     * Store the workbook in an OLE container
  575.     *
  576.     * @access private
  577.     * @return mixed true on success. PEAR_Error on failure
  578.     */
  579.     function _storeOLEFile()
  580.     {
  581.         $OLE = new OLE_PPS_File(OLE::Asc2Ucs('Book'));
  582.         if ($this->_tmp_dir != ''{
  583.             $OLE->setTempDir($this->_tmp_dir);
  584.         }
  585.         $res $OLE->init();
  586.         if ($this->isError($res)) {
  587.             return $this->raiseError("OLE Error: ".$res->getMessage());
  588.         }
  589.         $OLE->append($this->_data);
  590.         $total_worksheets count($this->_worksheets);
  591.         for ($i = 0; $i $total_worksheets$i++)
  592.         {
  593.             while ($tmp $this->_worksheets[$i]->getData()) {
  594.                 $OLE->append($tmp);
  595.             }
  596.         }
  597.         $root = new OLE_PPS_Root(time()time()array($OLE));
  598.         if ($this->_tmp_dir != ''{
  599.             $root->setTempDir($this->_tmp_dir);
  600.         }
  601.         $res $root->save($this->_filename);
  602.         if ($this->isError($res)) {
  603.             return $this->raiseError("OLE Error: ".$res->getMessage());
  604.         }
  605.         return true;
  606.     }
  607.  
  608.     /**
  609.     * Calculate offsets for Worksheet BOF records.
  610.     *
  611.     * @access private
  612.     */
  613.     function _calcSheetOffsets()
  614.     {
  615.         if ($this->_BIFF_version == 0x0600{
  616.             $boundsheet_length = 12;  // fixed length for a BOUNDSHEET record
  617.         }
  618.         else {
  619.             $boundsheet_length = 11;
  620.         }
  621.         $EOF               = 4;
  622.         $offset            $this->_datasize;
  623.  
  624.         if ($this->_BIFF_version == 0x0600{
  625.             // add the length of the SST
  626.             /* TODO: check this works for a lot of strings (> 8224 bytes) */
  627.             $offset += $this->_calculateSharedStringsSizes();
  628.             if ($this->_country_code != -1{
  629.                 $offset += 8; // adding COUNTRY record
  630.             }
  631.             // add the lenght of SUPBOOK, EXTERNSHEET and NAME records
  632.             //$offset += 8; // FIXME: calculate real value when storing the records
  633.         }
  634.         $total_worksheets count($this->_worksheets);
  635.         // add the length of the BOUNDSHEET records 
  636.         for ($i=0; $i $total_worksheets$i++{
  637.             $offset += $boundsheet_length strlen($this->_worksheets[$i]->name);
  638.         }
  639.         $offset += $EOF;
  640.  
  641.         for ($i=0; $i $total_worksheets$i++{
  642.             $this->_worksheets[$i]->offset = $offset;
  643.             $offset += $this->_worksheets[$i]->_datasize;
  644.         }
  645.         $this->_biffsize $offset;
  646.     }
  647.     
  648.     /**
  649.     * Store the Excel FONT records.
  650.     *
  651.     * @access private
  652.     */
  653.     function _storeAllFonts()
  654.     {
  655.         // tmp_format is added by the constructor. We use this to write the default XF's
  656.         $format $this->_tmp_format;
  657.         $font   $format->getFont();
  658.     
  659.         // Note: Fonts are 0-indexed. According to the SDK there is no index 4,
  660.         // so the following fonts are 0, 1, 2, 3, 5
  661.         //
  662.         for ($i=1; $i <= 5; $i++){
  663.             $this->_append($font);
  664.         }
  665.     
  666.         // Iterate through the XF objects and write a FONT record if it isn't the
  667.         // same as the default FONT and if it hasn't already been used.
  668.         //
  669.         $fonts = array();
  670.         $index = 6;                  // The first user defined FONT
  671.     
  672.         $key $format->getFontKey()// The default font from _tmp_format
  673.         $fonts[$key= 0;             // Index of the default font
  674.  
  675.         $total_formats count($this->_formats);
  676.         for ($i=0; $i $total_formats$i++)
  677.         {
  678.             $key $this->_formats[$i]->getFontKey();
  679.             if (isset($fonts[$key])) {
  680.                 // FONT has already been used
  681.                 $this->_formats[$i]->font_index = $fonts[$key];
  682.             }
  683.             else {
  684.                 // Add a new FONT record
  685.                 $fonts[$key]        $index;
  686.                 $this->_formats[$i]->font_index = $index;
  687.                 $index++;
  688.                 $font $this->_formats[$i]->getFont();
  689.                 $this->_append($font);
  690.             }
  691.         }
  692.     }
  693.     
  694.     /**
  695.     * Store user defined numerical formats i.e. FORMAT records
  696.     *
  697.     * @access private
  698.     */
  699.     function _storeAllNumFormats()
  700.     {
  701.         // Leaning num_format syndrome
  702.         $hash_num_formats = array();
  703.         $num_formats      = array();
  704.         $index = 164;
  705.     
  706.         // Iterate through the XF objects and write a FORMAT record if it isn't a
  707.         // built-in format type and if the FORMAT string hasn't already been used.
  708.         $total_formats count($this->_formats);
  709.         for ($i=0; $i $total_formats$i++)
  710.         {
  711.             $num_format $this->_formats[$i]->_num_format;
  712.     
  713.             // Check if $num_format is an index to a built-in format.
  714.             // Also check for a string of zeros, which is a valid format string
  715.             // but would evaluate to zero.
  716.             //
  717.             if (!preg_match("/^0+\d/",$num_format))
  718.             {
  719.                 if (preg_match("/^\d+$/",$num_format)) // built-in format
  720.                     continue;
  721.                 }
  722.             }
  723.     
  724.             if (isset($hash_num_formats[$num_format])) {
  725.                 // FORMAT has already been used
  726.                 $this->_formats[$i]->_num_format = $hash_num_formats[$num_format];
  727.             }
  728.             else{
  729.                 // Add a new FORMAT
  730.                 $hash_num_formats[$num_format]  $index;
  731.                 $this->_formats[$i]->_num_format = $index;
  732.                 array_push($num_formats,$num_format);
  733.                 $index++;
  734.             }
  735.         }
  736.     
  737.         // Write the new FORMAT records starting from 0xA4
  738.         $index = 164;
  739.         foreach ($num_formats as $num_format{
  740.             $this->_storeNumFormat($num_format,$index);
  741.             $index++;
  742.         }
  743.     }
  744.     
  745.     /**
  746.     * Write all XF records.
  747.     *
  748.     * @access private
  749.     */
  750.     function _storeAllXfs()
  751.     {
  752.         // _tmp_format is added by the constructor. We use this to write the default XF's
  753.         // The default font index is 0
  754.         //
  755.         $format $this->_tmp_format;
  756.         for ($i=0; $i <= 14; $i++{
  757.             $xf $format->getXf('style')// Style XF
  758.             $this->_append($xf);
  759.         }
  760.     
  761.         $xf $format->getXf('cell');      // Cell XF
  762.         $this->_append($xf);
  763.     
  764.         // User defined XFs
  765.         $total_formats count($this->_formats);
  766.         for ($i=0; $i $total_formats$i++{
  767.             $xf $this->_formats[$i]->getXf('cell');
  768.             $this->_append($xf);
  769.         }
  770.     }
  771.     
  772.     /**
  773.     * Write all STYLE records.
  774.     *
  775.     * @access private
  776.     */
  777.     function _storeAllStyles()
  778.     {
  779.         $this->_storeStyle();
  780.     }
  781.     
  782.     /**
  783.     * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
  784.     * the NAME records.
  785.     *
  786.     * @access private
  787.     */
  788.     function _storeExterns()
  789.     {
  790.         // Create EXTERNCOUNT with number of worksheets
  791.         $this->_storeExterncount(count($this->_worksheets));
  792.     
  793.         // Create EXTERNSHEET for each worksheet
  794.         foreach ($this->_sheetnames as $sheetname{
  795.             $this->_storeExternsheet($sheetname);
  796.         }
  797.     }
  798.     
  799.     /**
  800.     * Write the NAME record to define the print area and the repeat rows and cols.
  801.     *
  802.     * @access private
  803.     */
  804.     function _storeNames()
  805.     {
  806.         // Create the print area NAME records
  807.         $total_worksheets count($this->_worksheets);
  808.         for ($i = 0; $i $total_worksheets$i++{
  809.             // Write a Name record if the print area has been defined
  810.             if (isset($this->_worksheets[$i]->print_rowmin))
  811.             {
  812.                 $this->_storeNameShort(
  813.                     $this->_worksheets[$i]->index,
  814.                     0x06// NAME type
  815.                     $this->_worksheets[$i]->print_rowmin,
  816.                     $this->_worksheets[$i]->print_rowmax,
  817.                     $this->_worksheets[$i]->print_colmin,
  818.                     $this->_worksheets[$i]->print_colmax
  819.                     );
  820.             }
  821.         }
  822.     
  823.         // Create the print title NAME records
  824.         $total_worksheets count($this->_worksheets);
  825.         for ($i = 0; $i $total_worksheets$i++{
  826.             $rowmin $this->_worksheets[$i]->title_rowmin;
  827.             $rowmax $this->_worksheets[$i]->title_rowmax;
  828.             $colmin $this->_worksheets[$i]->title_colmin;
  829.             $colmax $this->_worksheets[$i]->title_colmax;
  830.     
  831.             // Determine if row + col, row, col or nothing has been defined
  832.             // and write the appropriate record
  833.             //
  834.             if (isset($rowminand isset($colmin)) {
  835.                 // Row and column titles have been defined.
  836.                 // Row title has been defined.
  837.                 $this->_storeNameLong(
  838.                     $this->_worksheets[$i]->index,
  839.                     0x07// NAME type
  840.                     $rowmin,
  841.                     $rowmax,
  842.                     $colmin,
  843.                     $colmax
  844.                     );
  845.             }
  846.             elseif (isset($rowmin)) {
  847.                 // Row title has been defined.
  848.                 $this->_storeNameShort(
  849.                     $this->_worksheets[$i]->index,
  850.                     0x07// NAME type
  851.                     $rowmin,
  852.                     $rowmax,
  853.                     0x00,
  854.                     0xff
  855.                     );
  856.             }
  857.             elseif (isset($colmin)) {
  858.                 // Column title has been defined.
  859.                 $this->_storeNameShort(
  860.                     $this->_worksheets[$i]->index,
  861.                     0x07// NAME type
  862.                     0x0000,
  863.                     0x3fff,
  864.                     $colmin,
  865.                     $colmax
  866.                     );
  867.             }
  868.             else {
  869.                 // Print title hasn't been defined.
  870.             }
  871.         }
  872.     }
  873.     
  874.     
  875.     
  876.     
  877.     /******************************************************************************
  878.     *
  879.     * BIFF RECORDS
  880.     *
  881.     */
  882.     
  883.     /**
  884.     * Stores the CODEPAGE biff record.
  885.     *
  886.     * @access private
  887.     */
  888.     function _storeCodepage()
  889.     {
  890.         $record          = 0x0042;             // Record identifier
  891.         $length          = 0x0002;             // Number of bytes to follow
  892.         $cv              $this->_codepage;   // The code page
  893.  
  894.         $header          pack('vv'$record$length);
  895.         $data            pack('v',  $cv);
  896.  
  897.         $this->_append($header.$data);
  898.     }
  899.  
  900.     /**
  901.     * Write Excel BIFF WINDOW1 record.
  902.     *
  903.     * @access private
  904.     */
  905.     function _storeWindow1()
  906.     {
  907.         $record    = 0x003D;                 // Record identifier
  908.         $length    = 0x0012;                 // Number of bytes to follow
  909.     
  910.         $xWn       = 0x0000;                 // Horizontal position of window
  911.         $yWn       = 0x0000;                 // Vertical position of window
  912.         $dxWn      = 0x25BC;                 // Width of window
  913.         $dyWn      = 0x1572;                 // Height of window
  914.     
  915.         $grbit     = 0x0038;                 // Option flags
  916.         $ctabsel   $this->_selected;       // Number of workbook tabs selected
  917.         $wTabRatio = 0x0258;                 // Tab to scrollbar ratio
  918.     
  919.         $itabFirst $this->_firstsheet;     // 1st displayed worksheet
  920.         $itabCur   $this->_activesheet;    // Active worksheet
  921.     
  922.         $header    pack("vv",        $record$length);
  923.         $data      pack("vvvvvvvvv"$xWn$yWn$dxWn$dyWn,
  924.                                        $grbit,
  925.                                        $itabCur$itabFirst,
  926.                                        $ctabsel$wTabRatio);
  927.         $this->_append($header.$data);
  928.     }
  929.     
  930.     /**
  931.     * Writes Excel BIFF BOUNDSHEET record.
  932.     * FIXME: inconsistent with BIFF documentation
  933.     *
  934.     * @param string  $sheetname Worksheet name
  935.     * @param integer $offset    Location of worksheet BOF
  936.     * @access private
  937.     */
  938.     function _storeBoundsheet($sheetname,$offset)
  939.     {
  940.         $record    = 0x0085;                    // Record identifier
  941.         if ($this->_BIFF_version == 0x0600{
  942.             $length    = 0x08 + strlen($sheetname)// Number of bytes to follow
  943.         }
  944.         else {
  945.             $length = 0x07 + strlen($sheetname)// Number of bytes to follow
  946.         }
  947.     
  948.         $grbit     = 0x0000;                    // Visibility and sheet type
  949.         $cch       strlen($sheetname);        // Length of sheet name
  950.     
  951.         $header    pack("vv",  $record$length);
  952.         if ($this->_BIFF_version == 0x0600{
  953.             $data      pack("Vvv"$offset$grbit$cch);
  954.         }
  955.         else {
  956.             $data      pack("VvC"$offset$grbit$cch);
  957.         }
  958.         $this->_append($header.$data.$sheetname);
  959.     }
  960.  
  961.     /**
  962.     * Write Internal SUPBOOK record
  963.     *
  964.     * @access private
  965.     */
  966.     function _storeSupbookInternal()
  967.     {
  968.         $record    = 0x01AE;   // Record identifier
  969.         $length    = 0x0004;   // Bytes to follow
  970.                                
  971.         $header    pack("vv"$record$length);
  972.         $data      pack("vv"count($this->_worksheets)0x0104);
  973.         $this->_append($header.$data);
  974.     }
  975.  
  976.     /**
  977.     * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  978.     * formulas.
  979.     *
  980.     * @param string $sheetname Worksheet name
  981.     * @access private
  982.     */
  983.     function _storeExternsheetBiff8()
  984.     {
  985.         $total_references count($this->_parser->_references);
  986.         $record   = 0x0017;                     // Record identifier
  987.         $length   = 2 + 6 * $total_references;  // Number of bytes to follow
  988.  
  989.         $supbook_index = 0;           // FIXME: only using internal SUPBOOK record
  990.         $header           pack("vv",  $record$length);
  991.         $data             pack('v'$total_references);
  992.         for ($i = 0; $i $total_references$i++{
  993.             $data .= $this->_parser->_references[$i];
  994.         }
  995.         $this->_append($header.$data);
  996.     }
  997.  
  998.     /**
  999.     * Write Excel BIFF STYLE records.
  1000.     *
  1001.     * @access private
  1002.     */
  1003.     function _storeStyle()
  1004.     {
  1005.         $record    = 0x0293;   // Record identifier
  1006.         $length    = 0x0004;   // Bytes to follow
  1007.                                
  1008.         $ixfe      = 0x8000;   // Index to style XF
  1009.         $BuiltIn   = 0x00;     // Built-in style
  1010.         $iLevel    = 0xff;     // Outline style level
  1011.     
  1012.         $header    pack("vv",  $record$length);
  1013.         $data      pack("vCC"$ixfe$BuiltIn$iLevel);
  1014.         $this->_append($header.$data);
  1015.     }
  1016.     
  1017.     
  1018.     /**
  1019.     * Writes Excel FORMAT record for non "built-in" numerical formats.
  1020.     *
  1021.     * @param string  $format Custom format string
  1022.     * @param integer $ifmt   Format index code
  1023.     * @access private
  1024.     */
  1025.     function _storeNumFormat($format,$ifmt)
  1026.     {
  1027.         $record    = 0x041E;                      // Record identifier
  1028.  
  1029.         if ($this->_BIFF_version == 0x0600{
  1030.             $length    = 5 + strlen($format);      // Number of bytes to follow
  1031.             $encoding = 0x0;
  1032.         }
  1033.         elseif ($this->_BIFF_version == 0x0500{
  1034.             $length    = 3 + strlen($format);      // Number of bytes to follow
  1035.         }
  1036.  
  1037.         $cch       strlen($format);             // Length of format string
  1038.     
  1039.         $header    pack("vv"$record$length);
  1040.         if ($this->_BIFF_version == 0x0600{
  1041.             $data      pack("vvC"$ifmt$cch$encoding);
  1042.         }
  1043.         elseif ($this->_BIFF_version == 0x0500{
  1044.             $data      pack("vC"$ifmt$cch);
  1045.         }
  1046.         $this->_append($header.$data.$format);
  1047.     }
  1048.     
  1049.     /**
  1050.     * Write DATEMODE record to indicate the date system in use (1904 or 1900).
  1051.     *
  1052.     * @access private
  1053.     */
  1054.     function _storeDatemode()
  1055.     {
  1056.         $record    = 0x0022;         // Record identifier
  1057.         $length    = 0x0002;         // Bytes to follow
  1058.     
  1059.         $f1904     $this->_1904;   // Flag for 1904 date system
  1060.     
  1061.         $header    pack("vv"$record$length);
  1062.         $data      pack("v"$f1904);
  1063.         $this->_append($header.$data);
  1064.     }
  1065.     
  1066.     
  1067.     /**
  1068.     * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  1069.     * references in the workbook.
  1070.     *
  1071.     * Excel only stores references to external sheets that are used in NAME.
  1072.     * The workbook NAME record is required to define the print area and the repeat
  1073.     * rows and columns.
  1074.     *
  1075.     * A similar method is used in Worksheet.php for a slightly different purpose.
  1076.     *
  1077.     * @param integer $cxals Number of external references
  1078.     * @access private
  1079.     */
  1080.     function _storeExterncount($cxals)
  1081.     {
  1082.         $record   = 0x0016;          // Record identifier
  1083.         $length   = 0x0002;          // Number of bytes to follow
  1084.     
  1085.         $header   pack("vv"$record$length);
  1086.         $data     pack("v",  $cxals);
  1087.         $this->_append($header.$data);
  1088.     }
  1089.     
  1090.     
  1091.     /**
  1092.     * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  1093.     * formulas. NAME record is required to define the print area and the repeat
  1094.     * rows and columns.
  1095.     *
  1096.     * A similar method is used in Worksheet.php for a slightly different purpose.
  1097.     *
  1098.     * @param string $sheetname Worksheet name
  1099.     * @access private
  1100.     */
  1101.     function _storeExternsheet($sheetname)
  1102.     {
  1103.         $record      = 0x0017;                     // Record identifier
  1104.         $length      = 0x02 + strlen($sheetname);  // Number of bytes to follow
  1105.                                                    
  1106.         $cch         strlen($sheetname);         // Length of sheet name
  1107.         $rgch        = 0x03;                       // Filename encoding
  1108.     
  1109.         $header      pack("vv",  $record$length);
  1110.         $data        pack("CC"$cch$rgch);
  1111.         $this->_append($header.$data.$sheetname);
  1112.     }
  1113.     
  1114.     
  1115.     /**
  1116.     * Store the NAME record in the short format that is used for storing the print
  1117.     * area, repeat rows only and repeat columns only.
  1118.     *
  1119.     * @param integer $index  Sheet index
  1120.     * @param integer $type   Built-in name type
  1121.     * @param integer $rowmin Start row
  1122.     * @param integer $rowmax End row
  1123.     * @param integer $colmin Start colum
  1124.     * @param integer $colmax End column
  1125.     * @access private
  1126.     */
  1127.     function _storeNameShort($index,$type,$rowmin,$rowmax,$colmin,$colmax)
  1128.     {
  1129.         $record          = 0x0018;       // Record identifier
  1130.         $length          = 0x0024;       // Number of bytes to follow
  1131.     
  1132.         $grbit           = 0x0020;       // Option flags
  1133.         $chKey           = 0x00;         // Keyboard shortcut
  1134.         $cch             = 0x01;         // Length of text name
  1135.         $cce             = 0x0015;       // Length of text definition
  1136.         $ixals           $index + 1;   // Sheet index
  1137.         $itab            $ixals;       // Equal to ixals
  1138.         $cchCustMenu     = 0x00;         // Length of cust menu text
  1139.         $cchDescription  = 0x00;         // Length of description text
  1140.         $cchHelptopic    = 0x00;         // Length of help topic text
  1141.         $cchStatustext   = 0x00;         // Length of status bar text
  1142.         $rgch            $type;        // Built-in name type
  1143.     
  1144.         $unknown03       = 0x3b;
  1145.         $unknown04       = 0xffff-$index;
  1146.         $unknown05       = 0x0000;
  1147.         $unknown06       = 0x0000;
  1148.         $unknown07       = 0x1087;
  1149.         $unknown08       = 0x8005;
  1150.     
  1151.         $header             pack("vv"$record$length);
  1152.         $data               pack("v"$grbit);
  1153.         $data              .= pack("C"$chKey);
  1154.         $data              .= pack("C"$cch);
  1155.         $data              .= pack("v"$cce);
  1156.         $data              .= pack("v"$ixals);
  1157.         $data              .= pack("v"$itab);
  1158.         $data              .= pack("C"$cchCustMenu);
  1159.         $data              .= pack("C"$cchDescription);
  1160.         $data              .= pack("C"$cchHelptopic);
  1161.         $data              .= pack("C"$cchStatustext);
  1162.         $data              .= pack("C"$rgch);
  1163.         $data              .= pack("C"$unknown03);
  1164.         $data              .= pack("v"$unknown04);
  1165.         $data              .= pack("v"$unknown05);
  1166.         $data              .= pack("v"$unknown06);
  1167.         $data              .= pack("v"$unknown07);
  1168.         $data              .= pack("v"$unknown08);
  1169.         $data              .= pack("v"$index);
  1170.         $data              .= pack("v"$index);
  1171.         $data              .= pack("v"$rowmin);
  1172.         $data              .= pack("v"$rowmax);
  1173.         $data              .= pack("C"$colmin);
  1174.         $data              .= pack("C"$colmax);
  1175.         $this->_append($header.$data);
  1176.     }
  1177.     
  1178.     
  1179.     /**
  1180.     * Store the NAME record in the long format that is used for storing the repeat
  1181.     * rows and columns when both are specified. This shares a lot of code with
  1182.     * _storeNameShort() but we use a separate method to keep the code clean.
  1183.     * Code abstraction for reuse can be carried too far, and I should know. ;-)
  1184.     *
  1185.     * @param integer $index Sheet index
  1186.     * @param integer $type  Built-in name type
  1187.     * @param integer $rowmin Start row
  1188.     * @param integer $rowmax End row
  1189.     * @param integer $colmin Start colum
  1190.     * @param integer $colmax End column
  1191.     * @access private
  1192.     */
  1193.     function _storeNameLong($index,$type,$rowmin,$rowmax,$colmin,$colmax)
  1194.     {
  1195.         $record          = 0x0018;       // Record identifier
  1196.         $length          = 0x003d;       // Number of bytes to follow
  1197.         $grbit           = 0x0020;       // Option flags
  1198.         $chKey           = 0x00;         // Keyboard shortcut
  1199.         $cch             = 0x01;         // Length of text name
  1200.         $cce             = 0x002e;       // Length of text definition
  1201.         $ixals           $index + 1;   // Sheet index
  1202.         $itab            $ixals;       // Equal to ixals
  1203.         $cchCustMenu     = 0x00;         // Length of cust menu text
  1204.         $cchDescription  = 0x00;         // Length of description text
  1205.         $cchHelptopic    = 0x00;         // Length of help topic text
  1206.         $cchStatustext   = 0x00;         // Length of status bar text
  1207.         $rgch            $type;        // Built-in name type
  1208.     
  1209.         $unknown01       = 0x29;
  1210.         $unknown02       = 0x002b;
  1211.         $unknown03       = 0x3b;
  1212.         $unknown04       = 0xffff-$index;
  1213.         $unknown05       = 0x0000;
  1214.         $unknown06       = 0x0000;
  1215.         $unknown07       = 0x1087;
  1216.         $unknown08       = 0x8008;
  1217.     
  1218.         $header             pack("vv",  $record$length);
  1219.         $data               pack("v"$grbit);
  1220.         $data              .= pack("C"$chKey);
  1221.         $data              .= pack("C"$cch);
  1222.         $data              .= pack("v"$cce);
  1223.         $data              .= pack("v"$ixals);
  1224.         $data              .= pack("v"$itab);
  1225.         $data              .= pack("C"$cchCustMenu);
  1226.         $data              .= pack("C"$cchDescription);
  1227.         $data              .= pack("C"$cchHelptopic);
  1228.         $data              .= pack("C"$cchStatustext);
  1229.         $data              .= pack("C"$rgch);
  1230.         $data              .= pack("C"$unknown01);
  1231.         $data              .= pack("v"$unknown02);
  1232.         // Column definition
  1233.         $data              .= pack("C"$unknown03);
  1234.         $data              .= pack("v"$unknown04);
  1235.         $data              .= pack("v"$unknown05);
  1236.         $data              .= pack("v"$unknown06);
  1237.         $data              .= pack("v"$unknown07);
  1238.         $data              .= pack("v"$unknown08);
  1239.         $data              .= pack("v"$index);
  1240.         $data              .= pack("v"$index);
  1241.         $data              .= pack("v"0x0000);
  1242.         $data              .= pack("v"0x3fff);
  1243.         $data              .= pack("C"$colmin);
  1244.         $data              .= pack("C"$colmax);
  1245.         // Row definition
  1246.         $data              .= pack("C"$unknown03);
  1247.         $data              .= pack("v"$unknown04);
  1248.         $data              .= pack("v"$unknown05);
  1249.         $data              .= pack("v"$unknown06);
  1250.         $data              .= pack("v"$unknown07);
  1251.         $data              .= pack("v"$unknown08);
  1252.         $data              .= pack("v"$index);
  1253.         $data              .= pack("v"$index);
  1254.         $data              .= pack("v"$rowmin);
  1255.         $data              .= pack("v"$rowmax);
  1256.         $data              .= pack("C"0x00);
  1257.         $data              .= pack("C"0xff);
  1258.         // End of data
  1259.         $data              .= pack("C"0x10);
  1260.         $this->_append($header.$data);
  1261.     }
  1262.     
  1263.     /**
  1264.     * Stores the COUNTRY record for localization
  1265.     *
  1266.     * @access private
  1267.     */
  1268.     function _storeCountry()
  1269.     {
  1270.         $record          = 0x008C;    // Record identifier
  1271.         $length          = 4;         // Number of bytes to follow
  1272.  
  1273.         $header pack('vv',  $record$length);
  1274.         /* using the same country code always for simplicity */
  1275.         $data pack('vv'$this->_country_code$this->_country_code);
  1276.         $this->_append($header.$data);
  1277.     }
  1278.     
  1279.     /**
  1280.     * Stores the PALETTE biff record.
  1281.     *
  1282.     * @access private
  1283.     */
  1284.     function _storePalette()
  1285.     {
  1286.         $aref            $this->_palette;
  1287.     
  1288.         $record          = 0x0092;                 // Record identifier
  1289.         $length          = 2 + 4 * count($aref);   // Number of bytes to follow
  1290.         $ccv             =         count($aref);   // Number of RGB values to follow
  1291.         $data '';                                // The RGB data
  1292.     
  1293.         // Pack the RGB data
  1294.         foreach($aref as $color)
  1295.         {
  1296.             foreach($color as $byte{
  1297.                 $data .= pack("C",$byte);
  1298.             }
  1299.         }
  1300.     
  1301.         $header pack("vvv",  $record$length$ccv);
  1302.         $this->_append($header.$data);
  1303.     }
  1304.  
  1305.     /**
  1306.     * Calculate
  1307.     * Handling of the SST continue blocks is complicated by the need to include an
  1308.     * additional continuation byte depending on whether the string is split between
  1309.     * blocks or whether it starts at the beginning of the block. (There are also
  1310.     * additional complications that will arise later when/if Rich Strings are
  1311.     * supported).
  1312.     *
  1313.     * @access private
  1314.     */
  1315.     function _calculateSharedStringsSizes()
  1316.     {
  1317.         /* Iterate through the strings to calculate the CONTINUE block sizes.
  1318.            For simplicity we use the same size for the SST and CONTINUE records:
  1319.            8228 : Maximum Excel97 block size
  1320.              -4 : Length of block header
  1321.              -8 : Length of additional SST header information
  1322.          = 8216
  1323.         */
  1324.         $continue_limit     = 8216;
  1325.         $block_length       = 0;
  1326.         $written            = 0;
  1327.         $this->_block_sizes = array();
  1328.         $continue           = 0;
  1329.  
  1330.         foreach (array_keys($this->_str_tableas $string{
  1331.             $string_length strlen($string);
  1332.  
  1333.             // Block length is the total length of the strings that will be
  1334.             // written out in a single SST or CONTINUE block.
  1335.             $block_length += $string_length;
  1336.  
  1337.             // We can write the string if it doesn't cross a CONTINUE boundary
  1338.             if ($block_length $continue_limit{
  1339.                 $written      += $string_length;
  1340.                 continue;
  1341.             }
  1342.  
  1343.             // Deal with the cases where the next string to be written will exceed
  1344.             // the CONTINUE boundary. If the string is very long it may need to be
  1345.             // written in more than one CONTINUE record.
  1346.             while ($block_length >= $continue_limit{
  1347.  
  1348.                 // We need to avoid the case where a string is continued in the first
  1349.                 // n bytes that contain the string header information.
  1350.                 $header_length   = 3; // Min string + header size -1
  1351.                 $space_remaining $continue_limit $written $continue;
  1352.  
  1353.  
  1354.                 /* TODO: Unicode data should only be split on char (2 byte)
  1355.                 boundaries. Therefore, in some cases we need to reduce the
  1356.                 amount of available
  1357.                 */
  1358.  
  1359.                 if ($space_remaining $header_length{
  1360.                     // Write as much as possible of the string in the current block
  1361.                     $written      += $space_remaining;
  1362.  
  1363.                     // Reduce the current block length by the amount written
  1364.                     $block_length -= $continue_limit $continue;
  1365.  
  1366.                     // Store the max size for this block
  1367.                     $this->_block_sizes[$continue_limit;
  1368.  
  1369.                     // If the current string was split then the next CONTINUE block
  1370.                     // should have the string continue flag (grbit) set unless the
  1371.                     // split string fits exactly into the remaining space.
  1372.                     if ($block_length > 0{
  1373.                         $continue = 1;
  1374.                     }
  1375.                     else {
  1376.                         $continue = 0;
  1377.                     }
  1378.  
  1379.                 }
  1380.                 else {
  1381.                     // Store the max size for this block
  1382.                     $this->_block_sizes[$written $continue;
  1383.  
  1384.                     // Not enough space to start the string in the current block
  1385.                     $block_length -= $continue_limit $space_remaining $continue;
  1386.                     $continue = 0;
  1387.  
  1388.                 }
  1389.  
  1390.                 // If the string (or substr) is small enough we can write it in the
  1391.                 // new CONTINUE block. Else, go through the loop again to write it in
  1392.                 // one or more CONTINUE blocks
  1393.                 if ($block_length $continue_limit{
  1394.                     $written $block_length;
  1395.                 }
  1396.                 else {
  1397.                     $written = 0;
  1398.                 }
  1399.             }
  1400.         }
  1401.  
  1402.         // Store the max size for the last block unless it is empty
  1403.         if ($written $continue{
  1404.             $this->_block_sizes[$written $continue;
  1405.         }
  1406.  
  1407.  
  1408.         /* Calculate the total length of the SST and associated CONTINUEs (if any).
  1409.          The SST record will have a length even if it contains no strings.
  1410.          This length is required to set the offsets in the BOUNDSHEET records since
  1411.          they must be written before the SST records
  1412.         */
  1413.         $total_offset array_sum($this->_block_sizes);
  1414.         // SST information
  1415.         $total_offset += 8;
  1416.         if (!empty($this->_block_sizes)) {
  1417.             $total_offset += (count($this->_block_sizes)) * 4; // add CONTINUE headers
  1418.         }
  1419.         return $total_offset;
  1420.     }
  1421.  
  1422.     /**
  1423.     * Write all of the workbooks strings into an indexed array.
  1424.     * See the comments in _calculate_shared_string_sizes() for more information.
  1425.     *
  1426.     * The Excel documentation says that the SST record should be followed by an
  1427.     * EXTSST record. The EXTSST record is a hash table that is used to optimise
  1428.     * access to SST. However, despite the documentation it doesn't seem to be
  1429.     * required so we will ignore it.
  1430.     *
  1431.     * @access private
  1432.     */
  1433.     function _storeSharedStringsTable()
  1434.     {
  1435.         $record  = 0x00fc;  // Record identifier
  1436.         // sizes are upside down
  1437.         $this->_block_sizes array_reverse($this->_block_sizes);
  1438.         $length array_pop($this->_block_sizes+ 8; // First block size plus SST information
  1439.  
  1440.         // Write the SST block header information
  1441.         $header      pack("vv"$record$length);
  1442.         $data        pack("VV"$this->_str_total$this->_str_unique);
  1443.         $this->_append($header.$data);
  1444.  
  1445.  
  1446.         // Iterate through the strings to calculate the CONTINUE block sizes
  1447.         $continue_limit = 8216;
  1448.         $block_length   = 0;
  1449.         $written        = 0;
  1450.         $continue       = 0;
  1451.  
  1452.  
  1453.         /* TODO: not good for performance */
  1454.         foreach (array_keys($this->_str_tableas $string{
  1455.  
  1456.             $string_length strlen($string);
  1457.             $encoding      = 0; // assume there are no Unicode strings
  1458.             $split_string  = 0;
  1459.  
  1460.             // Block length is the total length of the strings that will be
  1461.             // written out in a single SST or CONTINUE block.
  1462.             //
  1463.             $block_length += $string_length;
  1464.  
  1465.  
  1466.             // We can write the string if it doesn't cross a CONTINUE boundary
  1467.             if ($block_length $continue_limit{
  1468.                 $this->_append($string);
  1469.                 $written += $string_length;
  1470.                 continue;
  1471.             }
  1472.  
  1473.             // Deal with the cases where the next string to be written will exceed
  1474.             // the CONTINUE boundary. If the string is very long it may need to be
  1475.             // written in more than one CONTINUE record.
  1476.             // 
  1477.             while ($block_length >= $continue_limit{
  1478.  
  1479.                 // We need to avoid the case where a string is continued in the first
  1480.                 // n bytes that contain the string header information.
  1481.                 //
  1482.                 $header_length   = 3; // Min string + header size -1
  1483.                 $space_remaining $continue_limit $written $continue;
  1484.  
  1485.  
  1486.                 // Unicode data should only be split on char (2 byte) boundaries.
  1487.                 // Therefore, in some cases we need to reduce the amount of available
  1488.  
  1489.                 if ($space_remaining $header_length{
  1490.                     // Write as much as possible of the string in the current block
  1491.                     $tmp substr($string0$space_remaining);
  1492.                     $this->_append($tmp);
  1493.  
  1494.                     // The remainder will be written in the next block(s)
  1495.                     $string substr($string$space_remaining);
  1496.  
  1497.                     // Reduce the current block length by the amount written
  1498.                     $block_length -= $continue_limit $continue;
  1499.  
  1500.                     // If the current string was split then the next CONTINUE block
  1501.                     // should have the string continue flag (grbit) set unless the
  1502.                     // split string fits exactly into the remaining space.
  1503.                     //
  1504.                     if ($block_length > 0{
  1505.                         $continue = 1;
  1506.                     }
  1507.                     else {
  1508.                         $continue = 0;
  1509.                     }
  1510.                 }
  1511.                 else {
  1512.                     // Not enough space to start the string in the current block
  1513.                     $block_length -= $continue_limit $space_remaining $continue;
  1514.                     $continue = 0;
  1515.                 }
  1516.  
  1517.                 // Write the CONTINUE block header
  1518.                 if (!empty($this->_block_sizes)) {
  1519.                     $record  = 0x003C;
  1520.                     $length  array_pop($this->_block_sizes);
  1521.                     $header  pack('vv'$record$length);
  1522.                     if ($continue{
  1523.                         $header .= pack('C'$encoding);
  1524.                     }
  1525.                     $this->_append($header);
  1526.                 }
  1527.  
  1528.                 // If the string (or substr) is small enough we can write it in the
  1529.                 // new CONTINUE block. Else, go through the loop again to write it in
  1530.                 // one or more CONTINUE blocks
  1531.                 //
  1532.                 if ($block_length $continue_limit{
  1533.                     $this->_append($string);
  1534.                     $written $block_length;
  1535.                 }
  1536.                 else {
  1537.                     $written = 0;
  1538.                 }
  1539.             }
  1540.         }
  1541.     }
  1542. }
  1543. ?>

Documentation generated on Mon, 11 Mar 2019 13:51:58 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.