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

/phpmyadmin/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php

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

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