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

Documentation generated on Mon, 25 Aug 2008 13:52:22 +0200 by phpDocumentor 1.4.1