PageRenderTime 90ms CodeModel.GetById 41ms RepoModel.GetById 2ms app.codeStats 0ms

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

#
PHP | 3529 lines | 1756 code | 427 blank | 1346 comment | 276 complexity | 011406da9d9a1f37221215d35e34b9fb 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, $numberFormat = 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 (($numberFormat != 'General') && (PHPExcel_Shared_Date::isDateTimeFormatCode($numberFormat))) {
  999. if (is_string($token)) {
  1000. // Error string
  1001. return $this->writeString($row, $col, $token, $format);
  1002. } elseif (!is_float($token)) {
  1003. // PHP serialized date/time or date/time object
  1004. return $this->writeNumber($row, $col, PHPExcel_Shared_Date::PHPToExcel($token), $format);
  1005. } else {
  1006. // Excel serialized date/time
  1007. return $this->writeNumber($row, $col, $token, $format);
  1008. }
  1009. } elseif (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/", $token)) {
  1010. // Match number
  1011. return $this->writeNumber($row, $col, $token, $format);
  1012. } elseif (preg_match("/^[fh]tt?p:\/\//", $token)) {
  1013. // Match http or ftp URL
  1014. return $this->writeUrl($row, $col, $token, '', $format);
  1015. } elseif (preg_match("/^mailto:/", $token)) {
  1016. // Match mailto:
  1017. return $this->writeUrl($row, $col, $token, '', $format);
  1018. } elseif (preg_match("/^(?:in|ex)ternal:/", $token)) {
  1019. // Match internal or external sheet link
  1020. return $this->writeUrl($row, $col, $token, '', $format);
  1021. } elseif (preg_match("/^=/", $token)) {
  1022. // Match formula
  1023. return $this->writeFormula($row, $col, $token, $format);
  1024. } elseif (preg_match("/^@/", $token)) {
  1025. // Match formula
  1026. return $this->writeFormula($row, $col, $token, $format);
  1027. } elseif ($token == '') {
  1028. // Match blank
  1029. return $this->writeBlank($row, $col, $format);
  1030. } else {
  1031. // Default: match string
  1032. return $this->writeString($row, $col, $token, $format);
  1033. }
  1034. }
  1035. /**
  1036. * Write an array of values as a row
  1037. *
  1038. * @access public
  1039. * @param integer $row The row we are writing to
  1040. * @param integer $col The first col (leftmost col) we are writing to
  1041. * @param array $val The array of values to write
  1042. * @param mixed $format The optional format to apply to the cell
  1043. */
  1044. function writeRow($row, $col, $val, $format = null, $numberFormat = null)
  1045. {
  1046. $retval = '';
  1047. if (is_array($val)) {
  1048. foreach ($val as $v) {
  1049. if (is_array($v)) {
  1050. $this->writeCol($row, $col, $v, $format, $numberFormat = null);
  1051. } else {
  1052. $this->write($row, $col, $v, $format, $numberFormat);
  1053. }
  1054. $col++;
  1055. }
  1056. } else {
  1057. throw new Exception('$val needs to be an array');
  1058. }
  1059. return($retval);
  1060. }
  1061. /**
  1062. * Write an array of values as a column
  1063. *
  1064. * @access public
  1065. * @param integer $row The first row (uppermost row) we are writing to
  1066. * @param integer $col The col we are writing to
  1067. * @param array $val The array of values to write
  1068. * @param mixed $format The optional format to apply to the cell
  1069. */
  1070. function writeCol($row, $col, $val, $format = null, $numberFormat = null)
  1071. {
  1072. $retval = '';
  1073. if (is_array($val)) {
  1074. foreach ($val as $v) {
  1075. $this->write($row, $col, $v, $format, $numberFormat);
  1076. $row++;
  1077. }
  1078. } else {
  1079. throw new Exception('$val needs to be an array');
  1080. }
  1081. return($retval);
  1082. }
  1083. /**
  1084. * Returns an index to the XF record in the workbook
  1085. *
  1086. * @access private
  1087. * @param mixed &$format The optional XF format
  1088. * @return integer The XF record index
  1089. */
  1090. function _XF(&$format)
  1091. {
  1092. if ($format) {
  1093. return($format->getXfIndex());
  1094. } else {
  1095. return(0x0F);
  1096. }
  1097. }
  1098. /******************************************************************************
  1099. *******************************************************************************
  1100. *
  1101. * Internal methods
  1102. */
  1103. /**
  1104. * Store Worksheet data in memory using the parent's class append() or to a
  1105. * temporary file, the default.
  1106. *
  1107. * @access private
  1108. * @param string $data The binary data to append
  1109. */
  1110. function _append($data)
  1111. {
  1112. if ($this->_using_tmpfile) {
  1113. // Add CONTINUE records if necessary
  1114. if (strlen($data) > $this->_limit) {
  1115. $data = $this->_addContinue($data);
  1116. }
  1117. fwrite($this->_filehandle, $data);
  1118. $this->_datasize += strlen($data);
  1119. } else {
  1120. parent::_append($data);
  1121. }
  1122. }
  1123. /**
  1124. * Substitute an Excel cell reference in A1 notation for zero based row and
  1125. * column values in an argument list.
  1126. *
  1127. * Ex: ("A4", "Hello") is converted to (3, 0, "Hello").
  1128. *
  1129. * @access private
  1130. * @param string $cell The cell reference. Or range of cells.
  1131. * @return array
  1132. */
  1133. function _substituteCellref($cell)
  1134. {
  1135. $cell = strtoupper($cell);
  1136. // Convert a column range: 'A:A' or 'B:G'
  1137. if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/", $cell, $match)) {
  1138. list($no_use, $col1) = $this->_cellToRowcol($match[1] .'1'); // Add a dummy row
  1139. list($no_use, $col2) = $this->_cellToRowcol($match[2] .'1'); // Add a dummy row
  1140. return(array($col1, $col2));
  1141. }
  1142. // Convert a cell range: 'A1:B7'
  1143. if (preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/", $cell, $match)) {
  1144. list($row1, $col1) = $this->_cellToRowcol($match[1]);
  1145. list($row2, $col2) = $this->_cellToRowcol($match[2]);
  1146. return(array($row1, $col1, $row2, $col2));
  1147. }
  1148. // Convert a cell reference: 'A1' or 'AD2000'
  1149. if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/", $cell)) {
  1150. list($row1, $col1) = $this->_cellToRowcol($match[1]);
  1151. return(array($row1, $col1));
  1152. }
  1153. // TODO use real error codes
  1154. throw new Exception("Unknown cell reference $cell");
  1155. }
  1156. /**
  1157. * Convert an Excel cell reference in A1 notation to a zero based row and column
  1158. * reference; converts C1 to (0, 2).
  1159. *
  1160. * @access private
  1161. * @param string $cell The cell reference.
  1162. * @return array containing (row, column)
  1163. */
  1164. function _cellToRowcol($cell)
  1165. {
  1166. preg_match("/\$?([A-I]?[A-Z])\$?(\d+)/",$cell,$match);
  1167. $col = $match[1];
  1168. $row = $match[2];
  1169. // Convert base26 column string to number
  1170. $chars = split('', $col);
  1171. $expn = 0;
  1172. $col = 0;
  1173. while ($chars) {
  1174. $char = array_pop($chars); // LS char first
  1175. $col += (ord($char) -ord('A') +1) * pow(26,$expn);
  1176. $expn++;
  1177. }
  1178. // Convert 1-index to zero-index
  1179. $row--;
  1180. $col--;
  1181. return(array($row, $col));
  1182. }
  1183. /**
  1184. * Based on the algorithm provided by Daniel Rentz of OpenOffice.
  1185. *
  1186. * @access private
  1187. * @param string $plaintext The password to be encoded in plaintext.
  1188. * @return string The encoded password
  1189. */
  1190. function _encodePassword($plaintext)
  1191. {
  1192. $password = 0x0000;
  1193. $i = 1; // char position
  1194. // split the plain text password in its component characters
  1195. $chars = preg_split('//', $plaintext, -1, PREG_SPLIT_NO_EMPTY);
  1196. foreach ($chars as $char) {
  1197. $value = ord($char) << $i; // shifted ASCII value
  1198. $rotated_bits = $value >> 15; // rotated bits beyond bit 15
  1199. $value &= 0x7fff; // first 15 bits
  1200. $password ^= ($value | $rotated_bits);
  1201. $i++;
  1202. }
  1203. $password ^= strlen($plaintext);
  1204. $password ^= 0xCE4B;
  1205. return($password);
  1206. }
  1207. /**
  1208. * This method sets the properties for outlining and grouping. The defaults
  1209. * correspond to Excel's defaults.
  1210. *
  1211. * @param bool $visible
  1212. * @param bool $symbols_below
  1213. * @param bool $symbols_right
  1214. * @param bool $auto_style
  1215. */
  1216. function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
  1217. {
  1218. $this->_outline_on = $visible;
  1219. $this->_outline_below = $symbols_below;
  1220. $this->_outline_right = $symbols_right;
  1221. $this->_outline_style = $auto_style;
  1222. // Ensure this is a boolean vale for Window2
  1223. if ($this->_outline_on) {
  1224. $this->_outline_on = 1;
  1225. }
  1226. }
  1227. /******************************************************************************
  1228. *******************************************************************************
  1229. *
  1230. * BIFF RECORDS
  1231. */
  1232. /**
  1233. * Write a double to the specified row and column (zero indexed).
  1234. * An integer can be written as a double. Excel will display an
  1235. * integer. $format is optional.
  1236. *
  1237. * Returns 0 : normal termination
  1238. * -2 : row or column out of range
  1239. *
  1240. * @access public
  1241. * @param integer $row Zero indexed row
  1242. * @param integer $col Zero indexed column
  1243. * @param float $num The number to write
  1244. * @param mixed $format The optional XF format
  1245. * @return integer
  1246. */
  1247. function writeNumber($row, $col, $num, $format = null)
  1248. {
  1249. $record = 0x0203; // Record identifier
  1250. $length = 0x000E; // Number of bytes to follow
  1251. $xf = $this->_XF($format); // The cell format
  1252. // Check that row and col are valid and store max and min values
  1253. if ($row >= $this->_xls_rowmax) {
  1254. return(-2);
  1255. }
  1256. if ($col >= $this->_xls_colmax) {
  1257. return(-2);
  1258. }
  1259. if ($row < $this->_dim_rowmin) {
  1260. $this->_dim_rowmin = $row;
  1261. }
  1262. if ($row > $this->_dim_rowmax) {
  1263. $this->_dim_rowmax = $row;
  1264. }
  1265. if ($col < $this->_dim_colmin) {
  1266. $this->_dim_colmin = $col;
  1267. }
  1268. if ($col > $this->_dim_colmax) {
  1269. $this->_dim_colmax = $col;
  1270. }
  1271. $header = pack("vv", $record, $length);
  1272. $data = pack("vvv", $row, $col, $xf);
  1273. $xl_double = pack("d", $num);
  1274. if ($this->_byte_order) { // if it's Big Endian
  1275. $xl_double = strrev($xl_double);
  1276. }
  1277. $this->_append($header.$data.$xl_double);
  1278. return(0);
  1279. }
  1280. /**
  1281. * Write a string to the specified row and column (zero indexed).
  1282. * NOTE: there is an Excel 5 defined limit of 255 characters.
  1283. * $format is optional.
  1284. * Returns 0 : normal termination
  1285. * -2 : row or column out of range
  1286. * -3 : long string truncated to 255 chars
  1287. *
  1288. * @access public
  1289. * @param integer $row Zero indexed row
  1290. * @param integer $col Zero indexed column
  1291. * @param string $str The string to write
  1292. * @param mixed $format The XF format for the cell
  1293. * @return integer
  1294. */
  1295. function writeString($row, $col, $str, $format = null)
  1296. {
  1297. if ($this->_BIFF_version == 0x0600) {
  1298. return $this->writeStringBIFF8($row, $col, $str, $format);
  1299. }
  1300. $strlen = strlen($str);
  1301. $record = 0x0204; // Record identifier
  1302. $length = 0x0008 + $strlen; // Bytes to follow
  1303. $xf = $this->_XF($format); // The cell format
  1304. $str_error = 0;
  1305. // Check that row and col are valid and store max and min values
  1306. if ($row >= $this->_xls_rowmax) {
  1307. return(-2);
  1308. }
  1309. if ($col >= $this->_xls_colmax) {
  1310. return(-2);
  1311. }
  1312. if ($row < $this->_dim_rowmin) {
  1313. $this->_dim_rowmin = $row;
  1314. }
  1315. if ($row > $this->_dim_rowmax) {
  1316. $this->_dim_rowmax = $row;
  1317. }
  1318. if ($col < $this->_dim_colmin) {
  1319. $this->_dim_colmin = $col;
  1320. }
  1321. if ($col > $this->_dim_colmax) {
  1322. $this->_dim_colmax = $col;
  1323. }
  1324. if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
  1325. $str = substr($str, 0, $this->_xls_strmax);
  1326. $length = 0x0008 + $this->_xls_strmax;
  1327. $strlen = $this->_xls_strmax;
  1328. $str_error = -3;
  1329. }
  1330. $header = pack("vv", $record, $length);
  1331. $data = pack("vvvv", $row, $col, $xf, $strlen);
  1332. $this->_append($header . $data . $str);
  1333. return($str_error);
  1334. }
  1335. var $_biff8_input_encoding = 'UTF-16LE';
  1336. function setBIFF8InputEncoding($encoding) {
  1337. if ($encoding != 'UTF-16LE' && !function_exists('iconv')) {
  1338. $this->raiseError("Using an input encoding other than UTF-16LE requires PHP support for iconv");
  1339. }
  1340. $this->_biff8_input_encoding = $encoding;
  1341. }
  1342. /**
  1343. * Sets Input Encoding for writing strings
  1344. *
  1345. * @access public
  1346. * @param string $encoding The encoding. Ex: 'UTF-16LE', 'utf-8', 'ISO-859-7'
  1347. */
  1348. function setInputEncoding($encoding)
  1349. {
  1350. if ($encoding != 'UTF-16LE' && !function_exists('iconv')) {
  1351. throw new Exception("Using an input encoding other than UTF-16LE requires PHP support for iconv");
  1352. }
  1353. $this->_input_encoding = $encoding;
  1354. }
  1355. /**
  1356. * Write a string to the specified row and column (zero indexed).
  1357. * This is the BIFF8 version (no 255 chars limit).
  1358. * $format is optional.
  1359. * Returns 0 : normal termination
  1360. * -2 : row or column out of range
  1361. * -3 : long string truncated to 255 chars
  1362. *
  1363. * @access public
  1364. * @param integer $row Zero indexed row
  1365. * @param integer $col Zero indexed column
  1366. * @param string $str The string to write
  1367. * @param mixed $format The XF format for the cell
  1368. * @return integer
  1369. */
  1370. function writeStringBIFF8($row, $col, $str, $format = null)
  1371. {
  1372. if ($this->_input_encoding == 'UTF-16LE')
  1373. {
  1374. $strlen = function_exists('mb_strlen') ? mb_strlen($str, 'UTF-16LE') : (strlen($str) / 2);
  1375. $encoding = 0x1;
  1376. }
  1377. elseif ($this->_input_encoding != '')
  1378. {
  1379. $str = iconv($this->_input_encoding, 'UTF-16LE', $str);
  1380. $strlen = function_exists('mb_strlen') ? mb_strlen($str, 'UTF-16LE') : (strlen($str) / 2);
  1381. $encoding = 0x1;
  1382. }
  1383. else
  1384. {
  1385. $strlen = strlen($str);
  1386. $encoding = 0x0;
  1387. }
  1388. $record = 0x00FD; // Record identifier
  1389. $length = 0x000A; // Bytes to follow
  1390. $xf = $this->_XF($format); // The cell format
  1391. $str_error = 0;
  1392. // Check that row and col are valid and store max and min values
  1393. if ($this->_checkRowCol($row, $col) == false) {
  1394. return -2;
  1395. }
  1396. $str = pack('vC', $strlen, $encoding).$str;
  1397. /* check if string is already present */
  1398. if (!isset($this->_str_table[$str])) {
  1399. $this->_str_table[$str] = $this->_str_unique++;
  1400. }
  1401. $this->_str_total++;
  1402. $header = pack('vv', $record, $length);
  1403. $data = pack('vvvV', $row, $col, $xf, $this->_str_table[$str]);
  1404. $this->_append($header.$data);
  1405. return $str_error;
  1406. }
  1407. /**
  1408. * Check row and col before writing to a cell, and update the sheet's
  1409. * dimensions accordingly
  1410. *
  1411. * @access private
  1412. * @param integer $row Zero indexed row
  1413. * @param integer $col Zero indexed column
  1414. * @return boolean true for success, false if row and/or col are grester
  1415. * then maximums allowed.
  1416. */
  1417. function _checkRowCol($row, $col)
  1418. {
  1419. if ($row >= $this->_xls_rowmax) {
  1420. return false;
  1421. }
  1422. if ($col >= $this->_xls_colmax) {
  1423. return false;
  1424. }
  1425. if ($row < $this->_dim_rowmin) {
  1426. $this->_dim_rowmin = $row;
  1427. }
  1428. if ($row > $this->_dim_rowmax) {
  1429. $this->_dim_rowmax = $row;
  1430. }
  1431. if ($col < $this->_dim_colmin) {
  1432. $this->_dim_colmin = $col;
  1433. }
  1434. if ($col > $this->_dim_colmax) {
  1435. $this->_dim_colmax = $col;
  1436. }
  1437. return true;
  1438. }
  1439. /**
  1440. * Writes a note associated with the cell given by the row and column.
  1441. * NOTE records don't have a length limit.
  1442. *
  1443. * @access public
  1444. * @param integer $row Zero indexed row
  1445. * @param integer $col Zero indexed column
  1446. * @param string $note The note to write
  1447. */
  1448. function writeNote($row, $col, $note)
  1449. {
  1450. $note_length = strlen($note);
  1451. $record = 0x001C; // Record identifier
  1452. $max_length = 2048; // Maximun length for a NOTE record
  1453. //$length = 0x0006 + $note_length; // Bytes to follow
  1454. // Check that row and col are valid and store max and min values
  1455. if ($row >= $this->_xls_rowmax) {
  1456. return(-2);
  1457. }
  1458. if ($col >= $this->_xls_colmax) {
  1459. return(-2);
  1460. }
  1461. if ($row < $this->_dim_rowmin) {
  1462. $this->_dim_rowmin = $row;
  1463. }
  1464. if ($row > $this->_dim_rowmax) {
  1465. $this->_dim_rowmax = $row;
  1466. }
  1467. if ($col < $this->_dim_colmin) {
  1468. $this->_dim_colmin = $col;
  1469. }
  1470. if ($col > $this->_dim_colmax) {
  1471. $this->_dim_colmax = $col;
  1472. }
  1473. // Length for this record is no more than 2048 + 6
  1474. $length = 0x0006 + min($note_length, 2048);
  1475. $header = pack("vv", $record, $length);
  1476. $data = pack("vvv", $row, $col, $note_length);
  1477. $this->_append($header . $data . substr($note, 0, 2048));
  1478. for ($i = $max_length; $i < $note_length; $i += $max_length) {
  1479. $chunk = substr($note, $i, $max_length);
  1480. $length = 0x0006 + strlen($chunk);
  1481. $header = pack("vv", $record, $length);
  1482. $data = pack("vvv", -1, 0, strlen($chunk));
  1483. $this->_append($header.$data.$chunk);
  1484. }
  1485. return(0);
  1486. }
  1487. /**
  1488. * Write a blank cell to the specified row and column (zero indexed).
  1489. * A blank cell is used to specify formatting without adding a string
  1490. * or a number.
  1491. *
  1492. * A blank cell without a format serves no purpose. Therefore, we don't write
  1493. * a BLANK record unless a format is specified.
  1494. *
  1495. * Returns 0 : normal termination (including no format)
  1496. * -1 : insufficient number of arguments
  1497. * -2 : row or column out of range
  1498. *
  1499. * @access public
  1500. * @param integer $row Zero indexed row
  1501. * @param integer $col Zero indexed column
  1502. * @param mixed $format The XF format
  1503. */
  1504. function writeBlank($row, $col, $format)
  1505. {
  1506. // Don't write a blank cell unless it has a format
  1507. if (!$format) {
  1508. return(0);
  1509. }
  1510. $record = 0x0201; // Record identifier
  1511. $length = 0x0006; // Number of bytes to follow
  1512. $xf = $this->_XF($format); // The cell format
  1513. // Check that row and col are valid and store max and min values
  1514. if ($row >= $this->_xls_rowmax) {
  1515. return(-2);
  1516. }
  1517. if ($col >= $this->_xls_colmax) {
  1518. return(-2);
  1519. }
  1520. if ($row < $this->_dim_rowmin) {
  1521. $this->_dim_rowmin = $row;
  1522. }
  1523. if ($row > $this->_dim_rowmax) {
  1524. $this->_dim_rowmax = $row;
  1525. }
  1526. if ($col < $this->_dim_colmin) {
  1527. $this->_dim_colmin = $col;
  1528. }
  1529. if ($col > $this->_dim_colmax) {
  1530. $this->_dim_colmax = $col;
  1531. }
  1532. $header = pack("vv", $record, $length);
  1533. $data = pack("vvv", $row, $col, $xf);
  1534. $this->_append($header . $data);
  1535. return 0;
  1536. }
  1537. /**
  1538. * Write a formula to the specified row and column (zero indexed).
  1539. * The textual representation of the formula is passed to the parser in
  1540. * Parser.php which returns a packed binary string.
  1541. *
  1542. * Returns 0 : normal termination
  1543. * -1 : formula errors (bad formula)
  1544. * -2 : row or column out of range
  1545. *
  1546. * @access public
  1547. * @param integer $row Zero indexed row
  1548. * @param integer $col Zero indexed column
  1549. * @param string $formula The formula text string
  1550. * @param mixed $format The optional XF format
  1551. * @return integer
  1552. */
  1553. function writeFormula($row, $col, $formula, $format = null)
  1554. {
  1555. $record = 0x0006; // Record identifier
  1556. // Excel normally stores the last calculated value of the formula in $num.
  1557. // Clearly we are not in a position to calculate this a priori. Instead
  1558. // we set $num to zero and set the option flags in $grbit to ensure
  1559. // automatic calculation of the formula when the file is opened.
  1560. //
  1561. $xf = $this->_XF($format); // The cell format
  1562. $num = 0x00; // Current value of formula
  1563. $grbit = 0x03; // Option flags
  1564. $unknown = 0x0000; // Must be zero
  1565. // Check that row and col are valid and store max and min values
  1566. if ($this->_checkRowCol($row, $col) == false) {
  1567. return -2;
  1568. }
  1569. // Strip the '=' or '@' sign at the beginning of the formula string
  1570. if (preg_match("/^=/", $formula)) {
  1571. $formula = preg_replace("/(^=)/", "", $formula);
  1572. } elseif (preg_match("/^@/", $formula)) {
  1573. $formula = preg_replace("/(^@)/", "", $formula);
  1574. } else {
  1575. // Error handling
  1576. $this->writeString($row, $col, 'Unrecognised character for formula');
  1577. return -1;
  1578. }
  1579. // Parse the formula using the parser in Parser.php
  1580. $error = $this->_parser->parse($formula);
  1581. $formula = $this->_parser->toReversePolish();
  1582. $formlen = strlen($formula); // Length of the binary string
  1583. $length = 0x16 + $formlen; // Length of the record data
  1584. $header = pack("vv", $record, $length);
  1585. $data = pack("vvvdvVv", $row, $col, $xf, $num,
  1586. $grbit, $unknown, $formlen);
  1587. $this->_append($header . $data . $formula);
  1588. return 0;
  1589. }
  1590. /**
  1591. * Write a hyperlink.
  1592. * This is comprised of two elements: the visible label and
  1593. * the invisible link. The visible label is the same as the link unless an
  1594. * alternative string is specified. The label is written using the
  1595. * writeString() method. Therefore the 255 characters string limit applies.
  1596. * $string and $format are optional.
  1597. *
  1598. * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
  1599. * directory url.
  1600. *
  1601. * Returns 0 : normal termination
  1602. * -2 : row or column out of range
  1603. * -3 : long string truncated to 255 chars
  1604. *
  1605. * @access public
  1606. * @param integer $row Row
  1607. * @param integer $col Column
  1608. * @param string $url URL string
  1609. * @param string $string Alternative label
  1610. * @param mixed $format The cell format
  1611. * @return integer
  1612. */
  1613. function writeUrl($row, $col, $url, $string = '', $format = null)
  1614. {
  1615. // Add start row and col to arg list
  1616. return($this->_writeUrlRange($row, $col, $row, $col, $url, $string, $format));
  1617. }
  1618. /**
  1619. * This is the more general form of writeUrl(). It allows a hyperlink to be
  1620. * written to a range of cells. This function also decides the type of hyperlink
  1621. * to be written. These are either, Web (http, ftp, mailto), Internal
  1622. * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
  1623. *
  1624. * @access private
  1625. * @see writeUrl()
  1626. * @param integer $row1 Start row
  1627. * @param integer $col1 Start column
  1628. * @param integer $row2 End row
  1629. * @param integer $col2 End column
  1630. * @param string $url URL string
  1631. * @param string $string Alternative label
  1632. * @param mixed $format The cell format
  1633. * @return integer
  1634. */
  1635. function _writeUrlRange($row1, $col1, $row2, $col2, $url, $string = '', $format = null)
  1636. {
  1637. // Check for internal/external sheet links or default to web link
  1638. if (preg_match('[^internal:]', $url)) {
  1639. return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url, $string, $format));
  1640. }
  1641. if (preg_match('[^external:]', $url)) {
  1642. return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url, $string, $format));
  1643. }
  1644. return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url, $string, $format));
  1645. }
  1646. /**
  1647. * Used to write http, ftp and mailto hyperlinks.
  1648. * The link type ($options) is 0x03 is the same as absolute dir ref without
  1649. * sheet. However it is differentiated by the $unknown2 data stream.
  1650. *
  1651. * @access private
  1652. * @see writeUrl()
  1653. * @param integer $row1 Start row
  1654. * @param integer $col1 Start column
  1655. * @param integer $row2 End row
  1656. * @param integer $col2 End column
  1657. * @param string $url URL string
  1658. * @param string $str Alternative label
  1659. * @param mixed $format The cell format
  1660. * @return integer
  1661. */
  1662. function _writeUrlWeb($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1663. {
  1664. $record = 0x01B8; // Record identifier
  1665. $length = 0x00000; // Bytes to follow
  1666. if (!$format) {
  1667. $format = $this->_url_format;
  1668. }
  1669. // Write the visible label using the writeString() method.
  1670. if ($str == '') {
  1671. $str = $url;
  1672. }
  1673. $str_error = $this->writeString($row1, $col1, $str, $format);
  1674. if (($str_error == -2) || ($str_error == -3)) {
  1675. return $str_error;
  1676. }
  1677. // Pack the undocumented parts of the hyperlink stream
  1678. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  1679. $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
  1680. // Pack the option flags
  1681. $options = pack("V", 0x03);
  1682. // Convert URL to a null terminated wchar string
  1683. $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  1684. $url = $url . "\0\0\0";
  1685. // Pack the length of the URL
  1686. $url_len = pack("V", strlen($url));
  1687. // Calculate the data length
  1688. $length = 0x34 + strlen($url);
  1689. // Pack the header data
  1690. $header = pack("vv", $record, $length);
  1691. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  1692. // Write the packed data
  1693. $this->_append($header . $data .
  1694. $unknown1 . $options .
  1695. $unknown2 . $url_len . $url);
  1696. return($str_error);
  1697. }
  1698. /**
  1699. * Used to write internal reference hyperlinks such as "Sheet1!A1".
  1700. *
  1701. * @access private
  1702. * @see writeUrl()
  1703. * @param integer $row1 Start row
  1704. * @param integer $col1 Start column
  1705. * @param integer $row2 End row
  1706. * @param integer $col2 End column
  1707. * @param string $url URL string
  1708. * @param string $str Alternative label
  1709. * @param mixed $format The cell format
  1710. * @return integer
  1711. */
  1712. function _writeUrlInternal($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1713. {
  1714. $record = 0x01B8; // Record identifier
  1715. $length = 0x00000; // Bytes to follow
  1716. if (!$format) {
  1717. $format = $this->_url_format;
  1718. }
  1719. // Strip URL type
  1720. $url = preg_replace('/^internal:/', '', $url);
  1721. // Write the visible label
  1722. if ($str == '') {
  1723. $str = $url;
  1724. }
  1725. $str_error = $this->writeString($row1, $col1, $str, $format);
  1726. if (($str_error == -2) || ($str_error == -3)) {
  1727. return $str_error;
  1728. }
  1729. // Pack the undocumented parts of the hyperlink stream
  1730. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  1731. // Pack the option flags
  1732. $options = pack("V", 0x08);
  1733. // Convert the URL type and to a null terminated wchar string
  1734. $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  1735. $url = $url . "\0\0\0";
  1736. // Pack the length of the URL as chars (not wchars)
  1737. $url_len = pack("V", floor(strlen($url)/2));
  1738. // Calculate the data length
  1739. $length = 0x24 + strlen($url);
  1740. // Pack the header data
  1741. $header = pack("vv", $record, $length);
  1742. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  1743. // Write the packed data
  1744. $this->_append($header . $data .
  1745. $unknown1 . $options .
  1746. $url_len . $url);
  1747. return($str_error);
  1748. }
  1749. /**
  1750. * Write links to external directory names such as 'c:\foo.xls',
  1751. * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
  1752. *
  1753. * Note: Excel writes some relative links with the $dir_long string. We ignore
  1754. * these cases for the sake of simpler code.
  1755. *
  1756. * @access private
  1757. * @see writeUrl()
  1758. * @param integer $row1 Start row
  1759. * @param integer $col1 Start column
  1760. * @param integer $row2 End row
  1761. * @param integer $col2 End column
  1762. * @param string $url URL string
  1763. * @param string $str Alternative label
  1764. * @param mixed $format The cell format
  1765. * @return integer
  1766. */
  1767. function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = null)
  1768. {
  1769. // Network drives are different. We will handle them separately
  1770. // MS/Novell network drives and shares start with \\
  1771. if (preg_match('[^external:\\\\]', $url)) {
  1772. return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
  1773. }
  1774. $record = 0x01B8; // Record identifier
  1775. $length = 0x00000; // Bytes to follow
  1776. if (!$format) {
  1777. $format = $this->_url_format;
  1778. }
  1779. // Strip URL type and change Unix dir separator to Dos style (if needed)
  1780. //
  1781. $url = preg_replace('/^external:/', '', $url);
  1782. $url = preg_replace('/\//', "\\", $url);
  1783. // Write the visible label
  1784. if ($str == '') {
  1785. $str = preg_replace('/\#/', ' - ', $url);
  1786. }
  1787. $str_error = $this->writeString($row1, $col1, $str, $format);
  1788. if (($str_error == -2) or ($str_error == -3)) {
  1789. return $str_error;
  1790. }
  1791. // Determine if the link is relative or absolute:
  1792. // relative if link contains no dir separator, "somefile.xls"
  1793. // relative if link starts with up-dir, "..\..\somefile.xls"
  1794. // otherwise, absolute
  1795. $absolute = 0x02; // Bit mask
  1796. if (!preg_match("/\\\/", $url)) {
  1797. $absolute = 0x00;
  1798. }
  1799. if (preg_match("/^\.\.\\\/", $url)) {
  1800. $absolute = 0x00;
  1801. }
  1802. $link_type = 0x01 | $absolute;
  1803. // Determine if the link contains a sheet reference and change some of the
  1804. // parameters accordingly.
  1805. // Split the dir name and sheet name (if it exists)
  1806. /*if (preg_match("/\#/", $url)) {
  1807. list($dir_long, $sheet) = split("\#", $url);
  1808. } else {
  1809. $dir_long = $url;
  1810. }
  1811. if (isset($sheet)) {
  1812. $link_type |= 0x08;
  1813. $sheet_len = pack("V", strlen($sheet) + 0x01);
  1814. $sheet = join("\0", split('', $sheet));
  1815. $sheet .= "\0\0\0";
  1816. } else {
  1817. $sheet_len = '';
  1818. $sheet = '';
  1819. }*/
  1820. $dir_long = $url;
  1821. if (preg_match("/\#/", $url)) {
  1822. $link_type |= 0x08;
  1823. }
  1824. // Pack the link type
  1825. $link_type = pack("V", $link_type);
  1826. // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
  1827. $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
  1828. $up_count = pack("v", $up_count);
  1829. // Store the short dos dir name (null terminated)
  1830. $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
  1831. // Store the long dir name as a wchar string (non-null terminated)
  1832. //$dir_long = join("\0", split('', $dir_long));
  1833. $dir_long = $dir_long . "\0";
  1834. // Pack the lengths of the dir strings
  1835. $dir_short_len = pack("V", strlen($dir_short) );
  1836. $dir_long_len = pack("V", strlen($dir_long) );
  1837. $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
  1838. // Pack the undocumented parts of the hyperlink stream
  1839. $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
  1840. $unknown2 = pack("H*",'0303000000000000C000000000000046' );
  1841. $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
  1842. $unknown4 = pack("v", 0x03 );
  1843. // Pack the main data stream
  1844. $data = pack("vvvv", $row1, $row2, $col1, $col2) .
  1845. $unknown1 .
  1846. $link_type .
  1847. $unknown2 .
  1848. $up_count .
  1849. $dir_short_len.
  1850. $dir_short .
  1851. $unknown3 .
  1852. $stream_len ;/*.
  1853. $dir_long_len .
  1854. $unknown4 .
  1855. $dir_long .
  1856. $sheet_len .
  1857. $sheet ;*/
  1858. // Pack the header data
  1859. $length = strlen($data);
  1860. $header = pack("vv", $record, $length);
  1861. // Write the packed data
  1862. $this->_append($header. $data);
  1863. return($str_error);
  1864. }
  1865. /**
  1866. * This method is used to set the height and format for a row.
  1867. *
  1868. * @access public
  1869. * @param integer $row The row to set
  1870. * @param integer $height Height we are giving to the row.
  1871. * Use null to set XF without setting height
  1872. * @param mixed $format XF format we are giving to the row
  1873. * @param bool $hidden The optional hidden attribute
  1874. * @param integer $level The optional outline level for row, in range [0,7]
  1875. */
  1876. function setRow($row, $height, $format = null, $hidden = false, $level = 0)
  1877. {
  1878. $record = 0x0208; // Record identifier
  1879. $length = 0x0010; // Number of bytes to follow
  1880. $colMic = 0x0000; // First defined column
  1881. $colMac = 0x0000; // Last defined column
  1882. $irwMac = 0x0000; // Used by Excel to optimise loading
  1883. $reserved = 0x0000; // Reserved
  1884. $grbit = 0x0000; // Option flags
  1885. $ixfe = $this->_XF($format); // XF index
  1886. if ( $height < 0 ){
  1887. $height = null;
  1888. }
  1889. // set _row_sizes so _sizeRow() can use it
  1890. $this->_row_sizes[$row] = $height;
  1891. // Use setRow($row, null, $XF) to set XF format without setting height
  1892. if ($height != null) {
  1893. $miyRw = $height * 20; // row height
  1894. } else {
  1895. $miyRw = 0xff; // default row height is 256
  1896. }
  1897. $level = max(0, min($level, 7)); // level should be between 0 and 7
  1898. $this->_outline_row_level = max($level, $this->_outline_row_level);
  1899. // Set the options flags. fUnsynced is used to show that the font and row
  1900. // heights are not compatible. This is usually the case for WriteExcel.
  1901. // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
  1902. // is collapsed. Instead it is used to indicate that the previous row is
  1903. // collapsed. The zero height flag, 0x20, is used to collapse a row.
  1904. $grbit |= $level;
  1905. if ($hidden) {
  1906. $grbit |= 0x0020;
  1907. }
  1908. $grbit |= 0x0040; // fUnsynced
  1909. if ($format) {
  1910. $grbit |= 0x0080;
  1911. }
  1912. $grbit |= 0x0100;
  1913. $header = pack("vv", $record, $length);
  1914. $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
  1915. $irwMac,$reserved, $grbit, $ixfe);
  1916. $this->_append($header.$data);
  1917. }
  1918. /**
  1919. * Writes Excel DIMENSIONS to define the area in which there is data.
  1920. *
  1921. * @access private
  1922. */
  1923. function _storeDimensions()
  1924. {
  1925. $record = 0x0200; // Record identifier
  1926. $row_min = $this->_dim_rowmin; // First row
  1927. $row_max = $this->_dim_rowmax + 1; // Last row plus 1
  1928. $col_min = $this->_dim_colmin; // First column
  1929. $col_max = $this->_dim_colmax + 1; // Last column plus 1
  1930. $reserved = 0x0000; // Reserved by Excel
  1931. if ($this->_BIFF_version == 0x0500) {
  1932. $length = 0x000A; // Number of bytes to follow
  1933. $data = pack("vvvvv", $row_min, $row_max,
  1934. $col_min, $col_max, $reserved);
  1935. } elseif ($this->_BIFF_version == 0x0600) {
  1936. $length = 0x000E;
  1937. $data = pack("VVvvv", $row_min, $row_max,
  1938. $col_min, $col_max, $reserved);
  1939. }
  1940. $header = pack("vv", $record, $length);
  1941. $this->_prepend($header.$data);
  1942. }
  1943. /**
  1944. * Write BIFF record Window2.
  1945. *
  1946. * @access private
  1947. */
  1948. function _storeWindow2()
  1949. {
  1950. $record = 0x023E; // Record identifier
  1951. if ($this->_BIFF_version == 0x0500) {
  1952. $length = 0x000A; // Number of bytes to follow
  1953. } elseif ($this->_BIFF_version == 0x0600) {
  1954. $length = 0x0012;
  1955. }
  1956. $grbit = 0x00B6; // Option flags
  1957. $rwTop = 0x0000; // Top row visible in window
  1958. $colLeft = 0x0000; // Leftmost column visible in window
  1959. // The options flags that comprise $grbit
  1960. $fDspFmla = 0; // 0 - bit
  1961. $fDspGrid = $this->_screen_gridlines; // 1
  1962. $fDspRwCol = 1; // 2
  1963. $fFrozen = $this->_frozen; // 3
  1964. $fDspZeros = 1; // 4
  1965. $fDefaultHdr = 1; // 5
  1966. $fArabic = 0; // 6
  1967. $fDspGuts = $this->_outline_on; // 7
  1968. $fFrozenNoSplit = 0; // 0 - bit
  1969. $fSelected = $this->selected; // 1
  1970. $fPaged = 1; // 2
  1971. $grbit = $fDspFmla;
  1972. $grbit |= $fDspGrid << 1;
  1973. $grbit |= $fDspRwCol << 2;
  1974. $grbit |= $fFrozen << 3;
  1975. $grbit |= $fDspZeros << 4;
  1976. $grbit |= $fDefaultHdr << 5;
  1977. $grbit |= $fArabic << 6;
  1978. $grbit |= $fDspGuts << 7;
  1979. $grbit |= $fFrozenNoSplit << 8;
  1980. $grbit |= $fSelected << 9;
  1981. $grbit |= $fPaged << 10;
  1982. $header = pack("vv", $record, $length);
  1983. $data = pack("vvv", $grbit, $rwTop, $colLeft);
  1984. // FIXME !!!
  1985. if ($this->_BIFF_version == 0x0500) {
  1986. $rgbHdr = 0x00000000; // Row/column heading and gridline color
  1987. $data .= pack("V", $rgbHdr);
  1988. } elseif ($this->_BIFF_version == 0x0600) {
  1989. $rgbHdr = 0x0040; // Row/column heading and gridline color index
  1990. $zoom_factor_page_break = 0x0000;
  1991. $zoom_factor_normal = 0x0000;
  1992. $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
  1993. }
  1994. $this->_append($header.$data);
  1995. }
  1996. /**
  1997. * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
  1998. *
  1999. * @access private
  2000. */
  2001. function _storeDefcol()
  2002. {
  2003. $record = 0x0055; // Record identifier
  2004. $length = 0x0002; // Number of bytes to follow
  2005. $colwidth = 0x0008; // Default column width
  2006. $header = pack("vv", $record, $length);
  2007. $data = pack("v", $colwidth);
  2008. $this->_prepend($header . $data);
  2009. }
  2010. /**
  2011. * Write BIFF record COLINFO to define column widths
  2012. *
  2013. * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
  2014. * length record.
  2015. *
  2016. * @access private
  2017. * @param array $col_array This is the only parameter received and is composed of the following:
  2018. * 0 => First formatted column,
  2019. * 1 => Last formatted column,
  2020. * 2 => Col width (8.43 is Excel default),
  2021. * 3 => The optional XF format of the column,
  2022. * 4 => Option flags.
  2023. * 5 => Optional outline level
  2024. */
  2025. function _storeColinfo($col_array)
  2026. {
  2027. if (isset($col_array[0])) {
  2028. $colFirst = $col_array[0];
  2029. }
  2030. if (isset($col_array[1])) {
  2031. $colLast = $col_array[1];
  2032. }
  2033. if (isset($col_array[2])) {
  2034. $coldx = $col_array[2];
  2035. } else {
  2036. $coldx = 8.43;
  2037. }
  2038. if (isset($col_array[3])) {
  2039. $format = $col_array[3];
  2040. } else {
  2041. $format = 0;
  2042. }
  2043. if (isset($col_array[4])) {
  2044. $grbit = $col_array[4];
  2045. } else {
  2046. $grbit = 0;
  2047. }
  2048. if (isset($col_array[5])) {
  2049. $level = $col_array[5];
  2050. } else {
  2051. $level = 0;
  2052. }
  2053. $record = 0x007D; // Record identifier
  2054. $length = 0x000B; // Number of bytes to follow
  2055. $coldx += 0.72; // Fudge. Excel subtracts 0.72 !?
  2056. $coldx *= 256; // Convert to units of 1/256 of a char
  2057. $ixfe = $this->_XF($format);
  2058. $reserved = 0x00; // Reserved
  2059. $level = max(0, min($level, 7));
  2060. $grbit |= $level << 8;
  2061. $header = pack("vv", $record, $length);
  2062. $data = pack("vvvvvC", $colFirst, $colLast, $coldx,
  2063. $ixfe, $grbit, $reserved);
  2064. $this->_prepend($header.$data);
  2065. }
  2066. /**
  2067. * Write BIFF record SELECTION.
  2068. *
  2069. * @access private
  2070. * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast)
  2071. * @see setSelection()
  2072. */
  2073. function _storeSelection($array)
  2074. {
  2075. list($rwFirst,$colFirst,$rwLast,$colLast) = $array;
  2076. $record = 0x001D; // Record identifier
  2077. $length = 0x000F; // Number of bytes to follow
  2078. $pnn = $this->_active_pane; // Pane position
  2079. $rwAct = $rwFirst; // Active row
  2080. $colAct = $colFirst; // Active column
  2081. $irefAct = 0; // Active cell ref
  2082. $cref = 1; // Number of refs
  2083. if (!isset($rwLast)) {
  2084. $rwLast = $rwFirst; // Last row in reference
  2085. }
  2086. if (!isset($colLast)) {
  2087. $colLast = $colFirst; // Last col in reference
  2088. }
  2089. // Swap last row/col for first row/col as necessary
  2090. if ($rwFirst > $rwLast) {
  2091. list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
  2092. }
  2093. if ($colFirst > $colLast) {
  2094. list($colFirst, $colLast) = array($colLast, $colFirst);
  2095. }
  2096. $header = pack("vv", $record, $length);
  2097. $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
  2098. $irefAct, $cref,
  2099. $rwFirst, $rwLast,
  2100. $colFirst, $colLast);
  2101. $this->_append($header . $data);
  2102. }
  2103. /**
  2104. * Store the MERGEDCELLS record for all ranges of merged cells
  2105. *
  2106. * @access private
  2107. */
  2108. function _storeMergedCells()
  2109. {
  2110. // if there are no merged cell ranges set, return
  2111. if (count($this->_merged_ranges) == 0) {
  2112. return;
  2113. }
  2114. $record = 0x00E5;
  2115. $length = 2 + count($this->_merged_ranges) * 8;
  2116. $header = pack('vv', $record, $length);
  2117. $data = pack('v', count($this->_merged_ranges));
  2118. foreach ($this->_merged_ranges as $range) {
  2119. $data .= pack('vvvv', $range[0], $range[2], $range[1], $range[3]);
  2120. }
  2121. $this->_append($header . $data);
  2122. }
  2123. /**
  2124. * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  2125. * references in a worksheet.
  2126. *
  2127. * Excel only stores references to external sheets that are used in formulas.
  2128. * For simplicity we store references to all the sheets in the workbook
  2129. * regardless of whether they are used or not. This reduces the overall
  2130. * complexity and eliminates the need for a two way dialogue between the formula
  2131. * parser the worksheet objects.
  2132. *
  2133. * @access private
  2134. * @param integer $count The number of external sheet references in this worksheet
  2135. */
  2136. function _storeExterncount($count)
  2137. {
  2138. $record = 0x0016; // Record identifier
  2139. $length = 0x0002; // Number of bytes to follow
  2140. $header = pack("vv", $record, $length);
  2141. $data = pack("v", $count);
  2142. $this->_prepend($header . $data);
  2143. }
  2144. /**
  2145. * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  2146. * formulas. A formula references a sheet name via an index. Since we store a
  2147. * reference to all of the external worksheets the EXTERNSHEET index is the same
  2148. * as the worksheet index.
  2149. *
  2150. * @access private
  2151. * @param string $sheetname The name of a external worksheet
  2152. */
  2153. function _storeExternsheet($sheetname)
  2154. {
  2155. $record = 0x0017; // Record identifier
  2156. // References to the current sheet are encoded differently to references to
  2157. // external sheets.
  2158. //
  2159. if ($this->name == $sheetname) {
  2160. $sheetname = '';
  2161. $length = 0x02; // The following 2 bytes
  2162. $cch = 1; // The following byte
  2163. $rgch = 0x02; // Self reference
  2164. } else {
  2165. $length = 0x02 + strlen($sheetname);
  2166. $cch = strlen($sheetname);
  2167. $rgch = 0x03; // Reference to a sheet in the current workbook
  2168. }
  2169. $header = pack("vv", $record, $length);
  2170. $data = pack("CC", $cch, $rgch);
  2171. $this->_prepend($header . $data . $sheetname);
  2172. }
  2173. /**
  2174. * Writes the Excel BIFF PANE record.
  2175. * The panes can either be frozen or thawed (unfrozen).
  2176. * Frozen panes are specified in terms of an integer number of rows and columns.
  2177. * Thawed panes are specified in terms of Excel's units for rows and columns.
  2178. *
  2179. * @access private
  2180. * @param array $panes This is the only parameter received and is composed of the following:
  2181. * 0 => Vertical split position,
  2182. * 1 => Horizontal split position
  2183. * 2 => Top row visible
  2184. * 3 => Leftmost column visible
  2185. * 4 => Active pane
  2186. */
  2187. function _storePanes($panes)
  2188. {
  2189. $y = isset($panes[0]) ? $panes[0] : null;
  2190. $x = isset($panes[1]) ? $panes[1] : null;
  2191. $rwTop = isset($panes[2]) ? $panes[2] : null;
  2192. $colLeft = isset($panes[3]) ? $panes[3] : null;
  2193. if (count($panes) > 4) { // if Active pane was received
  2194. $pnnAct = $panes[4];
  2195. } else {
  2196. $pnnAct = null;
  2197. }
  2198. $record = 0x0041; // Record identifier
  2199. $length = 0x000A; // Number of bytes to follow
  2200. // Code specific to frozen or thawed panes.
  2201. if ($this->_frozen) {
  2202. // Set default values for $rwTop and $colLeft
  2203. if (!isset($rwTop)) {
  2204. $rwTop = $y;
  2205. }
  2206. if (!isset($colLeft)) {
  2207. $colLeft = $x;
  2208. }
  2209. } else {
  2210. // Set default values for $rwTop and $colLeft
  2211. if (!isset($rwTop)) {
  2212. $rwTop = 0;
  2213. }
  2214. if (!isset($colLeft)) {
  2215. $colLeft = 0;
  2216. }
  2217. // Convert Excel's row and column units to the internal units.
  2218. // The default row height is 12.75
  2219. // The default column width is 8.43
  2220. // The following slope and intersection values were interpolated.
  2221. //
  2222. $y = 20*$y + 255;
  2223. $x = 113.879*$x + 390;
  2224. }
  2225. // Determine which pane should be active. There is also the undocumented
  2226. // option to override this should it be necessary: may be removed later.
  2227. //
  2228. if (!isset($pnnAct)) {
  2229. if ($x != 0 && $y != 0) {
  2230. $pnnAct = 0; // Bottom right
  2231. }
  2232. if ($x != 0 && $y == 0) {
  2233. $pnnAct = 1; // Top right
  2234. }
  2235. if ($x == 0 && $y != 0) {
  2236. $pnnAct = 2; // Bottom left
  2237. }
  2238. if ($x == 0 && $y == 0) {
  2239. $pnnAct = 3; // Top left
  2240. }
  2241. }
  2242. $this->_active_pane = $pnnAct; // Used in _storeSelection
  2243. $header = pack("vv", $record, $length);
  2244. $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
  2245. $this->_append($header . $data);
  2246. }
  2247. /**
  2248. * Store the page setup SETUP BIFF record.
  2249. *
  2250. * @access private
  2251. */
  2252. function _storeSetup()
  2253. {
  2254. $record = 0x00A1; // Record identifier
  2255. $length = 0x0022; // Number of bytes to follow
  2256. $iPaperSize = $this->_paper_size; // Paper size
  2257. $iScale = $this->_print_scale; // Print scaling factor
  2258. $iPageStart = 0x01; // Starting page number
  2259. $iFitWidth = $this->_fit_width; // Fit to number of pages wide
  2260. $iFitHeight = $this->_fit_height; // Fit to number of pages high
  2261. $grbit = 0x00; // Option flags
  2262. $iRes = 0x0258; // Print resolution
  2263. $iVRes = 0x0258; // Vertical print resolution
  2264. $numHdr = $this->_margin_head; // Header Margin
  2265. $numFtr = $this->_margin_foot; // Footer Margin
  2266. $iCopies = 0x01; // Number of copies
  2267. $fLeftToRight = 0x0; // Print over then down
  2268. $fLandscape = $this->_orientation; // Page orientation
  2269. $fNoPls = 0x0; // Setup not read from printer
  2270. $fNoColor = 0x0; // Print black and white
  2271. $fDraft = 0x0; // Print draft quality
  2272. $fNotes = 0x0; // Print notes
  2273. $fNoOrient = 0x0; // Orientation not set
  2274. $fUsePage = 0x0; // Use custom starting page
  2275. $grbit = $fLeftToRight;
  2276. $grbit |= $fLandscape << 1;
  2277. $grbit |= $fNoPls << 2;
  2278. $grbit |= $fNoColor << 3;
  2279. $grbit |= $fDraft << 4;
  2280. $grbit |= $fNotes << 5;
  2281. $grbit |= $fNoOrient << 6;
  2282. $grbit |= $fUsePage << 7;
  2283. $numHdr = pack("d", $numHdr);
  2284. $numFtr = pack("d", $numFtr);
  2285. if ($this->_byte_order) { // if it's Big Endian
  2286. $numHdr = strrev($numHdr);
  2287. $numFtr = strrev($numFtr);
  2288. }
  2289. $header = pack("vv", $record, $length);
  2290. $data1 = pack("vvvvvvvv", $iPaperSize,
  2291. $iScale,
  2292. $iPageStart,
  2293. $iFitWidth,
  2294. $iFitHeight,
  2295. $grbit,
  2296. $iRes,
  2297. $iVRes);
  2298. $data2 = $numHdr.$numFtr;
  2299. $data3 = pack("v", $iCopies);
  2300. $this->_prepend($header . $data1 . $data2 . $data3);
  2301. }
  2302. /**
  2303. * Store the header caption BIFF record.
  2304. *
  2305. * @access private
  2306. */
  2307. function _storeHeader()
  2308. {
  2309. $record = 0x0014; // Record identifier
  2310. $str = $this->_header; // header string
  2311. $cch = strlen($str); // Length of header string
  2312. if ($this->_BIFF_version == 0x0600) {
  2313. $encoding = 0x0; // TODO: Unicode support
  2314. $length = 3 + $cch; // Bytes to follow
  2315. } else {
  2316. $length = 1 + $cch; // Bytes to follow
  2317. }
  2318. $header = pack("vv", $record, $length);
  2319. if ($this->_BIFF_version == 0x0600) {
  2320. $data = pack("vC", $cch, $encoding);
  2321. } else {
  2322. $data = pack("C", $cch);
  2323. }
  2324. $this->_prepend($header.$data.$str);
  2325. }
  2326. /**
  2327. * Store the footer caption BIFF record.
  2328. *
  2329. * @access private
  2330. */
  2331. function _storeFooter()
  2332. {
  2333. $record = 0x0015; // Record identifier
  2334. $str = $this->_footer; // Footer string
  2335. $cch = strlen($str); // Length of footer string
  2336. if ($this->_BIFF_version == 0x0600) {
  2337. $encoding = 0x0; // TODO: Unicode support
  2338. $length = 3 + $cch; // Bytes to follow
  2339. } else {
  2340. $length = 1 + $cch;
  2341. }
  2342. $header = pack("vv", $record, $length);
  2343. if ($this->_BIFF_version == 0x0600) {
  2344. $data = pack("vC", $cch, $encoding);
  2345. } else {
  2346. $data = pack("C", $cch);
  2347. }
  2348. $this->_prepend($header . $data . $str);
  2349. }
  2350. /**
  2351. * Store the horizontal centering HCENTER BIFF record.
  2352. *
  2353. * @access private
  2354. */
  2355. function _storeHcenter()
  2356. {
  2357. $record = 0x0083; // Record identifier
  2358. $length = 0x0002; // Bytes to follow
  2359. $fHCenter = $this->_hcenter; // Horizontal centering
  2360. $header = pack("vv", $record, $length);
  2361. $data = pack("v", $fHCenter);
  2362. $this->_prepend($header.$data);
  2363. }
  2364. /**
  2365. * Store the vertical centering VCENTER BIFF record.
  2366. *
  2367. * @access private
  2368. */
  2369. function _storeVcenter()
  2370. {
  2371. $record = 0x0084; // Record identifier
  2372. $length = 0x0002; // Bytes to follow
  2373. $fVCenter = $this->_vcenter; // Horizontal centering
  2374. $header = pack("vv", $record, $length);
  2375. $data = pack("v", $fVCenter);
  2376. $this->_prepend($header . $data);
  2377. }
  2378. /**
  2379. * Store the LEFTMARGIN BIFF record.
  2380. *
  2381. * @access private
  2382. */
  2383. function _storeMarginLeft()
  2384. {
  2385. $record = 0x0026; // Record identifier
  2386. $length = 0x0008; // Bytes to follow
  2387. $margin = $this->_margin_left; // Margin in inches
  2388. $header = pack("vv", $record, $length);
  2389. $data = pack("d", $margin);
  2390. if ($this->_byte_order) { // if it's Big Endian
  2391. $data = strrev($data);
  2392. }
  2393. $this->_prepend($header . $data);
  2394. }
  2395. /**
  2396. * Store the RIGHTMARGIN BIFF record.
  2397. *
  2398. * @access private
  2399. */
  2400. function _storeMarginRight()
  2401. {
  2402. $record = 0x0027; // Record identifier
  2403. $length = 0x0008; // Bytes to follow
  2404. $margin = $this->_margin_right; // Margin in inches
  2405. $header = pack("vv", $record, $length);
  2406. $data = pack("d", $margin);
  2407. if ($this->_byte_order) { // if it's Big Endian
  2408. $data = strrev($data);
  2409. }
  2410. $this->_prepend($header . $data);
  2411. }
  2412. /**
  2413. * Store the TOPMARGIN BIFF record.
  2414. *
  2415. * @access private
  2416. */
  2417. function _storeMarginTop()
  2418. {
  2419. $record = 0x0028; // Record identifier
  2420. $length = 0x0008; // Bytes to follow
  2421. $margin = $this->_margin_top; // Margin in inches
  2422. $header = pack("vv", $record, $length);
  2423. $data = pack("d", $margin);
  2424. if ($this->_byte_order) { // if it's Big Endian
  2425. $data = strrev($data);
  2426. }
  2427. $this->_prepend($header . $data);
  2428. }
  2429. /**
  2430. * Store the BOTTOMMARGIN BIFF record.
  2431. *
  2432. * @access private
  2433. */
  2434. function _storeMarginBottom()
  2435. {
  2436. $record = 0x0029; // Record identifier
  2437. $length = 0x0008; // Bytes to follow
  2438. $margin = $this->_margin_bottom; // Margin in inches
  2439. $header = pack("vv", $record, $length);
  2440. $data = pack("d", $margin);
  2441. if ($this->_byte_order) { // if it's Big Endian
  2442. $data = strrev($data);
  2443. }
  2444. $this->_prepend($header . $data);
  2445. }
  2446. /**
  2447. * Merges the area given by its arguments.
  2448. * This is an Excel97/2000 method. It is required to perform more complicated
  2449. * merging than the normal setAlign('merge').
  2450. *
  2451. * @access public
  2452. * @param integer $first_row First row of the area to merge
  2453. * @param integer $first_col First column of the area to merge
  2454. * @param integer $last_row Last row of the area to merge
  2455. * @param integer $last_col Last column of the area to merge
  2456. */
  2457. function mergeCells($first_row, $first_col, $last_row, $last_col)
  2458. {
  2459. $record = 0x00E5; // Record identifier
  2460. $length = 0x000A; // Bytes to follow
  2461. $cref = 1; // Number of refs
  2462. // Swap last row/col for first row/col as necessary
  2463. if ($first_row > $last_row) {
  2464. list($first_row, $last_row) = array($last_row, $first_row);
  2465. }
  2466. if ($first_col > $last_col) {
  2467. list($first_col, $last_col) = array($last_col, $first_col);
  2468. }
  2469. $header = pack("vv", $record, $length);
  2470. $data = pack("vvvvv", $cref, $first_row, $last_row,
  2471. $first_col, $last_col);
  2472. $this->_append($header.$data);
  2473. }
  2474. /**
  2475. * Write the PRINTHEADERS BIFF record.
  2476. *
  2477. * @access private
  2478. */
  2479. function _storePrintHeaders()
  2480. {
  2481. $record = 0x002a; // Record identifier
  2482. $length = 0x0002; // Bytes to follow
  2483. $fPrintRwCol = $this->_print_headers; // Boolean flag
  2484. $header = pack("vv", $record, $length);
  2485. $data = pack("v", $fPrintRwCol);
  2486. $this->_prepend($header . $data);
  2487. }
  2488. /**
  2489. * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
  2490. * GRIDSET record.
  2491. *
  2492. * @access private
  2493. */
  2494. function _storePrintGridlines()
  2495. {
  2496. $record = 0x002b; // Record identifier
  2497. $length = 0x0002; // Bytes to follow
  2498. $fPrintGrid = $this->_print_gridlines; // Boolean flag
  2499. $header = pack("vv", $record, $length);
  2500. $data = pack("v", $fPrintGrid);
  2501. $this->_prepend($header . $data);
  2502. }
  2503. /**
  2504. * Write the GRIDSET BIFF record. Must be used in conjunction with the
  2505. * PRINTGRIDLINES record.
  2506. *
  2507. * @access private
  2508. */
  2509. function _storeGridset()
  2510. {
  2511. $record = 0x0082; // Record identifier
  2512. $length = 0x0002; // Bytes to follow
  2513. $fGridSet = !($this->_print_gridlines); // Boolean flag
  2514. $header = pack("vv", $record, $length);
  2515. $data = pack("v", $fGridSet);
  2516. $this->_prepend($header . $data);
  2517. }
  2518. /**
  2519. * Write the GUTS BIFF record. This is used to configure the gutter margins
  2520. * where Excel outline symbols are displayed. The visibility of the gutters is
  2521. * controlled by a flag in WSBOOL.
  2522. *
  2523. * @see _storeWsbool()
  2524. * @access private
  2525. */
  2526. function _storeGuts()
  2527. {
  2528. $record = 0x0080; // Record identifier
  2529. $length = 0x0008; // Bytes to follow
  2530. $dxRwGut = 0x0000; // Size of row gutter
  2531. $dxColGut = 0x0000; // Size of col gutter
  2532. $row_level = $this->_outline_row_level;
  2533. $col_level = 0;
  2534. // Calculate the maximum column outline level. The equivalent calculation
  2535. // for the row outline level is carried out in setRow().
  2536. $colcount = count($this->_colinfo);
  2537. for ($i = 0; $i < $colcount; $i++) {
  2538. // Skip cols without outline level info.
  2539. if (count($col_level) >= 6) {
  2540. $col_level = max($this->_colinfo[$i][5], $col_level);
  2541. }
  2542. }
  2543. // Set the limits for the outline levels (0 <= x <= 7).
  2544. $col_level = max(0, min($col_level, 7));
  2545. // The displayed level is one greater than the max outline levels
  2546. if ($row_level) {
  2547. $row_level++;
  2548. }
  2549. if ($col_level) {
  2550. $col_level++;
  2551. }
  2552. $header = pack("vv", $record, $length);
  2553. $data = pack("vvvv", $dxRwGut, $dxColGut, $row_level, $col_level);
  2554. $this->_prepend($header.$data);
  2555. }
  2556. /**
  2557. * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
  2558. * with the SETUP record.
  2559. *
  2560. * @access private
  2561. */
  2562. function _storeWsbool()
  2563. {
  2564. $record = 0x0081; // Record identifier
  2565. $length = 0x0002; // Bytes to follow
  2566. $grbit = 0x0000;
  2567. // The only option that is of interest is the flag for fit to page. So we
  2568. // set all the options in one go.
  2569. //
  2570. /*if ($this->_fit_page) {
  2571. $grbit = 0x05c1;
  2572. } else {
  2573. $grbit = 0x04c1;
  2574. }*/
  2575. // Set the option flags
  2576. $grbit |= 0x0001; // Auto page breaks visible
  2577. if ($this->_outline_style) {
  2578. $grbit |= 0x0020; // Auto outline styles
  2579. }
  2580. if ($this->_outline_below) {
  2581. $grbit |= 0x0040; // Outline summary below
  2582. }
  2583. if ($this->_outline_right) {
  2584. $grbit |= 0x0080; // Outline summary right
  2585. }
  2586. if ($this->_fit_page) {
  2587. $grbit |= 0x0100; // Page setup fit to page
  2588. }
  2589. if ($this->_outline_on) {
  2590. $grbit |= 0x0400; // Outline symbols displayed
  2591. }
  2592. $header = pack("vv", $record, $length);
  2593. $data = pack("v", $grbit);
  2594. $this->_prepend($header . $data);
  2595. }
  2596. /**
  2597. * Write the HORIZONTALPAGEBREAKS BIFF record.
  2598. *
  2599. * @access private
  2600. */
  2601. function _storeHbreak()
  2602. {
  2603. // Return if the user hasn't specified pagebreaks
  2604. if (empty($this->_hbreaks)) {
  2605. return;
  2606. }
  2607. // Sort and filter array of page breaks
  2608. $breaks = $this->_hbreaks;
  2609. sort($breaks, SORT_NUMERIC);
  2610. if ($breaks[0] == 0) { // don't use first break if it's 0
  2611. array_shift($breaks);
  2612. }
  2613. $record = 0x001b; // Record identifier
  2614. $cbrk = count($breaks); // Number of page breaks
  2615. if ($this->_BIFF_version == 0x0600) {
  2616. $length = 2 + 6*$cbrk; // Bytes to follow
  2617. } else {
  2618. $length = 2 + 2*$cbrk; // Bytes to follow
  2619. }
  2620. $header = pack("vv", $record, $length);
  2621. $data = pack("v", $cbrk);
  2622. // Append each page break
  2623. foreach ($breaks as $break) {
  2624. if ($this->_BIFF_version == 0x0600) {
  2625. $data .= pack("vvv", $break, 0x0000, 0x00ff);
  2626. } else {
  2627. $data .= pack("v", $break);
  2628. }
  2629. }
  2630. $this->_prepend($header.$data);
  2631. }
  2632. /**
  2633. * Write the VERTICALPAGEBREAKS BIFF record.
  2634. *
  2635. * @access private
  2636. */
  2637. function _storeVbreak()
  2638. {
  2639. // Return if the user hasn't specified pagebreaks
  2640. if (empty($this->_vbreaks)) {
  2641. return;
  2642. }
  2643. // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
  2644. // It is slightly higher in Excel 97/200, approx. 1026
  2645. $breaks = array_slice($this->_vbreaks,0,1000);
  2646. // Sort and filter array of page breaks
  2647. sort($breaks, SORT_NUMERIC);
  2648. if ($breaks[0] == 0) { // don't use first break if it's 0
  2649. array_shift($breaks);
  2650. }
  2651. $record = 0x001a; // Record identifier
  2652. $cbrk = count($breaks); // Number of page breaks
  2653. if ($this->_BIFF_version == 0x0600) {
  2654. $length = 2 + 6*$cbrk; // Bytes to follow
  2655. } else {
  2656. $length = 2 + 2*$cbrk; // Bytes to follow
  2657. }
  2658. $header = pack("vv", $record, $length);
  2659. $data = pack("v", $cbrk);
  2660. // Append each page break
  2661. foreach ($breaks as $break) {
  2662. if ($this->_BIFF_version == 0x0600) {
  2663. $data .= pack("vvv", $break, 0x0000, 0xffff);
  2664. } else {
  2665. $data .= pack("v", $break);
  2666. }
  2667. }
  2668. $this->_prepend($header . $data);
  2669. }
  2670. /**
  2671. * Set the Biff PROTECT record to indicate that the worksheet is protected.
  2672. *
  2673. * @access private
  2674. */
  2675. function _storeProtect()
  2676. {
  2677. // Exit unless sheet protection has been specified
  2678. if ($this->_protect == 0) {
  2679. return;
  2680. }
  2681. $record = 0x0012; // Record identifier
  2682. $length = 0x0002; // Bytes to follow
  2683. $fLock = $this->_protect; // Worksheet is protected
  2684. $header = pack("vv", $record, $length);
  2685. $data = pack("v", $fLock);
  2686. $this->_prepend($header.$data);
  2687. }
  2688. /**
  2689. * Write the worksheet PASSWORD record.
  2690. *
  2691. * @access private
  2692. */
  2693. function _storePassword()
  2694. {
  2695. // Exit unless sheet protection and password have been specified
  2696. if (($this->_protect == 0) || (!isset($this->_password))) {
  2697. return;
  2698. }
  2699. $record = 0x0013; // Record identifier
  2700. $length = 0x0002; // Bytes to follow
  2701. $wPassword = $this->_password; // Encoded password
  2702. $header = pack("vv", $record, $length);
  2703. $data = pack("v", $wPassword);
  2704. $this->_prepend($header . $data);
  2705. }
  2706. /**
  2707. * Insert a 24bit bitmap image in a worksheet.
  2708. *
  2709. * @access public
  2710. * @param integer $row The row we are going to insert the bitmap into
  2711. * @param integer $col The column we are going to insert the bitmap into
  2712. * @param mixed $bitmap The bitmap filename or GD-image resource
  2713. * @param integer $x The horizontal position (offset) of the image inside the cell.
  2714. * @param integer $y The vertical position (offset) of the image inside the cell.
  2715. * @param float $scale_x The horizontal scale
  2716. * @param float $scale_y The vertical scale
  2717. */
  2718. function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
  2719. {
  2720. $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
  2721. list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
  2722. // Scale the frame of the image.
  2723. $width *= $scale_x;
  2724. $height *= $scale_y;
  2725. // Calculate the vertices of the image and write the OBJ record
  2726. $this->_positionImage($col, $row, $x, $y, $width, $height);
  2727. // Write the IMDATA record to store the bitmap data
  2728. $record = 0x007f;
  2729. $length = 8 + $size;
  2730. $cf = 0x09;
  2731. $env = 0x01;
  2732. $lcb = $size;
  2733. $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
  2734. $this->_append($header.$data);
  2735. }
  2736. /**
  2737. * Calculate the vertices that define the position of the image as required by
  2738. * the OBJ record.
  2739. *
  2740. * +------------+------------+
  2741. * | A | B |
  2742. * +-----+------------+------------+
  2743. * | |(x1,y1) | |
  2744. * | 1 |(A1)._______|______ |
  2745. * | | | | |
  2746. * | | | | |
  2747. * +-----+----| BITMAP |-----+
  2748. * | | | | |
  2749. * | 2 | |______________. |
  2750. * | | | (B2)|
  2751. * | | | (x2,y2)|
  2752. * +---- +------------+------------+
  2753. *
  2754. * Example of a bitmap that covers some of the area from cell A1 to cell B2.
  2755. *
  2756. * Based on the width and height of the bitmap we need to calculate 8 vars:
  2757. * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
  2758. * The width and height of the cells are also variable and have to be taken into
  2759. * account.
  2760. * The values of $col_start and $row_start are passed in from the calling
  2761. * function. The values of $col_end and $row_end are calculated by subtracting
  2762. * the width and height of the bitmap from the width and height of the
  2763. * underlying cells.
  2764. * The vertices are expressed as a percentage of the underlying cell width as
  2765. * follows (rhs values are in pixels):
  2766. *
  2767. * x1 = X / W *1024
  2768. * y1 = Y / H *256
  2769. * x2 = (X-1) / W *1024
  2770. * y2 = (Y-1) / H *256
  2771. *
  2772. * Where: X is distance from the left side of the underlying cell
  2773. * Y is distance from the top of the underlying cell
  2774. * W is the width of the cell
  2775. * H is the height of the cell
  2776. *
  2777. * @access private
  2778. * @note the SDK incorrectly states that the height should be expressed as a
  2779. * percentage of 1024.
  2780. * @param integer $col_start Col containing upper left corner of object
  2781. * @param integer $row_start Row containing top left corner of object
  2782. * @param integer $x1 Distance to left side of object
  2783. * @param integer $y1 Distance to top of object
  2784. * @param integer $width Width of image frame
  2785. * @param integer $height Height of image frame
  2786. */
  2787. function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
  2788. {
  2789. // Initialise end cell to the same as the start cell
  2790. $col_end = $col_start; // Col containing lower right corner of object
  2791. $row_end = $row_start; // Row containing bottom right corner of object
  2792. // Zero the specified offset if greater than the cell dimensions
  2793. if ($x1 >= $this->_sizeCol($col_start)) {
  2794. $x1 = 0;
  2795. }
  2796. if ($y1 >= $this->_sizeRow($row_start)) {
  2797. $y1 = 0;
  2798. }
  2799. $width = $width + $x1 -1;
  2800. $height = $height + $y1 -1;
  2801. // Subtract the underlying cell widths to find the end cell of the image
  2802. while ($width >= $this->_sizeCol($col_end)) {
  2803. $width -= $this->_sizeCol($col_end);
  2804. $col_end++;
  2805. }
  2806. // Subtract the underlying cell heights to find the end cell of the image
  2807. while ($height >= $this->_sizeRow($row_end)) {
  2808. $height -= $this->_sizeRow($row_end);
  2809. $row_end++;
  2810. }
  2811. // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
  2812. // with zero eight or width.
  2813. //
  2814. if ($this->_sizeCol($col_start) == 0) {
  2815. return;
  2816. }
  2817. if ($this->_sizeCol($col_end) == 0) {
  2818. return;
  2819. }
  2820. if ($this->_sizeRow($row_start) == 0) {
  2821. return;
  2822. }
  2823. if ($this->_sizeRow($row_end) == 0) {
  2824. return;
  2825. }
  2826. // Convert the pixel values to the percentage value expected by Excel
  2827. $x1 = $x1 / $this->_sizeCol($col_start) * 1024;
  2828. $y1 = $y1 / $this->_sizeRow($row_start) * 256;
  2829. $x2 = $width / $this->_sizeCol($col_end) * 1024; // Distance to right side of object
  2830. $y2 = $height / $this->_sizeRow($row_end) * 256; // Distance to bottom of object
  2831. $this->_storeObjPicture($col_start, $x1,
  2832. $row_start, $y1,
  2833. $col_end, $x2,
  2834. $row_end, $y2);
  2835. }
  2836. /**
  2837. * Convert the width of a cell from user's units to pixels. By interpolation
  2838. * the relationship is: y = 7x +5. If the width hasn't been set by the user we
  2839. * use the default value. If the col is hidden we use a value of zero.
  2840. *
  2841. * @access private
  2842. * @param integer $col The column
  2843. * @return integer The width in pixels
  2844. */
  2845. function _sizeCol($col)
  2846. {
  2847. // Look up the cell value to see if it has been changed
  2848. if (isset($this->col_sizes[$col])) {
  2849. if ($this->col_sizes[$col] == 0) {
  2850. return(0);
  2851. } else {
  2852. return(floor(7 * $this->col_sizes[$col] + 5));
  2853. }
  2854. } else {
  2855. return(64);
  2856. }
  2857. }
  2858. /**
  2859. * Convert the height of a cell from user's units to pixels. By interpolation
  2860. * the relationship is: y = 4/3x. If the height hasn't been set by the user we
  2861. * use the default value. If the row is hidden we use a value of zero. (Not
  2862. * possible to hide row yet).
  2863. *
  2864. * @access private
  2865. * @param integer $row The row
  2866. * @return integer The width in pixels
  2867. */
  2868. function _sizeRow($row)
  2869. {
  2870. // Look up the cell value to see if it has been changed
  2871. if (isset($this->_row_sizes[$row])) {
  2872. if ($this->_row_sizes[$row] == 0) {
  2873. return(0);
  2874. } else {
  2875. return(floor(4/3 * $this->_row_sizes[$row]));
  2876. }
  2877. } else {
  2878. return(17);
  2879. }
  2880. }
  2881. /**
  2882. * Store the OBJ record that precedes an IMDATA record. This could be generalise
  2883. * to support other Excel objects.
  2884. *
  2885. * @access private
  2886. * @param integer $colL Column containing upper left corner of object
  2887. * @param integer $dxL Distance from left side of cell
  2888. * @param integer $rwT Row containing top left corner of object
  2889. * @param integer $dyT Distance from top of cell
  2890. * @param integer $colR Column containing lower right corner of object
  2891. * @param integer $dxR Distance from right of cell
  2892. * @param integer $rwB Row containing bottom right corner of object
  2893. * @param integer $dyB Distance from bottom of cell
  2894. */
  2895. function _storeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
  2896. {
  2897. $record = 0x005d; // Record identifier
  2898. $length = 0x003c; // Bytes to follow
  2899. $cObj = 0x0001; // Count of objects in file (set to 1)
  2900. $OT = 0x0008; // Object type. 8 = Picture
  2901. $id = 0x0001; // Object ID
  2902. $grbit = 0x0614; // Option flags
  2903. $cbMacro = 0x0000; // Length of FMLA structure
  2904. $Reserved1 = 0x0000; // Reserved
  2905. $Reserved2 = 0x0000; // Reserved
  2906. $icvBack = 0x09; // Background colour
  2907. $icvFore = 0x09; // Foreground colour
  2908. $fls = 0x00; // Fill pattern
  2909. $fAuto = 0x00; // Automatic fill
  2910. $icv = 0x08; // Line colour
  2911. $lns = 0xff; // Line style
  2912. $lnw = 0x01; // Line weight
  2913. $fAutoB = 0x00; // Automatic border
  2914. $frs = 0x0000; // Frame style
  2915. $cf = 0x0009; // Image format, 9 = bitmap
  2916. $Reserved3 = 0x0000; // Reserved
  2917. $cbPictFmla = 0x0000; // Length of FMLA structure
  2918. $Reserved4 = 0x0000; // Reserved
  2919. $grbit2 = 0x0001; // Option flags
  2920. $Reserved5 = 0x0000; // Reserved
  2921. $header = pack("vv", $record, $length);
  2922. $data = pack("V", $cObj);
  2923. $data .= pack("v", $OT);
  2924. $data .= pack("v", $id);
  2925. $data .= pack("v", $grbit);
  2926. $data .= pack("v", $colL);
  2927. $data .= pack("v", $dxL);
  2928. $data .= pack("v", $rwT);
  2929. $data .= pack("v", $dyT);
  2930. $data .= pack("v", $colR);
  2931. $data .= pack("v", $dxR);
  2932. $data .= pack("v", $rwB);
  2933. $data .= pack("v", $dyB);
  2934. $data .= pack("v", $cbMacro);
  2935. $data .= pack("V", $Reserved1);
  2936. $data .= pack("v", $Reserved2);
  2937. $data .= pack("C", $icvBack);
  2938. $data .= pack("C", $icvFore);
  2939. $data .= pack("C", $fls);
  2940. $data .= pack("C", $fAuto);
  2941. $data .= pack("C", $icv);
  2942. $data .= pack("C", $lns);
  2943. $data .= pack("C", $lnw);
  2944. $data .= pack("C", $fAutoB);
  2945. $data .= pack("v", $frs);
  2946. $data .= pack("V", $cf);
  2947. $data .= pack("v", $Reserved3);
  2948. $data .= pack("v", $cbPictFmla);
  2949. $data .= pack("v", $Reserved4);
  2950. $data .= pack("v", $grbit2);
  2951. $data .= pack("V", $Reserved5);
  2952. $this->_append($header . $data);
  2953. }
  2954. /**
  2955. * Convert a GD-image into the internal format.
  2956. *
  2957. * @access private
  2958. * @param resource $image The image to process
  2959. * @return array Array with data and properties of the bitmap
  2960. */
  2961. function _processBitmapGd($image) {
  2962. $width = imagesx($image);
  2963. $height = imagesy($image);
  2964. $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  2965. for ($j=$height; $j--; ) {
  2966. for ($i=0; $i < $width; $i++) {
  2967. $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
  2968. foreach (array("red", "green", "blue") as $key) {
  2969. $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
  2970. }
  2971. $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
  2972. }
  2973. if (3*$width % 4) {
  2974. $data .= str_repeat("\x00", 4 - 3*$width % 4);
  2975. }
  2976. }
  2977. return array($width, $height, strlen($data), $data);
  2978. }
  2979. /**
  2980. * Convert a 24 bit bitmap into the modified internal format used by Windows.
  2981. * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
  2982. * MSDN library.
  2983. *
  2984. * @access private
  2985. * @param string $bitmap The bitmap to process
  2986. * @return array Array with data and properties of the bitmap
  2987. */
  2988. function _processBitmap($bitmap)
  2989. {
  2990. // Open file.
  2991. $bmp_fd = @fopen($bitmap,"rb");
  2992. if (!$bmp_fd) {
  2993. throw new Exception("Couldn't import $bitmap");
  2994. }
  2995. // Slurp the file into a string.
  2996. $data = fread($bmp_fd, filesize($bitmap));
  2997. // Check that the file is big enough to be a bitmap.
  2998. if (strlen($data) <= 0x36) {
  2999. throw new Exception("$bitmap doesn't contain enough data.\n");
  3000. }
  3001. // The first 2 bytes are used to identify the bitmap.
  3002. $identity = unpack("A2ident", $data);
  3003. if ($identity['ident'] != "BM") {
  3004. throw new Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
  3005. }
  3006. // Remove bitmap data: ID.
  3007. $data = substr($data, 2);
  3008. // Read and remove the bitmap size. This is more reliable than reading
  3009. // the data size at offset 0x22.
  3010. //
  3011. $size_array = unpack("Vsa", substr($data, 0, 4));
  3012. $size = $size_array['sa'];
  3013. $data = substr($data, 4);
  3014. $size -= 0x36; // Subtract size of bitmap header.
  3015. $size += 0x0C; // Add size of BIFF header.
  3016. // Remove bitmap data: reserved, offset, header length.
  3017. $data = substr($data, 12);
  3018. // Read and remove the bitmap width and height. Verify the sizes.
  3019. $width_and_height = unpack("V2", substr($data, 0, 8));
  3020. $width = $width_and_height[1];
  3021. $height = $width_and_height[2];
  3022. $data = substr($data, 8);
  3023. if ($width > 0xFFFF) {
  3024. throw new Exception("$bitmap: largest image width supported is 65k.\n");
  3025. }
  3026. if ($height > 0xFFFF) {
  3027. throw new Exception("$bitmap: largest image height supported is 65k.\n");
  3028. }
  3029. // Read and remove the bitmap planes and bpp data. Verify them.
  3030. $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
  3031. $data = substr($data, 4);
  3032. if ($planes_and_bitcount[2] != 24) { // Bitcount
  3033. throw new Exception("$bitmap isn't a 24bit true color bitmap.\n");
  3034. }
  3035. if ($planes_and_bitcount[1] != 1) {
  3036. throw new Exception("$bitmap: only 1 plane supported in bitmap image.\n");
  3037. }
  3038. // Read and remove the bitmap compression. Verify compression.
  3039. $compression = unpack("Vcomp", substr($data, 0, 4));
  3040. $data = substr($data, 4);
  3041. //$compression = 0;
  3042. if ($compression['comp'] != 0) {
  3043. throw new Exception("$bitmap: compression not supported in bitmap image.\n");
  3044. }
  3045. // Remove bitmap data: data size, hres, vres, colours, imp. colours.
  3046. $data = substr($data, 20);
  3047. // Add the BITMAPCOREHEADER data
  3048. $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  3049. $data = $header . $data;
  3050. return (array($width, $height, $size, $data));
  3051. }
  3052. /**
  3053. * Store the window zoom factor. This should be a reduced fraction but for
  3054. * simplicity we will store all fractions with a numerator of 100.
  3055. *
  3056. * @access private
  3057. */
  3058. function _storeZoom()
  3059. {
  3060. // If scale is 100 we don't need to write a record
  3061. if ($this->_zoom == 100) {
  3062. return;
  3063. }
  3064. $record = 0x00A0; // Record identifier
  3065. $length = 0x0004; // Bytes to follow
  3066. $header = pack("vv", $record, $length);
  3067. $data = pack("vv", $this->_zoom, 100);
  3068. $this->_append($header . $data);
  3069. }
  3070. /**
  3071. * Store the DVAL and DV records.
  3072. *
  3073. * @access private
  3074. */
  3075. function _storeDataValidity()
  3076. {
  3077. $record = 0x01b2; // Record identifier
  3078. $length = 0x0012; // Bytes to follow
  3079. $grbit = 0x0002; // Prompt box at cell, no cached validity data at DV records
  3080. $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
  3081. $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
  3082. $objId = 0xffffffff; // Object identifier of drop down arrow object, or -1 if not visible
  3083. $header = pack('vv', $record, $length);
  3084. $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
  3085. count($this->_dv));
  3086. $this->_append($header.$data);
  3087. $record = 0x01be; // Record identifier
  3088. foreach ($this->_dv as $dv) {
  3089. $length = strlen($dv); // Bytes to follow
  3090. $header = pack("vv", $record, $length);
  3091. $this->_append($header . $dv);
  3092. }
  3093. }
  3094. }