PageRenderTime 65ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/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

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.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 functi

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