PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/v1.6.3/Classes/PHPExcel/Writer/Excel5/Worksheet.php

#
PHP | 3573 lines | 1775 code | 433 blank | 1365 comment | 277 complexity | 50bcb82b48de4f778ad78b454d0de8f9 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.0, LGPL-2.1, GPL-3.0, LGPL-3.0
  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. require_once 'PHPExcel/Writer/Excel5/Parser.php';
  35. require_once 'PHPExcel/Writer/Excel5/BIFFwriter.php';
  36. /**
  37. * Class for generating Excel Spreadsheets
  38. *
  39. * @author Xavier Noguer <xnoguer@rezebra.com>
  40. * @category FileFormats
  41. * @package PHPExcel_Writer_Excel5_Writer
  42. */
  43. class PHPExcel_Writer_Excel5_Worksheet extends PHPExcel_Writer_Excel5_BIFFwriter
  44. {
  45. /**
  46. * Name of the Worksheet
  47. * @var string
  48. */
  49. var $name;
  50. /**
  51. * Index for the Worksheet
  52. * @var integer
  53. */
  54. var $index;
  55. /**
  56. * Reference to the (default) Format object for URLs
  57. * @var object Format
  58. */
  59. var $_url_format;
  60. /**
  61. * Reference to the parser used for parsing formulas
  62. * @var object Format
  63. */
  64. var $_parser;
  65. /**
  66. * Filehandle to the temporary file for storing data
  67. * @var resource
  68. */
  69. var $_filehandle;
  70. /**
  71. * Boolean indicating if we are using a temporary file for storing data
  72. * @var bool
  73. */
  74. var $_using_tmpfile;
  75. /**
  76. * Maximum number of rows for an Excel spreadsheet (BIFF5)
  77. * @var integer
  78. */
  79. var $_xls_rowmax;
  80. /**
  81. * Maximum number of columns for an Excel spreadsheet (BIFF5)
  82. * @var integer
  83. */
  84. var $_xls_colmax;
  85. /**
  86. * Maximum number of characters for a string (LABEL record in BIFF5)
  87. * @var integer
  88. */
  89. var $_xls_strmax;
  90. /**
  91. * First row for the DIMENSIONS record
  92. * @var integer
  93. * @see _storeDimensions()
  94. */
  95. var $_dim_rowmin;
  96. /**
  97. * Last row for the DIMENSIONS record
  98. * @var integer
  99. * @see _storeDimensions()
  100. */
  101. var $_dim_rowmax;
  102. /**
  103. * First column for the DIMENSIONS record
  104. * @var integer
  105. * @see _storeDimensions()
  106. */
  107. var $_dim_colmin;
  108. /**
  109. * Last column for the DIMENSIONS record
  110. * @var integer
  111. * @see _storeDimensions()
  112. */
  113. var $_dim_colmax;
  114. /**
  115. * Array containing format information for columns
  116. * @var array
  117. */
  118. var $_colinfo;
  119. /**
  120. * Array containing the selected area for the worksheet
  121. * @var array
  122. */
  123. var $_selection;
  124. /**
  125. * Array containing the panes for the worksheet
  126. * @var array
  127. */
  128. var $_panes;
  129. /**
  130. * The active pane for the worksheet
  131. * @var integer
  132. */
  133. var $_active_pane;
  134. /**
  135. * Bit specifying if panes are frozen
  136. * @var integer
  137. */
  138. var $_frozen;
  139. /**
  140. * Bit specifying if the worksheet is selected
  141. * @var integer
  142. */
  143. var $selected;
  144. /**
  145. * The paper size (for printing) (DOCUMENT!!!)
  146. * @var integer
  147. */
  148. var $_paper_size;
  149. /**
  150. * Bit specifying paper orientation (for printing). 0 => landscape, 1 => portrait
  151. * @var integer
  152. */
  153. var $_orientation;
  154. /**
  155. * The page header caption
  156. * @var string
  157. */
  158. var $_header;
  159. /**
  160. * The page footer caption
  161. * @var string
  162. */
  163. var $_footer;
  164. /**
  165. * The horizontal centering value for the page
  166. * @var integer
  167. */
  168. var $_hcenter;
  169. /**
  170. * The vertical centering value for the page
  171. * @var integer
  172. */
  173. var $_vcenter;
  174. /**
  175. * The margin for the header
  176. * @var float
  177. */
  178. var $_margin_head;
  179. /**
  180. * The margin for the footer
  181. * @var float
  182. */
  183. var $_margin_foot;
  184. /**
  185. * The left margin for the worksheet in inches
  186. * @var float
  187. */
  188. var $_margin_left;
  189. /**
  190. * The right margin for the worksheet in inches
  191. * @var float
  192. */
  193. var $_margin_right;
  194. /**
  195. * The top margin for the worksheet in inches
  196. * @var float
  197. */
  198. var $_margin_top;
  199. /**
  200. * The bottom margin for the worksheet in inches
  201. * @var float
  202. */
  203. var $_margin_bottom;
  204. /**
  205. * First row to reapeat on each printed page
  206. * @var integer
  207. */
  208. var $title_rowmin;
  209. /**
  210. * Last row to reapeat on each printed page
  211. * @var integer
  212. */
  213. var $title_rowmax;
  214. /**
  215. * First column to reapeat on each printed page
  216. * @var integer
  217. */
  218. var $title_colmin;
  219. /**
  220. * First row of the area to print
  221. * @var integer
  222. */
  223. var $print_rowmin;
  224. /**
  225. * Last row to of the area to print
  226. * @var integer
  227. */
  228. var $print_rowmax;
  229. /**
  230. * First column of the area to print
  231. * @var integer
  232. */
  233. var $print_colmin;
  234. /**
  235. * Last column of the area to print
  236. * @var integer
  237. */
  238. var $print_colmax;
  239. /**
  240. * Whether to use outline.
  241. * @var integer
  242. */
  243. var $_outline_on;
  244. /**
  245. * Auto outline styles.
  246. * @var bool
  247. */
  248. var $_outline_style;
  249. /**
  250. * Whether to have outline summary below.
  251. * @var bool
  252. */
  253. var $_outline_below;
  254. /**
  255. * Whether to have outline summary at the right.
  256. * @var bool
  257. */
  258. var $_outline_right;
  259. /**
  260. * Outline row level.
  261. * @var integer
  262. */
  263. var $_outline_row_level;
  264. /**
  265. * Whether to fit to page when printing or not.
  266. * @var bool
  267. */
  268. var $_fit_page;
  269. /**
  270. * Number of pages to fit wide
  271. * @var integer
  272. */
  273. var $_fit_width;
  274. /**
  275. * Number of pages to fit high
  276. * @var integer
  277. */
  278. var $_fit_height;
  279. /**
  280. * Reference to the total number of strings in the workbook
  281. * @var integer
  282. */
  283. var $_str_total;
  284. /**
  285. * Reference to the number of unique strings in the workbook
  286. * @var integer
  287. */
  288. var $_str_unique;
  289. /**
  290. * Reference to the array containing all the unique strings in the workbook
  291. * @var array
  292. */
  293. var $_str_table;
  294. /**
  295. * Merged cell ranges
  296. * @var array
  297. */
  298. var $_merged_ranges;
  299. /**
  300. * Charset encoding currently used when calling writeString()
  301. * @var string
  302. */
  303. var $_input_encoding;
  304. /**
  305. * The temporary dir for storing files
  306. * @var string
  307. */
  308. var $_tmp_dir;
  309. /**
  310. * List of temporary files created
  311. * @var array
  312. */
  313. var $_tempFilesCreated = array();
  314. /**
  315. * Constructor
  316. *
  317. * @param string $name The name of the new worksheet
  318. * @param integer $index The index of the new worksheet
  319. * @param mixed &$activesheet The current activesheet of the workbook we belong to
  320. * @param mixed &$firstsheet The first worksheet in the workbook we belong to
  321. * @param mixed &$url_format The default format for hyperlinks
  322. * @param mixed &$parser The formula parser created for the Workbook
  323. * @param string $tempDir The temporary directory to be used
  324. * @access private
  325. */
  326. function PHPExcel_Writer_Excel5_Worksheet($BIFF_version, $name,
  327. $index, &$activesheet,
  328. &$firstsheet, &$str_total,
  329. &$str_unique, &$str_table,
  330. &$url_format, &$parser, $tempDir = '')
  331. {
  332. // It needs to call its parent's constructor explicitly
  333. $this->PHPExcel_Writer_Excel5_BIFFwriter();
  334. $this->_BIFF_version = $BIFF_version;
  335. $rowmax = 65536; // 16384 in Excel 5
  336. $colmax = 256;
  337. $this->name = $name;
  338. $this->index = $index;
  339. $this->activesheet = &$activesheet;
  340. $this->firstsheet = &$firstsheet;
  341. $this->_str_total = &$str_total;
  342. $this->_str_unique = &$str_unique;
  343. $this->_str_table = &$str_table;
  344. $this->_url_format = &$url_format;
  345. $this->_parser = &$parser;
  346. //$this->ext_sheets = array();
  347. $this->_filehandle = '';
  348. $this->_using_tmpfile = true;
  349. //$this->fileclosed = 0;
  350. //$this->offset = 0;
  351. $this->_xls_rowmax = $rowmax;
  352. $this->_xls_colmax = $colmax;
  353. $this->_xls_strmax = 255;
  354. $this->_dim_rowmin = $rowmax + 1;
  355. $this->_dim_rowmax = 0;
  356. $this->_dim_colmin = $colmax + 1;
  357. $this->_dim_colmax = 0;
  358. $this->_colinfo = array();
  359. $this->_selection = array(0,0,0,0);
  360. $this->_panes = array();
  361. $this->_active_pane = 3;
  362. $this->_frozen = 0;
  363. $this->selected = 0;
  364. $this->_paper_size = 0x0;
  365. $this->_orientation = 0x1;
  366. $this->_header = '';
  367. $this->_footer = '';
  368. $this->_hcenter = 0;
  369. $this->_vcenter = 0;
  370. $this->_margin_head = 0.50;
  371. $this->_margin_foot = 0.50;
  372. $this->_margin_left = 0.75;
  373. $this->_margin_right = 0.75;
  374. $this->_margin_top = 1.00;
  375. $this->_margin_bottom = 1.00;
  376. $this->title_rowmin = null;
  377. $this->title_rowmax = null;
  378. $this->title_colmin = null;
  379. $this->title_colmax = null;
  380. $this->print_rowmin = null;
  381. $this->print_rowmax = null;
  382. $this->print_colmin = null;
  383. $this->print_colmax = null;
  384. $this->_print_gridlines = 1;
  385. $this->_screen_gridlines = 1;
  386. $this->_print_headers = 0;
  387. $this->_fit_page = 0;
  388. $this->_fit_width = 0;
  389. $this->_fit_height = 0;
  390. $this->_hbreaks = array();
  391. $this->_vbreaks = array();
  392. $this->_protect = 0;
  393. $this->_password = null;
  394. $this->col_sizes = array();
  395. $this->_row_sizes = array();
  396. $this->_zoom = 100;
  397. $this->_print_scale = 100;
  398. $this->_outline_row_level = 0;
  399. $this->_outline_style = 0;
  400. $this->_outline_below = 1;
  401. $this->_outline_right = 1;
  402. $this->_outline_on = 1;
  403. $this->_merged_ranges = array();
  404. $this->_input_encoding = '';
  405. $this->_dv = array();
  406. $this->_tmp_dir = $tempDir;
  407. $this->_initialize();
  408. }
  409. /**
  410. * Cleanup
  411. */
  412. public function cleanup() {
  413. @fclose($this->_filehandle);
  414. foreach ($this->_tempFilesCreated as $file) {
  415. @unlink($file);
  416. }
  417. }
  418. /**
  419. * Open a tmp file to store the majority of the Worksheet data. If this fails,
  420. * for example due to write permissions, store the data in memory. This can be
  421. * slow for large files.
  422. *
  423. * @access private
  424. */
  425. function _initialize()
  426. {
  427. // Open tmp file for storing Worksheet data
  428. $fileName = tempnam($this->_tmp_dir, 'XLSHEET');
  429. $fh = fopen($fileName, 'w+');
  430. if ($fh) {
  431. // Store filehandle
  432. $this->_filehandle = $fh;
  433. $this->_tempFilesCreated[] = $fileName;
  434. } else {
  435. // If tmpfile() fails store data in memory
  436. $this->_using_tmpfile = false;
  437. }
  438. }
  439. /**
  440. * Sets the temp dir used for storing files
  441. *
  442. * @access public
  443. * @param string $dir The dir to be used as temp dir
  444. * @return true if given dir is valid, false otherwise
  445. */
  446. function setTempDir($dir)
  447. {
  448. if (is_dir($dir)) {
  449. $this->_tmp_dir = $dir;
  450. return true;
  451. }
  452. return false;
  453. }
  454. /**
  455. * Add data to the beginning of the workbook (note the reverse order)
  456. * and to the end of the workbook.
  457. *
  458. * @access public
  459. * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook()
  460. * @param array $sheetnames The array of sheetnames from the Workbook this
  461. * worksheet belongs to
  462. */
  463. function close($sheetnames)
  464. {
  465. $num_sheets = count($sheetnames);
  466. /***********************************************
  467. * Prepend in reverse order!!
  468. */
  469. // Prepend the sheet dimensions
  470. $this->_storeDimensions();
  471. // Prepend the sheet password
  472. $this->_storePassword();
  473. // Prepend the sheet protection
  474. $this->_storeProtect();
  475. // Prepend the page setup
  476. $this->_storeSetup();
  477. /* FIXME: margins are actually appended */
  478. // Prepend the bottom margin
  479. $this->_storeMarginBottom();
  480. // Prepend the top margin
  481. $this->_storeMarginTop();
  482. // Prepend the right margin
  483. $this->_storeMarginRight();
  484. // Prepend the left margin
  485. $this->_storeMarginLeft();
  486. // Prepend the page vertical centering
  487. $this->_storeVcenter();
  488. // Prepend the page horizontal centering
  489. $this->_storeHcenter();
  490. // Prepend the page footer
  491. $this->_storeFooter();
  492. // Prepend the page header
  493. $this->_storeHeader();
  494. // Prepend the vertical page breaks
  495. $this->_storeVbreak();
  496. // Prepend the horizontal page breaks
  497. $this->_storeHbreak();
  498. // Prepend WSBOOL
  499. $this->_storeWsbool();
  500. // Prepend GRIDSET
  501. $this->_storeGridset();
  502. // Prepend GUTS
  503. if ($this->_BIFF_version == 0x0500) {
  504. $this->_storeGuts();
  505. }
  506. // Prepend PRINTGRIDLINES
  507. $this->_storePrintGridlines();
  508. // Prepend PRINTHEADERS
  509. $this->_storePrintHeaders();
  510. // Prepend EXTERNSHEET references
  511. if ($this->_BIFF_version == 0x0500) {
  512. for ($i = $num_sheets; $i > 0; $i--) {
  513. $sheetname = $sheetnames[$i-1];
  514. $this->_storeExternsheet($sheetname);
  515. }
  516. }
  517. // Prepend the EXTERNCOUNT of external references.
  518. if ($this->_BIFF_version == 0x0500) {
  519. $this->_storeExterncount($num_sheets);
  520. }
  521. // Prepend the COLINFO records if they exist
  522. if (!empty($this->_colinfo)) {
  523. $colcount = count($this->_colinfo);
  524. for ($i = 0; $i < $colcount; $i++) {
  525. $this->_storeColinfo($this->_colinfo[$i]);
  526. }
  527. $this->_storeDefcol();
  528. }
  529. // Prepend the BOF record
  530. $this->_storeBof(0x0010);
  531. /*
  532. * End of prepend. Read upwards from here.
  533. ***********************************************/
  534. // Append
  535. $this->_storeWindow2();
  536. $this->_storeZoom();
  537. if (!empty($this->_panes)) {
  538. $this->_storePanes($this->_panes);
  539. }
  540. $this->_storeSelection($this->_selection);
  541. $this->_storeMergedCells();
  542. /* TODO: add data validity */
  543. /*if ($this->_BIFF_version == 0x0600) {
  544. $this->_storeDataValidity();
  545. }*/
  546. $this->_storeEof();
  547. }
  548. /**
  549. * Retrieve the worksheet name.
  550. * This is usefull when creating worksheets without a name.
  551. *
  552. * @access public
  553. * @return string The worksheet's name
  554. */
  555. function getName()
  556. {
  557. return $this->name;
  558. }
  559. /**
  560. * Retrieves data from memory in one chunk, or from disk in $buffer
  561. * sized chunks.
  562. *
  563. * @return string The data
  564. */
  565. function getData()
  566. {
  567. $buffer = 4096;
  568. // Return data stored in memory
  569. if (isset($this->_data)) {
  570. $tmp = $this->_data;
  571. unset($this->_data);
  572. $fh = $this->_filehandle;
  573. if ($this->_using_tmpfile) {
  574. fseek($fh, 0);
  575. }
  576. return $tmp;
  577. }
  578. // Return data stored on disk
  579. if ($this->_using_tmpfile) {
  580. if ($tmp = fread($this->_filehandle, $buffer)) {
  581. return $tmp;
  582. }
  583. }
  584. // No data to return
  585. return '';
  586. }
  587. /**
  588. * Sets a merged cell range
  589. *
  590. * @access public
  591. * @param integer $first_row First row of the area to merge
  592. * @param integer $first_col First column of the area to merge
  593. * @param integer $last_row Last row of the area to merge
  594. * @param integer $last_col Last column of the area to merge
  595. */
  596. function setMerge($first_row, $first_col, $last_row, $last_col)
  597. {
  598. if (($last_row < $first_row) || ($last_col < $first_col)) {
  599. return;
  600. }
  601. // don't check rowmin, rowmax, etc... because we don't know when this
  602. // is going to be called
  603. $this->_merged_ranges[] = array($first_row, $first_col, $last_row, $last_col);
  604. }
  605. /**
  606. * Set this worksheet as a selected worksheet,
  607. * i.e. the worksheet has its tab highlighted.
  608. *
  609. * @access public
  610. */
  611. function select()
  612. {
  613. $this->selected = 1;
  614. }
  615. /**
  616. * Set this worksheet as the active worksheet,
  617. * i.e. the worksheet that is displayed when the workbook is opened.
  618. * Also set it as selected.
  619. *
  620. * @access public
  621. */
  622. function activate()
  623. {
  624. $this->selected = 1;
  625. $this->activesheet = $this->index;
  626. }
  627. /**
  628. * Set this worksheet as the first visible sheet.
  629. * This is necessary when there are a large number of worksheets and the
  630. * activated worksheet is not visible on the screen.
  631. *
  632. * @access public
  633. */
  634. function setFirstSheet()
  635. {
  636. $this->firstsheet = $this->index;
  637. }
  638. /**
  639. * Set the worksheet protection flag
  640. * to prevent accidental modification and to
  641. * hide formulas if the locked and hidden format properties have been set.
  642. *
  643. * @access public
  644. * @param string $password The password to use for protecting the sheet.
  645. */
  646. function protect($password, $encoded = false)
  647. {
  648. $this->_protect = 1;
  649. $this->_password = ($encoded ? $password : $this->_encodePassword($password));
  650. }
  651. /**
  652. * Set the width of a single column or a range of columns.
  653. *
  654. * @access public
  655. * @param integer $firstcol first column on the range
  656. * @param integer $lastcol last column on the range
  657. * @param integer $width width to set
  658. * @param mixed $format The optional XF format to apply to the columns
  659. * @param integer $hidden The optional hidden atribute
  660. * @param integer $level The optional outline level
  661. */
  662. function setColumn($firstcol, $lastcol, $width, $format = null, $hidden = 0, $level = 0)
  663. {
  664. $this->_colinfo[] = array($firstcol, $lastcol, $width, &$format, $hidden, $level);
  665. // Set width to zero if column is hidden
  666. $width = ($hidden) ? 0 : $width;
  667. for ($col = $firstcol; $col <= $lastcol; $col++) {
  668. $this->col_sizes[$col] = $width;
  669. }
  670. }
  671. /**
  672. * Set which cell or cells are selected in a worksheet
  673. *
  674. * @access public
  675. * @param integer $first_row first row in the selected quadrant
  676. * @param integer $first_column first column in the selected quadrant
  677. * @param integer $last_row last row in the selected quadrant
  678. * @param integer $last_column last column in the selected quadrant
  679. */
  680. function setSelection($first_row,$first_column,$last_row,$last_column)
  681. {
  682. $this->_selection = array($first_row,$first_column,$last_row,$last_column);
  683. }
  684. /**
  685. * Set panes and mark them as frozen.
  686. *
  687. * @access public
  688. * @param array $panes This is the only parameter received and is composed of the following:
  689. * 0 => Vertical split position,
  690. * 1 => Horizontal split position
  691. * 2 => Top row visible
  692. * 3 => Leftmost column visible
  693. * 4 => Active pane
  694. */
  695. function freezePanes($panes)
  696. {
  697. $this->_frozen = 1;
  698. $this->_panes = $panes;
  699. }
  700. /**
  701. * Set panes and mark them as unfrozen.
  702. *
  703. * @access public
  704. * @param array $panes This is the only parameter received and is composed of the following:
  705. * 0 => Vertical split position,
  706. * 1 => Horizontal split position
  707. * 2 => Top row visible
  708. * 3 => Leftmost column visible
  709. * 4 => Active pane
  710. */
  711. function thawPanes($panes)
  712. {
  713. $this->_frozen = 0;
  714. $this->_panes = $panes;
  715. }
  716. /**
  717. * Set the page orientation as portrait.
  718. *
  719. * @access public
  720. */
  721. function setPortrait()
  722. {
  723. $this->_orientation = 1;
  724. }
  725. /**
  726. * Set the page orientation as landscape.
  727. *
  728. * @access public
  729. */
  730. function setLandscape()
  731. {
  732. $this->_orientation = 0;
  733. }
  734. /**
  735. * Set the paper type. Ex. 1 = US Letter, 9 = A4
  736. *
  737. * @access public
  738. * @param integer $size The type of paper size to use
  739. */
  740. function setPaper($size = 0)
  741. {
  742. $this->_paper_size = $size;
  743. }
  744. /**
  745. * Set the page header caption and optional margin.
  746. *
  747. * @access public
  748. * @param string $string The header text
  749. * @param float $margin optional head margin in inches.
  750. */
  751. function setHeader($string,$margin = 0.50)
  752. {
  753. if (strlen($string) >= 255) {
  754. //carp 'Header string must be less than 255 characters';
  755. return;
  756. }
  757. $this->_header = $string;
  758. $this->_margin_head = $margin;
  759. }
  760. /**
  761. * Set the page footer caption and optional margin.
  762. *
  763. * @access public
  764. * @param string $string The footer text
  765. * @param float $margin optional foot margin in inches.
  766. */
  767. function setFooter($string,$margin = 0.50)
  768. {
  769. if (strlen($string) >= 255) {
  770. //carp 'Footer string must be less than 255 characters';
  771. return;
  772. }
  773. $this->_footer = $string;
  774. $this->_margin_foot = $margin;
  775. }
  776. /**
  777. * Center the page horinzontally.
  778. *
  779. * @access public
  780. * @param integer $center the optional value for centering. Defaults to 1 (center).
  781. */
  782. function centerHorizontally($center = 1)
  783. {
  784. $this->_hcenter = $center;
  785. }
  786. /**
  787. * Center the page vertically.
  788. *
  789. * @access public
  790. * @param integer $center the optional value for centering. Defaults to 1 (center).
  791. */
  792. function centerVertically($center = 1)
  793. {
  794. $this->_vcenter = $center;
  795. }
  796. /**
  797. * Set all the page margins to the same value in inches.
  798. *
  799. * @access public
  800. * @param float $margin The margin to set in inches
  801. */
  802. function setMargins($margin)
  803. {
  804. $this->setMarginLeft($margin);
  805. $this->setMarginRight($margin);
  806. $this->setMarginTop($margin);
  807. $this->setMarginBottom($margin);
  808. }
  809. /**
  810. * Set the left and right margins to the same value in inches.
  811. *
  812. * @access public
  813. * @param float $margin The margin to set in inches
  814. */
  815. function setMargins_LR($margin)
  816. {
  817. $this->setMarginLeft($margin);
  818. $this->setMarginRight($margin);
  819. }
  820. /**
  821. * Set the top and bottom margins to the same value in inches.
  822. *
  823. * @access public
  824. * @param float $margin The margin to set in inches
  825. */
  826. function setMargins_TB($margin)
  827. {
  828. $this->setMarginTop($margin);
  829. $this->setMarginBottom($margin);
  830. }
  831. /**
  832. * Set the left margin in inches.
  833. *
  834. * @access public
  835. * @param float $margin The margin to set in inches
  836. */
  837. function setMarginLeft($margin = 0.75)
  838. {
  839. $this->_margin_left = $margin;
  840. }
  841. /**
  842. * Set the right margin in inches.
  843. *
  844. * @access public
  845. * @param float $margin The margin to set in inches
  846. */
  847. function setMarginRight($margin = 0.75)
  848. {
  849. $this->_margin_right = $margin;
  850. }
  851. /**
  852. * Set the top margin in inches.
  853. *
  854. * @access public
  855. * @param float $margin The margin to set in inches
  856. */
  857. function setMarginTop($margin = 1.00)
  858. {
  859. $this->_margin_top = $margin;
  860. }
  861. /**
  862. * Set the bottom margin in inches.
  863. *
  864. * @access public
  865. * @param float $margin The margin to set in inches
  866. */
  867. function setMarginBottom($margin = 1.00)
  868. {
  869. $this->_margin_bottom = $margin;
  870. }
  871. /**
  872. * Set the rows to repeat at the top of each printed page.
  873. *
  874. * @access public
  875. * @param integer $first_row First row to repeat
  876. * @param integer $last_row Last row to repeat. Optional.
  877. */
  878. function repeatRows($first_row, $last_row = null)
  879. {
  880. $this->title_rowmin = $first_row;
  881. if (isset($last_row)) { //Second row is optional
  882. $this->title_rowmax = $last_row;
  883. } else {
  884. $this->title_rowmax = $first_row;
  885. }
  886. }
  887. /**
  888. * Set the columns to repeat at the left hand side of each printed page.
  889. *
  890. * @access public
  891. * @param integer $first_col First column to repeat
  892. * @param integer $last_col Last column to repeat. Optional.
  893. */
  894. function repeatColumns($first_col, $last_col = null)
  895. {
  896. $this->title_colmin = $first_col;
  897. if (isset($last_col)) { // Second col is optional
  898. $this->title_colmax = $last_col;
  899. } else {
  900. $this->title_colmax = $first_col;
  901. }
  902. }
  903. /**
  904. * Set the area of each worksheet that will be printed.
  905. *
  906. * @access public
  907. * @param integer $first_row First row of the area to print
  908. * @param integer $first_col First column of the area to print
  909. * @param integer $last_row Last row of the area to print
  910. * @param integer $last_col Last column of the area to print
  911. */
  912. function printArea($first_row, $first_col, $last_row, $last_col)
  913. {
  914. $this->print_rowmin = $first_row;
  915. $this->print_colmin = $first_col;
  916. $this->print_rowmax = $last_row;
  917. $this->print_colmax = $last_col;
  918. }
  919. /**
  920. * Set the option to hide gridlines on the printed page.
  921. *
  922. * @access public
  923. */
  924. function hideGridlines()
  925. {
  926. $this->_print_gridlines = 0;
  927. }
  928. /**
  929. * Set the option to hide gridlines on the worksheet (as seen on the screen).
  930. *
  931. * @access public
  932. */
  933. function hideScreenGridlines()
  934. {
  935. $this->_screen_gridlines = 0;
  936. }
  937. /**
  938. * Set the option to print the row and column headers on the printed page.
  939. *
  940. * @access public
  941. * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
  942. */
  943. function printRowColHeaders($print = 1)
  944. {
  945. $this->_print_headers = $print;
  946. }
  947. /**
  948. * Set the vertical and horizontal number of pages that will define the maximum area printed.
  949. * It doesn't seem to work with OpenOffice.
  950. *
  951. * @access public
  952. * @param integer $width Maximun width of printed area in pages
  953. * @param integer $height Maximun heigth of printed area in pages
  954. * @see setPrintScale()
  955. */
  956. function fitToPages($width, $height)
  957. {
  958. $this->_fit_page = 1;
  959. $this->_fit_width = $width;
  960. $this->_fit_height = $height;
  961. }
  962. /**
  963. * Store the horizontal page breaks on a worksheet (for printing).
  964. * The breaks represent the row after which the break is inserted.
  965. *
  966. * @access public
  967. * @param array $breaks Array containing the horizontal page breaks
  968. */
  969. function setHPagebreaks($breaks)
  970. {
  971. foreach ($breaks as $break) {
  972. array_push($this->_hbreaks, $break);
  973. }
  974. }
  975. /**
  976. * Store the vertical page breaks on a worksheet (for printing).
  977. * The breaks represent the column after which the break is inserted.
  978. *
  979. * @access public
  980. * @param array $breaks Array containing the vertical page breaks
  981. */
  982. function setVPagebreaks($breaks)
  983. {
  984. foreach ($breaks as $break) {
  985. array_push($this->_vbreaks, $break);
  986. }
  987. }
  988. /**
  989. * Set the worksheet zoom factor.
  990. *
  991. * @access public
  992. * @param integer $scale The zoom factor
  993. */
  994. function setZoom($scale = 100)
  995. {
  996. // Confine the scale to Excel's range
  997. if ($scale < 10 || $scale > 400) {
  998. throw new Exception("Zoom factor $scale outside range: 10 <= zoom <= 400");
  999. $scale = 100;
  1000. }
  1001. $this->_zoom = floor($scale);
  1002. }
  1003. /**
  1004. * Set the scale factor for the printed page.
  1005. * It turns off the "fit to page" option
  1006. *
  1007. * @access public
  1008. * @param integer $scale The optional scale factor. Defaults to 100
  1009. */
  1010. function setPrintScale($scale = 100)
  1011. {
  1012. // Confine the scale to Excel's range
  1013. if ($scale < 10 || $scale > 400) {
  1014. throw new Exception("Print scale $scale outside range: 10 <= zoom <= 400");
  1015. $scale = 100;
  1016. }
  1017. // Turn off "fit to page" option
  1018. $this->_fit_page = 0;
  1019. $this->_print_scale = floor($scale);
  1020. }
  1021. /**
  1022. * Map to the appropriate write method acording to the token recieved.
  1023. *
  1024. * @access public
  1025. * @param integer $row The row of the cell we are writing to
  1026. * @param integer $col The column of the cell we are writing to
  1027. * @param mixed $token What we are writing
  1028. * @param mixed $format The optional format to apply to the cell
  1029. */
  1030. function write($row, $col, $token, $format = null, $numberFormat = null)
  1031. {
  1032. // Check for a cell reference in A1 notation and substitute row and column
  1033. /*if ($_[0] =~ /^\D/) {
  1034. @_ = $this->_substituteCellref(@_);
  1035. }*/
  1036. if (($numberFormat != 'General') && (PHPExcel_Shared_Date::isDateTimeFormatCode($numberFormat))) {
  1037. if (is_string($token)) {
  1038. // Error string
  1039. return $this->writeString($row, $col, $token, $format);
  1040. } elseif (!is_float($token)) {
  1041. // PHP serialized date/time or date/time object
  1042. return $this->writeNumber($row, $col, PHPExcel_Shared_Date::PHPToExcel($token), $format);
  1043. } else {
  1044. // Excel serialized date/time
  1045. return $this->writeNumber($row, $col, $token, $format);
  1046. }
  1047. } elseif (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/", $token)) {
  1048. // Match number
  1049. return $this->writeNumber($row, $col, $token, $format);
  1050. } elseif (preg_match("/^[fh]tt?p:\/\//", $token)) {
  1051. // Match http or ftp URL
  1052. return $this->writeUrl($row, $col, $token, '', $format);
  1053. } elseif (preg_match("/^mailto:/", $token)) {
  1054. // Match mailto:
  1055. return $this->writeUrl($row, $col, $token, '', $format);
  1056. } elseif (preg_match("/^(?:in|ex)ternal:/", $token)) {
  1057. // Match internal or external sheet link
  1058. return $this->writeUrl($row, $col, $token, '', $format);
  1059. } elseif (preg_match("/^=/", $token)) {
  1060. // Match formula
  1061. return $this->writeFormula($row, $col, $token, $format);
  1062. } elseif (preg_match("/^@/", $token)) {
  1063. // Match formula
  1064. return $this->writeFormula($row, $col, $token, $format);
  1065. } elseif ($token == '') {
  1066. // Match blank
  1067. return $this->writeBlank($row, $col, $format);
  1068. } else {
  1069. // Default: match string
  1070. return $this->writeString($row, $col, $token, $format);
  1071. }
  1072. }
  1073. /**
  1074. * Write an array of values as a row
  1075. *
  1076. * @access public
  1077. * @param integer $row The row we are writing to
  1078. * @param integer $col The first col (leftmost col) we are writing to
  1079. * @param array $val The array of values to write
  1080. * @param mixed $format The optional format to apply to the cell
  1081. */
  1082. function writeRow($row, $col, $val, $format = null, $numberFormat = null)
  1083. {
  1084. $retval = '';
  1085. if (is_array($val)) {
  1086. foreach ($val as $v) {
  1087. if (is_array($v)) {
  1088. $this->writeCol($row, $col, $v, $format, $numberFormat = null);
  1089. } else {
  1090. $this->write($row, $col, $v, $format, $numberFormat);
  1091. }
  1092. $col++;
  1093. }
  1094. } else {
  1095. throw new Exception('$val needs to be an array');
  1096. }
  1097. return($retval);
  1098. }
  1099. /**
  1100. * Write an array of values as a column
  1101. *
  1102. * @access public
  1103. * @param integer $row The first row (uppermost row) we are writing to
  1104. * @param integer $col The col we are writing to
  1105. * @param array $val The array of values to write
  1106. * @param mixed $format The optional format to apply to the cell
  1107. */
  1108. function writeCol($row, $col, $val, $format = null, $numberFormat = null)
  1109. {
  1110. $retval = '';
  1111. if (is_array($val)) {
  1112. foreach ($val as $v) {
  1113. $this->write($row, $col, $v, $format, $numberFormat);
  1114. $row++;
  1115. }
  1116. } else {
  1117. throw new Exception('$val needs to be an array');
  1118. }
  1119. return($retval);
  1120. }
  1121. /**
  1122. * Returns an index to the XF record in the workbook
  1123. *
  1124. * @access private
  1125. * @param mixed &$format The optional XF format
  1126. * @return integer The XF record index
  1127. */
  1128. function _XF(&$format)
  1129. {
  1130. if ($format) {
  1131. return($format->getXfIndex());
  1132. } else {
  1133. return(0x0F);
  1134. }
  1135. }
  1136. /******************************************************************************
  1137. *******************************************************************************
  1138. *
  1139. * Internal methods
  1140. */
  1141. /**
  1142. * Store Worksheet data in memory using the parent's class append() or to a
  1143. * temporary file, the default.
  1144. *
  1145. * @access private
  1146. * @param string $data The binary data to append
  1147. */
  1148. function _append($data)
  1149. {
  1150. if ($this->_using_tmpfile) {
  1151. // Add CONTINUE records if necessary
  1152. if (strlen($data) > $this->_limit) {
  1153. $data = $this->_addContinue($data);
  1154. }
  1155. fwrite($this->_filehandle, $data);
  1156. $this->_datasize += strlen($data);
  1157. } else {
  1158. parent::_append($data);
  1159. }
  1160. }
  1161. /**
  1162. * Substitute an Excel cell reference in A1 notation for zero based row and
  1163. * column values in an argument list.
  1164. *
  1165. * Ex: ("A4", "Hello") is converted to (3, 0, "Hello").
  1166. *
  1167. * @access private
  1168. * @param string $cell The cell reference. Or range of cells.
  1169. * @return array
  1170. */
  1171. function _substituteCellref($cell)
  1172. {
  1173. $cell = strtoupper($cell);
  1174. // Convert a column range: 'A:A' or 'B:G'
  1175. if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/", $cell, $match)) {
  1176. list($no_use, $col1) = $this->_cellToRowcol($match[1] .'1'); // Add a dummy row
  1177. list($no_use, $col2) = $this->_cellToRowcol($match[2] .'1'); // Add a dummy row
  1178. return(array($col1, $col2));
  1179. }
  1180. // Convert a cell range: 'A1:B7'
  1181. if (preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/", $cell, $match)) {
  1182. list($row1, $col1) = $this->_cellToRowcol($match[1]);
  1183. list($row2, $col2) = $this->_cellToRowcol($match[2]);
  1184. return(array($row1, $col1, $row2, $col2));
  1185. }
  1186. // Convert a cell reference: 'A1' or 'AD2000'
  1187. if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/", $cell)) {
  1188. list($row1, $col1) = $this->_cellToRowcol($match[1]);
  1189. return(array($row1, $col1));
  1190. }
  1191. // TODO use real error codes
  1192. throw new Exception("Unknown cell reference $cell");
  1193. }
  1194. /**
  1195. * Convert an Excel cell reference in A1 notation to a zero based row and column
  1196. * reference; converts C1 to (0, 2).
  1197. *
  1198. * @access private
  1199. * @param string $cell The cell reference.
  1200. * @return array containing (row, column)
  1201. */
  1202. function _cellToRowcol($cell)
  1203. {
  1204. preg_match("/\$?([A-I]?[A-Z])\$?(\d+)/",$cell,$match);
  1205. $col = $match[1];
  1206. $row = $match[2];
  1207. // Convert base26 column string to number
  1208. $chars = split('', $col);
  1209. $expn = 0;
  1210. $col = 0;
  1211. while ($chars) {
  1212. $char = array_pop($chars); // LS char first
  1213. $col += (ord($char) -ord('A') +1) * pow(26,$expn);
  1214. $expn++;
  1215. }
  1216. // Convert 1-index to zero-index
  1217. $row--;
  1218. $col--;
  1219. return(array($row, $col));
  1220. }
  1221. /**
  1222. * Based on the algorithm provided by Daniel Rentz of OpenOffice.
  1223. *
  1224. * @access private
  1225. * @param string $plaintext The password to be encoded in plaintext.
  1226. * @return string The encoded password
  1227. */
  1228. function _encodePassword($plaintext)
  1229. {
  1230. $password = 0x0000;
  1231. $i = 1; // char position
  1232. // split the plain text password in its component characters
  1233. $chars = preg_split('//', $plaintext, -1, PREG_SPLIT_NO_EMPTY);
  1234. foreach ($chars as $char) {
  1235. $value = ord($char) << $i; // shifted ASCII value
  1236. $rotated_bits = $value >> 15; // rotated bits beyond bit 15
  1237. $value &= 0x7fff; // first 15 bits
  1238. $password ^= ($value | $rotated_bits);
  1239. $i++;
  1240. }
  1241. $password ^= strlen($plaintext);
  1242. $password ^= 0xCE4B;
  1243. return($password);
  1244. }
  1245. /**
  1246. * This method sets the properties for outlining and grouping. The defaults
  1247. * correspond to Excel's defaults.
  1248. *
  1249. * @param bool $visible
  1250. * @param bool $symbols_below
  1251. * @param bool $symbols_right
  1252. * @param bool $auto_style
  1253. */
  1254. function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
  1255. {
  1256. $this->_outline_on = $visible;
  1257. $this->_outline_below = $symbols_below;
  1258. $this->_outline_right = $symbols_right;
  1259. $this->_outline_style = $auto_style;
  1260. // Ensure this is a boolean vale for Window2
  1261. if ($this->_outline_on) {
  1262. $this->_outline_on = 1;
  1263. }
  1264. }
  1265. /******************************************************************************
  1266. *******************************************************************************
  1267. *
  1268. * BIFF RECORDS
  1269. */
  1270. /**
  1271. * Write a double to the specified row and column (zero indexed).
  1272. * An integer can be written as a double. Excel will display an
  1273. * integer. $format is optional.
  1274. *
  1275. * Returns 0 : normal termination
  1276. * -2 : row or column out of range
  1277. *
  1278. * @access public
  1279. * @param integer $row Zero indexed row
  1280. * @param integer $col Zero indexed column
  1281. * @param float $num The number to write
  1282. * @param mixed $format The optional XF format
  1283. * @return integer
  1284. */
  1285. function writeNumber($row, $col, $num, $format = null)
  1286. {
  1287. $record = 0x0203; // Record identifier
  1288. $length = 0x000E; // Number of bytes to follow
  1289. $xf = $this->_XF($format); // The cell format
  1290. // Check that row and col are valid and store max and min values
  1291. if ($row >= $this->_xls_rowmax) {
  1292. return(-2);
  1293. }
  1294. if ($col >= $this->_xls_colmax) {
  1295. return(-2);
  1296. }
  1297. if ($row < $this->_dim_rowmin) {
  1298. $this->_dim_rowmin = $row;
  1299. }
  1300. if ($row > $this->_dim_rowmax) {
  1301. $this->_dim_rowmax = $row;
  1302. }
  1303. if ($col < $this->_dim_colmin) {
  1304. $this->_dim_colmin = $col;
  1305. }
  1306. if ($col > $this->_dim_colmax) {
  1307. $this->_dim_colmax = $col;
  1308. }
  1309. $header = pack("vv", $record, $length);
  1310. $data = pack("vvv", $row, $col, $xf);
  1311. $xl_double = pack("d", $num);
  1312. if ($this->_byte_order) { // if it's Big Endian
  1313. $xl_double = strrev($xl_double);
  1314. }
  1315. $this->_append($header.$data.$xl_double);
  1316. return(0);
  1317. }
  1318. /**
  1319. * Write a string to the specified row and column (zero indexed).
  1320. * NOTE: there is an Excel 5 defined limit of 255 characters.
  1321. * $format is optional.
  1322. * Returns 0 : normal termination
  1323. * -2 : row or column out of range
  1324. * -3 : long string truncated to 255 chars
  1325. *
  1326. * @access public
  1327. * @param integer $row Zero indexed row
  1328. * @param integer $col Zero indexed column
  1329. * @param string $str The string to write
  1330. * @param mixed $format The XF format for the cell
  1331. * @return integer
  1332. */
  1333. function writeString($row, $col, $str, $format = null)
  1334. {
  1335. if ($this->_BIFF_version == 0x0600) {
  1336. return $this->writeStringBIFF8($row, $col, $str, $format);
  1337. }
  1338. $strlen = strlen($str);
  1339. $record = 0x0204; // Record identifier
  1340. $length = 0x0008 + $strlen; // Bytes to follow
  1341. $xf = $this->_XF($format); // The cell format
  1342. $str_error = 0;
  1343. // Check that row and col are valid and store max and min values
  1344. if ($row >= $this->_xls_rowmax) {
  1345. return(-2);
  1346. }
  1347. if ($col >= $this->_xls_colmax) {
  1348. return(-2);
  1349. }
  1350. if ($row < $this->_dim_rowmin) {
  1351. $this->_dim_rowmin = $row;
  1352. }
  1353. if ($row > $this->_dim_rowmax) {
  1354. $this->_dim_rowmax = $row;
  1355. }
  1356. if ($col < $this->_dim_colmin) {
  1357. $this->_dim_colmin = $col;
  1358. }
  1359. if ($col > $this->_dim_colmax) {
  1360. $this->_dim_colmax = $col;
  1361. }
  1362. if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
  1363. $str = substr($str, 0, $this->_xls_strmax);
  1364. $length = 0x0008 + $this->_xls_strmax;
  1365. $strlen = $this->_xls_strmax;
  1366. $str_error = -3;
  1367. }
  1368. $header = pack("vv", $record, $length);
  1369. $data = pack("vvvv", $row, $col, $xf, $strlen);
  1370. $this->_append($header . $data . $str);
  1371. return($str_error);
  1372. }
  1373. var $_biff8_input_encoding = 'UTF-16LE';
  1374. function setBIFF8InputEncoding($encoding) {
  1375. if ($encoding != 'UTF-16LE' && !function_exists('iconv')) {
  1376. $this->raiseError("Using an input encoding other than UTF-16LE requires PHP support for iconv");
  1377. }
  1378. $this->_biff8_input_encoding = $encoding;
  1379. }
  1380. /**
  1381. * Sets Input Encoding for writing strings
  1382. *
  1383. * @access public
  1384. * @param string $encoding The encoding. Ex: 'UTF-16LE', 'utf-8', 'ISO-859-7'
  1385. */
  1386. function setInputEncoding($encoding)
  1387. {
  1388. if ($encoding != 'UTF-16LE' && !function_exists('iconv')) {
  1389. throw new Exception("Using an input encoding other than UTF-16LE requires PHP support for iconv");
  1390. }
  1391. $this->_input_encoding = $encoding;
  1392. }
  1393. /**
  1394. * Write a string to the specified row and column (zero indexed).
  1395. * This is the BIFF8 version (no 255 chars limit).
  1396. * $format is optional.
  1397. * Returns 0 : normal termination
  1398. * -2 : row or column out of range
  1399. * -3 : long string truncated to 255 chars
  1400. *
  1401. * @access public
  1402. * @param integer $row Zero indexed row
  1403. * @param integer $col Zero indexed column
  1404. * @param string $str The string to write
  1405. * @param mixed $format The XF format for the cell
  1406. * @return integer
  1407. */
  1408. function writeStringBIFF8($row, $col, $str, $format = null)
  1409. {
  1410. if ($this->_input_encoding == 'UTF-16LE')
  1411. {
  1412. $strlen = function_exists('mb_strlen') ? mb_strlen($str, 'UTF-16LE') : (strlen($str) / 2);
  1413. $encoding = 0x1;
  1414. }
  1415. elseif ($this->_input_encoding != '')
  1416. {
  1417. $str = iconv($this->_input_encoding, 'UTF-16LE', $str);
  1418. $strlen = function_exists('mb_strlen') ? mb_strlen($str, 'UTF-16LE') : (strlen($str) / 2);
  1419. $encoding = 0x1;
  1420. }
  1421. else
  1422. {
  1423. $strlen = strlen($str);
  1424. $encoding = 0x0;
  1425. }
  1426. $record = 0x00FD; // Record identifier
  1427. $length = 0x000A; // Bytes to follow
  1428. $xf = $this->_XF($format); // The cell format
  1429. $str_error = 0;
  1430. // Check that row and col are valid and store max and min values
  1431. if ($this->_checkRowCol($row, $col) == false) {
  1432. return -2;
  1433. }
  1434. $str = pack('vC', $strlen, $encoding).$str;
  1435. /* check if string is already present */
  1436. if (!isset($this->_str_table[$str])) {
  1437. $this->_str_table[$str] = $this->_str_unique++;
  1438. }
  1439. $this->_str_total++;
  1440. $header = pack('vv', $record, $length);
  1441. $data = pack('vvvV', $row, $col, $xf, $this->_str_table[$str]);
  1442. $this->_append($header.$data);
  1443. return $str_error;
  1444. }
  1445. /**
  1446. * Check row and col before writing to a cell, and update the sheet's
  1447. * dimensions accordingly
  1448. *
  1449. * @access private
  1450. * @param integer $row Zero indexed row
  1451. * @param integer $col Zero indexed column
  1452. * @return boolean true for success, false if row and/or col are grester
  1453. * then maximums allowed.
  1454. */
  1455. function _checkRowCol($row, $col)
  1456. {
  1457. if ($row >= $this->_xls_rowmax) {
  1458. return false;
  1459. }
  1460. if ($col >= $this->_xls_colmax) {
  1461. return false;
  1462. }
  1463. if ($row < $this->_dim_rowmin) {
  1464. $this->_dim_rowmin = $row;
  1465. }
  1466. if ($row > $this->_dim_rowmax) {
  1467. $this->_dim_rowmax = $row;
  1468. }
  1469. if ($col < $this->_dim_colmin) {
  1470. $this->_dim_colmin = $col;
  1471. }
  1472. if ($col > $this->_dim_colmax) {
  1473. $this->_dim_colmax = $col;
  1474. }
  1475. return true;
  1476. }
  1477. /**
  1478. * Writes a note associated with the cell given by the row and column.
  1479. * NOTE records don't have a length limit.
  1480. *
  1481. * @access public
  1482. * @param integer $row Zero indexed row
  1483. * @param integer $col Zero indexed column
  1484. * @param string $note The note to write
  1485. */
  1486. function writeNote($row, $col, $note)
  1487. {
  1488. $note_length = strlen($note);
  1489. $record = 0x001C; // Record identifier
  1490. $max_length = 2048; // Maximun length for a NOTE record
  1491. //$length = 0x0006 + $note_length; // Bytes to follow
  1492. // Check that row and col are valid and store max and min values
  1493. if ($row >= $this->_xls_rowmax) {
  1494. return(-2);
  1495. }
  1496. if ($col >= $this->_xls_colmax) {
  1497. return(-2);
  1498. }
  1499. if ($row < $this->_dim_rowmin) {
  1500. $this->_dim_rowmin = $row;
  1501. }
  1502. if ($row > $this->_dim_rowmax) {
  1503. $this->_dim_rowmax = $row;
  1504. }
  1505. if ($col < $this->_dim_colmin) {
  1506. $this->_dim_colmin = $col;
  1507. }
  1508. if ($col > $this->_dim_colmax) {
  1509. $this->_dim_colmax = $col;
  1510. }
  1511. // Length for this record is no more than 2048 + 6
  1512. $length = 0x0006 + min($note_length, 2048);
  1513. $header = pack("vv", $record, $length);
  1514. $data = pack("vvv", $row, $col, $note_length);
  1515. $this->_append($header . $data . substr($note, 0, 2048));
  1516. for ($i = $max_length; $i < $note_length; $i += $max_length) {
  1517. $chunk = substr($note, $i, $max_length);
  1518. $length = 0x0006 + strlen($chunk);
  1519. $header = pack("vv", $record, $length);
  1520. $data = pack("vvv", -1, 0, strlen($chunk));
  1521. $this->_append($header.$data.$chunk);
  1522. }
  1523. return(0);
  1524. }
  1525. /**
  1526. * Write a blank cell to the specified row and column (zero indexed).
  1527. * A blank cell is used to specify formatting without adding a string
  1528. * or a number.
  1529. *
  1530. * A blank cell without a format serves no purpose. Therefore, we don't write
  1531. * a BLANK record unless a format is specified.
  1532. *
  1533. * Returns 0 : normal termination (including no format)
  1534. * -1 : insufficient number of arguments
  1535. * -2 : row or column out of range
  1536. *
  1537. * @access public
  1538. * @param integer $row Zero indexed row
  1539. * @param integer $col Zero indexed column
  1540. * @param mixed $format The XF format
  1541. */
  1542. function writeBlank($row, $col, $format)
  1543. {
  1544. // Don't write a blank cell unless it has a format
  1545. if (!$format) {
  1546. return(0);
  1547. }
  1548. $record = 0x0201; // Record identifier
  1549. $length = 0x0006; // Number of bytes to follow
  1550. $xf = $this->_XF($format); // The cell format
  1551. // Check that row and col are valid and store max and min values
  1552. if ($row >= $this->_xls_rowmax) {
  1553. return(-2);
  1554. }
  1555. if ($col >= $this->_xls_colmax) {
  1556. return(-2);
  1557. }
  1558. if ($row < $this->_dim_rowmin) {
  1559. $this->_dim_rowmin = $row;
  1560. }
  1561. if ($row > $this->_dim_rowmax) {
  1562. $this->_dim_rowmax = $row;
  1563. }
  1564. if ($col < $this->_dim_colmin) {
  1565. $this->_dim_colmin = $col;
  1566. }
  1567. if ($col > $this->_dim_colmax) {
  1568. $this->_dim_colmax = $col;
  1569. }
  1570. $header = pack("vv", $record, $length);
  1571. $data = pack("vvv", $row, $col, $xf);
  1572. $this->_append($header . $data);
  1573. return 0;
  1574. }
  1575. /**
  1576. * Write a formula to the specified row and column (zero indexed).
  1577. * The textual representation of the formula is passed to the parser in
  1578. * Parser.php which returns a packed binary string.
  1579. *
  1580. * Returns 0 : normal termination
  1581. * -1 : formula errors (bad formula)
  1582. * -2 : row or column out of range
  1583. *
  1584. * @access public
  1585. * @param integer $row Zero indexed row
  1586. * @param integer $col Zero indexed column
  1587. * @param string $formula The formula text string
  1588. * @param mixed $format The optional XF format
  1589. * @return integer
  1590. */
  1591. function writeFormula($row, $col, $formula, $format = null)
  1592. {
  1593. $record = 0x0006; // Record identifier
  1594. // Excel normally stores the last calculated value of the formula in $num.
  1595. // Clearly we are not in a position to calculate this a priori. Instead
  1596. // we set $num to zero and set the option flags in $grbit to ensure
  1597. // automatic calculation of the formula when the file is opened.
  1598. //
  1599. $xf = $this->_XF($format); // The cell format
  1600. $num = 0x00; // Current value of formula
  1601. $grbit = 0x03; // Option flags
  1602. $unknown = 0x0000; // Must be zero
  1603. // Check that row and col are valid and store max and min values
  1604. if ($this->_checkRowCol($row, $col) == false) {
  1605. return -2;
  1606. }
  1607. // Strip the '=' or '@' sign at the beginning of the formula string
  1608. if (preg_match("/^=/", $formula)) {
  1609. $formula = preg_replace("/(^=)/", "", $formula);
  1610. } elseif (preg_match("/^@/", $formula)) {
  1611. $formula = preg_replace("/(^@)/", "", $formula);
  1612. } else {
  1613. // Error handling
  1614. $this->writeString($row, $col, 'Unrecognised character for formula');
  1615. return -1;
  1616. }
  1617. // Parse the formula using the parser in Parser.php
  1618. $error = $this->_parser->parse($formula);
  1619. $formula = $this->_parser->toReversePolish();
  1620. $formlen = strlen($formula); // Length of the binary string
  1621. $length = 0x16 + $formlen; // Length of the record data
  1622. $header = pack("vv", $record, $length);
  1623. $data = pack("vvvdvVv", $row, $col, $xf, $num,
  1624. $grbit, $unknown, $formlen);
  1625. $this->_append($header . $data . $formula);
  1626. return 0;
  1627. }
  1628. /**
  1629. * Write a hyperlink.
  1630. * This is comprised of two elements: the visible label and
  1631. * the invisible link. The visible label is the same as the link unless an
  1632. * alternative string is specified. The label is written using the
  1633. * writeString() method. Therefore the 255 characters string limit applies.
  1634. * $string and $format are optional.
  1635. *
  1636. * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
  1637. * directory url.
  1638. *
  1639. * Returns 0 : normal termination
  1640. * -2 : row or column out of range
  1641. * -3 : long string truncated to 255 chars
  1642. *
  1643. * @access public
  1644. * @param integer $row Row
  1645. * @param integer $col Column
  1646. * @param string $url URL string
  1647. * @param string $string Alternative label
  1648. * @param mixed $format The cell format
  1649. * @return integer
  1650. */
  1651. function writeUrl($row, $col, $url, $string = '', $format = null)
  1652. {
  1653. // Add start row and col to arg list
  1654. return($this->_writeUrlRange($row, $col, $row, $col, $url, $string, $format));
  1655. }
  1656. /**
  1657. * This is the more general form of writeUrl(). It allows a hyperlink to be
  1658. * written to a range of cells. This function also decides the type of hyperlink
  1659. * to be written. These are either, Web (http, ftp, mailto), Internal
  1660. * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
  1661. *
  1662. * @access private
  1663. * @see writeUrl()
  1664. * @param integer $row1 Start row
  1665. * @param integer $col1 Start column
  1666. * @param integer $row2 End row
  1667. * @param integer $col2 End column
  1668. * @param string $url URL string
  1669. * @param string $string Alternative label
  1670. * @param mixed $format The cell format
  1671. * @return integer
  1672. */
  1673. function _writeUrlRange($row1, $col1, $row2, $col2, $url, $string = '', $format = null)
  1674. {
  1675. // Check for internal/external sheet links or default to web link
  1676. if (preg_match('[^internal:]', $url)) {
  1677. return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url, $string, $format));
  1678. }
  1679. if (preg_match('[^external:]', $url)) {
  1680. return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url, $string, $format));
  1681. }
  1682. return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url, $string, $format));
  1683. }
  1684. /**
  1685. * Used to write http, ftp and mailto hyperlinks.
  1686. * The link type ($options) is 0x03 is the same as absolute dir ref without
  1687. * sheet. However it is differentiated by the $unknown2 data stream.
  1688. *
  1689. * @access private
  1690. * @see writeUrl()
  1691. * @param integer $row1 Start row
  1692. * @param integer $col1 Start column
  1693. * @param integer $row2 End row
  1694. * @param integer $col2 End column
  1695. * @param string $url URL string
  1696. * @param string $str Alternative label
  1697. * @param mixed $format The cell format
  1698. * @return integer
  1699. */
  1700. function _writeUrlWeb($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1701. {
  1702. $record = 0x01B8; // Record identifier
  1703. $length = 0x00000; // Bytes to follow
  1704. if (!$format) {
  1705. $format = $this->_url_format;
  1706. }
  1707. // Write the visible label using the writeString() method.
  1708. if ($str == '') {
  1709. $str = $url;
  1710. }
  1711. $str_error = $this->writeString($row1, $col1, $str, $format);
  1712. if (($str_error == -2) || ($str_error == -3)) {
  1713. return $str_error;
  1714. }
  1715. // Pack the undocumented parts of the hyperlink stream
  1716. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  1717. $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
  1718. // Pack the option flags
  1719. $options = pack("V", 0x03);
  1720. // Convert URL to a null terminated wchar string
  1721. $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  1722. $url = $url . "\0\0\0";
  1723. // Pack the length of the URL
  1724. $url_len = pack("V", strlen($url));
  1725. // Calculate the data length
  1726. $length = 0x34 + strlen($url);
  1727. // Pack the header data
  1728. $header = pack("vv", $record, $length);
  1729. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  1730. // Write the packed data
  1731. $this->_append($header . $data .
  1732. $unknown1 . $options .
  1733. $unknown2 . $url_len . $url);
  1734. return($str_error);
  1735. }
  1736. /**
  1737. * Used to write internal reference hyperlinks such as "Sheet1!A1".
  1738. *
  1739. * @access private
  1740. * @see writeUrl()
  1741. * @param integer $row1 Start row
  1742. * @param integer $col1 Start column
  1743. * @param integer $row2 End row
  1744. * @param integer $col2 End column
  1745. * @param string $url URL string
  1746. * @param string $str Alternative label
  1747. * @param mixed $format The cell format
  1748. * @return integer
  1749. */
  1750. function _writeUrlInternal($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1751. {
  1752. $record = 0x01B8; // Record identifier
  1753. $length = 0x00000; // Bytes to follow
  1754. if (!$format) {
  1755. $format = $this->_url_format;
  1756. }
  1757. // Strip URL type
  1758. $url = preg_replace('/^internal:/', '', $url);
  1759. // Write the visible label
  1760. if ($str == '') {
  1761. $str = $url;
  1762. }
  1763. $str_error = $this->writeString($row1, $col1, $str, $format);
  1764. if (($str_error == -2) || ($str_error == -3)) {
  1765. return $str_error;
  1766. }
  1767. // Pack the undocumented parts of the hyperlink stream
  1768. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  1769. // Pack the option flags
  1770. $options = pack("V", 0x08);
  1771. // Convert the URL type and to a null terminated wchar string
  1772. $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  1773. $url = $url . "\0\0\0";
  1774. // Pack the length of the URL as chars (not wchars)
  1775. $url_len = pack("V", floor(strlen($url)/2));
  1776. // Calculate the data length
  1777. $length = 0x24 + strlen($url);
  1778. // Pack the header data
  1779. $header = pack("vv", $record, $length);
  1780. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  1781. // Write the packed data
  1782. $this->_append($header . $data .
  1783. $unknown1 . $options .
  1784. $url_len . $url);
  1785. return($str_error);
  1786. }
  1787. /**
  1788. * Write links to external directory names such as 'c:\foo.xls',
  1789. * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
  1790. *
  1791. * Note: Excel writes some relative links with the $dir_long string. We ignore
  1792. * these cases for the sake of simpler code.
  1793. *
  1794. * @access private
  1795. * @see writeUrl()
  1796. * @param integer $row1 Start row
  1797. * @param integer $col1 Start column
  1798. * @param integer $row2 End row
  1799. * @param integer $col2 End column
  1800. * @param string $url URL string
  1801. * @param string $str Alternative label
  1802. * @param mixed $format The cell format
  1803. * @return integer
  1804. */
  1805. function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1806. {
  1807. // Network drives are different. We will handle them separately
  1808. // MS/Novell network drives and shares start with \\
  1809. if (preg_match('[^external:\\\\]', $url)) {
  1810. return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
  1811. }
  1812. $record = 0x01B8; // Record identifier
  1813. $length = 0x00000; // Bytes to follow
  1814. if (!$format) {
  1815. $format = $this->_url_format;
  1816. }
  1817. // Strip URL type and change Unix dir separator to Dos style (if needed)
  1818. //
  1819. $url = preg_replace('/^external:/', '', $url);
  1820. $url = preg_replace('/\//', "\\", $url);
  1821. // Write the visible label
  1822. if ($str == '') {
  1823. $str = preg_replace('/\#/', ' - ', $url);
  1824. }
  1825. $str_error = $this->writeString($row1, $col1, $str, $format);
  1826. if (($str_error == -2) or ($str_error == -3)) {
  1827. return $str_error;
  1828. }
  1829. // Determine if the link is relative or absolute:
  1830. // relative if link contains no dir separator, "somefile.xls"
  1831. // relative if link starts with up-dir, "..\..\somefile.xls"
  1832. // otherwise, absolute
  1833. $absolute = 0x02; // Bit mask
  1834. if (!preg_match("/\\\/", $url)) {
  1835. $absolute = 0x00;
  1836. }
  1837. if (preg_match("/^\.\.\\\/", $url)) {
  1838. $absolute = 0x00;
  1839. }
  1840. $link_type = 0x01 | $absolute;
  1841. // Determine if the link contains a sheet reference and change some of the
  1842. // parameters accordingly.
  1843. // Split the dir name and sheet name (if it exists)
  1844. /*if (preg_match("/\#/", $url)) {
  1845. list($dir_long, $sheet) = split("\#", $url);
  1846. } else {
  1847. $dir_long = $url;
  1848. }
  1849. if (isset($sheet)) {
  1850. $link_type |= 0x08;
  1851. $sheet_len = pack("V", strlen($sheet) + 0x01);
  1852. $sheet = join("\0", split('', $sheet));
  1853. $sheet .= "\0\0\0";
  1854. } else {
  1855. $sheet_len = '';
  1856. $sheet = '';
  1857. }*/
  1858. $dir_long = $url;
  1859. if (preg_match("/\#/", $url)) {
  1860. $link_type |= 0x08;
  1861. }
  1862. // Pack the link type
  1863. $link_type = pack("V", $link_type);
  1864. // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
  1865. $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
  1866. $up_count = pack("v", $up_count);
  1867. // Store the short dos dir name (null terminated)
  1868. $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
  1869. // Store the long dir name as a wchar string (non-null terminated)
  1870. //$dir_long = join("\0", split('', $dir_long));
  1871. $dir_long = $dir_long . "\0";
  1872. // Pack the lengths of the dir strings
  1873. $dir_short_len = pack("V", strlen($dir_short) );
  1874. $dir_long_len = pack("V", strlen($dir_long) );
  1875. $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
  1876. // Pack the undocumented parts of the hyperlink stream
  1877. $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
  1878. $unknown2 = pack("H*",'0303000000000000C000000000000046' );
  1879. $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
  1880. $unknown4 = pack("v", 0x03 );
  1881. // Pack the main data stream
  1882. $data = pack("vvvv", $row1, $row2, $col1, $col2) .
  1883. $unknown1 .
  1884. $link_type .
  1885. $unknown2 .
  1886. $up_count .
  1887. $dir_short_len.
  1888. $dir_short .
  1889. $unknown3 .
  1890. $stream_len ;/*.
  1891. $dir_long_len .
  1892. $unknown4 .
  1893. $dir_long .
  1894. $sheet_len .
  1895. $sheet ;*/
  1896. // Pack the header data
  1897. $length = strlen($data);
  1898. $header = pack("vv", $record, $length);
  1899. // Write the packed data
  1900. $this->_append($header. $data);
  1901. return($str_error);
  1902. }
  1903. /**
  1904. * This method is used to set the height and format for a row.
  1905. *
  1906. * @access public
  1907. * @param integer $row The row to set
  1908. * @param integer $height Height we are giving to the row.
  1909. * Use null to set XF without setting height
  1910. * @param mixed $format XF format we are giving to the row
  1911. * @param bool $hidden The optional hidden attribute
  1912. * @param integer $level The optional outline level for row, in range [0,7]
  1913. */
  1914. function setRow($row, $height, $format = null, $hidden = false, $level = 0)
  1915. {
  1916. $record = 0x0208; // Record identifier
  1917. $length = 0x0010; // Number of bytes to follow
  1918. $colMic = 0x0000; // First defined column
  1919. $colMac = 0x0000; // Last defined column
  1920. $irwMac = 0x0000; // Used by Excel to optimise loading
  1921. $reserved = 0x0000; // Reserved
  1922. $grbit = 0x0000; // Option flags
  1923. $ixfe = $this->_XF($format); // XF index
  1924. if ( $height < 0 ){
  1925. $height = null;
  1926. }
  1927. // set _row_sizes so _sizeRow() can use it
  1928. $this->_row_sizes[$row] = $height;
  1929. // Use setRow($row, null, $XF) to set XF format without setting height
  1930. if ($height != null) {
  1931. $miyRw = $height * 20; // row height
  1932. } else {
  1933. $miyRw = 0xff; // default row height is 256
  1934. }
  1935. $level = max(0, min($level, 7)); // level should be between 0 and 7
  1936. $this->_outline_row_level = max($level, $this->_outline_row_level);
  1937. // Set the options flags. fUnsynced is used to show that the font and row
  1938. // heights are not compatible. This is usually the case for WriteExcel.
  1939. // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
  1940. // is collapsed. Instead it is used to indicate that the previous row is
  1941. // collapsed. The zero height flag, 0x20, is used to collapse a row.
  1942. $grbit |= $level;
  1943. if ($hidden) {
  1944. $grbit |= 0x0020;
  1945. }
  1946. $grbit |= 0x0040; // fUnsynced
  1947. if ($format) {
  1948. $grbit |= 0x0080;
  1949. }
  1950. $grbit |= 0x0100;
  1951. $header = pack("vv", $record, $length);
  1952. $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
  1953. $irwMac,$reserved, $grbit, $ixfe);
  1954. $this->_append($header.$data);
  1955. }
  1956. /**
  1957. * Writes Excel DIMENSIONS to define the area in which there is data.
  1958. *
  1959. * @access private
  1960. */
  1961. function _storeDimensions()
  1962. {
  1963. $record = 0x0200; // Record identifier
  1964. $row_min = $this->_dim_rowmin; // First row
  1965. $row_max = $this->_dim_rowmax + 1; // Last row plus 1
  1966. $col_min = $this->_dim_colmin; // First column
  1967. $col_max = $this->_dim_colmax + 1; // Last column plus 1
  1968. $reserved = 0x0000; // Reserved by Excel
  1969. if ($this->_BIFF_version == 0x0500) {
  1970. $length = 0x000A; // Number of bytes to follow
  1971. $data = pack("vvvvv", $row_min, $row_max,
  1972. $col_min, $col_max, $reserved);
  1973. } elseif ($this->_BIFF_version == 0x0600) {
  1974. $length = 0x000E;
  1975. $data = pack("VVvvv", $row_min, $row_max,
  1976. $col_min, $col_max, $reserved);
  1977. }
  1978. $header = pack("vv", $record, $length);
  1979. $this->_prepend($header.$data);
  1980. }
  1981. /**
  1982. * Write BIFF record Window2.
  1983. *
  1984. * @access private
  1985. */
  1986. function _storeWindow2()
  1987. {
  1988. $record = 0x023E; // Record identifier
  1989. if ($this->_BIFF_version == 0x0500) {
  1990. $length = 0x000A; // Number of bytes to follow
  1991. } elseif ($this->_BIFF_version == 0x0600) {
  1992. $length = 0x0012;
  1993. }
  1994. $grbit = 0x00B6; // Option flags
  1995. $rwTop = 0x0000; // Top row visible in window
  1996. $colLeft = 0x0000; // Leftmost column visible in window
  1997. // The options flags that comprise $grbit
  1998. $fDspFmla = 0; // 0 - bit
  1999. $fDspGrid = $this->_screen_gridlines; // 1
  2000. $fDspRwCol = 1; // 2
  2001. $fFrozen = $this->_frozen; // 3
  2002. $fDspZeros = 1; // 4
  2003. $fDefaultHdr = 1; // 5
  2004. $fArabic = 0; // 6
  2005. $fDspGuts = $this->_outline_on; // 7
  2006. $fFrozenNoSplit = 0; // 0 - bit
  2007. $fSelected = $this->selected; // 1
  2008. $fPaged = 1; // 2
  2009. $grbit = $fDspFmla;
  2010. $grbit |= $fDspGrid << 1;
  2011. $grbit |= $fDspRwCol << 2;
  2012. $grbit |= $fFrozen << 3;
  2013. $grbit |= $fDspZeros << 4;
  2014. $grbit |= $fDefaultHdr << 5;
  2015. $grbit |= $fArabic << 6;
  2016. $grbit |= $fDspGuts << 7;
  2017. $grbit |= $fFrozenNoSplit << 8;
  2018. $grbit |= $fSelected << 9;
  2019. $grbit |= $fPaged << 10;
  2020. $header = pack("vv", $record, $length);
  2021. $data = pack("vvv", $grbit, $rwTop, $colLeft);
  2022. // FIXME !!!
  2023. if ($this->_BIFF_version == 0x0500) {
  2024. $rgbHdr = 0x00000000; // Row/column heading and gridline color
  2025. $data .= pack("V", $rgbHdr);
  2026. } elseif ($this->_BIFF_version == 0x0600) {
  2027. $rgbHdr = 0x0040; // Row/column heading and gridline color index
  2028. $zoom_factor_page_break = 0x0000;
  2029. $zoom_factor_normal = 0x0000;
  2030. $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
  2031. }
  2032. $this->_append($header.$data);
  2033. }
  2034. /**
  2035. * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
  2036. *
  2037. * @access private
  2038. */
  2039. function _storeDefcol()
  2040. {
  2041. $record = 0x0055; // Record identifier
  2042. $length = 0x0002; // Number of bytes to follow
  2043. $colwidth = 0x0008; // Default column width
  2044. $header = pack("vv", $record, $length);
  2045. $data = pack("v", $colwidth);
  2046. $this->_prepend($header . $data);
  2047. }
  2048. /**
  2049. * Write BIFF record COLINFO to define column widths
  2050. *
  2051. * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
  2052. * length record.
  2053. *
  2054. * @access private
  2055. * @param array $col_array This is the only parameter received and is composed of the following:
  2056. * 0 => First formatted column,
  2057. * 1 => Last formatted column,
  2058. * 2 => Col width (8.43 is Excel default),
  2059. * 3 => The optional XF format of the column,
  2060. * 4 => Option flags.
  2061. * 5 => Optional outline level
  2062. */
  2063. function _storeColinfo($col_array)
  2064. {
  2065. if (isset($col_array[0])) {
  2066. $colFirst = $col_array[0];
  2067. }
  2068. if (isset($col_array[1])) {
  2069. $colLast = $col_array[1];
  2070. }
  2071. if (isset($col_array[2])) {
  2072. $coldx = $col_array[2];
  2073. } else {
  2074. $coldx = 8.43;
  2075. }
  2076. if (isset($col_array[3])) {
  2077. $format = $col_array[3];
  2078. } else {
  2079. $format = 0;
  2080. }
  2081. if (isset($col_array[4])) {
  2082. $grbit = $col_array[4];
  2083. } else {
  2084. $grbit = 0;
  2085. }
  2086. if (isset($col_array[5])) {
  2087. $level = $col_array[5];
  2088. } else {
  2089. $level = 0;
  2090. }
  2091. $record = 0x007D; // Record identifier
  2092. $length = 0x000B; // Number of bytes to follow
  2093. $coldx += 0.72; // Fudge. Excel subtracts 0.72 !?
  2094. $coldx *= 256; // Convert to units of 1/256 of a char
  2095. $ixfe = $this->_XF($format);
  2096. $reserved = 0x00; // Reserved
  2097. $level = max(0, min($level, 7));
  2098. $grbit |= $level << 8;
  2099. $header = pack("vv", $record, $length);
  2100. $data = pack("vvvvvC", $colFirst, $colLast, $coldx,
  2101. $ixfe, $grbit, $reserved);
  2102. $this->_prepend($header.$data);
  2103. }
  2104. /**
  2105. * Write BIFF record SELECTION.
  2106. *
  2107. * @access private
  2108. * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast)
  2109. * @see setSelection()
  2110. */
  2111. function _storeSelection($array)
  2112. {
  2113. list($rwFirst,$colFirst,$rwLast,$colLast) = $array;
  2114. $record = 0x001D; // Record identifier
  2115. $length = 0x000F; // Number of bytes to follow
  2116. $pnn = $this->_active_pane; // Pane position
  2117. $rwAct = $rwFirst; // Active row
  2118. $colAct = $colFirst; // Active column
  2119. $irefAct = 0; // Active cell ref
  2120. $cref = 1; // Number of refs
  2121. if (!isset($rwLast)) {
  2122. $rwLast = $rwFirst; // Last row in reference
  2123. }
  2124. if (!isset($colLast)) {
  2125. $colLast = $colFirst; // Last col in reference
  2126. }
  2127. // Swap last row/col for first row/col as necessary
  2128. if ($rwFirst > $rwLast) {
  2129. list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
  2130. }
  2131. if ($colFirst > $colLast) {
  2132. list($colFirst, $colLast) = array($colLast, $colFirst);
  2133. }
  2134. $header = pack("vv", $record, $length);
  2135. $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
  2136. $irefAct, $cref,
  2137. $rwFirst, $rwLast,
  2138. $colFirst, $colLast);
  2139. $this->_append($header . $data);
  2140. }
  2141. /**
  2142. * Store the MERGEDCELLS record for all ranges of merged cells
  2143. *
  2144. * @access private
  2145. */
  2146. function _storeMergedCells()
  2147. {
  2148. // if there are no merged cell ranges set, return
  2149. if (count($this->_merged_ranges) == 0) {
  2150. return;
  2151. }
  2152. $record = 0x00E5;
  2153. $length = 2 + count($this->_merged_ranges) * 8;
  2154. $header = pack('vv', $record, $length);
  2155. $data = pack('v', count($this->_merged_ranges));
  2156. foreach ($this->_merged_ranges as $range) {
  2157. $data .= pack('vvvv', $range[0], $range[2], $range[1], $range[3]);
  2158. }
  2159. $this->_append($header . $data);
  2160. }
  2161. /**
  2162. * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  2163. * references in a worksheet.
  2164. *
  2165. * Excel only stores references to external sheets that are used in formulas.
  2166. * For simplicity we store references to all the sheets in the workbook
  2167. * regardless of whether they are used or not. This reduces the overall
  2168. * complexity and eliminates the need for a two way dialogue between the formula
  2169. * parser the worksheet objects.
  2170. *
  2171. * @access private
  2172. * @param integer $count The number of external sheet references in this worksheet
  2173. */
  2174. function _storeExterncount($count)
  2175. {
  2176. $record = 0x0016; // Record identifier
  2177. $length = 0x0002; // Number of bytes to follow
  2178. $header = pack("vv", $record, $length);
  2179. $data = pack("v", $count);
  2180. $this->_prepend($header . $data);
  2181. }
  2182. /**
  2183. * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  2184. * formulas. A formula references a sheet name via an index. Since we store a
  2185. * reference to all of the external worksheets the EXTERNSHEET index is the same
  2186. * as the worksheet index.
  2187. *
  2188. * @access private
  2189. * @param string $sheetname The name of a external worksheet
  2190. */
  2191. function _storeExternsheet($sheetname)
  2192. {
  2193. $record = 0x0017; // Record identifier
  2194. // References to the current sheet are encoded differently to references to
  2195. // external sheets.
  2196. //
  2197. if ($this->name == $sheetname) {
  2198. $sheetname = '';
  2199. $length = 0x02; // The following 2 bytes
  2200. $cch = 1; // The following byte
  2201. $rgch = 0x02; // Self reference
  2202. } else {
  2203. $length = 0x02 + strlen($sheetname);
  2204. $cch = strlen($sheetname);
  2205. $rgch = 0x03; // Reference to a sheet in the current workbook
  2206. }
  2207. $header = pack("vv", $record, $length);
  2208. $data = pack("CC", $cch, $rgch);
  2209. $this->_prepend($header . $data . $sheetname);
  2210. }
  2211. /**
  2212. * Writes the Excel BIFF PANE record.
  2213. * The panes can either be frozen or thawed (unfrozen).
  2214. * Frozen panes are specified in terms of an integer number of rows and columns.
  2215. * Thawed panes are specified in terms of Excel's units for rows and columns.
  2216. *
  2217. * @access private
  2218. * @param array $panes This is the only parameter received and is composed of the following:
  2219. * 0 => Vertical split position,
  2220. * 1 => Horizontal split position
  2221. * 2 => Top row visible
  2222. * 3 => Leftmost column visible
  2223. * 4 => Active pane
  2224. */
  2225. function _storePanes($panes)
  2226. {
  2227. $y = isset($panes[0]) ? $panes[0] : null;
  2228. $x = isset($panes[1]) ? $panes[1] : null;
  2229. $rwTop = isset($panes[2]) ? $panes[2] : null;
  2230. $colLeft = isset($panes[3]) ? $panes[3] : null;
  2231. if (count($panes) > 4) { // if Active pane was received
  2232. $pnnAct = $panes[4];
  2233. } else {
  2234. $pnnAct = null;
  2235. }
  2236. $record = 0x0041; // Record identifier
  2237. $length = 0x000A; // Number of bytes to follow
  2238. // Code specific to frozen or thawed panes.
  2239. if ($this->_frozen) {
  2240. // Set default values for $rwTop and $colLeft
  2241. if (!isset($rwTop)) {
  2242. $rwTop = $y;
  2243. }
  2244. if (!isset($colLeft)) {
  2245. $colLeft = $x;
  2246. }
  2247. } else {
  2248. // Set default values for $rwTop and $colLeft
  2249. if (!isset($rwTop)) {
  2250. $rwTop = 0;
  2251. }
  2252. if (!isset($colLeft)) {
  2253. $colLeft = 0;
  2254. }
  2255. // Convert Excel's row and column units to the internal units.
  2256. // The default row height is 12.75
  2257. // The default column width is 8.43
  2258. // The following slope and intersection values were interpolated.
  2259. //
  2260. $y = 20*$y + 255;
  2261. $x = 113.879*$x + 390;
  2262. }
  2263. // Determine which pane should be active. There is also the undocumented
  2264. // option to override this should it be necessary: may be removed later.
  2265. //
  2266. if (!isset($pnnAct)) {
  2267. if ($x != 0 && $y != 0) {
  2268. $pnnAct = 0; // Bottom right
  2269. }
  2270. if ($x != 0 && $y == 0) {
  2271. $pnnAct = 1; // Top right
  2272. }
  2273. if ($x == 0 && $y != 0) {
  2274. $pnnAct = 2; // Bottom left
  2275. }
  2276. if ($x == 0 && $y == 0) {
  2277. $pnnAct = 3; // Top left
  2278. }
  2279. }
  2280. $this->_active_pane = $pnnAct; // Used in _storeSelection
  2281. $header = pack("vv", $record, $length);
  2282. $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
  2283. $this->_append($header . $data);
  2284. }
  2285. /**
  2286. * Store the page setup SETUP BIFF record.
  2287. *
  2288. * @access private
  2289. */
  2290. function _storeSetup()
  2291. {
  2292. $record = 0x00A1; // Record identifier
  2293. $length = 0x0022; // Number of bytes to follow
  2294. $iPaperSize = $this->_paper_size; // Paper size
  2295. $iScale = $this->_print_scale; // Print scaling factor
  2296. $iPageStart = 0x01; // Starting page number
  2297. $iFitWidth = $this->_fit_width; // Fit to number of pages wide
  2298. $iFitHeight = $this->_fit_height; // Fit to number of pages high
  2299. $grbit = 0x00; // Option flags
  2300. $iRes = 0x0258; // Print resolution
  2301. $iVRes = 0x0258; // Vertical print resolution
  2302. $numHdr = $this->_margin_head; // Header Margin
  2303. $numFtr = $this->_margin_foot; // Footer Margin
  2304. $iCopies = 0x01; // Number of copies
  2305. $fLeftToRight = 0x0; // Print over then down
  2306. $fLandscape = $this->_orientation; // Page orientation
  2307. $fNoPls = 0x0; // Setup not read from printer
  2308. $fNoColor = 0x0; // Print black and white
  2309. $fDraft = 0x0; // Print draft quality
  2310. $fNotes = 0x0; // Print notes
  2311. $fNoOrient = 0x0; // Orientation not set
  2312. $fUsePage = 0x0; // Use custom starting page
  2313. $grbit = $fLeftToRight;
  2314. $grbit |= $fLandscape << 1;
  2315. $grbit |= $fNoPls << 2;
  2316. $grbit |= $fNoColor << 3;
  2317. $grbit |= $fDraft << 4;
  2318. $grbit |= $fNotes << 5;
  2319. $grbit |= $fNoOrient << 6;
  2320. $grbit |= $fUsePage << 7;
  2321. $numHdr = pack("d", $numHdr);
  2322. $numFtr = pack("d", $numFtr);
  2323. if ($this->_byte_order) { // if it's Big Endian
  2324. $numHdr = strrev($numHdr);
  2325. $numFtr = strrev($numFtr);
  2326. }
  2327. $header = pack("vv", $record, $length);
  2328. $data1 = pack("vvvvvvvv", $iPaperSize,
  2329. $iScale,
  2330. $iPageStart,
  2331. $iFitWidth,
  2332. $iFitHeight,
  2333. $grbit,
  2334. $iRes,
  2335. $iVRes);
  2336. $data2 = $numHdr.$numFtr;
  2337. $data3 = pack("v", $iCopies);
  2338. $this->_prepend($header . $data1 . $data2 . $data3);
  2339. }
  2340. /**
  2341. * Store the header caption BIFF record.
  2342. *
  2343. * @access private
  2344. */
  2345. function _storeHeader()
  2346. {
  2347. $record = 0x0014; // Record identifier
  2348. $str = $this->_header; // header string
  2349. $cch = strlen($str); // Length of header string
  2350. if ($this->_BIFF_version == 0x0600) {
  2351. $encoding = 0x0; // TODO: Unicode support
  2352. $length = 3 + $cch; // Bytes to follow
  2353. } else {
  2354. $length = 1 + $cch; // Bytes to follow
  2355. }
  2356. $header = pack("vv", $record, $length);
  2357. if ($this->_BIFF_version == 0x0600) {
  2358. $data = pack("vC", $cch, $encoding);
  2359. } else {
  2360. $data = pack("C", $cch);
  2361. }
  2362. $this->_prepend($header.$data.$str);
  2363. }
  2364. /**
  2365. * Store the footer caption BIFF record.
  2366. *
  2367. * @access private
  2368. */
  2369. function _storeFooter()
  2370. {
  2371. $record = 0x0015; // Record identifier
  2372. $str = $this->_footer; // Footer string
  2373. $cch = strlen($str); // Length of footer string
  2374. if ($this->_BIFF_version == 0x0600) {
  2375. $encoding = 0x0; // TODO: Unicode support
  2376. $length = 3 + $cch; // Bytes to follow
  2377. } else {
  2378. $length = 1 + $cch;
  2379. }
  2380. $header = pack("vv", $record, $length);
  2381. if ($this->_BIFF_version == 0x0600) {
  2382. $data = pack("vC", $cch, $encoding);
  2383. } else {
  2384. $data = pack("C", $cch);
  2385. }
  2386. $this->_prepend($header . $data . $str);
  2387. }
  2388. /**
  2389. * Store the horizontal centering HCENTER BIFF record.
  2390. *
  2391. * @access private
  2392. */
  2393. function _storeHcenter()
  2394. {
  2395. $record = 0x0083; // Record identifier
  2396. $length = 0x0002; // Bytes to follow
  2397. $fHCenter = $this->_hcenter; // Horizontal centering
  2398. $header = pack("vv", $record, $length);
  2399. $data = pack("v", $fHCenter);
  2400. $this->_prepend($header.$data);
  2401. }
  2402. /**
  2403. * Store the vertical centering VCENTER BIFF record.
  2404. *
  2405. * @access private
  2406. */
  2407. function _storeVcenter()
  2408. {
  2409. $record = 0x0084; // Record identifier
  2410. $length = 0x0002; // Bytes to follow
  2411. $fVCenter = $this->_vcenter; // Horizontal centering
  2412. $header = pack("vv", $record, $length);
  2413. $data = pack("v", $fVCenter);
  2414. $this->_prepend($header . $data);
  2415. }
  2416. /**
  2417. * Store the LEFTMARGIN BIFF record.
  2418. *
  2419. * @access private
  2420. */
  2421. function _storeMarginLeft()
  2422. {
  2423. $record = 0x0026; // Record identifier
  2424. $length = 0x0008; // Bytes to follow
  2425. $margin = $this->_margin_left; // Margin in inches
  2426. $header = pack("vv", $record, $length);
  2427. $data = pack("d", $margin);
  2428. if ($this->_byte_order) { // if it's Big Endian
  2429. $data = strrev($data);
  2430. }
  2431. $this->_prepend($header . $data);
  2432. }
  2433. /**
  2434. * Store the RIGHTMARGIN BIFF record.
  2435. *
  2436. * @access private
  2437. */
  2438. function _storeMarginRight()
  2439. {
  2440. $record = 0x0027; // Record identifier
  2441. $length = 0x0008; // Bytes to follow
  2442. $margin = $this->_margin_right; // Margin in inches
  2443. $header = pack("vv", $record, $length);
  2444. $data = pack("d", $margin);
  2445. if ($this->_byte_order) { // if it's Big Endian
  2446. $data = strrev($data);
  2447. }
  2448. $this->_prepend($header . $data);
  2449. }
  2450. /**
  2451. * Store the TOPMARGIN BIFF record.
  2452. *
  2453. * @access private
  2454. */
  2455. function _storeMarginTop()
  2456. {
  2457. $record = 0x0028; // Record identifier
  2458. $length = 0x0008; // Bytes to follow
  2459. $margin = $this->_margin_top; // Margin in inches
  2460. $header = pack("vv", $record, $length);
  2461. $data = pack("d", $margin);
  2462. if ($this->_byte_order) { // if it's Big Endian
  2463. $data = strrev($data);
  2464. }
  2465. $this->_prepend($header . $data);
  2466. }
  2467. /**
  2468. * Store the BOTTOMMARGIN BIFF record.
  2469. *
  2470. * @access private
  2471. */
  2472. function _storeMarginBottom()
  2473. {
  2474. $record = 0x0029; // Record identifier
  2475. $length = 0x0008; // Bytes to follow
  2476. $margin = $this->_margin_bottom; // Margin in inches
  2477. $header = pack("vv", $record, $length);
  2478. $data = pack("d", $margin);
  2479. if ($this->_byte_order) { // if it's Big Endian
  2480. $data = strrev($data);
  2481. }
  2482. $this->_prepend($header . $data);
  2483. }
  2484. /**
  2485. * Merges the area given by its arguments.
  2486. * This is an Excel97/2000 method. It is required to perform more complicated
  2487. * merging than the normal setAlign('merge').
  2488. *
  2489. * @access public
  2490. * @param integer $first_row First row of the area to merge
  2491. * @param integer $first_col First column of the area to merge
  2492. * @param integer $last_row Last row of the area to merge
  2493. * @param integer $last_col Last column of the area to merge
  2494. */
  2495. function mergeCells($first_row, $first_col, $last_row, $last_col)
  2496. {
  2497. $record = 0x00E5; // Record identifier
  2498. $length = 0x000A; // Bytes to follow
  2499. $cref = 1; // Number of refs
  2500. // Swap last row/col for first row/col as necessary
  2501. if ($first_row > $last_row) {
  2502. list($first_row, $last_row) = array($last_row, $first_row);
  2503. }
  2504. if ($first_col > $last_col) {
  2505. list($first_col, $last_col) = array($last_col, $first_col);
  2506. }
  2507. $header = pack("vv", $record, $length);
  2508. $data = pack("vvvvv", $cref, $first_row, $last_row,
  2509. $first_col, $last_col);
  2510. $this->_append($header.$data);
  2511. }
  2512. /**
  2513. * Write the PRINTHEADERS BIFF record.
  2514. *
  2515. * @access private
  2516. */
  2517. function _storePrintHeaders()
  2518. {
  2519. $record = 0x002a; // Record identifier
  2520. $length = 0x0002; // Bytes to follow
  2521. $fPrintRwCol = $this->_print_headers; // Boolean flag
  2522. $header = pack("vv", $record, $length);
  2523. $data = pack("v", $fPrintRwCol);
  2524. $this->_prepend($header . $data);
  2525. }
  2526. /**
  2527. * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
  2528. * GRIDSET record.
  2529. *
  2530. * @access private
  2531. */
  2532. function _storePrintGridlines()
  2533. {
  2534. $record = 0x002b; // Record identifier
  2535. $length = 0x0002; // Bytes to follow
  2536. $fPrintGrid = $this->_print_gridlines; // Boolean flag
  2537. $header = pack("vv", $record, $length);
  2538. $data = pack("v", $fPrintGrid);
  2539. $this->_prepend($header . $data);
  2540. }
  2541. /**
  2542. * Write the GRIDSET BIFF record. Must be used in conjunction with the
  2543. * PRINTGRIDLINES record.
  2544. *
  2545. * @access private
  2546. */
  2547. function _storeGridset()
  2548. {
  2549. $record = 0x0082; // Record identifier
  2550. $length = 0x0002; // Bytes to follow
  2551. $fGridSet = !($this->_print_gridlines); // Boolean flag
  2552. $header = pack("vv", $record, $length);
  2553. $data = pack("v", $fGridSet);
  2554. $this->_prepend($header . $data);
  2555. }
  2556. /**
  2557. * Write the GUTS BIFF record. This is used to configure the gutter margins
  2558. * where Excel outline symbols are displayed. The visibility of the gutters is
  2559. * controlled by a flag in WSBOOL.
  2560. *
  2561. * @see _storeWsbool()
  2562. * @access private
  2563. */
  2564. function _storeGuts()
  2565. {
  2566. $record = 0x0080; // Record identifier
  2567. $length = 0x0008; // Bytes to follow
  2568. $dxRwGut = 0x0000; // Size of row gutter
  2569. $dxColGut = 0x0000; // Size of col gutter
  2570. $row_level = $this->_outline_row_level;
  2571. $col_level = 0;
  2572. // Calculate the maximum column outline level. The equivalent calculation
  2573. // for the row outline level is carried out in setRow().
  2574. $colcount = count($this->_colinfo);
  2575. for ($i = 0; $i < $colcount; $i++) {
  2576. // Skip cols without outline level info.
  2577. if (count($col_level) >= 6) {
  2578. $col_level = max($this->_colinfo[$i][5], $col_level);
  2579. }
  2580. }
  2581. // Set the limits for the outline levels (0 <= x <= 7).
  2582. $col_level = max(0, min($col_level, 7));
  2583. // The displayed level is one greater than the max outline levels
  2584. if ($row_level) {
  2585. $row_level++;
  2586. }
  2587. if ($col_level) {
  2588. $col_level++;
  2589. }
  2590. $header = pack("vv", $record, $length);
  2591. $data = pack("vvvv", $dxRwGut, $dxColGut, $row_level, $col_level);
  2592. $this->_prepend($header.$data);
  2593. }
  2594. /**
  2595. * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
  2596. * with the SETUP record.
  2597. *
  2598. * @access private
  2599. */
  2600. function _storeWsbool()
  2601. {
  2602. $record = 0x0081; // Record identifier
  2603. $length = 0x0002; // Bytes to follow
  2604. $grbit = 0x0000;
  2605. // The only option that is of interest is the flag for fit to page. So we
  2606. // set all the options in one go.
  2607. //
  2608. /*if ($this->_fit_page) {
  2609. $grbit = 0x05c1;
  2610. } else {
  2611. $grbit = 0x04c1;
  2612. }*/
  2613. // Set the option flags
  2614. $grbit |= 0x0001; // Auto page breaks visible
  2615. if ($this->_outline_style) {
  2616. $grbit |= 0x0020; // Auto outline styles
  2617. }
  2618. if ($this->_outline_below) {
  2619. $grbit |= 0x0040; // Outline summary below
  2620. }
  2621. if ($this->_outline_right) {
  2622. $grbit |= 0x0080; // Outline summary right
  2623. }
  2624. if ($this->_fit_page) {
  2625. $grbit |= 0x0100; // Page setup fit to page
  2626. }
  2627. if ($this->_outline_on) {
  2628. $grbit |= 0x0400; // Outline symbols displayed
  2629. }
  2630. $header = pack("vv", $record, $length);
  2631. $data = pack("v", $grbit);
  2632. $this->_prepend($header . $data);
  2633. }
  2634. /**
  2635. * Write the HORIZONTALPAGEBREAKS BIFF record.
  2636. *
  2637. * @access private
  2638. */
  2639. function _storeHbreak()
  2640. {
  2641. // Return if the user hasn't specified pagebreaks
  2642. if (empty($this->_hbreaks)) {
  2643. return;
  2644. }
  2645. // Sort and filter array of page breaks
  2646. $breaks = $this->_hbreaks;
  2647. sort($breaks, SORT_NUMERIC);
  2648. if ($breaks[0] == 0) { // don't use first break if it's 0
  2649. array_shift($breaks);
  2650. }
  2651. $record = 0x001b; // Record identifier
  2652. $cbrk = count($breaks); // Number of page breaks
  2653. if ($this->_BIFF_version == 0x0600) {
  2654. $length = 2 + 6*$cbrk; // Bytes to follow
  2655. } else {
  2656. $length = 2 + 2*$cbrk; // Bytes to follow
  2657. }
  2658. $header = pack("vv", $record, $length);
  2659. $data = pack("v", $cbrk);
  2660. // Append each page break
  2661. foreach ($breaks as $break) {
  2662. if ($this->_BIFF_version == 0x0600) {
  2663. $data .= pack("vvv", $break, 0x0000, 0x00ff);
  2664. } else {
  2665. $data .= pack("v", $break);
  2666. }
  2667. }
  2668. $this->_prepend($header.$data);
  2669. }
  2670. /**
  2671. * Write the VERTICALPAGEBREAKS BIFF record.
  2672. *
  2673. * @access private
  2674. */
  2675. function _storeVbreak()
  2676. {
  2677. // Return if the user hasn't specified pagebreaks
  2678. if (empty($this->_vbreaks)) {
  2679. return;
  2680. }
  2681. // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
  2682. // It is slightly higher in Excel 97/200, approx. 1026
  2683. $breaks = array_slice($this->_vbreaks,0,1000);
  2684. // Sort and filter array of page breaks
  2685. sort($breaks, SORT_NUMERIC);
  2686. if ($breaks[0] == 0) { // don't use first break if it's 0
  2687. array_shift($breaks);
  2688. }
  2689. $record = 0x001a; // Record identifier
  2690. $cbrk = count($breaks); // Number of page breaks
  2691. if ($this->_BIFF_version == 0x0600) {
  2692. $length = 2 + 6*$cbrk; // Bytes to follow
  2693. } else {
  2694. $length = 2 + 2*$cbrk; // Bytes to follow
  2695. }
  2696. $header = pack("vv", $record, $length);
  2697. $data = pack("v", $cbrk);
  2698. // Append each page break
  2699. foreach ($breaks as $break) {
  2700. if ($this->_BIFF_version == 0x0600) {
  2701. $data .= pack("vvv", $break, 0x0000, 0xffff);
  2702. } else {
  2703. $data .= pack("v", $break);
  2704. }
  2705. }
  2706. $this->_prepend($header . $data);
  2707. }
  2708. /**
  2709. * Set the Biff PROTECT record to indicate that the worksheet is protected.
  2710. *
  2711. * @access private
  2712. */
  2713. function _storeProtect()
  2714. {
  2715. // Exit unless sheet protection has been specified
  2716. if ($this->_protect == 0) {
  2717. return;
  2718. }
  2719. $record = 0x0012; // Record identifier
  2720. $length = 0x0002; // Bytes to follow
  2721. $fLock = $this->_protect; // Worksheet is protected
  2722. $header = pack("vv", $record, $length);
  2723. $data = pack("v", $fLock);
  2724. $this->_prepend($header.$data);
  2725. }
  2726. /**
  2727. * Write the worksheet PASSWORD record.
  2728. *
  2729. * @access private
  2730. */
  2731. function _storePassword()
  2732. {
  2733. // Exit unless sheet protection and password have been specified
  2734. if (($this->_protect == 0) || (!isset($this->_password))) {
  2735. return;
  2736. }
  2737. $record = 0x0013; // Record identifier
  2738. $length = 0x0002; // Bytes to follow
  2739. $wPassword = $this->_password; // Encoded password
  2740. $header = pack("vv", $record, $length);
  2741. $data = pack("v", $wPassword);
  2742. $this->_prepend($header . $data);
  2743. }
  2744. /**
  2745. * Insert a 24bit bitmap image in a worksheet.
  2746. *
  2747. * @access public
  2748. * @param integer $row The row we are going to insert the bitmap into
  2749. * @param integer $col The column we are going to insert the bitmap into
  2750. * @param mixed $bitmap The bitmap filename or GD-image resource
  2751. * @param integer $x The horizontal position (offset) of the image inside the cell.
  2752. * @param integer $y The vertical position (offset) of the image inside the cell.
  2753. * @param float $scale_x The horizontal scale
  2754. * @param float $scale_y The vertical scale
  2755. */
  2756. function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
  2757. {
  2758. $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
  2759. list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
  2760. // Scale the frame of the image.
  2761. $width *= $scale_x;
  2762. $height *= $scale_y;
  2763. // Calculate the vertices of the image and write the OBJ record
  2764. $this->_positionImage($col, $row, $x, $y, $width, $height);
  2765. // Write the IMDATA record to store the bitmap data
  2766. $record = 0x007f;
  2767. $length = 8 + $size;
  2768. $cf = 0x09;
  2769. $env = 0x01;
  2770. $lcb = $size;
  2771. $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
  2772. $this->_append($header.$data);
  2773. }
  2774. /**
  2775. * Calculate the vertices that define the position of the image as required by
  2776. * the OBJ record.
  2777. *
  2778. * +------------+------------+
  2779. * | A | B |
  2780. * +-----+------------+------------+
  2781. * | |(x1,y1) | |
  2782. * | 1 |(A1)._______|______ |
  2783. * | | | | |
  2784. * | | | | |
  2785. * +-----+----| BITMAP |-----+
  2786. * | | | | |
  2787. * | 2 | |______________. |
  2788. * | | | (B2)|
  2789. * | | | (x2,y2)|
  2790. * +---- +------------+------------+
  2791. *
  2792. * Example of a bitmap that covers some of the area from cell A1 to cell B2.
  2793. *
  2794. * Based on the width and height of the bitmap we need to calculate 8 vars:
  2795. * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
  2796. * The width and height of the cells are also variable and have to be taken into
  2797. * account.
  2798. * The values of $col_start and $row_start are passed in from the calling
  2799. * function. The values of $col_end and $row_end are calculated by subtracting
  2800. * the width and height of the bitmap from the width and height of the
  2801. * underlying cells.
  2802. * The vertices are expressed as a percentage of the underlying cell width as
  2803. * follows (rhs values are in pixels):
  2804. *
  2805. * x1 = X / W *1024
  2806. * y1 = Y / H *256
  2807. * x2 = (X-1) / W *1024
  2808. * y2 = (Y-1) / H *256
  2809. *
  2810. * Where: X is distance from the left side of the underlying cell
  2811. * Y is distance from the top of the underlying cell
  2812. * W is the width of the cell
  2813. * H is the height of the cell
  2814. *
  2815. * @access private
  2816. * @note the SDK incorrectly states that the height should be expressed as a
  2817. * percentage of 1024.
  2818. * @param integer $col_start Col containing upper left corner of object
  2819. * @param integer $row_start Row containing top left corner of object
  2820. * @param integer $x1 Distance to left side of object
  2821. * @param integer $y1 Distance to top of object
  2822. * @param integer $width Width of image frame
  2823. * @param integer $height Height of image frame
  2824. */
  2825. function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
  2826. {
  2827. // Initialise end cell to the same as the start cell
  2828. $col_end = $col_start; // Col containing lower right corner of object
  2829. $row_end = $row_start; // Row containing bottom right corner of object
  2830. // Zero the specified offset if greater than the cell dimensions
  2831. if ($x1 >= $this->_sizeCol($col_start)) {
  2832. $x1 = 0;
  2833. }
  2834. if ($y1 >= $this->_sizeRow($row_start)) {
  2835. $y1 = 0;
  2836. }
  2837. $width = $width + $x1 -1;
  2838. $height = $height + $y1 -1;
  2839. // Subtract the underlying cell widths to find the end cell of the image
  2840. while ($width >= $this->_sizeCol($col_end)) {
  2841. $width -= $this->_sizeCol($col_end);
  2842. $col_end++;
  2843. }
  2844. // Subtract the underlying cell heights to find the end cell of the image
  2845. while ($height >= $this->_sizeRow($row_end)) {
  2846. $height -= $this->_sizeRow($row_end);
  2847. $row_end++;
  2848. }
  2849. // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
  2850. // with zero eight or width.
  2851. //
  2852. if ($this->_sizeCol($col_start) == 0) {
  2853. return;
  2854. }
  2855. if ($this->_sizeCol($col_end) == 0) {
  2856. return;
  2857. }
  2858. if ($this->_sizeRow($row_start) == 0) {
  2859. return;
  2860. }
  2861. if ($this->_sizeRow($row_end) == 0) {
  2862. return;
  2863. }
  2864. // Convert the pixel values to the percentage value expected by Excel
  2865. $x1 = $x1 / $this->_sizeCol($col_start) * 1024;
  2866. $y1 = $y1 / $this->_sizeRow($row_start) * 256;
  2867. $x2 = $width / $this->_sizeCol($col_end) * 1024; // Distance to right side of object
  2868. $y2 = $height / $this->_sizeRow($row_end) * 256; // Distance to bottom of object
  2869. $this->_storeObjPicture($col_start, $x1,
  2870. $row_start, $y1,
  2871. $col_end, $x2,
  2872. $row_end, $y2);
  2873. }
  2874. /**
  2875. * Convert the width of a cell from user's units to pixels. By interpolation
  2876. * the relationship is: y = 7x +5. If the width hasn't been set by the user we
  2877. * use the default value. If the col is hidden we use a value of zero.
  2878. *
  2879. * @access private
  2880. * @param integer $col The column
  2881. * @return integer The width in pixels
  2882. */
  2883. function _sizeCol($col)
  2884. {
  2885. // Look up the cell value to see if it has been changed
  2886. if (isset($this->col_sizes[$col])) {
  2887. if ($this->col_sizes[$col] == 0) {
  2888. return(0);
  2889. } else {
  2890. return(floor(7 * $this->col_sizes[$col] + 5));
  2891. }
  2892. } else {
  2893. return(64);
  2894. }
  2895. }
  2896. /**
  2897. * Convert the height of a cell from user's units to pixels. By interpolation
  2898. * the relationship is: y = 4/3x. If the height hasn't been set by the user we
  2899. * use the default value. If the row is hidden we use a value of zero. (Not
  2900. * possible to hide row yet).
  2901. *
  2902. * @access private
  2903. * @param integer $row The row
  2904. * @return integer The width in pixels
  2905. */
  2906. function _sizeRow($row)
  2907. {
  2908. // Look up the cell value to see if it has been changed
  2909. if (isset($this->_row_sizes[$row])) {
  2910. if ($this->_row_sizes[$row] == 0) {
  2911. return(0);
  2912. } else {
  2913. return(floor(4/3 * $this->_row_sizes[$row]));
  2914. }
  2915. } else {
  2916. return(17);
  2917. }
  2918. }
  2919. /**
  2920. * Store the OBJ record that precedes an IMDATA record. This could be generalise
  2921. * to support other Excel objects.
  2922. *
  2923. * @access private
  2924. * @param integer $colL Column containing upper left corner of object
  2925. * @param integer $dxL Distance from left side of cell
  2926. * @param integer $rwT Row containing top left corner of object
  2927. * @param integer $dyT Distance from top of cell
  2928. * @param integer $colR Column containing lower right corner of object
  2929. * @param integer $dxR Distance from right of cell
  2930. * @param integer $rwB Row containing bottom right corner of object
  2931. * @param integer $dyB Distance from bottom of cell
  2932. */
  2933. function _storeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
  2934. {
  2935. $record = 0x005d; // Record identifier
  2936. $length = 0x003c; // Bytes to follow
  2937. $cObj = 0x0001; // Count of objects in file (set to 1)
  2938. $OT = 0x0008; // Object type. 8 = Picture
  2939. $id = 0x0001; // Object ID
  2940. $grbit = 0x0614; // Option flags
  2941. $cbMacro = 0x0000; // Length of FMLA structure
  2942. $Reserved1 = 0x0000; // Reserved
  2943. $Reserved2 = 0x0000; // Reserved
  2944. $icvBack = 0x09; // Background colour
  2945. $icvFore = 0x09; // Foreground colour
  2946. $fls = 0x00; // Fill pattern
  2947. $fAuto = 0x00; // Automatic fill
  2948. $icv = 0x08; // Line colour
  2949. $lns = 0xff; // Line style
  2950. $lnw = 0x01; // Line weight
  2951. $fAutoB = 0x00; // Automatic border
  2952. $frs = 0x0000; // Frame style
  2953. $cf = 0x0009; // Image format, 9 = bitmap
  2954. $Reserved3 = 0x0000; // Reserved
  2955. $cbPictFmla = 0x0000; // Length of FMLA structure
  2956. $Reserved4 = 0x0000; // Reserved
  2957. $grbit2 = 0x0001; // Option flags
  2958. $Reserved5 = 0x0000; // Reserved
  2959. $header = pack("vv", $record, $length);
  2960. $data = pack("V", $cObj);
  2961. $data .= pack("v", $OT);
  2962. $data .= pack("v", $id);
  2963. $data .= pack("v", $grbit);
  2964. $data .= pack("v", $colL);
  2965. $data .= pack("v", $dxL);
  2966. $data .= pack("v", $rwT);
  2967. $data .= pack("v", $dyT);
  2968. $data .= pack("v", $colR);
  2969. $data .= pack("v", $dxR);
  2970. $data .= pack("v", $rwB);
  2971. $data .= pack("v", $dyB);
  2972. $data .= pack("v", $cbMacro);
  2973. $data .= pack("V", $Reserved1);
  2974. $data .= pack("v", $Reserved2);
  2975. $data .= pack("C", $icvBack);
  2976. $data .= pack("C", $icvFore);
  2977. $data .= pack("C", $fls);
  2978. $data .= pack("C", $fAuto);
  2979. $data .= pack("C", $icv);
  2980. $data .= pack("C", $lns);
  2981. $data .= pack("C", $lnw);
  2982. $data .= pack("C", $fAutoB);
  2983. $data .= pack("v", $frs);
  2984. $data .= pack("V", $cf);
  2985. $data .= pack("v", $Reserved3);
  2986. $data .= pack("v", $cbPictFmla);
  2987. $data .= pack("v", $Reserved4);
  2988. $data .= pack("v", $grbit2);
  2989. $data .= pack("V", $Reserved5);
  2990. $this->_append($header . $data);
  2991. }
  2992. /**
  2993. * Convert a GD-image into the internal format.
  2994. *
  2995. * @access private
  2996. * @param resource $image The image to process
  2997. * @return array Array with data and properties of the bitmap
  2998. */
  2999. function _processBitmapGd($image) {
  3000. $width = imagesx($image);
  3001. $height = imagesy($image);
  3002. $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  3003. for ($j=$height; $j--; ) {
  3004. for ($i=0; $i < $width; $i++) {
  3005. $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
  3006. foreach (array("red", "green", "blue") as $key) {
  3007. $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
  3008. }
  3009. $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
  3010. }
  3011. if (3*$width % 4) {
  3012. $data .= str_repeat("\x00", 4 - 3*$width % 4);
  3013. }
  3014. }
  3015. return array($width, $height, strlen($data), $data);
  3016. }
  3017. /**
  3018. * Convert a 24 bit bitmap into the modified internal format used by Windows.
  3019. * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
  3020. * MSDN library.
  3021. *
  3022. * @access private
  3023. * @param string $bitmap The bitmap to process
  3024. * @return array Array with data and properties of the bitmap
  3025. */
  3026. function _processBitmap($bitmap)
  3027. {
  3028. // Open file.
  3029. $bmp_fd = @fopen($bitmap,"rb");
  3030. if (!$bmp_fd) {
  3031. throw new Exception("Couldn't import $bitmap");
  3032. }
  3033. // Slurp the file into a string.
  3034. $data = fread($bmp_fd, filesize($bitmap));
  3035. // Check that the file is big enough to be a bitmap.
  3036. if (strlen($data) <= 0x36) {
  3037. throw new Exception("$bitmap doesn't contain enough data.\n");
  3038. }
  3039. // The first 2 bytes are used to identify the bitmap.
  3040. $identity = unpack("A2ident", $data);
  3041. if ($identity['ident'] != "BM") {
  3042. throw new Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
  3043. }
  3044. // Remove bitmap data: ID.
  3045. $data = substr($data, 2);
  3046. // Read and remove the bitmap size. This is more reliable than reading
  3047. // the data size at offset 0x22.
  3048. //
  3049. $size_array = unpack("Vsa", substr($data, 0, 4));
  3050. $size = $size_array['sa'];
  3051. $data = substr($data, 4);
  3052. $size -= 0x36; // Subtract size of bitmap header.
  3053. $size += 0x0C; // Add size of BIFF header.
  3054. // Remove bitmap data: reserved, offset, header length.
  3055. $data = substr($data, 12);
  3056. // Read and remove the bitmap width and height. Verify the sizes.
  3057. $width_and_height = unpack("V2", substr($data, 0, 8));
  3058. $width = $width_and_height[1];
  3059. $height = $width_and_height[2];
  3060. $data = substr($data, 8);
  3061. if ($width > 0xFFFF) {
  3062. throw new Exception("$bitmap: largest image width supported is 65k.\n");
  3063. }
  3064. if ($height > 0xFFFF) {
  3065. throw new Exception("$bitmap: largest image height supported is 65k.\n");
  3066. }
  3067. // Read and remove the bitmap planes and bpp data. Verify them.
  3068. $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
  3069. $data = substr($data, 4);
  3070. if ($planes_and_bitcount[2] != 24) { // Bitcount
  3071. throw new Exception("$bitmap isn't a 24bit true color bitmap.\n");
  3072. }
  3073. if ($planes_and_bitcount[1] != 1) {
  3074. throw new Exception("$bitmap: only 1 plane supported in bitmap image.\n");
  3075. }
  3076. // Read and remove the bitmap compression. Verify compression.
  3077. $compression = unpack("Vcomp", substr($data, 0, 4));
  3078. $data = substr($data, 4);
  3079. //$compression = 0;
  3080. if ($compression['comp'] != 0) {
  3081. throw new Exception("$bitmap: compression not supported in bitmap image.\n");
  3082. }
  3083. // Remove bitmap data: data size, hres, vres, colours, imp. colours.
  3084. $data = substr($data, 20);
  3085. // Add the BITMAPCOREHEADER data
  3086. $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  3087. $data = $header . $data;
  3088. return (array($width, $height, $size, $data));
  3089. }
  3090. /**
  3091. * Store the window zoom factor. This should be a reduced fraction but for
  3092. * simplicity we will store all fractions with a numerator of 100.
  3093. *
  3094. * @access private
  3095. */
  3096. function _storeZoom()
  3097. {
  3098. // If scale is 100 we don't need to write a record
  3099. if ($this->_zoom == 100) {
  3100. return;
  3101. }
  3102. $record = 0x00A0; // Record identifier
  3103. $length = 0x0004; // Bytes to follow
  3104. $header = pack("vv", $record, $length);
  3105. $data = pack("vv", $this->_zoom, 100);
  3106. $this->_append($header . $data);
  3107. }
  3108. /**
  3109. * Store the DVAL and DV records.
  3110. *
  3111. * @access private
  3112. */
  3113. function _storeDataValidity()
  3114. {
  3115. $record = 0x01b2; // Record identifier
  3116. $length = 0x0012; // Bytes to follow
  3117. $grbit = 0x0002; // Prompt box at cell, no cached validity data at DV records
  3118. $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
  3119. $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
  3120. $objId = 0xffffffff; // Object identifier of drop down arrow object, or -1 if not visible
  3121. $header = pack('vv', $record, $length);
  3122. $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
  3123. count($this->_dv));
  3124. $this->_append($header.$data);
  3125. $record = 0x01be; // Record identifier
  3126. foreach ($this->_dv as $dv) {
  3127. $length = strlen($dv); // Bytes to follow
  3128. $header = pack("vv", $record, $length);
  3129. $this->_append($header . $dv);
  3130. }
  3131. }
  3132. }