PageRenderTime 140ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

/common/libraries/plugin/phpexcel/PHPExcel/Writer/Excel5/Worksheet.php

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