PageRenderTime 36ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/add-ons/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php

https://github.com/jcplat/console-seolan
PHP | 2921 lines | 1518 code | 427 blank | 976 comment | 203 complexity | 56389526036bc420ed72b5f923a3fdac MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1, GPL-3.0, Apache-2.0, BSD-3-Clause
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2009 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Writer_Excel5
  23. * @copyright Copyright (c) 2006 - 2009 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.7.1, 2009-11-02
  26. */
  27. // Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class):
  28. // -----------------------------------------------------------------------------------------
  29. // /*
  30. // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
  31. // *
  32. // * The majority of this is _NOT_ my code. I simply ported it from the
  33. // * PERL Spreadsheet::WriteExcel module.
  34. // *
  35. // * The author of the Spreadsheet::WriteExcel module is John McNamara
  36. // * <jmcnamara@cpan.org>
  37. // *
  38. // * I _DO_ maintain this code, and John McNamara has nothing to do with the
  39. // * porting of this code to PHP. Any questions directly related to this
  40. // * class library should be directed to me.
  41. // *
  42. // * License Information:
  43. // *
  44. // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
  45. // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
  46. // *
  47. // * This library is free software; you can redistribute it and/or
  48. // * modify it under the terms of the GNU Lesser General Public
  49. // * License as published by the Free Software Foundation; either
  50. // * version 2.1 of the License, or (at your option) any later version.
  51. // *
  52. // * This library is distributed in the hope that it will be useful,
  53. // * but WITHOUT ANY WARRANTY; without even the implied warranty of
  54. // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  55. // * Lesser General Public License for more details.
  56. // *
  57. // * You should have received a copy of the GNU Lesser General Public
  58. // * License along with this library; if not, write to the Free Software
  59. // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  60. // */
  61. /** PHPExcel root directory */
  62. if (!defined('PHPEXCEL_ROOT')) {
  63. /**
  64. * @ignore
  65. */
  66. define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../../');
  67. }
  68. /** PHPExcel_Writer_Excel5_Parser.php */
  69. require_once PHPEXCEL_ROOT . 'PHPExcel/Writer/Excel5/Parser.php';
  70. /** PHPExcel_Writer_Excel5_BIFFwriter.php */
  71. require_once PHPEXCEL_ROOT . 'PHPExcel/Writer/Excel5/BIFFwriter.php';
  72. /** PHPExcel_Writer_Excel5_Escher */
  73. require_once PHPEXCEL_ROOT . 'PHPExcel/Writer/Excel5/Escher.php';
  74. /** PHPExcel_RichText */
  75. require_once PHPEXCEL_ROOT . 'PHPExcel/RichText.php';
  76. /** PHPExcel_Shared_Font */
  77. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Font.php';
  78. /** PHPExcel_Shared_String */
  79. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/String.php';
  80. /** PHPExcel_Shared_Excel5 */
  81. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Excel5.php';
  82. /** PHPExcel_Shared_Escher */
  83. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Escher.php';
  84. /** PHPExcel_Shared_Escher_DgContainer */
  85. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Escher/DgContainer.php';
  86. /** PHPExcel_Shared_Escher_DgContainer_SpgrContainer */
  87. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php';
  88. /** PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer */
  89. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php';
  90. /**
  91. * PHPExcel_Writer_Excel5_Worksheet
  92. *
  93. * @category PHPExcel
  94. * @package PHPExcel_Writer_Excel5
  95. * @copyright Copyright (c) 2006 - 2009 PHPExcel (http://www.codeplex.com/PHPExcel)
  96. */
  97. class PHPExcel_Writer_Excel5_Worksheet extends PHPExcel_Writer_Excel5_BIFFwriter
  98. {
  99. /**
  100. * Formula parser
  101. *
  102. * @var PHPExcel_Writer_Excel5_Parser
  103. */
  104. private $_parser;
  105. /**
  106. * Filehandle to the temporary file for storing data
  107. * @var resource
  108. */
  109. var $_filehandle;
  110. /**
  111. * Boolean indicating if we are using a temporary file for storing data
  112. * @var bool
  113. */
  114. var $_using_tmpfile;
  115. /**
  116. * Maximum number of characters for a string (LABEL record in BIFF5)
  117. * @var integer
  118. */
  119. var $_xls_strmax;
  120. /**
  121. * Array containing format information for columns
  122. * @var array
  123. */
  124. var $_colinfo;
  125. /**
  126. * Array containing the selected area for the worksheet
  127. * @var array
  128. */
  129. var $_selection;
  130. /**
  131. * The active pane for the worksheet
  132. * @var integer
  133. */
  134. var $_active_pane;
  135. /**
  136. * Whether to use outline.
  137. * @var integer
  138. */
  139. var $_outline_on;
  140. /**
  141. * Auto outline styles.
  142. * @var bool
  143. */
  144. var $_outline_style;
  145. /**
  146. * Whether to have outline summary below.
  147. * @var bool
  148. */
  149. var $_outline_below;
  150. /**
  151. * Whether to have outline summary at the right.
  152. * @var bool
  153. */
  154. var $_outline_right;
  155. /**
  156. * Reference to the total number of strings in the workbook
  157. * @var integer
  158. */
  159. var $_str_total;
  160. /**
  161. * Reference to the number of unique strings in the workbook
  162. * @var integer
  163. */
  164. var $_str_unique;
  165. /**
  166. * Reference to the array containing all the unique strings in the workbook
  167. * @var array
  168. */
  169. var $_str_table;
  170. /**
  171. * Color cache
  172. */
  173. private $_colors;
  174. /**
  175. * The temporary dir for storing files
  176. * @var string
  177. */
  178. var $_tmp_dir;
  179. /**
  180. * List of temporary files created
  181. * @var array
  182. */
  183. var $_tempFilesCreated = array();
  184. /**
  185. * Index of first used row (at least 0)
  186. * @var int
  187. */
  188. private $_firstRowIndex;
  189. /**
  190. * Index of last used row. (no used rows means -1)
  191. * @var int
  192. */
  193. private $_lastRowIndex;
  194. /**
  195. * Index of first used column (at least 0)
  196. * @var int
  197. */
  198. private $_firstColumnIndex;
  199. /**
  200. * Index of last used column (no used columns means -1)
  201. * @var int
  202. */
  203. private $_lastColumnIndex;
  204. /**
  205. * Sheet object
  206. * @var PHPExcel_Worksheet
  207. */
  208. private $_phpSheet;
  209. /**
  210. * Count cell style Xfs
  211. *
  212. * @var int
  213. */
  214. private $_countCellStyleXfs;
  215. /**
  216. * Constructor
  217. *
  218. * @param int $BIFF_version BIFF version
  219. * @param int $str_total Total number of strings
  220. * @param int $str_unique Total number of unique strings
  221. * @param array $str_table
  222. * @param mixed $parser The formula parser created for the Workbook
  223. * @param string $tempDir The temporary directory to be used
  224. * @param PHPExcel_Worksheet $phpSheet
  225. */
  226. public function __construct($BIFF_version,
  227. &$str_total,
  228. &$str_unique, &$str_table, &$colors,
  229. $parser, $tempDir = '', $phpSheet)
  230. {
  231. // It needs to call its parent's constructor explicitly
  232. parent::__construct();
  233. $this->_BIFF_version = $BIFF_version;
  234. if ($BIFF_version == 0x0600) {
  235. // change BIFFwriter limit for CONTINUE records
  236. $this->_limit = 8224;
  237. }
  238. $this->_str_total = &$str_total;
  239. $this->_str_unique = &$str_unique;
  240. $this->_str_table = &$str_table;
  241. $this->_colors = &$colors;
  242. $this->_parser = $parser;
  243. $this->_phpSheet = $phpSheet;
  244. //$this->ext_sheets = array();
  245. $this->_filehandle = '';
  246. $this->_using_tmpfile = true;
  247. //$this->fileclosed = 0;
  248. //$this->offset = 0;
  249. $this->_xls_strmax = 255;
  250. $this->_colinfo = array();
  251. $this->_selection = array(0,0,0,0);
  252. $this->_active_pane = 3;
  253. $this->_print_headers = 0;
  254. $this->_outline_style = 0;
  255. $this->_outline_below = 1;
  256. $this->_outline_right = 1;
  257. $this->_outline_on = 1;
  258. $this->_dv = array();
  259. $this->_tmp_dir = $tempDir;
  260. // calculate values for DIMENSIONS record
  261. $this->_firstRowIndex = 0;
  262. $this->_lastRowIndex = -1;
  263. $this->_firstColumnIndex = 0;
  264. $this->_lastColumnIndex = -1;
  265. foreach ($this->_phpSheet->getCellCollection(false) as $cell) {
  266. $row = $cell->getRow() - 1;
  267. $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
  268. // Don't break Excel!
  269. if ($row + 1 > 65536 or $column + 1 > 256) {
  270. break;
  271. }
  272. $this->_firstRowIndex = min($this->_firstRowIndex, $row);
  273. $this->_lastRowIndex = max($this->_lastRowIndex, $row);
  274. $this->_firstColumnIndex = min($this->_firstColumnIndex, $column);
  275. $this->_lastColumnIndex = max($this->_lastColumnIndex, $column);
  276. }
  277. $this->_initialize();
  278. $this->_countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
  279. }
  280. /**
  281. * Cleanup
  282. */
  283. public function cleanup() {
  284. @fclose($this->_filehandle);
  285. foreach ($this->_tempFilesCreated as $file) {
  286. @unlink($file);
  287. }
  288. }
  289. /**
  290. * Open a tmp file to store the majority of the Worksheet data. If this fails,
  291. * for example due to write permissions, store the data in memory. This can be
  292. * slow for large files.
  293. *
  294. * @access private
  295. */
  296. function _initialize()
  297. {
  298. // Open tmp file for storing Worksheet data
  299. $fileName = tempnam($this->_tmp_dir, 'XLSHEET');
  300. $fh = fopen($fileName, 'w+');
  301. if ($fh) {
  302. // Store filehandle
  303. $this->_filehandle = $fh;
  304. $this->_tempFilesCreated[] = $fileName;
  305. } else {
  306. // If tmpfile() fails store data in memory
  307. $this->_using_tmpfile = false;
  308. }
  309. }
  310. /**
  311. * Add data to the beginning of the workbook (note the reverse order)
  312. * and to the end of the workbook.
  313. *
  314. * @access public
  315. * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook()
  316. */
  317. function close()
  318. {
  319. $num_sheets = count($this->_phpSheet->getParent()->getAllSheets());
  320. // Write BOF record
  321. $this->_storeBof(0x0010);
  322. // Write DEFCOLWIDTH record
  323. $this->_storeDefcol();
  324. // Calculate column widths
  325. $this->_phpSheet->calculateColumnWidths();
  326. // Column dimensions
  327. $columnDimensions = $this->_phpSheet->getColumnDimensions();
  328. for ($i = 0; $i < 256; ++$i) {
  329. $hidden = 0;
  330. $level = 0;
  331. $xfIndex = 15; // there are 15 cell style Xfs
  332. if ($this->_phpSheet->getDefaultColumnDimension()->getWidth() >= 0) {
  333. $width = $this->_phpSheet->getDefaultColumnDimension()->getWidth();
  334. } else {
  335. $width = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($this->_phpSheet->getParent()->getDefaultStyle()->getFont());
  336. }
  337. $columnLetter = PHPExcel_Cell::stringFromColumnIndex($i);
  338. if (isset($columnDimensions[$columnLetter])) {
  339. $columnDimension = $columnDimensions[$columnLetter];
  340. if ($columnDimension->getWidth() >= 0) {
  341. $width = $columnDimension->getWidth();
  342. }
  343. $hidden = $columnDimension->getVisible() ? 0 : 1;
  344. $level = $columnDimension->getOutlineLevel();
  345. $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
  346. }
  347. $this->_setColumn( $i, $i, $width, $xfIndex, $hidden, $level);
  348. }
  349. // Write the COLINFO records if they exist
  350. if (!empty($this->_colinfo)) {
  351. $colcount = count($this->_colinfo);
  352. for ($i = 0; $i < $colcount; ++$i) {
  353. $this->_storeColinfo($this->_colinfo[$i]);
  354. }
  355. }
  356. // Write EXTERNCOUNT of external references
  357. if ($this->_BIFF_version == 0x0500) {
  358. $this->_storeExterncount($num_sheets);
  359. }
  360. // Write EXTERNSHEET references
  361. if ($this->_BIFF_version == 0x0500) {
  362. for ($i = 0; $i < $num_sheets; ++$i) {
  363. $this->_storeExternsheet($this->_phpSheet->getParent()->getSheet($i)->getTitle());
  364. }
  365. }
  366. // Write PRINTHEADERS
  367. $this->_storePrintHeaders();
  368. // Write PRINTGRIDLINES
  369. $this->_storePrintGridlines();
  370. // Write GUTS
  371. $this->_storeGuts();
  372. // Write GRIDSET
  373. $this->_storeGridset();
  374. // Write DEFAULTROWHEIGHT
  375. if ($this->_BIFF_version == 0x0600) {
  376. $this->_storeDefaultRowHeight();
  377. }
  378. // Write WSBOOL
  379. $this->_storeWsbool();
  380. // Write horizontal and vertical page breaks
  381. $this->_storeBreaks();
  382. // Write page header
  383. $this->_storeHeader();
  384. // Write page footer
  385. $this->_storeFooter();
  386. // Write page horizontal centering
  387. $this->_storeHcenter();
  388. // Write page vertical centering
  389. $this->_storeVcenter();
  390. // Write left margin
  391. $this->_storeMarginLeft();
  392. // Write right margin
  393. $this->_storeMarginRight();
  394. // Write top margin
  395. $this->_storeMarginTop();
  396. // Write bottom margin
  397. $this->_storeMarginBottom();
  398. // Write page setup
  399. $this->_storeSetup();
  400. // Write sheet protection
  401. $this->_storeProtect();
  402. // Write sheet password
  403. $this->_storePassword();
  404. // Write sheet dimensions
  405. $this->_storeDimensions();
  406. // Row dimensions
  407. foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) {
  408. $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
  409. $this->_setRow( $rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel() );
  410. }
  411. // Write Cells
  412. foreach ($this->_phpSheet->getCellCollection() as $cell) {
  413. $row = $cell->getRow() - 1;
  414. $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
  415. // Don't break Excel!
  416. if ($row + 1 > 65536 or $column + 1 > 256) {
  417. break;
  418. }
  419. // Write cell value
  420. $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
  421. if ($cell->getValue() instanceof PHPExcel_RichText) {
  422. $this->_writeString($row, $column, $cell->getValue()->getPlainText(), $xfIndex);
  423. } else {
  424. switch ($cell->getDatatype()) {
  425. case PHPExcel_Cell_DataType::TYPE_STRING:
  426. if ($cell->getValue() === '' or $cell->getValue() === null) {
  427. $this->_writeBlank($row, $column, $xfIndex);
  428. } else {
  429. $this->_writeString($row, $column, $cell->getValue(), $xfIndex);
  430. }
  431. break;
  432. case PHPExcel_Cell_DataType::TYPE_FORMULA:
  433. $this->_writeFormula($row, $column, $cell->getValue(), $xfIndex);
  434. break;
  435. case PHPExcel_Cell_DataType::TYPE_BOOL:
  436. $this->_writeBoolErr($row, $column, $cell->getValue(), 0, $xfIndex);
  437. break;
  438. case PHPExcel_Cell_DataType::TYPE_ERROR:
  439. $this->_writeBoolErr($row, $column, $this->_mapErrorCode($cell->getValue()), 1, $xfIndex);
  440. break;
  441. case PHPExcel_Cell_DataType::TYPE_NUMERIC:
  442. $this->_writeNumber($row, $column, $cell->getValue(), $xfIndex);
  443. break;
  444. }
  445. }
  446. }
  447. // Append
  448. if ($this->_BIFF_version == 0x0600) {
  449. $this->_storeMsoDrawing();
  450. }
  451. $this->_storeWindow2();
  452. $this->_storeZoom();
  453. if ($this->_phpSheet->getFreezePane()) {
  454. $this->_storePanes();
  455. }
  456. $this->_storeSelection($this->_selection);
  457. $this->_storeMergedCells();
  458. // Hyperlinks
  459. if ($this->_BIFF_version == 0x0600) {
  460. foreach ($this->_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
  461. list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinate);
  462. $url = $hyperlink->getUrl();
  463. if ( strpos($url, 'sheet://') !== false ) {
  464. // internal to current workbook
  465. $url = str_replace('sheet://', 'internal:', $url);
  466. } else if ( preg_match('/^(http:|https:|ftp:|mailto:)/', $url) ) {
  467. // URL
  468. // $url = $url;
  469. } else {
  470. // external (local file)
  471. $url = 'external:' . $url;
  472. }
  473. $this->_writeUrl($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $url);
  474. }
  475. }
  476. /*if ($this->_BIFF_version == 0x0600) {
  477. $this->_storeDataValidity();
  478. }*/
  479. if ($this->_BIFF_version == 0x0600) {
  480. $this->_storeSheetLayout();
  481. $this->_storeRangeProtection();
  482. }
  483. $this->_storeEof();
  484. }
  485. /**
  486. * Write a cell range address in BIFF8
  487. * always fixed range
  488. * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format
  489. *
  490. * @param string $range E.g. 'A1' or 'A1:B6'
  491. * @return string Binary data
  492. */
  493. private function _writeBIFF8CellRangeAddressFixed($range = 'A1')
  494. {
  495. $explodes = explode(':', $range);
  496. // extract first cell, e.g. 'A1'
  497. $firstCell = $explodes[0];
  498. // extract last cell, e.g. 'B6'
  499. if (count($explodes) == 1) {
  500. $lastCell = $firstCell;
  501. } else {
  502. $lastCell = $explodes[1];
  503. }
  504. $firstCellCoordinates = PHPExcel_Cell::coordinateFromString($firstCell); // e.g. array(0, 1)
  505. $lastCellCoordinates = PHPExcel_Cell::coordinateFromString($lastCell); // e.g. array(1, 6)
  506. $data = pack('vvvv',
  507. $firstCellCoordinates[1] - 1,
  508. $lastCellCoordinates[1] - 1,
  509. PHPExcel_Cell::columnIndexFromString($firstCellCoordinates[0]) - 1,
  510. PHPExcel_Cell::columnIndexFromString($lastCellCoordinates[0]) - 1
  511. );
  512. return $data;
  513. }
  514. /**
  515. * Retrieves data from memory in one chunk, or from disk in $buffer
  516. * sized chunks.
  517. *
  518. * @return string The data
  519. */
  520. function getData()
  521. {
  522. $buffer = 4096;
  523. // Return data stored in memory
  524. if (isset($this->_data)) {
  525. $tmp = $this->_data;
  526. unset($this->_data);
  527. $fh = $this->_filehandle;
  528. if ($this->_using_tmpfile) {
  529. fseek($fh, 0);
  530. }
  531. return $tmp;
  532. }
  533. // Return data stored on disk
  534. if ($this->_using_tmpfile) {
  535. if ($tmp = fread($this->_filehandle, $buffer)) {
  536. return $tmp;
  537. }
  538. }
  539. // No data to return
  540. return false;
  541. }
  542. /**
  543. * Set the width of a single column or a range of columns.
  544. *
  545. * @param integer $firstcol first column on the range
  546. * @param integer $lastcol last column on the range
  547. * @param integer $width width to set
  548. * @param integer $xfIndex The optional cell style Xf index to apply to the columns
  549. * @param integer $hidden The optional hidden atribute
  550. * @param integer $level The optional outline level
  551. */
  552. private function _setColumn($firstcol, $lastcol, $width, $xfIndex = 15, $hidden = 0, $level = 0)
  553. {
  554. $this->_colinfo[] = array($firstcol, $lastcol, $width, $xfIndex, $hidden, $level);
  555. // Set width to zero if column is hidden
  556. $width = ($hidden) ? 0 : $width;
  557. }
  558. /**
  559. * Set which cell or cells are selected in a worksheet
  560. *
  561. * @access public
  562. * @param integer $first_row first row in the selected quadrant
  563. * @param integer $first_column first column in the selected quadrant
  564. * @param integer $last_row last row in the selected quadrant
  565. * @param integer $last_column last column in the selected quadrant
  566. */
  567. function setSelection($first_row,$first_column,$last_row,$last_column)
  568. {
  569. $this->_selection = array($first_row,$first_column,$last_row,$last_column);
  570. }
  571. /**
  572. * Set the option to print the row and column headers on the printed page.
  573. *
  574. * @access public
  575. * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
  576. */
  577. function printRowColHeaders($print = 1)
  578. {
  579. $this->_print_headers = $print;
  580. }
  581. /**
  582. * Store Worksheet data in memory using the parent's class append() or to a
  583. * temporary file, the default.
  584. *
  585. * @access private
  586. * @param string $data The binary data to append
  587. */
  588. function _append($data)
  589. {
  590. if ($this->_using_tmpfile) {
  591. // Add CONTINUE records if necessary
  592. if (strlen($data) - 4 > $this->_limit) {
  593. $data = $this->_addContinue($data);
  594. }
  595. fwrite($this->_filehandle, $data);
  596. $this->_datasize += strlen($data);
  597. } else {
  598. parent::_append($data);
  599. }
  600. }
  601. /**
  602. * This method sets the properties for outlining and grouping. The defaults
  603. * correspond to Excel's defaults.
  604. *
  605. * @param bool $visible
  606. * @param bool $symbols_below
  607. * @param bool $symbols_right
  608. * @param bool $auto_style
  609. */
  610. function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
  611. {
  612. $this->_outline_on = $visible;
  613. $this->_outline_below = $symbols_below;
  614. $this->_outline_right = $symbols_right;
  615. $this->_outline_style = $auto_style;
  616. // Ensure this is a boolean vale for Window2
  617. if ($this->_outline_on) {
  618. $this->_outline_on = 1;
  619. }
  620. }
  621. /**
  622. * Write a double to the specified row and column (zero indexed).
  623. * An integer can be written as a double. Excel will display an
  624. * integer. $format is optional.
  625. *
  626. * Returns 0 : normal termination
  627. * -2 : row or column out of range
  628. *
  629. * @param integer $row Zero indexed row
  630. * @param integer $col Zero indexed column
  631. * @param float $num The number to write
  632. * @param mixed $format The optional XF format
  633. * @return integer
  634. */
  635. private function _writeNumber($row, $col, $num, $xfIndex)
  636. {
  637. $record = 0x0203; // Record identifier
  638. $length = 0x000E; // Number of bytes to follow
  639. $header = pack("vv", $record, $length);
  640. $data = pack("vvv", $row, $col, $xfIndex);
  641. $xl_double = pack("d", $num);
  642. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  643. $xl_double = strrev($xl_double);
  644. }
  645. $this->_append($header.$data.$xl_double);
  646. return(0);
  647. }
  648. /**
  649. * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
  650. *
  651. * @param int $row Row index (0-based)
  652. * @param int $col Column index (0-based)
  653. * @param string $str The string
  654. * @param int $xfIndex Index to XF record
  655. */
  656. private function _writeString($row, $col, $str, $xfIndex)
  657. {
  658. if ($this->_BIFF_version == 0x0600) {
  659. $this->_writeLabelSst($row, $col, $str, $xfIndex);
  660. } else {
  661. $this->_writeLabel($row, $col, $str, $xfIndex);
  662. }
  663. }
  664. /**
  665. * Write a string to the specified row and column (zero indexed).
  666. * NOTE: there is an Excel 5 defined limit of 255 characters.
  667. * $format is optional.
  668. * Returns 0 : normal termination
  669. * -2 : row or column out of range
  670. * -3 : long string truncated to 255 chars
  671. *
  672. * @access public
  673. * @param integer $row Zero indexed row
  674. * @param integer $col Zero indexed column
  675. * @param string $str The string to write
  676. * @param mixed $format The XF format for the cell
  677. * @return integer
  678. */
  679. private function _writeLabel($row, $col, $str, $xfIndex)
  680. {
  681. $strlen = strlen($str);
  682. $record = 0x0204; // Record identifier
  683. $length = 0x0008 + $strlen; // Bytes to follow
  684. $str_error = 0;
  685. if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
  686. $str = substr($str, 0, $this->_xls_strmax);
  687. $length = 0x0008 + $this->_xls_strmax;
  688. $strlen = $this->_xls_strmax;
  689. $str_error = -3;
  690. }
  691. $header = pack("vv", $record, $length);
  692. $data = pack("vvvv", $row, $col, $xfIndex, $strlen);
  693. $this->_append($header . $data . $str);
  694. return($str_error);
  695. }
  696. /**
  697. * Write a string to the specified row and column (zero indexed).
  698. * This is the BIFF8 version (no 255 chars limit).
  699. * $format is optional.
  700. * Returns 0 : normal termination
  701. * -2 : row or column out of range
  702. * -3 : long string truncated to 255 chars
  703. *
  704. * @access public
  705. * @param integer $row Zero indexed row
  706. * @param integer $col Zero indexed column
  707. * @param string $str The string to write
  708. * @param mixed $format The XF format for the cell
  709. * @return integer
  710. */
  711. private function _writeLabelSst($row, $col, $str, $xfIndex)
  712. {
  713. $record = 0x00FD; // Record identifier
  714. $length = 0x000A; // Bytes to follow
  715. $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($str);
  716. /* check if string is already present */
  717. if (!isset($this->_str_table[$str])) {
  718. $this->_str_table[$str] = $this->_str_unique++;
  719. }
  720. $this->_str_total++;
  721. $header = pack('vv', $record, $length);
  722. $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
  723. $this->_append($header.$data);
  724. }
  725. /**
  726. * Writes a note associated with the cell given by the row and column.
  727. * NOTE records don't have a length limit.
  728. *
  729. * @param integer $row Zero indexed row
  730. * @param integer $col Zero indexed column
  731. * @param string $note The note to write
  732. */
  733. private function _writeNote($row, $col, $note)
  734. {
  735. $note_length = strlen($note);
  736. $record = 0x001C; // Record identifier
  737. $max_length = 2048; // Maximun length for a NOTE record
  738. //$length = 0x0006 + $note_length; // Bytes to follow
  739. // Length for this record is no more than 2048 + 6
  740. $length = 0x0006 + min($note_length, 2048);
  741. $header = pack("vv", $record, $length);
  742. $data = pack("vvv", $row, $col, $note_length);
  743. $this->_append($header . $data . substr($note, 0, 2048));
  744. for ($i = $max_length; $i < $note_length; $i += $max_length) {
  745. $chunk = substr($note, $i, $max_length);
  746. $length = 0x0006 + strlen($chunk);
  747. $header = pack("vv", $record, $length);
  748. $data = pack("vvv", -1, 0, strlen($chunk));
  749. $this->_append($header.$data.$chunk);
  750. }
  751. return(0);
  752. }
  753. /**
  754. * Write a blank cell to the specified row and column (zero indexed).
  755. * A blank cell is used to specify formatting without adding a string
  756. * or a number.
  757. *
  758. * A blank cell without a format serves no purpose. Therefore, we don't write
  759. * a BLANK record unless a format is specified.
  760. *
  761. * Returns 0 : normal termination (including no format)
  762. * -1 : insufficient number of arguments
  763. * -2 : row or column out of range
  764. *
  765. * @param integer $row Zero indexed row
  766. * @param integer $col Zero indexed column
  767. * @param mixed $format The XF format
  768. */
  769. function _writeBlank($row, $col, $xfIndex)
  770. {
  771. $record = 0x0201; // Record identifier
  772. $length = 0x0006; // Number of bytes to follow
  773. $header = pack("vv", $record, $length);
  774. $data = pack("vvv", $row, $col, $xfIndex);
  775. $this->_append($header . $data);
  776. return 0;
  777. }
  778. /**
  779. * Write a boolean or an error type to the specified row and column (zero indexed)
  780. *
  781. * @param int $row Row index (0-based)
  782. * @param int $col Column index (0-based)
  783. * @param int $value
  784. * @param boolean $isError Error or Boolean?
  785. * @param int $xfIndex
  786. */
  787. private function _writeBoolErr($row, $col, $value, $isError, $xfIndex)
  788. {
  789. $record = 0x0205;
  790. $length = 8;
  791. $header = pack("vv", $record, $length);
  792. $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError);
  793. $this->_append($header . $data);
  794. return 0;
  795. }
  796. /**
  797. * Write a formula to the specified row and column (zero indexed).
  798. * The textual representation of the formula is passed to the parser in
  799. * Parser.php which returns a packed binary string.
  800. *
  801. * Returns 0 : normal termination
  802. * -1 : formula errors (bad formula)
  803. * -2 : row or column out of range
  804. *
  805. * @param integer $row Zero indexed row
  806. * @param integer $col Zero indexed column
  807. * @param string $formula The formula text string
  808. * @param mixed $format The optional XF format
  809. * @return integer
  810. */
  811. private function _writeFormula($row, $col, $formula, $xfIndex)
  812. {
  813. $record = 0x0006; // Record identifier
  814. // Excel normally stores the last calculated value of the formula in $num.
  815. // Clearly we are not in a position to calculate this a priori. Instead
  816. // we set $num to zero and set the option flags in $grbit to ensure
  817. // automatic calculation of the formula when the file is opened.
  818. //
  819. $num = 0x00; // Current value of formula
  820. $grbit = 0x03; // Option flags
  821. $unknown = 0x0000; // Must be zero
  822. // Strip the '=' or '@' sign at the beginning of the formula string
  823. if (preg_match("/^=/", $formula)) {
  824. $formula = preg_replace("/(^=)/", "", $formula);
  825. } elseif (preg_match("/^@/", $formula)) {
  826. $formula = preg_replace("/(^@)/", "", $formula);
  827. } else {
  828. // Error handling
  829. $this->_writeString($row, $col, 'Unrecognised character for formula');
  830. return -1;
  831. }
  832. // Parse the formula using the parser in Parser.php
  833. try {
  834. $error = $this->_parser->parse($formula);
  835. $formula = $this->_parser->toReversePolish();
  836. $formlen = strlen($formula); // Length of the binary string
  837. $length = 0x16 + $formlen; // Length of the record data
  838. $header = pack("vv", $record, $length);
  839. $data = pack("vvvdvVv", $row, $col, $xfIndex, $num,
  840. $grbit, $unknown, $formlen);
  841. $this->_append($header . $data . $formula);
  842. return 0;
  843. } catch (Exception $e) {
  844. // do nothing
  845. }
  846. }
  847. /**
  848. * Write a hyperlink.
  849. * This is comprised of two elements: the visible label and
  850. * the invisible link. The visible label is the same as the link unless an
  851. * alternative string is specified. The label is written using the
  852. * _writeString() method. Therefore the 255 characters string limit applies.
  853. * $string and $format are optional.
  854. *
  855. * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
  856. * directory url.
  857. *
  858. * Returns 0 : normal termination
  859. * -2 : row or column out of range
  860. * -3 : long string truncated to 255 chars
  861. *
  862. * @param integer $row Row
  863. * @param integer $col Column
  864. * @param string $url URL string
  865. * @return integer
  866. */
  867. private function _writeUrl($row, $col, $url)
  868. {
  869. // Add start row and col to arg list
  870. return($this->_writeUrlRange($row, $col, $row, $col, $url));
  871. }
  872. /**
  873. * This is the more general form of _writeUrl(). It allows a hyperlink to be
  874. * written to a range of cells. This function also decides the type of hyperlink
  875. * to be written. These are either, Web (http, ftp, mailto), Internal
  876. * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
  877. *
  878. * @access private
  879. * @see _writeUrl()
  880. * @param integer $row1 Start row
  881. * @param integer $col1 Start column
  882. * @param integer $row2 End row
  883. * @param integer $col2 End column
  884. * @param string $url URL string
  885. * @return integer
  886. */
  887. function _writeUrlRange($row1, $col1, $row2, $col2, $url)
  888. {
  889. // Check for internal/external sheet links or default to web link
  890. if (preg_match('[^internal:]', $url)) {
  891. return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url));
  892. }
  893. if (preg_match('[^external:]', $url)) {
  894. return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url));
  895. }
  896. return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url));
  897. }
  898. /**
  899. * Used to write http, ftp and mailto hyperlinks.
  900. * The link type ($options) is 0x03 is the same as absolute dir ref without
  901. * sheet. However it is differentiated by the $unknown2 data stream.
  902. *
  903. * @access private
  904. * @see _writeUrl()
  905. * @param integer $row1 Start row
  906. * @param integer $col1 Start column
  907. * @param integer $row2 End row
  908. * @param integer $col2 End column
  909. * @param string $url URL string
  910. * @return integer
  911. */
  912. function _writeUrlWeb($row1, $col1, $row2, $col2, $url)
  913. {
  914. $record = 0x01B8; // Record identifier
  915. $length = 0x00000; // Bytes to follow
  916. // Pack the undocumented parts of the hyperlink stream
  917. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  918. $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
  919. // Pack the option flags
  920. $options = pack("V", 0x03);
  921. // Convert URL to a null terminated wchar string
  922. $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  923. $url = $url . "\0\0\0";
  924. // Pack the length of the URL
  925. $url_len = pack("V", strlen($url));
  926. // Calculate the data length
  927. $length = 0x34 + strlen($url);
  928. // Pack the header data
  929. $header = pack("vv", $record, $length);
  930. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  931. // Write the packed data
  932. $this->_append($header . $data .
  933. $unknown1 . $options .
  934. $unknown2 . $url_len . $url);
  935. return 0;
  936. }
  937. /**
  938. * Used to write internal reference hyperlinks such as "Sheet1!A1".
  939. *
  940. * @access private
  941. * @see _writeUrl()
  942. * @param integer $row1 Start row
  943. * @param integer $col1 Start column
  944. * @param integer $row2 End row
  945. * @param integer $col2 End column
  946. * @param string $url URL string
  947. * @return integer
  948. */
  949. function _writeUrlInternal($row1, $col1, $row2, $col2, $url)
  950. {
  951. $record = 0x01B8; // Record identifier
  952. $length = 0x00000; // Bytes to follow
  953. // Strip URL type
  954. $url = preg_replace('/^internal:/', '', $url);
  955. // Pack the undocumented parts of the hyperlink stream
  956. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  957. // Pack the option flags
  958. $options = pack("V", 0x08);
  959. // Convert the URL type and to a null terminated wchar string
  960. $url .= "\0";
  961. // character count
  962. $url_len = PHPExcel_Shared_String::CountCharacters($url);
  963. $url_len = pack('V', $url_len);
  964. $url = PHPExcel_Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8');
  965. // Calculate the data length
  966. $length = 0x24 + strlen($url);
  967. // Pack the header data
  968. $header = pack("vv", $record, $length);
  969. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  970. // Write the packed data
  971. $this->_append($header . $data .
  972. $unknown1 . $options .
  973. $url_len . $url);
  974. return 0;
  975. }
  976. /**
  977. * Write links to external directory names such as 'c:\foo.xls',
  978. * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
  979. *
  980. * Note: Excel writes some relative links with the $dir_long string. We ignore
  981. * these cases for the sake of simpler code.
  982. *
  983. * @access private
  984. * @see _writeUrl()
  985. * @param integer $row1 Start row
  986. * @param integer $col1 Start column
  987. * @param integer $row2 End row
  988. * @param integer $col2 End column
  989. * @param string $url URL string
  990. * @return integer
  991. */
  992. function _writeUrlExternal($row1, $col1, $row2, $col2, $url)
  993. {
  994. // Network drives are different. We will handle them separately
  995. // MS/Novell network drives and shares start with \\
  996. if (preg_match('[^external:\\\\]', $url)) {
  997. return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
  998. }
  999. $record = 0x01B8; // Record identifier
  1000. $length = 0x00000; // Bytes to follow
  1001. // Strip URL type and change Unix dir separator to Dos style (if needed)
  1002. //
  1003. $url = preg_replace('/^external:/', '', $url);
  1004. $url = preg_replace('/\//', "\\", $url);
  1005. // Determine if the link is relative or absolute:
  1006. // relative if link contains no dir separator, "somefile.xls"
  1007. // relative if link starts with up-dir, "..\..\somefile.xls"
  1008. // otherwise, absolute
  1009. $absolute = 0x00; // relative path
  1010. if ( preg_match('/^[A-Z]:/', $url) ) {
  1011. $absolute = 0x02; // absolute path on Windows, e.g. C:\...
  1012. }
  1013. $link_type = 0x01 | $absolute;
  1014. // Determine if the link contains a sheet reference and change some of the
  1015. // parameters accordingly.
  1016. // Split the dir name and sheet name (if it exists)
  1017. /*if (preg_match("/\#/", $url)) {
  1018. list($dir_long, $sheet) = split("\#", $url);
  1019. } else {
  1020. $dir_long = $url;
  1021. }
  1022. if (isset($sheet)) {
  1023. $link_type |= 0x08;
  1024. $sheet_len = pack("V", strlen($sheet) + 0x01);
  1025. $sheet = join("\0", split('', $sheet));
  1026. $sheet .= "\0\0\0";
  1027. } else {
  1028. $sheet_len = '';
  1029. $sheet = '';
  1030. }*/
  1031. $dir_long = $url;
  1032. if (preg_match("/\#/", $url)) {
  1033. $link_type |= 0x08;
  1034. }
  1035. // Pack the link type
  1036. $link_type = pack("V", $link_type);
  1037. // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
  1038. $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
  1039. $up_count = pack("v", $up_count);
  1040. // Store the short dos dir name (null terminated)
  1041. $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
  1042. // Store the long dir name as a wchar string (non-null terminated)
  1043. //$dir_long = join("\0", split('', $dir_long));
  1044. $dir_long = $dir_long . "\0";
  1045. // Pack the lengths of the dir strings
  1046. $dir_short_len = pack("V", strlen($dir_short) );
  1047. $dir_long_len = pack("V", strlen($dir_long) );
  1048. $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
  1049. // Pack the undocumented parts of the hyperlink stream
  1050. $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
  1051. $unknown2 = pack("H*",'0303000000000000C000000000000046' );
  1052. $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
  1053. $unknown4 = pack("v", 0x03 );
  1054. // Pack the main data stream
  1055. $data = pack("vvvv", $row1, $row2, $col1, $col2) .
  1056. $unknown1 .
  1057. $link_type .
  1058. $unknown2 .
  1059. $up_count .
  1060. $dir_short_len.
  1061. $dir_short .
  1062. $unknown3 .
  1063. $stream_len ;/*.
  1064. $dir_long_len .
  1065. $unknown4 .
  1066. $dir_long .
  1067. $sheet_len .
  1068. $sheet ;*/
  1069. // Pack the header data
  1070. $length = strlen($data);
  1071. $header = pack("vv", $record, $length);
  1072. // Write the packed data
  1073. $this->_append($header. $data);
  1074. return 0;
  1075. }
  1076. /**
  1077. * This method is used to set the height and format for a row.
  1078. *
  1079. * @param integer $row The row to set
  1080. * @param integer $height Height we are giving to the row.
  1081. * Use null to set XF without setting height
  1082. * @param integer $xfIndex The optional cell style Xf index to apply to the columns
  1083. * @param bool $hidden The optional hidden attribute
  1084. * @param integer $level The optional outline level for row, in range [0,7]
  1085. */
  1086. private function _setRow($row, $height, $xfIndex, $hidden = false, $level = 0)
  1087. {
  1088. $record = 0x0208; // Record identifier
  1089. $length = 0x0010; // Number of bytes to follow
  1090. $colMic = 0x0000; // First defined column
  1091. $colMac = 0x0000; // Last defined column
  1092. $irwMac = 0x0000; // Used by Excel to optimise loading
  1093. $reserved = 0x0000; // Reserved
  1094. $grbit = 0x0000; // Option flags
  1095. $ixfe = $xfIndex;
  1096. if ( $height < 0 ){
  1097. $height = null;
  1098. }
  1099. // Use _setRow($row, null, $XF) to set XF format without setting height
  1100. if ($height != null) {
  1101. $miyRw = $height * 20; // row height
  1102. } else {
  1103. $miyRw = 0xff; // default row height is 256
  1104. }
  1105. // Set the options flags. fUnsynced is used to show that the font and row
  1106. // heights are not compatible. This is usually the case for WriteExcel.
  1107. // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
  1108. // is collapsed. Instead it is used to indicate that the previous row is
  1109. // collapsed. The zero height flag, 0x20, is used to collapse a row.
  1110. $grbit |= $level;
  1111. if ($hidden) {
  1112. $grbit |= 0x0020;
  1113. }
  1114. if ($height !== null) {
  1115. $grbit |= 0x0040; // fUnsynced
  1116. }
  1117. if ($xfIndex !== 0xF) {
  1118. $grbit |= 0x0080;
  1119. }
  1120. $grbit |= 0x0100;
  1121. $header = pack("vv", $record, $length);
  1122. $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
  1123. $irwMac,$reserved, $grbit, $ixfe);
  1124. $this->_append($header.$data);
  1125. }
  1126. /**
  1127. * Writes Excel DIMENSIONS to define the area in which there is data.
  1128. *
  1129. * @access private
  1130. */
  1131. function _storeDimensions()
  1132. {
  1133. $record = 0x0200; // Record identifier
  1134. if ($this->_BIFF_version == 0x0500) {
  1135. $length = 0x000A; // Number of bytes to follow
  1136. $data = pack("vvvvv"
  1137. , $this->_firstRowIndex
  1138. , $this->_lastRowIndex + 1
  1139. , $this->_firstColumnIndex
  1140. , $this->_lastColumnIndex + 1
  1141. , 0x0000 // reserved
  1142. );
  1143. } elseif ($this->_BIFF_version == 0x0600) {
  1144. $length = 0x000E;
  1145. $data = pack('VVvvv'
  1146. , $this->_firstRowIndex
  1147. , $this->_lastRowIndex + 1
  1148. , $this->_firstColumnIndex
  1149. , $this->_lastColumnIndex + 1
  1150. , 0x0000 // reserved
  1151. );
  1152. }
  1153. $header = pack("vv", $record, $length);
  1154. $this->_append($header.$data);
  1155. }
  1156. /**
  1157. * Write BIFF record Window2.
  1158. *
  1159. * @access private
  1160. */
  1161. function _storeWindow2()
  1162. {
  1163. $record = 0x023E; // Record identifier
  1164. if ($this->_BIFF_version == 0x0500) {
  1165. $length = 0x000A; // Number of bytes to follow
  1166. } elseif ($this->_BIFF_version == 0x0600) {
  1167. $length = 0x0012;
  1168. }
  1169. $grbit = 0x00B6; // Option flags
  1170. $rwTop = 0x0000; // Top row visible in window
  1171. $colLeft = 0x0000; // Leftmost column visible in window
  1172. // The options flags that comprise $grbit
  1173. $fDspFmla = 0; // 0 - bit
  1174. $fDspGrid = $this->_phpSheet->getShowGridlines() ? 1 : 0; // 1
  1175. $fDspRwCol = 1; // 2
  1176. $fFrozen = $this->_phpSheet->getFreezePane() ? 1 : 0; // 3
  1177. $fDspZeros = 1; // 4
  1178. $fDefaultHdr = 1; // 5
  1179. $fArabic = $this->_phpSheet->getRightToLeft() ? 1 : 0; // 6
  1180. $fDspGuts = $this->_outline_on; // 7
  1181. $fFrozenNoSplit = 0; // 0 - bit
  1182. // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet
  1183. $fSelected = ($this->_phpSheet === $this->_phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
  1184. $fPaged = 1; // 2
  1185. $grbit = $fDspFmla;
  1186. $grbit |= $fDspGrid << 1;
  1187. $grbit |= $fDspRwCol << 2;
  1188. $grbit |= $fFrozen << 3;
  1189. $grbit |= $fDspZeros << 4;
  1190. $grbit |= $fDefaultHdr << 5;
  1191. $grbit |= $fArabic << 6;
  1192. $grbit |= $fDspGuts << 7;
  1193. $grbit |= $fFrozenNoSplit << 8;
  1194. $grbit |= $fSelected << 9;
  1195. $grbit |= $fPaged << 10;
  1196. $header = pack("vv", $record, $length);
  1197. $data = pack("vvv", $grbit, $rwTop, $colLeft);
  1198. // FIXME !!!
  1199. if ($this->_BIFF_version == 0x0500) {
  1200. $rgbHdr = 0x00000000; // Row/column heading and gridline color
  1201. $data .= pack("V", $rgbHdr);
  1202. } elseif ($this->_BIFF_version == 0x0600) {
  1203. $rgbHdr = 0x0040; // Row/column heading and gridline color index
  1204. $zoom_factor_page_break = 0x0000;
  1205. $zoom_factor_normal = 0x0000;
  1206. $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
  1207. }
  1208. $this->_append($header.$data);
  1209. }
  1210. /**
  1211. * Write BIFF record DEFAULTROWHEIGHT.
  1212. *
  1213. * @access private
  1214. */
  1215. private function _storeDefaultRowHeight()
  1216. {
  1217. $defaultRowHeight = $this->_phpSheet->getDefaultRowDimension()->getRowHeight();
  1218. if ($defaultRowHeight < 0) {
  1219. return;
  1220. }
  1221. // convert to twips
  1222. $defaultRowHeight = (int) 20 * $defaultRowHeight;
  1223. $record = 0x0225; // Record identifier
  1224. $length = 0x0004; // Number of bytes to follow
  1225. $header = pack("vv", $record, $length);
  1226. $data = pack("vv", 1, $defaultRowHeight);
  1227. $this->_append($header . $data);
  1228. }
  1229. /**
  1230. * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
  1231. *
  1232. * @access private
  1233. */
  1234. function _storeDefcol()
  1235. {
  1236. $defaultColWidth = 8;
  1237. $record = 0x0055; // Record identifier
  1238. $length = 0x0002; // Number of bytes to follow
  1239. $header = pack("vv", $record, $length);
  1240. $data = pack("v", $defaultColWidth);
  1241. $this->_append($header . $data);
  1242. }
  1243. /**
  1244. * Write BIFF record COLINFO to define column widths
  1245. *
  1246. * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
  1247. * length record.
  1248. *
  1249. * @access private
  1250. * @param array $col_array This is the only parameter received and is composed of the following:
  1251. * 0 => First formatted column,
  1252. * 1 => Last formatted column,
  1253. * 2 => Col width (8.43 is Excel default),
  1254. * 3 => The optional XF format of the column,
  1255. * 4 => Option flags.
  1256. * 5 => Optional outline level
  1257. */
  1258. function _storeColinfo($col_array)
  1259. {
  1260. if (isset($col_array[0])) {
  1261. $colFirst = $col_array[0];
  1262. }
  1263. if (isset($col_array[1])) {
  1264. $colLast = $col_array[1];
  1265. }
  1266. if (isset($col_array[2])) {
  1267. $coldx = $col_array[2];
  1268. } else {
  1269. $coldx = 8.43;
  1270. }
  1271. if (isset($col_array[3])) {
  1272. $xfIndex = $col_array[3];
  1273. } else {
  1274. $xfIndex = 15;
  1275. }
  1276. if (isset($col_array[4])) {
  1277. $grbit = $col_array[4];
  1278. } else {
  1279. $grbit = 0;
  1280. }
  1281. if (isset($col_array[5])) {
  1282. $level = $col_array[5];
  1283. } else {
  1284. $level = 0;
  1285. }
  1286. $record = 0x007D; // Record identifier
  1287. $length = 0x000B; // Number of bytes to follow
  1288. $coldx *= 256; // Convert to units of 1/256 of a char
  1289. $ixfe = $xfIndex;
  1290. $reserved = 0x00; // Reserved
  1291. $level = max(0, min($level, 7));
  1292. $grbit |= $level << 8;
  1293. $header = pack("vv", $record, $length);
  1294. $data = pack("vvvvvC", $colFirst, $colLast, $coldx,
  1295. $ixfe, $grbit, $reserved);
  1296. $this->_append($header.$data);
  1297. }
  1298. /**
  1299. * Write BIFF record SELECTION.
  1300. *
  1301. * @access private
  1302. * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast)
  1303. * @see setSelection()
  1304. */
  1305. function _storeSelection($array)
  1306. {
  1307. list($rwFirst,$colFirst,$rwLast,$colLast) = $array;
  1308. $record = 0x001D; // Record identifier
  1309. $length = 0x000F; // Number of bytes to follow
  1310. $pnn = $this->_active_pane; // Pane position
  1311. $rwAct = $rwFirst; // Active row
  1312. $colAct = $colFirst; // Active column
  1313. $irefAct = 0; // Active cell ref
  1314. $cref = 1; // Number of refs
  1315. if (!isset($rwLast)) {
  1316. $rwLast = $rwFirst; // Last row in reference
  1317. }
  1318. if (!isset($colLast)) {
  1319. $colLast = $colFirst; // Last col in reference
  1320. }
  1321. // Swap last row/col for first row/col as necessary
  1322. if ($rwFirst > $rwLast) {
  1323. list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
  1324. }
  1325. if ($colFirst > $colLast) {
  1326. list($colFirst, $colLast) = array($colLast, $colFirst);
  1327. }
  1328. $header = pack("vv", $record, $length);
  1329. $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
  1330. $irefAct, $cref,
  1331. $rwFirst, $rwLast,
  1332. $colFirst, $colLast);
  1333. $this->_append($header . $data);
  1334. }
  1335. /**
  1336. * Store the MERGEDCELLS records for all ranges of merged cells
  1337. *
  1338. * @access private
  1339. */
  1340. function _storeMergedCells()
  1341. {
  1342. $mergeCells = $this->_phpSheet->getMergeCells();
  1343. $countMergeCells = count($mergeCells);
  1344. if ($countMergeCells == 0) {
  1345. return;
  1346. }
  1347. // maximum allowed number of merged cells per record
  1348. if ($this->_BIFF_version == 0x0600) {
  1349. $maxCountMergeCellsPerRecord = 1027;
  1350. } else {
  1351. $maxCountMergeCellsPerRecord = 259;
  1352. }
  1353. // record identifier
  1354. $record = 0x00E5;
  1355. // counter for total number of merged cells treated so far by the writer
  1356. $i = 0;
  1357. // counter for number of merged cells written in record currently being written
  1358. $j = 0;
  1359. // initialize record data
  1360. $recordData = '';
  1361. // loop through the merged cells
  1362. foreach ($mergeCells as $mergeCell) {
  1363. ++$i;
  1364. ++$j;
  1365. // extract the row and column indexes
  1366. $range = PHPExcel_Cell::splitRange($mergeCell);
  1367. list($first, $last) = $range[0];
  1368. list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first);
  1369. list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last);
  1370. $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1);
  1371. // flush record if we have reached limit for number of merged cells, or reached final merged cell
  1372. if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
  1373. $recordData = pack('v', $j) . $recordData;
  1374. $length = strlen($recordData);
  1375. $header = pack('vv', $record, $length);
  1376. $this->_append($header . $recordData);
  1377. // initialize for next record, if any
  1378. $recordData = '';
  1379. $j = 0;
  1380. }
  1381. }
  1382. }
  1383. /**
  1384. * Write SHEETLAYOUT record
  1385. */
  1386. private function _storeSheetLayout()
  1387. {
  1388. if (!$this->_phpSheet->isTabColorSet()) {
  1389. return;
  1390. }
  1391. $recordData = pack(
  1392. 'vvVVVvv'
  1393. , 0x0862
  1394. , 0x0000 // unused
  1395. , 0x00000000 // unused
  1396. , 0x00000000 // unused
  1397. , 0x00000014 // size of record data
  1398. , $this->_colors[$this->_phpSheet->getTabColor()->getRGB()] // color index
  1399. , 0x0000 // unused
  1400. );
  1401. $length = strlen($recordData);
  1402. $record = 0x0862; // Record identifier
  1403. $header = pack('vv', $record, $length);
  1404. $this->_append($header . $recordData);
  1405. }
  1406. /**
  1407. * Write BIFF record RANGEPROTECTION
  1408. *
  1409. * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
  1410. * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
  1411. */
  1412. private function _storeRangeProtection()
  1413. {
  1414. foreach ($this->_phpSheet->getProtectedCells() as $range => $password) {
  1415. // number of ranges, e.g. 'A1:B3 C20:D25'
  1416. $cellRanges = explode(' ', $range);
  1417. $cref = count($cellRanges);
  1418. $recordData = pack(
  1419. 'vvVVvCVvVv',
  1420. 0x0868,
  1421. 0x00,
  1422. 0x0000,
  1423. 0x0000,
  1424. 0x02,
  1425. 0x0,
  1426. 0x0000,
  1427. $cref,
  1428. 0x0000,
  1429. 0x00
  1430. );
  1431. foreach ($cellRanges as $cellRange) {
  1432. $recordData .= $this->_writeBIFF8CellRangeAddressFixed($cellRange);
  1433. }
  1434. // the rgbFeat structure
  1435. $recordData .= pack(
  1436. 'VV',
  1437. 0x0000,
  1438. hexdec($password)
  1439. );
  1440. $recordData .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
  1441. $length = strlen($recordData);
  1442. $record = 0x0868; // Record identifier
  1443. $header = pack("vv", $record, $length);
  1444. $this->_append($header . $recordData);
  1445. }
  1446. }
  1447. /**
  1448. * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  1449. * references in a worksheet.
  1450. *
  1451. * Excel only stores references to external sheets that are used in formulas.
  1452. * For simplicity we store references to all the sheets in the workbook
  1453. * regardless of whether they are used or not. This reduces the overall
  1454. * complexity and eliminates the need for a two way dialogue between the formula
  1455. * parser the worksheet objects.
  1456. *
  1457. * @access private
  1458. * @param integer $count The number of external sheet references in this worksheet
  1459. */
  1460. function _storeExterncount($count)
  1461. {
  1462. $record = 0x0016; // Record identifier
  1463. $length = 0x0002; // Number of bytes to follow
  1464. $header = pack("vv", $record, $length);
  1465. $data = pack("v", $count);
  1466. $this->_append($header . $data);
  1467. }
  1468. /**
  1469. * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  1470. * formulas. A formula references a sheet name via an index. Since we store a
  1471. * reference to all of the external worksheets the EXTERNSHEET index is the same
  1472. * as the worksheet index.
  1473. *
  1474. * @access private
  1475. * @param string $sheetname The name of a external worksheet
  1476. */
  1477. function _storeExternsheet($sheetname)
  1478. {
  1479. $record = 0x0017; // Record identifier
  1480. // References to the current sheet are encoded differently to references to
  1481. // external sheets.
  1482. //
  1483. if ($this->_phpSheet->getTitle() == $sheetname) {
  1484. $sheetname = '';
  1485. $length = 0x02; // The following 2 bytes
  1486. $cch = 1; // The following byte
  1487. $rgch = 0x02; // Self reference
  1488. } else {
  1489. $length = 0x02 + strlen($sheetname);
  1490. $cch = strlen($sheetname);
  1491. $rgch = 0x03; // Reference to a sheet in the current workbook
  1492. }
  1493. $header = pack("vv", $record, $length);
  1494. $data = pack("CC", $cch, $rgch);
  1495. $this->_append($header . $data . $sheetname);
  1496. }
  1497. /**
  1498. * Writes the Excel BIFF PANE record.
  1499. * The panes can either be frozen or thawed (unfrozen).
  1500. * Frozen panes are specified in terms of an integer number of rows and columns.
  1501. * Thawed panes are specified in terms of Excel's units for rows and columns.
  1502. *
  1503. * @access private
  1504. */
  1505. function _storePanes()
  1506. {
  1507. $panes = array();
  1508. if ($freezePane = $this->_phpSheet->getFreezePane()) {
  1509. list($column, $row) = PHPExcel_Cell::coordinateFromString($freezePane);
  1510. $panes[0] = $row - 1;
  1511. $panes[1] = PHPExcel_Cell::columnIndexFromString($column) - 1;
  1512. } else {
  1513. // thaw panes
  1514. return;
  1515. }
  1516. $y = isset($panes[0]) ? $panes[0] : null;
  1517. $x = isset($panes[1]) ? $panes[1] : null;
  1518. $rwTop = isset($panes[2]) ? $panes[2] : null;
  1519. $colLeft = isset($panes[3]) ? $panes[3] : null;
  1520. if (count($panes) > 4) { // if Active pane was received
  1521. $pnnAct = $panes[4];
  1522. } else {
  1523. $pnnAct = null;
  1524. }
  1525. $record = 0x0041; // Record identifier
  1526. $length = 0x000A; // Number of bytes to follow
  1527. // Code specific to frozen or thawed panes.
  1528. if ($this->_phpSheet->getFreezePane()) {
  1529. // Set default values for $rwTop and $colLeft
  1530. if (!isset($rwTop)) {
  1531. $rwTop = $y;
  1532. }
  1533. if (!isset($colLeft)) {
  1534. $colLeft = $x;
  1535. }
  1536. } else {
  1537. // Set default values for $rwTop and $colLeft
  1538. if (!isset($rwTop)) {
  1539. $rwTop = 0;
  1540. }
  1541. if (!isset($colLeft)) {
  1542. $colLeft = 0;
  1543. }
  1544. // Convert Excel's row and column units to the internal units.
  1545. // The default row height is 12.75
  1546. // The default column width is 8.43
  1547. // The following slope and intersection values were interpolated.
  1548. //
  1549. $y = 20*$y + 255;
  1550. $x = 113.879*$x + 390;
  1551. }
  1552. // Determine which pane should be active. There is also the undocumented
  1553. // option to override this should it be necessary: may be removed later.
  1554. //
  1555. if (!isset($pnnAct)) {
  1556. if ($x != 0 && $y != 0) {
  1557. $pnnAct = 0; // Bottom right
  1558. }
  1559. if ($x != 0 && $y == 0) {
  1560. $pnnAct = 1; // Top right
  1561. }
  1562. if ($x == 0 && $y != 0) {
  1563. $pnnAct = 2; // Bottom left
  1564. }
  1565. if ($x == 0 && $y == 0) {
  1566. $pnnAct = 3; // Top left
  1567. }
  1568. }
  1569. $this->_active_pane = $pnnAct; // Used in _storeSelection
  1570. $header = pack("vv", $record, $length);
  1571. $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
  1572. $this->_append($header . $data);
  1573. }
  1574. /**
  1575. * Store the page setup SETUP BIFF record.
  1576. *
  1577. * @access private
  1578. */
  1579. function _storeSetup()
  1580. {
  1581. $record = 0x00A1; // Record identifier
  1582. $length = 0x0022; // Number of bytes to follow
  1583. $iPaperSize = $this->_phpSheet->getPageSetup()->getPaperSize(); // Paper size
  1584. $iScale = $this->_phpSheet->getPageSetup()->getScale() ?
  1585. $this->_phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
  1586. $iPageStart = 0x01; // Starting page number
  1587. $iFitWidth = (int) $this->_phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
  1588. $iFitHeight = (int) $this->_phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
  1589. $grbit = 0x00; // Option flags
  1590. $iRes = 0x0258; // Print resolution
  1591. $iVRes = 0x0258; // Vertical print resolution
  1592. $numHdr = $this->_phpSheet->getPageMargins()->getHeader(); // Header Margin
  1593. $numFtr = $this->_phpSheet->getPageMargins()->getFooter(); // Footer Margin
  1594. $iCopies = 0x01; // Number of copies
  1595. $fLeftToRight = 0x0; // Print over then down
  1596. // Page orientation
  1597. $fLandscape = ($this->_phpSheet->getPageSetup()->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ?
  1598. 0x0 : 0x1;
  1599. $fNoPls = 0x0; // Setup not read from printer
  1600. $fNoColor = 0x0; // Print black and white
  1601. $fDraft = 0x0; // Print draft quality
  1602. $fNotes = 0x0; // Print notes
  1603. $fNoOrient = 0x0; // Orientation not set
  1604. $fUsePage = 0x0; // Use custom starting page
  1605. $grbit = $fLeftToRight;
  1606. $grbit |= $fLandscape << 1;
  1607. $grbit |= $fNoPls << 2;
  1608. $grbit |= $fNoColor << 3;
  1609. $grbit |= $fDraft << 4;
  1610. $grbit |= $fNotes << 5;
  1611. $grbit |= $fNoOrient << 6;
  1612. $grbit |= $fUsePage << 7;
  1613. $numHdr = pack("d", $numHdr);
  1614. $numFtr = pack("d", $numFtr);
  1615. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1616. $numHdr = strrev($numHdr);
  1617. $numFtr = strrev($numFtr);
  1618. }
  1619. $header = pack("vv", $record, $length);
  1620. $data1 = pack("vvvvvvvv", $iPaperSize,
  1621. $iScale,
  1622. $iPageStart,
  1623. $iFitWidth,
  1624. $iFitHeight,
  1625. $grbit,
  1626. $iRes,
  1627. $iVRes);
  1628. $data2 = $numHdr.$numFtr;
  1629. $data3 = pack("v", $iCopies);
  1630. $this->_append($header . $data1 . $data2 . $data3);
  1631. }
  1632. /**
  1633. * Store the header caption BIFF record.
  1634. *
  1635. * @access private
  1636. */
  1637. function _storeHeader()
  1638. {
  1639. $record = 0x0014; // Record identifier
  1640. /* removing for now
  1641. // need to fix character count (multibyte!)
  1642. if (strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
  1643. $str = $this->_phpSheet->getHeaderFooter()->getOddHeader(); // header string
  1644. } else {
  1645. $str = '';
  1646. }
  1647. */
  1648. if ($this->_BIFF_version == 0x0600) {
  1649. $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddHeader());
  1650. $length = strlen($recordData);
  1651. } else {
  1652. $cch = strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()); // Length of header string
  1653. $length = 1 + $cch; // Bytes to follow
  1654. $data = pack("C", $cch);
  1655. $recordData = $data . $this->_phpSheet->getHeaderFooter()->getOddHeader();
  1656. }
  1657. $header = pack("vv", $record, $length);
  1658. $this->_append($header . $recordData);
  1659. }
  1660. /**
  1661. * Store the footer caption BIFF record.
  1662. *
  1663. * @access private
  1664. */
  1665. function _storeFooter()
  1666. {
  1667. $record = 0x0015; // Record identifier
  1668. /* removing for now
  1669. // need to fix character count (multibyte!)
  1670. if (strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
  1671. $str = $this->_phpSheet->getHeaderFooter()->getOddFooter();
  1672. } else {
  1673. $str = '';
  1674. }
  1675. */
  1676. if ($this->_BIFF_version == 0x0600) {
  1677. $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddFooter());
  1678. $length = strlen($recordData);
  1679. } else {
  1680. $cch = strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()); // Length of footer string
  1681. $length = 1 + $cch;
  1682. $data = pack("C", $cch);
  1683. $recordData = $data . $this->_phpSheet->getHeaderFooter()->getOddFooter();
  1684. }
  1685. $header = pack("vv", $record, $length);
  1686. $this->_append($header . $recordData);
  1687. }
  1688. /**
  1689. * Store the horizontal centering HCENTER BIFF record.
  1690. *
  1691. * @access private
  1692. */
  1693. function _storeHcenter()
  1694. {
  1695. $record = 0x0083; // Record identifier
  1696. $length = 0x0002; // Bytes to follow
  1697. $fHCenter = $this->_phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
  1698. $header = pack("vv", $record, $length);
  1699. $data = pack("v", $fHCenter);
  1700. $this->_append($header.$data);
  1701. }
  1702. /**
  1703. * Store the vertical centering VCENTER BIFF record.
  1704. *
  1705. * @access private
  1706. */
  1707. function _storeVcenter()
  1708. {
  1709. $record = 0x0084; // Record identifier
  1710. $length = 0x0002; // Bytes to follow
  1711. $fVCenter = $this->_phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
  1712. $header = pack("vv", $record, $length);
  1713. $data = pack("v", $fVCenter);
  1714. $this->_append($header . $data);
  1715. }
  1716. /**
  1717. * Store the LEFTMARGIN BIFF record.
  1718. *
  1719. * @access private
  1720. */
  1721. function _storeMarginLeft()
  1722. {
  1723. $record = 0x0026; // Record identifier
  1724. $length = 0x0008; // Bytes to follow
  1725. $margin = $this->_phpSheet->getPageMargins()->getLeft(); // Margin in inches
  1726. $header = pack("vv", $record, $length);
  1727. $data = pack("d", $margin);
  1728. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1729. $data = strrev($data);
  1730. }
  1731. $this->_append($header . $data);
  1732. }
  1733. /**
  1734. * Store the RIGHTMARGIN BIFF record.
  1735. *
  1736. * @access private
  1737. */
  1738. function _storeMarginRight()
  1739. {
  1740. $record = 0x0027; // Record identifier
  1741. $length = 0x0008; // Bytes to follow
  1742. $margin = $this->_phpSheet->getPageMargins()->getRight(); // Margin in inches
  1743. $header = pack("vv", $record, $length);
  1744. $data = pack("d", $margin);
  1745. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1746. $data = strrev($data);
  1747. }
  1748. $this->_append($header . $data);
  1749. }
  1750. /**
  1751. * Store the TOPMARGIN BIFF record.
  1752. *
  1753. * @access private
  1754. */
  1755. function _storeMarginTop()
  1756. {
  1757. $record = 0x0028; // Record identifier
  1758. $length = 0x0008; // Bytes to follow
  1759. $margin = $this->_phpSheet->getPageMargins()->getTop(); // Margin in inches
  1760. $header = pack("vv", $record, $length);
  1761. $data = pack("d", $margin);
  1762. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1763. $data = strrev($data);
  1764. }
  1765. $this->_append($header . $data);
  1766. }
  1767. /**
  1768. * Store the BOTTOMMARGIN BIFF record.
  1769. *
  1770. * @access private
  1771. */
  1772. function _storeMarginBottom()
  1773. {
  1774. $record = 0x0029; // Record identifier
  1775. $length = 0x0008; // Bytes to follow
  1776. $margin = $this->_phpSheet->getPageMargins()->getBottom(); // Margin in inches
  1777. $header = pack("vv", $record, $length);
  1778. $data = pack("d", $margin);
  1779. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1780. $data = strrev($data);
  1781. }
  1782. $this->_append($header . $data);
  1783. }
  1784. /**
  1785. * Write the PRINTHEADERS BIFF record.
  1786. *
  1787. * @access private
  1788. */
  1789. function _storePrintHeaders()
  1790. {
  1791. $record = 0x002a; // Record identifier
  1792. $length = 0x0002; // Bytes to follow
  1793. $fPrintRwCol = $this->_print_headers; // Boolean flag
  1794. $header = pack("vv", $record, $length);
  1795. $data = pack("v", $fPrintRwCol);
  1796. $this->_append($header . $data);
  1797. }
  1798. /**
  1799. * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
  1800. * GRIDSET record.
  1801. *
  1802. * @access private
  1803. */
  1804. function _storePrintGridlines()
  1805. {
  1806. $record = 0x002b; // Record identifier
  1807. $length = 0x0002; // Bytes to follow
  1808. $fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
  1809. $header = pack("vv", $record, $length);
  1810. $data = pack("v", $fPrintGrid);
  1811. $this->_append($header . $data);
  1812. }
  1813. /**
  1814. * Write the GRIDSET BIFF record. Must be used in conjunction with the
  1815. * PRINTGRIDLINES record.
  1816. *
  1817. * @access private
  1818. */
  1819. function _storeGridset()
  1820. {
  1821. $record = 0x0082; // Record identifier
  1822. $length = 0x0002; // Bytes to follow
  1823. $fGridSet = !$this->_phpSheet->getPrintGridlines(); // Boolean flag
  1824. $header = pack("vv", $record, $length);
  1825. $data = pack("v", $fGridSet);
  1826. $this->_append($header . $data);
  1827. }
  1828. /**
  1829. * Write the GUTS BIFF record. This is used to configure the gutter margins
  1830. * where Excel outline symbols are displayed. The visibility of the gutters is
  1831. * controlled by a flag in WSBOOL.
  1832. *
  1833. * @see _storeWsbool()
  1834. * @access private
  1835. */
  1836. function _storeGuts()
  1837. {
  1838. $record = 0x0080; // Record identifier
  1839. $length = 0x0008; // Bytes to follow
  1840. $dxRwGut = 0x0000; // Size of row gutter
  1841. $dxColGut = 0x0000; // Size of col gutter
  1842. // determine maximum row outline level
  1843. $maxRowOutlineLevel = 0;
  1844. foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) {
  1845. $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
  1846. }
  1847. $col_level = 0;
  1848. // Calculate the maximum column outline level. The equivalent calculation
  1849. // for the row outline level is carried out in _setRow().
  1850. $colcount = count($this->_colinfo);
  1851. for ($i = 0; $i < $colcount; ++$i) {
  1852. $col_level = max($this->_colinfo[$i][5], $col_level);
  1853. }
  1854. // Set the limits for the outline levels (0 <= x <= 7).
  1855. $col_level = max(0, min($col_level, 7));
  1856. // The displayed level is one greater than the max outline levels
  1857. if ($maxRowOutlineLevel) {
  1858. ++$maxRowOutlineLevel;
  1859. }
  1860. if ($col_level) {
  1861. ++$col_level;
  1862. }
  1863. $header = pack("vv", $record, $length);
  1864. $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
  1865. $this->_append($header.$data);
  1866. }
  1867. /**
  1868. * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
  1869. * with the SETUP record.
  1870. *
  1871. * @access private
  1872. */
  1873. function _storeWsbool()
  1874. {
  1875. $record = 0x0081; // Record identifier
  1876. $length = 0x0002; // Bytes to follow
  1877. $grbit = 0x0000;
  1878. // The only option that is of interest is the flag for fit to page. So we
  1879. // set all the options in one go.
  1880. //
  1881. // Set the option flags
  1882. $grbit |= 0x0001; // Auto page breaks visible
  1883. if ($this->_outline_style) {
  1884. $grbit |= 0x0020; // Auto outline styles
  1885. }
  1886. if ($this->_phpSheet->getShowSummaryBelow()) {
  1887. $grbit |= 0x0040; // Outline summary below
  1888. }
  1889. if ($this->_phpSheet->getShowSummaryRight()) {
  1890. $grbit |= 0x0080; // Outline summary right
  1891. }
  1892. if ($this->_phpSheet->getPageSetup()->getFitToPage()) {
  1893. $grbit |= 0x0100; // Page setup fit to page
  1894. }
  1895. if ($this->_outline_on) {
  1896. $grbit |= 0x0400; // Outline symbols displayed
  1897. }
  1898. $header = pack("vv", $record, $length);
  1899. $data = pack("v", $grbit);
  1900. $this->_append($header . $data);
  1901. }
  1902. /**
  1903. * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
  1904. */
  1905. private function _storeBreaks()
  1906. {
  1907. // initialize
  1908. $vbreaks = array();
  1909. $hbreaks = array();
  1910. foreach ($this->_phpSheet->getBreaks() as $cell => $breakType) {
  1911. // Fetch coordinates
  1912. $coordinates = PHPExcel_Cell::coordinateFromString($cell);
  1913. // Decide what to do by the type of break
  1914. switch ($breakType) {
  1915. case PHPExcel_Worksheet::BREAK_COLUMN:
  1916. // Add to list of vertical breaks
  1917. $vbreaks[] = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1;
  1918. break;
  1919. case PHPExcel_Worksheet::BREAK_ROW:
  1920. // Add to list of horizontal breaks
  1921. $hbreaks[] = $coordinates[1];
  1922. break;
  1923. case PHPExcel_Worksheet::BREAK_NONE:
  1924. default:
  1925. // Nothing to do
  1926. break;
  1927. }
  1928. }
  1929. //horizontal page breaks
  1930. if (count($hbreaks) > 0) {
  1931. // Sort and filter array of page breaks
  1932. sort($hbreaks, SORT_NUMERIC);
  1933. if ($hbreaks[0] == 0) { // don't use first break if it's 0
  1934. array_shift($hbreaks);
  1935. }
  1936. $record = 0x001b; // Record identifier
  1937. $cbrk = count($hbreaks); // Number of page breaks
  1938. if ($this->_BIFF_version == 0x0600) {
  1939. $length = 2 + 6 * $cbrk; // Bytes to follow
  1940. } else {
  1941. $length = 2 + 2 * $cbrk; // Bytes to follow
  1942. }
  1943. $header = pack("vv", $record, $length);
  1944. $data = pack("v", $cbrk);
  1945. // Append each page break
  1946. foreach ($hbreaks as $hbreak) {
  1947. if ($this->_BIFF_version == 0x0600) {
  1948. $data .= pack("vvv", $hbreak, 0x0000, 0x00ff);
  1949. } else {
  1950. $data .= pack("v", $hbreak);
  1951. }
  1952. }
  1953. $this->_append($header . $data);
  1954. }
  1955. // vertical page breaks
  1956. if (count($vbreaks) > 0) {
  1957. // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
  1958. // It is slightly higher in Excel 97/200, approx. 1026
  1959. $vbreaks = array_slice($vbreaks, 0, 1000);
  1960. // Sort and filter array of page breaks
  1961. sort($vbreaks, SORT_NUMERIC);
  1962. if ($vbreaks[0] == 0) { // don't use first break if it's 0
  1963. array_shift($vbreaks);
  1964. }
  1965. $record = 0x001a; // Record identifier
  1966. $cbrk = count($vbreaks); // Number of page breaks
  1967. if ($this->_BIFF_version == 0x0600) {
  1968. $length = 2 + 6 * $cbrk; // Bytes to follow
  1969. } else {
  1970. $length = 2 + 2 * $cbrk; // Bytes to follow
  1971. }
  1972. $header = pack("vv", $record, $length);
  1973. $data = pack("v", $cbrk);
  1974. // Append each page break
  1975. foreach ($vbreaks as $vbreak) {
  1976. if ($this->_BIFF_version == 0x0600) {
  1977. $data .= pack("vvv", $vbreak, 0x0000, 0xffff);
  1978. } else {
  1979. $data .= pack("v", $vbreak);
  1980. }
  1981. }
  1982. $this->_append($header . $data);
  1983. }
  1984. }
  1985. /**
  1986. * Set the Biff PROTECT record to indicate that the worksheet is protected.
  1987. *
  1988. * @access private
  1989. */
  1990. function _storeProtect()
  1991. {
  1992. // Exit unless sheet protection has been specified
  1993. if (!$this->_phpSheet->getProtection()->getSheet()) {
  1994. return;
  1995. }
  1996. $record = 0x0012; // Record identifier
  1997. $length = 0x0002; // Bytes to follow
  1998. $fLock = 1; // Worksheet is protected
  1999. $header = pack("vv", $record, $length);
  2000. $data = pack("v", $fLock);
  2001. $this->_append($header.$data);
  2002. }
  2003. /**
  2004. * Write the worksheet PASSWORD record.
  2005. *
  2006. * @access private
  2007. */
  2008. function _storePassword()
  2009. {
  2010. // Exit unless sheet protection and password have been specified
  2011. if (!$this->_phpSheet->getProtection()->getSheet() || !$this->_phpSheet->getProtection()->getPassword()) {
  2012. return;
  2013. }
  2014. $record = 0x0013; // Record identifier
  2015. $length = 0x0002; // Bytes to follow
  2016. $wPassword = hexdec($this->_phpSheet->getProtection()->getPassword()); // Encoded password
  2017. $header = pack("vv", $record, $length);
  2018. $data = pack("v", $wPassword);
  2019. $this->_append($header . $data);
  2020. }
  2021. /**
  2022. * Insert a 24bit bitmap image in a worksheet.
  2023. *
  2024. * @access public
  2025. * @param integer $row The row we are going to insert the bitmap into
  2026. * @param integer $col The column we are going to insert the bitmap into
  2027. * @param mixed $bitmap The bitmap filename or GD-image resource
  2028. * @param integer $x The horizontal position (offset) of the image inside the cell.
  2029. * @param integer $y The vertical position (offset) of the image inside the cell.
  2030. * @param float $scale_x The horizontal scale
  2031. * @param float $scale_y The vertical scale
  2032. */
  2033. function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
  2034. {
  2035. $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
  2036. list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
  2037. // Scale the frame of the image.
  2038. $width *= $scale_x;
  2039. $height *= $scale_y;
  2040. // Calculate the vertices of the image and write the OBJ record
  2041. $this->_positionImage($col, $row, $x, $y, $width, $height);
  2042. // Write the IMDATA record to store the bitmap data
  2043. $record = 0x007f;
  2044. $length = 8 + $size;
  2045. $cf = 0x09;
  2046. $env = 0x01;
  2047. $lcb = $size;
  2048. $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
  2049. $this->_append($header.$data);
  2050. }
  2051. /**
  2052. * Calculate the vertices that define the position of the image as required by
  2053. * the OBJ record.
  2054. *
  2055. * +------------+------------+
  2056. * | A | B |
  2057. * +-----+------------+------------+
  2058. * | |(x1,y1) | |
  2059. * | 1 |(A1)._______|______ |
  2060. * | | | | |
  2061. * | | | | |
  2062. * +-----+----| BITMAP |-----+
  2063. * | | | | |
  2064. * | 2 | |______________. |
  2065. * | | | (B2)|
  2066. * | | | (x2,y2)|
  2067. * +---- +------------+------------+
  2068. *
  2069. * Example of a bitmap that covers some of the area from cell A1 to cell B2.
  2070. *
  2071. * Based on the width and height of the bitmap we need to calculate 8 vars:
  2072. * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
  2073. * The width and height of the cells are also variable and have to be taken into
  2074. * account.
  2075. * The values of $col_start and $row_start are passed in from the calling
  2076. * function. The values of $col_end and $row_end are calculated by subtracting
  2077. * the width and height of the bitmap from the width and height of the
  2078. * underlying cells.
  2079. * The vertices are expressed as a percentage of the underlying cell width as
  2080. * follows (rhs values are in pixels):
  2081. *
  2082. * x1 = X / W *1024
  2083. * y1 = Y / H *256
  2084. * x2 = (X-1) / W *1024
  2085. * y2 = (Y-1) / H *256
  2086. *
  2087. * Where: X is distance from the left side of the underlying cell
  2088. * Y is distance from the top of the underlying cell
  2089. * W is the width of the cell
  2090. * H is the height of the cell
  2091. * The SDK incorrectly states that the height should be expressed as a
  2092. * percentage of 1024.
  2093. *
  2094. * @access private
  2095. * @param integer $col_start Col containing upper left corner of object
  2096. * @param integer $row_start Row containing top left corner of object
  2097. * @param integer $x1 Distance to left side of object
  2098. * @param integer $y1 Distance to top of object
  2099. * @param integer $width Width of image frame
  2100. * @param integer $height Height of image frame
  2101. */
  2102. function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
  2103. {
  2104. // Initialise end cell to the same as the start cell
  2105. $col_end = $col_start; // Col containing lower right corner of object
  2106. $row_end = $row_start; // Row containing bottom right corner of object
  2107. // Zero the specified offset if greater than the cell dimensions
  2108. if ($x1 >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) {
  2109. $x1 = 0;
  2110. }
  2111. if ($y1 >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1)) {
  2112. $y1 = 0;
  2113. }
  2114. $width = $width + $x1 -1;
  2115. $height = $height + $y1 -1;
  2116. // Subtract the underlying cell widths to find the end cell of the image
  2117. while ($width >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) {
  2118. $width -= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end));
  2119. ++$col_end;
  2120. }
  2121. // Subtract the underlying cell heights to find the end cell of the image
  2122. while ($height >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1)) {
  2123. $height -= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1);
  2124. ++$row_end;
  2125. }
  2126. // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
  2127. // with zero eight or width.
  2128. //
  2129. if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) {
  2130. return;
  2131. }
  2132. if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) {
  2133. return;
  2134. }
  2135. if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) == 0) {
  2136. return;
  2137. }
  2138. if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) == 0) {
  2139. return;
  2140. }
  2141. // Convert the pixel values to the percentage value expected by Excel
  2142. $x1 = $x1 / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024;
  2143. $y1 = $y1 / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) * 256;
  2144. $x2 = $width / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
  2145. $y2 = $height / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) * 256; // Distance to bottom of object
  2146. $this->_storeObjPicture($col_start, $x1,
  2147. $row_start, $y1,
  2148. $col_end, $x2,
  2149. $row_end, $y2);
  2150. }
  2151. /**
  2152. * Store the OBJ record that precedes an IMDATA record. This could be generalise
  2153. * to support other Excel objects.
  2154. *
  2155. * @access private
  2156. * @param integer $colL Column containing upper left corner of object
  2157. * @param integer $dxL Distance from left side of cell
  2158. * @param integer $rwT Row containing top left corner of object
  2159. * @param integer $dyT Distance from top of cell
  2160. * @param integer $colR Column containing lower right corner of object
  2161. * @param integer $dxR Distance from right of cell
  2162. * @param integer $rwB Row containing bottom right corner of object
  2163. * @param integer $dyB Distance from bottom of cell
  2164. */
  2165. function _storeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
  2166. {
  2167. $record = 0x005d; // Record identifier
  2168. $length = 0x003c; // Bytes to follow
  2169. $cObj = 0x0001; // Count of objects in file (set to 1)
  2170. $OT = 0x0008; // Object type. 8 = Picture
  2171. $id = 0x0001; // Object ID
  2172. $grbit = 0x0614; // Option flags
  2173. $cbMacro = 0x0000; // Length of FMLA structure
  2174. $Reserved1 = 0x0000; // Reserved
  2175. $Reserved2 = 0x0000; // Reserved
  2176. $icvBack = 0x09; // Background colour
  2177. $icvFore = 0x09; // Foreground colour
  2178. $fls = 0x00; // Fill pattern
  2179. $fAuto = 0x00; // Automatic fill
  2180. $icv = 0x08; // Line colour
  2181. $lns = 0xff; // Line style
  2182. $lnw = 0x01; // Line weight
  2183. $fAutoB = 0x00; // Automatic border
  2184. $frs = 0x0000; // Frame style
  2185. $cf = 0x0009; // Image format, 9 = bitmap
  2186. $Reserved3 = 0x0000; // Reserved
  2187. $cbPictFmla = 0x0000; // Length of FMLA structure
  2188. $Reserved4 = 0x0000; // Reserved
  2189. $grbit2 = 0x0001; // Option flags
  2190. $Reserved5 = 0x0000; // Reserved
  2191. $header = pack("vv", $record, $length);
  2192. $data = pack("V", $cObj);
  2193. $data .= pack("v", $OT);
  2194. $data .= pack("v", $id);
  2195. $data .= pack("v", $grbit);
  2196. $data .= pack("v", $colL);
  2197. $data .= pack("v", $dxL);
  2198. $data .= pack("v", $rwT);
  2199. $data .= pack("v", $dyT);
  2200. $data .= pack("v", $colR);
  2201. $data .= pack("v", $dxR);
  2202. $data .= pack("v", $rwB);
  2203. $data .= pack("v", $dyB);
  2204. $data .= pack("v", $cbMacro);
  2205. $data .= pack("V", $Reserved1);
  2206. $data .= pack("v", $Reserved2);
  2207. $data .= pack("C", $icvBack);
  2208. $data .= pack("C", $icvFore);
  2209. $data .= pack("C", $fls);
  2210. $data .= pack("C", $fAuto);
  2211. $data .= pack("C", $icv);
  2212. $data .= pack("C", $lns);
  2213. $data .= pack("C", $lnw);
  2214. $data .= pack("C", $fAutoB);
  2215. $data .= pack("v", $frs);
  2216. $data .= pack("V", $cf);
  2217. $data .= pack("v", $Reserved3);
  2218. $data .= pack("v", $cbPictFmla);
  2219. $data .= pack("v", $Reserved4);
  2220. $data .= pack("v", $grbit2);
  2221. $data .= pack("V", $Reserved5);
  2222. $this->_append($header . $data);
  2223. }
  2224. /**
  2225. * Convert a GD-image into the internal format.
  2226. *
  2227. * @access private
  2228. * @param resource $image The image to process
  2229. * @return array Array with data and properties of the bitmap
  2230. */
  2231. function _processBitmapGd($image) {
  2232. $width = imagesx($image);
  2233. $height = imagesy($image);
  2234. $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  2235. for ($j=$height; $j--; ) {
  2236. for ($i=0; $i < $width; ++$i) {
  2237. $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
  2238. foreach (array("red", "green", "blue") as $key) {
  2239. $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
  2240. }
  2241. $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
  2242. }
  2243. if (3*$width % 4) {
  2244. $data .= str_repeat("\x00", 4 - 3*$width % 4);
  2245. }
  2246. }
  2247. return array($width, $height, strlen($data), $data);
  2248. }
  2249. /**
  2250. * Convert a 24 bit bitmap into the modified internal format used by Windows.
  2251. * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
  2252. * MSDN library.
  2253. *
  2254. * @access private
  2255. * @param string $bitmap The bitmap to process
  2256. * @return array Array with data and properties of the bitmap
  2257. */
  2258. function _processBitmap($bitmap)
  2259. {
  2260. // Open file.
  2261. $bmp_fd = @fopen($bitmap,"rb");
  2262. if (!$bmp_fd) {
  2263. throw new Exception("Couldn't import $bitmap");
  2264. }
  2265. // Slurp the file into a string.
  2266. $data = fread($bmp_fd, filesize($bitmap));
  2267. // Check that the file is big enough to be a bitmap.
  2268. if (strlen($data) <= 0x36) {
  2269. throw new Exception("$bitmap doesn't contain enough data.\n");
  2270. }
  2271. // The first 2 bytes are used to identify the bitmap.
  2272. $identity = unpack("A2ident", $data);
  2273. if ($identity['ident'] != "BM") {
  2274. throw new Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
  2275. }
  2276. // Remove bitmap data: ID.
  2277. $data = substr($data, 2);
  2278. // Read and remove the bitmap size. This is more reliable than reading
  2279. // the data size at offset 0x22.
  2280. //
  2281. $size_array = unpack("Vsa", substr($data, 0, 4));
  2282. $size = $size_array['sa'];
  2283. $data = substr($data, 4);
  2284. $size -= 0x36; // Subtract size of bitmap header.
  2285. $size += 0x0C; // Add size of BIFF header.
  2286. // Remove bitmap data: reserved, offset, header length.
  2287. $data = substr($data, 12);
  2288. // Read and remove the bitmap width and height. Verify the sizes.
  2289. $width_and_height = unpack("V2", substr($data, 0, 8));
  2290. $width = $width_and_height[1];
  2291. $height = $width_and_height[2];
  2292. $data = substr($data, 8);
  2293. if ($width > 0xFFFF) {
  2294. throw new Exception("$bitmap: largest image width supported is 65k.\n");
  2295. }
  2296. if ($height > 0xFFFF) {
  2297. throw new Exception("$bitmap: largest image height supported is 65k.\n");
  2298. }
  2299. // Read and remove the bitmap planes and bpp data. Verify them.
  2300. $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
  2301. $data = substr($data, 4);
  2302. if ($planes_and_bitcount[2] != 24) { // Bitcount
  2303. throw new Exception("$bitmap isn't a 24bit true color bitmap.\n");
  2304. }
  2305. if ($planes_and_bitcount[1] != 1) {
  2306. throw new Exception("$bitmap: only 1 plane supported in bitmap image.\n");
  2307. }
  2308. // Read and remove the bitmap compression. Verify compression.
  2309. $compression = unpack("Vcomp", substr($data, 0, 4));
  2310. $data = substr($data, 4);
  2311. //$compression = 0;
  2312. if ($compression['comp'] != 0) {
  2313. throw new Exception("$bitmap: compression not supported in bitmap image.\n");
  2314. }
  2315. // Remove bitmap data: data size, hres, vres, colours, imp. colours.
  2316. $data = substr($data, 20);
  2317. // Add the BITMAPCOREHEADER data
  2318. $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  2319. $data = $header . $data;
  2320. return (array($width, $height, $size, $data));
  2321. }
  2322. /**
  2323. * Store the window zoom factor. This should be a reduced fraction but for
  2324. * simplicity we will store all fractions with a numerator of 100.
  2325. *
  2326. * @access private
  2327. */
  2328. function _storeZoom()
  2329. {
  2330. // If scale is 100 we don't need to write a record
  2331. if ($this->_phpSheet->getSheetView()->getZoomScale() == 100) {
  2332. return;
  2333. }
  2334. $record = 0x00A0; // Record identifier
  2335. $length = 0x0004; // Bytes to follow
  2336. $header = pack("vv", $record, $length);
  2337. $data = pack("vv", $this->_phpSheet->getSheetView()->getZoomScale(), 100);
  2338. $this->_append($header . $data);
  2339. }
  2340. /**
  2341. * Write MSODRAWING record
  2342. */
  2343. private function _storeMsoDrawing()
  2344. {
  2345. // check if there are any shapes for this sheet
  2346. if (count($this->_phpSheet->getDrawingCollection()) == 0) {
  2347. return;
  2348. }
  2349. // create intermediate Escher object
  2350. $escher = new PHPExcel_Shared_Escher();
  2351. // dgContainer
  2352. $dgContainer = new PHPExcel_Shared_Escher_DgContainer();
  2353. // set the drawing index (we use sheet index + 1)
  2354. $dgContainer->setDgId($this->_phpSheet->getParent()->getIndex($this->_phpSheet) + 1);
  2355. $escher->setDgContainer($dgContainer);
  2356. // spgrContainer
  2357. $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer();
  2358. $dgContainer->setSpgrContainer($spgrContainer);
  2359. // add one shape which is the group shape
  2360. $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
  2361. $spContainer->setSpgr(true);
  2362. $spContainer->setSpType(0);
  2363. $spContainer->setSpId(($this->_phpSheet->getParent()->getIndex($this->_phpSheet) + 1) << 10);
  2364. $spgrContainer->addChild($spContainer);
  2365. // add the shapes
  2366. // outer loop is for determining BSE index
  2367. $blipIndex = 0; // 1-based index to BstoreContainer
  2368. $countShapes = 0; // count number of shapes (minus group shape), in this sheet
  2369. foreach ($this->_phpSheet->getParent()->getAllsheets() as $sheet) {
  2370. foreach ($sheet->getDrawingCollection() as $drawing) {
  2371. ++$blipIndex;
  2372. if ($sheet === $this->_phpSheet) {
  2373. ++$countShapes;
  2374. // add the shape
  2375. $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
  2376. // set the shape type
  2377. $spContainer->setSpType(0x004B);
  2378. // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
  2379. $spId = $countShapes
  2380. | ($this->_phpSheet->getParent()->getIndex($this->_phpSheet) + 1) << 10;
  2381. $spContainer->setSpId($spId);
  2382. // keep track of last spId
  2383. $lastSpId = $spId;
  2384. // set the BLIP index
  2385. $spContainer->setOPT(0x4104, $blipIndex);
  2386. // set coordinates and offsets, client anchor
  2387. $coordinates = $drawing->getCoordinates();
  2388. $offsetX = $drawing->getOffsetX();
  2389. $offsetY = $drawing->getOffsetY();
  2390. $width = $drawing->getWidth();
  2391. $height = $drawing->getHeight();
  2392. $twoAnchor = PHPExcel_Shared_Excel5::oneAnchor2twoAnchor($this->_phpSheet, $coordinates, $offsetX, $offsetY, $width, $height);
  2393. $spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
  2394. $spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
  2395. $spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
  2396. $spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
  2397. $spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
  2398. $spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
  2399. $spgrContainer->addChild($spContainer);
  2400. }
  2401. }
  2402. }
  2403. // set last shape index
  2404. $dgContainer->setLastSpId($lastSpId);
  2405. // write the Escher stream
  2406. $writer = new PHPExcel_Writer_Excel5_Escher($escher);
  2407. $data = $writer->close();
  2408. $spOffsets = $writer->getSpOffsets();
  2409. // write the neccesary MSODRAWING, OBJ records
  2410. // split the Escher stream
  2411. $spOffsets[0] = 0;
  2412. $nm = count($spOffsets) - 1; // number of shapes excluding first shape
  2413. for ($i = 1; $i <= $nm; ++$i) {
  2414. // MSODRAWING record
  2415. $record = 0x00EC; // Record identifier
  2416. // chunk of Escher stream for one shape
  2417. $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);
  2418. $length = strlen($dataChunk);
  2419. $header = pack("vv", $record, $length);
  2420. $this->_append($header . $dataChunk);
  2421. // OBJ record
  2422. $record = 0x005D; // record identifier
  2423. $objData = '';
  2424. // ftCmo
  2425. $objData .=
  2426. pack('vvvvvVVV'
  2427. , 0x0015 // 0x0015 = ftCmo
  2428. , 0x0012 // length of ftCmo data
  2429. , 0x0008 // object type, 0x0008 = picture
  2430. , $i // object id number, Excel seems to use 1-based index, local for the sheet
  2431. , 0x6011 // option flags, 0x6011 is what OpenOffice.org uses
  2432. , 0 // reserved
  2433. , 0 // reserved
  2434. , 0 // reserved
  2435. );
  2436. // ftEnd
  2437. $objData .=
  2438. pack('vv'
  2439. , 0x0000 // 0x0000 = ftEnd
  2440. , 0x0000 // length of ftEnd data
  2441. );
  2442. $length = strlen($objData);
  2443. $header = pack('vv', $record, $length);
  2444. $this->_append($header . $objData);
  2445. }
  2446. }
  2447. /**
  2448. * Store the DVAL and DV records.
  2449. *
  2450. * @access private
  2451. */
  2452. function _storeDataValidity()
  2453. {
  2454. $record = 0x01b2; // Record identifier
  2455. $length = 0x0012; // Bytes to follow
  2456. $grbit = 0x0002; // Prompt box at cell, no cached validity data at DV records
  2457. $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
  2458. $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
  2459. $objId = 0xffffffff; // Object identifier of drop down arrow object, or -1 if not visible
  2460. $header = pack('vv', $record, $length);
  2461. $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
  2462. count($this->_dv));
  2463. $this->_append($header.$data);
  2464. $record = 0x01be; // Record identifier
  2465. foreach ($this->_dv as $dv) {
  2466. $length = strlen($dv); // Bytes to follow
  2467. $header = pack("vv", $record, $length);
  2468. $this->_append($header . $dv);
  2469. }
  2470. }
  2471. /**
  2472. * Map Error code
  2473. */
  2474. private function _mapErrorCode($errorCode) {
  2475. switch ($errorCode) {
  2476. case '#NULL!': return 0x00;
  2477. case '#DIV/0!': return 0x07;
  2478. case '#VALUE!': return 0x0F;
  2479. case '#REF!': return 0x17;
  2480. case '#NAME?': return 0x1D;
  2481. case '#NUM!': return 0x24;
  2482. case '#N/A': return 0x2A;
  2483. }
  2484. return 0;
  2485. }
  2486. }