PageRenderTime 64ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

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

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