MDL-33399 files: Fixed up handling of empty sort in File API methods.
[moodle.git] / lib / excel / Worksheet.php
blobd7c5cfc9e440bed62171d3563141752f89889d83
1 <?php
2 /*
3 * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
5 * The majority of this is _NOT_ my code. I simply ported it from the
6 * PERL Spreadsheet::WriteExcel module.
8 * The author of the Spreadsheet::WriteExcel module is John McNamara
9 * <jmcnamara@cpan.org>
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.
15 * License Information:
17 * Spreadsheet::WriteExcel: A library for generating Excel Spreadsheets
18 * Copyright (C) 2002 Xavier Noguer xnoguer@rezebra.com
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.
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.
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
35 require_once('Parser.php');
36 require_once('BIFFwriter.php');
38 /**
39 * Class for generating Excel Spreadsheets
41 * @author Xavier Noguer <xnoguer@rezebra.com>
42 * @package Spreadsheet_WriteExcel
45 class Worksheet extends BIFFwriter
48 /**
49 * Constructor
51 * @param string $name The name of the new worksheet
52 * @param integer $index The index of the new worksheet
53 * @param mixed &$activesheet The current activesheet of the workbook we belong to
54 * @param mixed &$firstsheet The first worksheet in the workbook we belong to
55 * @param mixed &$url_format The default format for hyperlinks
56 * @param mixed &$parser The formula parser created for the Workbook
58 function Worksheet($name,$index,&$activesheet,&$firstsheet,&$url_format,&$parser)
60 $this->BIFFwriter(); // It needs to call its parent's constructor explicitly
61 $rowmax = 65536; // 16384 in Excel 5
62 $colmax = 256;
63 $strmax = 255;
65 $this->name = $name;
66 $this->index = $index;
67 $this->activesheet = &$activesheet;
68 $this->firstsheet = &$firstsheet;
69 $this->_url_format = $url_format;
70 $this->_parser = &$parser;
72 $this->ext_sheets = array();
73 $this->_using_tmpfile = 1;
74 $this->_filehandle = "";
75 $this->fileclosed = 0;
76 $this->offset = 0;
77 $this->xls_rowmax = $rowmax;
78 $this->xls_colmax = $colmax;
79 $this->xls_strmax = $strmax;
80 $this->dim_rowmin = $rowmax +1;
81 $this->dim_rowmax = 0;
82 $this->dim_colmin = $colmax +1;
83 $this->dim_colmax = 0;
84 $this->colinfo = array();
85 $this->_selection = array(0,0,0,0);
86 $this->_panes = array();
87 $this->_active_pane = 3;
88 $this->_frozen = 0;
89 $this->selected = 0;
91 $this->_paper_size = 0x0;
92 $this->_orientation = 0x1;
93 $this->_header = '';
94 $this->_footer = '';
95 $this->_hcenter = 0;
96 $this->_vcenter = 0;
97 $this->_margin_head = 0.50;
98 $this->_margin_foot = 0.50;
99 $this->_margin_left = 0.75;
100 $this->_margin_right = 0.75;
101 $this->_margin_top = 1.00;
102 $this->_margin_bottom = 1.00;
104 $this->_title_rowmin = NULL;
105 $this->_title_rowmax = NULL;
106 $this->_title_colmin = NULL;
107 $this->_title_colmax = NULL;
108 $this->_print_rowmin = NULL;
109 $this->_print_rowmax = NULL;
110 $this->_print_colmin = NULL;
111 $this->_print_colmax = NULL;
113 $this->_print_gridlines = 1;
114 $this->_print_headers = 0;
116 $this->_fit_page = 0;
117 $this->_fit_width = 0;
118 $this->_fit_height = 0;
120 $this->_hbreaks = array();
121 $this->_vbreaks = array();
123 $this->_protect = 0;
124 $this->_password = NULL;
126 $this->col_sizes = array();
127 $this->row_sizes = array();
129 $this->_zoom = 100;
130 $this->_print_scale = 100;
132 $this->_initialize();
136 * Open a tmp file to store the majority of the Worksheet data. If this fails,
137 * for example due to write permissions, store the data in memory. This can be
138 * slow for large files.
140 function _initialize()
142 // Open tmp file for storing Worksheet data
143 $fh = tmpfile();
144 if ( $fh) {
145 // Store filehandle
146 $this->_filehandle = $fh;
148 else {
149 // If tmpfile() fails store data in memory
150 $this->_using_tmpfile = 0;
155 * Add data to the beginning of the workbook (note the reverse order)
156 * and to the end of the workbook.
158 * @access public
159 * @see Workbook::store_workbook()
160 * @param array $sheetnames The array of sheetnames from the Workbook this
161 * worksheet belongs to
163 function close($sheetnames)
165 $num_sheets = count($sheetnames);
167 /***********************************************
168 * Prepend in reverse order!!
171 // Prepend the sheet dimensions
172 $this->_store_dimensions();
174 // Prepend the sheet password
175 $this->_store_password();
177 // Prepend the sheet protection
178 $this->_store_protect();
180 // Prepend the page setup
181 $this->_store_setup();
183 // Prepend the bottom margin
184 $this->_store_margin_bottom();
186 // Prepend the top margin
187 $this->_store_margin_top();
189 // Prepend the right margin
190 $this->_store_margin_right();
192 // Prepend the left margin
193 $this->_store_margin_left();
195 // Prepend the page vertical centering
196 $this->store_vcenter();
198 // Prepend the page horizontal centering
199 $this->store_hcenter();
201 // Prepend the page footer
202 $this->store_footer();
204 // Prepend the page header
205 $this->store_header();
207 // Prepend the vertical page breaks
208 $this->_store_vbreak();
210 // Prepend the horizontal page breaks
211 $this->_store_hbreak();
213 // Prepend WSBOOL
214 $this->_store_wsbool();
216 // Prepend GRIDSET
217 $this->_store_gridset();
219 // Prepend PRINTGRIDLINES
220 $this->_store_print_gridlines();
222 // Prepend PRINTHEADERS
223 $this->_store_print_headers();
225 // Prepend EXTERNSHEET references
226 for ($i = $num_sheets; $i > 0; $i--) {
227 $sheetname = $sheetnames[$i-1];
228 $this->_store_externsheet($sheetname);
231 // Prepend the EXTERNCOUNT of external references.
232 $this->_store_externcount($num_sheets);
234 // Prepend the COLINFO records if they exist
235 if (!empty($this->colinfo)){
236 for($i=0; $i < count($this->colinfo); $i++)
238 $this->_store_colinfo($this->colinfo[$i]);
240 $this->_store_defcol();
243 // Prepend the BOF record
244 $this->_store_bof(0x0010);
247 * End of prepend. Read upwards from here.
248 ***********************************************/
250 // Append
251 $this->_store_window2();
252 $this->_store_zoom();
253 if(!empty($this->_panes))
254 $this->_store_panes($this->_panes);
255 $this->_store_selection($this->_selection);
256 $this->_store_eof();
260 * Retrieve the worksheet name. This is usefull when creating worksheets
261 * without a name.
263 * @access public
264 * @return string The worksheet's name
266 function get_name()
268 return($this->name);
272 * Retrieves data from memory in one chunk, or from disk in $buffer
273 * sized chunks.
275 * @return string The data
277 function get_data()
279 $buffer = 4096;
281 // Return data stored in memory
282 if (isset($this->_data)) {
283 $tmp = $this->_data;
284 unset($this->_data);
285 $fh = $this->_filehandle;
286 if ($this->_using_tmpfile) {
287 fseek($fh, 0);
289 return($tmp);
291 // Return data stored on disk
292 if ($this->_using_tmpfile) {
293 if ($tmp = fread($this->_filehandle, $buffer)) {
294 return($tmp);
298 // No data to return
299 return('');
303 * Set this worksheet as a selected worksheet, i.e. the worksheet has its tab
304 * highlighted.
306 * @access public
308 function select()
310 $this->selected = 1;
314 * Set this worksheet as the active worksheet, i.e. the worksheet that is
315 * displayed when the workbook is opened. Also set it as selected.
317 * @access public
319 function activate()
321 $this->selected = 1;
322 $this->activesheet =& $this->index;
326 * Set this worksheet as the first visible sheet. This is necessary
327 * when there are a large number of worksheets and the activated
328 * worksheet is not visible on the screen.
330 * @access public
332 function set_first_sheet()
334 $this->firstsheet = $this->index;
338 * Set the worksheet protection flag to prevent accidental modification and to
339 * hide formulas if the locked and hidden format properties have been set.
341 * @access public
342 * @param string $password The password to use for protecting the sheet.
344 function protect($password)
346 $this->_protect = 1;
347 $this->_password = $this->_encode_password($password);
351 * Set the width of a single column or a range of columns.
353 * @access public
354 * @see _store_colinfo()
355 * @param integer $firstcol first column on the range
356 * @param integer $lastcol last column on the range
357 * @param integer $width width to set
358 * @param mixed $format The optional XF format to apply to the columns
359 * @param integer $hidden The optional hidden atribute
361 function set_column($firstcol, $lastcol, $width, $format = 0, $hidden = 0)
363 $this->colinfo[] = array($firstcol, $lastcol, $width, $format, $hidden);
365 // Set width to zero if column is hidden
366 $width = ($hidden) ? 0 : $width;
368 for($col = $firstcol; $col <= $lastcol; $col++) {
369 $this->col_sizes[$col] = $width;
374 * Set which cell or cells are selected in a worksheet
376 * @access public
377 * @param integer $first_row first row in the selected quadrant
378 * @param integer $first_column first column in the selected quadrant
379 * @param integer $last_row last row in the selected quadrant
380 * @param integer $last_column last column in the selected quadrant
381 * @see _store_selection()
383 function set_selection($first_row,$first_column,$last_row,$last_column)
385 $this->_selection = array($first_row,$first_column,$last_row,$last_column);
389 * Set panes and mark them as frozen.
391 * @access public
392 * @param array $panes This is the only parameter received and is composed of the following:
393 * 0 => Vertical split position,
394 * 1 => Horizontal split position
395 * 2 => Top row visible
396 * 3 => Leftmost column visible
397 * 4 => Active pane
399 function freeze_panes($panes)
401 $this->_frozen = 1;
402 $this->_panes = $panes;
406 * Set panes and mark them as unfrozen.
408 * @access public
409 * @param array $panes This is the only parameter received and is composed of the following:
410 * 0 => Vertical split position,
411 * 1 => Horizontal split position
412 * 2 => Top row visible
413 * 3 => Leftmost column visible
414 * 4 => Active pane
416 function thaw_panes($panes)
418 $this->_frozen = 0;
419 $this->_panes = $panes;
423 * Set the page orientation as portrait.
425 * @access public
427 function set_portrait()
429 $this->_orientation = 1;
433 * Set the page orientation as landscape.
435 * @access public
437 function set_landscape()
439 $this->_orientation = 0;
443 * Set the paper type. Ex. 1 = US Letter, 9 = A4
445 * @access public
446 * @param integer $size The type of paper size to use
448 function set_paper($size = 0)
450 $this->_paper_size = $size;
455 * Set the page header caption and optional margin.
457 * @access public
458 * @param string $string The header text
459 * @param float $margin optional head margin in inches.
461 function set_header($string,$margin = 0.50)
463 if (strlen($string) >= 255) {
464 //carp 'Header string must be less than 255 characters';
465 return;
467 $this->_header = $string;
468 $this->_margin_head = $margin;
472 * Set the page footer caption and optional margin.
474 * @access public
475 * @param string $string The footer text
476 * @param float $margin optional foot margin in inches.
478 function set_footer($string,$margin = 0.50)
480 if (strlen($string) >= 255) {
481 //carp 'Footer string must be less than 255 characters';
482 return;
484 $this->_footer = $string;
485 $this->_margin_foot = $margin;
489 * Center the page horinzontally.
491 * @access public
492 * @param integer $center the optional value for centering. Defaults to 1 (center).
494 function center_horizontally($center = 1)
496 $this->_hcenter = $center;
500 * Center the page horinzontally.
502 * @access public
503 * @param integer $center the optional value for centering. Defaults to 1 (center).
505 function center_vertically($center = 1)
507 $this->_vcenter = $center;
511 * Set all the page margins to the same value in inches.
513 * @access public
514 * @param float $margin The margin to set in inches
516 function set_margins($margin)
518 $this->set_margin_left($margin);
519 $this->set_margin_right($margin);
520 $this->set_margin_top($margin);
521 $this->set_margin_bottom($margin);
525 * Set the left and right margins to the same value in inches.
527 * @access public
528 * @param float $margin The margin to set in inches
530 function set_margins_LR($margin)
532 $this->set_margin_left($margin);
533 $this->set_margin_right($margin);
537 * Set the top and bottom margins to the same value in inches.
539 * @access public
540 * @param float $margin The margin to set in inches
542 function set_margins_TB($margin)
544 $this->set_margin_top($margin);
545 $this->set_margin_bottom($margin);
549 * Set the left margin in inches.
551 * @access public
552 * @param float $margin The margin to set in inches
554 function set_margin_left($margin = 0.75)
556 $this->_margin_left = $margin;
560 * Set the right margin in inches.
562 * @access public
563 * @param float $margin The margin to set in inches
565 function set_margin_right($margin = 0.75)
567 $this->_margin_right = $margin;
571 * Set the top margin in inches.
573 * @access public
574 * @param float $margin The margin to set in inches
576 function set_margin_top($margin = 1.00)
578 $this->_margin_top = $margin;
582 * Set the bottom margin in inches.
584 * @access public
585 * @param float $margin The margin to set in inches
587 function set_margin_bottom($margin = 1.00)
589 $this->_margin_bottom = $margin;
593 * Set the rows to repeat at the top of each printed page. See also the
594 * _store_name_xxxx() methods in Workbook.php
596 * @access public
597 * @param integer $first_row First row to repeat
598 * @param integer $last_row Last row to repeat. Optional.
600 function repeat_rows($first_row, $last_row = NULL)
602 $this->_title_rowmin = $first_row;
603 if(isset($last_row)) { //Second row is optional
604 $this->_title_rowmax = $last_row;
606 else {
607 $this->_title_rowmax = $first_row;
612 * Set the columns to repeat at the left hand side of each printed page.
613 * See also the _store_names() methods in Workbook.php
615 * @access public
616 * @param integer $first_col First column to repeat
617 * @param integer $last_col Last column to repeat. Optional.
619 function repeat_columns($first_col, $last_col = NULL)
621 $this->_title_colmin = $first_col;
622 if(isset($last_col)) { // Second col is optional
623 $this->_title_colmax = $last_col;
625 else {
626 $this->_title_colmax = $first_col;
631 * Set the area of each worksheet that will be printed.
633 * @access public
634 * @see Workbook::_store_names()
635 * @param integer $first_row First row of the area to print
636 * @param integer $first_col First column of the area to print
637 * @param integer $last_row Last row of the area to print
638 * @param integer $last_col Last column of the area to print
640 function print_area($first_row, $first_col, $last_row, $last_col)
642 $this->_print_rowmin = $first_row;
643 $this->_print_colmin = $first_col;
644 $this->_print_rowmax = $last_row;
645 $this->_print_colmax = $last_col;
650 * Set the option to hide gridlines on the printed page.
652 * @access public
653 * @see _store_print_gridlines(), _store_gridset()
655 function hide_gridlines()
657 $this->_print_gridlines = 0;
661 * Set the option to print the row and column headers on the printed page.
662 * See also the _store_print_headers() method below.
664 * @access public
665 * @see _store_print_headers()
666 * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
668 function print_row_col_headers($print = 1)
670 $this->_print_headers = $print;
674 * Store the vertical and horizontal number of pages that will define the
675 * maximum area printed. It doesn't seem to work with OpenOffice.
677 * @access public
678 * @param integer $width Maximun width of printed area in pages
679 * @param integer $heigth Maximun heigth of printed area in pages
680 * @see set_print_scale()
682 function fit_to_pages($width, $height)
684 $this->_fit_page = 1;
685 $this->_fit_width = $width;
686 $this->_fit_height = $height;
690 * Store the horizontal page breaks on a worksheet (for printing).
691 * The breaks represent the row after which the break is inserted.
693 * @access public
694 * @param array $breaks Array containing the horizontal page breaks
696 function set_h_pagebreaks($breaks)
698 foreach($breaks as $break) {
699 array_push($this->_hbreaks,$break);
704 * Store the vertical page breaks on a worksheet (for printing).
705 * The breaks represent the column after which the break is inserted.
707 * @access public
708 * @param array $breaks Array containing the vertical page breaks
710 function set_v_pagebreaks($breaks)
712 foreach($breaks as $break) {
713 array_push($this->_vbreaks,$break);
719 * Set the worksheet zoom factor.
721 * @access public
722 * @param integer $scale The zoom factor
724 function set_zoom($scale = 100)
726 // Confine the scale to Excel's range
727 if ($scale < 10 or $scale > 400) {
728 //carp "Zoom factor $scale outside range: 10 <= zoom <= 400";
729 $scale = 100;
732 $this->_zoom = floor($scale);
736 * Set the scale factor for the printed page.
737 * It turns off the "fit to page" option
739 * @access public
740 * @param integer $scale The optional scale factor. Defaults to 100
742 function set_print_scale($scale = 100)
744 // Confine the scale to Excel's range
745 if ($scale < 10 or $scale > 400)
747 // REPLACE THIS FOR A WARNING
748 die("Print scale $scale outside range: 10 <= zoom <= 400");
749 $scale = 100;
752 // Turn off "fit to page" option
753 $this->_fit_page = 0;
755 $this->_print_scale = floor($scale);
759 * Map to the appropriate write method acording to the token recieved.
761 * @access public
762 * @param integer $row The row of the cell we are writing to
763 * @param integer $col The column of the cell we are writing to
764 * @param mixed $token What we are writing
765 * @param mixed $format The optional format to apply to the cell
767 function write($row, $col, $token, $format = 0)
769 // Check for a cell reference in A1 notation and substitute row and column
770 /*if ($_[0] =~ /^\D/) {
771 @_ = $this->_substitute_cellref(@_);
775 # Match an array ref.
776 if (ref $token eq "ARRAY") {
777 return $this->write_row(@_);
780 // Match number
781 if (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/",$token)) {
782 return $this->write_number($row,$col,$token,$format);
784 // Match http or ftp URL
785 elseif (preg_match("/^[fh]tt?p:\/\//",$token)) {
786 return $this->write_url($row, $col, $token, $format);
788 // Match mailto:
789 elseif (preg_match("/^mailto:/",$token)) {
790 return $this->write_url($row, $col, $token, $format);
792 // Match internal or external sheet link
793 elseif (preg_match("/^(?:in|ex)ternal:/",$token)) {
794 return $this->write_url($row, $col, $token, $format);
796 // Match formula
797 elseif (preg_match("/^=/",$token)) {
798 return $this->write_formula($row, $col, $token, $format);
800 // Match formula
801 elseif (preg_match("/^@/",$token)) {
802 return $this->write_formula($row, $col, $token, $format);
804 // Match blank
805 elseif ($token == '') {
806 return $this->write_blank($row,$col,$format);
808 // Default: match string
809 else {
810 return $this->write_string($row,$col,$token,$format);
815 * Returns an index to the XF record in the workbook
817 * @param mixed $format The optional XF format
818 * @return integer The XF record index
820 function _XF(&$format)
822 if($format != 0)
824 return($format->get_xf_index());
826 else
828 return(0x0F);
833 /******************************************************************************
834 *******************************************************************************
836 * Internal methods
841 * Store Worksheet data in memory using the parent's class append() or to a
842 * temporary file, the default.
844 * @param string $data The binary data to append
846 function _append($data)
848 if ($this->_using_tmpfile)
850 // Add CONTINUE records if necessary
851 if (strlen($data) > $this->_limit) {
852 $data = $this->_add_continue($data);
854 fwrite($this->_filehandle,$data);
855 $this->_datasize += strlen($data);
857 else {
858 parent::_append($data);
863 * Substitute an Excel cell reference in A1 notation for zero based row and
864 * column values in an argument list.
866 * Ex: ("A4", "Hello") is converted to (3, 0, "Hello").
868 * @param string $cell The cell reference. Or range of cells.
869 * @return array
871 function _substitute_cellref($cell)
873 $cell = strtoupper($cell);
875 // Convert a column range: 'A:A' or 'B:G'
876 if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/",$cell,$match)) {
877 list($no_use, $col1) = $this->_cell_to_rowcol($match[1] .'1'); // Add a dummy row
878 list($no_use, $col2) = $this->_cell_to_rowcol($match[2] .'1'); // Add a dummy row
879 return(array($col1, $col2));
882 // Convert a cell range: 'A1:B7'
883 if (preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/",$cell,$match)) {
884 list($row1, $col1) = $this->_cell_to_rowcol($match[1]);
885 list($row2, $col2) = $this->_cell_to_rowcol($match[2]);
886 return(array($row1, $col1, $row2, $col2));
889 // Convert a cell reference: 'A1' or 'AD2000'
890 if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/",$cell)) {
891 list($row1, $col1) = $this->_cell_to_rowcol($match[1]);
892 return(array($row1, $col1));
895 die("Unknown cell reference $cell ");
899 * Convert an Excel cell reference in A1 notation to a zero based row and column
900 * reference; converts C1 to (0, 2).
902 * @param string $cell The cell reference.
903 * @return array containing (row, column)
905 function _cell_to_rowcol($cell)
907 preg_match("/\$?([A-I]?[A-Z])\$?(\d+)/",$cell,$match);
908 $col = $match[1];
909 $row = $match[2];
911 // Convert base26 column string to number
912 $chars = str_split($col);
913 $expn = 0;
914 $col = 0;
916 while ($chars) {
917 $char = array_pop($chars); // LS char first
918 $col += (ord($char) -ord('A') +1) * pow(26,$expn);
919 $expn++;
922 // Convert 1-index to zero-index
923 $row--;
924 $col--;
926 return(array($row, $col));
930 * Based on the algorithm provided by Daniel Rentz of OpenOffice.
932 * @param string $plaintext The password to be encoded in plaintext.
933 * @return string The encoded password
935 function _encode_password($plaintext)
937 $password = 0x0000;
938 $i = 1; // char position
940 // split the plain text password in its component characters
941 $chars = preg_split('//', $plaintext, -1, PREG_SPLIT_NO_EMPTY);
942 foreach($chars as $char)
944 $value = ord($char) << $i; // shifted ASCII value
945 $bit_16 = $value & 0x8000; // the bit 16
946 $bit_16 >>= 15; // 0x0000 or 0x0001
947 //$bit_17 = $value & 0x00010000;
948 //$bit_17 >>= 15;
949 $value &= 0x7fff; // first 15 bits
950 $password ^= ($value | $bit_16);
951 //$password ^= ($value | $bit_16 | $bit_17);
952 $i++;
955 $password ^= strlen($plaintext);
956 $password ^= 0xCE4B;
958 return($password);
961 /******************************************************************************
962 *******************************************************************************
964 * BIFF RECORDS
969 * Write a double to the specified row and column (zero indexed).
970 * An integer can be written as a double. Excel will display an
971 * integer. $format is optional.
973 * Returns 0 : normal termination
974 * -2 : row or column out of range
976 * @access public
977 * @param integer $row Zero indexed row
978 * @param integer $col Zero indexed column
979 * @param float $num The number to write
980 * @param mixed $format The optional XF format
982 function write_number($row, $col, $num, $format = 0)
984 $record = 0x0203; // Record identifier
985 $length = 0x000E; // Number of bytes to follow
986 $xf = $this->_XF($format); // The cell format
988 // Check that row and col are valid and store max and min values
989 if ($row >= $this->xls_rowmax)
991 return(-2);
993 if ($col >= $this->xls_colmax)
995 return(-2);
997 if ($row < $this->dim_rowmin)
999 $this->dim_rowmin = $row;
1001 if ($row > $this->dim_rowmax)
1003 $this->dim_rowmax = $row;
1005 if ($col < $this->dim_colmin)
1007 $this->dim_colmin = $col;
1009 if ($col > $this->dim_colmax)
1011 $this->dim_colmax = $col;
1014 $header = pack("vv", $record, $length);
1015 $data = pack("vvv", $row, $col, $xf);
1016 $xl_double = pack("d", $num);
1017 if ($this->_byte_order) // if it's Big Endian
1019 $xl_double = strrev($xl_double);
1022 $this->_append($header.$data.$xl_double);
1023 return(0);
1027 * Write a string to the specified row and column (zero indexed).
1028 * NOTE: there is an Excel 5 defined limit of 255 characters.
1029 * $format is optional.
1030 * Returns 0 : normal termination
1031 * -1 : insufficient number of arguments
1032 * -2 : row or column out of range
1033 * -3 : long string truncated to 255 chars
1035 * @access public
1036 * @param integer $row Zero indexed row
1037 * @param integer $col Zero indexed column
1038 * @param string $str The string to write
1039 * @param mixed $format The XF format for the cell
1041 function write_string($row, $col, $str, $format = 0)
1043 $strlen = strlen($str);
1044 $record = 0x0204; // Record identifier
1045 $length = 0x0008 + $strlen; // Bytes to follow
1046 $xf = $this->_XF($format); // The cell format
1048 $str_error = 0;
1050 // Check that row and col are valid and store max and min values
1051 if ($row >= $this->xls_rowmax)
1053 return(-2);
1055 if ($col >= $this->xls_colmax)
1057 return(-2);
1059 if ($row < $this->dim_rowmin)
1061 $this->dim_rowmin = $row;
1063 if ($row > $this->dim_rowmax)
1065 $this->dim_rowmax = $row;
1067 if ($col < $this->dim_colmin)
1069 $this->dim_colmin = $col;
1071 if ($col > $this->dim_colmax)
1073 $this->dim_colmax = $col;
1076 if ($strlen > $this->xls_strmax) // LABEL must be < 255 chars
1078 $str = substr($str, 0, $this->xls_strmax);
1079 $length = 0x0008 + $this->xls_strmax;
1080 $strlen = $this->xls_strmax;
1081 $str_error = -3;
1084 $header = pack("vv", $record, $length);
1085 $data = pack("vvvv", $row, $col, $xf, $strlen);
1086 $this->_append($header.$data.$str);
1087 return($str_error);
1091 * Writes a note associated with the cell given by the row and column.
1092 * NOTE records don't have a length limit.
1094 * @access public
1095 * @param integer $row Zero indexed row
1096 * @param integer $col Zero indexed column
1097 * @param string $note The note to write
1099 function write_note($row, $col, $note)
1101 $note_length = strlen($note);
1102 $record = 0x001C; // Record identifier
1103 $max_length = 2048; // Maximun length for a NOTE record
1104 //$length = 0x0006 + $note_length; // Bytes to follow
1106 // Check that row and col are valid and store max and min values
1107 if ($row >= $this->xls_rowmax)
1109 return(-2);
1111 if ($col >= $this->xls_colmax)
1113 return(-2);
1115 if ($row < $this->dim_rowmin)
1117 $this->dim_rowmin = $row;
1119 if ($row > $this->dim_rowmax)
1121 $this->dim_rowmax = $row;
1123 if ($col < $this->dim_colmin)
1125 $this->dim_colmin = $col;
1127 if ($col > $this->dim_colmax)
1129 $this->dim_colmax = $col;
1132 // Length for this record is no more than 2048 + 6
1133 $length = 0x0006 + min($note_length, 2048);
1134 $header = pack("vv", $record, $length);
1135 $data = pack("vvv", $row, $col, $note_length);
1136 $this->_append($header.$data.substr($note, 0, 2048));
1138 for($i = $max_length; $i < $note_length; $i += $max_length)
1140 $chunk = substr($note, $i, $max_length);
1141 $length = 0x0006 + strlen($chunk);
1142 $header = pack("vv", $record, $length);
1143 $data = pack("vvv", -1, 0, strlen($chunk));
1144 $this->_append($header.$data.$chunk);
1146 return(0);
1150 * Write a blank cell to the specified row and column (zero indexed).
1151 * A blank cell is used to specify formatting without adding a string
1152 * or a number.
1154 * A blank cell without a format serves no purpose. Therefore, we don't write
1155 * a BLANK record unless a format is specified. This is mainly an optimisation
1156 * for the write_row() and write_col() methods.
1158 * Returns 0 : normal termination (including no format)
1159 * -1 : insufficient number of arguments
1160 * -2 : row or column out of range
1162 * @access public
1163 * @param integer $row Zero indexed row
1164 * @param integer $col Zero indexed column
1165 * @param mixed $format The XF format
1167 function write_blank($row, $col, $format = 0)
1169 // Don't write a blank cell unless it has a format
1170 if ($format == 0)
1172 return(0);
1175 $record = 0x0201; // Record identifier
1176 $length = 0x0006; // Number of bytes to follow
1177 $xf = $this->_XF($format); // The cell format
1179 // Check that row and col are valid and store max and min values
1180 if ($row >= $this->xls_rowmax)
1182 return(-2);
1184 if ($col >= $this->xls_colmax)
1186 return(-2);
1188 if ($row < $this->dim_rowmin)
1190 $this->dim_rowmin = $row;
1192 if ($row > $this->dim_rowmax)
1194 $this->dim_rowmax = $row;
1196 if ($col < $this->dim_colmin)
1198 $this->dim_colmin = $col;
1200 if ($col > $this->dim_colmax)
1202 $this->dim_colmax = $col;
1205 $header = pack("vv", $record, $length);
1206 $data = pack("vvv", $row, $col, $xf);
1207 $this->_append($header.$data);
1208 return 0;
1212 * Write a formula to the specified row and column (zero indexed).
1213 * The textual representation of the formula is passed to the parser in
1214 * Parser.php which returns a packed binary string.
1216 * Returns 0 : normal termination
1217 * -2 : row or column out of range
1219 * @access public
1220 * @param integer $row Zero indexed row
1221 * @param integer $col Zero indexed column
1222 * @param string $formula The formula text string
1223 * @param mixed $format The optional XF format
1225 function write_formula($row, $col, $formula, $format = 0)
1227 $record = 0x0006; // Record identifier
1229 // Excel normally stores the last calculated value of the formula in $num.
1230 // Clearly we are not in a position to calculate this a priori. Instead
1231 // we set $num to zero and set the option flags in $grbit to ensure
1232 // automatic calculation of the formula when the file is opened.
1234 $xf = $this->_XF($format); // The cell format
1235 $num = 0x00; // Current value of formula
1236 $grbit = 0x03; // Option flags
1237 $chn = 0x0000; // Must be zero
1240 // Check that row and col are valid and store max and min values
1241 if ($row >= $this->xls_rowmax)
1243 return(-2);
1245 if ($col >= $this->xls_colmax)
1247 return(-2);
1249 if ($row < $this->dim_rowmin)
1251 $this->dim_rowmin = $row;
1253 if ($row > $this->dim_rowmax)
1255 $this->dim_rowmax = $row;
1257 if ($col < $this->dim_colmin)
1259 $this->dim_colmin = $col;
1261 if ($col > $this->dim_colmax)
1263 $this->dim_colmax = $col;
1266 // Strip the '=' or '@' sign at the beginning of the formula string
1267 if (preg_match("/^=/",$formula)) {
1268 $formula = preg_replace("/(^=)/","",$formula);
1270 elseif(preg_match("/^@/",$formula)) {
1271 $formula = preg_replace("/(^@)/","",$formula);
1273 else {
1274 die("Unrecognised character for formula");
1277 // Parse the formula using the parser in Parser.php
1278 //$tree = new Parser($this->_byte_order);
1279 $this->_parser->parse($formula);
1280 //$tree->parse($formula);
1281 $formula = $this->_parser->to_reverse_polish();
1283 $formlen = strlen($formula); // Length of the binary string
1284 $length = 0x16 + $formlen; // Length of the record data
1286 $header = pack("vv", $record, $length);
1287 $data = pack("vvvdvVv", $row, $col, $xf, $num,
1288 $grbit, $chn, $formlen);
1290 $this->_append($header.$data.$formula);
1291 return 0;
1295 * Write a hyperlink. This is comprised of two elements: the visible label and
1296 * the invisible link. The visible label is the same as the link unless an
1297 * alternative string is specified. The label is written using the
1298 * write_string() method. Therefore the 255 characters string limit applies.
1299 * $string and $format are optional and their order is interchangeable.
1301 * The hyperlink can be to a http, ftp, mail, internal sheet, or external
1302 * directory url.
1304 * Returns 0 : normal termination
1305 * -1 : insufficient number of arguments
1306 * -2 : row or column out of range
1307 * -3 : long string truncated to 255 chars
1309 * @access public
1310 * @param integer $row Row
1311 * @param integer $col Column
1312 * @param string $url URL string
1313 * @param string $string Alternative label
1314 * @param mixed $format The cell format
1316 function write_url($row, $col, $url, $string = '', $format = 0)
1318 // Add start row and col to arg list
1319 return($this->_write_url_range($row, $col, $row, $col, $url, $string, $format));
1323 * This is the more general form of write_url(). It allows a hyperlink to be
1324 * written to a range of cells. This function also decides the type of hyperlink
1325 * to be written. These are either, Web (http, ftp, mailto), Internal
1326 * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
1328 * See also write_url() above for a general description and return values.
1330 * @param integer $row1 Start row
1331 * @param integer $col1 Start column
1332 * @param integer $row2 End row
1333 * @param integer $col2 End column
1334 * @param string $url URL string
1335 * @param string $string Alternative label
1336 * @param mixed $format The cell format
1339 function _write_url_range($row1, $col1, $row2, $col2, $url, $string = '', $format = 0)
1341 // Check for internal/external sheet links or default to web link
1342 if (preg_match('[^internal:]', $url)) {
1343 return($this->_write_url_internal($row1, $col1, $row2, $col2, $url, $string, $format));
1345 if (preg_match('[^external:]', $url)) {
1346 return($this->_write_url_external($row1, $col1, $row2, $col2, $url, $string, $format));
1348 return($this->_write_url_web($row1, $col1, $row2, $col2, $url, $string, $format));
1353 * Used to write http, ftp and mailto hyperlinks.
1354 * The link type ($options) is 0x03 is the same as absolute dir ref without
1355 * sheet. However it is differentiated by the $unknown2 data stream.
1357 * @see write_url()
1358 * @param integer $row1 Start row
1359 * @param integer $col1 Start column
1360 * @param integer $row2 End row
1361 * @param integer $col2 End column
1362 * @param string $url URL string
1363 * @param string $str Alternative label
1364 * @param mixed $format The cell format
1366 function _write_url_web($row1, $col1, $row2, $col2, $url, $str, $format = 0)
1368 $record = 0x01B8; // Record identifier
1369 $length = 0x00000; // Bytes to follow
1371 if($format == 0) {
1372 $format = $this->_url_format;
1375 // Write the visible label using the write_string() method.
1376 if($str == '') {
1377 $str = $url;
1379 $str_error = $this->write_string($row1, $col1, $str, $format);
1380 if ($str_error == -2) {
1381 return($str_error);
1384 // Pack the undocumented parts of the hyperlink stream
1385 $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
1386 $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
1388 // Pack the option flags
1389 $options = pack("V", 0x03);
1391 // Convert URL to a null terminated wchar string
1392 $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
1393 $url = $url . "\0\0\0";
1395 // Pack the length of the URL
1396 $url_len = pack("V", strlen($url));
1398 // Calculate the data length
1399 $length = 0x34 + strlen($url);
1401 // Pack the header data
1402 $header = pack("vv", $record, $length);
1403 $data = pack("vvvv", $row1, $row2, $col1, $col2);
1405 // Write the packed data
1406 $this->_append( $header. $data.
1407 $unknown1. $options.
1408 $unknown2. $url_len. $url);
1409 return($str_error);
1413 * Used to write internal reference hyperlinks such as "Sheet1!A1".
1415 * @see write_url()
1416 * @param integer $row1 Start row
1417 * @param integer $col1 Start column
1418 * @param integer $row2 End row
1419 * @param integer $col2 End column
1420 * @param string $url URL string
1421 * @param string $str Alternative label
1422 * @param mixed $format The cell format
1424 function _write_url_internal($row1, $col1, $row2, $col2, $url, $str, $format = 0)
1426 $record = 0x01B8; // Record identifier
1427 $length = 0x00000; // Bytes to follow
1429 if ($format == 0) {
1430 $format = $this->_url_format;
1433 // Strip URL type
1434 $url = preg_replace('s[^internal:]', '', $url);
1436 // Write the visible label
1437 if($str == '') {
1438 $str = $url;
1440 $str_error = $this->write_string($row1, $col1, $str, $format);
1441 if ($str_error == -2) {
1442 return($str_error);
1445 // Pack the undocumented parts of the hyperlink stream
1446 $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
1448 // Pack the option flags
1449 $options = pack("V", 0x08);
1451 // Convert the URL type and to a null terminated wchar string
1452 $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
1453 $url = $url . "\0\0\0";
1455 // Pack the length of the URL as chars (not wchars)
1456 $url_len = pack("V", floor(strlen($url)/2));
1458 // Calculate the data length
1459 $length = 0x24 + strlen($url);
1461 // Pack the header data
1462 $header = pack("vv", $record, $length);
1463 $data = pack("vvvv", $row1, $row2, $col1, $col2);
1465 // Write the packed data
1466 $this->_append($header. $data.
1467 $unknown1. $options.
1468 $url_len. $url);
1469 return($str_error);
1473 * Write links to external directory names such as 'c:\foo.xls',
1474 * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
1476 * Note: Excel writes some relative links with the $dir_long string. We ignore
1477 * these cases for the sake of simpler code.
1479 * @see write_url()
1480 * @param integer $row1 Start row
1481 * @param integer $col1 Start column
1482 * @param integer $row2 End row
1483 * @param integer $col2 End column
1484 * @param string $url URL string
1485 * @param string $str Alternative label
1486 * @param mixed $format The cell format
1488 function _write_url_external($row1, $col1, $row2, $col2, $url, $str, $format = 0)
1490 // Network drives are different. We will handle them separately
1491 // MS/Novell network drives and shares start with \\
1492 if (preg_match('[^external:\\\\]', $url)) {
1493 return($this->_write_url_external_net($row1, $col1, $row2, $col2, $url, $str, $format));
1496 $record = 0x01B8; // Record identifier
1497 $length = 0x00000; // Bytes to follow
1499 if ($format == 0) {
1500 $format = $this->_url_format;
1503 // Strip URL type and change Unix dir separator to Dos style (if needed)
1505 $url = preg_replace('[^external:]', '', $url);
1506 $url = preg_replace('[/]', "\\", $url);
1508 // Write the visible label
1509 if ($str == '') {
1510 $str = preg_replace('[\#]', ' - ', $url);
1512 $str_error = $this->write_string($row1, $col1, $str, $format);
1513 if ($str_error == -2) {
1514 return($str_error);
1517 // Determine if the link is relative or absolute:
1518 // relative if link contains no dir separator, "somefile.xls"
1519 // relative if link starts with up-dir, "..\..\somefile.xls"
1520 // otherwise, absolute
1522 $absolute = 0x02; // Bit mask
1523 if (!preg_match('[\\]', $url)) {
1524 $absolute = 0x00;
1526 if (preg_match('[^\.\.\\]', $url)) {
1527 $absolute = 0x00;
1530 // Determine if the link contains a sheet reference and change some of the
1531 // parameters accordingly.
1532 // Split the dir name and sheet name (if it exists)
1533 list($dir_long , $sheet) = explode('/#/', $url);
1534 $link_type = 0x01 | $absolute;
1536 if (isset($sheet)) {
1537 $link_type |= 0x08;
1538 $sheet_len = pack("V", strlen($sheet) + 0x01);
1539 $sheet = join("\0", str_split($sheet));
1540 $sheet .= "\0\0\0";
1542 else {
1543 $sheet_len = '';
1544 $sheet = '';
1547 // Pack the link type
1548 $link_type = pack("V", $link_type);
1550 // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
1551 $up_count = preg_match_all("/\.\.\\/", $dir_long, $useless);
1552 $up_count = pack("v", $up_count);
1554 // Store the short dos dir name (null terminated)
1555 $dir_short = preg_replace('/\.\.\\/', '', $dir_long) . "\0";
1557 // Store the long dir name as a wchar string (non-null terminated)
1558 $dir_long = join("\0", str_split($dir_long));
1559 $dir_long = $dir_long . "\0";
1561 // Pack the lengths of the dir strings
1562 $dir_short_len = pack("V", strlen($dir_short) );
1563 $dir_long_len = pack("V", strlen($dir_long) );
1564 $stream_len = pack("V", strlen($dir_long) + 0x06);
1566 // Pack the undocumented parts of the hyperlink stream
1567 $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
1568 $unknown2 = pack("H*",'0303000000000000C000000000000046' );
1569 $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
1570 $unknown4 = pack("v", 0x03 );
1572 // Pack the main data stream
1573 $data = pack("vvvv", $row1, $row2, $col1, $col2) .
1574 $unknown1 .
1575 $link_type .
1576 $unknown2 .
1577 $up_count .
1578 $dir_short_len.
1579 $dir_short .
1580 $unknown3 .
1581 $stream_len .
1582 $dir_long_len .
1583 $unknown4 .
1584 $dir_long .
1585 $sheet_len .
1586 $sheet ;
1588 // Pack the header data
1589 $length = strlen($data);
1590 $header = pack("vv", $record, $length);
1592 // Write the packed data
1593 $this->_append($header. $data);
1594 return($str_error);
1599 ###############################################################################
1601 # write_url_xxx($row1, $col1, $row2, $col2, $url, $string, $format)
1603 # Write links to external MS/Novell network drives and shares such as
1604 # '//NETWORK/share/foo.xls' and '//NETWORK/share/foo.xls#Sheet1!A1'.
1606 # See also write_url() above for a general description and return values.
1608 sub _write_url_external_net {
1610 my $this = shift;
1612 my $record = 0x01B8; # Record identifier
1613 my $length = 0x00000; # Bytes to follow
1615 my $row1 = $_[0]; # Start row
1616 my $col1 = $_[1]; # Start column
1617 my $row2 = $_[2]; # End row
1618 my $col2 = $_[3]; # End column
1619 my $url = $_[4]; # URL string
1620 my $str = $_[5]; # Alternative label
1621 my $xf = $_[6] || $this->{_url_format};# The cell format
1624 # Strip URL type and change Unix dir separator to Dos style (if needed)
1626 $url =~ s[^external:][];
1627 $url =~ s[/][\\]g;
1630 # Write the visible label
1631 ($str = $url) =~ s[\#][ - ] unless defined $str;
1632 my $str_error = $this->write_string($row1, $col1, $str, $xf);
1633 return $str_error if $str_error == -2;
1636 # Determine if the link contains a sheet reference and change some of the
1637 # parameters accordingly.
1638 # Split the dir name and sheet name (if it exists)
1640 my ($dir_long , $sheet) = split /\#/, $url;
1641 my $link_type = 0x0103; # Always absolute
1642 my $sheet_len;
1644 if (defined $sheet) {
1645 $link_type |= 0x08;
1646 $sheet_len = pack("V", length($sheet) + 0x01);
1647 $sheet = join("\0", str_split($sheet));
1648 $sheet .= "\0\0\0";
1650 else {
1651 $sheet_len = '';
1652 $sheet = '';
1655 # Pack the link type
1656 $link_type = pack("V", $link_type);
1659 # Make the string null terminated
1660 $dir_long = $dir_long . "\0";
1663 # Pack the lengths of the dir string
1664 my $dir_long_len = pack("V", length $dir_long);
1667 # Store the long dir name as a wchar string (non-null terminated)
1668 $dir_long = join("\0", str_split($dir_long));
1669 $dir_long = $dir_long . "\0";
1672 # Pack the undocumented part of the hyperlink stream
1673 my $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000');
1676 # Pack the main data stream
1677 my $data = pack("vvvv", $row1, $row2, $col1, $col2) .
1678 $unknown1 .
1679 $link_type .
1680 $dir_long_len .
1681 $dir_long .
1682 $sheet_len .
1683 $sheet ;
1686 # Pack the header data
1687 $length = length $data;
1688 my $header = pack("vv", $record, $length);
1691 # Write the packed data
1692 $this->_append( $header, $data);
1694 return $str_error;
1698 * This method is used to set the height and XF format for a row.
1699 * Writes the BIFF record ROW.
1701 * @access public
1702 * @param integer $row The row to set
1703 * @param integer $height Height we are giving to the row.
1704 * Use NULL to set XF without setting height
1705 * @param mixed $format XF format we are giving to the row
1707 function set_row($row, $height, $format = 0)
1709 $record = 0x0208; // Record identifier
1710 $length = 0x0010; // Number of bytes to follow
1712 $colMic = 0x0000; // First defined column
1713 $colMac = 0x0000; // Last defined column
1714 $irwMac = 0x0000; // Used by Excel to optimise loading
1715 $reserved = 0x0000; // Reserved
1716 $grbit = 0x01C0; // Option flags. (monkey) see $1 do
1717 $ixfe = $this->_XF($format); // XF index
1719 // Use set_row($row, NULL, $XF) to set XF without setting height
1720 if ($height != NULL) {
1721 $miyRw = $height * 20; // row height
1723 else {
1724 $miyRw = 0xff; // default row height is 256
1727 $header = pack("vv", $record, $length);
1728 $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
1729 $irwMac,$reserved, $grbit, $ixfe);
1730 $this->_append($header.$data);
1734 * Writes Excel DIMENSIONS to define the area in which there is data.
1736 function _store_dimensions()
1738 $record = 0x0000; // Record identifier
1739 $length = 0x000A; // Number of bytes to follow
1740 $row_min = $this->dim_rowmin; // First row
1741 $row_max = $this->dim_rowmax; // Last row plus 1
1742 $col_min = $this->dim_colmin; // First column
1743 $col_max = $this->dim_colmax; // Last column plus 1
1744 $reserved = 0x0000; // Reserved by Excel
1746 $header = pack("vv", $record, $length);
1747 $data = pack("vvvvv", $row_min, $row_max,
1748 $col_min, $col_max, $reserved);
1749 $this->_prepend($header.$data);
1753 * Write BIFF record Window2.
1755 function _store_window2()
1757 $record = 0x023E; // Record identifier
1758 $length = 0x000A; // Number of bytes to follow
1760 $grbit = 0x00B6; // Option flags
1761 $rwTop = 0x0000; // Top row visible in window
1762 $colLeft = 0x0000; // Leftmost column visible in window
1763 $rgbHdr = 0x00000000; // Row/column heading and gridline color
1765 // The options flags that comprise $grbit
1766 $fDspFmla = 0; // 0 - bit
1767 $fDspGrid = 1; // 1
1768 $fDspRwCol = 1; // 2
1769 $fFrozen = $this->_frozen; // 3
1770 $fDspZeros = 1; // 4
1771 $fDefaultHdr = 1; // 5
1772 $fArabic = 0; // 6
1773 $fDspGuts = 1; // 7
1774 $fFrozenNoSplit = 0; // 0 - bit
1775 $fSelected = $this->selected; // 1
1776 $fPaged = 1; // 2
1778 $grbit = $fDspFmla;
1779 $grbit |= $fDspGrid << 1;
1780 $grbit |= $fDspRwCol << 2;
1781 $grbit |= $fFrozen << 3;
1782 $grbit |= $fDspZeros << 4;
1783 $grbit |= $fDefaultHdr << 5;
1784 $grbit |= $fArabic << 6;
1785 $grbit |= $fDspGuts << 7;
1786 $grbit |= $fFrozenNoSplit << 8;
1787 $grbit |= $fSelected << 9;
1788 $grbit |= $fPaged << 10;
1790 $header = pack("vv", $record, $length);
1791 $data = pack("vvvV", $grbit, $rwTop, $colLeft, $rgbHdr);
1792 $this->_append($header.$data);
1796 * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
1798 function _store_defcol()
1800 $record = 0x0055; // Record identifier
1801 $length = 0x0002; // Number of bytes to follow
1802 $colwidth = 0x0008; // Default column width
1804 $header = pack("vv", $record, $length);
1805 $data = pack("v", $colwidth);
1806 $this->_prepend($header.$data);
1810 * Write BIFF record COLINFO to define column widths
1812 * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
1813 * length record.
1815 * @param array $col_array This is the only parameter received and is composed of the following:
1816 * 0 => First formatted column,
1817 * 1 => Last formatted column,
1818 * 2 => Col width (8.43 is Excel default),
1819 * 3 => The optional XF format of the column,
1820 * 4 => Option flags.
1822 function _store_colinfo($col_array)
1824 if(isset($col_array[0])) {
1825 $colFirst = $col_array[0];
1827 if(isset($col_array[1])) {
1828 $colLast = $col_array[1];
1830 if(isset($col_array[2])) {
1831 $coldx = $col_array[2];
1833 else {
1834 $coldx = 8.43;
1836 if(isset($col_array[3])) {
1837 $format = $col_array[3];
1839 else {
1840 $format = 0;
1842 if(isset($col_array[4])) {
1843 $grbit = $col_array[4];
1845 else {
1846 $grbit = 0;
1848 $record = 0x007D; // Record identifier
1849 $length = 0x000B; // Number of bytes to follow
1851 $coldx += 0.72; // Fudge. Excel subtracts 0.72 !?
1852 $coldx *= 256; // Convert to units of 1/256 of a char
1854 $ixfe = $this->_XF($format);
1855 $reserved = 0x00; // Reserved
1857 $header = pack("vv", $record, $length);
1858 $data = pack("vvvvvC", $colFirst, $colLast, $coldx,
1859 $ixfe, $grbit, $reserved);
1860 $this->_prepend($header.$data);
1864 * Write BIFF record SELECTION.
1866 * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast)
1867 * @see set_selection()
1869 function _store_selection($array)
1871 list($rwFirst,$colFirst,$rwLast,$colLast) = $array;
1872 $record = 0x001D; // Record identifier
1873 $length = 0x000F; // Number of bytes to follow
1875 $pnn = $this->_active_pane; // Pane position
1876 $rwAct = $rwFirst; // Active row
1877 $colAct = $colFirst; // Active column
1878 $irefAct = 0; // Active cell ref
1879 $cref = 1; // Number of refs
1881 if (!isset($rwLast)) {
1882 $rwLast = $rwFirst; // Last row in reference
1884 if (!isset($colLast)) {
1885 $colLast = $colFirst; // Last col in reference
1888 // Swap last row/col for first row/col as necessary
1889 if ($rwFirst > $rwLast)
1891 list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
1894 if ($colFirst > $colLast)
1896 list($colFirst, $colLast) = array($colLast, $colFirst);
1899 $header = pack("vv", $record, $length);
1900 $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
1901 $irefAct, $cref,
1902 $rwFirst, $rwLast,
1903 $colFirst, $colLast);
1904 $this->_append($header.$data);
1909 * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
1910 * references in a worksheet.
1912 * Excel only stores references to external sheets that are used in formulas.
1913 * For simplicity we store references to all the sheets in the workbook
1914 * regardless of whether they are used or not. This reduces the overall
1915 * complexity and eliminates the need for a two way dialogue between the formula
1916 * parser the worksheet objects.
1918 * @param integer $count The number of external sheet references in this worksheet
1920 function _store_externcount($count)
1922 $record = 0x0016; // Record identifier
1923 $length = 0x0002; // Number of bytes to follow
1925 $header = pack("vv", $record, $length);
1926 $data = pack("v", $count);
1927 $this->_prepend($header.$data);
1931 * Writes the Excel BIFF EXTERNSHEET record. These references are used by
1932 * formulas. A formula references a sheet name via an index. Since we store a
1933 * reference to all of the external worksheets the EXTERNSHEET index is the same
1934 * as the worksheet index.
1936 * @param string $sheetname The name of a external worksheet
1938 function _store_externsheet($sheetname)
1940 $record = 0x0017; // Record identifier
1942 // References to the current sheet are encoded differently to references to
1943 // external sheets.
1945 if ($this->name == $sheetname) {
1946 $sheetname = '';
1947 $length = 0x02; // The following 2 bytes
1948 $cch = 1; // The following byte
1949 $rgch = 0x02; // Self reference
1951 else {
1952 $length = 0x02 + strlen($sheetname);
1953 $cch = strlen($sheetname);
1954 $rgch = 0x03; // Reference to a sheet in the current workbook
1957 $header = pack("vv", $record, $length);
1958 $data = pack("CC", $cch, $rgch);
1959 $this->_prepend($header.$data.$sheetname);
1963 * Writes the Excel BIFF PANE record.
1964 * The panes can either be frozen or thawed (unfrozen).
1965 * Frozen panes are specified in terms of an integer number of rows and columns.
1966 * Thawed panes are specified in terms of Excel's units for rows and columns.
1968 * @param array $panes This is the only parameter received and is composed of the following:
1969 * 0 => Vertical split position,
1970 * 1 => Horizontal split position
1971 * 2 => Top row visible
1972 * 3 => Leftmost column visible
1973 * 4 => Active pane
1975 function _store_panes($panes)
1977 $y = $panes[0];
1978 $x = $panes[1];
1979 $rwTop = $panes[2];
1980 $colLeft = $panes[3];
1981 if(count($panes) > 4) { // if Active pane was received
1982 $pnnAct = $panes[4];
1984 else {
1985 $pnnAct = NULL;
1987 $record = 0x0041; // Record identifier
1988 $length = 0x000A; // Number of bytes to follow
1990 // Code specific to frozen or thawed panes.
1991 if ($this->_frozen) {
1992 // Set default values for $rwTop and $colLeft
1993 if(!isset($rwTop)) {
1994 $rwTop = $y;
1996 if(!isset($colLeft)) {
1997 $colLeft = $x;
2000 else {
2001 // Set default values for $rwTop and $colLeft
2002 if(!isset($rwTop)) {
2003 $rwTop = 0;
2005 if(!isset($colLeft)) {
2006 $colLeft = 0;
2009 // Convert Excel's row and column units to the internal units.
2010 // The default row height is 12.75
2011 // The default column width is 8.43
2012 // The following slope and intersection values were interpolated.
2014 $y = 20*$y + 255;
2015 $x = 113.879*$x + 390;
2019 // Determine which pane should be active. There is also the undocumented
2020 // option to override this should it be necessary: may be removed later.
2022 if (!isset($pnnAct))
2024 if ($x != 0 and $y != 0)
2025 $pnnAct = 0; // Bottom right
2026 if ($x != 0 and $y == 0)
2027 $pnnAct = 1; // Top right
2028 if ($x == 0 and $y != 0)
2029 $pnnAct = 2; // Bottom left
2030 if ($x == 0 and $y == 0)
2031 $pnnAct = 3; // Top left
2034 $this->_active_pane = $pnnAct; // Used in _store_selection
2036 $header = pack("vv", $record, $length);
2037 $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
2038 $this->_append($header.$data);
2042 * Store the page setup SETUP BIFF record.
2044 function _store_setup()
2046 $record = 0x00A1; // Record identifier
2047 $length = 0x0022; // Number of bytes to follow
2049 $iPaperSize = $this->_paper_size; // Paper size
2050 $iScale = $this->_print_scale; // Print scaling factor
2051 $iPageStart = 0x01; // Starting page number
2052 $iFitWidth = $this->_fit_width; // Fit to number of pages wide
2053 $iFitHeight = $this->_fit_height; // Fit to number of pages high
2054 $grbit = 0x00; // Option flags
2055 $iRes = 0x0258; // Print resolution
2056 $iVRes = 0x0258; // Vertical print resolution
2057 $numHdr = $this->_margin_head; // Header Margin
2058 $numFtr = $this->_margin_foot; // Footer Margin
2059 $iCopies = 0x01; // Number of copies
2061 $fLeftToRight = 0x0; // Print over then down
2062 $fLandscape = $this->_orientation; // Page orientation
2063 $fNoPls = 0x0; // Setup not read from printer
2064 $fNoColor = 0x0; // Print black and white
2065 $fDraft = 0x0; // Print draft quality
2066 $fNotes = 0x0; // Print notes
2067 $fNoOrient = 0x0; // Orientation not set
2068 $fUsePage = 0x0; // Use custom starting page
2070 $grbit = $fLeftToRight;
2071 $grbit |= $fLandscape << 1;
2072 $grbit |= $fNoPls << 2;
2073 $grbit |= $fNoColor << 3;
2074 $grbit |= $fDraft << 4;
2075 $grbit |= $fNotes << 5;
2076 $grbit |= $fNoOrient << 6;
2077 $grbit |= $fUsePage << 7;
2079 $numHdr = pack("d", $numHdr);
2080 $numFtr = pack("d", $numFtr);
2081 if ($this->_byte_order) // if it's Big Endian
2083 $numHdr = strrev($numHdr);
2084 $numFtr = strrev($numFtr);
2087 $header = pack("vv", $record, $length);
2088 $data1 = pack("vvvvvvvv", $iPaperSize,
2089 $iScale,
2090 $iPageStart,
2091 $iFitWidth,
2092 $iFitHeight,
2093 $grbit,
2094 $iRes,
2095 $iVRes);
2096 $data2 = $numHdr .$numFtr;
2097 $data3 = pack("v", $iCopies);
2098 $this->_prepend($header.$data1.$data2.$data3);
2102 * Store the header caption BIFF record.
2104 function store_header()
2106 $record = 0x0014; // Record identifier
2108 $str = $this->_header; // header string
2109 $cch = strlen($str); // Length of header string
2110 $length = 1 + $cch; // Bytes to follow
2112 $header = pack("vv", $record, $length);
2113 $data = pack("C", $cch);
2115 $this->_append($header.$data.$str);
2119 * Store the footer caption BIFF record.
2121 function store_footer()
2123 $record = 0x0015; // Record identifier
2125 $str = $this->_footer; // Footer string
2126 $cch = strlen($str); // Length of footer string
2127 $length = 1 + $cch; // Bytes to follow
2129 $header = pack("vv", $record, $length);
2130 $data = pack("C", $cch);
2132 $this->_append($header.$data.$str);
2136 * Store the horizontal centering HCENTER BIFF record.
2138 function store_hcenter()
2140 $record = 0x0083; // Record identifier
2141 $length = 0x0002; // Bytes to follow
2143 $fHCenter = $this->_hcenter; // Horizontal centering
2145 $header = pack("vv", $record, $length);
2146 $data = pack("v", $fHCenter);
2148 $this->_append($header.$data);
2152 * Store the vertical centering VCENTER BIFF record.
2154 function store_vcenter()
2156 $record = 0x0084; // Record identifier
2157 $length = 0x0002; // Bytes to follow
2159 $fVCenter = $this->_vcenter; // Horizontal centering
2161 $header = pack("vv", $record, $length);
2162 $data = pack("v", $fVCenter);
2163 $this->_append($header.$data);
2167 * Store the LEFTMARGIN BIFF record.
2169 function _store_margin_left()
2171 $record = 0x0026; // Record identifier
2172 $length = 0x0008; // Bytes to follow
2174 $margin = $this->_margin_left; // Margin in inches
2176 $header = pack("vv", $record, $length);
2177 $data = pack("d", $margin);
2178 if ($this->_byte_order) // if it's Big Endian
2180 $data = strrev($data);
2183 $this->_append($header.$data);
2187 * Store the RIGHTMARGIN BIFF record.
2189 function _store_margin_right()
2191 $record = 0x0027; // Record identifier
2192 $length = 0x0008; // Bytes to follow
2194 $margin = $this->_margin_right; // Margin in inches
2196 $header = pack("vv", $record, $length);
2197 $data = pack("d", $margin);
2198 if ($this->_byte_order) // if it's Big Endian
2200 $data = strrev($data);
2203 $this->_append($header.$data);
2207 * Store the TOPMARGIN BIFF record.
2209 function _store_margin_top()
2211 $record = 0x0028; // Record identifier
2212 $length = 0x0008; // Bytes to follow
2214 $margin = $this->_margin_top; // Margin in inches
2216 $header = pack("vv", $record, $length);
2217 $data = pack("d", $margin);
2218 if ($this->_byte_order) // if it's Big Endian
2220 $data = strrev($data);
2223 $this->_append($header.$data);
2227 * Store the BOTTOMMARGIN BIFF record.
2229 function _store_margin_bottom()
2231 $record = 0x0029; // Record identifier
2232 $length = 0x0008; // Bytes to follow
2234 $margin = $this->_margin_bottom; // Margin in inches
2236 $header = pack("vv", $record, $length);
2237 $data = pack("d", $margin);
2238 if ($this->_byte_order) // if it's Big Endian
2240 $data = strrev($data);
2243 $this->_append($header.$data);
2247 * This is an Excel97/2000 method. It is required to perform more complicated
2248 * merging than the normal set_align('merge'). It merges the area given by
2249 * its arguments.
2251 * @access public
2252 * @param integer $first_row First row of the area to merge
2253 * @param integer $first_col First column of the area to merge
2254 * @param integer $last_row Last row of the area to merge
2255 * @param integer $last_col Last column of the area to merge
2257 function merge_cells($first_row, $first_col, $last_row, $last_col)
2259 $record = 0x00E5; // Record identifier
2260 $length = 0x000A; // Bytes to follow
2261 $cref = 1; // Number of refs
2263 // Swap last row/col for first row/col as necessary
2264 if ($first_row > $last_row) {
2265 list($first_row, $last_row) = array($last_row, $first_row);
2268 if ($first_col > $last_col) {
2269 list($first_col, $last_col) = array($last_col, $first_col);
2272 $header = pack("vv", $record, $length);
2273 $data = pack("vvvvv", $cref, $first_row, $last_row,
2274 $first_col, $last_col);
2276 $this->_append($header.$data);
2280 * Write the PRINTHEADERS BIFF record.
2282 function _store_print_headers()
2284 $record = 0x002a; // Record identifier
2285 $length = 0x0002; // Bytes to follow
2287 $fPrintRwCol = $this->_print_headers; // Boolean flag
2289 $header = pack("vv", $record, $length);
2290 $data = pack("v", $fPrintRwCol);
2291 $this->_prepend($header.$data);
2295 * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
2296 * GRIDSET record.
2298 function _store_print_gridlines()
2300 $record = 0x002b; // Record identifier
2301 $length = 0x0002; // Bytes to follow
2303 $fPrintGrid = $this->_print_gridlines; // Boolean flag
2305 $header = pack("vv", $record, $length);
2306 $data = pack("v", $fPrintGrid);
2307 $this->_prepend($header.$data);
2311 * Write the GRIDSET BIFF record. Must be used in conjunction with the
2312 * PRINTGRIDLINES record.
2314 function _store_gridset()
2316 $record = 0x0082; // Record identifier
2317 $length = 0x0002; // Bytes to follow
2319 $fGridSet = !($this->_print_gridlines); // Boolean flag
2321 $header = pack("vv", $record, $length);
2322 $data = pack("v", $fGridSet);
2323 $this->_prepend($header.$data);
2327 * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
2328 * with the SETUP record.
2330 function _store_wsbool()
2332 $record = 0x0081; // Record identifier
2333 $length = 0x0002; // Bytes to follow
2335 // The only option that is of interest is the flag for fit to page. So we
2336 // set all the options in one go.
2338 if ($this->_fit_page) {
2339 $grbit = 0x05c1;
2341 else {
2342 $grbit = 0x04c1;
2345 $header = pack("vv", $record, $length);
2346 $data = pack("v", $grbit);
2347 $this->_prepend($header.$data);
2352 * Write the HORIZONTALPAGEBREAKS BIFF record.
2354 function _store_hbreak()
2356 // Return if the user hasn't specified pagebreaks
2357 if(empty($this->_hbreaks)) {
2358 return;
2361 // Sort and filter array of page breaks
2362 $breaks = $this->_hbreaks;
2363 sort($breaks,SORT_NUMERIC);
2364 if($breaks[0] == 0) { // don't use first break if it's 0
2365 array_shift($breaks);
2368 $record = 0x001b; // Record identifier
2369 $cbrk = count($breaks); // Number of page breaks
2370 $length = ($cbrk + 1) * 2; // Bytes to follow
2372 $header = pack("vv", $record, $length);
2373 $data = pack("v", $cbrk);
2375 // Append each page break
2376 foreach($breaks as $break) {
2377 $data .= pack("v", $break);
2380 $this->_prepend($header.$data);
2385 * Write the VERTICALPAGEBREAKS BIFF record.
2387 function _store_vbreak()
2389 // Return if the user hasn't specified pagebreaks
2390 if(empty($this->_vbreaks)) {
2391 return;
2394 // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
2395 // It is slightly higher in Excel 97/200, approx. 1026
2396 $breaks = array_slice($this->_vbreaks,0,1000);
2398 // Sort and filter array of page breaks
2399 sort($breaks,SORT_NUMERIC);
2400 if($breaks[0] == 0) { // don't use first break if it's 0
2401 array_shift($breaks);
2404 $record = 0x001a; // Record identifier
2405 $cbrk = count($breaks); // Number of page breaks
2406 $length = ($cbrk + 1) * 2; // Bytes to follow
2408 $header = pack("vv", $record, $length);
2409 $data = pack("v", $cbrk);
2411 // Append each page break
2412 foreach ($breaks as $break) {
2413 $data .= pack("v", $break);
2416 $this->_prepend($header.$data);
2420 * Set the Biff PROTECT record to indicate that the worksheet is protected.
2422 function _store_protect()
2424 // Exit unless sheet protection has been specified
2425 if($this->_protect == 0) {
2426 return;
2429 $record = 0x0012; // Record identifier
2430 $length = 0x0002; // Bytes to follow
2432 $fLock = $this->_protect; // Worksheet is protected
2434 $header = pack("vv", $record, $length);
2435 $data = pack("v", $fLock);
2437 $this->_prepend($header.$data);
2441 * Write the worksheet PASSWORD record.
2443 function _store_password()
2445 // Exit unless sheet protection and password have been specified
2446 if(($this->_protect == 0) or (!isset($this->_password))) {
2447 return;
2450 $record = 0x0013; // Record identifier
2451 $length = 0x0002; // Bytes to follow
2453 $wPassword = $this->_password; // Encoded password
2455 $header = pack("vv", $record, $length);
2456 $data = pack("v", $wPassword);
2458 $this->_prepend($header.$data);
2462 * Insert a 24bit bitmap image in a worksheet. The main record required is
2463 * IMDATA but it must be proceeded by a OBJ record to define its position.
2465 * @access public
2466 * @param integer $row The row we are going to insert the bitmap into
2467 * @param integer $col The column we are going to insert the bitmap into
2468 * @param string $bitmap The bitmap filename
2469 * @param integer $x The horizontal position (offset) of the image inside the cell.
2470 * @param integer $y The vertical position (offset) of the image inside the cell.
2471 * @param integer $scale_x The horizontal scale
2472 * @param integer $scale_y The vertical scale
2474 function insert_bitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
2476 list($width, $height, $size, $data) = $this->_process_bitmap($bitmap);
2478 // Scale the frame of the image.
2479 $width *= $scale_x;
2480 $height *= $scale_y;
2482 // Calculate the vertices of the image and write the OBJ record
2483 $this->_position_image($col, $row, $x, $y, $width, $height);
2485 // Write the IMDATA record to store the bitmap data
2486 $record = 0x007f;
2487 $length = 8 + $size;
2488 $cf = 0x09;
2489 $env = 0x01;
2490 $lcb = $size;
2492 $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
2493 $this->_append($header.$data);
2497 * Calculate the vertices that define the position of the image as required by
2498 * the OBJ record.
2500 * +------------+------------+
2501 * | A | B |
2502 * +-----+------------+------------+
2503 * | |(x1,y1) | |
2504 * | 1 |(A1)._______|______ |
2505 * | | | | |
2506 * | | | | |
2507 * +-----+----| BITMAP |-----+
2508 * | | | | |
2509 * | 2 | |______________. |
2510 * | | | (B2)|
2511 * | | | (x2,y2)|
2512 * +---- +------------+------------+
2514 * Example of a bitmap that covers some of the area from cell A1 to cell B2.
2516 * Based on the width and height of the bitmap we need to calculate 8 vars:
2517 * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
2518 * The width and height of the cells are also variable and have to be taken into
2519 * account.
2520 * The values of $col_start and $row_start are passed in from the calling
2521 * function. The values of $col_end and $row_end are calculated by subtracting
2522 * the width and height of the bitmap from the width and height of the
2523 * underlying cells.
2524 * The vertices are expressed as a percentage of the underlying cell width as
2525 * follows (rhs values are in pixels):
2527 * x1 = X / W *1024
2528 * y1 = Y / H *256
2529 * x2 = (X-1) / W *1024
2530 * y2 = (Y-1) / H *256
2532 * Where: X is distance from the left side of the underlying cell
2533 * Y is distance from the top of the underlying cell
2534 * W is the width of the cell
2535 * H is the height of the cell
2537 * @note the SDK incorrectly states that the height should be expressed as a
2538 * percentage of 1024.
2539 * @param integer $col_start Col containing upper left corner of object
2540 * @param integer $row_start Row containing top left corner of object
2541 * @param integer $x1 Distance to left side of object
2542 * @param integer $y1 Distance to top of object
2543 * @param integer $width Width of image frame
2544 * @param integer $height Height of image frame
2546 function _position_image($col_start, $row_start, $x1, $y1, $width, $height)
2548 // Initialise end cell to the same as the start cell
2549 $col_end = $col_start; // Col containing lower right corner of object
2550 $row_end = $row_start; // Row containing bottom right corner of object
2552 // Zero the specified offset if greater than the cell dimensions
2553 if ($x1 >= $this->size_col($col_start))
2555 $x1 = 0;
2557 if ($y1 >= $this->size_row($row_start))
2559 $y1 = 0;
2562 $width = $width + $x1 -1;
2563 $height = $height + $y1 -1;
2565 // Subtract the underlying cell widths to find the end cell of the image
2566 while ($width >= $this->size_col($col_end)) {
2567 $width -= $this->size_col($col_end);
2568 $col_end++;
2571 // Subtract the underlying cell heights to find the end cell of the image
2572 while ($height >= $this->size_row($row_end)) {
2573 $height -= $this->size_row($row_end);
2574 $row_end++;
2577 // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
2578 // with zero eight or width.
2580 if ($this->size_col($col_start) == 0)
2581 return;
2582 if ($this->size_col($col_end) == 0)
2583 return;
2584 if ($this->size_row($row_start) == 0)
2585 return;
2586 if ($this->size_row($row_end) == 0)
2587 return;
2589 // Convert the pixel values to the percentage value expected by Excel
2590 $x1 = $x1 / $this->size_col($col_start) * 1024;
2591 $y1 = $y1 / $this->size_row($row_start) * 256;
2592 $x2 = $width / $this->size_col($col_end) * 1024; // Distance to right side of object
2593 $y2 = $height / $this->size_row($row_end) * 256; // Distance to bottom of object
2595 $this->_store_obj_picture( $col_start, $x1,
2596 $row_start, $y1,
2597 $col_end, $x2,
2598 $row_end, $y2
2603 * Convert the width of a cell from user's units to pixels. By interpolation
2604 * the relationship is: y = 7x +5. If the width hasn't been set by the user we
2605 * use the default value. If the col is hidden we use a value of zero.
2607 * @param integer $col The column
2608 * @return integer The width in pixels
2610 function size_col($col)
2612 // Look up the cell value to see if it has been changed
2613 if (isset($this->col_sizes[$col])) {
2614 if ($this->col_sizes[$col] == 0) {
2615 return(0);
2617 else {
2618 return(floor(7 * $this->col_sizes[$col] + 5));
2621 else {
2622 return(64);
2627 * Convert the height of a cell from user's units to pixels. By interpolation
2628 * the relationship is: y = 4/3x. If the height hasn't been set by the user we
2629 * use the default value. If the row is hidden we use a value of zero. (Not
2630 * possible to hide row yet).
2632 * @param integer $row The row
2633 * @return integer The width in pixels
2635 function size_row($row)
2637 // Look up the cell value to see if it has been changed
2638 if (isset($this->row_sizes[$row])) {
2639 if ($this->row_sizes[$row] == 0) {
2640 return(0);
2642 else {
2643 return(floor(4/3 * $this->row_sizes[$row]));
2646 else {
2647 return(17);
2652 * Store the OBJ record that precedes an IMDATA record. This could be generalise
2653 * to support other Excel objects.
2655 * @param integer $colL Column containing upper left corner of object
2656 * @param integer $dxL Distance from left side of cell
2657 * @param integer $rwT Row containing top left corner of object
2658 * @param integer $dyT Distance from top of cell
2659 * @param integer $colR Column containing lower right corner of object
2660 * @param integer $dxR Distance from right of cell
2661 * @param integer $rwB Row containing bottom right corner of object
2662 * @param integer $dyB Distance from bottom of cell
2664 function _store_obj_picture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
2666 $record = 0x005d; // Record identifier
2667 $length = 0x003c; // Bytes to follow
2669 $cObj = 0x0001; // Count of objects in file (set to 1)
2670 $OT = 0x0008; // Object type. 8 = Picture
2671 $id = 0x0001; // Object ID
2672 $grbit = 0x0614; // Option flags
2674 $cbMacro = 0x0000; // Length of FMLA structure
2675 $Reserved1 = 0x0000; // Reserved
2676 $Reserved2 = 0x0000; // Reserved
2678 $icvBack = 0x09; // Background colour
2679 $icvFore = 0x09; // Foreground colour
2680 $fls = 0x00; // Fill pattern
2681 $fAuto = 0x00; // Automatic fill
2682 $icv = 0x08; // Line colour
2683 $lns = 0xff; // Line style
2684 $lnw = 0x01; // Line weight
2685 $fAutoB = 0x00; // Automatic border
2686 $frs = 0x0000; // Frame style
2687 $cf = 0x0009; // Image format, 9 = bitmap
2688 $Reserved3 = 0x0000; // Reserved
2689 $cbPictFmla = 0x0000; // Length of FMLA structure
2690 $Reserved4 = 0x0000; // Reserved
2691 $grbit2 = 0x0001; // Option flags
2692 $Reserved5 = 0x0000; // Reserved
2695 $header = pack("vv", $record, $length);
2696 $data = pack("V", $cObj);
2697 $data .= pack("v", $OT);
2698 $data .= pack("v", $id);
2699 $data .= pack("v", $grbit);
2700 $data .= pack("v", $colL);
2701 $data .= pack("v", $dxL);
2702 $data .= pack("v", $rwT);
2703 $data .= pack("v", $dyT);
2704 $data .= pack("v", $colR);
2705 $data .= pack("v", $dxR);
2706 $data .= pack("v", $rwB);
2707 $data .= pack("v", $dyB);
2708 $data .= pack("v", $cbMacro);
2709 $data .= pack("V", $Reserved1);
2710 $data .= pack("v", $Reserved2);
2711 $data .= pack("C", $icvBack);
2712 $data .= pack("C", $icvFore);
2713 $data .= pack("C", $fls);
2714 $data .= pack("C", $fAuto);
2715 $data .= pack("C", $icv);
2716 $data .= pack("C", $lns);
2717 $data .= pack("C", $lnw);
2718 $data .= pack("C", $fAutoB);
2719 $data .= pack("v", $frs);
2720 $data .= pack("V", $cf);
2721 $data .= pack("v", $Reserved3);
2722 $data .= pack("v", $cbPictFmla);
2723 $data .= pack("v", $Reserved4);
2724 $data .= pack("v", $grbit2);
2725 $data .= pack("V", $Reserved5);
2727 $this->_append($header.$data);
2731 * Convert a 24 bit bitmap into the modified internal format used by Windows.
2732 * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
2733 * MSDN library.
2735 * @param string $bitmap The bitmap to process
2736 * @return array Array with data and properties of the bitmap
2738 function _process_bitmap($bitmap)
2740 // Open file.
2741 $bmp_fd = fopen($bitmap,"rb");
2742 if (!$bmp_fd) {
2743 die("Couldn't import $bitmap");
2746 // Slurp the file into a string.
2747 $data = fread($bmp_fd, filesize($bitmap));
2749 // Check that the file is big enough to be a bitmap.
2750 if (strlen($data) <= 0x36) {
2751 die("$bitmap doesn't contain enough data.\n");
2754 // The first 2 bytes are used to identify the bitmap.
2755 $identity = unpack("A2", $data);
2756 if ($identity[''] != "BM") {
2757 die("$bitmap doesn't appear to be a valid bitmap image.\n");
2760 // Remove bitmap data: ID.
2761 $data = substr($data, 2);
2763 // Read and remove the bitmap size. This is more reliable than reading
2764 // the data size at offset 0x22.
2766 $size_array = unpack("V", substr($data, 0, 4));
2767 $size = $size_array[''];
2768 $data = substr($data, 4);
2769 $size -= 0x36; // Subtract size of bitmap header.
2770 $size += 0x0C; // Add size of BIFF header.
2772 // Remove bitmap data: reserved, offset, header length.
2773 $data = substr($data, 12);
2775 // Read and remove the bitmap width and height. Verify the sizes.
2776 $width_and_height = unpack("V2", substr($data, 0, 8));
2777 $width = $width_and_height[1];
2778 $height = $width_and_height[2];
2779 $data = substr($data, 8);
2780 if ($width > 0xFFFF) {
2781 die("$bitmap: largest image width supported is 65k.\n");
2783 if ($height > 0xFFFF) {
2784 die("$bitmap: largest image height supported is 65k.\n");
2787 // Read and remove the bitmap planes and bpp data. Verify them.
2788 $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
2789 $data = substr($data, 4);
2790 if ($planes_and_bitcount[2] != 24) { // Bitcount
2791 die("$bitmap isn't a 24bit true color bitmap.\n");
2793 if ($planes_and_bitcount[1] != 1) {
2794 die("$bitmap: only 1 plane supported in bitmap image.\n");
2797 // Read and remove the bitmap compression. Verify compression.
2798 $compression = unpack("V", substr($data, 0, 4));
2799 $data = substr($data, 4);
2801 //$compression = 0;
2802 if ($compression[""] != 0) {
2803 die("$bitmap: compression not supported in bitmap image.\n");
2806 // Remove bitmap data: data size, hres, vres, colours, imp. colours.
2807 $data = substr($data, 20);
2809 // Add the BITMAPCOREHEADER data
2810 $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
2811 $data = $header . $data;
2813 return (array($width, $height, $size, $data));
2817 * Store the window zoom factor. This should be a reduced fraction but for
2818 * simplicity we will store all fractions with a numerator of 100.
2820 function _store_zoom()
2822 // If scale is 100 we don't need to write a record
2823 if ($this->_zoom == 100) {
2824 return;
2827 $record = 0x00A0; // Record identifier
2828 $length = 0x0004; // Bytes to follow
2830 $header = pack("vv", $record, $length);
2831 $data = pack("vv", $this->_zoom, 100);
2832 $this->_append($header.$data);