PageRenderTime 78ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/PHPExcel_1.7.8-with_documentation-msoffice_format/PHPExcel_1.7.8-with_documentation-msoffice_format/Classes/PHPExcel/Writer/Excel5/Worksheet.php

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