PageRenderTime 30ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/include/PHPExcel/Writer/Excel5/Worksheet.php

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