PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/sleininger/stock_online
PHP | 2910 lines | 1560 code | 437 blank | 913 comment | 174 complexity | 214fed073a06f49247f10082342608ac MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2012 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Writer_Excel5
  23. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.7.7, 2012-05-19
  26. */
  27. // Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class):
  28. // -----------------------------------------------------------------------------------------
  29. // /*
  30. // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
  31. // *
  32. // * The majority of this is _NOT_ my code. I simply ported it from the
  33. // * PERL Spreadsheet::WriteExcel module.
  34. // *
  35. // * The author of the Spreadsheet::WriteExcel module is John McNamara
  36. // * <jmcnamara@cpan.org>
  37. // *
  38. // * I _DO_ maintain this code, and John McNamara has nothing to do with the
  39. // * porting of this code to PHP. Any questions directly related to this
  40. // * class library should be directed to me.
  41. // *
  42. // * License Information:
  43. // *
  44. // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
  45. // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
  46. // *
  47. // * This library is free software; you can redistribute it and/or
  48. // * modify it under the terms of the GNU Lesser General Public
  49. // * License as published by the Free Software Foundation; either
  50. // * version 2.1 of the License, or (at your option) any later version.
  51. // *
  52. // * This library is distributed in the hope that it will be useful,
  53. // * but WITHOUT ANY WARRANTY; without even the implied warranty of
  54. // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  55. // * Lesser General Public License for more details.
  56. // *
  57. // * You should have received a copy of the GNU Lesser General Public
  58. // * License along with this library; if not, write to the Free Software
  59. // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  60. // */
  61. /**
  62. * PHPExcel_Writer_Excel5_Worksheet
  63. *
  64. * @category PHPExcel
  65. * @package PHPExcel_Writer_Excel5
  66. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  67. */
  68. class PHPExcel_Writer_Excel5_Worksheet extends PHPExcel_Writer_Excel5_BIFFwriter
  69. {
  70. /**
  71. * Formula parser
  72. *
  73. * @var PHPExcel_Writer_Excel5_Parser
  74. */
  75. private $_parser;
  76. /**
  77. * Maximum number of characters for a string (LABEL record in BIFF5)
  78. * @var integer
  79. */
  80. public $_xls_strmax;
  81. /**
  82. * Array containing format information for columns
  83. * @var array
  84. */
  85. public $_colinfo;
  86. /**
  87. * Array containing the selected area for the worksheet
  88. * @var array
  89. */
  90. public $_selection;
  91. /**
  92. * The active pane for the worksheet
  93. * @var integer
  94. */
  95. public $_active_pane;
  96. /**
  97. * Whether to use outline.
  98. * @var integer
  99. */
  100. public $_outline_on;
  101. /**
  102. * Auto outline styles.
  103. * @var bool
  104. */
  105. public $_outline_style;
  106. /**
  107. * Whether to have outline summary below.
  108. * @var bool
  109. */
  110. public $_outline_below;
  111. /**
  112. * Whether to have outline summary at the right.
  113. * @var bool
  114. */
  115. public $_outline_right;
  116. /**
  117. * Reference to the total number of strings in the workbook
  118. * @var integer
  119. */
  120. public $_str_total;
  121. /**
  122. * Reference to the number of unique strings in the workbook
  123. * @var integer
  124. */
  125. public $_str_unique;
  126. /**
  127. * Reference to the array containing all the unique strings in the workbook
  128. * @var array
  129. */
  130. public $_str_table;
  131. /**
  132. * Color cache
  133. */
  134. private $_colors;
  135. /**
  136. * Index of first used row (at least 0)
  137. * @var int
  138. */
  139. private $_firstRowIndex;
  140. /**
  141. * Index of last used row. (no used rows means -1)
  142. * @var int
  143. */
  144. private $_lastRowIndex;
  145. /**
  146. * Index of first used column (at least 0)
  147. * @var int
  148. */
  149. private $_firstColumnIndex;
  150. /**
  151. * Index of last used column (no used columns means -1)
  152. * @var int
  153. */
  154. private $_lastColumnIndex;
  155. /**
  156. * Sheet object
  157. * @var PHPExcel_Worksheet
  158. */
  159. public $_phpSheet;
  160. /**
  161. * Count cell style Xfs
  162. *
  163. * @var int
  164. */
  165. private $_countCellStyleXfs;
  166. /**
  167. * Escher object corresponding to MSODRAWING
  168. *
  169. * @var PHPExcel_Shared_Escher
  170. */
  171. private $_escher;
  172. /**
  173. * Array of font hashes associated to FONT records index
  174. *
  175. * @var array
  176. */
  177. public $_fntHashIndex;
  178. /**
  179. * Constructor
  180. *
  181. * @param int &$str_total Total number of strings
  182. * @param int &$str_unique Total number of unique strings
  183. * @param array &$str_table String Table
  184. * @param array &$colors Colour Table
  185. * @param mixed $parser The formula parser created for the Workbook
  186. * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written
  187. * @param string $phpSheet The worksheet to write
  188. * @param PHPExcel_Worksheet $phpSheet
  189. */
  190. public function __construct(&$str_total, &$str_unique, &$str_table, &$colors,
  191. $parser, $preCalculateFormulas, $phpSheet)
  192. {
  193. // It needs to call its parent's constructor explicitly
  194. parent::__construct();
  195. // change BIFFwriter limit for CONTINUE records
  196. // $this->_limit = 8224;
  197. $this->_preCalculateFormulas = $preCalculateFormulas;
  198. $this->_str_total = &$str_total;
  199. $this->_str_unique = &$str_unique;
  200. $this->_str_table = &$str_table;
  201. $this->_colors = &$colors;
  202. $this->_parser = $parser;
  203. $this->_phpSheet = $phpSheet;
  204. //$this->ext_sheets = array();
  205. //$this->offset = 0;
  206. $this->_xls_strmax = 255;
  207. $this->_colinfo = array();
  208. $this->_selection = array(0,0,0,0);
  209. $this->_active_pane = 3;
  210. $this->_print_headers = 0;
  211. $this->_outline_style = 0;
  212. $this->_outline_below = 1;
  213. $this->_outline_right = 1;
  214. $this->_outline_on = 1;
  215. $this->_fntHashIndex = array();
  216. // calculate values for DIMENSIONS record
  217. $minR = 1;
  218. $minC = 'A';
  219. $maxR = $this->_phpSheet->getHighestRow();
  220. $maxC = $this->_phpSheet->getHighestColumn();
  221. // Determine lowest and highest column and row
  222. // $this->_firstRowIndex = ($minR > 65535) ? 65535 : $minR;
  223. $this->_lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ;
  224. $this->_firstColumnIndex = PHPExcel_Cell::columnIndexFromString($minC);
  225. $this->_lastColumnIndex = PHPExcel_Cell::columnIndexFromString($maxC);
  226. // if ($this->_firstColumnIndex > 255) $this->_firstColumnIndex = 255;
  227. if ($this->_lastColumnIndex > 255) $this->_lastColumnIndex = 255;
  228. $this->_countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
  229. }
  230. /**
  231. * Add data to the beginning of the workbook (note the reverse order)
  232. * and to the end of the workbook.
  233. *
  234. * @access public
  235. * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook()
  236. */
  237. function close()
  238. {
  239. $_phpSheet = $this->_phpSheet;
  240. $num_sheets = $_phpSheet->getParent()->getSheetCount();
  241. // Write BOF record
  242. $this->_storeBof(0x0010);
  243. // Write PRINTHEADERS
  244. $this->_writePrintHeaders();
  245. // Write PRINTGRIDLINES
  246. $this->_writePrintGridlines();
  247. // Write GRIDSET
  248. $this->_writeGridset();
  249. // Calculate column widths
  250. $_phpSheet->calculateColumnWidths();
  251. // Column dimensions
  252. if (($defaultWidth = $_phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
  253. $defaultWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($_phpSheet->getParent()->getDefaultStyle()->getFont());
  254. }
  255. $columnDimensions = $_phpSheet->getColumnDimensions();
  256. $maxCol = $this->_lastColumnIndex -1;
  257. for ($i = 0; $i <= $maxCol; ++$i) {
  258. $hidden = 0;
  259. $level = 0;
  260. $xfIndex = 15; // there are 15 cell style Xfs
  261. $width = $defaultWidth;
  262. $columnLetter = PHPExcel_Cell::stringFromColumnIndex($i);
  263. if (isset($columnDimensions[$columnLetter])) {
  264. $columnDimension = $columnDimensions[$columnLetter];
  265. if ($columnDimension->getWidth() >= 0) {
  266. $width = $columnDimension->getWidth();
  267. }
  268. $hidden = $columnDimension->getVisible() ? 0 : 1;
  269. $level = $columnDimension->getOutlineLevel();
  270. $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
  271. }
  272. // Components of _colinfo:
  273. // $firstcol first column on the range
  274. // $lastcol last column on the range
  275. // $width width to set
  276. // $xfIndex The optional cell style Xf index to apply to the columns
  277. // $hidden The optional hidden atribute
  278. // $level The optional outline level
  279. $this->_colinfo[] = array($i, $i, $width, $xfIndex, $hidden, $level);
  280. }
  281. // Write GUTS
  282. $this->_writeGuts();
  283. // Write DEFAULTROWHEIGHT
  284. $this->_writeDefaultRowHeight();
  285. // Write WSBOOL
  286. $this->_writeWsbool();
  287. // Write horizontal and vertical page breaks
  288. $this->_writeBreaks();
  289. // Write page header
  290. $this->_writeHeader();
  291. // Write page footer
  292. $this->_writeFooter();
  293. // Write page horizontal centering
  294. $this->_writeHcenter();
  295. // Write page vertical centering
  296. $this->_writeVcenter();
  297. // Write left margin
  298. $this->_writeMarginLeft();
  299. // Write right margin
  300. $this->_writeMarginRight();
  301. // Write top margin
  302. $this->_writeMarginTop();
  303. // Write bottom margin
  304. $this->_writeMarginBottom();
  305. // Write page setup
  306. $this->_writeSetup();
  307. // Write sheet protection
  308. $this->_writeProtect();
  309. // Write SCENPROTECT
  310. $this->_writeScenProtect();
  311. // Write OBJECTPROTECT
  312. $this->_writeObjectProtect();
  313. // Write sheet password
  314. $this->_writePassword();
  315. // Write DEFCOLWIDTH record
  316. $this->_writeDefcol();
  317. // Write the COLINFO records if they exist
  318. if (!empty($this->_colinfo)) {
  319. $colcount = count($this->_colinfo);
  320. for ($i = 0; $i < $colcount; ++$i) {
  321. $this->_writeColinfo($this->_colinfo[$i]);
  322. }
  323. }
  324. // Write sheet dimensions
  325. $this->_writeDimensions();
  326. // Row dimensions
  327. foreach ($_phpSheet->getRowDimensions() as $rowDimension) {
  328. $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
  329. $this->_writeRow( $rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel() );
  330. }
  331. // Write Cells
  332. foreach ($_phpSheet->getCellCollection() as $cellID) {
  333. $cell = $_phpSheet->getCell($cellID);
  334. $row = $cell->getRow() - 1;
  335. $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
  336. // Don't break Excel!
  337. // if ($row + 1 > 65536 or $column + 1 > 256) {
  338. if ($row > 65535 || $column > 255) {
  339. break;
  340. }
  341. // Write cell value
  342. $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
  343. $cVal = $cell->getValue();
  344. if ($cVal instanceof PHPExcel_RichText) {
  345. // $this->_writeString($row, $column, $cVal->getPlainText(), $xfIndex);
  346. $arrcRun = array();
  347. $str_len = strlen($cVal->getPlainText());
  348. $str_pos = 0;
  349. $elements = $cVal->getRichTextElements();
  350. foreach ($elements as $element) {
  351. // FONT Index
  352. if ($element instanceof PHPExcel_RichText_Run) {
  353. $str_fontidx = $this->_fntHashIndex[$element->getFont()->getHashCode()];
  354. }
  355. else {
  356. $str_fontidx = 0;
  357. }
  358. $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx);
  359. // Position FROM
  360. $str_pos += strlen($element->getText());
  361. }
  362. $this->_writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
  363. } else {
  364. switch ($cell->getDatatype()) {
  365. case PHPExcel_Cell_DataType::TYPE_STRING:
  366. case PHPExcel_Cell_DataType::TYPE_NULL:
  367. if ($cVal === '' || $cVal === null) {
  368. $this->_writeBlank($row, $column, $xfIndex);
  369. } else {
  370. $this->_writeString($row, $column, $cVal, $xfIndex);
  371. }
  372. break;
  373. case PHPExcel_Cell_DataType::TYPE_NUMERIC:
  374. $this->_writeNumber($row, $column, $cVal, $xfIndex);
  375. break;
  376. case PHPExcel_Cell_DataType::TYPE_FORMULA:
  377. $calculatedValue = $this->_preCalculateFormulas ?
  378. $cell->getCalculatedValue() : null;
  379. $this->_writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue);
  380. break;
  381. case PHPExcel_Cell_DataType::TYPE_BOOL:
  382. $this->_writeBoolErr($row, $column, $cVal, 0, $xfIndex);
  383. break;
  384. case PHPExcel_Cell_DataType::TYPE_ERROR:
  385. $this->_writeBoolErr($row, $column, self::_mapErrorCode($cVal), 1, $xfIndex);
  386. break;
  387. }
  388. }
  389. }
  390. // Append
  391. $this->_writeMsoDrawing();
  392. $this->_writeWindow2();
  393. $this->_writeZoom();
  394. if ($_phpSheet->getFreezePane()) {
  395. $this->_writePanes();
  396. }
  397. $this->_writeSelection();
  398. $this->_writeMergedCells();
  399. // Hyperlinks
  400. foreach ($_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
  401. list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinate);
  402. $url = $hyperlink->getUrl();
  403. if ( strpos($url, 'sheet://') !== false ) {
  404. // internal to current workbook
  405. $url = str_replace('sheet://', 'internal:', $url);
  406. } else if ( preg_match('/^(http:|https:|ftp:|mailto:)/', $url) ) {
  407. // URL
  408. // $url = $url;
  409. } else {
  410. // external (local file)
  411. $url = 'external:' . $url;
  412. }
  413. $this->_writeUrl($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $url);
  414. }
  415. $this->_writeDataValidity();
  416. $this->_writeSheetLayout();
  417. $this->_writeSheetProtection();
  418. $this->_writeRangeProtection();
  419. $this->_storeEof();
  420. }
  421. /**
  422. * Write a cell range address in BIFF8
  423. * always fixed range
  424. * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format
  425. *
  426. * @param string $range E.g. 'A1' or 'A1:B6'
  427. * @return string Binary data
  428. */
  429. private function _writeBIFF8CellRangeAddressFixed($range = 'A1')
  430. {
  431. $explodes = explode(':', $range);
  432. // extract first cell, e.g. 'A1'
  433. $firstCell = $explodes[0];
  434. // extract last cell, e.g. 'B6'
  435. if (count($explodes) == 1) {
  436. $lastCell = $firstCell;
  437. } else {
  438. $lastCell = $explodes[1];
  439. }
  440. $firstCellCoordinates = PHPExcel_Cell::coordinateFromString($firstCell); // e.g. array(0, 1)
  441. $lastCellCoordinates = PHPExcel_Cell::coordinateFromString($lastCell); // e.g. array(1, 6)
  442. return(pack('vvvv',
  443. $firstCellCoordinates[1] - 1,
  444. $lastCellCoordinates[1] - 1,
  445. PHPExcel_Cell::columnIndexFromString($firstCellCoordinates[0]) - 1,
  446. PHPExcel_Cell::columnIndexFromString($lastCellCoordinates[0]) - 1
  447. ));
  448. }
  449. /**
  450. * Retrieves data from memory in one chunk, or from disk in $buffer
  451. * sized chunks.
  452. *
  453. * @return string The data
  454. */
  455. function getData()
  456. {
  457. $buffer = 4096;
  458. // Return data stored in memory
  459. if (isset($this->_data)) {
  460. $tmp = $this->_data;
  461. unset($this->_data);
  462. return $tmp;
  463. }
  464. // No data to return
  465. return false;
  466. }
  467. /**
  468. * Set the option to print the row and column headers on the printed page.
  469. *
  470. * @access public
  471. * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
  472. */
  473. function printRowColHeaders($print = 1)
  474. {
  475. $this->_print_headers = $print;
  476. }
  477. /**
  478. * This method sets the properties for outlining and grouping. The defaults
  479. * correspond to Excel's defaults.
  480. *
  481. * @param bool $visible
  482. * @param bool $symbols_below
  483. * @param bool $symbols_right
  484. * @param bool $auto_style
  485. */
  486. function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
  487. {
  488. $this->_outline_on = $visible;
  489. $this->_outline_below = $symbols_below;
  490. $this->_outline_right = $symbols_right;
  491. $this->_outline_style = $auto_style;
  492. // Ensure this is a boolean vale for Window2
  493. if ($this->_outline_on) {
  494. $this->_outline_on = 1;
  495. }
  496. }
  497. /**
  498. * Write a double to the specified row and column (zero indexed).
  499. * An integer can be written as a double. Excel will display an
  500. * integer. $format is optional.
  501. *
  502. * Returns 0 : normal termination
  503. * -2 : row or column out of range
  504. *
  505. * @param integer $row Zero indexed row
  506. * @param integer $col Zero indexed column
  507. * @param float $num The number to write
  508. * @param mixed $xfIndex The optional XF format
  509. * @return integer
  510. */
  511. private function _writeNumber($row, $col, $num, $xfIndex)
  512. {
  513. $record = 0x0203; // Record identifier
  514. $length = 0x000E; // Number of bytes to follow
  515. $header = pack("vv", $record, $length);
  516. $data = pack("vvv", $row, $col, $xfIndex);
  517. $xl_double = pack("d", $num);
  518. if (self::getByteOrder()) { // if it's Big Endian
  519. $xl_double = strrev($xl_double);
  520. }
  521. $this->_append($header.$data.$xl_double);
  522. return(0);
  523. }
  524. /**
  525. * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
  526. *
  527. * @param int $row Row index (0-based)
  528. * @param int $col Column index (0-based)
  529. * @param string $str The string
  530. * @param int $xfIndex Index to XF record
  531. */
  532. private function _writeString($row, $col, $str, $xfIndex)
  533. {
  534. $this->_writeLabelSst($row, $col, $str, $xfIndex);
  535. }
  536. /**
  537. * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
  538. * It differs from _writeString by the writing of rich text strings.
  539. * @param int $row Row index (0-based)
  540. * @param int $col Column index (0-based)
  541. * @param string $str The string
  542. * @param mixed $xfIndex The XF format index for the cell
  543. * @param array $arrcRun Index to Font record and characters beginning
  544. */
  545. private function _writeRichTextString($row, $col, $str, $xfIndex, $arrcRun){
  546. $record = 0x00FD; // Record identifier
  547. $length = 0x000A; // Bytes to follow
  548. $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun);
  549. /* check if string is already present */
  550. if (!isset($this->_str_table[$str])) {
  551. $this->_str_table[$str] = $this->_str_unique++;
  552. }
  553. $this->_str_total++;
  554. $header = pack('vv', $record, $length);
  555. $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
  556. $this->_append($header.$data);
  557. }
  558. /**
  559. * Write a string to the specified row and column (zero indexed).
  560. * NOTE: there is an Excel 5 defined limit of 255 characters.
  561. * $format is optional.
  562. * Returns 0 : normal termination
  563. * -2 : row or column out of range
  564. * -3 : long string truncated to 255 chars
  565. *
  566. * @access public
  567. * @param integer $row Zero indexed row
  568. * @param integer $col Zero indexed column
  569. * @param string $str The string to write
  570. * @param mixed $xfIndex The XF format index for the cell
  571. * @return integer
  572. */
  573. private function _writeLabel($row, $col, $str, $xfIndex)
  574. {
  575. $strlen = strlen($str);
  576. $record = 0x0204; // Record identifier
  577. $length = 0x0008 + $strlen; // Bytes to follow
  578. $str_error = 0;
  579. if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
  580. $str = substr($str, 0, $this->_xls_strmax);
  581. $length = 0x0008 + $this->_xls_strmax;
  582. $strlen = $this->_xls_strmax;
  583. $str_error = -3;
  584. }
  585. $header = pack("vv", $record, $length);
  586. $data = pack("vvvv", $row, $col, $xfIndex, $strlen);
  587. $this->_append($header . $data . $str);
  588. return($str_error);
  589. }
  590. /**
  591. * Write a string to the specified row and column (zero indexed).
  592. * This is the BIFF8 version (no 255 chars limit).
  593. * $format is optional.
  594. * Returns 0 : normal termination
  595. * -2 : row or column out of range
  596. * -3 : long string truncated to 255 chars
  597. *
  598. * @access public
  599. * @param integer $row Zero indexed row
  600. * @param integer $col Zero indexed column
  601. * @param string $str The string to write
  602. * @param mixed $xfIndex The XF format index for the cell
  603. * @return integer
  604. */
  605. private function _writeLabelSst($row, $col, $str, $xfIndex)
  606. {
  607. $record = 0x00FD; // Record identifier
  608. $length = 0x000A; // Bytes to follow
  609. $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($str);
  610. /* check if string is already present */
  611. if (!isset($this->_str_table[$str])) {
  612. $this->_str_table[$str] = $this->_str_unique++;
  613. }
  614. $this->_str_total++;
  615. $header = pack('vv', $record, $length);
  616. $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
  617. $this->_append($header.$data);
  618. }
  619. /**
  620. * Writes a note associated with the cell given by the row and column.
  621. * NOTE records don't have a length limit.
  622. *
  623. * @param integer $row Zero indexed row
  624. * @param integer $col Zero indexed column
  625. * @param string $note The note to write
  626. */
  627. private function _writeNote($row, $col, $note)
  628. {
  629. $note_length = strlen($note);
  630. $record = 0x001C; // Record identifier
  631. $max_length = 2048; // Maximun length for a NOTE record
  632. // Length for this record is no more than 2048 + 6
  633. $length = 0x0006 + min($note_length, 2048);
  634. $header = pack("vv", $record, $length);
  635. $data = pack("vvv", $row, $col, $note_length);
  636. $this->_append($header . $data . substr($note, 0, 2048));
  637. for ($i = $max_length; $i < $note_length; $i += $max_length) {
  638. $chunk = substr($note, $i, $max_length);
  639. $length = 0x0006 + strlen($chunk);
  640. $header = pack("vv", $record, $length);
  641. $data = pack("vvv", -1, 0, strlen($chunk));
  642. $this->_append($header.$data.$chunk);
  643. }
  644. return(0);
  645. }
  646. /**
  647. * Write a blank cell to the specified row and column (zero indexed).
  648. * A blank cell is used to specify formatting without adding a string
  649. * or a number.
  650. *
  651. * A blank cell without a format serves no purpose. Therefore, we don't write
  652. * a BLANK record unless a format is specified.
  653. *
  654. * Returns 0 : normal termination (including no format)
  655. * -1 : insufficient number of arguments
  656. * -2 : row or column out of range
  657. *
  658. * @param integer $row Zero indexed row
  659. * @param integer $col Zero indexed column
  660. * @param mixed $xfIndex The XF format index
  661. */
  662. function _writeBlank($row, $col, $xfIndex)
  663. {
  664. $record = 0x0201; // Record identifier
  665. $length = 0x0006; // Number of bytes to follow
  666. $header = pack("vv", $record, $length);
  667. $data = pack("vvv", $row, $col, $xfIndex);
  668. $this->_append($header . $data);
  669. return 0;
  670. }
  671. /**
  672. * Write a boolean or an error type to the specified row and column (zero indexed)
  673. *
  674. * @param int $row Row index (0-based)
  675. * @param int $col Column index (0-based)
  676. * @param int $value
  677. * @param boolean $isError Error or Boolean?
  678. * @param int $xfIndex
  679. */
  680. private function _writeBoolErr($row, $col, $value, $isError, $xfIndex)
  681. {
  682. $record = 0x0205;
  683. $length = 8;
  684. $header = pack("vv", $record, $length);
  685. $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError);
  686. $this->_append($header . $data);
  687. return 0;
  688. }
  689. /**
  690. * Write a formula to the specified row and column (zero indexed).
  691. * The textual representation of the formula is passed to the parser in
  692. * Parser.php which returns a packed binary string.
  693. *
  694. * Returns 0 : normal termination
  695. * -1 : formula errors (bad formula)
  696. * -2 : row or column out of range
  697. *
  698. * @param integer $row Zero indexed row
  699. * @param integer $col Zero indexed column
  700. * @param string $formula The formula text string
  701. * @param mixed $xfIndex The XF format index
  702. * @param mixed $calculatedValue Calculated value
  703. * @return integer
  704. */
  705. private function _writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
  706. {
  707. $record = 0x0006; // Record identifier
  708. // Initialize possible additional value for STRING record that should be written after the FORMULA record?
  709. $stringValue = null;
  710. // calculated value
  711. if (isset($calculatedValue)) {
  712. // Since we can't yet get the data type of the calculated value,
  713. // we use best effort to determine data type
  714. if (is_bool($calculatedValue)) {
  715. // Boolean value
  716. $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF);
  717. } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
  718. // Numeric value
  719. $num = pack('d', $calculatedValue);
  720. } elseif (is_string($calculatedValue)) {
  721. if (array_key_exists($calculatedValue, PHPExcel_Cell_DataType::getErrorCodes())) {
  722. // Error value
  723. $num = pack('CCCvCv', 0x02, 0x00, self::_mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF);
  724. } elseif ($calculatedValue === '') {
  725. // Empty string (and BIFF8)
  726. $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
  727. } else {
  728. // Non-empty string value (or empty string BIFF5)
  729. $stringValue = $calculatedValue;
  730. $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
  731. }
  732. } else {
  733. // We are really not supposed to reach here
  734. $num = pack('d', 0x00);
  735. }
  736. } else {
  737. $num = pack('d', 0x00);
  738. }
  739. $grbit = 0x03; // Option flags
  740. $unknown = 0x0000; // Must be zero
  741. // Strip the '=' or '@' sign at the beginning of the formula string
  742. if ($formula{0} == '=') {
  743. $formula = substr($formula,1);
  744. } else {
  745. // Error handling
  746. $this->_writeString($row, $col, 'Unrecognised character for formula');
  747. return -1;
  748. }
  749. // Parse the formula using the parser in Parser.php
  750. try {
  751. $error = $this->_parser->parse($formula);
  752. $formula = $this->_parser->toReversePolish();
  753. $formlen = strlen($formula); // Length of the binary string
  754. $length = 0x16 + $formlen; // Length of the record data
  755. $header = pack("vv", $record, $length);
  756. $data = pack("vvv", $row, $col, $xfIndex)
  757. . $num
  758. . pack("vVv", $grbit, $unknown, $formlen);
  759. $this->_append($header . $data . $formula);
  760. // Append also a STRING record if necessary
  761. if ($stringValue !== null) {
  762. $this->_writeStringRecord($stringValue);
  763. }
  764. return 0;
  765. } catch (Exception $e) {
  766. // do nothing
  767. }
  768. }
  769. /**
  770. * Write a STRING record. This
  771. *
  772. * @param string $stringValue
  773. */
  774. private function _writeStringRecord($stringValue)
  775. {
  776. $record = 0x0207; // Record identifier
  777. $data = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($stringValue);
  778. $length = strlen($data);
  779. $header = pack('vv', $record, $length);
  780. $this->_append($header . $data);
  781. }
  782. /**
  783. * Write a hyperlink.
  784. * This is comprised of two elements: the visible label and
  785. * the invisible link. The visible label is the same as the link unless an
  786. * alternative string is specified. The label is written using the
  787. * _writeString() method. Therefore the 255 characters string limit applies.
  788. * $string and $format are optional.
  789. *
  790. * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
  791. * directory url.
  792. *
  793. * Returns 0 : normal termination
  794. * -2 : row or column out of range
  795. * -3 : long string truncated to 255 chars
  796. *
  797. * @param integer $row Row
  798. * @param integer $col Column
  799. * @param string $url URL string
  800. * @return integer
  801. */
  802. private function _writeUrl($row, $col, $url)
  803. {
  804. // Add start row and col to arg list
  805. return($this->_writeUrlRange($row, $col, $row, $col, $url));
  806. }
  807. /**
  808. * This is the more general form of _writeUrl(). It allows a hyperlink to be
  809. * written to a range of cells. This function also decides the type of hyperlink
  810. * to be written. These are either, Web (http, ftp, mailto), Internal
  811. * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
  812. *
  813. * @access private
  814. * @see _writeUrl()
  815. * @param integer $row1 Start row
  816. * @param integer $col1 Start column
  817. * @param integer $row2 End row
  818. * @param integer $col2 End column
  819. * @param string $url URL string
  820. * @return integer
  821. */
  822. function _writeUrlRange($row1, $col1, $row2, $col2, $url)
  823. {
  824. // Check for internal/external sheet links or default to web link
  825. if (preg_match('[^internal:]', $url)) {
  826. return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url));
  827. }
  828. if (preg_match('[^external:]', $url)) {
  829. return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url));
  830. }
  831. return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url));
  832. }
  833. /**
  834. * Used to write http, ftp and mailto hyperlinks.
  835. * The link type ($options) is 0x03 is the same as absolute dir ref without
  836. * sheet. However it is differentiated by the $unknown2 data stream.
  837. *
  838. * @access private
  839. * @see _writeUrl()
  840. * @param integer $row1 Start row
  841. * @param integer $col1 Start column
  842. * @param integer $row2 End row
  843. * @param integer $col2 End column
  844. * @param string $url URL string
  845. * @return integer
  846. */
  847. function _writeUrlWeb($row1, $col1, $row2, $col2, $url)
  848. {
  849. $record = 0x01B8; // Record identifier
  850. $length = 0x00000; // Bytes to follow
  851. // Pack the undocumented parts of the hyperlink stream
  852. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  853. $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
  854. // Pack the option flags
  855. $options = pack("V", 0x03);
  856. // Convert URL to a null terminated wchar string
  857. $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
  858. $url = $url . "\0\0\0";
  859. // Pack the length of the URL
  860. $url_len = pack("V", strlen($url));
  861. // Calculate the data length
  862. $length = 0x34 + strlen($url);
  863. // Pack the header data
  864. $header = pack("vv", $record, $length);
  865. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  866. // Write the packed data
  867. $this->_append($header . $data .
  868. $unknown1 . $options .
  869. $unknown2 . $url_len . $url);
  870. return 0;
  871. }
  872. /**
  873. * Used to write internal reference hyperlinks such as "Sheet1!A1".
  874. *
  875. * @access private
  876. * @see _writeUrl()
  877. * @param integer $row1 Start row
  878. * @param integer $col1 Start column
  879. * @param integer $row2 End row
  880. * @param integer $col2 End column
  881. * @param string $url URL string
  882. * @return integer
  883. */
  884. function _writeUrlInternal($row1, $col1, $row2, $col2, $url)
  885. {
  886. $record = 0x01B8; // Record identifier
  887. $length = 0x00000; // Bytes to follow
  888. // Strip URL type
  889. $url = preg_replace('/^internal:/', '', $url);
  890. // Pack the undocumented parts of the hyperlink stream
  891. $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
  892. // Pack the option flags
  893. $options = pack("V", 0x08);
  894. // Convert the URL type and to a null terminated wchar string
  895. $url .= "\0";
  896. // character count
  897. $url_len = PHPExcel_Shared_String::CountCharacters($url);
  898. $url_len = pack('V', $url_len);
  899. $url = PHPExcel_Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8');
  900. // Calculate the data length
  901. $length = 0x24 + strlen($url);
  902. // Pack the header data
  903. $header = pack("vv", $record, $length);
  904. $data = pack("vvvv", $row1, $row2, $col1, $col2);
  905. // Write the packed data
  906. $this->_append($header . $data .
  907. $unknown1 . $options .
  908. $url_len . $url);
  909. return 0;
  910. }
  911. /**
  912. * Write links to external directory names such as 'c:\foo.xls',
  913. * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
  914. *
  915. * Note: Excel writes some relative links with the $dir_long string. We ignore
  916. * these cases for the sake of simpler code.
  917. *
  918. * @access private
  919. * @see _writeUrl()
  920. * @param integer $row1 Start row
  921. * @param integer $col1 Start column
  922. * @param integer $row2 End row
  923. * @param integer $col2 End column
  924. * @param string $url URL string
  925. * @return integer
  926. */
  927. function _writeUrlExternal($row1, $col1, $row2, $col2, $url)
  928. {
  929. // Network drives are different. We will handle them separately
  930. // MS/Novell network drives and shares start with \\
  931. if (preg_match('[^external:\\\\]', $url)) {
  932. return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
  933. }
  934. $record = 0x01B8; // Record identifier
  935. $length = 0x00000; // Bytes to follow
  936. // Strip URL type and change Unix dir separator to Dos style (if needed)
  937. //
  938. $url = preg_replace('/^external:/', '', $url);
  939. $url = preg_replace('/\//', "\\", $url);
  940. // Determine if the link is relative or absolute:
  941. // relative if link contains no dir separator, "somefile.xls"
  942. // relative if link starts with up-dir, "..\..\somefile.xls"
  943. // otherwise, absolute
  944. $absolute = 0x00; // relative path
  945. if ( preg_match('/^[A-Z]:/', $url) ) {
  946. $absolute = 0x02; // absolute path on Windows, e.g. C:\...
  947. }
  948. $link_type = 0x01 | $absolute;
  949. // Determine if the link contains a sheet reference and change some of the
  950. // parameters accordingly.
  951. // Split the dir name and sheet name (if it exists)
  952. $dir_long = $url;
  953. if (preg_match("/\#/", $url)) {
  954. $link_type |= 0x08;
  955. }
  956. // Pack the link type
  957. $link_type = pack("V", $link_type);
  958. // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
  959. $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
  960. $up_count = pack("v", $up_count);
  961. // Store the short dos dir name (null terminated)
  962. $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
  963. // Store the long dir name as a wchar string (non-null terminated)
  964. $dir_long = $dir_long . "\0";
  965. // Pack the lengths of the dir strings
  966. $dir_short_len = pack("V", strlen($dir_short) );
  967. $dir_long_len = pack("V", strlen($dir_long) );
  968. $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
  969. // Pack the undocumented parts of the hyperlink stream
  970. $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
  971. $unknown2 = pack("H*",'0303000000000000C000000000000046' );
  972. $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
  973. $unknown4 = pack("v", 0x03 );
  974. // Pack the main data stream
  975. $data = pack("vvvv", $row1, $row2, $col1, $col2) .
  976. $unknown1 .
  977. $link_type .
  978. $unknown2 .
  979. $up_count .
  980. $dir_short_len.
  981. $dir_short .
  982. $unknown3 .
  983. $stream_len ;/*.
  984. $dir_long_len .
  985. $unknown4 .
  986. $dir_long .
  987. $sheet_len .
  988. $sheet ;*/
  989. // Pack the header data
  990. $length = strlen($data);
  991. $header = pack("vv", $record, $length);
  992. // Write the packed data
  993. $this->_append($header. $data);
  994. return 0;
  995. }
  996. /**
  997. * This method is used to set the height and format for a row.
  998. *
  999. * @param integer $row The row to set
  1000. * @param integer $height Height we are giving to the row.
  1001. * Use null to set XF without setting height
  1002. * @param integer $xfIndex The optional cell style Xf index to apply to the columns
  1003. * @param bool $hidden The optional hidden attribute
  1004. * @param integer $level The optional outline level for row, in range [0,7]
  1005. */
  1006. private function _writeRow($row, $height, $xfIndex, $hidden = false, $level = 0)
  1007. {
  1008. $record = 0x0208; // Record identifier
  1009. $length = 0x0010; // Number of bytes to follow
  1010. $colMic = 0x0000; // First defined column
  1011. $colMac = 0x0000; // Last defined column
  1012. $irwMac = 0x0000; // Used by Excel to optimise loading
  1013. $reserved = 0x0000; // Reserved
  1014. $grbit = 0x0000; // Option flags
  1015. $ixfe = $xfIndex;
  1016. if ( $height < 0 ){
  1017. $height = null;
  1018. }
  1019. // Use _writeRow($row, null, $XF) to set XF format without setting height
  1020. if ($height != null) {
  1021. $miyRw = $height * 20; // row height
  1022. } else {
  1023. $miyRw = 0xff; // default row height is 256
  1024. }
  1025. // Set the options flags. fUnsynced is used to show that the font and row
  1026. // heights are not compatible. This is usually the case for WriteExcel.
  1027. // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
  1028. // is collapsed. Instead it is used to indicate that the previous row is
  1029. // collapsed. The zero height flag, 0x20, is used to collapse a row.
  1030. $grbit |= $level;
  1031. if ($hidden) {
  1032. $grbit |= 0x0020;
  1033. }
  1034. if ($height !== null) {
  1035. $grbit |= 0x0040; // fUnsynced
  1036. }
  1037. if ($xfIndex !== 0xF) {
  1038. $grbit |= 0x0080;
  1039. }
  1040. $grbit |= 0x0100;
  1041. $header = pack("vv", $record, $length);
  1042. $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
  1043. $irwMac,$reserved, $grbit, $ixfe);
  1044. $this->_append($header.$data);
  1045. }
  1046. /**
  1047. * Writes Excel DIMENSIONS to define the area in which there is data.
  1048. */
  1049. private function _writeDimensions()
  1050. {
  1051. $record = 0x0200; // Record identifier
  1052. $length = 0x000E;
  1053. $data = pack('VVvvv'
  1054. , $this->_firstRowIndex
  1055. , $this->_lastRowIndex + 1
  1056. , $this->_firstColumnIndex
  1057. , $this->_lastColumnIndex + 1
  1058. , 0x0000 // reserved
  1059. );
  1060. $header = pack("vv", $record, $length);
  1061. $this->_append($header.$data);
  1062. }
  1063. /**
  1064. * Write BIFF record Window2.
  1065. */
  1066. private function _writeWindow2()
  1067. {
  1068. $record = 0x023E; // Record identifier
  1069. $length = 0x0012;
  1070. $grbit = 0x00B6; // Option flags
  1071. $rwTop = 0x0000; // Top row visible in window
  1072. $colLeft = 0x0000; // Leftmost column visible in window
  1073. // The options flags that comprise $grbit
  1074. $fDspFmla = 0; // 0 - bit
  1075. $fDspGrid = $this->_phpSheet->getShowGridlines() ? 1 : 0; // 1
  1076. $fDspRwCol = $this->_phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
  1077. $fFrozen = $this->_phpSheet->getFreezePane() ? 1 : 0; // 3
  1078. $fDspZeros = 1; // 4
  1079. $fDefaultHdr = 1; // 5
  1080. $fArabic = $this->_phpSheet->getRightToLeft() ? 1 : 0; // 6
  1081. $fDspGuts = $this->_outline_on; // 7
  1082. $fFrozenNoSplit = 0; // 0 - bit
  1083. // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet
  1084. $fSelected = ($this->_phpSheet === $this->_phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
  1085. $fPaged = 1; // 2
  1086. $grbit = $fDspFmla;
  1087. $grbit |= $fDspGrid << 1;
  1088. $grbit |= $fDspRwCol << 2;
  1089. $grbit |= $fFrozen << 3;
  1090. $grbit |= $fDspZeros << 4;
  1091. $grbit |= $fDefaultHdr << 5;
  1092. $grbit |= $fArabic << 6;
  1093. $grbit |= $fDspGuts << 7;
  1094. $grbit |= $fFrozenNoSplit << 8;
  1095. $grbit |= $fSelected << 9;
  1096. $grbit |= $fPaged << 10;
  1097. $header = pack("vv", $record, $length);
  1098. $data = pack("vvv", $grbit, $rwTop, $colLeft);
  1099. // FIXME !!!
  1100. $rgbHdr = 0x0040; // Row/column heading and gridline color index
  1101. $zoom_factor_page_break = 0x0000;
  1102. $zoom_factor_normal = 0x0000;
  1103. $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
  1104. $this->_append($header.$data);
  1105. }
  1106. /**
  1107. * Write BIFF record DEFAULTROWHEIGHT.
  1108. */
  1109. private function _writeDefaultRowHeight()
  1110. {
  1111. $defaultRowHeight = $this->_phpSheet->getDefaultRowDimension()->getRowHeight();
  1112. if ($defaultRowHeight < 0) {
  1113. return;
  1114. }
  1115. // convert to twips
  1116. $defaultRowHeight = (int) 20 * $defaultRowHeight;
  1117. $record = 0x0225; // Record identifier
  1118. $length = 0x0004; // Number of bytes to follow
  1119. $header = pack("vv", $record, $length);
  1120. $data = pack("vv", 1, $defaultRowHeight);
  1121. $this->_append($header . $data);
  1122. }
  1123. /**
  1124. * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
  1125. */
  1126. private function _writeDefcol()
  1127. {
  1128. $defaultColWidth = 8;
  1129. $record = 0x0055; // Record identifier
  1130. $length = 0x0002; // Number of bytes to follow
  1131. $header = pack("vv", $record, $length);
  1132. $data = pack("v", $defaultColWidth);
  1133. $this->_append($header . $data);
  1134. }
  1135. /**
  1136. * Write BIFF record COLINFO to define column widths
  1137. *
  1138. * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
  1139. * length record.
  1140. *
  1141. * @param array $col_array This is the only parameter received and is composed of the following:
  1142. * 0 => First formatted column,
  1143. * 1 => Last formatted column,
  1144. * 2 => Col width (8.43 is Excel default),
  1145. * 3 => The optional XF format of the column,
  1146. * 4 => Option flags.
  1147. * 5 => Optional outline level
  1148. */
  1149. private function _writeColinfo($col_array)
  1150. {
  1151. if (isset($col_array[0])) {
  1152. $colFirst = $col_array[0];
  1153. }
  1154. if (isset($col_array[1])) {
  1155. $colLast = $col_array[1];
  1156. }
  1157. if (isset($col_array[2])) {
  1158. $coldx = $col_array[2];
  1159. } else {
  1160. $coldx = 8.43;
  1161. }
  1162. if (isset($col_array[3])) {
  1163. $xfIndex = $col_array[3];
  1164. } else {
  1165. $xfIndex = 15;
  1166. }
  1167. if (isset($col_array[4])) {
  1168. $grbit = $col_array[4];
  1169. } else {
  1170. $grbit = 0;
  1171. }
  1172. if (isset($col_array[5])) {
  1173. $level = $col_array[5];
  1174. } else {
  1175. $level = 0;
  1176. }
  1177. $record = 0x007D; // Record identifier
  1178. $length = 0x000C; // Number of bytes to follow
  1179. $coldx *= 256; // Convert to units of 1/256 of a char
  1180. $ixfe = $xfIndex;
  1181. $reserved = 0x0000; // Reserved
  1182. $level = max(0, min($level, 7));
  1183. $grbit |= $level << 8;
  1184. $header = pack("vv", $record, $length);
  1185. $data = pack("vvvvvv", $colFirst, $colLast, $coldx,
  1186. $ixfe, $grbit, $reserved);
  1187. $this->_append($header.$data);
  1188. }
  1189. /**
  1190. * Write BIFF record SELECTION.
  1191. */
  1192. private function _writeSelection()
  1193. {
  1194. // look up the selected cell range
  1195. $selectedCells = $this->_phpSheet->getSelectedCells();
  1196. $selectedCells = PHPExcel_Cell::splitRange($this->_phpSheet->getSelectedCells());
  1197. $selectedCells = $selectedCells[0];
  1198. if (count($selectedCells) == 2) {
  1199. list($first, $last) = $selectedCells;
  1200. } else {
  1201. $first = $selectedCells[0];
  1202. $last = $selectedCells[0];
  1203. }
  1204. list($colFirst, $rwFirst) = PHPExcel_Cell::coordinateFromString($first);
  1205. $colFirst = PHPExcel_Cell::columnIndexFromString($colFirst) - 1; // base 0 column index
  1206. --$rwFirst; // base 0 row index
  1207. list($colLast, $rwLast) = PHPExcel_Cell::coordinateFromString($last);
  1208. $colLast = PHPExcel_Cell::columnIndexFromString($colLast) - 1; // base 0 column index
  1209. --$rwLast; // base 0 row index
  1210. // make sure we are not out of bounds
  1211. $colFirst = min($colFirst, 255);
  1212. $colLast = min($colLast, 255);
  1213. $rwFirst = min($rwFirst, 65535);
  1214. $rwLast = min($rwLast, 65535);
  1215. $record = 0x001D; // Record identifier
  1216. $length = 0x000F; // Number of bytes to follow
  1217. $pnn = $this->_active_pane; // Pane position
  1218. $rwAct = $rwFirst; // Active row
  1219. $colAct = $colFirst; // Active column
  1220. $irefAct = 0; // Active cell ref
  1221. $cref = 1; // Number of refs
  1222. if (!isset($rwLast)) {
  1223. $rwLast = $rwFirst; // Last row in reference
  1224. }
  1225. if (!isset($colLast)) {
  1226. $colLast = $colFirst; // Last col in reference
  1227. }
  1228. // Swap last row/col for first row/col as necessary
  1229. if ($rwFirst > $rwLast) {
  1230. list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
  1231. }
  1232. if ($colFirst > $colLast) {
  1233. list($colFirst, $colLast) = array($colLast, $colFirst);
  1234. }
  1235. $header = pack("vv", $record, $length);
  1236. $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
  1237. $irefAct, $cref,
  1238. $rwFirst, $rwLast,
  1239. $colFirst, $colLast);
  1240. $this->_append($header . $data);
  1241. }
  1242. /**
  1243. * Store the MERGEDCELLS records for all ranges of merged cells
  1244. */
  1245. private function _writeMergedCells()
  1246. {
  1247. $mergeCells = $this->_phpSheet->getMergeCells();
  1248. $countMergeCells = count($mergeCells);
  1249. if ($countMergeCells == 0) {
  1250. return;
  1251. }
  1252. // maximum allowed number of merged cells per record
  1253. $maxCountMergeCellsPerRecord = 1027;
  1254. // record identifier
  1255. $record = 0x00E5;
  1256. // counter for total number of merged cells treated so far by the writer
  1257. $i = 0;
  1258. // counter for number of merged cells written in record currently being written
  1259. $j = 0;
  1260. // initialize record data
  1261. $recordData = '';
  1262. // loop through the merged cells
  1263. foreach ($mergeCells as $mergeCell) {
  1264. ++$i;
  1265. ++$j;
  1266. // extract the row and column indexes
  1267. $range = PHPExcel_Cell::splitRange($mergeCell);
  1268. list($first, $last) = $range[0];
  1269. list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first);
  1270. list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last);
  1271. $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1);
  1272. // flush record if we have reached limit for number of merged cells, or reached final merged cell
  1273. if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
  1274. $recordData = pack('v', $j) . $recordData;
  1275. $length = strlen($recordData);
  1276. $header = pack('vv', $record, $length);
  1277. $this->_append($header . $recordData);
  1278. // initialize for next record, if any
  1279. $recordData = '';
  1280. $j = 0;
  1281. }
  1282. }
  1283. }
  1284. /**
  1285. * Write SHEETLAYOUT record
  1286. */
  1287. private function _writeSheetLayout()
  1288. {
  1289. if (!$this->_phpSheet->isTabColorSet()) {
  1290. return;
  1291. }
  1292. $recordData = pack(
  1293. 'vvVVVvv'
  1294. , 0x0862
  1295. , 0x0000 // unused
  1296. , 0x00000000 // unused
  1297. , 0x00000000 // unused
  1298. , 0x00000014 // size of record data
  1299. , $this->_colors[$this->_phpSheet->getTabColor()->getRGB()] // color index
  1300. , 0x0000 // unused
  1301. );
  1302. $length = strlen($recordData);
  1303. $record = 0x0862; // Record identifier
  1304. $header = pack('vv', $record, $length);
  1305. $this->_append($header . $recordData);
  1306. }
  1307. /**
  1308. * Write SHEETPROTECTION
  1309. */
  1310. private function _writeSheetProtection()
  1311. {
  1312. // record identifier
  1313. $record = 0x0867;
  1314. // prepare options
  1315. $options = (int) !$this->_phpSheet->getProtection()->getObjects()
  1316. | (int) !$this->_phpSheet->getProtection()->getScenarios() << 1
  1317. | (int) !$this->_phpSheet->getProtection()->getFormatCells() << 2
  1318. | (int) !$this->_phpSheet->getProtection()->getFormatColumns() << 3
  1319. | (int) !$this->_phpSheet->getProtection()->getFormatRows() << 4
  1320. | (int) !$this->_phpSheet->getProtection()->getInsertColumns() << 5
  1321. | (int) !$this->_phpSheet->getProtection()->getInsertRows() << 6
  1322. | (int) !$this->_phpSheet->getProtection()->getInsertHyperlinks() << 7
  1323. | (int) !$this->_phpSheet->getProtection()->getDeleteColumns() << 8
  1324. | (int) !$this->_phpSheet->getProtection()->getDeleteRows() << 9
  1325. | (int) !$this->_phpSheet->getProtection()->getSelectLockedCells() << 10
  1326. | (int) !$this->_phpSheet->getProtection()->getSort() << 11
  1327. | (int) !$this->_phpSheet->getProtection()->getAutoFilter() << 12
  1328. | (int) !$this->_phpSheet->getProtection()->getPivotTables() << 13
  1329. | (int) !$this->_phpSheet->getProtection()->getSelectUnlockedCells() << 14 ;
  1330. // record data
  1331. $recordData = pack(
  1332. 'vVVCVVvv'
  1333. , 0x0867 // repeated record identifier
  1334. , 0x0000 // not used
  1335. , 0x0000 // not used
  1336. , 0x00 // not used
  1337. , 0x01000200 // unknown data
  1338. , 0xFFFFFFFF // unknown data
  1339. , $options // options
  1340. , 0x0000 // not used
  1341. );
  1342. $length = strlen($recordData);
  1343. $header = pack('vv', $record, $length);
  1344. $this->_append($header . $recordData);
  1345. }
  1346. /**
  1347. * Write BIFF record RANGEPROTECTION
  1348. *
  1349. * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
  1350. * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
  1351. */
  1352. private function _writeRangeProtection()
  1353. {
  1354. foreach ($this->_phpSheet->getProtectedCells() as $range => $password) {
  1355. // number of ranges, e.g. 'A1:B3 C20:D25'
  1356. $cellRanges = explode(' ', $range);
  1357. $cref = count($cellRanges);
  1358. $recordData = pack(
  1359. 'vvVVvCVvVv',
  1360. 0x0868,
  1361. 0x00,
  1362. 0x0000,
  1363. 0x0000,
  1364. 0x02,
  1365. 0x0,
  1366. 0x0000,
  1367. $cref,
  1368. 0x0000,
  1369. 0x00
  1370. );
  1371. foreach ($cellRanges as $cellRange) {
  1372. $recordData .= $this->_writeBIFF8CellRangeAddressFixed($cellRange);
  1373. }
  1374. // the rgbFeat structure
  1375. $recordData .= pack(
  1376. 'VV',
  1377. 0x0000,
  1378. hexdec($password)
  1379. );
  1380. $recordData .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
  1381. $length = strlen($recordData);
  1382. $record = 0x0868; // Record identifier
  1383. $header = pack("vv", $record, $length);
  1384. $this->_append($header . $recordData);
  1385. }
  1386. }
  1387. /**
  1388. * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
  1389. * references in a worksheet.
  1390. *
  1391. * Excel only stores references to external sheets that are used in formulas.
  1392. * For simplicity we store references to all the sheets in the workbook
  1393. * regardless of whether they are used or not. This reduces the overall
  1394. * complexity and eliminates the need for a two way dialogue between the formula
  1395. * parser the worksheet objects.
  1396. *
  1397. * @param integer $count The number of external sheet references in this worksheet
  1398. */
  1399. private function _writeExterncount($count)
  1400. {
  1401. $record = 0x0016; // Record identifier
  1402. $length = 0x0002; // Number of bytes to follow
  1403. $header = pack("vv", $record, $length);
  1404. $data = pack("v", $count);
  1405. $this->_append($header . $data);
  1406. }
  1407. /**
  1408. * Writes the Excel BIFF EXTERNSHEET record. These references are used by
  1409. * formulas. A formula references a sheet name via an index. Since we store a
  1410. * reference to all of the external worksheets the EXTERNSHEET index is the same
  1411. * as the worksheet index.
  1412. *
  1413. * @param string $sheetname The name of a external worksheet
  1414. */
  1415. private function _writeExternsheet($sheetname)
  1416. {
  1417. $record = 0x0017; // Record identifier
  1418. // References to the current sheet are encoded differently to references to
  1419. // external sheets.
  1420. //
  1421. if ($this->_phpSheet->getTitle() == $sheetname) {
  1422. $sheetname = '';
  1423. $length = 0x02; // The following 2 bytes
  1424. $cch = 1; // The following byte
  1425. $rgch = 0x02; // Self reference
  1426. } else {
  1427. $length = 0x02 + strlen($sheetname);
  1428. $cch = strlen($sheetname);
  1429. $rgch = 0x03; // Reference to a sheet in the current workbook
  1430. }
  1431. $header = pack("vv", $record, $length);
  1432. $data = pack("CC", $cch, $rgch);
  1433. $this->_append($header . $data . $sheetname);
  1434. }
  1435. /**
  1436. * Writes the Excel BIFF PANE record.
  1437. * The panes can either be frozen or thawed (unfrozen).
  1438. * Frozen panes are specified in terms of an integer number of rows and columns.
  1439. * Thawed panes are specified in terms of Excel's units for rows and columns.
  1440. */
  1441. private function _writePanes()
  1442. {
  1443. $panes = array();
  1444. if ($freezePane = $this->_phpSheet->getFreezePane()) {
  1445. list($column, $row) = PHPExcel_Cell::coordinateFromString($fr

Large files files are truncated, but you can click here to view the full file