PageRenderTime 37ms CodeModel.GetById 9ms 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
  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 specified in terms of an integer number of rows and columns.
  1450. * Thawed panes are specified in terms of Excel's units for rows and columns.
  1451. */
  1452. private function _writePanes()
  1453. {
  1454. $panes = array();
  1455. if ($freezePane = $this->_phpSheet->getFreezePane()) {
  1456. list($column, $row) = PHPExcel_Cell::coordinateFromString($freezePane);
  1457. $panes[0] = $row - 1;
  1458. $panes[1] = PHPExcel_Cell::columnIndexFromString($column) - 1;
  1459. } else {
  1460. // thaw panes
  1461. return;
  1462. }
  1463. $y = isset($panes[0]) ? $panes[0] : null;
  1464. $x = isset($panes[1]) ? $panes[1] : null;
  1465. $rwTop = isset($panes[2]) ? $panes[2] : null;
  1466. $colLeft = isset($panes[3]) ? $panes[3] : null;
  1467. if (count($panes) > 4) { // if Active pane was received
  1468. $pnnAct = $panes[4];
  1469. } else {
  1470. $pnnAct = null;
  1471. }
  1472. $record = 0x0041; // Record identifier
  1473. $length = 0x000A; // Number of bytes to follow
  1474. // Code specific to frozen or thawed panes.
  1475. if ($this->_phpSheet->getFreezePane()) {
  1476. // Set default values for $rwTop and $colLeft
  1477. if (!isset($rwTop)) {
  1478. $rwTop = $y;
  1479. }
  1480. if (!isset($colLeft)) {
  1481. $colLeft = $x;
  1482. }
  1483. } else {
  1484. // Set default values for $rwTop and $colLeft
  1485. if (!isset($rwTop)) {
  1486. $rwTop = 0;
  1487. }
  1488. if (!isset($colLeft)) {
  1489. $colLeft = 0;
  1490. }
  1491. // Convert Excel's row and column units to the internal units.
  1492. // The default row height is 12.75
  1493. // The default column width is 8.43
  1494. // The following slope and intersection values were interpolated.
  1495. //
  1496. $y = 20*$y + 255;
  1497. $x = 113.879*$x + 390;
  1498. }
  1499. // Determine which pane should be active. There is also the undocumented
  1500. // option to override this should it be necessary: may be removed later.
  1501. //
  1502. if (!isset($pnnAct)) {
  1503. if ($x != 0 && $y != 0) {
  1504. $pnnAct = 0; // Bottom right
  1505. }
  1506. if ($x != 0 && $y == 0) {
  1507. $pnnAct = 1; // Top right
  1508. }
  1509. if ($x == 0 && $y != 0) {
  1510. $pnnAct = 2; // Bottom left
  1511. }
  1512. if ($x == 0 && $y == 0) {
  1513. $pnnAct = 3; // Top left
  1514. }
  1515. }
  1516. $this->_active_pane = $pnnAct; // Used in _writeSelection
  1517. $header = pack("vv", $record, $length);
  1518. $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
  1519. $this->_append($header . $data);
  1520. }
  1521. /**
  1522. * Store the page setup SETUP BIFF record.
  1523. */
  1524. private function _writeSetup()
  1525. {
  1526. $record = 0x00A1; // Record identifier
  1527. $length = 0x0022; // Number of bytes to follow
  1528. $iPaperSize = $this->_phpSheet->getPageSetup()->getPaperSize(); // Paper size
  1529. $iScale = $this->_phpSheet->getPageSetup()->getScale() ?
  1530. $this->_phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
  1531. $iPageStart = 0x01; // Starting page number
  1532. $iFitWidth = (int) $this->_phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
  1533. $iFitHeight = (int) $this->_phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
  1534. $grbit = 0x00; // Option flags
  1535. $iRes = 0x0258; // Print resolution
  1536. $iVRes = 0x0258; // Vertical print resolution
  1537. $numHdr = $this->_phpSheet->getPageMargins()->getHeader(); // Header Margin
  1538. $numFtr = $this->_phpSheet->getPageMargins()->getFooter(); // Footer Margin
  1539. $iCopies = 0x01; // Number of copies
  1540. $fLeftToRight = 0x0; // Print over then down
  1541. // Page orientation
  1542. $fLandscape = ($this->_phpSheet->getPageSetup()->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ?
  1543. 0x0 : 0x1;
  1544. $fNoPls = 0x0; // Setup not read from printer
  1545. $fNoColor = 0x0; // Print black and white
  1546. $fDraft = 0x0; // Print draft quality
  1547. $fNotes = 0x0; // Print notes
  1548. $fNoOrient = 0x0; // Orientation not set
  1549. $fUsePage = 0x0; // Use custom starting page
  1550. $grbit = $fLeftToRight;
  1551. $grbit |= $fLandscape << 1;
  1552. $grbit |= $fNoPls << 2;
  1553. $grbit |= $fNoColor << 3;
  1554. $grbit |= $fDraft << 4;
  1555. $grbit |= $fNotes << 5;
  1556. $grbit |= $fNoOrient << 6;
  1557. $grbit |= $fUsePage << 7;
  1558. $numHdr = pack("d", $numHdr);
  1559. $numFtr = pack("d", $numFtr);
  1560. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1561. $numHdr = strrev($numHdr);
  1562. $numFtr = strrev($numFtr);
  1563. }
  1564. $header = pack("vv", $record, $length);
  1565. $data1 = pack("vvvvvvvv", $iPaperSize,
  1566. $iScale,
  1567. $iPageStart,
  1568. $iFitWidth,
  1569. $iFitHeight,
  1570. $grbit,
  1571. $iRes,
  1572. $iVRes);
  1573. $data2 = $numHdr.$numFtr;
  1574. $data3 = pack("v", $iCopies);
  1575. $this->_append($header . $data1 . $data2 . $data3);
  1576. }
  1577. /**
  1578. * Store the header caption BIFF record.
  1579. */
  1580. private function _writeHeader()
  1581. {
  1582. $record = 0x0014; // Record identifier
  1583. /* removing for now
  1584. // need to fix character count (multibyte!)
  1585. if (strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
  1586. $str = $this->_phpSheet->getHeaderFooter()->getOddHeader(); // header string
  1587. } else {
  1588. $str = '';
  1589. }
  1590. */
  1591. if ($this->_BIFF_version == 0x0600) {
  1592. $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddHeader());
  1593. $length = strlen($recordData);
  1594. } else {
  1595. $cch = strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()); // Length of header string
  1596. $length = 1 + $cch; // Bytes to follow
  1597. $data = pack("C", $cch);
  1598. $recordData = $data . $this->_phpSheet->getHeaderFooter()->getOddHeader();
  1599. }
  1600. $header = pack("vv", $record, $length);
  1601. $this->_append($header . $recordData);
  1602. }
  1603. /**
  1604. * Store the footer caption BIFF record.
  1605. */
  1606. private function _writeFooter()
  1607. {
  1608. $record = 0x0015; // Record identifier
  1609. /* removing for now
  1610. // need to fix character count (multibyte!)
  1611. if (strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
  1612. $str = $this->_phpSheet->getHeaderFooter()->getOddFooter();
  1613. } else {
  1614. $str = '';
  1615. }
  1616. */
  1617. if ($this->_BIFF_version == 0x0600) {
  1618. $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddFooter());
  1619. $length = strlen($recordData);
  1620. } else {
  1621. $cch = strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()); // Length of footer string
  1622. $length = 1 + $cch;
  1623. $data = pack("C", $cch);
  1624. $recordData = $data . $this->_phpSheet->getHeaderFooter()->getOddFooter();
  1625. }
  1626. $header = pack("vv", $record, $length);
  1627. $this->_append($header . $recordData);
  1628. }
  1629. /**
  1630. * Store the horizontal centering HCENTER BIFF record.
  1631. *
  1632. * @access private
  1633. */
  1634. private function _writeHcenter()
  1635. {
  1636. $record = 0x0083; // Record identifier
  1637. $length = 0x0002; // Bytes to follow
  1638. $fHCenter = $this->_phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
  1639. $header = pack("vv", $record, $length);
  1640. $data = pack("v", $fHCenter);
  1641. $this->_append($header.$data);
  1642. }
  1643. /**
  1644. * Store the vertical centering VCENTER BIFF record.
  1645. */
  1646. private function _writeVcenter()
  1647. {
  1648. $record = 0x0084; // Record identifier
  1649. $length = 0x0002; // Bytes to follow
  1650. $fVCenter = $this->_phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
  1651. $header = pack("vv", $record, $length);
  1652. $data = pack("v", $fVCenter);
  1653. $this->_append($header . $data);
  1654. }
  1655. /**
  1656. * Store the LEFTMARGIN BIFF record.
  1657. */
  1658. private function _writeMarginLeft()
  1659. {
  1660. $record = 0x0026; // Record identifier
  1661. $length = 0x0008; // Bytes to follow
  1662. $margin = $this->_phpSheet->getPageMargins()->getLeft(); // Margin in inches
  1663. $header = pack("vv", $record, $length);
  1664. $data = pack("d", $margin);
  1665. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1666. $data = strrev($data);
  1667. }
  1668. $this->_append($header . $data);
  1669. }
  1670. /**
  1671. * Store the RIGHTMARGIN BIFF record.
  1672. */
  1673. private function _writeMarginRight()
  1674. {
  1675. $record = 0x0027; // Record identifier
  1676. $length = 0x0008; // Bytes to follow
  1677. $margin = $this->_phpSheet->getPageMargins()->getRight(); // Margin in inches
  1678. $header = pack("vv", $record, $length);
  1679. $data = pack("d", $margin);
  1680. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1681. $data = strrev($data);
  1682. }
  1683. $this->_append($header . $data);
  1684. }
  1685. /**
  1686. * Store the TOPMARGIN BIFF record.
  1687. */
  1688. private function _writeMarginTop()
  1689. {
  1690. $record = 0x0028; // Record identifier
  1691. $length = 0x0008; // Bytes to follow
  1692. $margin = $this->_phpSheet->getPageMargins()->getTop(); // Margin in inches
  1693. $header = pack("vv", $record, $length);
  1694. $data = pack("d", $margin);
  1695. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1696. $data = strrev($data);
  1697. }
  1698. $this->_append($header . $data);
  1699. }
  1700. /**
  1701. * Store the BOTTOMMARGIN BIFF record.
  1702. */
  1703. private function _writeMarginBottom()
  1704. {
  1705. $record = 0x0029; // Record identifier
  1706. $length = 0x0008; // Bytes to follow
  1707. $margin = $this->_phpSheet->getPageMargins()->getBottom(); // Margin in inches
  1708. $header = pack("vv", $record, $length);
  1709. $data = pack("d", $margin);
  1710. if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
  1711. $data = strrev($data);
  1712. }
  1713. $this->_append($header . $data);
  1714. }
  1715. /**
  1716. * Write the PRINTHEADERS BIFF record.
  1717. */
  1718. private function _writePrintHeaders()
  1719. {
  1720. $record = 0x002a; // Record identifier
  1721. $length = 0x0002; // Bytes to follow
  1722. $fPrintRwCol = $this->_print_headers; // Boolean flag
  1723. $header = pack("vv", $record, $length);
  1724. $data = pack("v", $fPrintRwCol);
  1725. $this->_append($header . $data);
  1726. }
  1727. /**
  1728. * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
  1729. * GRIDSET record.
  1730. */
  1731. private function _writePrintGridlines()
  1732. {
  1733. $record = 0x002b; // Record identifier
  1734. $length = 0x0002; // Bytes to follow
  1735. $fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
  1736. $header = pack("vv", $record, $length);
  1737. $data = pack("v", $fPrintGrid);
  1738. $this->_append($header . $data);
  1739. }
  1740. /**
  1741. * Write the GRIDSET BIFF record. Must be used in conjunction with the
  1742. * PRINTGRIDLINES record.
  1743. */
  1744. private function _writeGridset()
  1745. {
  1746. $record = 0x0082; // Record identifier
  1747. $length = 0x0002; // Bytes to follow
  1748. $fGridSet = !$this->_phpSheet->getPrintGridlines(); // Boolean flag
  1749. $header = pack("vv", $record, $length);
  1750. $data = pack("v", $fGridSet);
  1751. $this->_append($header . $data);
  1752. }
  1753. /**
  1754. * Write the GUTS BIFF record. This is used to configure the gutter margins
  1755. * where Excel outline symbols are displayed. The visibility of the gutters is
  1756. * controlled by a flag in WSBOOL.
  1757. *
  1758. * @see _writeWsbool()
  1759. */
  1760. private function _writeGuts()
  1761. {
  1762. $record = 0x0080; // Record identifier
  1763. $length = 0x0008; // Bytes to follow
  1764. $dxRwGut = 0x0000; // Size of row gutter
  1765. $dxColGut = 0x0000; // Size of col gutter
  1766. // determine maximum row outline level
  1767. $maxRowOutlineLevel = 0;
  1768. foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) {
  1769. $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
  1770. }
  1771. $col_level = 0;
  1772. // Calculate the maximum column outline level. The equivalent calculation
  1773. // for the row outline level is carried out in _writeRow().
  1774. $colcount = count($this->_colinfo);
  1775. for ($i = 0; $i < $colcount; ++$i) {
  1776. $col_level = max($this->_colinfo[$i][5], $col_level);
  1777. }
  1778. // Set the limits for the outline levels (0 <= x <= 7).
  1779. $col_level = max(0, min($col_level, 7));
  1780. // The displayed level is one greater than the max outline levels
  1781. if ($maxRowOutlineLevel) {
  1782. ++$maxRowOutlineLevel;
  1783. }
  1784. if ($col_level) {
  1785. ++$col_level;
  1786. }
  1787. $header = pack("vv", $record, $length);
  1788. $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
  1789. $this->_append($header.$data);
  1790. }
  1791. /**
  1792. * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
  1793. * with the SETUP record.
  1794. */
  1795. private function _writeWsbool()
  1796. {
  1797. $record = 0x0081; // Record identifier
  1798. $length = 0x0002; // Bytes to follow
  1799. $grbit = 0x0000;
  1800. // The only option that is of interest is the flag for fit to page. So we
  1801. // set all the options in one go.
  1802. //
  1803. // Set the option flags
  1804. $grbit |= 0x0001; // Auto page breaks visible
  1805. if ($this->_outline_style) {
  1806. $grbit |= 0x0020; // Auto outline styles
  1807. }
  1808. if ($this->_phpSheet->getShowSummaryBelow()) {
  1809. $grbit |= 0x0040; // Outline summary below
  1810. }
  1811. if ($this->_phpSheet->getShowSummaryRight()) {
  1812. $grbit |= 0x0080; // Outline summary right
  1813. }
  1814. if ($this->_phpSheet->getPageSetup()->getFitToPage()) {
  1815. $grbit |= 0x0100; // Page setup fit to page
  1816. }
  1817. if ($this->_outline_on) {
  1818. $grbit |= 0x0400; // Outline symbols displayed
  1819. }
  1820. $header = pack("vv", $record, $length);
  1821. $data = pack("v", $grbit);
  1822. $this->_append($header . $data);
  1823. }
  1824. /**
  1825. * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
  1826. */
  1827. private function _writeBreaks()
  1828. {
  1829. // initialize
  1830. $vbreaks = array();
  1831. $hbreaks = array();
  1832. foreach ($this->_phpSheet->getBreaks() as $cell => $breakType) {
  1833. // Fetch coordinates
  1834. $coordinates = PHPExcel_Cell::coordinateFromString($cell);
  1835. // Decide what to do by the type of break
  1836. switch ($breakType) {
  1837. case PHPExcel_Worksheet::BREAK_COLUMN:
  1838. // Add to list of vertical breaks
  1839. $vbreaks[] = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1;
  1840. break;
  1841. case PHPExcel_Worksheet::BREAK_ROW:
  1842. // Add to list of horizontal breaks
  1843. $hbreaks[] = $coordinates[1];
  1844. break;
  1845. case PHPExcel_Worksheet::BREAK_NONE:
  1846. default:
  1847. // Nothing to do
  1848. break;
  1849. }
  1850. }
  1851. //horizontal page breaks
  1852. if (count($hbreaks) > 0) {
  1853. // Sort and filter array of page breaks
  1854. sort($hbreaks, SORT_NUMERIC);
  1855. if ($hbreaks[0] == 0) { // don't use first break if it's 0
  1856. array_shift($hbreaks);
  1857. }
  1858. $record = 0x001b; // Record identifier
  1859. $cbrk = count($hbreaks); // Number of page breaks
  1860. if ($this->_BIFF_version == 0x0600) {
  1861. $length = 2 + 6 * $cbrk; // Bytes to follow
  1862. } else {
  1863. $length = 2 + 2 * $cbrk; // Bytes to follow
  1864. }
  1865. $header = pack("vv", $record, $length);
  1866. $data = pack("v", $cbrk);
  1867. // Append each page break
  1868. foreach ($hbreaks as $hbreak) {
  1869. if ($this->_BIFF_version == 0x0600) {
  1870. $data .= pack("vvv", $hbreak, 0x0000, 0x00ff);
  1871. } else {
  1872. $data .= pack("v", $hbreak);
  1873. }
  1874. }
  1875. $this->_append($header . $data);
  1876. }
  1877. // vertical page breaks
  1878. if (count($vbreaks) > 0) {
  1879. // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
  1880. // It is slightly higher in Excel 97/200, approx. 1026
  1881. $vbreaks = array_slice($vbreaks, 0, 1000);
  1882. // Sort and filter array of page breaks
  1883. sort($vbreaks, SORT_NUMERIC);
  1884. if ($vbreaks[0] == 0) { // don't use first break if it's 0
  1885. array_shift($vbreaks);
  1886. }
  1887. $record = 0x001a; // Record identifier
  1888. $cbrk = count($vbreaks); // Number of page breaks
  1889. if ($this->_BIFF_version == 0x0600) {
  1890. $length = 2 + 6 * $cbrk; // Bytes to follow
  1891. } else {
  1892. $length = 2 + 2 * $cbrk; // Bytes to follow
  1893. }
  1894. $header = pack("vv", $record, $length);
  1895. $data = pack("v", $cbrk);
  1896. // Append each page break
  1897. foreach ($vbreaks as $vbreak) {
  1898. if ($this->_BIFF_version == 0x0600) {
  1899. $data .= pack("vvv", $vbreak, 0x0000, 0xffff);
  1900. } else {
  1901. $data .= pack("v", $vbreak);
  1902. }
  1903. }
  1904. $this->_append($header . $data);
  1905. }
  1906. }
  1907. /**
  1908. * Set the Biff PROTECT record to indicate that the worksheet is protected.
  1909. */
  1910. private function _writeProtect()
  1911. {
  1912. // Exit unless sheet protection has been specified
  1913. if (!$this->_phpSheet->getProtection()->getSheet()) {
  1914. return;
  1915. }
  1916. $record = 0x0012; // Record identifier
  1917. $length = 0x0002; // Bytes to follow
  1918. $fLock = 1; // Worksheet is protected
  1919. $header = pack("vv", $record, $length);
  1920. $data = pack("v", $fLock);
  1921. $this->_append($header.$data);
  1922. }
  1923. /**
  1924. * Write SCENPROTECT
  1925. */
  1926. private function _writeScenProtect()
  1927. {
  1928. // Exit if sheet protection is not active
  1929. if (!$this->_phpSheet->getProtection()->getSheet()) {
  1930. return;
  1931. }
  1932. // Exit if scenarios are not protected
  1933. if (!$this->_phpSheet->getProtection()->getScenarios()) {
  1934. return;
  1935. }
  1936. $record = 0x00DD; // Record identifier
  1937. $length = 0x0002; // Bytes to follow
  1938. $header = pack('vv', $record, $length);
  1939. $data = pack('v', 1);
  1940. $this->_append($header . $data);
  1941. }
  1942. /**
  1943. * Write OBJECTPROTECT
  1944. */
  1945. private function _writeObjectProtect()
  1946. {
  1947. // Exit if sheet protection is not active
  1948. if (!$this->_phpSheet->getProtection()->getSheet()) {
  1949. return;
  1950. }
  1951. // Exit if objects are not protected
  1952. if (!$this->_phpSheet->getProtection()->getObjects()) {
  1953. return;
  1954. }
  1955. $record = 0x0063; // Record identifier
  1956. $length = 0x0002; // Bytes to follow
  1957. $header = pack('vv', $record, $length);
  1958. $data = pack('v', 1);
  1959. $this->_append($header . $data);
  1960. }
  1961. /**
  1962. * Write the worksheet PASSWORD record.
  1963. */
  1964. private function _writePassword()
  1965. {
  1966. // Exit unless sheet protection and password have been specified
  1967. if (!$this->_phpSheet->getProtection()->getSheet() || !$this->_phpSheet->getProtection()->getPassword()) {
  1968. return;
  1969. }
  1970. $record = 0x0013; // Record identifier
  1971. $length = 0x0002; // Bytes to follow
  1972. $wPassword = hexdec($this->_phpSheet->getProtection()->getPassword()); // Encoded password
  1973. $header = pack("vv", $record, $length);
  1974. $data = pack("v", $wPassword);
  1975. $this->_append($header . $data);
  1976. }
  1977. /**
  1978. * Insert a 24bit bitmap image in a worksheet.
  1979. *
  1980. * @access public
  1981. * @param integer $row The row we are going to insert the bitmap into
  1982. * @param integer $col The column we are going to insert the bitmap into
  1983. * @param mixed $bitmap The bitmap filename or GD-image resource
  1984. * @param integer $x The horizontal position (offset) of the image inside the cell.
  1985. * @param integer $y The vertical position (offset) of the image inside the cell.
  1986. * @param float $scale_x The horizontal scale
  1987. * @param float $scale_y The vertical scale
  1988. */
  1989. function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
  1990. {
  1991. $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
  1992. list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
  1993. // Scale the frame of the image.
  1994. $width *= $scale_x;
  1995. $height *= $scale_y;
  1996. // Calculate the vertices of the image and write the OBJ record
  1997. $this->_positionImage($col, $row, $x, $y, $width, $height);
  1998. // Write the IMDATA record to store the bitmap data
  1999. $record = 0x007f;
  2000. $length = 8 + $size;
  2001. $cf = 0x09;
  2002. $env = 0x01;
  2003. $lcb = $size;
  2004. $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
  2005. $this->_append($header.$data);
  2006. }
  2007. /**
  2008. * Calculate the vertices that define the position of the image as required by
  2009. * the OBJ record.
  2010. *
  2011. * +------------+------------+
  2012. * | A | B |
  2013. * +-----+------------+------------+
  2014. * | |(x1,y1) | |
  2015. * | 1 |(A1)._______|______ |
  2016. * | | | | |
  2017. * | | | | |
  2018. * +-----+----| BITMAP |-----+
  2019. * | | | | |
  2020. * | 2 | |______________. |
  2021. * | | | (B2)|
  2022. * | | | (x2,y2)|
  2023. * +---- +------------+------------+
  2024. *
  2025. * Example of a bitmap that covers some of the area from cell A1 to cell B2.
  2026. *
  2027. * Based on the width and height of the bitmap we need to calculate 8 vars:
  2028. * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
  2029. * The width and height of the cells are also variable and have to be taken into
  2030. * account.
  2031. * The values of $col_start and $row_start are passed in from the calling
  2032. * function. The values of $col_end and $row_end are calculated by subtracting
  2033. * the width and height of the bitmap from the width and height of the
  2034. * underlying cells.
  2035. * The vertices are expressed as a percentage of the underlying cell width as
  2036. * follows (rhs values are in pixels):
  2037. *
  2038. * x1 = X / W *1024
  2039. * y1 = Y / H *256
  2040. * x2 = (X-1) / W *1024
  2041. * y2 = (Y-1) / H *256
  2042. *
  2043. * Where: X is distance from the left side of the underlying cell
  2044. * Y is distance from the top of the underlying cell
  2045. * W is the width of the cell
  2046. * H is the height of the cell
  2047. * The SDK incorrectly states that the height should be expressed as a
  2048. * percentage of 1024.
  2049. *
  2050. * @access private
  2051. * @param integer $col_start Col containing upper left corner of object
  2052. * @param integer $row_start Row containing top left corner of object
  2053. * @param integer $x1 Distance to left side of object
  2054. * @param integer $y1 Distance to top of object
  2055. * @param integer $width Width of image frame
  2056. * @param integer $height Height of image frame
  2057. */
  2058. function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
  2059. {
  2060. // Initialise end cell to the same as the start cell
  2061. $col_end = $col_start; // Col containing lower right corner of object
  2062. $row_end = $row_start; // Row containing bottom right corner of object
  2063. // Zero the specified offset if greater than the cell dimensions
  2064. if ($x1 >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) {
  2065. $x1 = 0;
  2066. }
  2067. if ($y1 >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1)) {
  2068. $y1 = 0;
  2069. }
  2070. $width = $width + $x1 -1;
  2071. $height = $height + $y1 -1;
  2072. // Subtract the underlying cell widths to find the end cell of the image
  2073. while ($width >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) {
  2074. $width -= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end));
  2075. ++$col_end;
  2076. }
  2077. // Subtract the underlying cell heights to find the end cell of the image
  2078. while ($height >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1)) {
  2079. $height -= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1);
  2080. ++$row_end;
  2081. }
  2082. // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
  2083. // with zero eight or width.
  2084. //
  2085. if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) {
  2086. return;
  2087. }
  2088. if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) {
  2089. return;
  2090. }
  2091. if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) == 0) {
  2092. return;
  2093. }
  2094. if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) == 0) {
  2095. return;
  2096. }
  2097. // Convert the pixel values to the percentage value expected by Excel
  2098. $x1 = $x1 / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024;
  2099. $y1 = $y1 / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) * 256;
  2100. $x2 = $width / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
  2101. $y2 = $height / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) * 256; // Distance to bottom of object
  2102. $this->_writeObjPicture($col_start, $x1,
  2103. $row_start, $y1,
  2104. $col_end, $x2,
  2105. $row_end, $y2);
  2106. }
  2107. /**
  2108. * Store the OBJ record that precedes an IMDATA record. This could be generalise
  2109. * to support other Excel objects.
  2110. *
  2111. * @param integer $colL Column containing upper left corner of object
  2112. * @param integer $dxL Distance from left side of cell
  2113. * @param integer $rwT Row containing top left corner of object
  2114. * @param integer $dyT Distance from top of cell
  2115. * @param integer $colR Column containing lower right corner of object
  2116. * @param integer $dxR Distance from right of cell
  2117. * @param integer $rwB Row containing bottom right corner of object
  2118. * @param integer $dyB Distance from bottom of cell
  2119. */
  2120. private function _writeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
  2121. {
  2122. $record = 0x005d; // Record identifier
  2123. $length = 0x003c; // Bytes to follow
  2124. $cObj = 0x0001; // Count of objects in file (set to 1)
  2125. $OT = 0x0008; // Object type. 8 = Picture
  2126. $id = 0x0001; // Object ID
  2127. $grbit = 0x0614; // Option flags
  2128. $cbMacro = 0x0000; // Length of FMLA structure
  2129. $Reserved1 = 0x0000; // Reserved
  2130. $Reserved2 = 0x0000; // Reserved
  2131. $icvBack = 0x09; // Background colour
  2132. $icvFore = 0x09; // Foreground colour
  2133. $fls = 0x00; // Fill pattern
  2134. $fAuto = 0x00; // Automatic fill
  2135. $icv = 0x08; // Line colour
  2136. $lns = 0xff; // Line style
  2137. $lnw = 0x01; // Line weight
  2138. $fAutoB = 0x00; // Automatic border
  2139. $frs = 0x0000; // Frame style
  2140. $cf = 0x0009; // Image format, 9 = bitmap
  2141. $Reserved3 = 0x0000; // Reserved
  2142. $cbPictFmla = 0x0000; // Length of FMLA structure
  2143. $Reserved4 = 0x0000; // Reserved
  2144. $grbit2 = 0x0001; // Option flags
  2145. $Reserved5 = 0x0000; // Reserved
  2146. $header = pack("vv", $record, $length);
  2147. $data = pack("V", $cObj);
  2148. $data .= pack("v", $OT);
  2149. $data .= pack("v", $id);
  2150. $data .= pack("v", $grbit);
  2151. $data .= pack("v", $colL);
  2152. $data .= pack("v", $dxL);
  2153. $data .= pack("v", $rwT);
  2154. $data .= pack("v", $dyT);
  2155. $data .= pack("v", $colR);
  2156. $data .= pack("v", $dxR);
  2157. $data .= pack("v", $rwB);
  2158. $data .= pack("v", $dyB);
  2159. $data .= pack("v", $cbMacro);
  2160. $data .= pack("V", $Reserved1);
  2161. $data .= pack("v", $Reserved2);
  2162. $data .= pack("C", $icvBack);
  2163. $data .= pack("C", $icvFore);
  2164. $data .= pack("C", $fls);
  2165. $data .= pack("C", $fAuto);
  2166. $data .= pack("C", $icv);
  2167. $data .= pack("C", $lns);
  2168. $data .= pack("C", $lnw);
  2169. $data .= pack("C", $fAutoB);
  2170. $data .= pack("v", $frs);
  2171. $data .= pack("V", $cf);
  2172. $data .= pack("v", $Reserved3);
  2173. $data .= pack("v", $cbPictFmla);
  2174. $data .= pack("v", $Reserved4);
  2175. $data .= pack("v", $grbit2);
  2176. $data .= pack("V", $Reserved5);
  2177. $this->_append($header . $data);
  2178. }
  2179. /**
  2180. * Convert a GD-image into the internal format.
  2181. *
  2182. * @access private
  2183. * @param resource $image The image to process
  2184. * @return array Array with data and properties of the bitmap
  2185. */
  2186. function _processBitmapGd($image) {
  2187. $width = imagesx($image);
  2188. $height = imagesy($image);
  2189. $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  2190. for ($j=$height; $j--; ) {
  2191. for ($i=0; $i < $width; ++$i) {
  2192. $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
  2193. foreach (array("red", "green", "blue") as $key) {
  2194. $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
  2195. }
  2196. $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
  2197. }
  2198. if (3*$width % 4) {
  2199. $data .= str_repeat("\x00", 4 - 3*$width % 4);
  2200. }
  2201. }
  2202. return array($width, $height, strlen($data), $data);
  2203. }
  2204. /**
  2205. * Convert a 24 bit bitmap into the modified internal format used by Windows.
  2206. * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
  2207. * MSDN library.
  2208. *
  2209. * @access private
  2210. * @param string $bitmap The bitmap to process
  2211. * @return array Array with data and properties of the bitmap
  2212. */
  2213. function _processBitmap($bitmap)
  2214. {
  2215. // Open file.
  2216. $bmp_fd = @fopen($bitmap,"rb");
  2217. if (!$bmp_fd) {
  2218. throw new Exception("Couldn't import $bitmap");
  2219. }
  2220. // Slurp the file into a string.
  2221. $data = fread($bmp_fd, filesize($bitmap));
  2222. // Check that the file is big enough to be a bitmap.
  2223. if (strlen($data) <= 0x36) {
  2224. throw new Exception("$bitmap doesn't contain enough data.\n");
  2225. }
  2226. // The first 2 bytes are used to identify the bitmap.
  2227. $identity = unpack("A2ident", $data);
  2228. if ($identity['ident'] != "BM") {
  2229. throw new Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
  2230. }
  2231. // Remove bitmap data: ID.
  2232. $data = substr($data, 2);
  2233. // Read and remove the bitmap size. This is more reliable than reading
  2234. // the data size at offset 0x22.
  2235. //
  2236. $size_array = unpack("Vsa", substr($data, 0, 4));
  2237. $size = $size_array['sa'];
  2238. $data = substr($data, 4);
  2239. $size -= 0x36; // Subtract size of bitmap header.
  2240. $size += 0x0C; // Add size of BIFF header.
  2241. // Remove bitmap data: reserved, offset, header length.
  2242. $data = substr($data, 12);
  2243. // Read and remove the bitmap width and height. Verify the sizes.
  2244. $width_and_height = unpack("V2", substr($data, 0, 8));
  2245. $width = $width_and_height[1];
  2246. $height = $width_and_height[2];
  2247. $data = substr($data, 8);
  2248. if ($width > 0xFFFF) {
  2249. throw new Exception("$bitmap: largest image width supported is 65k.\n");
  2250. }
  2251. if ($height > 0xFFFF) {
  2252. throw new Exception("$bitmap: largest image height supported is 65k.\n");
  2253. }
  2254. // Read and remove the bitmap planes and bpp data. Verify them.
  2255. $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
  2256. $data = substr($data, 4);
  2257. if ($planes_and_bitcount[2] != 24) { // Bitcount
  2258. throw new Exception("$bitmap isn't a 24bit true color bitmap.\n");
  2259. }
  2260. if ($planes_and_bitcount[1] != 1) {
  2261. throw new Exception("$bitmap: only 1 plane supported in bitmap image.\n");
  2262. }
  2263. // Read and remove the bitmap compression. Verify compression.
  2264. $compression = unpack("Vcomp", substr($data, 0, 4));
  2265. $data = substr($data, 4);
  2266. //$compression = 0;
  2267. if ($compression['comp'] != 0) {
  2268. throw new Exception("$bitmap: compression not supported in bitmap image.\n");
  2269. }
  2270. // Remove bitmap data: data size, hres, vres, colours, imp. colours.
  2271. $data = substr($data, 20);
  2272. // Add the BITMAPCOREHEADER data
  2273. $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
  2274. $data = $header . $data;
  2275. return (array($width, $height, $size, $data));
  2276. }
  2277. /**
  2278. * Store the window zoom factor. This should be a reduced fraction but for
  2279. * simplicity we will store all fractions with a numerator of 100.
  2280. */
  2281. private function _writeZoom()
  2282. {
  2283. // If scale is 100 we don't need to write a record
  2284. if ($this->_phpSheet->getSheetView()->getZoomScale() == 100) {
  2285. return;
  2286. }
  2287. $record = 0x00A0; // Record identifier
  2288. $length = 0x0004; // Bytes to follow
  2289. $header = pack("vv", $record, $length);
  2290. $data = pack("vv", $this->_phpSheet->getSheetView()->getZoomScale(), 100);
  2291. $this->_append($header . $data);
  2292. }
  2293. /**
  2294. * Get Escher object
  2295. *
  2296. * @return PHPExcel_Shared_Escher
  2297. */
  2298. public function getEscher()
  2299. {
  2300. return $this->_escher;
  2301. }
  2302. /**
  2303. * Set Escher object
  2304. *
  2305. * @param PHPExcel_Shared_Escher $pValue
  2306. */
  2307. public function setEscher(PHPExcel_Shared_Escher $pValue = null)
  2308. {
  2309. $this->_escher = $pValue;
  2310. }
  2311. /**
  2312. * Write MSODRAWING record
  2313. */
  2314. private function _writeMsoDrawing()
  2315. {
  2316. // write the Escher stream if necessary
  2317. if (isset($this->_escher)) {
  2318. $writer = new PHPExcel_Writer_Excel5_Escher($this->_escher);
  2319. $data = $writer->close();
  2320. $spOffsets = $writer->getSpOffsets();
  2321. // write the neccesary MSODRAWING, OBJ records
  2322. // split the Escher stream
  2323. $spOffsets[0] = 0;
  2324. $nm = count($spOffsets) - 1; // number of shapes excluding first shape
  2325. for ($i = 1; $i <= $nm; ++$i) {
  2326. // MSODRAWING record
  2327. $record = 0x00EC; // Record identifier
  2328. // chunk of Escher stream for one shape
  2329. $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);
  2330. $length = strlen($dataChunk);
  2331. $header = pack("vv", $record, $length);
  2332. $this->_append($header . $dataChunk);
  2333. // OBJ record
  2334. $record = 0x005D; // record identifier
  2335. $objData = '';
  2336. // ftCmo
  2337. $objData .=
  2338. pack('vvvvvVVV'
  2339. , 0x0015 // 0x0015 = ftCmo
  2340. , 0x0012 // length of ftCmo data
  2341. , 0x0008 // object type, 0x0008 = picture
  2342. , $i // object id number, Excel seems to use 1-based index, local for the sheet
  2343. , 0x6011 // option flags, 0x6011 is what OpenOffice.org uses
  2344. , 0 // reserved
  2345. , 0 // reserved
  2346. , 0 // reserved
  2347. );
  2348. // ftEnd
  2349. $objData .=
  2350. pack('vv'
  2351. , 0x0000 // 0x0000 = ftEnd
  2352. , 0x0000 // length of ftEnd data
  2353. );
  2354. $length = strlen($objData);
  2355. $header = pack('vv', $record, $length);
  2356. $this->_append($header . $objData);
  2357. }
  2358. }
  2359. }
  2360. /**
  2361. * Store the DATAVALIDATIONS and DATAVALIDATION records.
  2362. */
  2363. private function _writeDataValidity()
  2364. {
  2365. // Datavalidation collection
  2366. $dataValidationCollection = $this->_phpSheet->getDataValidationCollection();
  2367. // Write data validations?
  2368. if (count($dataValidationCollection) > 0) {
  2369. // DATAVALIDATIONS record
  2370. $record = 0x01B2; // Record identifier
  2371. $length = 0x0012; // Bytes to follow
  2372. $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
  2373. $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
  2374. $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
  2375. $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
  2376. $header = pack('vv', $record, $length);
  2377. $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
  2378. count($dataValidationCollection));
  2379. $this->_append($header.$data);
  2380. // DATAVALIDATION records
  2381. $record = 0x01BE; // Record identifier
  2382. foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
  2383. // initialize record data
  2384. $data = '';
  2385. // options
  2386. $options = 0x00000000;
  2387. // data type
  2388. $type = $dataValidation->getType();
  2389. switch ($type) {
  2390. case PHPExcel_Cell_DataValidation::TYPE_NONE: $type = 0x00; break;
  2391. case PHPExcel_Cell_DataValidation::TYPE_WHOLE: $type = 0x01; break;
  2392. case PHPExcel_Cell_DataValidation::TYPE_DECIMAL: $type = 0x02; break;
  2393. case PHPExcel_Cell_DataValidation::TYPE_LIST: $type = 0x03; break;
  2394. case PHPExcel_Cell_DataValidation::TYPE_DATE: $type = 0x04; break;
  2395. case PHPExcel_Cell_DataValidation::TYPE_TIME: $type = 0x05; break;
  2396. case PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH: $type = 0x06; break;
  2397. case PHPExcel_Cell_DataValidation::TYPE_CUSTOM: $type = 0x07; break;
  2398. }
  2399. $options |= $type << 0;
  2400. // error style
  2401. $errorStyle = $dataValidation->getType();
  2402. switch ($errorStyle) {
  2403. case PHPExcel_Cell_DataValidation::STYLE_STOP: $errorStyle = 0x00; break;
  2404. case PHPExcel_Cell_DataValidation::STYLE_WARNING: $errorStyle = 0x01; break;
  2405. case PHPExcel_Cell_DataValidation::STYLE_INFORMATION: $errorStyle = 0x02; break;
  2406. }
  2407. $options |= $errorStyle << 4;
  2408. // explicit formula?
  2409. if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
  2410. $options |= 0x01 << 7;
  2411. }
  2412. // empty cells allowed
  2413. $options |= $dataValidation->getAllowBlank() << 8;
  2414. // show drop down
  2415. $options |= (!$dataValidation->getShowDropDown()) << 9;
  2416. // show input message
  2417. $options |= $dataValidation->getShowInputMessage() << 18;
  2418. // show error message
  2419. $options |= $dataValidation->getShowErrorMessage() << 19;
  2420. // condition operator
  2421. $operator = $dataValidation->getOperator();
  2422. switch ($operator) {
  2423. case PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN: $operator = 0x00 ; break;
  2424. case PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN: $operator = 0x01 ; break;
  2425. case PHPExcel_Cell_DataValidation::OPERATOR_EQUAL: $operator = 0x02 ; break;
  2426. case PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL: $operator = 0x03 ; break;
  2427. case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN: $operator = 0x04 ; break;
  2428. case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN: $operator = 0x05 ; break;
  2429. case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL: $operator = 0x06; break;
  2430. case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL: $operator = 0x07 ; break;
  2431. }
  2432. $options |= $operator << 20;
  2433. $data = pack('V', $options);
  2434. // prompt title
  2435. $promptTitle = $dataValidation->getPromptTitle() !== '' ?
  2436. $dataValidation->getPromptTitle() : chr(0);
  2437. $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($promptTitle);
  2438. // error title
  2439. $errorTitle = $dataValidation->getErrorTitle() !== '' ?
  2440. $dataValidation->getErrorTitle() : chr(0);
  2441. $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($errorTitle);
  2442. // prompt text
  2443. $prompt = $dataValidation->getPrompt() !== '' ?
  2444. $dataValidation->getPrompt() : chr(0);
  2445. $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($prompt);
  2446. // error text
  2447. $error = $dataValidation->getError() !== '' ?
  2448. $dataValidation->getError() : chr(0);
  2449. $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($error);
  2450. // formula 1
  2451. try {
  2452. $formula1 = $dataValidation->getFormula1();
  2453. if ($type == 0x03) { // list type
  2454. $formula1 = str_replace(',', chr(0), $formula1);
  2455. }
  2456. $this->_parser->parse($formula1);
  2457. $formula1 = $this->_parser->toReversePolish();
  2458. $sz1 = strlen($formula1);
  2459. } catch(Exception $e) {
  2460. $sz1 = 0;
  2461. $formula1 = '';
  2462. }
  2463. $data .= pack('vv', $sz1, 0x0000);
  2464. $data .= $formula1;
  2465. // formula 2
  2466. try {
  2467. $formula2 = $dataValidation->getFormula2();
  2468. if ($formula2 === '') {
  2469. throw new Exception('No formula2');
  2470. }
  2471. $this->_parser->parse($formula2);
  2472. $formula2 = $this->_parser->toReversePolish();
  2473. $sz2 = strlen($formula2);
  2474. } catch(Exception $e) {
  2475. $sz2 = 0;
  2476. $formula2 = '';
  2477. }
  2478. $data .= pack('vv', $sz2, 0x0000);
  2479. $data .= $formula2;
  2480. // cell range address list
  2481. $data .= pack('v', 0x0001);
  2482. $data .= $this->_writeBIFF8CellRangeAddressFixed($cellCoordinate);
  2483. $length = strlen($data);
  2484. $header = pack("vv", $record, $length);
  2485. $this->_append($header . $data);
  2486. }
  2487. }
  2488. }
  2489. /**
  2490. * Map Error code
  2491. */
  2492. private function _mapErrorCode($errorCode) {
  2493. switch ($errorCode) {
  2494. case '#NULL!': return 0x00;
  2495. case '#DIV/0!': return 0x07;
  2496. case '#VALUE!': return 0x0F;
  2497. case '#REF!': return 0x17;
  2498. case '#NAME?': return 0x1D;
  2499. case '#NUM!': return 0x24;
  2500. case '#N/A': return 0x2A;
  2501. }
  2502. return 0;
  2503. }
  2504. }