PageRenderTime 95ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/Classes/PHPExcel/Reader/Excel5.php

https://bitbucket.org/amorello/changeover
PHP | 6890 lines | 3878 code | 1141 blank | 1871 comment | 502 complexity | 6aafac239786f82d527d72cb8c0222e4 MD5 | raw file
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2012 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Reader_Excel5
  23. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.7.8, 2012-10-12
  26. */
  27. // Original file header of ParseXL (used as the base for this class):
  28. // --------------------------------------------------------------------------------
  29. // Adapted from Excel_Spreadsheet_Reader developed by users bizon153,
  30. // trex005, and mmp11 (SourceForge.net)
  31. // http://sourceforge.net/projects/phpexcelreader/
  32. // Primary changes made by canyoncasa (dvc) for ParseXL 1.00 ...
  33. // Modelled moreso after Perl Excel Parse/Write modules
  34. // Added Parse_Excel_Spreadsheet object
  35. // Reads a whole worksheet or tab as row,column array or as
  36. // associated hash of indexed rows and named column fields
  37. // Added variables for worksheet (tab) indexes and names
  38. // Added an object call for loading individual woorksheets
  39. // Changed default indexing defaults to 0 based arrays
  40. // Fixed date/time and percent formats
  41. // Includes patches found at SourceForge...
  42. // unicode patch by nobody
  43. // unpack("d") machine depedency patch by matchy
  44. // boundsheet utf16 patch by bjaenichen
  45. // Renamed functions for shorter names
  46. // General code cleanup and rigor, including <80 column width
  47. // Included a testcase Excel file and PHP example calls
  48. // Code works for PHP 5.x
  49. // Primary changes made by canyoncasa (dvc) for ParseXL 1.10 ...
  50. // http://sourceforge.net/tracker/index.php?func=detail&aid=1466964&group_id=99160&atid=623334
  51. // Decoding of formula conditions, results, and tokens.
  52. // Support for user-defined named cells added as an array "namedcells"
  53. // Patch code for user-defined named cells supports single cells only.
  54. // NOTE: this patch only works for BIFF8 as BIFF5-7 use a different
  55. // external sheet reference structure
  56. /** PHPExcel root directory */
  57. if (!defined('PHPEXCEL_ROOT')) {
  58. /**
  59. * @ignore
  60. */
  61. define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
  62. require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
  63. }
  64. /**
  65. * PHPExcel_Reader_Excel5
  66. *
  67. * This class uses {@link http://sourceforge.net/projects/phpexcelreader/parseXL}
  68. *
  69. * @category PHPExcel
  70. * @package PHPExcel_Reader_Excel5
  71. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  72. */
  73. class PHPExcel_Reader_Excel5 implements PHPExcel_Reader_IReader
  74. {
  75. // ParseXL definitions
  76. const XLS_BIFF8 = 0x0600;
  77. const XLS_BIFF7 = 0x0500;
  78. const XLS_WorkbookGlobals = 0x0005;
  79. const XLS_Worksheet = 0x0010;
  80. // record identifiers
  81. const XLS_Type_FORMULA = 0x0006;
  82. const XLS_Type_EOF = 0x000a;
  83. const XLS_Type_PROTECT = 0x0012;
  84. const XLS_Type_OBJECTPROTECT = 0x0063;
  85. const XLS_Type_SCENPROTECT = 0x00dd;
  86. const XLS_Type_PASSWORD = 0x0013;
  87. const XLS_Type_HEADER = 0x0014;
  88. const XLS_Type_FOOTER = 0x0015;
  89. const XLS_Type_EXTERNSHEET = 0x0017;
  90. const XLS_Type_DEFINEDNAME = 0x0018;
  91. const XLS_Type_VERTICALPAGEBREAKS = 0x001a;
  92. const XLS_Type_HORIZONTALPAGEBREAKS = 0x001b;
  93. const XLS_Type_NOTE = 0x001c;
  94. const XLS_Type_SELECTION = 0x001d;
  95. const XLS_Type_DATEMODE = 0x0022;
  96. const XLS_Type_EXTERNNAME = 0x0023;
  97. const XLS_Type_LEFTMARGIN = 0x0026;
  98. const XLS_Type_RIGHTMARGIN = 0x0027;
  99. const XLS_Type_TOPMARGIN = 0x0028;
  100. const XLS_Type_BOTTOMMARGIN = 0x0029;
  101. const XLS_Type_PRINTGRIDLINES = 0x002b;
  102. const XLS_Type_FILEPASS = 0x002f;
  103. const XLS_Type_FONT = 0x0031;
  104. const XLS_Type_CONTINUE = 0x003c;
  105. const XLS_Type_PANE = 0x0041;
  106. const XLS_Type_CODEPAGE = 0x0042;
  107. const XLS_Type_DEFCOLWIDTH = 0x0055;
  108. const XLS_Type_OBJ = 0x005d;
  109. const XLS_Type_COLINFO = 0x007d;
  110. const XLS_Type_IMDATA = 0x007f;
  111. const XLS_Type_SHEETPR = 0x0081;
  112. const XLS_Type_HCENTER = 0x0083;
  113. const XLS_Type_VCENTER = 0x0084;
  114. const XLS_Type_SHEET = 0x0085;
  115. const XLS_Type_PALETTE = 0x0092;
  116. const XLS_Type_SCL = 0x00a0;
  117. const XLS_Type_PAGESETUP = 0x00a1;
  118. const XLS_Type_MULRK = 0x00bd;
  119. const XLS_Type_MULBLANK = 0x00be;
  120. const XLS_Type_DBCELL = 0x00d7;
  121. const XLS_Type_XF = 0x00e0;
  122. const XLS_Type_MERGEDCELLS = 0x00e5;
  123. const XLS_Type_MSODRAWINGGROUP = 0x00eb;
  124. const XLS_Type_MSODRAWING = 0x00ec;
  125. const XLS_Type_SST = 0x00fc;
  126. const XLS_Type_LABELSST = 0x00fd;
  127. const XLS_Type_EXTSST = 0x00ff;
  128. const XLS_Type_EXTERNALBOOK = 0x01ae;
  129. const XLS_Type_DATAVALIDATIONS = 0x01b2;
  130. const XLS_Type_TXO = 0x01b6;
  131. const XLS_Type_HYPERLINK = 0x01b8;
  132. const XLS_Type_DATAVALIDATION = 0x01be;
  133. const XLS_Type_DIMENSION = 0x0200;
  134. const XLS_Type_BLANK = 0x0201;
  135. const XLS_Type_NUMBER = 0x0203;
  136. const XLS_Type_LABEL = 0x0204;
  137. const XLS_Type_BOOLERR = 0x0205;
  138. const XLS_Type_STRING = 0x0207;
  139. const XLS_Type_ROW = 0x0208;
  140. const XLS_Type_INDEX = 0x020b;
  141. const XLS_Type_ARRAY = 0x0221;
  142. const XLS_Type_DEFAULTROWHEIGHT = 0x0225;
  143. const XLS_Type_WINDOW2 = 0x023e;
  144. const XLS_Type_RK = 0x027e;
  145. const XLS_Type_STYLE = 0x0293;
  146. const XLS_Type_FORMAT = 0x041e;
  147. const XLS_Type_SHAREDFMLA = 0x04bc;
  148. const XLS_Type_BOF = 0x0809;
  149. const XLS_Type_SHEETPROTECTION = 0x0867;
  150. const XLS_Type_RANGEPROTECTION = 0x0868;
  151. const XLS_Type_SHEETLAYOUT = 0x0862;
  152. const XLS_Type_XFEXT = 0x087d;
  153. const XLS_Type_UNKNOWN = 0xffff;
  154. /**
  155. * Read data only?
  156. * Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
  157. * or whether it should read both data and formatting
  158. *
  159. * @var boolean
  160. */
  161. private $_readDataOnly = false;
  162. /**
  163. * Restrict which sheets should be loaded?
  164. * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
  165. *
  166. * @var array of string
  167. */
  168. private $_loadSheetsOnly = null;
  169. /**
  170. * PHPExcel_Reader_IReadFilter instance
  171. *
  172. * @var PHPExcel_Reader_IReadFilter
  173. */
  174. private $_readFilter = null;
  175. /**
  176. * Summary Information stream data.
  177. *
  178. * @var string
  179. */
  180. private $_summaryInformation;
  181. /**
  182. * Extended Summary Information stream data.
  183. *
  184. * @var string
  185. */
  186. private $_documentSummaryInformation;
  187. /**
  188. * User-Defined Properties stream data.
  189. *
  190. * @var string
  191. */
  192. private $_userDefinedProperties;
  193. /**
  194. * Workbook stream data. (Includes workbook globals substream as well as sheet substreams)
  195. *
  196. * @var string
  197. */
  198. private $_data;
  199. /**
  200. * Size in bytes of $this->_data
  201. *
  202. * @var int
  203. */
  204. private $_dataSize;
  205. /**
  206. * Current position in stream
  207. *
  208. * @var integer
  209. */
  210. private $_pos;
  211. /**
  212. * Workbook to be returned by the reader.
  213. *
  214. * @var PHPExcel
  215. */
  216. private $_phpExcel;
  217. /**
  218. * Worksheet that is currently being built by the reader.
  219. *
  220. * @var PHPExcel_Worksheet
  221. */
  222. private $_phpSheet;
  223. /**
  224. * BIFF version
  225. *
  226. * @var int
  227. */
  228. private $_version;
  229. /**
  230. * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95)
  231. * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE'
  232. *
  233. * @var string
  234. */
  235. private $_codepage;
  236. /**
  237. * Shared formats
  238. *
  239. * @var array
  240. */
  241. private $_formats;
  242. /**
  243. * Shared fonts
  244. *
  245. * @var array
  246. */
  247. private $_objFonts;
  248. /**
  249. * Color palette
  250. *
  251. * @var array
  252. */
  253. private $_palette;
  254. /**
  255. * Worksheets
  256. *
  257. * @var array
  258. */
  259. private $_sheets;
  260. /**
  261. * External books
  262. *
  263. * @var array
  264. */
  265. private $_externalBooks;
  266. /**
  267. * REF structures. Only applies to BIFF8.
  268. *
  269. * @var array
  270. */
  271. private $_ref;
  272. /**
  273. * External names
  274. *
  275. * @var array
  276. */
  277. private $_externalNames;
  278. /**
  279. * Defined names
  280. *
  281. * @var array
  282. */
  283. private $_definedname;
  284. /**
  285. * Shared strings. Only applies to BIFF8.
  286. *
  287. * @var array
  288. */
  289. private $_sst;
  290. /**
  291. * Panes are frozen? (in sheet currently being read). See WINDOW2 record.
  292. *
  293. * @var boolean
  294. */
  295. private $_frozen;
  296. /**
  297. * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record.
  298. *
  299. * @var boolean
  300. */
  301. private $_isFitToPages;
  302. /**
  303. * Objects. One OBJ record contributes with one entry.
  304. *
  305. * @var array
  306. */
  307. private $_objs;
  308. /**
  309. * Text Objects. One TXO record corresponds with one entry.
  310. *
  311. * @var array
  312. */
  313. private $_textObjects;
  314. /**
  315. * Cell Annotations (BIFF8)
  316. *
  317. * @var array
  318. */
  319. private $_cellNotes;
  320. /**
  321. * The combined MSODRAWINGGROUP data
  322. *
  323. * @var string
  324. */
  325. private $_drawingGroupData;
  326. /**
  327. * The combined MSODRAWING data (per sheet)
  328. *
  329. * @var string
  330. */
  331. private $_drawingData;
  332. /**
  333. * Keep track of XF index
  334. *
  335. * @var int
  336. */
  337. private $_xfIndex;
  338. /**
  339. * Mapping of XF index (that is a cell XF) to final index in cellXf collection
  340. *
  341. * @var array
  342. */
  343. private $_mapCellXfIndex;
  344. /**
  345. * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection
  346. *
  347. * @var array
  348. */
  349. private $_mapCellStyleXfIndex;
  350. /**
  351. * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value.
  352. *
  353. * @var array
  354. */
  355. private $_sharedFormulas;
  356. /**
  357. * The shared formula parts in a sheet. One FORMULA record contributes with one value if it
  358. * refers to a shared formula.
  359. *
  360. * @var array
  361. */
  362. private $_sharedFormulaParts;
  363. /**
  364. * Create a new PHPExcel_Reader_Excel5 instance
  365. */
  366. public function __construct() {
  367. $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter();
  368. }
  369. /**
  370. * Read data only?
  371. * If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
  372. * If false (the default) it will read data and formatting.
  373. *
  374. * @return boolean
  375. */
  376. public function getReadDataOnly()
  377. {
  378. return $this->_readDataOnly;
  379. }
  380. /**
  381. * Set read data only
  382. * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
  383. * Set to false (the default) to advise the Reader to read both data and formatting for cells.
  384. *
  385. * @param boolean $pValue
  386. *
  387. * @return PHPExcel_Reader_Excel5
  388. */
  389. public function setReadDataOnly($pValue = false)
  390. {
  391. $this->_readDataOnly = $pValue;
  392. return $this;
  393. }
  394. /**
  395. * Get which sheets to load
  396. * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
  397. * indicating that all worksheets in the workbook should be loaded.
  398. *
  399. * @return mixed
  400. */
  401. public function getLoadSheetsOnly()
  402. {
  403. return $this->_loadSheetsOnly;
  404. }
  405. /**
  406. * Set which sheets to load
  407. *
  408. * @param mixed $value
  409. * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
  410. * If NULL, then it tells the Reader to read all worksheets in the workbook
  411. *
  412. * @return PHPExcel_Reader_Excel5
  413. */
  414. public function setLoadSheetsOnly($value = null)
  415. {
  416. $this->_loadSheetsOnly = is_array($value) ?
  417. $value : array($value);
  418. return $this;
  419. }
  420. /**
  421. * Set all sheets to load
  422. * Tells the Reader to load all worksheets from the workbook.
  423. *
  424. * @return PHPExcel_Reader_Excel5
  425. */
  426. public function setLoadAllSheets()
  427. {
  428. $this->_loadSheetsOnly = null;
  429. return $this;
  430. }
  431. /**
  432. * Read filter
  433. *
  434. * @return PHPExcel_Reader_IReadFilter
  435. */
  436. public function getReadFilter() {
  437. return $this->_readFilter;
  438. }
  439. /**
  440. * Set read filter
  441. *
  442. * @param PHPExcel_Reader_IReadFilter $pValue
  443. * @return PHPExcel_Reader_Excel5
  444. */
  445. public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
  446. $this->_readFilter = $pValue;
  447. return $this;
  448. }
  449. /**
  450. * Can the current PHPExcel_Reader_IReader read the file?
  451. *
  452. * @param string $pFileName
  453. * @return boolean
  454. * @throws Exception
  455. */
  456. public function canRead($pFilename)
  457. {
  458. // Check if file exists
  459. if (!file_exists($pFilename)) {
  460. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  461. }
  462. try {
  463. // Use ParseXL for the hard work.
  464. $ole = new PHPExcel_Shared_OLERead();
  465. // get excel data
  466. $res = $ole->read($pFilename);
  467. return true;
  468. } catch (Exception $e) {
  469. return false;
  470. }
  471. }
  472. /**
  473. * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
  474. *
  475. * @param string $pFilename
  476. * @throws Exception
  477. */
  478. public function listWorksheetNames($pFilename)
  479. {
  480. // Check if file exists
  481. if (!file_exists($pFilename)) {
  482. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  483. }
  484. $worksheetNames = array();
  485. // Read the OLE file
  486. $this->_loadOLE($pFilename);
  487. // total byte size of Excel data (workbook global substream + sheet substreams)
  488. $this->_dataSize = strlen($this->_data);
  489. $this->_pos = 0;
  490. $this->_sheets = array();
  491. // Parse Workbook Global Substream
  492. while ($this->_pos < $this->_dataSize) {
  493. $code = self::_GetInt2d($this->_data, $this->_pos);
  494. switch ($code) {
  495. case self::XLS_Type_BOF: $this->_readBof(); break;
  496. case self::XLS_Type_SHEET: $this->_readSheet(); break;
  497. case self::XLS_Type_EOF: $this->_readDefault(); break 2;
  498. default: $this->_readDefault(); break;
  499. }
  500. }
  501. foreach ($this->_sheets as $sheet) {
  502. if ($sheet['sheetType'] != 0x00) {
  503. // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
  504. continue;
  505. }
  506. $worksheetNames[] = $sheet['name'];
  507. }
  508. return $worksheetNames;
  509. }
  510. /**
  511. * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
  512. *
  513. * @param string $pFilename
  514. * @throws Exception
  515. */
  516. public function listWorksheetInfo($pFilename)
  517. {
  518. // Check if file exists
  519. if (!file_exists($pFilename)) {
  520. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  521. }
  522. $worksheetInfo = array();
  523. // Read the OLE file
  524. $this->_loadOLE($pFilename);
  525. // total byte size of Excel data (workbook global substream + sheet substreams)
  526. $this->_dataSize = strlen($this->_data);
  527. // initialize
  528. $this->_pos = 0;
  529. $this->_sheets = array();
  530. // Parse Workbook Global Substream
  531. while ($this->_pos < $this->_dataSize) {
  532. $code = self::_GetInt2d($this->_data, $this->_pos);
  533. switch ($code) {
  534. case self::XLS_Type_BOF: $this->_readBof(); break;
  535. case self::XLS_Type_SHEET: $this->_readSheet(); break;
  536. case self::XLS_Type_EOF: $this->_readDefault(); break 2;
  537. default: $this->_readDefault(); break;
  538. }
  539. }
  540. // Parse the individual sheets
  541. foreach ($this->_sheets as $sheet) {
  542. if ($sheet['sheetType'] != 0x00) {
  543. // 0x00: Worksheet
  544. // 0x02: Chart
  545. // 0x06: Visual Basic module
  546. continue;
  547. }
  548. $tmpInfo = array();
  549. $tmpInfo['worksheetName'] = $sheet['name'];
  550. $tmpInfo['lastColumnLetter'] = 'A';
  551. $tmpInfo['lastColumnIndex'] = 0;
  552. $tmpInfo['totalRows'] = 0;
  553. $tmpInfo['totalColumns'] = 0;
  554. $this->_pos = $sheet['offset'];
  555. while ($this->_pos <= $this->_dataSize - 4) {
  556. $code = self::_GetInt2d($this->_data, $this->_pos);
  557. switch ($code) {
  558. case self::XLS_Type_RK:
  559. case self::XLS_Type_LABELSST:
  560. case self::XLS_Type_NUMBER:
  561. case self::XLS_Type_FORMULA:
  562. case self::XLS_Type_BOOLERR:
  563. case self::XLS_Type_LABEL:
  564. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  565. $recordData = substr($this->_data, $this->_pos + 4, $length);
  566. // move stream pointer to next record
  567. $this->_pos += 4 + $length;
  568. $rowIndex = self::_GetInt2d($recordData, 0) + 1;
  569. $columnIndex = self::_GetInt2d($recordData, 2);
  570. $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
  571. $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
  572. break;
  573. case self::XLS_Type_BOF: $this->_readBof(); break;
  574. case self::XLS_Type_EOF: $this->_readDefault(); break 2;
  575. default: $this->_readDefault(); break;
  576. }
  577. }
  578. $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
  579. $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;
  580. $worksheetInfo[] = $tmpInfo;
  581. }
  582. return $worksheetInfo;
  583. }
  584. /**
  585. * Loads PHPExcel from file
  586. *
  587. * @param string $pFilename
  588. * @return PHPExcel
  589. * @throws Exception
  590. */
  591. public function load($pFilename)
  592. {
  593. // Read the OLE file
  594. $this->_loadOLE($pFilename);
  595. // Initialisations
  596. $this->_phpExcel = new PHPExcel;
  597. $this->_phpExcel->removeSheetByIndex(0); // remove 1st sheet
  598. if (!$this->_readDataOnly) {
  599. $this->_phpExcel->removeCellStyleXfByIndex(0); // remove the default style
  600. $this->_phpExcel->removeCellXfByIndex(0); // remove the default style
  601. }
  602. // Read the summary information stream (containing meta data)
  603. $this->_readSummaryInformation();
  604. // Read the Additional document summary information stream (containing application-specific meta data)
  605. $this->_readDocumentSummaryInformation();
  606. // total byte size of Excel data (workbook global substream + sheet substreams)
  607. $this->_dataSize = strlen($this->_data);
  608. // initialize
  609. $this->_pos = 0;
  610. $this->_codepage = 'CP1252';
  611. $this->_formats = array();
  612. $this->_objFonts = array();
  613. $this->_palette = array();
  614. $this->_sheets = array();
  615. $this->_externalBooks = array();
  616. $this->_ref = array();
  617. $this->_definedname = array();
  618. $this->_sst = array();
  619. $this->_drawingGroupData = '';
  620. $this->_xfIndex = '';
  621. $this->_mapCellXfIndex = array();
  622. $this->_mapCellStyleXfIndex = array();
  623. // Parse Workbook Global Substream
  624. while ($this->_pos < $this->_dataSize) {
  625. $code = self::_GetInt2d($this->_data, $this->_pos);
  626. switch ($code) {
  627. case self::XLS_Type_BOF: $this->_readBof(); break;
  628. case self::XLS_Type_FILEPASS: $this->_readFilepass(); break;
  629. case self::XLS_Type_CODEPAGE: $this->_readCodepage(); break;
  630. case self::XLS_Type_DATEMODE: $this->_readDateMode(); break;
  631. case self::XLS_Type_FONT: $this->_readFont(); break;
  632. case self::XLS_Type_FORMAT: $this->_readFormat(); break;
  633. case self::XLS_Type_XF: $this->_readXf(); break;
  634. case self::XLS_Type_XFEXT: $this->_readXfExt(); break;
  635. case self::XLS_Type_STYLE: $this->_readStyle(); break;
  636. case self::XLS_Type_PALETTE: $this->_readPalette(); break;
  637. case self::XLS_Type_SHEET: $this->_readSheet(); break;
  638. case self::XLS_Type_EXTERNALBOOK: $this->_readExternalBook(); break;
  639. case self::XLS_Type_EXTERNNAME: $this->_readExternName(); break;
  640. case self::XLS_Type_EXTERNSHEET: $this->_readExternSheet(); break;
  641. case self::XLS_Type_DEFINEDNAME: $this->_readDefinedName(); break;
  642. case self::XLS_Type_MSODRAWINGGROUP: $this->_readMsoDrawingGroup(); break;
  643. case self::XLS_Type_SST: $this->_readSst(); break;
  644. case self::XLS_Type_EOF: $this->_readDefault(); break 2;
  645. default: $this->_readDefault(); break;
  646. }
  647. }
  648. // Resolve indexed colors for font, fill, and border colors
  649. // Cannot be resolved already in XF record, because PALETTE record comes afterwards
  650. if (!$this->_readDataOnly) {
  651. foreach ($this->_objFonts as $objFont) {
  652. if (isset($objFont->colorIndex)) {
  653. $color = self::_readColor($objFont->colorIndex,$this->_palette,$this->_version);
  654. $objFont->getColor()->setRGB($color['rgb']);
  655. }
  656. }
  657. foreach ($this->_phpExcel->getCellXfCollection() as $objStyle) {
  658. // fill start and end color
  659. $fill = $objStyle->getFill();
  660. if (isset($fill->startcolorIndex)) {
  661. $startColor = self::_readColor($fill->startcolorIndex,$this->_palette,$this->_version);
  662. $fill->getStartColor()->setRGB($startColor['rgb']);
  663. }
  664. if (isset($fill->endcolorIndex)) {
  665. $endColor = self::_readColor($fill->endcolorIndex,$this->_palette,$this->_version);
  666. $fill->getEndColor()->setRGB($endColor['rgb']);
  667. }
  668. // border colors
  669. $top = $objStyle->getBorders()->getTop();
  670. $right = $objStyle->getBorders()->getRight();
  671. $bottom = $objStyle->getBorders()->getBottom();
  672. $left = $objStyle->getBorders()->getLeft();
  673. $diagonal = $objStyle->getBorders()->getDiagonal();
  674. if (isset($top->colorIndex)) {
  675. $borderTopColor = self::_readColor($top->colorIndex,$this->_palette,$this->_version);
  676. $top->getColor()->setRGB($borderTopColor['rgb']);
  677. }
  678. if (isset($right->colorIndex)) {
  679. $borderRightColor = self::_readColor($right->colorIndex,$this->_palette,$this->_version);
  680. $right->getColor()->setRGB($borderRightColor['rgb']);
  681. }
  682. if (isset($bottom->colorIndex)) {
  683. $borderBottomColor = self::_readColor($bottom->colorIndex,$this->_palette,$this->_version);
  684. $bottom->getColor()->setRGB($borderBottomColor['rgb']);
  685. }
  686. if (isset($left->colorIndex)) {
  687. $borderLeftColor = self::_readColor($left->colorIndex,$this->_palette,$this->_version);
  688. $left->getColor()->setRGB($borderLeftColor['rgb']);
  689. }
  690. if (isset($diagonal->colorIndex)) {
  691. $borderDiagonalColor = self::_readColor($diagonal->colorIndex,$this->_palette,$this->_version);
  692. $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']);
  693. }
  694. }
  695. }
  696. // treat MSODRAWINGGROUP records, workbook-level Escher
  697. if (!$this->_readDataOnly && $this->_drawingGroupData) {
  698. $escherWorkbook = new PHPExcel_Shared_Escher();
  699. $reader = new PHPExcel_Reader_Excel5_Escher($escherWorkbook);
  700. $escherWorkbook = $reader->load($this->_drawingGroupData);
  701. // debug Escher stream
  702. //$debug = new Debug_Escher(new PHPExcel_Shared_Escher());
  703. //$debug->load($this->_drawingGroupData);
  704. }
  705. // Parse the individual sheets
  706. foreach ($this->_sheets as $sheet) {
  707. if ($sheet['sheetType'] != 0x00) {
  708. // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
  709. continue;
  710. }
  711. // check if sheet should be skipped
  712. if (isset($this->_loadSheetsOnly) && !in_array($sheet['name'], $this->_loadSheetsOnly)) {
  713. continue;
  714. }
  715. // add sheet to PHPExcel object
  716. $this->_phpSheet = $this->_phpExcel->createSheet();
  717. // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula
  718. // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet
  719. // name in line with the formula, not the reverse
  720. $this->_phpSheet->setTitle($sheet['name'],false);
  721. $this->_phpSheet->setSheetState($sheet['sheetState']);
  722. $this->_pos = $sheet['offset'];
  723. // Initialize isFitToPages. May change after reading SHEETPR record.
  724. $this->_isFitToPages = false;
  725. // Initialize drawingData
  726. $this->_drawingData = '';
  727. // Initialize objs
  728. $this->_objs = array();
  729. // Initialize shared formula parts
  730. $this->_sharedFormulaParts = array();
  731. // Initialize shared formulas
  732. $this->_sharedFormulas = array();
  733. // Initialize text objs
  734. $this->_textObjects = array();
  735. // Initialize cell annotations
  736. $this->_cellNotes = array();
  737. $this->textObjRef = -1;
  738. while ($this->_pos <= $this->_dataSize - 4) {
  739. $code = self::_GetInt2d($this->_data, $this->_pos);
  740. switch ($code) {
  741. case self::XLS_Type_BOF: $this->_readBof(); break;
  742. case self::XLS_Type_PRINTGRIDLINES: $this->_readPrintGridlines(); break;
  743. case self::XLS_Type_DEFAULTROWHEIGHT: $this->_readDefaultRowHeight(); break;
  744. case self::XLS_Type_SHEETPR: $this->_readSheetPr(); break;
  745. case self::XLS_Type_HORIZONTALPAGEBREAKS: $this->_readHorizontalPageBreaks(); break;
  746. case self::XLS_Type_VERTICALPAGEBREAKS: $this->_readVerticalPageBreaks(); break;
  747. case self::XLS_Type_HEADER: $this->_readHeader(); break;
  748. case self::XLS_Type_FOOTER: $this->_readFooter(); break;
  749. case self::XLS_Type_HCENTER: $this->_readHcenter(); break;
  750. case self::XLS_Type_VCENTER: $this->_readVcenter(); break;
  751. case self::XLS_Type_LEFTMARGIN: $this->_readLeftMargin(); break;
  752. case self::XLS_Type_RIGHTMARGIN: $this->_readRightMargin(); break;
  753. case self::XLS_Type_TOPMARGIN: $this->_readTopMargin(); break;
  754. case self::XLS_Type_BOTTOMMARGIN: $this->_readBottomMargin(); break;
  755. case self::XLS_Type_PAGESETUP: $this->_readPageSetup(); break;
  756. case self::XLS_Type_PROTECT: $this->_readProtect(); break;
  757. case self::XLS_Type_SCENPROTECT: $this->_readScenProtect(); break;
  758. case self::XLS_Type_OBJECTPROTECT: $this->_readObjectProtect(); break;
  759. case self::XLS_Type_PASSWORD: $this->_readPassword(); break;
  760. case self::XLS_Type_DEFCOLWIDTH: $this->_readDefColWidth(); break;
  761. case self::XLS_Type_COLINFO: $this->_readColInfo(); break;
  762. case self::XLS_Type_DIMENSION: $this->_readDefault(); break;
  763. case self::XLS_Type_ROW: $this->_readRow(); break;
  764. case self::XLS_Type_DBCELL: $this->_readDefault(); break;
  765. case self::XLS_Type_RK: $this->_readRk(); break;
  766. case self::XLS_Type_LABELSST: $this->_readLabelSst(); break;
  767. case self::XLS_Type_MULRK: $this->_readMulRk(); break;
  768. case self::XLS_Type_NUMBER: $this->_readNumber(); break;
  769. case self::XLS_Type_FORMULA: $this->_readFormula(); break;
  770. case self::XLS_Type_SHAREDFMLA: $this->_readSharedFmla(); break;
  771. case self::XLS_Type_BOOLERR: $this->_readBoolErr(); break;
  772. case self::XLS_Type_MULBLANK: $this->_readMulBlank(); break;
  773. case self::XLS_Type_LABEL: $this->_readLabel(); break;
  774. case self::XLS_Type_BLANK: $this->_readBlank(); break;
  775. case self::XLS_Type_MSODRAWING: $this->_readMsoDrawing(); break;
  776. case self::XLS_Type_OBJ: $this->_readObj(); break;
  777. case self::XLS_Type_WINDOW2: $this->_readWindow2(); break;
  778. case self::XLS_Type_SCL: $this->_readScl(); break;
  779. case self::XLS_Type_PANE: $this->_readPane(); break;
  780. case self::XLS_Type_SELECTION: $this->_readSelection(); break;
  781. case self::XLS_Type_MERGEDCELLS: $this->_readMergedCells(); break;
  782. case self::XLS_Type_HYPERLINK: $this->_readHyperLink(); break;
  783. case self::XLS_Type_DATAVALIDATIONS: $this->_readDataValidations(); break;
  784. case self::XLS_Type_DATAVALIDATION: $this->_readDataValidation(); break;
  785. case self::XLS_Type_SHEETLAYOUT: $this->_readSheetLayout(); break;
  786. case self::XLS_Type_SHEETPROTECTION: $this->_readSheetProtection(); break;
  787. case self::XLS_Type_RANGEPROTECTION: $this->_readRangeProtection(); break;
  788. case self::XLS_Type_NOTE: $this->_readNote(); break;
  789. //case self::XLS_Type_IMDATA: $this->_readImData(); break;
  790. case self::XLS_Type_TXO: $this->_readTextObject(); break;
  791. case self::XLS_Type_CONTINUE: $this->_readContinue(); break;
  792. case self::XLS_Type_EOF: $this->_readDefault(); break 2;
  793. default: $this->_readDefault(); break;
  794. }
  795. }
  796. // treat MSODRAWING records, sheet-level Escher
  797. if (!$this->_readDataOnly && $this->_drawingData) {
  798. $escherWorksheet = new PHPExcel_Shared_Escher();
  799. $reader = new PHPExcel_Reader_Excel5_Escher($escherWorksheet);
  800. $escherWorksheet = $reader->load($this->_drawingData);
  801. // debug Escher stream
  802. //$debug = new Debug_Escher(new PHPExcel_Shared_Escher());
  803. //$debug->load($this->_drawingData);
  804. // get all spContainers in one long array, so they can be mapped to OBJ records
  805. $allSpContainers = $escherWorksheet->getDgContainer()->getSpgrContainer()->getAllSpContainers();
  806. }
  807. // treat OBJ records
  808. foreach ($this->_objs as $n => $obj) {
  809. // echo '<hr /><b>Object</b> reference is ',$n,'<br />';
  810. // var_dump($obj);
  811. // echo '<br />';
  812. // the first shape container never has a corresponding OBJ record, hence $n + 1
  813. if (isset($allSpContainers[$n + 1]) && is_object($allSpContainers[$n + 1])) {
  814. $spContainer = $allSpContainers[$n + 1];
  815. // we skip all spContainers that are a part of a group shape since we cannot yet handle those
  816. if ($spContainer->getNestingLevel() > 1) {
  817. continue;
  818. }
  819. // calculate the width and height of the shape
  820. list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($spContainer->getStartCoordinates());
  821. list($endColumn, $endRow) = PHPExcel_Cell::coordinateFromString($spContainer->getEndCoordinates());
  822. $startOffsetX = $spContainer->getStartOffsetX();
  823. $startOffsetY = $spContainer->getStartOffsetY();
  824. $endOffsetX = $spContainer->getEndOffsetX();
  825. $endOffsetY = $spContainer->getEndOffsetY();
  826. $width = PHPExcel_Shared_Excel5::getDistanceX($this->_phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX);
  827. $height = PHPExcel_Shared_Excel5::getDistanceY($this->_phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY);
  828. // calculate offsetX and offsetY of the shape
  829. $offsetX = $startOffsetX * PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, $startColumn) / 1024;
  830. $offsetY = $startOffsetY * PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $startRow) / 256;
  831. switch ($obj['otObjType']) {
  832. case 0x19:
  833. // Note
  834. // echo 'Cell Annotation Object<br />';
  835. // echo 'Object ID is ',$obj['idObjID'],'<br />';
  836. //
  837. if (isset($this->_cellNotes[$obj['idObjID']])) {
  838. $cellNote = $this->_cellNotes[$obj['idObjID']];
  839. if (isset($this->_textObjects[$obj['idObjID']])) {
  840. $textObject = $this->_textObjects[$obj['idObjID']];
  841. $this->_cellNotes[$obj['idObjID']]['objTextData'] = $textObject;
  842. }
  843. }
  844. break;
  845. case 0x08:
  846. // echo 'Picture Object<br />';
  847. // picture
  848. // get index to BSE entry (1-based)
  849. $BSEindex = $spContainer->getOPT(0x0104);
  850. $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection();
  851. $BSE = $BSECollection[$BSEindex - 1];
  852. $blipType = $BSE->getBlipType();
  853. // need check because some blip types are not supported by Escher reader such as EMF
  854. if ($blip = $BSE->getBlip()) {
  855. $ih = imagecreatefromstring($blip->getData());
  856. $drawing = new PHPExcel_Worksheet_MemoryDrawing();
  857. $drawing->setImageResource($ih);
  858. // width, height, offsetX, offsetY
  859. $drawing->setResizeProportional(false);
  860. $drawing->setWidth($width);
  861. $drawing->setHeight($height);
  862. $drawing->setOffsetX($offsetX);
  863. $drawing->setOffsetY($offsetY);
  864. switch ($blipType) {
  865. case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG:
  866. $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
  867. $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG);
  868. break;
  869. case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG:
  870. $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG);
  871. $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG);
  872. break;
  873. }
  874. $drawing->setWorksheet($this->_phpSheet);
  875. $drawing->setCoordinates($spContainer->getStartCoordinates());
  876. }
  877. break;
  878. default:
  879. // other object type
  880. break;
  881. }
  882. }
  883. }
  884. // treat SHAREDFMLA records
  885. if ($this->_version == self::XLS_BIFF8) {
  886. foreach ($this->_sharedFormulaParts as $cell => $baseCell) {
  887. list($column, $row) = PHPExcel_Cell::coordinateFromString($cell);
  888. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($column, $row, $this->_phpSheet->getTitle()) ) {
  889. $formula = $this->_getFormulaFromStructure($this->_sharedFormulas[$baseCell], $cell);
  890. $this->_phpSheet->getCell($cell)->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA);
  891. }
  892. }
  893. }
  894. if (!empty($this->_cellNotes)) {
  895. foreach($this->_cellNotes as $note => $noteDetails) {
  896. if (!isset($noteDetails['objTextData'])) {
  897. if (isset($this->_textObjects[$note])) {
  898. $textObject = $this->_textObjects[$note];
  899. $noteDetails['objTextData'] = $textObject;
  900. } else {
  901. $noteDetails['objTextData']['text'] = '';
  902. }
  903. }
  904. // echo '<b>Cell annotation ',$note,'</b><br />';
  905. // var_dump($noteDetails);
  906. // echo '<br />';
  907. $cellAddress = str_replace('$','',$noteDetails['cellRef']);
  908. $this->_phpSheet->getComment( $cellAddress )
  909. ->setAuthor( $noteDetails['author'] )
  910. ->setText($this->_parseRichText($noteDetails['objTextData']['text']) );
  911. }
  912. }
  913. }
  914. // add the named ranges (defined names)
  915. foreach ($this->_definedname as $definedName) {
  916. if ($definedName['isBuiltInName']) {
  917. switch ($definedName['name']) {
  918. case pack('C', 0x06):
  919. // print area
  920. // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2
  921. $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
  922. $extractedRanges = array();
  923. foreach ($ranges as $range) {
  924. // $range should look like one of these
  925. // Foo!$C$7:$J$66
  926. // Bar!$A$1:$IV$2
  927. $explodes = explode('!', $range); // FIXME: what if sheetname contains exclamation mark?
  928. $sheetName = $explodes[0];
  929. if (count($explodes) == 2) {
  930. $extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66
  931. }
  932. }
  933. if ($docSheet = $this->_phpExcel->getSheetByName($sheetName)) {
  934. $docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2
  935. }
  936. break;
  937. case pack('C', 0x07):
  938. // print titles (repeating rows)
  939. // Assuming BIFF8, there are 3 cases
  940. // 1. repeating rows
  941. // formula looks like this: Sheet!$A$1:$IV$2
  942. // rows 1-2 repeat
  943. // 2. repeating columns
  944. // formula looks like this: Sheet!$A$1:$B$65536
  945. // columns A-B repeat
  946. // 3. both repeating rows and repeating columns
  947. // formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2
  948. $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
  949. foreach ($ranges as $range) {
  950. // $range should look like this one of these
  951. // Sheet!$A$1:$B$65536
  952. // Sheet!$A$1:$IV$2
  953. $explodes = explode('!', $range);
  954. if (count($explodes) == 2) {
  955. if ($docSheet = $this->_phpExcel->getSheetByName($explodes[0])) {
  956. $extractedRange = $explodes[1];
  957. $extractedRange = str_replace('$', '', $extractedRange);
  958. $coordinateStrings = explode(':', $extractedRange);
  959. if (count($coordinateStrings) == 2) {
  960. list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[0]);
  961. list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[1]);
  962. if ($firstColumn == 'A' and $lastColumn == 'IV') {
  963. // then we have repeating rows
  964. $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($firstRow, $lastRow));
  965. } elseif ($firstRow == 1 and $lastRow == 65536) {
  966. // then we have repeating columns
  967. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($firstColumn, $lastColumn));
  968. }
  969. }
  970. }
  971. }
  972. }
  973. break;
  974. }
  975. } else {
  976. // Extract range
  977. $explodes = explode('!', $definedName['formula']);
  978. if (count($explodes) == 2) {
  979. if (($docSheet = $this->_phpExcel->getSheetByName($explodes[0])) ||
  980. ($docSheet = $this->_phpExcel->getSheetByName(trim($explodes[0],"'")))) {
  981. $extractedRange = $explodes[1];
  982. $extractedRange = str_replace('$', '', $extractedRange);
  983. $localOnly = ($definedName['scope'] == 0) ? false : true;
  984. $scope = ($definedName['scope'] == 0) ?
  985. null : $this->_phpExcel->getSheetByName($this->_sheets[$definedName['scope'] - 1]['name']);
  986. $this->_phpExcel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $docSheet, $extractedRange, $localOnly, $scope) );
  987. }
  988. } else {
  989. // Named Value
  990. // TODO Provide support for named values
  991. }
  992. }
  993. }
  994. return $this->_phpExcel;
  995. }
  996. /**
  997. * Use OLE reader to extract the relevant data streams from the OLE file
  998. *
  999. * @param string $pFilename
  1000. */
  1001. private function _loadOLE($pFilename)
  1002. {
  1003. // OLE reader
  1004. $ole = new PHPExcel_Shared_OLERead();
  1005. // get excel data,
  1006. $res = $ole->read($pFilename);
  1007. // Get workbook data: workbook stream + sheet streams
  1008. $this->_data = $ole->getStream($ole->wrkbook);
  1009. // Get summary information data
  1010. $this->_summaryInformation = $ole->getStream($ole->summaryInformation);
  1011. // Get additional document summary information data
  1012. $this->_documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation);
  1013. // Get user-defined property data
  1014. // $this->_userDefinedProperties = $ole->getUserDefinedProperties();
  1015. }
  1016. /**
  1017. * Read summary information
  1018. */
  1019. private function _readSummaryInformation()
  1020. {
  1021. if (!isset($this->_summaryInformation)) {
  1022. return;
  1023. }
  1024. // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
  1025. // offset: 2; size: 2;
  1026. // offset: 4; size: 2; OS version
  1027. // offset: 6; size: 2; OS indicator
  1028. // offset: 8; size: 16
  1029. // offset: 24; size: 4; section count
  1030. $secCount = self::_GetInt4d($this->_summaryInformation, 24);
  1031. // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
  1032. // offset: 44; size: 4
  1033. $secOffset = self::_GetInt4d($this->_summaryInformation, 44);
  1034. // section header
  1035. // offset: $secOffset; size: 4; section length
  1036. $secLength = self::_GetInt4d($this->_summaryInformation, $secOffset);
  1037. // offset: $secOffset+4; size: 4; property count
  1038. $countProperties = self::_GetInt4d($this->_summaryInformation, $secOffset+4);
  1039. // initialize code page (used to resolve string values)
  1040. $codePage = 'CP1252';
  1041. // offset: ($secOffset+8); size: var
  1042. // loop through property decarations and properties
  1043. for ($i = 0; $i < $countProperties; ++$i) {
  1044. // offset: ($secOffset+8) + (8 * $i); size: 4; property ID
  1045. $id = self::_GetInt4d($this->_summaryInformation, ($secOffset+8) + (8 * $i));
  1046. // Use value of property id as appropriate
  1047. // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48)
  1048. $offset = self::_GetInt4d($this->_summaryInformation, ($secOffset+12) + (8 * $i));
  1049. $type = self::_GetInt4d($this->_summaryInformation, $secOffset + $offset);
  1050. // initialize property value
  1051. $value = null;
  1052. // extract property value based on property type
  1053. switch ($type) {
  1054. case 0x02: // 2 byte signed integer
  1055. $value = self::_GetInt2d($this->_summaryInformation, $secOffset + 4 + $offset);
  1056. break;
  1057. case 0x03: // 4 byte signed integer
  1058. $value = self::_GetInt4d($this->_summaryInformation, $secOffset + 4 + $offset);
  1059. break;
  1060. case 0x13: // 4 byte unsigned integer
  1061. // not needed yet, fix later if necessary
  1062. break;
  1063. case 0x1E: // null-terminated string prepended by dword string length
  1064. $byteLength = self::_GetInt4d($this->_summaryInformation, $secOffset + 4 + $offset);
  1065. $value = substr($this->_summaryInformation, $secOffset + 8 + $offset, $byteLength);
  1066. $value = PHPExcel_Shared_String::ConvertEncoding($value, 'UTF-8', $codePage);
  1067. $value = rtrim($value);
  1068. break;
  1069. case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
  1070. // PHP-time
  1071. $value = PHPExcel_Shared_OLE::OLE2LocalDate(substr($this->_summaryInformation, $secOffset + 4 + $offset, 8));
  1072. break;
  1073. case 0x47: // Clipboard format
  1074. // not needed yet, fix later if necessary
  1075. break;
  1076. }
  1077. switch ($id) {
  1078. case 0x01: // Code Page
  1079. $codePage = PHPExcel_Shared_CodePage::NumberToName($value);
  1080. break;
  1081. case 0x02: // Title
  1082. $this->_phpExcel->getProperties()->setTitle($value);
  1083. break;
  1084. case 0x03: // Subject
  1085. $this->_phpExcel->getProperties()->setSubject($value);
  1086. break;
  1087. case 0x04: // Author (Creator)
  1088. $this->_phpExcel->getProperties()->setCreator($value);
  1089. break;
  1090. case 0x05: // Keywords
  1091. $this->_phpExcel->getProperties()->setKeywords($value);
  1092. break;
  1093. case 0x06: // Comments (Description)
  1094. $this->_phpExcel->getProperties()->setDescription($value);
  1095. break;
  1096. case 0x07: // Template
  1097. // Not supported by PHPExcel
  1098. break;
  1099. case 0x08: // Last Saved By (LastModifiedBy)
  1100. $this->_phpExcel->getProperties()->setLastModifiedBy($value);
  1101. break;
  1102. case 0x09: // Revision
  1103. // Not supported by PHPExcel
  1104. break;
  1105. case 0x0A: // Total Editing Time
  1106. // Not supported by PHPExcel
  1107. break;
  1108. case 0x0B: // Last Printed
  1109. // Not supported by PHPExcel
  1110. break;
  1111. case 0x0C: // Created Date/Time
  1112. $this->_phpExcel->getProperties()->setCreated($value);
  1113. break;
  1114. case 0x0D: // Modified Date/Time
  1115. $this->_phpExcel->getProperties()->setModified($value);
  1116. break;
  1117. case 0x0E: // Number of Pages
  1118. // Not supported by PHPExcel
  1119. break;
  1120. case 0x0F: // Number of Words
  1121. // Not supported by PHPExcel
  1122. break;
  1123. case 0x10: // Number of Characters
  1124. // Not supported by PHPExcel
  1125. break;
  1126. case 0x11: // Thumbnail
  1127. // Not supported by PHPExcel
  1128. break;
  1129. case 0x12: // Name of creating application
  1130. // Not supported by PHPExcel
  1131. break;
  1132. case 0x13: // Security
  1133. // Not supported by PHPExcel
  1134. break;
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * Read additional document summary information
  1140. */
  1141. private function _readDocumentSummaryInformation()
  1142. {
  1143. if (!isset($this->_documentSummaryInformation)) {
  1144. return;
  1145. }
  1146. // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
  1147. // offset: 2; size: 2;
  1148. // offset: 4; size: 2; OS version
  1149. // offset: 6; size: 2; OS indicator
  1150. // offset: 8; size: 16
  1151. // offset: 24; size: 4; section count
  1152. $secCount = self::_GetInt4d($this->_documentSummaryInformation, 24);
  1153. // echo '$secCount = ',$secCount,'<br />';
  1154. // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
  1155. // offset: 44; size: 4; first section offset
  1156. $secOffset = self::_GetInt4d($this->_documentSummaryInformation, 44);
  1157. // echo '$secOffset = ',$secOffset,'<br />';
  1158. // section header
  1159. // offset: $secOffset; size: 4; section length
  1160. $secLength = self::_GetInt4d($this->_documentSummaryInformation, $secOffset);
  1161. // echo '$secLength = ',$secLength,'<br />';
  1162. // offset: $secOffset+4; size: 4; property count
  1163. $countProperties = self::_GetInt4d($this->_documentSummaryInformation, $secOffset+4);
  1164. // echo '$countProperties = ',$countProperties,'<br />';
  1165. // initialize code page (used to resolve string values)
  1166. $codePage = 'CP1252';
  1167. // offset: ($secOffset+8); size: var
  1168. // loop through property decarations and properties
  1169. for ($i = 0; $i < $countProperties; ++$i) {
  1170. // echo 'Property ',$i,'<br />';
  1171. // offset: ($secOffset+8) + (8 * $i); size: 4; property ID
  1172. $id = self::_GetInt4d($this->_documentSummaryInformation, ($secOffset+8) + (8 * $i));
  1173. // echo 'ID is ',$id,'<br />';
  1174. // Use value of property id as appropriate
  1175. // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48)
  1176. $offset = self::_GetInt4d($this->_documentSummaryInformation, ($secOffset+12) + (8 * $i));
  1177. $type = self::_GetInt4d($this->_documentSummaryInformation, $secOffset + $offset);
  1178. // echo 'Type is ',$type,', ';
  1179. // initialize property value
  1180. $value = null;
  1181. // extract property value based on property type
  1182. switch ($type) {
  1183. case 0x02: // 2 byte signed integer
  1184. $value = self::_GetInt2d($this->_documentSummaryInformation, $secOffset + 4 + $offset);
  1185. break;
  1186. case 0x03: // 4 byte signed integer
  1187. $value = self::_GetInt4d($this->_documentSummaryInformation, $secOffset + 4 + $offset);
  1188. break;
  1189. case 0x0B: // Boolean
  1190. $value = self::_GetInt2d($this->_documentSummaryInformation, $secOffset + 4 + $offset);
  1191. $value = ($value == 0 ? false : true);
  1192. break;
  1193. case 0x13: // 4 byte unsigned integer
  1194. // not needed yet, fix later if necessary
  1195. break;
  1196. case 0x1E: // null-terminated string prepended by dword string length
  1197. $byteLength = self::_GetInt4d($this->_documentSummaryInformation, $secOffset + 4 + $offset);
  1198. $value = substr($this->_documentSummaryInformation, $secOffset + 8 + $offset, $byteLength);
  1199. $value = PHPExcel_Shared_String::ConvertEncoding($value, 'UTF-8', $codePage);
  1200. $value = rtrim($value);
  1201. break;
  1202. case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
  1203. // PHP-Time
  1204. $value = PHPExcel_Shared_OLE::OLE2LocalDate(substr($this->_documentSummaryInformation, $secOffset + 4 + $offset, 8));
  1205. break;
  1206. case 0x47: // Clipboard format
  1207. // not needed yet, fix later if necessary
  1208. break;
  1209. }
  1210. switch ($id) {
  1211. case 0x01: // Code Page
  1212. $codePage = PHPExcel_Shared_CodePage::NumberToName($value);
  1213. break;
  1214. case 0x02: // Category
  1215. $this->_phpExcel->getProperties()->setCategory($value);
  1216. break;
  1217. case 0x03: // Presentation Target
  1218. // Not supported by PHPExcel
  1219. break;
  1220. case 0x04: // Bytes
  1221. // Not supported by PHPExcel
  1222. break;
  1223. case 0x05: // Lines
  1224. // Not supported by PHPExcel
  1225. break;
  1226. case 0x06: // Paragraphs
  1227. // Not supported by PHPExcel
  1228. break;
  1229. case 0x07: // Slides
  1230. // Not supported by PHPExcel
  1231. break;
  1232. case 0x08: // Notes
  1233. // Not supported by PHPExcel
  1234. break;
  1235. case 0x09: // Hidden Slides
  1236. // Not supported by PHPExcel
  1237. break;
  1238. case 0x0A: // MM Clips
  1239. // Not supported by PHPExcel
  1240. break;
  1241. case 0x0B: // Scale Crop
  1242. // Not supported by PHPExcel
  1243. break;
  1244. case 0x0C: // Heading Pairs
  1245. // Not supported by PHPExcel
  1246. break;
  1247. case 0x0D: // Titles of Parts
  1248. // Not supported by PHPExcel
  1249. break;
  1250. case 0x0E: // Manager
  1251. $this->_phpExcel->getProperties()->setManager($value);
  1252. break;
  1253. case 0x0F: // Company
  1254. $this->_phpExcel->getProperties()->setCompany($value);
  1255. break;
  1256. case 0x10: // Links up-to-date
  1257. // Not supported by PHPExcel
  1258. break;
  1259. }
  1260. }
  1261. }
  1262. /**
  1263. * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record.
  1264. */
  1265. private function _readDefault()
  1266. {
  1267. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1268. // $recordData = substr($this->_data, $this->_pos + 4, $length);
  1269. // move stream pointer to next record
  1270. $this->_pos += 4 + $length;
  1271. }
  1272. /**
  1273. * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions,
  1274. * this record stores a note (cell note). This feature was significantly enhanced in Excel 97.
  1275. */
  1276. private function _readNote()
  1277. {
  1278. // echo '<b>Read Cell Annotation</b><br />';
  1279. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1280. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1281. // move stream pointer to next record
  1282. $this->_pos += 4 + $length;
  1283. if ($this->_readDataOnly) {
  1284. return;
  1285. }
  1286. $cellAddress = $this->_readBIFF8CellAddress(substr($recordData, 0, 4));
  1287. if ($this->_version == self::XLS_BIFF8) {
  1288. $noteObjID = self::_GetInt2d($recordData, 6);
  1289. $noteAuthor = self::_readUnicodeStringLong(substr($recordData, 8));
  1290. $noteAuthor = $noteAuthor['value'];
  1291. // echo 'Note Address=',$cellAddress,'<br />';
  1292. // echo 'Note Object ID=',$noteObjID,'<br />';
  1293. // echo 'Note Author=',$noteAuthor,'<hr />';
  1294. //
  1295. $this->_cellNotes[$noteObjID] = array('cellRef' => $cellAddress,
  1296. 'objectID' => $noteObjID,
  1297. 'author' => $noteAuthor
  1298. );
  1299. } else {
  1300. $extension = false;
  1301. if ($cellAddress == '$B$65536') {
  1302. // If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation
  1303. // note from the previous cell annotation. We're not yet handling this, so annotations longer than the
  1304. // max 2048 bytes will probably throw a wobbly.
  1305. $row = self::_GetInt2d($recordData, 0);
  1306. $extension = true;
  1307. $cellAddress = array_pop(array_keys($this->_phpSheet->getComments()));
  1308. }
  1309. // echo 'Note Address=',$cellAddress,'<br />';
  1310. $cellAddress = str_replace('$','',$cellAddress);
  1311. $noteLength = self::_GetInt2d($recordData, 4);
  1312. $noteText = trim(substr($recordData, 6));
  1313. // echo 'Note Length=',$noteLength,'<br />';
  1314. // echo 'Note Text=',$noteText,'<br />';
  1315. if ($extension) {
  1316. // Concatenate this extension with the currently set comment for the cell
  1317. $comment = $this->_phpSheet->getComment( $cellAddress );
  1318. $commentText = $comment->getText()->getPlainText();
  1319. $comment->setText($this->_parseRichText($commentText.$noteText) );
  1320. } else {
  1321. // Set comment for the cell
  1322. $this->_phpSheet->getComment( $cellAddress )
  1323. // ->setAuthor( $author )
  1324. ->setText($this->_parseRichText($noteText) );
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * The TEXT Object record contains the text associated with a cell annotation.
  1330. */
  1331. private function _readTextObject()
  1332. {
  1333. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1334. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1335. // move stream pointer to next record
  1336. $this->_pos += 4 + $length;
  1337. if ($this->_readDataOnly) {
  1338. return;
  1339. }
  1340. // recordData consists of an array of subrecords looking like this:
  1341. // grbit: 2 bytes; Option Flags
  1342. // rot: 2 bytes; rotation
  1343. // cchText: 2 bytes; length of the text (in the first continue record)
  1344. // cbRuns: 2 bytes; length of the formatting (in the second continue record)
  1345. // followed by the continuation records containing the actual text and formatting
  1346. $grbitOpts = self::_GetInt2d($recordData, 0);
  1347. $rot = self::_GetInt2d($recordData, 2);
  1348. $cchText = self::_GetInt2d($recordData, 10);
  1349. $cbRuns = self::_GetInt2d($recordData, 12);
  1350. $text = $this->_getSplicedRecordData();
  1351. $this->_textObjects[$this->textObjRef] = array(
  1352. 'text' => substr($text["recordData"],$text["spliceOffsets"][0]+1,$cchText),
  1353. 'format' => substr($text["recordData"],$text["spliceOffsets"][1],$cbRuns),
  1354. 'alignment' => $grbitOpts,
  1355. 'rotation' => $rot
  1356. );
  1357. // echo '<b>_readTextObject()</b><br />';
  1358. // var_dump($this->_textObjects[$this->textObjRef]);
  1359. // echo '<br />';
  1360. }
  1361. /**
  1362. * Read BOF
  1363. */
  1364. private function _readBof()
  1365. {
  1366. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1367. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1368. // move stream pointer to next record
  1369. $this->_pos += 4 + $length;
  1370. // offset: 2; size: 2; type of the following data
  1371. $substreamType = self::_GetInt2d($recordData, 2);
  1372. switch ($substreamType) {
  1373. case self::XLS_WorkbookGlobals:
  1374. $version = self::_GetInt2d($recordData, 0);
  1375. if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) {
  1376. throw new Exception('Cannot read this Excel file. Version is too old.');
  1377. }
  1378. $this->_version = $version;
  1379. break;
  1380. case self::XLS_Worksheet:
  1381. // do not use this version information for anything
  1382. // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream
  1383. break;
  1384. default:
  1385. // substream, e.g. chart
  1386. // just skip the entire substream
  1387. do {
  1388. $code = self::_GetInt2d($this->_data, $this->_pos);
  1389. $this->_readDefault();
  1390. } while ($code != self::XLS_Type_EOF && $this->_pos < $this->_dataSize);
  1391. break;
  1392. }
  1393. }
  1394. /**
  1395. * FILEPASS
  1396. *
  1397. * This record is part of the File Protection Block. It
  1398. * contains information about the read/write password of the
  1399. * file. All record contents following this record will be
  1400. * encrypted.
  1401. *
  1402. * -- "OpenOffice.org's Documentation of the Microsoft
  1403. * Excel File Format"
  1404. */
  1405. private function _readFilepass()
  1406. {
  1407. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1408. // $recordData = substr($this->_data, $this->_pos + 4, $length);
  1409. // move stream pointer to next record
  1410. $this->_pos += 4 + $length;
  1411. throw new Exception('Cannot read encrypted file');
  1412. }
  1413. /**
  1414. * CODEPAGE
  1415. *
  1416. * This record stores the text encoding used to write byte
  1417. * strings, stored as MS Windows code page identifier.
  1418. *
  1419. * -- "OpenOffice.org's Documentation of the Microsoft
  1420. * Excel File Format"
  1421. */
  1422. private function _readCodepage()
  1423. {
  1424. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1425. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1426. // move stream pointer to next record
  1427. $this->_pos += 4 + $length;
  1428. // offset: 0; size: 2; code page identifier
  1429. $codepage = self::_GetInt2d($recordData, 0);
  1430. $this->_codepage = PHPExcel_Shared_CodePage::NumberToName($codepage);
  1431. }
  1432. /**
  1433. * DATEMODE
  1434. *
  1435. * This record specifies the base date for displaying date
  1436. * values. All dates are stored as count of days past this
  1437. * base date. In BIFF2-BIFF4 this record is part of the
  1438. * Calculation Settings Block. In BIFF5-BIFF8 it is
  1439. * stored in the Workbook Globals Substream.
  1440. *
  1441. * -- "OpenOffice.org's Documentation of the Microsoft
  1442. * Excel File Format"
  1443. */
  1444. private function _readDateMode()
  1445. {
  1446. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1447. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1448. // move stream pointer to next record
  1449. $this->_pos += 4 + $length;
  1450. // offset: 0; size: 2; 0 = base 1900, 1 = base 1904
  1451. PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
  1452. if (ord($recordData{0}) == 1) {
  1453. PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
  1454. }
  1455. }
  1456. /**
  1457. * Read a FONT record
  1458. */
  1459. private function _readFont()
  1460. {
  1461. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1462. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1463. // move stream pointer to next record
  1464. $this->_pos += 4 + $length;
  1465. if (!$this->_readDataOnly) {
  1466. $objFont = new PHPExcel_Style_Font();
  1467. // offset: 0; size: 2; height of the font (in twips = 1/20 of a point)
  1468. $size = self::_GetInt2d($recordData, 0);
  1469. $objFont->setSize($size / 20);
  1470. // offset: 2; size: 2; option flags
  1471. // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8)
  1472. // bit: 1; mask 0x0002; italic
  1473. $isItalic = (0x0002 & self::_GetInt2d($recordData, 2)) >> 1;
  1474. if ($isItalic) $objFont->setItalic(true);
  1475. // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8)
  1476. // bit: 3; mask 0x0008; strike
  1477. $isStrike = (0x0008 & self::_GetInt2d($recordData, 2)) >> 3;
  1478. if ($isStrike) $objFont->setStrikethrough(true);
  1479. // offset: 4; size: 2; colour index
  1480. $colorIndex = self::_GetInt2d($recordData, 4);
  1481. $objFont->colorIndex = $colorIndex;
  1482. // offset: 6; size: 2; font weight
  1483. $weight = self::_GetInt2d($recordData, 6);
  1484. switch ($weight) {
  1485. case 0x02BC:
  1486. $objFont->setBold(true);
  1487. break;
  1488. }
  1489. // offset: 8; size: 2; escapement type
  1490. $escapement = self::_GetInt2d($recordData, 8);
  1491. switch ($escapement) {
  1492. case 0x0001:
  1493. $objFont->setSuperScript(true);
  1494. break;
  1495. case 0x0002:
  1496. $objFont->setSubScript(true);
  1497. break;
  1498. }
  1499. // offset: 10; size: 1; underline type
  1500. $underlineType = ord($recordData{10});
  1501. switch ($underlineType) {
  1502. case 0x00:
  1503. break; // no underline
  1504. case 0x01:
  1505. $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1506. break;
  1507. case 0x02:
  1508. $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLE);
  1509. break;
  1510. case 0x21:
  1511. $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING);
  1512. break;
  1513. case 0x22:
  1514. $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING);
  1515. break;
  1516. }
  1517. // offset: 11; size: 1; font family
  1518. // offset: 12; size: 1; character set
  1519. // offset: 13; size: 1; not used
  1520. // offset: 14; size: var; font name
  1521. if ($this->_version == self::XLS_BIFF8) {
  1522. $string = self::_readUnicodeStringShort(substr($recordData, 14));
  1523. } else {
  1524. $string = $this->_readByteStringShort(substr($recordData, 14));
  1525. }
  1526. $objFont->setName($string['value']);
  1527. $this->_objFonts[] = $objFont;
  1528. }
  1529. }
  1530. /**
  1531. * FORMAT
  1532. *
  1533. * This record contains information about a number format.
  1534. * All FORMAT records occur together in a sequential list.
  1535. *
  1536. * In BIFF2-BIFF4 other records referencing a FORMAT record
  1537. * contain a zero-based index into this list. From BIFF5 on
  1538. * the FORMAT record contains the index itself that will be
  1539. * used by other records.
  1540. *
  1541. * -- "OpenOffice.org's Documentation of the Microsoft
  1542. * Excel File Format"
  1543. */
  1544. private function _readFormat()
  1545. {
  1546. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1547. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1548. // move stream pointer to next record
  1549. $this->_pos += 4 + $length;
  1550. if (!$this->_readDataOnly) {
  1551. $indexCode = self::_GetInt2d($recordData, 0);
  1552. if ($this->_version == self::XLS_BIFF8) {
  1553. $string = self::_readUnicodeStringLong(substr($recordData, 2));
  1554. } else {
  1555. // BIFF7
  1556. $string = $this->_readByteStringShort(substr($recordData, 2));
  1557. }
  1558. $formatString = $string['value'];
  1559. $this->_formats[$indexCode] = $formatString;
  1560. }
  1561. }
  1562. /**
  1563. * XF - Extended Format
  1564. *
  1565. * This record contains formatting information for cells, rows, columns or styles.
  1566. * According to http://support.microsoft.com/kb/147732 there are always at least 15 cell style XF
  1567. * and 1 cell XF.
  1568. * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF
  1569. * and XF record 15 is a cell XF
  1570. * We only read the first cell style XF and skip the remaining cell style XF records
  1571. * We read all cell XF records.
  1572. *
  1573. * -- "OpenOffice.org's Documentation of the Microsoft
  1574. * Excel File Format"
  1575. */
  1576. private function _readXf()
  1577. {
  1578. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1579. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1580. // move stream pointer to next record
  1581. $this->_pos += 4 + $length;
  1582. $objStyle = new PHPExcel_Style();
  1583. if (!$this->_readDataOnly) {
  1584. // offset: 0; size: 2; Index to FONT record
  1585. if (self::_GetInt2d($recordData, 0) < 4) {
  1586. $fontIndex = self::_GetInt2d($recordData, 0);
  1587. } else {
  1588. // this has to do with that index 4 is omitted in all BIFF versions for some strange reason
  1589. // check the OpenOffice documentation of the FONT record
  1590. $fontIndex = self::_GetInt2d($recordData, 0) - 1;
  1591. }
  1592. $objStyle->setFont($this->_objFonts[$fontIndex]);
  1593. // offset: 2; size: 2; Index to FORMAT record
  1594. $numberFormatIndex = self::_GetInt2d($recordData, 2);
  1595. if (isset($this->_formats[$numberFormatIndex])) {
  1596. // then we have user-defined format code
  1597. $numberformat = array('code' => $this->_formats[$numberFormatIndex]);
  1598. } elseif (($code = PHPExcel_Style_NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') {
  1599. // then we have built-in format code
  1600. $numberformat = array('code' => $code);
  1601. } else {
  1602. // we set the general format code
  1603. $numberformat = array('code' => 'General');
  1604. }
  1605. $objStyle->getNumberFormat()->setFormatCode($numberformat['code']);
  1606. // offset: 4; size: 2; XF type, cell protection, and parent style XF
  1607. // bit 2-0; mask 0x0007; XF_TYPE_PROT
  1608. $xfTypeProt = self::_GetInt2d($recordData, 4);
  1609. // bit 0; mask 0x01; 1 = cell is locked
  1610. $isLocked = (0x01 & $xfTypeProt) >> 0;
  1611. $objStyle->getProtection()->setLocked($isLocked ?
  1612. PHPExcel_Style_Protection::PROTECTION_INHERIT : PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1613. // bit 1; mask 0x02; 1 = Formula is hidden
  1614. $isHidden = (0x02 & $xfTypeProt) >> 1;
  1615. $objStyle->getProtection()->setHidden($isHidden ?
  1616. PHPExcel_Style_Protection::PROTECTION_PROTECTED : PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1617. // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF
  1618. $isCellStyleXf = (0x04 & $xfTypeProt) >> 2;
  1619. // offset: 6; size: 1; Alignment and text break
  1620. // bit 2-0, mask 0x07; horizontal alignment
  1621. $horAlign = (0x07 & ord($recordData{6})) >> 0;
  1622. switch ($horAlign) {
  1623. case 0:
  1624. $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_GENERAL);
  1625. break;
  1626. case 1:
  1627. $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
  1628. break;
  1629. case 2:
  1630. $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  1631. break;
  1632. case 3:
  1633. $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  1634. break;
  1635. case 5:
  1636. $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
  1637. break;
  1638. case 6:
  1639. $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS);
  1640. break;
  1641. }
  1642. // bit 3, mask 0x08; wrap text
  1643. $wrapText = (0x08 & ord($recordData{6})) >> 3;
  1644. switch ($wrapText) {
  1645. case 0:
  1646. $objStyle->getAlignment()->setWrapText(false);
  1647. break;
  1648. case 1:
  1649. $objStyle->getAlignment()->setWrapText(true);
  1650. break;
  1651. }
  1652. // bit 6-4, mask 0x70; vertical alignment
  1653. $vertAlign = (0x70 & ord($recordData{6})) >> 4;
  1654. switch ($vertAlign) {
  1655. case 0:
  1656. $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP);
  1657. break;
  1658. case 1:
  1659. $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
  1660. break;
  1661. case 2:
  1662. $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_BOTTOM);
  1663. break;
  1664. case 3:
  1665. $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_JUSTIFY);
  1666. break;
  1667. }
  1668. if ($this->_version == self::XLS_BIFF8) {
  1669. // offset: 7; size: 1; XF_ROTATION: Text rotation angle
  1670. $angle = ord($recordData{7});
  1671. $rotation = 0;
  1672. if ($angle <= 90) {
  1673. $rotation = $angle;
  1674. } else if ($angle <= 180) {
  1675. $rotation = 90 - $angle;
  1676. } else if ($angle == 255) {
  1677. $rotation = -165;
  1678. }
  1679. $objStyle->getAlignment()->setTextRotation($rotation);
  1680. // offset: 8; size: 1; Indentation, shrink to cell size, and text direction
  1681. // bit: 3-0; mask: 0x0F; indent level
  1682. $indent = (0x0F & ord($recordData{8})) >> 0;
  1683. $objStyle->getAlignment()->setIndent($indent);
  1684. // bit: 4; mask: 0x10; 1 = shrink content to fit into cell
  1685. $shrinkToFit = (0x10 & ord($recordData{8})) >> 4;
  1686. switch ($shrinkToFit) {
  1687. case 0:
  1688. $objStyle->getAlignment()->setShrinkToFit(false);
  1689. break;
  1690. case 1:
  1691. $objStyle->getAlignment()->setShrinkToFit(true);
  1692. break;
  1693. }
  1694. // offset: 9; size: 1; Flags used for attribute groups
  1695. // offset: 10; size: 4; Cell border lines and background area
  1696. // bit: 3-0; mask: 0x0000000F; left style
  1697. if ($bordersLeftStyle = self::_mapBorderStyle((0x0000000F & self::_GetInt4d($recordData, 10)) >> 0)) {
  1698. $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle);
  1699. }
  1700. // bit: 7-4; mask: 0x000000F0; right style
  1701. if ($bordersRightStyle = self::_mapBorderStyle((0x000000F0 & self::_GetInt4d($recordData, 10)) >> 4)) {
  1702. $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle);
  1703. }
  1704. // bit: 11-8; mask: 0x00000F00; top style
  1705. if ($bordersTopStyle = self::_mapBorderStyle((0x00000F00 & self::_GetInt4d($recordData, 10)) >> 8)) {
  1706. $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle);
  1707. }
  1708. // bit: 15-12; mask: 0x0000F000; bottom style
  1709. if ($bordersBottomStyle = self::_mapBorderStyle((0x0000F000 & self::_GetInt4d($recordData, 10)) >> 12)) {
  1710. $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle);
  1711. }
  1712. // bit: 22-16; mask: 0x007F0000; left color
  1713. $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::_GetInt4d($recordData, 10)) >> 16;
  1714. // bit: 29-23; mask: 0x3F800000; right color
  1715. $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::_GetInt4d($recordData, 10)) >> 23;
  1716. // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom
  1717. $diagonalDown = (0x40000000 & self::_GetInt4d($recordData, 10)) >> 30 ?
  1718. true : false;
  1719. // bit: 31; mask: 0x80000000; 1 = diagonal line from bottom left to top right
  1720. $diagonalUp = (0x80000000 & self::_GetInt4d($recordData, 10)) >> 31 ?
  1721. true : false;
  1722. if ($diagonalUp == false && $diagonalDown == false) {
  1723. $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE);
  1724. } elseif ($diagonalUp == true && $diagonalDown == false) {
  1725. $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP);
  1726. } elseif ($diagonalUp == false && $diagonalDown == true) {
  1727. $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN);
  1728. } elseif ($diagonalUp == true && $diagonalDown == true) {
  1729. $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH);
  1730. }
  1731. // offset: 14; size: 4;
  1732. // bit: 6-0; mask: 0x0000007F; top color
  1733. $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::_GetInt4d($recordData, 14)) >> 0;
  1734. // bit: 13-7; mask: 0x00003F80; bottom color
  1735. $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::_GetInt4d($recordData, 14)) >> 7;
  1736. // bit: 20-14; mask: 0x001FC000; diagonal color
  1737. $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::_GetInt4d($recordData, 14)) >> 14;
  1738. // bit: 24-21; mask: 0x01E00000; diagonal style
  1739. if ($bordersDiagonalStyle = self::_mapBorderStyle((0x01E00000 & self::_GetInt4d($recordData, 14)) >> 21)) {
  1740. $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle);
  1741. }
  1742. // bit: 31-26; mask: 0xFC000000 fill pattern
  1743. if ($fillType = self::_mapFillPattern((0xFC000000 & self::_GetInt4d($recordData, 14)) >> 26)) {
  1744. $objStyle->getFill()->setFillType($fillType);
  1745. }
  1746. // offset: 18; size: 2; pattern and background colour
  1747. // bit: 6-0; mask: 0x007F; color index for pattern color
  1748. $objStyle->getFill()->startcolorIndex = (0x007F & self::_GetInt2d($recordData, 18)) >> 0;
  1749. // bit: 13-7; mask: 0x3F80; color index for pattern background
  1750. $objStyle->getFill()->endcolorIndex = (0x3F80 & self::_GetInt2d($recordData, 18)) >> 7;
  1751. } else {
  1752. // BIFF5
  1753. // offset: 7; size: 1; Text orientation and flags
  1754. $orientationAndFlags = ord($recordData{7});
  1755. // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation
  1756. $xfOrientation = (0x03 & $orientationAndFlags) >> 0;
  1757. switch ($xfOrientation) {
  1758. case 0:
  1759. $objStyle->getAlignment()->setTextRotation(0);
  1760. break;
  1761. case 1:
  1762. $objStyle->getAlignment()->setTextRotation(-165);
  1763. break;
  1764. case 2:
  1765. $objStyle->getAlignment()->setTextRotation(90);
  1766. break;
  1767. case 3:
  1768. $objStyle->getAlignment()->setTextRotation(-90);
  1769. break;
  1770. }
  1771. // offset: 8; size: 4; cell border lines and background area
  1772. $borderAndBackground = self::_GetInt4d($recordData, 8);
  1773. // bit: 6-0; mask: 0x0000007F; color index for pattern color
  1774. $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0;
  1775. // bit: 13-7; mask: 0x00003F80; color index for pattern background
  1776. $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7;
  1777. // bit: 21-16; mask: 0x003F0000; fill pattern
  1778. $objStyle->getFill()->setFillType(self::_mapFillPattern((0x003F0000 & $borderAndBackground) >> 16));
  1779. // bit: 24-22; mask: 0x01C00000; bottom line style
  1780. $objStyle->getBorders()->getBottom()->setBorderStyle(self::_mapBorderStyle((0x01C00000 & $borderAndBackground) >> 22));
  1781. // bit: 31-25; mask: 0xFE000000; bottom line color
  1782. $objStyle->getBorders()->getBottom()->colorIndex = (0xFE000000 & $borderAndBackground) >> 25;
  1783. // offset: 12; size: 4; cell border lines
  1784. $borderLines = self::_GetInt4d($recordData, 12);
  1785. // bit: 2-0; mask: 0x00000007; top line style
  1786. $objStyle->getBorders()->getTop()->setBorderStyle(self::_mapBorderStyle((0x00000007 & $borderLines) >> 0));
  1787. // bit: 5-3; mask: 0x00000038; left line style
  1788. $objStyle->getBorders()->getLeft()->setBorderStyle(self::_mapBorderStyle((0x00000038 & $borderLines) >> 3));
  1789. // bit: 8-6; mask: 0x000001C0; right line style
  1790. $objStyle->getBorders()->getRight()->setBorderStyle(self::_mapBorderStyle((0x000001C0 & $borderLines) >> 6));
  1791. // bit: 15-9; mask: 0x0000FE00; top line color index
  1792. $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9;
  1793. // bit: 22-16; mask: 0x007F0000; left line color index
  1794. $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16;
  1795. // bit: 29-23; mask: 0x3F800000; right line color index
  1796. $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23;
  1797. }
  1798. // add cellStyleXf or cellXf and update mapping
  1799. if ($isCellStyleXf) {
  1800. // we only read one style XF record which is always the first
  1801. if ($this->_xfIndex == 0) {
  1802. $this->_phpExcel->addCellStyleXf($objStyle);
  1803. $this->_mapCellStyleXfIndex[$this->_xfIndex] = 0;
  1804. }
  1805. } else {
  1806. // we read all cell XF records
  1807. $this->_phpExcel->addCellXf($objStyle);
  1808. $this->_mapCellXfIndex[$this->_xfIndex] = count($this->_phpExcel->getCellXfCollection()) - 1;
  1809. }
  1810. // update XF index for when we read next record
  1811. ++$this->_xfIndex;
  1812. }
  1813. }
  1814. /**
  1815. *
  1816. */
  1817. private function _readXfExt()
  1818. {
  1819. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1820. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1821. // move stream pointer to next record
  1822. $this->_pos += 4 + $length;
  1823. if (!$this->_readDataOnly) {
  1824. // offset: 0; size: 2; 0x087D = repeated header
  1825. // offset: 2; size: 2
  1826. // offset: 4; size: 8; not used
  1827. // offset: 12; size: 2; record version
  1828. // offset: 14; size: 2; index to XF record which this record modifies
  1829. $ixfe = self::_GetInt2d($recordData, 14);
  1830. // offset: 16; size: 2; not used
  1831. // offset: 18; size: 2; number of extension properties that follow
  1832. $cexts = self::_GetInt2d($recordData, 18);
  1833. // start reading the actual extension data
  1834. $offset = 20;
  1835. while ($offset < $length) {
  1836. // extension type
  1837. $extType = self::_GetInt2d($recordData, $offset);
  1838. // extension length
  1839. $cb = self::_GetInt2d($recordData, $offset + 2);
  1840. // extension data
  1841. $extData = substr($recordData, $offset + 4, $cb);
  1842. switch ($extType) {
  1843. case 4: // fill start color
  1844. $xclfType = self::_GetInt2d($extData, 0); // color type
  1845. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1846. if ($xclfType == 2) {
  1847. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1848. // modify the relevant style property
  1849. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1850. $fill = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getFill();
  1851. $fill->getStartColor()->setRGB($rgb);
  1852. unset($fill->startcolorIndex); // normal color index does not apply, discard
  1853. }
  1854. }
  1855. break;
  1856. case 5: // fill end color
  1857. $xclfType = self::_GetInt2d($extData, 0); // color type
  1858. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1859. if ($xclfType == 2) {
  1860. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1861. // modify the relevant style property
  1862. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1863. $fill = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getFill();
  1864. $fill->getEndColor()->setRGB($rgb);
  1865. unset($fill->endcolorIndex); // normal color index does not apply, discard
  1866. }
  1867. }
  1868. break;
  1869. case 7: // border color top
  1870. $xclfType = self::_GetInt2d($extData, 0); // color type
  1871. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1872. if ($xclfType == 2) {
  1873. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1874. // modify the relevant style property
  1875. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1876. $top = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getTop();
  1877. $top->getColor()->setRGB($rgb);
  1878. unset($top->colorIndex); // normal color index does not apply, discard
  1879. }
  1880. }
  1881. break;
  1882. case 8: // border color bottom
  1883. $xclfType = self::_GetInt2d($extData, 0); // color type
  1884. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1885. if ($xclfType == 2) {
  1886. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1887. // modify the relevant style property
  1888. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1889. $bottom = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getBottom();
  1890. $bottom->getColor()->setRGB($rgb);
  1891. unset($bottom->colorIndex); // normal color index does not apply, discard
  1892. }
  1893. }
  1894. break;
  1895. case 9: // border color left
  1896. $xclfType = self::_GetInt2d($extData, 0); // color type
  1897. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1898. if ($xclfType == 2) {
  1899. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1900. // modify the relevant style property
  1901. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1902. $left = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getLeft();
  1903. $left->getColor()->setRGB($rgb);
  1904. unset($left->colorIndex); // normal color index does not apply, discard
  1905. }
  1906. }
  1907. break;
  1908. case 10: // border color right
  1909. $xclfType = self::_GetInt2d($extData, 0); // color type
  1910. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1911. if ($xclfType == 2) {
  1912. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1913. // modify the relevant style property
  1914. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1915. $right = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getRight();
  1916. $right->getColor()->setRGB($rgb);
  1917. unset($right->colorIndex); // normal color index does not apply, discard
  1918. }
  1919. }
  1920. break;
  1921. case 11: // border color diagonal
  1922. $xclfType = self::_GetInt2d($extData, 0); // color type
  1923. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1924. if ($xclfType == 2) {
  1925. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1926. // modify the relevant style property
  1927. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1928. $diagonal = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getDiagonal();
  1929. $diagonal->getColor()->setRGB($rgb);
  1930. unset($diagonal->colorIndex); // normal color index does not apply, discard
  1931. }
  1932. }
  1933. break;
  1934. case 13: // font color
  1935. $xclfType = self::_GetInt2d($extData, 0); // color type
  1936. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  1937. if ($xclfType == 2) {
  1938. $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2}));
  1939. // modify the relevant style property
  1940. if ( isset($this->_mapCellXfIndex[$ixfe]) ) {
  1941. $font = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getFont();
  1942. $font->getColor()->setRGB($rgb);
  1943. unset($font->colorIndex); // normal color index does not apply, discard
  1944. }
  1945. }
  1946. break;
  1947. }
  1948. $offset += $cb;
  1949. }
  1950. }
  1951. }
  1952. /**
  1953. * Read STYLE record
  1954. */
  1955. private function _readStyle()
  1956. {
  1957. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1958. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1959. // move stream pointer to next record
  1960. $this->_pos += 4 + $length;
  1961. if (!$this->_readDataOnly) {
  1962. // offset: 0; size: 2; index to XF record and flag for built-in style
  1963. $ixfe = self::_GetInt2d($recordData, 0);
  1964. // bit: 11-0; mask 0x0FFF; index to XF record
  1965. $xfIndex = (0x0FFF & $ixfe) >> 0;
  1966. // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style
  1967. $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15);
  1968. if ($isBuiltIn) {
  1969. // offset: 2; size: 1; identifier for built-in style
  1970. $builtInId = ord($recordData{2});
  1971. switch ($builtInId) {
  1972. case 0x00:
  1973. // currently, we are not using this for anything
  1974. break;
  1975. default:
  1976. break;
  1977. }
  1978. } else {
  1979. // user-defined; not supported by PHPExcel
  1980. }
  1981. }
  1982. }
  1983. /**
  1984. * Read PALETTE record
  1985. */
  1986. private function _readPalette()
  1987. {
  1988. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  1989. $recordData = substr($this->_data, $this->_pos + 4, $length);
  1990. // move stream pointer to next record
  1991. $this->_pos += 4 + $length;
  1992. if (!$this->_readDataOnly) {
  1993. // offset: 0; size: 2; number of following colors
  1994. $nm = self::_GetInt2d($recordData, 0);
  1995. // list of RGB colors
  1996. for ($i = 0; $i < $nm; ++$i) {
  1997. $rgb = substr($recordData, 2 + 4 * $i, 4);
  1998. $this->_palette[] = self::_readRGB($rgb);
  1999. }
  2000. }
  2001. }
  2002. /**
  2003. * SHEET
  2004. *
  2005. * This record is located in the Workbook Globals
  2006. * Substream and represents a sheet inside the workbook.
  2007. * One SHEET record is written for each sheet. It stores the
  2008. * sheet name and a stream offset to the BOF record of the
  2009. * respective Sheet Substream within the Workbook Stream.
  2010. *
  2011. * -- "OpenOffice.org's Documentation of the Microsoft
  2012. * Excel File Format"
  2013. */
  2014. private function _readSheet()
  2015. {
  2016. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2017. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2018. // move stream pointer to next record
  2019. $this->_pos += 4 + $length;
  2020. // offset: 0; size: 4; absolute stream position of the BOF record of the sheet
  2021. $rec_offset = self::_GetInt4d($recordData, 0);
  2022. // offset: 4; size: 1; sheet state
  2023. switch (ord($recordData{4})) {
  2024. case 0x00: $sheetState = PHPExcel_Worksheet::SHEETSTATE_VISIBLE; break;
  2025. case 0x01: $sheetState = PHPExcel_Worksheet::SHEETSTATE_HIDDEN; break;
  2026. case 0x02: $sheetState = PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN; break;
  2027. default: $sheetState = PHPExcel_Worksheet::SHEETSTATE_VISIBLE; break;
  2028. }
  2029. // offset: 5; size: 1; sheet type
  2030. $sheetType = ord($recordData{5});
  2031. // offset: 6; size: var; sheet name
  2032. if ($this->_version == self::XLS_BIFF8) {
  2033. $string = self::_readUnicodeStringShort(substr($recordData, 6));
  2034. $rec_name = $string['value'];
  2035. } elseif ($this->_version == self::XLS_BIFF7) {
  2036. $string = $this->_readByteStringShort(substr($recordData, 6));
  2037. $rec_name = $string['value'];
  2038. }
  2039. $this->_sheets[] = array(
  2040. 'name' => $rec_name,
  2041. 'offset' => $rec_offset,
  2042. 'sheetState' => $sheetState,
  2043. 'sheetType' => $sheetType,
  2044. );
  2045. }
  2046. /**
  2047. * Read EXTERNALBOOK record
  2048. */
  2049. private function _readExternalBook()
  2050. {
  2051. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2052. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2053. // move stream pointer to next record
  2054. $this->_pos += 4 + $length;
  2055. // offset within record data
  2056. $offset = 0;
  2057. // there are 4 types of records
  2058. if (strlen($recordData) > 4) {
  2059. // external reference
  2060. // offset: 0; size: 2; number of sheet names ($nm)
  2061. $nm = self::_GetInt2d($recordData, 0);
  2062. $offset += 2;
  2063. // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length)
  2064. $encodedUrlString = self::_readUnicodeStringLong(substr($recordData, 2));
  2065. $offset += $encodedUrlString['size'];
  2066. // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length)
  2067. $externalSheetNames = array();
  2068. for ($i = 0; $i < $nm; ++$i) {
  2069. $externalSheetNameString = self::_readUnicodeStringLong(substr($recordData, $offset));
  2070. $externalSheetNames[] = $externalSheetNameString['value'];
  2071. $offset += $externalSheetNameString['size'];
  2072. }
  2073. // store the record data
  2074. $this->_externalBooks[] = array(
  2075. 'type' => 'external',
  2076. 'encodedUrl' => $encodedUrlString['value'],
  2077. 'externalSheetNames' => $externalSheetNames,
  2078. );
  2079. } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) {
  2080. // internal reference
  2081. // offset: 0; size: 2; number of sheet in this document
  2082. // offset: 2; size: 2; 0x01 0x04
  2083. $this->_externalBooks[] = array(
  2084. 'type' => 'internal',
  2085. );
  2086. } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) {
  2087. // add-in function
  2088. // offset: 0; size: 2; 0x0001
  2089. $this->_externalBooks[] = array(
  2090. 'type' => 'addInFunction',
  2091. );
  2092. } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) {
  2093. // DDE links, OLE links
  2094. // offset: 0; size: 2; 0x0000
  2095. // offset: 2; size: var; encoded source document name
  2096. $this->_externalBooks[] = array(
  2097. 'type' => 'DDEorOLE',
  2098. );
  2099. }
  2100. }
  2101. /**
  2102. * Read EXTERNNAME record.
  2103. */
  2104. private function _readExternName()
  2105. {
  2106. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2107. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2108. // move stream pointer to next record
  2109. $this->_pos += 4 + $length;
  2110. // external sheet references provided for named cells
  2111. if ($this->_version == self::XLS_BIFF8) {
  2112. // offset: 0; size: 2; options
  2113. $options = self::_GetInt2d($recordData, 0);
  2114. // offset: 2; size: 2;
  2115. // offset: 4; size: 2; not used
  2116. // offset: 6; size: var
  2117. $nameString = self::_readUnicodeStringShort(substr($recordData, 6));
  2118. // offset: var; size: var; formula data
  2119. $offset = 6 + $nameString['size'];
  2120. $formula = $this->_getFormulaFromStructure(substr($recordData, $offset));
  2121. $this->_externalNames[] = array(
  2122. 'name' => $nameString['value'],
  2123. 'formula' => $formula,
  2124. );
  2125. }
  2126. }
  2127. /**
  2128. * Read EXTERNSHEET record
  2129. */
  2130. private function _readExternSheet()
  2131. {
  2132. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2133. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2134. // move stream pointer to next record
  2135. $this->_pos += 4 + $length;
  2136. // external sheet references provided for named cells
  2137. if ($this->_version == self::XLS_BIFF8) {
  2138. // offset: 0; size: 2; number of following ref structures
  2139. $nm = self::_GetInt2d($recordData, 0);
  2140. for ($i = 0; $i < $nm; ++$i) {
  2141. $this->_ref[] = array(
  2142. // offset: 2 + 6 * $i; index to EXTERNALBOOK record
  2143. 'externalBookIndex' => self::_GetInt2d($recordData, 2 + 6 * $i),
  2144. // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record
  2145. 'firstSheetIndex' => self::_GetInt2d($recordData, 4 + 6 * $i),
  2146. // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record
  2147. 'lastSheetIndex' => self::_GetInt2d($recordData, 6 + 6 * $i),
  2148. );
  2149. }
  2150. }
  2151. }
  2152. /**
  2153. * DEFINEDNAME
  2154. *
  2155. * This record is part of a Link Table. It contains the name
  2156. * and the token array of an internal defined name. Token
  2157. * arrays of defined names contain tokens with aberrant
  2158. * token classes.
  2159. *
  2160. * -- "OpenOffice.org's Documentation of the Microsoft
  2161. * Excel File Format"
  2162. */
  2163. private function _readDefinedName()
  2164. {
  2165. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2166. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2167. // move stream pointer to next record
  2168. $this->_pos += 4 + $length;
  2169. if ($this->_version == self::XLS_BIFF8) {
  2170. // retrieves named cells
  2171. // offset: 0; size: 2; option flags
  2172. $opts = self::_GetInt2d($recordData, 0);
  2173. // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name
  2174. $isBuiltInName = (0x0020 & $opts) >> 5;
  2175. // offset: 2; size: 1; keyboard shortcut
  2176. // offset: 3; size: 1; length of the name (character count)
  2177. $nlen = ord($recordData{3});
  2178. // offset: 4; size: 2; size of the formula data (it can happen that this is zero)
  2179. // note: there can also be additional data, this is not included in $flen
  2180. $flen = self::_GetInt2d($recordData, 4);
  2181. // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based)
  2182. $scope = self::_GetInt2d($recordData, 8);
  2183. // offset: 14; size: var; Name (Unicode string without length field)
  2184. $string = self::_readUnicodeString(substr($recordData, 14), $nlen);
  2185. // offset: var; size: $flen; formula data
  2186. $offset = 14 + $string['size'];
  2187. $formulaStructure = pack('v', $flen) . substr($recordData, $offset);
  2188. try {
  2189. $formula = $this->_getFormulaFromStructure($formulaStructure);
  2190. } catch (Exception $e) {
  2191. $formula = '';
  2192. }
  2193. $this->_definedname[] = array(
  2194. 'isBuiltInName' => $isBuiltInName,
  2195. 'name' => $string['value'],
  2196. 'formula' => $formula,
  2197. 'scope' => $scope,
  2198. );
  2199. }
  2200. }
  2201. /**
  2202. * Read MSODRAWINGGROUP record
  2203. */
  2204. private function _readMsoDrawingGroup()
  2205. {
  2206. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2207. // get spliced record data
  2208. $splicedRecordData = $this->_getSplicedRecordData();
  2209. $recordData = $splicedRecordData['recordData'];
  2210. $this->_drawingGroupData .= $recordData;
  2211. }
  2212. /**
  2213. * SST - Shared String Table
  2214. *
  2215. * This record contains a list of all strings used anywhere
  2216. * in the workbook. Each string occurs only once. The
  2217. * workbook uses indexes into the list to reference the
  2218. * strings.
  2219. *
  2220. * -- "OpenOffice.org's Documentation of the Microsoft
  2221. * Excel File Format"
  2222. **/
  2223. private function _readSst()
  2224. {
  2225. // offset within (spliced) record data
  2226. $pos = 0;
  2227. // get spliced record data
  2228. $splicedRecordData = $this->_getSplicedRecordData();
  2229. $recordData = $splicedRecordData['recordData'];
  2230. $spliceOffsets = $splicedRecordData['spliceOffsets'];
  2231. // offset: 0; size: 4; total number of strings in the workbook
  2232. $pos += 4;
  2233. // offset: 4; size: 4; number of following strings ($nm)
  2234. $nm = self::_GetInt4d($recordData, 4);
  2235. $pos += 4;
  2236. // loop through the Unicode strings (16-bit length)
  2237. for ($i = 0; $i < $nm; ++$i) {
  2238. // number of characters in the Unicode string
  2239. $numChars = self::_GetInt2d($recordData, $pos);
  2240. $pos += 2;
  2241. // option flags
  2242. $optionFlags = ord($recordData{$pos});
  2243. ++$pos;
  2244. // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed
  2245. $isCompressed = (($optionFlags & 0x01) == 0) ;
  2246. // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic
  2247. $hasAsian = (($optionFlags & 0x04) != 0);
  2248. // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text
  2249. $hasRichText = (($optionFlags & 0x08) != 0);
  2250. if ($hasRichText) {
  2251. // number of Rich-Text formatting runs
  2252. $formattingRuns = self::_GetInt2d($recordData, $pos);
  2253. $pos += 2;
  2254. }
  2255. if ($hasAsian) {
  2256. // size of Asian phonetic setting
  2257. $extendedRunLength = self::_GetInt4d($recordData, $pos);
  2258. $pos += 4;
  2259. }
  2260. // expected byte length of character array if not split
  2261. $len = ($isCompressed) ? $numChars : $numChars * 2;
  2262. // look up limit position
  2263. foreach ($spliceOffsets as $spliceOffset) {
  2264. // it can happen that the string is empty, therefore we need
  2265. // <= and not just <
  2266. if ($pos <= $spliceOffset) {
  2267. $limitpos = $spliceOffset;
  2268. break;
  2269. }
  2270. }
  2271. if ($pos + $len <= $limitpos) {
  2272. // character array is not split between records
  2273. $retstr = substr($recordData, $pos, $len);
  2274. $pos += $len;
  2275. } else {
  2276. // character array is split between records
  2277. // first part of character array
  2278. $retstr = substr($recordData, $pos, $limitpos - $pos);
  2279. $bytesRead = $limitpos - $pos;
  2280. // remaining characters in Unicode string
  2281. $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2));
  2282. $pos = $limitpos;
  2283. // keep reading the characters
  2284. while ($charsLeft > 0) {
  2285. // look up next limit position, in case the string span more than one continue record
  2286. foreach ($spliceOffsets as $spliceOffset) {
  2287. if ($pos < $spliceOffset) {
  2288. $limitpos = $spliceOffset;
  2289. break;
  2290. }
  2291. }
  2292. // repeated option flags
  2293. // OpenOffice.org documentation 5.21
  2294. $option = ord($recordData{$pos});
  2295. ++$pos;
  2296. if ($isCompressed && ($option == 0)) {
  2297. // 1st fragment compressed
  2298. // this fragment compressed
  2299. $len = min($charsLeft, $limitpos - $pos);
  2300. $retstr .= substr($recordData, $pos, $len);
  2301. $charsLeft -= $len;
  2302. $isCompressed = true;
  2303. } elseif (!$isCompressed && ($option != 0)) {
  2304. // 1st fragment uncompressed
  2305. // this fragment uncompressed
  2306. $len = min($charsLeft * 2, $limitpos - $pos);
  2307. $retstr .= substr($recordData, $pos, $len);
  2308. $charsLeft -= $len / 2;
  2309. $isCompressed = false;
  2310. } elseif (!$isCompressed && ($option == 0)) {
  2311. // 1st fragment uncompressed
  2312. // this fragment compressed
  2313. $len = min($charsLeft, $limitpos - $pos);
  2314. for ($j = 0; $j < $len; ++$j) {
  2315. $retstr .= $recordData{$pos + $j} . chr(0);
  2316. }
  2317. $charsLeft -= $len;
  2318. $isCompressed = false;
  2319. } else {
  2320. // 1st fragment compressed
  2321. // this fragment uncompressed
  2322. $newstr = '';
  2323. for ($j = 0; $j < strlen($retstr); ++$j) {
  2324. $newstr .= $retstr[$j] . chr(0);
  2325. }
  2326. $retstr = $newstr;
  2327. $len = min($charsLeft * 2, $limitpos - $pos);
  2328. $retstr .= substr($recordData, $pos, $len);
  2329. $charsLeft -= $len / 2;
  2330. $isCompressed = false;
  2331. }
  2332. $pos += $len;
  2333. }
  2334. }
  2335. // convert to UTF-8
  2336. $retstr = self::_encodeUTF16($retstr, $isCompressed);
  2337. // read additional Rich-Text information, if any
  2338. $fmtRuns = array();
  2339. if ($hasRichText) {
  2340. // list of formatting runs
  2341. for ($j = 0; $j < $formattingRuns; ++$j) {
  2342. // first formatted character; zero-based
  2343. $charPos = self::_GetInt2d($recordData, $pos + $j * 4);
  2344. // index to font record
  2345. $fontIndex = self::_GetInt2d($recordData, $pos + 2 + $j * 4);
  2346. $fmtRuns[] = array(
  2347. 'charPos' => $charPos,
  2348. 'fontIndex' => $fontIndex,
  2349. );
  2350. }
  2351. $pos += 4 * $formattingRuns;
  2352. }
  2353. // read additional Asian phonetics information, if any
  2354. if ($hasAsian) {
  2355. // For Asian phonetic settings, we skip the extended string data
  2356. $pos += $extendedRunLength;
  2357. }
  2358. // store the shared sting
  2359. $this->_sst[] = array(
  2360. 'value' => $retstr,
  2361. 'fmtRuns' => $fmtRuns,
  2362. );
  2363. }
  2364. // _getSplicedRecordData() takes care of moving current position in data stream
  2365. }
  2366. /**
  2367. * Read PRINTGRIDLINES record
  2368. */
  2369. private function _readPrintGridlines()
  2370. {
  2371. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2372. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2373. // move stream pointer to next record
  2374. $this->_pos += 4 + $length;
  2375. if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) {
  2376. // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines
  2377. $printGridlines = (bool) self::_GetInt2d($recordData, 0);
  2378. $this->_phpSheet->setPrintGridlines($printGridlines);
  2379. }
  2380. }
  2381. /**
  2382. * Read DEFAULTROWHEIGHT record
  2383. */
  2384. private function _readDefaultRowHeight()
  2385. {
  2386. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2387. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2388. // move stream pointer to next record
  2389. $this->_pos += 4 + $length;
  2390. // offset: 0; size: 2; option flags
  2391. // offset: 2; size: 2; default height for unused rows, (twips 1/20 point)
  2392. $height = self::_GetInt2d($recordData, 2);
  2393. $this->_phpSheet->getDefaultRowDimension()->setRowHeight($height / 20);
  2394. }
  2395. /**
  2396. * Read SHEETPR record
  2397. */
  2398. private function _readSheetPr()
  2399. {
  2400. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2401. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2402. // move stream pointer to next record
  2403. $this->_pos += 4 + $length;
  2404. // offset: 0; size: 2
  2405. // bit: 6; mask: 0x0040; 0 = outline buttons above outline group
  2406. $isSummaryBelow = (0x0040 & self::_GetInt2d($recordData, 0)) >> 6;
  2407. $this->_phpSheet->setShowSummaryBelow($isSummaryBelow);
  2408. // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group
  2409. $isSummaryRight = (0x0080 & self::_GetInt2d($recordData, 0)) >> 7;
  2410. $this->_phpSheet->setShowSummaryRight($isSummaryRight);
  2411. // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages
  2412. // this corresponds to radio button setting in page setup dialog in Excel
  2413. $this->_isFitToPages = (bool) ((0x0100 & self::_GetInt2d($recordData, 0)) >> 8);
  2414. }
  2415. /**
  2416. * Read HORIZONTALPAGEBREAKS record
  2417. */
  2418. private function _readHorizontalPageBreaks()
  2419. {
  2420. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2421. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2422. // move stream pointer to next record
  2423. $this->_pos += 4 + $length;
  2424. if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) {
  2425. // offset: 0; size: 2; number of the following row index structures
  2426. $nm = self::_GetInt2d($recordData, 0);
  2427. // offset: 2; size: 6 * $nm; list of $nm row index structures
  2428. for ($i = 0; $i < $nm; ++$i) {
  2429. $r = self::_GetInt2d($recordData, 2 + 6 * $i);
  2430. $cf = self::_GetInt2d($recordData, 2 + 6 * $i + 2);
  2431. $cl = self::_GetInt2d($recordData, 2 + 6 * $i + 4);
  2432. // not sure why two column indexes are necessary?
  2433. $this->_phpSheet->setBreakByColumnAndRow($cf, $r, PHPExcel_Worksheet::BREAK_ROW);
  2434. }
  2435. }
  2436. }
  2437. /**
  2438. * Read VERTICALPAGEBREAKS record
  2439. */
  2440. private function _readVerticalPageBreaks()
  2441. {
  2442. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2443. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2444. // move stream pointer to next record
  2445. $this->_pos += 4 + $length;
  2446. if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) {
  2447. // offset: 0; size: 2; number of the following column index structures
  2448. $nm = self::_GetInt2d($recordData, 0);
  2449. // offset: 2; size: 6 * $nm; list of $nm row index structures
  2450. for ($i = 0; $i < $nm; ++$i) {
  2451. $c = self::_GetInt2d($recordData, 2 + 6 * $i);
  2452. $rf = self::_GetInt2d($recordData, 2 + 6 * $i + 2);
  2453. $rl = self::_GetInt2d($recordData, 2 + 6 * $i + 4);
  2454. // not sure why two row indexes are necessary?
  2455. $this->_phpSheet->setBreakByColumnAndRow($c, $rf, PHPExcel_Worksheet::BREAK_COLUMN);
  2456. }
  2457. }
  2458. }
  2459. /**
  2460. * Read HEADER record
  2461. */
  2462. private function _readHeader()
  2463. {
  2464. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2465. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2466. // move stream pointer to next record
  2467. $this->_pos += 4 + $length;
  2468. if (!$this->_readDataOnly) {
  2469. // offset: 0; size: var
  2470. // realized that $recordData can be empty even when record exists
  2471. if ($recordData) {
  2472. if ($this->_version == self::XLS_BIFF8) {
  2473. $string = self::_readUnicodeStringLong($recordData);
  2474. } else {
  2475. $string = $this->_readByteStringShort($recordData);
  2476. }
  2477. $this->_phpSheet->getHeaderFooter()->setOddHeader($string['value']);
  2478. $this->_phpSheet->getHeaderFooter()->setEvenHeader($string['value']);
  2479. }
  2480. }
  2481. }
  2482. /**
  2483. * Read FOOTER record
  2484. */
  2485. private function _readFooter()
  2486. {
  2487. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2488. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2489. // move stream pointer to next record
  2490. $this->_pos += 4 + $length;
  2491. if (!$this->_readDataOnly) {
  2492. // offset: 0; size: var
  2493. // realized that $recordData can be empty even when record exists
  2494. if ($recordData) {
  2495. if ($this->_version == self::XLS_BIFF8) {
  2496. $string = self::_readUnicodeStringLong($recordData);
  2497. } else {
  2498. $string = $this->_readByteStringShort($recordData);
  2499. }
  2500. $this->_phpSheet->getHeaderFooter()->setOddFooter($string['value']);
  2501. $this->_phpSheet->getHeaderFooter()->setEvenFooter($string['value']);
  2502. }
  2503. }
  2504. }
  2505. /**
  2506. * Read HCENTER record
  2507. */
  2508. private function _readHcenter()
  2509. {
  2510. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2511. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2512. // move stream pointer to next record
  2513. $this->_pos += 4 + $length;
  2514. if (!$this->_readDataOnly) {
  2515. // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally
  2516. $isHorizontalCentered = (bool) self::_GetInt2d($recordData, 0);
  2517. $this->_phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered);
  2518. }
  2519. }
  2520. /**
  2521. * Read VCENTER record
  2522. */
  2523. private function _readVcenter()
  2524. {
  2525. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2526. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2527. // move stream pointer to next record
  2528. $this->_pos += 4 + $length;
  2529. if (!$this->_readDataOnly) {
  2530. // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered
  2531. $isVerticalCentered = (bool) self::_GetInt2d($recordData, 0);
  2532. $this->_phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered);
  2533. }
  2534. }
  2535. /**
  2536. * Read LEFTMARGIN record
  2537. */
  2538. private function _readLeftMargin()
  2539. {
  2540. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2541. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2542. // move stream pointer to next record
  2543. $this->_pos += 4 + $length;
  2544. if (!$this->_readDataOnly) {
  2545. // offset: 0; size: 8
  2546. $this->_phpSheet->getPageMargins()->setLeft(self::_extractNumber($recordData));
  2547. }
  2548. }
  2549. /**
  2550. * Read RIGHTMARGIN record
  2551. */
  2552. private function _readRightMargin()
  2553. {
  2554. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2555. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2556. // move stream pointer to next record
  2557. $this->_pos += 4 + $length;
  2558. if (!$this->_readDataOnly) {
  2559. // offset: 0; size: 8
  2560. $this->_phpSheet->getPageMargins()->setRight(self::_extractNumber($recordData));
  2561. }
  2562. }
  2563. /**
  2564. * Read TOPMARGIN record
  2565. */
  2566. private function _readTopMargin()
  2567. {
  2568. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2569. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2570. // move stream pointer to next record
  2571. $this->_pos += 4 + $length;
  2572. if (!$this->_readDataOnly) {
  2573. // offset: 0; size: 8
  2574. $this->_phpSheet->getPageMargins()->setTop(self::_extractNumber($recordData));
  2575. }
  2576. }
  2577. /**
  2578. * Read BOTTOMMARGIN record
  2579. */
  2580. private function _readBottomMargin()
  2581. {
  2582. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2583. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2584. // move stream pointer to next record
  2585. $this->_pos += 4 + $length;
  2586. if (!$this->_readDataOnly) {
  2587. // offset: 0; size: 8
  2588. $this->_phpSheet->getPageMargins()->setBottom(self::_extractNumber($recordData));
  2589. }
  2590. }
  2591. /**
  2592. * Read PAGESETUP record
  2593. */
  2594. private function _readPageSetup()
  2595. {
  2596. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2597. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2598. // move stream pointer to next record
  2599. $this->_pos += 4 + $length;
  2600. if (!$this->_readDataOnly) {
  2601. // offset: 0; size: 2; paper size
  2602. $paperSize = self::_GetInt2d($recordData, 0);
  2603. // offset: 2; size: 2; scaling factor
  2604. $scale = self::_GetInt2d($recordData, 2);
  2605. // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed
  2606. $fitToWidth = self::_GetInt2d($recordData, 6);
  2607. // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed
  2608. $fitToHeight = self::_GetInt2d($recordData, 8);
  2609. // offset: 10; size: 2; option flags
  2610. // bit: 1; mask: 0x0002; 0=landscape, 1=portrait
  2611. $isPortrait = (0x0002 & self::_GetInt2d($recordData, 10)) >> 1;
  2612. // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init
  2613. // when this bit is set, do not use flags for those properties
  2614. $isNotInit = (0x0004 & self::_GetInt2d($recordData, 10)) >> 2;
  2615. if (!$isNotInit) {
  2616. $this->_phpSheet->getPageSetup()->setPaperSize($paperSize);
  2617. switch ($isPortrait) {
  2618. case 0: $this->_phpSheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE); break;
  2619. case 1: $this->_phpSheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT); break;
  2620. }
  2621. $this->_phpSheet->getPageSetup()->setScale($scale, false);
  2622. $this->_phpSheet->getPageSetup()->setFitToPage((bool) $this->_isFitToPages);
  2623. $this->_phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false);
  2624. $this->_phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false);
  2625. }
  2626. // offset: 16; size: 8; header margin (IEEE 754 floating-point value)
  2627. $marginHeader = self::_extractNumber(substr($recordData, 16, 8));
  2628. $this->_phpSheet->getPageMargins()->setHeader($marginHeader);
  2629. // offset: 24; size: 8; footer margin (IEEE 754 floating-point value)
  2630. $marginFooter = self::_extractNumber(substr($recordData, 24, 8));
  2631. $this->_phpSheet->getPageMargins()->setFooter($marginFooter);
  2632. }
  2633. }
  2634. /**
  2635. * PROTECT - Sheet protection (BIFF2 through BIFF8)
  2636. * if this record is omitted, then it also means no sheet protection
  2637. */
  2638. private function _readProtect()
  2639. {
  2640. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2641. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2642. // move stream pointer to next record
  2643. $this->_pos += 4 + $length;
  2644. if ($this->_readDataOnly) {
  2645. return;
  2646. }
  2647. // offset: 0; size: 2;
  2648. // bit 0, mask 0x01; 1 = sheet is protected
  2649. $bool = (0x01 & self::_GetInt2d($recordData, 0)) >> 0;
  2650. $this->_phpSheet->getProtection()->setSheet((bool)$bool);
  2651. }
  2652. /**
  2653. * SCENPROTECT
  2654. */
  2655. private function _readScenProtect()
  2656. {
  2657. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2658. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2659. // move stream pointer to next record
  2660. $this->_pos += 4 + $length;
  2661. if ($this->_readDataOnly) {
  2662. return;
  2663. }
  2664. // offset: 0; size: 2;
  2665. // bit: 0, mask 0x01; 1 = scenarios are protected
  2666. $bool = (0x01 & self::_GetInt2d($recordData, 0)) >> 0;
  2667. $this->_phpSheet->getProtection()->setScenarios((bool)$bool);
  2668. }
  2669. /**
  2670. * OBJECTPROTECT
  2671. */
  2672. private function _readObjectProtect()
  2673. {
  2674. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2675. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2676. // move stream pointer to next record
  2677. $this->_pos += 4 + $length;
  2678. if ($this->_readDataOnly) {
  2679. return;
  2680. }
  2681. // offset: 0; size: 2;
  2682. // bit: 0, mask 0x01; 1 = objects are protected
  2683. $bool = (0x01 & self::_GetInt2d($recordData, 0)) >> 0;
  2684. $this->_phpSheet->getProtection()->setObjects((bool)$bool);
  2685. }
  2686. /**
  2687. * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8)
  2688. */
  2689. private function _readPassword()
  2690. {
  2691. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2692. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2693. // move stream pointer to next record
  2694. $this->_pos += 4 + $length;
  2695. if (!$this->_readDataOnly) {
  2696. // offset: 0; size: 2; 16-bit hash value of password
  2697. $password = strtoupper(dechex(self::_GetInt2d($recordData, 0))); // the hashed password
  2698. $this->_phpSheet->getProtection()->setPassword($password, true);
  2699. }
  2700. }
  2701. /**
  2702. * Read DEFCOLWIDTH record
  2703. */
  2704. private function _readDefColWidth()
  2705. {
  2706. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2707. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2708. // move stream pointer to next record
  2709. $this->_pos += 4 + $length;
  2710. // offset: 0; size: 2; default column width
  2711. $width = self::_GetInt2d($recordData, 0);
  2712. if ($width != 8) {
  2713. $this->_phpSheet->getDefaultColumnDimension()->setWidth($width);
  2714. }
  2715. }
  2716. /**
  2717. * Read COLINFO record
  2718. */
  2719. private function _readColInfo()
  2720. {
  2721. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2722. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2723. // move stream pointer to next record
  2724. $this->_pos += 4 + $length;
  2725. if (!$this->_readDataOnly) {
  2726. // offset: 0; size: 2; index to first column in range
  2727. $fc = self::_GetInt2d($recordData, 0); // first column index
  2728. // offset: 2; size: 2; index to last column in range
  2729. $lc = self::_GetInt2d($recordData, 2); // first column index
  2730. // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character
  2731. $width = self::_GetInt2d($recordData, 4);
  2732. // offset: 6; size: 2; index to XF record for default column formatting
  2733. $xfIndex = self::_GetInt2d($recordData, 6);
  2734. // offset: 8; size: 2; option flags
  2735. // bit: 0; mask: 0x0001; 1= columns are hidden
  2736. $isHidden = (0x0001 & self::_GetInt2d($recordData, 8)) >> 0;
  2737. // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline)
  2738. $level = (0x0700 & self::_GetInt2d($recordData, 8)) >> 8;
  2739. // bit: 12; mask: 0x1000; 1 = collapsed
  2740. $isCollapsed = (0x1000 & self::_GetInt2d($recordData, 8)) >> 12;
  2741. // offset: 10; size: 2; not used
  2742. for ($i = $fc; $i <= $lc; ++$i) {
  2743. if ($lc == 255 || $lc == 256) {
  2744. $this->_phpSheet->getDefaultColumnDimension()->setWidth($width / 256);
  2745. break;
  2746. }
  2747. $this->_phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256);
  2748. $this->_phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden);
  2749. $this->_phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level);
  2750. $this->_phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed);
  2751. $this->_phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  2752. }
  2753. }
  2754. }
  2755. /**
  2756. * ROW
  2757. *
  2758. * This record contains the properties of a single row in a
  2759. * sheet. Rows and cells in a sheet are divided into blocks
  2760. * of 32 rows.
  2761. *
  2762. * -- "OpenOffice.org's Documentation of the Microsoft
  2763. * Excel File Format"
  2764. */
  2765. private function _readRow()
  2766. {
  2767. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2768. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2769. // move stream pointer to next record
  2770. $this->_pos += 4 + $length;
  2771. if (!$this->_readDataOnly) {
  2772. // offset: 0; size: 2; index of this row
  2773. $r = self::_GetInt2d($recordData, 0);
  2774. // offset: 2; size: 2; index to column of the first cell which is described by a cell record
  2775. // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1
  2776. // offset: 6; size: 2;
  2777. // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point
  2778. $height = (0x7FFF & self::_GetInt2d($recordData, 6)) >> 0;
  2779. // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height
  2780. $useDefaultHeight = (0x8000 & self::_GetInt2d($recordData, 6)) >> 15;
  2781. if (!$useDefaultHeight) {
  2782. $this->_phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20);
  2783. }
  2784. // offset: 8; size: 2; not used
  2785. // offset: 10; size: 2; not used in BIFF5-BIFF8
  2786. // offset: 12; size: 4; option flags and default row formatting
  2787. // bit: 2-0: mask: 0x00000007; outline level of the row
  2788. $level = (0x00000007 & self::_GetInt4d($recordData, 12)) >> 0;
  2789. $this->_phpSheet->getRowDimension($r + 1)->setOutlineLevel($level);
  2790. // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed
  2791. $isCollapsed = (0x00000010 & self::_GetInt4d($recordData, 12)) >> 4;
  2792. $this->_phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed);
  2793. // bit: 5; mask: 0x00000020; 1 = row is hidden
  2794. $isHidden = (0x00000020 & self::_GetInt4d($recordData, 12)) >> 5;
  2795. $this->_phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden);
  2796. // bit: 7; mask: 0x00000080; 1 = row has explicit format
  2797. $hasExplicitFormat = (0x00000080 & self::_GetInt4d($recordData, 12)) >> 7;
  2798. // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record
  2799. $xfIndex = (0x0FFF0000 & self::_GetInt4d($recordData, 12)) >> 16;
  2800. if ($hasExplicitFormat) {
  2801. $this->_phpSheet->getRowDimension($r + 1)->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  2802. }
  2803. }
  2804. }
  2805. /**
  2806. * Read RK record
  2807. * This record represents a cell that contains an RK value
  2808. * (encoded integer or floating-point value). If a
  2809. * floating-point value cannot be encoded to an RK value,
  2810. * a NUMBER record will be written. This record replaces the
  2811. * record INTEGER written in BIFF2.
  2812. *
  2813. * -- "OpenOffice.org's Documentation of the Microsoft
  2814. * Excel File Format"
  2815. */
  2816. private function _readRk()
  2817. {
  2818. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2819. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2820. // move stream pointer to next record
  2821. $this->_pos += 4 + $length;
  2822. // offset: 0; size: 2; index to row
  2823. $row = self::_GetInt2d($recordData, 0);
  2824. // offset: 2; size: 2; index to column
  2825. $column = self::_GetInt2d($recordData, 2);
  2826. $columnString = PHPExcel_Cell::stringFromColumnIndex($column);
  2827. // Read cell?
  2828. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  2829. // offset: 4; size: 2; index to XF record
  2830. $xfIndex = self::_GetInt2d($recordData, 4);
  2831. // offset: 6; size: 4; RK value
  2832. $rknum = self::_GetInt4d($recordData, 6);
  2833. $numValue = self::_GetIEEE754($rknum);
  2834. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  2835. if (!$this->_readDataOnly) {
  2836. // add style information
  2837. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  2838. }
  2839. // add cell
  2840. $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC);
  2841. }
  2842. }
  2843. /**
  2844. * Read LABELSST record
  2845. * This record represents a cell that contains a string. It
  2846. * replaces the LABEL record and RSTRING record used in
  2847. * BIFF2-BIFF5.
  2848. *
  2849. * -- "OpenOffice.org's Documentation of the Microsoft
  2850. * Excel File Format"
  2851. */
  2852. private function _readLabelSst()
  2853. {
  2854. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2855. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2856. // move stream pointer to next record
  2857. $this->_pos += 4 + $length;
  2858. // offset: 0; size: 2; index to row
  2859. $row = self::_GetInt2d($recordData, 0);
  2860. // offset: 2; size: 2; index to column
  2861. $column = self::_GetInt2d($recordData, 2);
  2862. $columnString = PHPExcel_Cell::stringFromColumnIndex($column);
  2863. // Read cell?
  2864. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  2865. // offset: 4; size: 2; index to XF record
  2866. $xfIndex = self::_GetInt2d($recordData, 4);
  2867. // offset: 6; size: 4; index to SST record
  2868. $index = self::_GetInt4d($recordData, 6);
  2869. // add cell
  2870. if (($fmtRuns = $this->_sst[$index]['fmtRuns']) && !$this->_readDataOnly) {
  2871. // then we should treat as rich text
  2872. $richText = new PHPExcel_RichText();
  2873. $charPos = 0;
  2874. $sstCount = count($this->_sst[$index]['fmtRuns']);
  2875. for ($i = 0; $i <= $sstCount; ++$i) {
  2876. if (isset($fmtRuns[$i])) {
  2877. $text = PHPExcel_Shared_String::Substring($this->_sst[$index]['value'], $charPos, $fmtRuns[$i]['charPos'] - $charPos);
  2878. $charPos = $fmtRuns[$i]['charPos'];
  2879. } else {
  2880. $text = PHPExcel_Shared_String::Substring($this->_sst[$index]['value'], $charPos, PHPExcel_Shared_String::CountCharacters($this->_sst[$index]['value']));
  2881. }
  2882. if (PHPExcel_Shared_String::CountCharacters($text) > 0) {
  2883. if ($i == 0) { // first text run, no style
  2884. $richText->createText($text);
  2885. } else {
  2886. $textRun = $richText->createTextRun($text);
  2887. if (isset($fmtRuns[$i - 1])) {
  2888. if ($fmtRuns[$i - 1]['fontIndex'] < 4) {
  2889. $fontIndex = $fmtRuns[$i - 1]['fontIndex'];
  2890. } else {
  2891. // this has to do with that index 4 is omitted in all BIFF versions for some strange reason
  2892. // check the OpenOffice documentation of the FONT record
  2893. $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1;
  2894. }
  2895. $textRun->setFont(clone $this->_objFonts[$fontIndex]);
  2896. }
  2897. }
  2898. }
  2899. }
  2900. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  2901. $cell->setValueExplicit($richText, PHPExcel_Cell_DataType::TYPE_STRING);
  2902. } else {
  2903. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  2904. $cell->setValueExplicit($this->_sst[$index]['value'], PHPExcel_Cell_DataType::TYPE_STRING);
  2905. }
  2906. if (!$this->_readDataOnly) {
  2907. // add style information
  2908. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  2909. }
  2910. }
  2911. }
  2912. /**
  2913. * Read MULRK record
  2914. * This record represents a cell range containing RK value
  2915. * cells. All cells are located in the same row.
  2916. *
  2917. * -- "OpenOffice.org's Documentation of the Microsoft
  2918. * Excel File Format"
  2919. */
  2920. private function _readMulRk()
  2921. {
  2922. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2923. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2924. // move stream pointer to next record
  2925. $this->_pos += 4 + $length;
  2926. // offset: 0; size: 2; index to row
  2927. $row = self::_GetInt2d($recordData, 0);
  2928. // offset: 2; size: 2; index to first column
  2929. $colFirst = self::_GetInt2d($recordData, 2);
  2930. // offset: var; size: 2; index to last column
  2931. $colLast = self::_GetInt2d($recordData, $length - 2);
  2932. $columns = $colLast - $colFirst + 1;
  2933. // offset within record data
  2934. $offset = 4;
  2935. for ($i = 0; $i < $columns; ++$i) {
  2936. $columnString = PHPExcel_Cell::stringFromColumnIndex($colFirst + $i);
  2937. // Read cell?
  2938. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  2939. // offset: var; size: 2; index to XF record
  2940. $xfIndex = self::_GetInt2d($recordData, $offset);
  2941. // offset: var; size: 4; RK value
  2942. $numValue = self::_GetIEEE754(self::_GetInt4d($recordData, $offset + 2));
  2943. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  2944. if (!$this->_readDataOnly) {
  2945. // add style
  2946. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  2947. }
  2948. // add cell value
  2949. $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC);
  2950. }
  2951. $offset += 6;
  2952. }
  2953. }
  2954. /**
  2955. * Read NUMBER record
  2956. * This record represents a cell that contains a
  2957. * floating-point value.
  2958. *
  2959. * -- "OpenOffice.org's Documentation of the Microsoft
  2960. * Excel File Format"
  2961. */
  2962. private function _readNumber()
  2963. {
  2964. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2965. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2966. // move stream pointer to next record
  2967. $this->_pos += 4 + $length;
  2968. // offset: 0; size: 2; index to row
  2969. $row = self::_GetInt2d($recordData, 0);
  2970. // offset: 2; size 2; index to column
  2971. $column = self::_GetInt2d($recordData, 2);
  2972. $columnString = PHPExcel_Cell::stringFromColumnIndex($column);
  2973. // Read cell?
  2974. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  2975. // offset 4; size: 2; index to XF record
  2976. $xfIndex = self::_GetInt2d($recordData, 4);
  2977. $numValue = self::_extractNumber(substr($recordData, 6, 8));
  2978. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  2979. if (!$this->_readDataOnly) {
  2980. // add cell style
  2981. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  2982. }
  2983. // add cell value
  2984. $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC);
  2985. }
  2986. }
  2987. /**
  2988. * Read FORMULA record + perhaps a following STRING record if formula result is a string
  2989. * This record contains the token array and the result of a
  2990. * formula cell.
  2991. *
  2992. * -- "OpenOffice.org's Documentation of the Microsoft
  2993. * Excel File Format"
  2994. */
  2995. private function _readFormula()
  2996. {
  2997. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  2998. $recordData = substr($this->_data, $this->_pos + 4, $length);
  2999. // move stream pointer to next record
  3000. $this->_pos += 4 + $length;
  3001. // offset: 0; size: 2; row index
  3002. $row = self::_GetInt2d($recordData, 0);
  3003. // offset: 2; size: 2; col index
  3004. $column = self::_GetInt2d($recordData, 2);
  3005. $columnString = PHPExcel_Cell::stringFromColumnIndex($column);
  3006. // offset: 20: size: variable; formula structure
  3007. $formulaStructure = substr($recordData, 20);
  3008. // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc.
  3009. $options = self::_GetInt2d($recordData, 14);
  3010. // bit: 0; mask: 0x0001; 1 = recalculate always
  3011. // bit: 1; mask: 0x0002; 1 = calculate on open
  3012. // bit: 2; mask: 0x0008; 1 = part of a shared formula
  3013. $isPartOfSharedFormula = (bool) (0x0008 & $options);
  3014. // WARNING:
  3015. // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true
  3016. // the formula data may be ordinary formula data, therefore we need to check
  3017. // explicitly for the tExp token (0x01)
  3018. $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure{2}) == 0x01;
  3019. if ($isPartOfSharedFormula) {
  3020. // part of shared formula which means there will be a formula with a tExp token and nothing else
  3021. // get the base cell, grab tExp token
  3022. $baseRow = self::_GetInt2d($formulaStructure, 3);
  3023. $baseCol = self::_GetInt2d($formulaStructure, 5);
  3024. $this->_baseCell = PHPExcel_Cell::stringFromColumnIndex($baseCol). ($baseRow + 1);
  3025. }
  3026. // Read cell?
  3027. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  3028. if ($isPartOfSharedFormula) {
  3029. // formula is added to this cell after the sheet has been read
  3030. $this->_sharedFormulaParts[$columnString . ($row + 1)] = $this->_baseCell;
  3031. }
  3032. // offset: 16: size: 4; not used
  3033. // offset: 4; size: 2; XF index
  3034. $xfIndex = self::_GetInt2d($recordData, 4);
  3035. // offset: 6; size: 8; result of the formula
  3036. if ( (ord($recordData{6}) == 0)
  3037. && (ord($recordData{12}) == 255)
  3038. && (ord($recordData{13}) == 255) ) {
  3039. // String formula. Result follows in appended STRING record
  3040. $dataType = PHPExcel_Cell_DataType::TYPE_STRING;
  3041. // read possible SHAREDFMLA record
  3042. $code = self::_GetInt2d($this->_data, $this->_pos);
  3043. if ($code == self::XLS_Type_SHAREDFMLA) {
  3044. $this->_readSharedFmla();
  3045. }
  3046. // read STRING record
  3047. $value = $this->_readString();
  3048. } elseif ((ord($recordData{6}) == 1)
  3049. && (ord($recordData{12}) == 255)
  3050. && (ord($recordData{13}) == 255)) {
  3051. // Boolean formula. Result is in +2; 0=false, 1=true
  3052. $dataType = PHPExcel_Cell_DataType::TYPE_BOOL;
  3053. $value = (bool) ord($recordData{8});
  3054. } elseif ((ord($recordData{6}) == 2)
  3055. && (ord($recordData{12}) == 255)
  3056. && (ord($recordData{13}) == 255)) {
  3057. // Error formula. Error code is in +2
  3058. $dataType = PHPExcel_Cell_DataType::TYPE_ERROR;
  3059. $value = self::_mapErrorCode(ord($recordData{8}));
  3060. } elseif ((ord($recordData{6}) == 3)
  3061. && (ord($recordData{12}) == 255)
  3062. && (ord($recordData{13}) == 255)) {
  3063. // Formula result is a null string
  3064. $dataType = PHPExcel_Cell_DataType::TYPE_NULL;
  3065. $value = '';
  3066. } else {
  3067. // forumla result is a number, first 14 bytes like _NUMBER record
  3068. $dataType = PHPExcel_Cell_DataType::TYPE_NUMERIC;
  3069. $value = self::_extractNumber(substr($recordData, 6, 8));
  3070. }
  3071. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  3072. if (!$this->_readDataOnly) {
  3073. // add cell style
  3074. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  3075. }
  3076. // store the formula
  3077. if (!$isPartOfSharedFormula) {
  3078. // not part of shared formula
  3079. // add cell value. If we can read formula, populate with formula, otherwise just used cached value
  3080. try {
  3081. if ($this->_version != self::XLS_BIFF8) {
  3082. throw new Exception('Not BIFF8. Can only read BIFF8 formulas');
  3083. }
  3084. $formula = $this->_getFormulaFromStructure($formulaStructure); // get formula in human language
  3085. $cell->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA);
  3086. } catch (Exception $e) {
  3087. $cell->setValueExplicit($value, $dataType);
  3088. }
  3089. } else {
  3090. if ($this->_version == self::XLS_BIFF8) {
  3091. // do nothing at this point, formula id added later in the code
  3092. } else {
  3093. $cell->setValueExplicit($value, $dataType);
  3094. }
  3095. }
  3096. // store the cached calculated value
  3097. $cell->setCalculatedValue($value);
  3098. }
  3099. }
  3100. /**
  3101. * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader,
  3102. * which usually contains relative references.
  3103. * These will be used to construct the formula in each shared formula part after the sheet is read.
  3104. */
  3105. private function _readSharedFmla()
  3106. {
  3107. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3108. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3109. // move stream pointer to next record
  3110. $this->_pos += 4 + $length;
  3111. // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything
  3112. $cellRange = substr($recordData, 0, 6);
  3113. $cellRange = $this->_readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax
  3114. // offset: 6, size: 1; not used
  3115. // offset: 7, size: 1; number of existing FORMULA records for this shared formula
  3116. $no = ord($recordData{7});
  3117. // offset: 8, size: var; Binary token array of the shared formula
  3118. $formula = substr($recordData, 8);
  3119. // at this point we only store the shared formula for later use
  3120. $this->_sharedFormulas[$this->_baseCell] = $formula;
  3121. }
  3122. /**
  3123. * Read a STRING record from current stream position and advance the stream pointer to next record
  3124. * This record is used for storing result from FORMULA record when it is a string, and
  3125. * it occurs directly after the FORMULA record
  3126. *
  3127. * @return string The string contents as UTF-8
  3128. */
  3129. private function _readString()
  3130. {
  3131. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3132. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3133. // move stream pointer to next record
  3134. $this->_pos += 4 + $length;
  3135. if ($this->_version == self::XLS_BIFF8) {
  3136. $string = self::_readUnicodeStringLong($recordData);
  3137. $value = $string['value'];
  3138. } else {
  3139. $string = $this->_readByteStringLong($recordData);
  3140. $value = $string['value'];
  3141. }
  3142. return $value;
  3143. }
  3144. /**
  3145. * Read BOOLERR record
  3146. * This record represents a Boolean value or error value
  3147. * cell.
  3148. *
  3149. * -- "OpenOffice.org's Documentation of the Microsoft
  3150. * Excel File Format"
  3151. */
  3152. private function _readBoolErr()
  3153. {
  3154. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3155. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3156. // move stream pointer to next record
  3157. $this->_pos += 4 + $length;
  3158. // offset: 0; size: 2; row index
  3159. $row = self::_GetInt2d($recordData, 0);
  3160. // offset: 2; size: 2; column index
  3161. $column = self::_GetInt2d($recordData, 2);
  3162. $columnString = PHPExcel_Cell::stringFromColumnIndex($column);
  3163. // Read cell?
  3164. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  3165. // offset: 4; size: 2; index to XF record
  3166. $xfIndex = self::_GetInt2d($recordData, 4);
  3167. // offset: 6; size: 1; the boolean value or error value
  3168. $boolErr = ord($recordData{6});
  3169. // offset: 7; size: 1; 0=boolean; 1=error
  3170. $isError = ord($recordData{7});
  3171. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  3172. switch ($isError) {
  3173. case 0: // boolean
  3174. $value = (bool) $boolErr;
  3175. // add cell value
  3176. $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_BOOL);
  3177. break;
  3178. case 1: // error type
  3179. $value = self::_mapErrorCode($boolErr);
  3180. // add cell value
  3181. $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_ERROR);
  3182. break;
  3183. }
  3184. if (!$this->_readDataOnly) {
  3185. // add cell style
  3186. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  3187. }
  3188. }
  3189. }
  3190. /**
  3191. * Read MULBLANK record
  3192. * This record represents a cell range of empty cells. All
  3193. * cells are located in the same row
  3194. *
  3195. * -- "OpenOffice.org's Documentation of the Microsoft
  3196. * Excel File Format"
  3197. */
  3198. private function _readMulBlank()
  3199. {
  3200. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3201. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3202. // move stream pointer to next record
  3203. $this->_pos += 4 + $length;
  3204. // offset: 0; size: 2; index to row
  3205. $row = self::_GetInt2d($recordData, 0);
  3206. // offset: 2; size: 2; index to first column
  3207. $fc = self::_GetInt2d($recordData, 2);
  3208. // offset: 4; size: 2 x nc; list of indexes to XF records
  3209. // add style information
  3210. if (!$this->_readDataOnly) {
  3211. for ($i = 0; $i < $length / 2 - 3; ++$i) {
  3212. $columnString = PHPExcel_Cell::stringFromColumnIndex($fc + $i);
  3213. // Read cell?
  3214. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  3215. $xfIndex = self::_GetInt2d($recordData, 4 + 2 * $i);
  3216. $this->_phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  3217. }
  3218. }
  3219. }
  3220. // offset: 6; size 2; index to last column (not needed)
  3221. }
  3222. /**
  3223. * Read LABEL record
  3224. * This record represents a cell that contains a string. In
  3225. * BIFF8 it is usually replaced by the LABELSST record.
  3226. * Excel still uses this record, if it copies unformatted
  3227. * text cells to the clipboard.
  3228. *
  3229. * -- "OpenOffice.org's Documentation of the Microsoft
  3230. * Excel File Format"
  3231. */
  3232. private function _readLabel()
  3233. {
  3234. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3235. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3236. // move stream pointer to next record
  3237. $this->_pos += 4 + $length;
  3238. // offset: 0; size: 2; index to row
  3239. $row = self::_GetInt2d($recordData, 0);
  3240. // offset: 2; size: 2; index to column
  3241. $column = self::_GetInt2d($recordData, 2);
  3242. $columnString = PHPExcel_Cell::stringFromColumnIndex($column);
  3243. // Read cell?
  3244. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  3245. // offset: 4; size: 2; XF index
  3246. $xfIndex = self::_GetInt2d($recordData, 4);
  3247. // add cell value
  3248. // todo: what if string is very long? continue record
  3249. if ($this->_version == self::XLS_BIFF8) {
  3250. $string = self::_readUnicodeStringLong(substr($recordData, 6));
  3251. $value = $string['value'];
  3252. } else {
  3253. $string = $this->_readByteStringLong(substr($recordData, 6));
  3254. $value = $string['value'];
  3255. }
  3256. $cell = $this->_phpSheet->getCell($columnString . ($row + 1));
  3257. $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
  3258. if (!$this->_readDataOnly) {
  3259. // add cell style
  3260. $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  3261. }
  3262. }
  3263. }
  3264. /**
  3265. * Read BLANK record
  3266. */
  3267. private function _readBlank()
  3268. {
  3269. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3270. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3271. // move stream pointer to next record
  3272. $this->_pos += 4 + $length;
  3273. // offset: 0; size: 2; row index
  3274. $row = self::_GetInt2d($recordData, 0);
  3275. // offset: 2; size: 2; col index
  3276. $col = self::_GetInt2d($recordData, 2);
  3277. $columnString = PHPExcel_Cell::stringFromColumnIndex($col);
  3278. // Read cell?
  3279. if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {
  3280. // offset: 4; size: 2; XF index
  3281. $xfIndex = self::_GetInt2d($recordData, 4);
  3282. // add style information
  3283. if (!$this->_readDataOnly) {
  3284. $this->_phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->_mapCellXfIndex[$xfIndex]);
  3285. }
  3286. }
  3287. }
  3288. /**
  3289. * Read MSODRAWING record
  3290. */
  3291. private function _readMsoDrawing()
  3292. {
  3293. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3294. // get spliced record data
  3295. $splicedRecordData = $this->_getSplicedRecordData();
  3296. $recordData = $splicedRecordData['recordData'];
  3297. $this->_drawingData .= $recordData;
  3298. }
  3299. /**
  3300. * Read OBJ record
  3301. */
  3302. private function _readObj()
  3303. {
  3304. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3305. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3306. // move stream pointer to next record
  3307. $this->_pos += 4 + $length;
  3308. if ($this->_readDataOnly || $this->_version != self::XLS_BIFF8) {
  3309. return;
  3310. }
  3311. // recordData consists of an array of subrecords looking like this:
  3312. // ft: 2 bytes; ftCmo type (0x15)
  3313. // cb: 2 bytes; size in bytes of ftCmo data
  3314. // ot: 2 bytes; Object Type
  3315. // id: 2 bytes; Object id number
  3316. // grbit: 2 bytes; Option Flags
  3317. // data: var; subrecord data
  3318. // for now, we are just interested in the second subrecord containing the object type
  3319. $ftCmoType = self::_GetInt2d($recordData, 0);
  3320. $cbCmoSize = self::_GetInt2d($recordData, 2);
  3321. $otObjType = self::_GetInt2d($recordData, 4);
  3322. $idObjID = self::_GetInt2d($recordData, 6);
  3323. $grbitOpts = self::_GetInt2d($recordData, 6);
  3324. $this->_objs[] = array(
  3325. 'ftCmoType' => $ftCmoType,
  3326. 'cbCmoSize' => $cbCmoSize,
  3327. 'otObjType' => $otObjType,
  3328. 'idObjID' => $idObjID,
  3329. 'grbitOpts' => $grbitOpts
  3330. );
  3331. $this->textObjRef = $idObjID;
  3332. // echo '<b>_readObj()</b><br />';
  3333. // var_dump(end($this->_objs));
  3334. // echo '<br />';
  3335. }
  3336. /**
  3337. * Read WINDOW2 record
  3338. */
  3339. private function _readWindow2()
  3340. {
  3341. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3342. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3343. // move stream pointer to next record
  3344. $this->_pos += 4 + $length;
  3345. // offset: 0; size: 2; option flags
  3346. $options = self::_GetInt2d($recordData, 0);
  3347. // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines
  3348. $showGridlines = (bool) ((0x0002 & $options) >> 1);
  3349. $this->_phpSheet->setShowGridlines($showGridlines);
  3350. // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers
  3351. $showRowColHeaders = (bool) ((0x0004 & $options) >> 2);
  3352. $this->_phpSheet->setShowRowColHeaders($showRowColHeaders);
  3353. // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen
  3354. $this->_frozen = (bool) ((0x0008 & $options) >> 3);
  3355. // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left
  3356. $this->_phpSheet->setRightToLeft((bool)((0x0040 & $options) >> 6));
  3357. // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active
  3358. $isActive = (bool) ((0x0400 & $options) >> 10);
  3359. if ($isActive) {
  3360. $this->_phpExcel->setActiveSheetIndex($this->_phpExcel->getIndex($this->_phpSheet));
  3361. }
  3362. }
  3363. /**
  3364. * Read SCL record
  3365. */
  3366. private function _readScl()
  3367. {
  3368. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3369. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3370. // move stream pointer to next record
  3371. $this->_pos += 4 + $length;
  3372. // offset: 0; size: 2; numerator of the view magnification
  3373. $numerator = self::_GetInt2d($recordData, 0);
  3374. // offset: 2; size: 2; numerator of the view magnification
  3375. $denumerator = self::_GetInt2d($recordData, 2);
  3376. // set the zoom scale (in percent)
  3377. $this->_phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator);
  3378. }
  3379. /**
  3380. * Read PANE record
  3381. */
  3382. private function _readPane()
  3383. {
  3384. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3385. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3386. // move stream pointer to next record
  3387. $this->_pos += 4 + $length;
  3388. if (!$this->_readDataOnly) {
  3389. // offset: 0; size: 2; position of vertical split
  3390. $px = self::_GetInt2d($recordData, 0);
  3391. // offset: 2; size: 2; position of horizontal split
  3392. $py = self::_GetInt2d($recordData, 2);
  3393. if ($this->_frozen) {
  3394. // frozen panes
  3395. $this->_phpSheet->freezePane(PHPExcel_Cell::stringFromColumnIndex($px) . ($py + 1));
  3396. } else {
  3397. // unfrozen panes; split windows; not supported by PHPExcel core
  3398. }
  3399. }
  3400. }
  3401. /**
  3402. * Read SELECTION record. There is one such record for each pane in the sheet.
  3403. */
  3404. private function _readSelection()
  3405. {
  3406. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3407. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3408. // move stream pointer to next record
  3409. $this->_pos += 4 + $length;
  3410. if (!$this->_readDataOnly) {
  3411. // offset: 0; size: 1; pane identifier
  3412. $paneId = ord($recordData{0});
  3413. // offset: 1; size: 2; index to row of the active cell
  3414. $r = self::_GetInt2d($recordData, 1);
  3415. // offset: 3; size: 2; index to column of the active cell
  3416. $c = self::_GetInt2d($recordData, 3);
  3417. // offset: 5; size: 2; index into the following cell range list to the
  3418. // entry that contains the active cell
  3419. $index = self::_GetInt2d($recordData, 5);
  3420. // offset: 7; size: var; cell range address list containing all selected cell ranges
  3421. $data = substr($recordData, 7);
  3422. $cellRangeAddressList = $this->_readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax
  3423. $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0];
  3424. // first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!)
  3425. if (preg_match('/^([A-Z]+1\:[A-Z]+)16384$/', $selectedCells)) {
  3426. $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)16384$/', '${1}1048576', $selectedCells);
  3427. }
  3428. // first row '1' + last row '65536' indicates that full column is selected
  3429. if (preg_match('/^([A-Z]+1\:[A-Z]+)65536$/', $selectedCells)) {
  3430. $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)65536$/', '${1}1048576', $selectedCells);
  3431. }
  3432. // first column 'A' + last column 'IV' indicates that full row is selected
  3433. if (preg_match('/^(A[0-9]+\:)IV([0-9]+)$/', $selectedCells)) {
  3434. $selectedCells = preg_replace('/^(A[0-9]+\:)IV([0-9]+)$/', '${1}XFD${2}', $selectedCells);
  3435. }
  3436. $this->_phpSheet->setSelectedCells($selectedCells);
  3437. }
  3438. }
  3439. private function _includeCellRangeFiltered($cellRangeAddress)
  3440. {
  3441. $includeCellRange = true;
  3442. if ($this->getReadFilter() !== NULL) {
  3443. $includeCellRange = false;
  3444. $rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($cellRangeAddress);
  3445. $rangeBoundaries[1][0]++;
  3446. for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; $row++) {
  3447. for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; $column++) {
  3448. if ($this->getReadFilter()->readCell($column, $row, $this->_phpSheet->getTitle())) {
  3449. $includeCellRange = true;
  3450. break 2;
  3451. }
  3452. }
  3453. }
  3454. }
  3455. return $includeCellRange;
  3456. }
  3457. /**
  3458. * MERGEDCELLS
  3459. *
  3460. * This record contains the addresses of merged cell ranges
  3461. * in the current sheet.
  3462. *
  3463. * -- "OpenOffice.org's Documentation of the Microsoft
  3464. * Excel File Format"
  3465. */
  3466. private function _readMergedCells()
  3467. {
  3468. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3469. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3470. // move stream pointer to next record
  3471. $this->_pos += 4 + $length;
  3472. if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) {
  3473. $cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($recordData);
  3474. foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) {
  3475. if ((strpos($cellRangeAddress,':') !== FALSE) &&
  3476. ($this->_includeCellRangeFiltered($cellRangeAddress))) {
  3477. $this->_phpSheet->mergeCells($cellRangeAddress);
  3478. }
  3479. }
  3480. }
  3481. }
  3482. /**
  3483. * Read HYPERLINK record
  3484. */
  3485. private function _readHyperLink()
  3486. {
  3487. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3488. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3489. // move stream pointer forward to next record
  3490. $this->_pos += 4 + $length;
  3491. if (!$this->_readDataOnly) {
  3492. // offset: 0; size: 8; cell range address of all cells containing this hyperlink
  3493. try {
  3494. $cellRange = $this->_readBIFF8CellRangeAddressFixed($recordData, 0, 8);
  3495. } catch (Exception $e) {
  3496. return;
  3497. }
  3498. // offset: 8, size: 16; GUID of StdLink
  3499. // offset: 24, size: 4; unknown value
  3500. // offset: 28, size: 4; option flags
  3501. // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL
  3502. $isFileLinkOrUrl = (0x00000001 & self::_GetInt2d($recordData, 28)) >> 0;
  3503. // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL
  3504. $isAbsPathOrUrl = (0x00000001 & self::_GetInt2d($recordData, 28)) >> 1;
  3505. // bit: 2 (and 4); mask: 0x00000014; 0 = no description
  3506. $hasDesc = (0x00000014 & self::_GetInt2d($recordData, 28)) >> 2;
  3507. // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text
  3508. $hasText = (0x00000008 & self::_GetInt2d($recordData, 28)) >> 3;
  3509. // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame
  3510. $hasFrame = (0x00000080 & self::_GetInt2d($recordData, 28)) >> 7;
  3511. // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name)
  3512. $isUNC = (0x00000100 & self::_GetInt2d($recordData, 28)) >> 8;
  3513. // offset within record data
  3514. $offset = 32;
  3515. if ($hasDesc) {
  3516. // offset: 32; size: var; character count of description text
  3517. $dl = self::_GetInt4d($recordData, 32);
  3518. // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated
  3519. $desc = self::_encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false);
  3520. $offset += 4 + 2 * $dl;
  3521. }
  3522. if ($hasFrame) {
  3523. $fl = self::_GetInt4d($recordData, $offset);
  3524. $offset += 4 + 2 * $fl;
  3525. }
  3526. // detect type of hyperlink (there are 4 types)
  3527. $hyperlinkType = null;
  3528. if ($isUNC) {
  3529. $hyperlinkType = 'UNC';
  3530. } else if (!$isFileLinkOrUrl) {
  3531. $hyperlinkType = 'workbook';
  3532. } else if (ord($recordData{$offset}) == 0x03) {
  3533. $hyperlinkType = 'local';
  3534. } else if (ord($recordData{$offset}) == 0xE0) {
  3535. $hyperlinkType = 'URL';
  3536. }
  3537. switch ($hyperlinkType) {
  3538. case 'URL':
  3539. // section 5.58.2: Hyperlink containing a URL
  3540. // e.g. http://example.org/index.php
  3541. // offset: var; size: 16; GUID of URL Moniker
  3542. $offset += 16;
  3543. // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word
  3544. $us = self::_GetInt4d($recordData, $offset);
  3545. $offset += 4;
  3546. // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated
  3547. $url = self::_encodeUTF16(substr($recordData, $offset, $us - 2), false);
  3548. $url .= $hasText ? '#' : '';
  3549. $offset += $us;
  3550. break;
  3551. case 'local':
  3552. // section 5.58.3: Hyperlink to local file
  3553. // examples:
  3554. // mydoc.txt
  3555. // ../../somedoc.xls#Sheet!A1
  3556. // offset: var; size: 16; GUI of File Moniker
  3557. $offset += 16;
  3558. // offset: var; size: 2; directory up-level count.
  3559. $upLevelCount = self::_GetInt2d($recordData, $offset);
  3560. $offset += 2;
  3561. // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word
  3562. $sl = self::_GetInt4d($recordData, $offset);
  3563. $offset += 4;
  3564. // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string)
  3565. $shortenedFilePath = substr($recordData, $offset, $sl);
  3566. $shortenedFilePath = self::_encodeUTF16($shortenedFilePath, true);
  3567. $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero
  3568. $offset += $sl;
  3569. // offset: var; size: 24; unknown sequence
  3570. $offset += 24;
  3571. // extended file path
  3572. // offset: var; size: 4; size of the following file link field including string lenth mark
  3573. $sz = self::_GetInt4d($recordData, $offset);
  3574. $offset += 4;
  3575. // only present if $sz > 0
  3576. if ($sz > 0) {
  3577. // offset: var; size: 4; size of the character array of the extended file path and name
  3578. $xl = self::_GetInt4d($recordData, $offset);
  3579. $offset += 4;
  3580. // offset: var; size 2; unknown
  3581. $offset += 2;
  3582. // offset: var; size $xl; character array of the extended file path and name.
  3583. $extendedFilePath = substr($recordData, $offset, $xl);
  3584. $extendedFilePath = self::_encodeUTF16($extendedFilePath, false);
  3585. $offset += $xl;
  3586. }
  3587. // construct the path
  3588. $url = str_repeat('..\\', $upLevelCount);
  3589. $url .= ($sz > 0) ?
  3590. $extendedFilePath : $shortenedFilePath; // use extended path if available
  3591. $url .= $hasText ? '#' : '';
  3592. break;
  3593. case 'UNC':
  3594. // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path
  3595. // todo: implement
  3596. return;
  3597. case 'workbook':
  3598. // section 5.58.5: Hyperlink to the Current Workbook
  3599. // e.g. Sheet2!B1:C2, stored in text mark field
  3600. $url = 'sheet://';
  3601. break;
  3602. default:
  3603. return;
  3604. }
  3605. if ($hasText) {
  3606. // offset: var; size: 4; character count of text mark including trailing zero word
  3607. $tl = self::_GetInt4d($recordData, $offset);
  3608. $offset += 4;
  3609. // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated
  3610. $text = self::_encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false);
  3611. $url .= $text;
  3612. }
  3613. // apply the hyperlink to all the relevant cells
  3614. foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cellRange) as $coordinate) {
  3615. $this->_phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url);
  3616. }
  3617. }
  3618. }
  3619. /**
  3620. * Read DATAVALIDATIONS record
  3621. */
  3622. private function _readDataValidations()
  3623. {
  3624. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3625. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3626. // move stream pointer forward to next record
  3627. $this->_pos += 4 + $length;
  3628. }
  3629. /**
  3630. * Read DATAVALIDATION record
  3631. */
  3632. private function _readDataValidation()
  3633. {
  3634. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3635. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3636. // move stream pointer forward to next record
  3637. $this->_pos += 4 + $length;
  3638. if ($this->_readDataOnly) {
  3639. return;
  3640. }
  3641. // offset: 0; size: 4; Options
  3642. $options = self::_GetInt4d($recordData, 0);
  3643. // bit: 0-3; mask: 0x0000000F; type
  3644. $type = (0x0000000F & $options) >> 0;
  3645. switch ($type) {
  3646. case 0x00: $type = PHPExcel_Cell_DataValidation::TYPE_NONE; break;
  3647. case 0x01: $type = PHPExcel_Cell_DataValidation::TYPE_WHOLE; break;
  3648. case 0x02: $type = PHPExcel_Cell_DataValidation::TYPE_DECIMAL; break;
  3649. case 0x03: $type = PHPExcel_Cell_DataValidation::TYPE_LIST; break;
  3650. case 0x04: $type = PHPExcel_Cell_DataValidation::TYPE_DATE; break;
  3651. case 0x05: $type = PHPExcel_Cell_DataValidation::TYPE_TIME; break;
  3652. case 0x06: $type = PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH; break;
  3653. case 0x07: $type = PHPExcel_Cell_DataValidation::TYPE_CUSTOM; break;
  3654. }
  3655. // bit: 4-6; mask: 0x00000070; error type
  3656. $errorStyle = (0x00000070 & $options) >> 4;
  3657. switch ($errorStyle) {
  3658. case 0x00: $errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP; break;
  3659. case 0x01: $errorStyle = PHPExcel_Cell_DataValidation::STYLE_WARNING; break;
  3660. case 0x02: $errorStyle = PHPExcel_Cell_DataValidation::STYLE_INFORMATION; break;
  3661. }
  3662. // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list)
  3663. // I have only seen cases where this is 1
  3664. $explicitFormula = (0x00000080 & $options) >> 7;
  3665. // bit: 8; mask: 0x00000100; 1= empty cells allowed
  3666. $allowBlank = (0x00000100 & $options) >> 8;
  3667. // bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity
  3668. $suppressDropDown = (0x00000200 & $options) >> 9;
  3669. // bit: 18; mask: 0x00040000; 1= show prompt box if cell selected
  3670. $showInputMessage = (0x00040000 & $options) >> 18;
  3671. // bit: 19; mask: 0x00080000; 1= show error box if invalid values entered
  3672. $showErrorMessage = (0x00080000 & $options) >> 19;
  3673. // bit: 20-23; mask: 0x00F00000; condition operator
  3674. $operator = (0x00F00000 & $options) >> 20;
  3675. switch ($operator) {
  3676. case 0x00: $operator = PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN ; break;
  3677. case 0x01: $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN ; break;
  3678. case 0x02: $operator = PHPExcel_Cell_DataValidation::OPERATOR_EQUAL ; break;
  3679. case 0x03: $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL ; break;
  3680. case 0x04: $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN ; break;
  3681. case 0x05: $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN ; break;
  3682. case 0x06: $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL; break;
  3683. case 0x07: $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL ; break;
  3684. }
  3685. // offset: 4; size: var; title of the prompt box
  3686. $offset = 4;
  3687. $string = self::_readUnicodeStringLong(substr($recordData, $offset));
  3688. $promptTitle = $string['value'] !== chr(0) ?
  3689. $string['value'] : '';
  3690. $offset += $string['size'];
  3691. // offset: var; size: var; title of the error box
  3692. $string = self::_readUnicodeStringLong(substr($recordData, $offset));
  3693. $errorTitle = $string['value'] !== chr(0) ?
  3694. $string['value'] : '';
  3695. $offset += $string['size'];
  3696. // offset: var; size: var; text of the prompt box
  3697. $string = self::_readUnicodeStringLong(substr($recordData, $offset));
  3698. $prompt = $string['value'] !== chr(0) ?
  3699. $string['value'] : '';
  3700. $offset += $string['size'];
  3701. // offset: var; size: var; text of the error box
  3702. $string = self::_readUnicodeStringLong(substr($recordData, $offset));
  3703. $error = $string['value'] !== chr(0) ?
  3704. $string['value'] : '';
  3705. $offset += $string['size'];
  3706. // offset: var; size: 2; size of the formula data for the first condition
  3707. $sz1 = self::_GetInt2d($recordData, $offset);
  3708. $offset += 2;
  3709. // offset: var; size: 2; not used
  3710. $offset += 2;
  3711. // offset: var; size: $sz1; formula data for first condition (without size field)
  3712. $formula1 = substr($recordData, $offset, $sz1);
  3713. $formula1 = pack('v', $sz1) . $formula1; // prepend the length
  3714. try {
  3715. $formula1 = $this->_getFormulaFromStructure($formula1);
  3716. // in list type validity, null characters are used as item separators
  3717. if ($type == PHPExcel_Cell_DataValidation::TYPE_LIST) {
  3718. $formula1 = str_replace(chr(0), ',', $formula1);
  3719. }
  3720. } catch (Exception $e) {
  3721. return;
  3722. }
  3723. $offset += $sz1;
  3724. // offset: var; size: 2; size of the formula data for the first condition
  3725. $sz2 = self::_GetInt2d($recordData, $offset);
  3726. $offset += 2;
  3727. // offset: var; size: 2; not used
  3728. $offset += 2;
  3729. // offset: var; size: $sz2; formula data for second condition (without size field)
  3730. $formula2 = substr($recordData, $offset, $sz2);
  3731. $formula2 = pack('v', $sz2) . $formula2; // prepend the length
  3732. try {
  3733. $formula2 = $this->_getFormulaFromStructure($formula2);
  3734. } catch (Exception $e) {
  3735. return;
  3736. }
  3737. $offset += $sz2;
  3738. // offset: var; size: var; cell range address list with
  3739. $cellRangeAddressList = $this->_readBIFF8CellRangeAddressList(substr($recordData, $offset));
  3740. $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses'];
  3741. foreach ($cellRangeAddresses as $cellRange) {
  3742. $stRange = $this->_phpSheet->shrinkRangeToFit($cellRange);
  3743. $stRange = PHPExcel_Cell::extractAllCellReferencesInRange($stRange);
  3744. foreach ($stRange as $coordinate) {
  3745. $objValidation = $this->_phpSheet->getCell($coordinate)->getDataValidation();
  3746. $objValidation->setType($type);
  3747. $objValidation->setErrorStyle($errorStyle);
  3748. $objValidation->setAllowBlank((bool)$allowBlank);
  3749. $objValidation->setShowInputMessage((bool)$showInputMessage);
  3750. $objValidation->setShowErrorMessage((bool)$showErrorMessage);
  3751. $objValidation->setShowDropDown(!$suppressDropDown);
  3752. $objValidation->setOperator($operator);
  3753. $objValidation->setErrorTitle($errorTitle);
  3754. $objValidation->setError($error);
  3755. $objValidation->setPromptTitle($promptTitle);
  3756. $objValidation->setPrompt($prompt);
  3757. $objValidation->setFormula1($formula1);
  3758. $objValidation->setFormula2($formula2);
  3759. }
  3760. }
  3761. }
  3762. /**
  3763. * Read SHEETLAYOUT record. Stores sheet tab color information.
  3764. */
  3765. private function _readSheetLayout()
  3766. {
  3767. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3768. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3769. // move stream pointer to next record
  3770. $this->_pos += 4 + $length;
  3771. // local pointer in record data
  3772. $offset = 0;
  3773. if (!$this->_readDataOnly) {
  3774. // offset: 0; size: 2; repeated record identifier 0x0862
  3775. // offset: 2; size: 10; not used
  3776. // offset: 12; size: 4; size of record data
  3777. // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?)
  3778. $sz = self::_GetInt4d($recordData, 12);
  3779. switch ($sz) {
  3780. case 0x14:
  3781. // offset: 16; size: 2; color index for sheet tab
  3782. $colorIndex = self::_GetInt2d($recordData, 16);
  3783. $color = self::_readColor($colorIndex,$this->_palette,$this->_version);
  3784. $this->_phpSheet->getTabColor()->setRGB($color['rgb']);
  3785. break;
  3786. case 0x28:
  3787. // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007
  3788. return;
  3789. break;
  3790. }
  3791. }
  3792. }
  3793. /**
  3794. * Read SHEETPROTECTION record (FEATHEADR)
  3795. */
  3796. private function _readSheetProtection()
  3797. {
  3798. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3799. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3800. // move stream pointer to next record
  3801. $this->_pos += 4 + $length;
  3802. if ($this->_readDataOnly) {
  3803. return;
  3804. }
  3805. // offset: 0; size: 2; repeated record header
  3806. // offset: 2; size: 2; FRT cell reference flag (=0 currently)
  3807. // offset: 4; size: 8; Currently not used and set to 0
  3808. // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag)
  3809. $isf = self::_GetInt2d($recordData, 12);
  3810. if ($isf != 2) {
  3811. return;
  3812. }
  3813. // offset: 14; size: 1; =1 since this is a feat header
  3814. // offset: 15; size: 4; size of rgbHdrSData
  3815. // rgbHdrSData, assume "Enhanced Protection"
  3816. // offset: 19; size: 2; option flags
  3817. $options = self::_GetInt2d($recordData, 19);
  3818. // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects
  3819. $bool = (0x0001 & $options) >> 0;
  3820. $this->_phpSheet->getProtection()->setObjects(!$bool);
  3821. // bit: 1; mask 0x0002; edit scenarios
  3822. $bool = (0x0002 & $options) >> 1;
  3823. $this->_phpSheet->getProtection()->setScenarios(!$bool);
  3824. // bit: 2; mask 0x0004; format cells
  3825. $bool = (0x0004 & $options) >> 2;
  3826. $this->_phpSheet->getProtection()->setFormatCells(!$bool);
  3827. // bit: 3; mask 0x0008; format columns
  3828. $bool = (0x0008 & $options) >> 3;
  3829. $this->_phpSheet->getProtection()->setFormatColumns(!$bool);
  3830. // bit: 4; mask 0x0010; format rows
  3831. $bool = (0x0010 & $options) >> 4;
  3832. $this->_phpSheet->getProtection()->setFormatRows(!$bool);
  3833. // bit: 5; mask 0x0020; insert columns
  3834. $bool = (0x0020 & $options) >> 5;
  3835. $this->_phpSheet->getProtection()->setInsertColumns(!$bool);
  3836. // bit: 6; mask 0x0040; insert rows
  3837. $bool = (0x0040 & $options) >> 6;
  3838. $this->_phpSheet->getProtection()->setInsertRows(!$bool);
  3839. // bit: 7; mask 0x0080; insert hyperlinks
  3840. $bool = (0x0080 & $options) >> 7;
  3841. $this->_phpSheet->getProtection()->setInsertHyperlinks(!$bool);
  3842. // bit: 8; mask 0x0100; delete columns
  3843. $bool = (0x0100 & $options) >> 8;
  3844. $this->_phpSheet->getProtection()->setDeleteColumns(!$bool);
  3845. // bit: 9; mask 0x0200; delete rows
  3846. $bool = (0x0200 & $options) >> 9;
  3847. $this->_phpSheet->getProtection()->setDeleteRows(!$bool);
  3848. // bit: 10; mask 0x0400; select locked cells
  3849. $bool = (0x0400 & $options) >> 10;
  3850. $this->_phpSheet->getProtection()->setSelectLockedCells(!$bool);
  3851. // bit: 11; mask 0x0800; sort cell range
  3852. $bool = (0x0800 & $options) >> 11;
  3853. $this->_phpSheet->getProtection()->setSort(!$bool);
  3854. // bit: 12; mask 0x1000; auto filter
  3855. $bool = (0x1000 & $options) >> 12;
  3856. $this->_phpSheet->getProtection()->setAutoFilter(!$bool);
  3857. // bit: 13; mask 0x2000; pivot tables
  3858. $bool = (0x2000 & $options) >> 13;
  3859. $this->_phpSheet->getProtection()->setPivotTables(!$bool);
  3860. // bit: 14; mask 0x4000; select unlocked cells
  3861. $bool = (0x4000 & $options) >> 14;
  3862. $this->_phpSheet->getProtection()->setSelectUnlockedCells(!$bool);
  3863. // offset: 21; size: 2; not used
  3864. }
  3865. /**
  3866. * Read RANGEPROTECTION record
  3867. * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification,
  3868. * where it is referred to as FEAT record
  3869. */
  3870. private function _readRangeProtection()
  3871. {
  3872. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3873. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3874. // move stream pointer to next record
  3875. $this->_pos += 4 + $length;
  3876. // local pointer in record data
  3877. $offset = 0;
  3878. if (!$this->_readDataOnly) {
  3879. $offset += 12;
  3880. // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag
  3881. $isf = self::_GetInt2d($recordData, 12);
  3882. if ($isf != 2) {
  3883. // we only read FEAT records of type 2
  3884. return;
  3885. }
  3886. $offset += 2;
  3887. $offset += 5;
  3888. // offset: 19; size: 2; count of ref ranges this feature is on
  3889. $cref = self::_GetInt2d($recordData, 19);
  3890. $offset += 2;
  3891. $offset += 6;
  3892. // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record)
  3893. $cellRanges = array();
  3894. for ($i = 0; $i < $cref; ++$i) {
  3895. try {
  3896. $cellRange = $this->_readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8));
  3897. } catch (Exception $e) {
  3898. return;
  3899. }
  3900. $cellRanges[] = $cellRange;
  3901. $offset += 8;
  3902. }
  3903. // offset: var; size: var; variable length of feature specific data
  3904. $rgbFeat = substr($recordData, $offset);
  3905. $offset += 4;
  3906. // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit)
  3907. $wPassword = self::_GetInt4d($recordData, $offset);
  3908. $offset += 4;
  3909. // Apply range protection to sheet
  3910. if ($cellRanges) {
  3911. $this->_phpSheet->protectCells(implode(' ', $cellRanges), strtoupper(dechex($wPassword)), true);
  3912. }
  3913. }
  3914. }
  3915. /**
  3916. * Read IMDATA record
  3917. */
  3918. private function _readImData()
  3919. {
  3920. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3921. // get spliced record data
  3922. $splicedRecordData = $this->_getSplicedRecordData();
  3923. $recordData = $splicedRecordData['recordData'];
  3924. // UNDER CONSTRUCTION
  3925. // offset: 0; size: 2; image format
  3926. $cf = self::_GetInt2d($recordData, 0);
  3927. // offset: 2; size: 2; environment from which the file was written
  3928. $env = self::_GetInt2d($recordData, 2);
  3929. // offset: 4; size: 4; length of the image data
  3930. $lcb = self::_GetInt4d($recordData, 4);
  3931. // offset: 8; size: var; image data
  3932. $iData = substr($recordData, 8);
  3933. switch ($cf) {
  3934. case 0x09: // Windows bitmap format
  3935. // BITMAPCOREINFO
  3936. // 1. BITMAPCOREHEADER
  3937. // offset: 0; size: 4; bcSize, Specifies the number of bytes required by the structure
  3938. $bcSize = self::_GetInt4d($iData, 0);
  3939. // var_dump($bcSize);
  3940. // offset: 4; size: 2; bcWidth, specifies the width of the bitmap, in pixels
  3941. $bcWidth = self::_GetInt2d($iData, 4);
  3942. // var_dump($bcWidth);
  3943. // offset: 6; size: 2; bcHeight, specifies the height of the bitmap, in pixels.
  3944. $bcHeight = self::_GetInt2d($iData, 6);
  3945. // var_dump($bcHeight);
  3946. $ih = imagecreatetruecolor($bcWidth, $bcHeight);
  3947. // offset: 8; size: 2; bcPlanes, specifies the number of planes for the target device. This value must be 1
  3948. // offset: 10; size: 2; bcBitCount specifies the number of bits-per-pixel. This value must be 1, 4, 8, or 24
  3949. $bcBitCount = self::_GetInt2d($iData, 10);
  3950. // var_dump($bcBitCount);
  3951. $rgbString = substr($iData, 12);
  3952. $rgbTriples = array();
  3953. while (strlen($rgbString) > 0) {
  3954. $rgbTriples[] = unpack('Cb/Cg/Cr', $rgbString);
  3955. $rgbString = substr($rgbString, 3);
  3956. }
  3957. $x = 0;
  3958. $y = 0;
  3959. foreach ($rgbTriples as $i => $rgbTriple) {
  3960. $color = imagecolorallocate($ih, $rgbTriple['r'], $rgbTriple['g'], $rgbTriple['b']);
  3961. imagesetpixel($ih, $x, $bcHeight - 1 - $y, $color);
  3962. $x = ($x + 1) % $bcWidth;
  3963. $y = $y + floor(($x + 1) / $bcWidth);
  3964. }
  3965. //imagepng($ih, 'image.png');
  3966. $drawing = new PHPExcel_Worksheet_Drawing();
  3967. $drawing->setPath($filename);
  3968. $drawing->setWorksheet($this->_phpSheet);
  3969. break;
  3970. case 0x02: // Windows metafile or Macintosh PICT format
  3971. case 0x0e: // native format
  3972. default;
  3973. break;
  3974. }
  3975. // _getSplicedRecordData() takes care of moving current position in data stream
  3976. }
  3977. /**
  3978. * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record
  3979. * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented.
  3980. * In this case, we must treat the CONTINUE record as a MSODRAWING record
  3981. */
  3982. private function _readContinue()
  3983. {
  3984. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  3985. $recordData = substr($this->_data, $this->_pos + 4, $length);
  3986. // check if we are reading drawing data
  3987. // this is in case a free CONTINUE record occurs in other circumstances we are unaware of
  3988. if ($this->_drawingData == '') {
  3989. // move stream pointer to next record
  3990. $this->_pos += 4 + $length;
  3991. return;
  3992. }
  3993. // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data
  3994. if ($length < 4) {
  3995. // move stream pointer to next record
  3996. $this->_pos += 4 + $length;
  3997. return;
  3998. }
  3999. // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record
  4000. // look inside CONTINUE record to see if it looks like a part of an Escher stream
  4001. // we know that Escher stream may be split at least at
  4002. // 0xF003 MsofbtSpgrContainer
  4003. // 0xF004 MsofbtSpContainer
  4004. // 0xF00D MsofbtClientTextbox
  4005. $validSplitPoints = array(0xF003, 0xF004, 0xF00D); // add identifiers if we find more
  4006. $splitPoint = self::_GetInt2d($recordData, 2);
  4007. if (in_array($splitPoint, $validSplitPoints)) {
  4008. // get spliced record data (and move pointer to next record)
  4009. $splicedRecordData = $this->_getSplicedRecordData();
  4010. $this->_drawingData .= $splicedRecordData['recordData'];
  4011. return;
  4012. }
  4013. // move stream pointer to next record
  4014. $this->_pos += 4 + $length;
  4015. }
  4016. /**
  4017. * Reads a record from current position in data stream and continues reading data as long as CONTINUE
  4018. * records are found. Splices the record data pieces and returns the combined string as if record data
  4019. * is in one piece.
  4020. * Moves to next current position in data stream to start of next record different from a CONtINUE record
  4021. *
  4022. * @return array
  4023. */
  4024. private function _getSplicedRecordData()
  4025. {
  4026. $data = '';
  4027. $spliceOffsets = array();
  4028. $i = 0;
  4029. $spliceOffsets[0] = 0;
  4030. do {
  4031. ++$i;
  4032. // offset: 0; size: 2; identifier
  4033. $identifier = self::_GetInt2d($this->_data, $this->_pos);
  4034. // offset: 2; size: 2; length
  4035. $length = self::_GetInt2d($this->_data, $this->_pos + 2);
  4036. $data .= substr($this->_data, $this->_pos + 4, $length);
  4037. $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length;
  4038. $this->_pos += 4 + $length;
  4039. $nextIdentifier = self::_GetInt2d($this->_data, $this->_pos);
  4040. }
  4041. while ($nextIdentifier == self::XLS_Type_CONTINUE);
  4042. $splicedData = array(
  4043. 'recordData' => $data,
  4044. 'spliceOffsets' => $spliceOffsets,
  4045. );
  4046. return $splicedData;
  4047. }
  4048. /**
  4049. * Convert formula structure into human readable Excel formula like 'A3+A5*5'
  4050. *
  4051. * @param string $formulaStructure The complete binary data for the formula
  4052. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4053. * @return string Human readable formula
  4054. */
  4055. private function _getFormulaFromStructure($formulaStructure, $baseCell = 'A1')
  4056. {
  4057. // offset: 0; size: 2; size of the following formula data
  4058. $sz = self::_GetInt2d($formulaStructure, 0);
  4059. // offset: 2; size: sz
  4060. $formulaData = substr($formulaStructure, 2, $sz);
  4061. // for debug: dump the formula data
  4062. //echo '<xmp>';
  4063. //echo 'size: ' . $sz . "\n";
  4064. //echo 'the entire formula data: ';
  4065. //Debug::dump($formulaData);
  4066. //echo "\n----\n";
  4067. // offset: 2 + sz; size: variable (optional)
  4068. if (strlen($formulaStructure) > 2 + $sz) {
  4069. $additionalData = substr($formulaStructure, 2 + $sz);
  4070. // for debug: dump the additional data
  4071. //echo 'the entire additional data: ';
  4072. //Debug::dump($additionalData);
  4073. //echo "\n----\n";
  4074. } else {
  4075. $additionalData = '';
  4076. }
  4077. return $this->_getFormulaFromData($formulaData, $additionalData, $baseCell);
  4078. }
  4079. /**
  4080. * Take formula data and additional data for formula and return human readable formula
  4081. *
  4082. * @param string $formulaData The binary data for the formula itself
  4083. * @param string $additionalData Additional binary data going with the formula
  4084. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4085. * @return string Human readable formula
  4086. */
  4087. private function _getFormulaFromData($formulaData, $additionalData = '', $baseCell = 'A1')
  4088. {
  4089. // start parsing the formula data
  4090. $tokens = array();
  4091. while (strlen($formulaData) > 0 and $token = $this->_getNextToken($formulaData, $baseCell)) {
  4092. $tokens[] = $token;
  4093. $formulaData = substr($formulaData, $token['size']);
  4094. // for debug: dump the token
  4095. //var_dump($token);
  4096. }
  4097. $formulaString = $this->_createFormulaFromTokens($tokens, $additionalData);
  4098. return $formulaString;
  4099. }
  4100. /**
  4101. * Take array of tokens together with additional data for formula and return human readable formula
  4102. *
  4103. * @param array $tokens
  4104. * @param array $additionalData Additional binary data going with the formula
  4105. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4106. * @return string Human readable formula
  4107. */
  4108. private function _createFormulaFromTokens($tokens, $additionalData)
  4109. {
  4110. // empty formula?
  4111. if (empty($tokens)) {
  4112. return '';
  4113. }
  4114. $formulaStrings = array();
  4115. foreach ($tokens as $token) {
  4116. // initialize spaces
  4117. $space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen
  4118. $space1 = isset($space1) ? $space1 : ''; // carriage returns before next token, not tParen
  4119. $space2 = isset($space2) ? $space2 : ''; // spaces before opening parenthesis
  4120. $space3 = isset($space3) ? $space3 : ''; // carriage returns before opening parenthesis
  4121. $space4 = isset($space4) ? $space4 : ''; // spaces before closing parenthesis
  4122. $space5 = isset($space5) ? $space5 : ''; // carriage returns before closing parenthesis
  4123. switch ($token['name']) {
  4124. case 'tAdd': // addition
  4125. case 'tConcat': // addition
  4126. case 'tDiv': // division
  4127. case 'tEQ': // equality
  4128. case 'tGE': // greater than or equal
  4129. case 'tGT': // greater than
  4130. case 'tIsect': // intersection
  4131. case 'tLE': // less than or equal
  4132. case 'tList': // less than or equal
  4133. case 'tLT': // less than
  4134. case 'tMul': // multiplication
  4135. case 'tNE': // multiplication
  4136. case 'tPower': // power
  4137. case 'tRange': // range
  4138. case 'tSub': // subtraction
  4139. $op2 = array_pop($formulaStrings);
  4140. $op1 = array_pop($formulaStrings);
  4141. $formulaStrings[] = "$op1$space1$space0{$token['data']}$op2";
  4142. unset($space0, $space1);
  4143. break;
  4144. case 'tUplus': // unary plus
  4145. case 'tUminus': // unary minus
  4146. $op = array_pop($formulaStrings);
  4147. $formulaStrings[] = "$space1$space0{$token['data']}$op";
  4148. unset($space0, $space1);
  4149. break;
  4150. case 'tPercent': // percent sign
  4151. $op = array_pop($formulaStrings);
  4152. $formulaStrings[] = "$op$space1$space0{$token['data']}";
  4153. unset($space0, $space1);
  4154. break;
  4155. case 'tAttrVolatile': // indicates volatile function
  4156. case 'tAttrIf':
  4157. case 'tAttrSkip':
  4158. case 'tAttrChoose':
  4159. // token is only important for Excel formula evaluator
  4160. // do nothing
  4161. break;
  4162. case 'tAttrSpace': // space / carriage return
  4163. // space will be used when next token arrives, do not alter formulaString stack
  4164. switch ($token['data']['spacetype']) {
  4165. case 'type0':
  4166. $space0 = str_repeat(' ', $token['data']['spacecount']);
  4167. break;
  4168. case 'type1':
  4169. $space1 = str_repeat("\n", $token['data']['spacecount']);
  4170. break;
  4171. case 'type2':
  4172. $space2 = str_repeat(' ', $token['data']['spacecount']);
  4173. break;
  4174. case 'type3':
  4175. $space3 = str_repeat("\n", $token['data']['spacecount']);
  4176. break;
  4177. case 'type4':
  4178. $space4 = str_repeat(' ', $token['data']['spacecount']);
  4179. break;
  4180. case 'type5':
  4181. $space5 = str_repeat("\n", $token['data']['spacecount']);
  4182. break;
  4183. }
  4184. break;
  4185. case 'tAttrSum': // SUM function with one parameter
  4186. $op = array_pop($formulaStrings);
  4187. $formulaStrings[] = "{$space1}{$space0}SUM($op)";
  4188. unset($space0, $space1);
  4189. break;
  4190. case 'tFunc': // function with fixed number of arguments
  4191. case 'tFuncV': // function with variable number of arguments
  4192. if ($token['data']['function'] != '') {
  4193. // normal function
  4194. $ops = array(); // array of operators
  4195. for ($i = 0; $i < $token['data']['args']; ++$i) {
  4196. $ops[] = array_pop($formulaStrings);
  4197. }
  4198. $ops = array_reverse($ops);
  4199. $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ")";
  4200. unset($space0, $space1);
  4201. } else {
  4202. // add-in function
  4203. $ops = array(); // array of operators
  4204. for ($i = 0; $i < $token['data']['args'] - 1; ++$i) {
  4205. $ops[] = array_pop($formulaStrings);
  4206. }
  4207. $ops = array_reverse($ops);
  4208. $function = array_pop($formulaStrings);
  4209. $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ")";
  4210. unset($space0, $space1);
  4211. }
  4212. break;
  4213. case 'tParen': // parenthesis
  4214. $expression = array_pop($formulaStrings);
  4215. $formulaStrings[] = "$space3$space2($expression$space5$space4)";
  4216. unset($space2, $space3, $space4, $space5);
  4217. break;
  4218. case 'tArray': // array constant
  4219. $constantArray = self::_readBIFF8ConstantArray($additionalData);
  4220. $formulaStrings[] = $space1 . $space0 . $constantArray['value'];
  4221. $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data
  4222. unset($space0, $space1);
  4223. break;
  4224. case 'tMemArea':
  4225. // bite off chunk of additional data
  4226. $cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($additionalData);
  4227. $additionalData = substr($additionalData, $cellRangeAddressList['size']);
  4228. $formulaStrings[] = "$space1$space0{$token['data']}";
  4229. unset($space0, $space1);
  4230. break;
  4231. case 'tArea': // cell range address
  4232. case 'tBool': // boolean
  4233. case 'tErr': // error code
  4234. case 'tInt': // integer
  4235. case 'tMemErr':
  4236. case 'tMemFunc':
  4237. case 'tMissArg':
  4238. case 'tName':
  4239. case 'tNameX':
  4240. case 'tNum': // number
  4241. case 'tRef': // single cell reference
  4242. case 'tRef3d': // 3d cell reference
  4243. case 'tArea3d': // 3d cell range reference
  4244. case 'tRefN':
  4245. case 'tAreaN':
  4246. case 'tStr': // string
  4247. $formulaStrings[] = "$space1$space0{$token['data']}";
  4248. unset($space0, $space1);
  4249. break;
  4250. }
  4251. }
  4252. $formulaString = $formulaStrings[0];
  4253. // for debug: dump the human readable formula
  4254. //echo '----' . "\n";
  4255. //echo 'Formula: ' . $formulaString;
  4256. return $formulaString;
  4257. }
  4258. /**
  4259. * Fetch next token from binary formula data
  4260. *
  4261. * @param string Formula data
  4262. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4263. * @return array
  4264. * @throws Exception
  4265. */
  4266. private function _getNextToken($formulaData, $baseCell = 'A1')
  4267. {
  4268. // offset: 0; size: 1; token id
  4269. $id = ord($formulaData[0]); // token id
  4270. $name = false; // initialize token name
  4271. switch ($id) {
  4272. case 0x03: $name = 'tAdd'; $size = 1; $data = '+'; break;
  4273. case 0x04: $name = 'tSub'; $size = 1; $data = '-'; break;
  4274. case 0x05: $name = 'tMul'; $size = 1; $data = '*'; break;
  4275. case 0x06: $name = 'tDiv'; $size = 1; $data = '/'; break;
  4276. case 0x07: $name = 'tPower'; $size = 1; $data = '^'; break;
  4277. case 0x08: $name = 'tConcat'; $size = 1; $data = '&'; break;
  4278. case 0x09: $name = 'tLT'; $size = 1; $data = '<'; break;
  4279. case 0x0A: $name = 'tLE'; $size = 1; $data = '<='; break;
  4280. case 0x0B: $name = 'tEQ'; $size = 1; $data = '='; break;
  4281. case 0x0C: $name = 'tGE'; $size = 1; $data = '>='; break;
  4282. case 0x0D: $name = 'tGT'; $size = 1; $data = '>'; break;
  4283. case 0x0E: $name = 'tNE'; $size = 1; $data = '<>'; break;
  4284. case 0x0F: $name = 'tIsect'; $size = 1; $data = ' '; break;
  4285. case 0x10: $name = 'tList'; $size = 1; $data = ','; break;
  4286. case 0x11: $name = 'tRange'; $size = 1; $data = ':'; break;
  4287. case 0x12: $name = 'tUplus'; $size = 1; $data = '+'; break;
  4288. case 0x13: $name = 'tUminus'; $size = 1; $data = '-'; break;
  4289. case 0x14: $name = 'tPercent'; $size = 1; $data = '%'; break;
  4290. case 0x15: // parenthesis
  4291. $name = 'tParen';
  4292. $size = 1;
  4293. $data = null;
  4294. break;
  4295. case 0x16: // missing argument
  4296. $name = 'tMissArg';
  4297. $size = 1;
  4298. $data = '';
  4299. break;
  4300. case 0x17: // string
  4301. $name = 'tStr';
  4302. // offset: 1; size: var; Unicode string, 8-bit string length
  4303. $string = self::_readUnicodeStringShort(substr($formulaData, 1));
  4304. $size = 1 + $string['size'];
  4305. $data = self::_UTF8toExcelDoubleQuoted($string['value']);
  4306. break;
  4307. case 0x19: // Special attribute
  4308. // offset: 1; size: 1; attribute type flags:
  4309. switch (ord($formulaData[1])) {
  4310. case 0x01:
  4311. $name = 'tAttrVolatile';
  4312. $size = 4;
  4313. $data = null;
  4314. break;
  4315. case 0x02:
  4316. $name = 'tAttrIf';
  4317. $size = 4;
  4318. $data = null;
  4319. break;
  4320. case 0x04:
  4321. $name = 'tAttrChoose';
  4322. // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1)
  4323. $nc = self::_GetInt2d($formulaData, 2);
  4324. // offset: 4; size: 2 * $nc
  4325. // offset: 4 + 2 * $nc; size: 2
  4326. $size = 2 * $nc + 6;
  4327. $data = null;
  4328. break;
  4329. case 0x08:
  4330. $name = 'tAttrSkip';
  4331. $size = 4;
  4332. $data = null;
  4333. break;
  4334. case 0x10:
  4335. $name = 'tAttrSum';
  4336. $size = 4;
  4337. $data = null;
  4338. break;
  4339. case 0x40:
  4340. case 0x41:
  4341. $name = 'tAttrSpace';
  4342. $size = 4;
  4343. // offset: 2; size: 2; space type and position
  4344. switch (ord($formulaData[2])) {
  4345. case 0x00:
  4346. $spacetype = 'type0';
  4347. break;
  4348. case 0x01:
  4349. $spacetype = 'type1';
  4350. break;
  4351. case 0x02:
  4352. $spacetype = 'type2';
  4353. break;
  4354. case 0x03:
  4355. $spacetype = 'type3';
  4356. break;
  4357. case 0x04:
  4358. $spacetype = 'type4';
  4359. break;
  4360. case 0x05:
  4361. $spacetype = 'type5';
  4362. break;
  4363. default:
  4364. throw new Exception('Unrecognized space type in tAttrSpace token');
  4365. break;
  4366. }
  4367. // offset: 3; size: 1; number of inserted spaces/carriage returns
  4368. $spacecount = ord($formulaData[3]);
  4369. $data = array('spacetype' => $spacetype, 'spacecount' => $spacecount);
  4370. break;
  4371. default:
  4372. throw new Exception('Unrecognized attribute flag in tAttr token');
  4373. break;
  4374. }
  4375. break;
  4376. case 0x1C: // error code
  4377. // offset: 1; size: 1; error code
  4378. $name = 'tErr';
  4379. $size = 2;
  4380. $data = self::_mapErrorCode(ord($formulaData[1]));
  4381. break;
  4382. case 0x1D: // boolean
  4383. // offset: 1; size: 1; 0 = false, 1 = true;
  4384. $name = 'tBool';
  4385. $size = 2;
  4386. $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE';
  4387. break;
  4388. case 0x1E: // integer
  4389. // offset: 1; size: 2; unsigned 16-bit integer
  4390. $name = 'tInt';
  4391. $size = 3;
  4392. $data = self::_GetInt2d($formulaData, 1);
  4393. break;
  4394. case 0x1F: // number
  4395. // offset: 1; size: 8;
  4396. $name = 'tNum';
  4397. $size = 9;
  4398. $data = self::_extractNumber(substr($formulaData, 1));
  4399. $data = str_replace(',', '.', (string)$data); // in case non-English locale
  4400. break;
  4401. case 0x20: // array constant
  4402. case 0x40:
  4403. case 0x60:
  4404. // offset: 1; size: 7; not used
  4405. $name = 'tArray';
  4406. $size = 8;
  4407. $data = null;
  4408. break;
  4409. case 0x21: // function with fixed number of arguments
  4410. case 0x41:
  4411. case 0x61:
  4412. $name = 'tFunc';
  4413. $size = 3;
  4414. // offset: 1; size: 2; index to built-in sheet function
  4415. switch (self::_GetInt2d($formulaData, 1)) {
  4416. case 2: $function = 'ISNA'; $args = 1; break;
  4417. case 3: $function = 'ISERROR'; $args = 1; break;
  4418. case 10: $function = 'NA'; $args = 0; break;
  4419. case 15: $function = 'SIN'; $args = 1; break;
  4420. case 16: $function = 'COS'; $args = 1; break;
  4421. case 17: $function = 'TAN'; $args = 1; break;
  4422. case 18: $function = 'ATAN'; $args = 1; break;
  4423. case 19: $function = 'PI'; $args = 0; break;
  4424. case 20: $function = 'SQRT'; $args = 1; break;
  4425. case 21: $function = 'EXP'; $args = 1; break;
  4426. case 22: $function = 'LN'; $args = 1; break;
  4427. case 23: $function = 'LOG10'; $args = 1; break;
  4428. case 24: $function = 'ABS'; $args = 1; break;
  4429. case 25: $function = 'INT'; $args = 1; break;
  4430. case 26: $function = 'SIGN'; $args = 1; break;
  4431. case 27: $function = 'ROUND'; $args = 2; break;
  4432. case 30: $function = 'REPT'; $args = 2; break;
  4433. case 31: $function = 'MID'; $args = 3; break;
  4434. case 32: $function = 'LEN'; $args = 1; break;
  4435. case 33: $function = 'VALUE'; $args = 1; break;
  4436. case 34: $function = 'TRUE'; $args = 0; break;
  4437. case 35: $function = 'FALSE'; $args = 0; break;
  4438. case 38: $function = 'NOT'; $args = 1; break;
  4439. case 39: $function = 'MOD'; $args = 2; break;
  4440. case 40: $function = 'DCOUNT'; $args = 3; break;
  4441. case 41: $function = 'DSUM'; $args = 3; break;
  4442. case 42: $function = 'DAVERAGE'; $args = 3; break;
  4443. case 43: $function = 'DMIN'; $args = 3; break;
  4444. case 44: $function = 'DMAX'; $args = 3; break;
  4445. case 45: $function = 'DSTDEV'; $args = 3; break;
  4446. case 48: $function = 'TEXT'; $args = 2; break;
  4447. case 61: $function = 'MIRR'; $args = 3; break;
  4448. case 63: $function = 'RAND'; $args = 0; break;
  4449. case 65: $function = 'DATE'; $args = 3; break;
  4450. case 66: $function = 'TIME'; $args = 3; break;
  4451. case 67: $function = 'DAY'; $args = 1; break;
  4452. case 68: $function = 'MONTH'; $args = 1; break;
  4453. case 69: $function = 'YEAR'; $args = 1; break;
  4454. case 71: $function = 'HOUR'; $args = 1; break;
  4455. case 72: $function = 'MINUTE'; $args = 1; break;
  4456. case 73: $function = 'SECOND'; $args = 1; break;
  4457. case 74: $function = 'NOW'; $args = 0; break;
  4458. case 75: $function = 'AREAS'; $args = 1; break;
  4459. case 76: $function = 'ROWS'; $args = 1; break;
  4460. case 77: $function = 'COLUMNS'; $args = 1; break;
  4461. case 83: $function = 'TRANSPOSE'; $args = 1; break;
  4462. case 86: $function = 'TYPE'; $args = 1; break;
  4463. case 97: $function = 'ATAN2'; $args = 2; break;
  4464. case 98: $function = 'ASIN'; $args = 1; break;
  4465. case 99: $function = 'ACOS'; $args = 1; break;
  4466. case 105: $function = 'ISREF'; $args = 1; break;
  4467. case 111: $function = 'CHAR'; $args = 1; break;
  4468. case 112: $function = 'LOWER'; $args = 1; break;
  4469. case 113: $function = 'UPPER'; $args = 1; break;
  4470. case 114: $function = 'PROPER'; $args = 1; break;
  4471. case 117: $function = 'EXACT'; $args = 2; break;
  4472. case 118: $function = 'TRIM'; $args = 1; break;
  4473. case 119: $function = 'REPLACE'; $args = 4; break;
  4474. case 121: $function = 'CODE'; $args = 1; break;
  4475. case 126: $function = 'ISERR'; $args = 1; break;
  4476. case 127: $function = 'ISTEXT'; $args = 1; break;
  4477. case 128: $function = 'ISNUMBER'; $args = 1; break;
  4478. case 129: $function = 'ISBLANK'; $args = 1; break;
  4479. case 130: $function = 'T'; $args = 1; break;
  4480. case 131: $function = 'N'; $args = 1; break;
  4481. case 140: $function = 'DATEVALUE'; $args = 1; break;
  4482. case 141: $function = 'TIMEVALUE'; $args = 1; break;
  4483. case 142: $function = 'SLN'; $args = 3; break;
  4484. case 143: $function = 'SYD'; $args = 4; break;
  4485. case 162: $function = 'CLEAN'; $args = 1; break;
  4486. case 163: $function = 'MDETERM'; $args = 1; break;
  4487. case 164: $function = 'MINVERSE'; $args = 1; break;
  4488. case 165: $function = 'MMULT'; $args = 2; break;
  4489. case 184: $function = 'FACT'; $args = 1; break;
  4490. case 189: $function = 'DPRODUCT'; $args = 3; break;
  4491. case 190: $function = 'ISNONTEXT'; $args = 1; break;
  4492. case 195: $function = 'DSTDEVP'; $args = 3; break;
  4493. case 196: $function = 'DVARP'; $args = 3; break;
  4494. case 198: $function = 'ISLOGICAL'; $args = 1; break;
  4495. case 199: $function = 'DCOUNTA'; $args = 3; break;
  4496. case 207: $function = 'REPLACEB'; $args = 4; break;
  4497. case 210: $function = 'MIDB'; $args = 3; break;
  4498. case 211: $function = 'LENB'; $args = 1; break;
  4499. case 212: $function = 'ROUNDUP'; $args = 2; break;
  4500. case 213: $function = 'ROUNDDOWN'; $args = 2; break;
  4501. case 214: $function = 'ASC'; $args = 1; break;
  4502. case 215: $function = 'DBCS'; $args = 1; break;
  4503. case 221: $function = 'TODAY'; $args = 0; break;
  4504. case 229: $function = 'SINH'; $args = 1; break;
  4505. case 230: $function = 'COSH'; $args = 1; break;
  4506. case 231: $function = 'TANH'; $args = 1; break;
  4507. case 232: $function = 'ASINH'; $args = 1; break;
  4508. case 233: $function = 'ACOSH'; $args = 1; break;
  4509. case 234: $function = 'ATANH'; $args = 1; break;
  4510. case 235: $function = 'DGET'; $args = 3; break;
  4511. case 244: $function = 'INFO'; $args = 1; break;
  4512. case 252: $function = 'FREQUENCY'; $args = 2; break;
  4513. case 261: $function = 'ERROR.TYPE'; $args = 1; break;
  4514. case 271: $function = 'GAMMALN'; $args = 1; break;
  4515. case 273: $function = 'BINOMDIST'; $args = 4; break;
  4516. case 274: $function = 'CHIDIST'; $args = 2; break;
  4517. case 275: $function = 'CHIINV'; $args = 2; break;
  4518. case 276: $function = 'COMBIN'; $args = 2; break;
  4519. case 277: $function = 'CONFIDENCE'; $args = 3; break;
  4520. case 278: $function = 'CRITBINOM'; $args = 3; break;
  4521. case 279: $function = 'EVEN'; $args = 1; break;
  4522. case 280: $function = 'EXPONDIST'; $args = 3; break;
  4523. case 281: $function = 'FDIST'; $args = 3; break;
  4524. case 282: $function = 'FINV'; $args = 3; break;
  4525. case 283: $function = 'FISHER'; $args = 1; break;
  4526. case 284: $function = 'FISHERINV'; $args = 1; break;
  4527. case 285: $function = 'FLOOR'; $args = 2; break;
  4528. case 286: $function = 'GAMMADIST'; $args = 4; break;
  4529. case 287: $function = 'GAMMAINV'; $args = 3; break;
  4530. case 288: $function = 'CEILING'; $args = 2; break;
  4531. case 289: $function = 'HYPGEOMDIST'; $args = 4; break;
  4532. case 290: $function = 'LOGNORMDIST'; $args = 3; break;
  4533. case 291: $function = 'LOGINV'; $args = 3; break;
  4534. case 292: $function = 'NEGBINOMDIST'; $args = 3; break;
  4535. case 293: $function = 'NORMDIST'; $args = 4; break;
  4536. case 294: $function = 'NORMSDIST'; $args = 1; break;
  4537. case 295: $function = 'NORMINV'; $args = 3; break;
  4538. case 296: $function = 'NORMSINV'; $args = 1; break;
  4539. case 297: $function = 'STANDARDIZE'; $args = 3; break;
  4540. case 298: $function = 'ODD'; $args = 1; break;
  4541. case 299: $function = 'PERMUT'; $args = 2; break;
  4542. case 300: $function = 'POISSON'; $args = 3; break;
  4543. case 301: $function = 'TDIST'; $args = 3; break;
  4544. case 302: $function = 'WEIBULL'; $args = 4; break;
  4545. case 303: $function = 'SUMXMY2'; $args = 2; break;
  4546. case 304: $function = 'SUMX2MY2'; $args = 2; break;
  4547. case 305: $function = 'SUMX2PY2'; $args = 2; break;
  4548. case 306: $function = 'CHITEST'; $args = 2; break;
  4549. case 307: $function = 'CORREL'; $args = 2; break;
  4550. case 308: $function = 'COVAR'; $args = 2; break;
  4551. case 309: $function = 'FORECAST'; $args = 3; break;
  4552. case 310: $function = 'FTEST'; $args = 2; break;
  4553. case 311: $function = 'INTERCEPT'; $args = 2; break;
  4554. case 312: $function = 'PEARSON'; $args = 2; break;
  4555. case 313: $function = 'RSQ'; $args = 2; break;
  4556. case 314: $function = 'STEYX'; $args = 2; break;
  4557. case 315: $function = 'SLOPE'; $args = 2; break;
  4558. case 316: $function = 'TTEST'; $args = 4; break;
  4559. case 325: $function = 'LARGE'; $args = 2; break;
  4560. case 326: $function = 'SMALL'; $args = 2; break;
  4561. case 327: $function = 'QUARTILE'; $args = 2; break;
  4562. case 328: $function = 'PERCENTILE'; $args = 2; break;
  4563. case 331: $function = 'TRIMMEAN'; $args = 2; break;
  4564. case 332: $function = 'TINV'; $args = 2; break;
  4565. case 337: $function = 'POWER'; $args = 2; break;
  4566. case 342: $function = 'RADIANS'; $args = 1; break;
  4567. case 343: $function = 'DEGREES'; $args = 1; break;
  4568. case 346: $function = 'COUNTIF'; $args = 2; break;
  4569. case 347: $function = 'COUNTBLANK'; $args = 1; break;
  4570. case 350: $function = 'ISPMT'; $args = 4; break;
  4571. case 351: $function = 'DATEDIF'; $args = 3; break;
  4572. case 352: $function = 'DATESTRING'; $args = 1; break;
  4573. case 353: $function = 'NUMBERSTRING'; $args = 2; break;
  4574. case 360: $function = 'PHONETIC'; $args = 1; break;
  4575. case 368: $function = 'BAHTTEXT'; $args = 1; break;
  4576. default:
  4577. throw new Exception('Unrecognized function in formula');
  4578. break;
  4579. }
  4580. $data = array('function' => $function, 'args' => $args);
  4581. break;
  4582. case 0x22: // function with variable number of arguments
  4583. case 0x42:
  4584. case 0x62:
  4585. $name = 'tFuncV';
  4586. $size = 4;
  4587. // offset: 1; size: 1; number of arguments
  4588. $args = ord($formulaData[1]);
  4589. // offset: 2: size: 2; index to built-in sheet function
  4590. $index = self::_GetInt2d($formulaData, 2);
  4591. switch ($index) {
  4592. case 0: $function = 'COUNT'; break;
  4593. case 1: $function = 'IF'; break;
  4594. case 4: $function = 'SUM'; break;
  4595. case 5: $function = 'AVERAGE'; break;
  4596. case 6: $function = 'MIN'; break;
  4597. case 7: $function = 'MAX'; break;
  4598. case 8: $function = 'ROW'; break;
  4599. case 9: $function = 'COLUMN'; break;
  4600. case 11: $function = 'NPV'; break;
  4601. case 12: $function = 'STDEV'; break;
  4602. case 13: $function = 'DOLLAR'; break;
  4603. case 14: $function = 'FIXED'; break;
  4604. case 28: $function = 'LOOKUP'; break;
  4605. case 29: $function = 'INDEX'; break;
  4606. case 36: $function = 'AND'; break;
  4607. case 37: $function = 'OR'; break;
  4608. case 46: $function = 'VAR'; break;
  4609. case 49: $function = 'LINEST'; break;
  4610. case 50: $function = 'TREND'; break;
  4611. case 51: $function = 'LOGEST'; break;
  4612. case 52: $function = 'GROWTH'; break;
  4613. case 56: $function = 'PV'; break;
  4614. case 57: $function = 'FV'; break;
  4615. case 58: $function = 'NPER'; break;
  4616. case 59: $function = 'PMT'; break;
  4617. case 60: $function = 'RATE'; break;
  4618. case 62: $function = 'IRR'; break;
  4619. case 64: $function = 'MATCH'; break;
  4620. case 70: $function = 'WEEKDAY'; break;
  4621. case 78: $function = 'OFFSET'; break;
  4622. case 82: $function = 'SEARCH'; break;
  4623. case 100: $function = 'CHOOSE'; break;
  4624. case 101: $function = 'HLOOKUP'; break;
  4625. case 102: $function = 'VLOOKUP'; break;
  4626. case 109: $function = 'LOG'; break;
  4627. case 115: $function = 'LEFT'; break;
  4628. case 116: $function = 'RIGHT'; break;
  4629. case 120: $function = 'SUBSTITUTE'; break;
  4630. case 124: $function = 'FIND'; break;
  4631. case 125: $function = 'CELL'; break;
  4632. case 144: $function = 'DDB'; break;
  4633. case 148: $function = 'INDIRECT'; break;
  4634. case 167: $function = 'IPMT'; break;
  4635. case 168: $function = 'PPMT'; break;
  4636. case 169: $function = 'COUNTA'; break;
  4637. case 183: $function = 'PRODUCT'; break;
  4638. case 193: $function = 'STDEVP'; break;
  4639. case 194: $function = 'VARP'; break;
  4640. case 197: $function = 'TRUNC'; break;
  4641. case 204: $function = 'USDOLLAR'; break;
  4642. case 205: $function = 'FINDB'; break;
  4643. case 206: $function = 'SEARCHB'; break;
  4644. case 208: $function = 'LEFTB'; break;
  4645. case 209: $function = 'RIGHTB'; break;
  4646. case 216: $function = 'RANK'; break;
  4647. case 219: $function = 'ADDRESS'; break;
  4648. case 220: $function = 'DAYS360'; break;
  4649. case 222: $function = 'VDB'; break;
  4650. case 227: $function = 'MEDIAN'; break;
  4651. case 228: $function = 'SUMPRODUCT'; break;
  4652. case 247: $function = 'DB'; break;
  4653. case 255: $function = ''; break;
  4654. case 269: $function = 'AVEDEV'; break;
  4655. case 270: $function = 'BETADIST'; break;
  4656. case 272: $function = 'BETAINV'; break;
  4657. case 317: $function = 'PROB'; break;
  4658. case 318: $function = 'DEVSQ'; break;
  4659. case 319: $function = 'GEOMEAN'; break;
  4660. case 320: $function = 'HARMEAN'; break;
  4661. case 321: $function = 'SUMSQ'; break;
  4662. case 322: $function = 'KURT'; break;
  4663. case 323: $function = 'SKEW'; break;
  4664. case 324: $function = 'ZTEST'; break;
  4665. case 329: $function = 'PERCENTRANK'; break;
  4666. case 330: $function = 'MODE'; break;
  4667. case 336: $function = 'CONCATENATE'; break;
  4668. case 344: $function = 'SUBTOTAL'; break;
  4669. case 345: $function = 'SUMIF'; break;
  4670. case 354: $function = 'ROMAN'; break;
  4671. case 358: $function = 'GETPIVOTDATA'; break;
  4672. case 359: $function = 'HYPERLINK'; break;
  4673. case 361: $function = 'AVERAGEA'; break;
  4674. case 362: $function = 'MAXA'; break;
  4675. case 363: $function = 'MINA'; break;
  4676. case 364: $function = 'STDEVPA'; break;
  4677. case 365: $function = 'VARPA'; break;
  4678. case 366: $function = 'STDEVA'; break;
  4679. case 367: $function = 'VARA'; break;
  4680. default:
  4681. throw new Exception('Unrecognized function in formula');
  4682. break;
  4683. }
  4684. $data = array('function' => $function, 'args' => $args);
  4685. break;
  4686. case 0x23: // index to defined name
  4687. case 0x43:
  4688. case 0x63:
  4689. $name = 'tName';
  4690. $size = 5;
  4691. // offset: 1; size: 2; one-based index to definedname record
  4692. $definedNameIndex = self::_GetInt2d($formulaData, 1) - 1;
  4693. // offset: 2; size: 2; not used
  4694. $data = $this->_definedname[$definedNameIndex]['name'];
  4695. break;
  4696. case 0x24: // single cell reference e.g. A5
  4697. case 0x44:
  4698. case 0x64:
  4699. $name = 'tRef';
  4700. $size = 5;
  4701. $data = $this->_readBIFF8CellAddress(substr($formulaData, 1, 4));
  4702. break;
  4703. case 0x25: // cell range reference to cells in the same sheet (2d)
  4704. case 0x45:
  4705. case 0x65:
  4706. $name = 'tArea';
  4707. $size = 9;
  4708. $data = $this->_readBIFF8CellRangeAddress(substr($formulaData, 1, 8));
  4709. break;
  4710. case 0x26: // Constant reference sub-expression
  4711. case 0x46:
  4712. case 0x66:
  4713. $name = 'tMemArea';
  4714. // offset: 1; size: 4; not used
  4715. // offset: 5; size: 2; size of the following subexpression
  4716. $subSize = self::_GetInt2d($formulaData, 5);
  4717. $size = 7 + $subSize;
  4718. $data = $this->_getFormulaFromData(substr($formulaData, 7, $subSize));
  4719. break;
  4720. case 0x27: // Deleted constant reference sub-expression
  4721. case 0x47:
  4722. case 0x67:
  4723. $name = 'tMemErr';
  4724. // offset: 1; size: 4; not used
  4725. // offset: 5; size: 2; size of the following subexpression
  4726. $subSize = self::_GetInt2d($formulaData, 5);
  4727. $size = 7 + $subSize;
  4728. $data = $this->_getFormulaFromData(substr($formulaData, 7, $subSize));
  4729. break;
  4730. case 0x29: // Variable reference sub-expression
  4731. case 0x49:
  4732. case 0x69:
  4733. $name = 'tMemFunc';
  4734. // offset: 1; size: 2; size of the following sub-expression
  4735. $subSize = self::_GetInt2d($formulaData, 1);
  4736. $size = 3 + $subSize;
  4737. $data = $this->_getFormulaFromData(substr($formulaData, 3, $subSize));
  4738. break;
  4739. case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places
  4740. case 0x4C:
  4741. case 0x6C:
  4742. $name = 'tRefN';
  4743. $size = 5;
  4744. $data = $this->_readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell);
  4745. break;
  4746. case 0x2D: // Relative 2d range reference
  4747. case 0x4D:
  4748. case 0x6D:
  4749. $name = 'tAreaN';
  4750. $size = 9;
  4751. $data = $this->_readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell);
  4752. break;
  4753. case 0x39: // External name
  4754. case 0x59:
  4755. case 0x79:
  4756. $name = 'tNameX';
  4757. $size = 7;
  4758. // offset: 1; size: 2; index to REF entry in EXTERNSHEET record
  4759. // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record
  4760. $index = self::_GetInt2d($formulaData, 3);
  4761. // assume index is to EXTERNNAME record
  4762. $data = $this->_externalNames[$index - 1]['name'];
  4763. // offset: 5; size: 2; not used
  4764. break;
  4765. case 0x3A: // 3d reference to cell
  4766. case 0x5A:
  4767. case 0x7A:
  4768. $name = 'tRef3d';
  4769. $size = 7;
  4770. try {
  4771. // offset: 1; size: 2; index to REF entry
  4772. $sheetRange = $this->_readSheetRangeByRefIndex(self::_GetInt2d($formulaData, 1));
  4773. // offset: 3; size: 4; cell address
  4774. $cellAddress = $this->_readBIFF8CellAddress(substr($formulaData, 3, 4));
  4775. $data = "$sheetRange!$cellAddress";
  4776. } catch (Exception $e) {
  4777. // deleted sheet reference
  4778. $data = '#REF!';
  4779. }
  4780. break;
  4781. case 0x3B: // 3d reference to cell range
  4782. case 0x5B:
  4783. case 0x7B:
  4784. $name = 'tArea3d';
  4785. $size = 11;
  4786. try {
  4787. // offset: 1; size: 2; index to REF entry
  4788. $sheetRange = $this->_readSheetRangeByRefIndex(self::_GetInt2d($formulaData, 1));
  4789. // offset: 3; size: 8; cell address
  4790. $cellRangeAddress = $this->_readBIFF8CellRangeAddress(substr($formulaData, 3, 8));
  4791. $data = "$sheetRange!$cellRangeAddress";
  4792. } catch (Exception $e) {
  4793. // deleted sheet reference
  4794. $data = '#REF!';
  4795. }
  4796. break;
  4797. // Unknown cases // don't know how to deal with
  4798. default:
  4799. throw new Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula');
  4800. break;
  4801. }
  4802. return array(
  4803. 'id' => $id,
  4804. 'name' => $name,
  4805. 'size' => $size,
  4806. 'data' => $data,
  4807. );
  4808. }
  4809. /**
  4810. * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2'
  4811. * section 3.3.4
  4812. *
  4813. * @param string $cellAddressStructure
  4814. * @return string
  4815. */
  4816. private function _readBIFF8CellAddress($cellAddressStructure)
  4817. {
  4818. // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))
  4819. $row = self::_GetInt2d($cellAddressStructure, 0) + 1;
  4820. // offset: 2; size: 2; index to column or column offset + relative flags
  4821. // bit: 7-0; mask 0x00FF; column index
  4822. $column = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($cellAddressStructure, 2));
  4823. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  4824. if (!(0x4000 & self::_GetInt2d($cellAddressStructure, 2))) {
  4825. $column = '$' . $column;
  4826. }
  4827. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  4828. if (!(0x8000 & self::_GetInt2d($cellAddressStructure, 2))) {
  4829. $row = '$' . $row;
  4830. }
  4831. return $column . $row;
  4832. }
  4833. /**
  4834. * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column
  4835. * to indicate offsets from a base cell
  4836. * section 3.3.4
  4837. *
  4838. * @param string $cellAddressStructure
  4839. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4840. * @return string
  4841. */
  4842. private function _readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1')
  4843. {
  4844. list($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell);
  4845. $baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1;
  4846. // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))
  4847. $rowIndex = self::_GetInt2d($cellAddressStructure, 0);
  4848. $row = self::_GetInt2d($cellAddressStructure, 0) + 1;
  4849. // offset: 2; size: 2; index to column or column offset + relative flags
  4850. // bit: 7-0; mask 0x00FF; column index
  4851. $colIndex = 0x00FF & self::_GetInt2d($cellAddressStructure, 2);
  4852. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  4853. if (!(0x4000 & self::_GetInt2d($cellAddressStructure, 2))) {
  4854. $column = PHPExcel_Cell::stringFromColumnIndex($colIndex);
  4855. $column = '$' . $column;
  4856. } else {
  4857. $colIndex = ($colIndex <= 127) ? $colIndex : $colIndex - 256;
  4858. $column = PHPExcel_Cell::stringFromColumnIndex($baseCol + $colIndex);
  4859. }
  4860. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  4861. if (!(0x8000 & self::_GetInt2d($cellAddressStructure, 2))) {
  4862. $row = '$' . $row;
  4863. } else {
  4864. $rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536;
  4865. $row = $baseRow + $rowIndex;
  4866. }
  4867. return $column . $row;
  4868. }
  4869. /**
  4870. * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1'
  4871. * always fixed range
  4872. * section 2.5.14
  4873. *
  4874. * @param string $subData
  4875. * @return string
  4876. * @throws Exception
  4877. */
  4878. private function _readBIFF5CellRangeAddressFixed($subData)
  4879. {
  4880. // offset: 0; size: 2; index to first row
  4881. $fr = self::_GetInt2d($subData, 0) + 1;
  4882. // offset: 2; size: 2; index to last row
  4883. $lr = self::_GetInt2d($subData, 2) + 1;
  4884. // offset: 4; size: 1; index to first column
  4885. $fc = ord($subData{4});
  4886. // offset: 5; size: 1; index to last column
  4887. $lc = ord($subData{5});
  4888. // check values
  4889. if ($fr > $lr || $fc > $lc) {
  4890. throw new Exception('Not a cell range address');
  4891. }
  4892. // column index to letter
  4893. $fc = PHPExcel_Cell::stringFromColumnIndex($fc);
  4894. $lc = PHPExcel_Cell::stringFromColumnIndex($lc);
  4895. if ($fr == $lr and $fc == $lc) {
  4896. return "$fc$fr";
  4897. }
  4898. return "$fc$fr:$lc$lr";
  4899. }
  4900. /**
  4901. * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1'
  4902. * always fixed range
  4903. * section 2.5.14
  4904. *
  4905. * @param string $subData
  4906. * @return string
  4907. * @throws Exception
  4908. */
  4909. private function _readBIFF8CellRangeAddressFixed($subData)
  4910. {
  4911. // offset: 0; size: 2; index to first row
  4912. $fr = self::_GetInt2d($subData, 0) + 1;
  4913. // offset: 2; size: 2; index to last row
  4914. $lr = self::_GetInt2d($subData, 2) + 1;
  4915. // offset: 4; size: 2; index to first column
  4916. $fc = self::_GetInt2d($subData, 4);
  4917. // offset: 6; size: 2; index to last column
  4918. $lc = self::_GetInt2d($subData, 6);
  4919. // check values
  4920. if ($fr > $lr || $fc > $lc) {
  4921. throw new Exception('Not a cell range address');
  4922. }
  4923. // column index to letter
  4924. $fc = PHPExcel_Cell::stringFromColumnIndex($fc);
  4925. $lc = PHPExcel_Cell::stringFromColumnIndex($lc);
  4926. if ($fr == $lr and $fc == $lc) {
  4927. return "$fc$fr";
  4928. }
  4929. return "$fc$fr:$lc$lr";
  4930. }
  4931. /**
  4932. * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6'
  4933. * there are flags indicating whether column/row index is relative
  4934. * section 3.3.4
  4935. *
  4936. * @param string $subData
  4937. * @return string
  4938. */
  4939. private function _readBIFF8CellRangeAddress($subData)
  4940. {
  4941. // todo: if cell range is just a single cell, should this funciton
  4942. // not just return e.g. 'A1' and not 'A1:A1' ?
  4943. // offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767))
  4944. $fr = self::_GetInt2d($subData, 0) + 1;
  4945. // offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767))
  4946. $lr = self::_GetInt2d($subData, 2) + 1;
  4947. // offset: 4; size: 2; index to first column or column offset + relative flags
  4948. // bit: 7-0; mask 0x00FF; column index
  4949. $fc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($subData, 4));
  4950. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  4951. if (!(0x4000 & self::_GetInt2d($subData, 4))) {
  4952. $fc = '$' . $fc;
  4953. }
  4954. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  4955. if (!(0x8000 & self::_GetInt2d($subData, 4))) {
  4956. $fr = '$' . $fr;
  4957. }
  4958. // offset: 6; size: 2; index to last column or column offset + relative flags
  4959. // bit: 7-0; mask 0x00FF; column index
  4960. $lc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($subData, 6));
  4961. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  4962. if (!(0x4000 & self::_GetInt2d($subData, 6))) {
  4963. $lc = '$' . $lc;
  4964. }
  4965. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  4966. if (!(0x8000 & self::_GetInt2d($subData, 6))) {
  4967. $lr = '$' . $lr;
  4968. }
  4969. return "$fc$fr:$lc$lr";
  4970. }
  4971. /**
  4972. * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column
  4973. * to indicate offsets from a base cell
  4974. * section 3.3.4
  4975. *
  4976. * @param string $subData
  4977. * @param string $baseCell Base cell
  4978. * @return string Cell range address
  4979. */
  4980. private function _readBIFF8CellRangeAddressB($subData, $baseCell = 'A1')
  4981. {
  4982. list($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell);
  4983. $baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1;
  4984. // TODO: if cell range is just a single cell, should this funciton
  4985. // not just return e.g. 'A1' and not 'A1:A1' ?
  4986. // offset: 0; size: 2; first row
  4987. $frIndex = self::_GetInt2d($subData, 0); // adjust below
  4988. // offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767)
  4989. $lrIndex = self::_GetInt2d($subData, 2); // adjust below
  4990. // offset: 4; size: 2; first column with relative/absolute flags
  4991. // bit: 7-0; mask 0x00FF; column index
  4992. $fcIndex = 0x00FF & self::_GetInt2d($subData, 4);
  4993. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  4994. if (!(0x4000 & self::_GetInt2d($subData, 4))) {
  4995. // absolute column index
  4996. $fc = PHPExcel_Cell::stringFromColumnIndex($fcIndex);
  4997. $fc = '$' . $fc;
  4998. } else {
  4999. // column offset
  5000. $fcIndex = ($fcIndex <= 127) ? $fcIndex : $fcIndex - 256;
  5001. $fc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $fcIndex);
  5002. }
  5003. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  5004. if (!(0x8000 & self::_GetInt2d($subData, 4))) {
  5005. // absolute row index
  5006. $fr = $frIndex + 1;
  5007. $fr = '$' . $fr;
  5008. } else {
  5009. // row offset
  5010. $frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536;
  5011. $fr = $baseRow + $frIndex;
  5012. }
  5013. // offset: 6; size: 2; last column with relative/absolute flags
  5014. // bit: 7-0; mask 0x00FF; column index
  5015. $lcIndex = 0x00FF & self::_GetInt2d($subData, 6);
  5016. $lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256;
  5017. $lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex);
  5018. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  5019. if (!(0x4000 & self::_GetInt2d($subData, 6))) {
  5020. // absolute column index
  5021. $lc = PHPExcel_Cell::stringFromColumnIndex($lcIndex);
  5022. $lc = '$' . $lc;
  5023. } else {
  5024. // column offset
  5025. $lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256;
  5026. $lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex);
  5027. }
  5028. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  5029. if (!(0x8000 & self::_GetInt2d($subData, 6))) {
  5030. // absolute row index
  5031. $lr = $lrIndex + 1;
  5032. $lr = '$' . $lr;
  5033. } else {
  5034. // row offset
  5035. $lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536;
  5036. $lr = $baseRow + $lrIndex;
  5037. }
  5038. return "$fc$fr:$lc$lr";
  5039. }
  5040. /**
  5041. * Read BIFF8 cell range address list
  5042. * section 2.5.15
  5043. *
  5044. * @param string $subData
  5045. * @return array
  5046. */
  5047. private function _readBIFF8CellRangeAddressList($subData)
  5048. {
  5049. $cellRangeAddresses = array();
  5050. // offset: 0; size: 2; number of the following cell range addresses
  5051. $nm = self::_GetInt2d($subData, 0);
  5052. $offset = 2;
  5053. // offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses
  5054. for ($i = 0; $i < $nm; ++$i) {
  5055. $cellRangeAddresses[] = $this->_readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8));
  5056. $offset += 8;
  5057. }
  5058. return array(
  5059. 'size' => 2 + 8 * $nm,
  5060. 'cellRangeAddresses' => $cellRangeAddresses,
  5061. );
  5062. }
  5063. /**
  5064. * Read BIFF5 cell range address list
  5065. * section 2.5.15
  5066. *
  5067. * @param string $subData
  5068. * @return array
  5069. */
  5070. private function _readBIFF5CellRangeAddressList($subData)
  5071. {
  5072. $cellRangeAddresses = array();
  5073. // offset: 0; size: 2; number of the following cell range addresses
  5074. $nm = self::_GetInt2d($subData, 0);
  5075. $offset = 2;
  5076. // offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses
  5077. for ($i = 0; $i < $nm; ++$i) {
  5078. $cellRangeAddresses[] = $this->_readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6));
  5079. $offset += 6;
  5080. }
  5081. return array(
  5082. 'size' => 2 + 6 * $nm,
  5083. 'cellRangeAddresses' => $cellRangeAddresses,
  5084. );
  5085. }
  5086. /**
  5087. * Get a sheet range like Sheet1:Sheet3 from REF index
  5088. * Note: If there is only one sheet in the range, one gets e.g Sheet1
  5089. * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets,
  5090. * in which case an exception is thrown
  5091. *
  5092. * @param int $index
  5093. * @return string|false
  5094. * @throws Exception
  5095. */
  5096. private function _readSheetRangeByRefIndex($index)
  5097. {
  5098. if (isset($this->_ref[$index])) {
  5099. $type = $this->_externalBooks[$this->_ref[$index]['externalBookIndex']]['type'];
  5100. switch ($type) {
  5101. case 'internal':
  5102. // check if we have a deleted 3d reference
  5103. if ($this->_ref[$index]['firstSheetIndex'] == 0xFFFF or $this->_ref[$index]['lastSheetIndex'] == 0xFFFF) {
  5104. throw new Exception('Deleted sheet reference');
  5105. }
  5106. // we have normal sheet range (collapsed or uncollapsed)
  5107. $firstSheetName = $this->_sheets[$this->_ref[$index]['firstSheetIndex']]['name'];
  5108. $lastSheetName = $this->_sheets[$this->_ref[$index]['lastSheetIndex']]['name'];
  5109. if ($firstSheetName == $lastSheetName) {
  5110. // collapsed sheet range
  5111. $sheetRange = $firstSheetName;
  5112. } else {
  5113. $sheetRange = "$firstSheetName:$lastSheetName";
  5114. }
  5115. // escape the single-quotes
  5116. $sheetRange = str_replace("'", "''", $sheetRange);
  5117. // if there are special characters, we need to enclose the range in single-quotes
  5118. // todo: check if we have identified the whole set of special characters
  5119. // it seems that the following characters are not accepted for sheet names
  5120. // and we may assume that they are not present: []*/:\?
  5121. if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/", $sheetRange)) {
  5122. $sheetRange = "'$sheetRange'";
  5123. }
  5124. return $sheetRange;
  5125. break;
  5126. default:
  5127. // TODO: external sheet support
  5128. throw new Exception('Excel5 reader only supports internal sheets in fomulas');
  5129. break;
  5130. }
  5131. }
  5132. return false;
  5133. }
  5134. /**
  5135. * read BIFF8 constant value array from array data
  5136. * returns e.g. array('value' => '{1,2;3,4}', 'size' => 40}
  5137. * section 2.5.8
  5138. *
  5139. * @param string $arrayData
  5140. * @return array
  5141. */
  5142. private static function _readBIFF8ConstantArray($arrayData)
  5143. {
  5144. // offset: 0; size: 1; number of columns decreased by 1
  5145. $nc = ord($arrayData[0]);
  5146. // offset: 1; size: 2; number of rows decreased by 1
  5147. $nr = self::_GetInt2d($arrayData, 1);
  5148. $size = 3; // initialize
  5149. $arrayData = substr($arrayData, 3);
  5150. // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values
  5151. $matrixChunks = array();
  5152. for ($r = 1; $r <= $nr + 1; ++$r) {
  5153. $items = array();
  5154. for ($c = 1; $c <= $nc + 1; ++$c) {
  5155. $constant = self::_readBIFF8Constant($arrayData);
  5156. $items[] = $constant['value'];
  5157. $arrayData = substr($arrayData, $constant['size']);
  5158. $size += $constant['size'];
  5159. }
  5160. $matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"'
  5161. }
  5162. $matrix = '{' . implode(';', $matrixChunks) . '}';
  5163. return array(
  5164. 'value' => $matrix,
  5165. 'size' => $size,
  5166. );
  5167. }
  5168. /**
  5169. * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value'
  5170. * section 2.5.7
  5171. * returns e.g. array('value' => '5', 'size' => 9)
  5172. *
  5173. * @param string $valueData
  5174. * @return array
  5175. */
  5176. private static function _readBIFF8Constant($valueData)
  5177. {
  5178. // offset: 0; size: 1; identifier for type of constant
  5179. $identifier = ord($valueData[0]);
  5180. switch ($identifier) {
  5181. case 0x00: // empty constant (what is this?)
  5182. $value = '';
  5183. $size = 9;
  5184. break;
  5185. case 0x01: // number
  5186. // offset: 1; size: 8; IEEE 754 floating-point value
  5187. $value = self::_extractNumber(substr($valueData, 1, 8));
  5188. $size = 9;
  5189. break;
  5190. case 0x02: // string value
  5191. // offset: 1; size: var; Unicode string, 16-bit string length
  5192. $string = self::_readUnicodeStringLong(substr($valueData, 1));
  5193. $value = '"' . $string['value'] . '"';
  5194. $size = 1 + $string['size'];
  5195. break;
  5196. case 0x04: // boolean
  5197. // offset: 1; size: 1; 0 = FALSE, 1 = TRUE
  5198. if (ord($valueData[1])) {
  5199. $value = 'TRUE';
  5200. } else {
  5201. $value = 'FALSE';
  5202. }
  5203. $size = 9;
  5204. break;
  5205. case 0x10: // error code
  5206. // offset: 1; size: 1; error code
  5207. $value = self::_mapErrorCode(ord($valueData[1]));
  5208. $size = 9;
  5209. break;
  5210. }
  5211. return array(
  5212. 'value' => $value,
  5213. 'size' => $size,
  5214. );
  5215. }
  5216. /**
  5217. * Extract RGB color
  5218. * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4
  5219. *
  5220. * @param string $rgb Encoded RGB value (4 bytes)
  5221. * @return array
  5222. */
  5223. private static function _readRGB($rgb)
  5224. {
  5225. // offset: 0; size 1; Red component
  5226. $r = ord($rgb{0});
  5227. // offset: 1; size: 1; Green component
  5228. $g = ord($rgb{1});
  5229. // offset: 2; size: 1; Blue component
  5230. $b = ord($rgb{2});
  5231. // HEX notation, e.g. 'FF00FC'
  5232. $rgb = sprintf('%02X%02X%02X', $r, $g, $b);
  5233. return array('rgb' => $rgb);
  5234. }
  5235. /**
  5236. * Read byte string (8-bit string length)
  5237. * OpenOffice documentation: 2.5.2
  5238. *
  5239. * @param string $subData
  5240. * @return array
  5241. */
  5242. private function _readByteStringShort($subData)
  5243. {
  5244. // offset: 0; size: 1; length of the string (character count)
  5245. $ln = ord($subData[0]);
  5246. // offset: 1: size: var; character array (8-bit characters)
  5247. $value = $this->_decodeCodepage(substr($subData, 1, $ln));
  5248. return array(
  5249. 'value' => $value,
  5250. 'size' => 1 + $ln, // size in bytes of data structure
  5251. );
  5252. }
  5253. /**
  5254. * Read byte string (16-bit string length)
  5255. * OpenOffice documentation: 2.5.2
  5256. *
  5257. * @param string $subData
  5258. * @return array
  5259. */
  5260. private function _readByteStringLong($subData)
  5261. {
  5262. // offset: 0; size: 2; length of the string (character count)
  5263. $ln = self::_GetInt2d($subData, 0);
  5264. // offset: 2: size: var; character array (8-bit characters)
  5265. $value = $this->_decodeCodepage(substr($subData, 2));
  5266. //return $string;
  5267. return array(
  5268. 'value' => $value,
  5269. 'size' => 2 + $ln, // size in bytes of data structure
  5270. );
  5271. }
  5272. /**
  5273. * Extracts an Excel Unicode short string (8-bit string length)
  5274. * OpenOffice documentation: 2.5.3
  5275. * function will automatically find out where the Unicode string ends.
  5276. *
  5277. * @param string $subData
  5278. * @return array
  5279. */
  5280. private static function _readUnicodeStringShort($subData)
  5281. {
  5282. $value = '';
  5283. // offset: 0: size: 1; length of the string (character count)
  5284. $characterCount = ord($subData[0]);
  5285. $string = self::_readUnicodeString(substr($subData, 1), $characterCount);
  5286. // add 1 for the string length
  5287. $string['size'] += 1;
  5288. return $string;
  5289. }
  5290. /**
  5291. * Extracts an Excel Unicode long string (16-bit string length)
  5292. * OpenOffice documentation: 2.5.3
  5293. * this function is under construction, needs to support rich text, and Asian phonetic settings
  5294. *
  5295. * @param string $subData
  5296. * @return array
  5297. */
  5298. private static function _readUnicodeStringLong($subData)
  5299. {
  5300. $value = '';
  5301. // offset: 0: size: 2; length of the string (character count)
  5302. $characterCount = self::_GetInt2d($subData, 0);
  5303. $string = self::_readUnicodeString(substr($subData, 2), $characterCount);
  5304. // add 2 for the string length
  5305. $string['size'] += 2;
  5306. return $string;
  5307. }
  5308. /**
  5309. * Read Unicode string with no string length field, but with known character count
  5310. * this function is under construction, needs to support rich text, and Asian phonetic settings
  5311. * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.3
  5312. *
  5313. * @param string $subData
  5314. * @param int $characterCount
  5315. * @return array
  5316. */
  5317. private static function _readUnicodeString($subData, $characterCount)
  5318. {
  5319. $value = '';
  5320. // offset: 0: size: 1; option flags
  5321. // bit: 0; mask: 0x01; character compression (0 = compressed 8-bit, 1 = uncompressed 16-bit)
  5322. $isCompressed = !((0x01 & ord($subData[0])) >> 0);
  5323. // bit: 2; mask: 0x04; Asian phonetic settings
  5324. $hasAsian = (0x04) & ord($subData[0]) >> 2;
  5325. // bit: 3; mask: 0x08; Rich-Text settings
  5326. $hasRichText = (0x08) & ord($subData[0]) >> 3;
  5327. // offset: 1: size: var; character array
  5328. // this offset assumes richtext and Asian phonetic settings are off which is generally wrong
  5329. // needs to be fixed
  5330. $value = self::_encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed);
  5331. return array(
  5332. 'value' => $value,
  5333. 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags
  5334. );
  5335. }
  5336. /**
  5337. * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas.
  5338. * Example: hello"world --> "hello""world"
  5339. *
  5340. * @param string $value UTF-8 encoded string
  5341. * @return string
  5342. */
  5343. private static function _UTF8toExcelDoubleQuoted($value)
  5344. {
  5345. return '"' . str_replace('"', '""', $value) . '"';
  5346. }
  5347. /**
  5348. * Reads first 8 bytes of a string and return IEEE 754 float
  5349. *
  5350. * @param string $data Binary string that is at least 8 bytes long
  5351. * @return float
  5352. */
  5353. private static function _extractNumber($data)
  5354. {
  5355. $rknumhigh = self::_GetInt4d($data, 4);
  5356. $rknumlow = self::_GetInt4d($data, 0);
  5357. $sign = ($rknumhigh & 0x80000000) >> 31;
  5358. $exp = (($rknumhigh & 0x7ff00000) >> 20) - 1023;
  5359. $mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
  5360. $mantissalow1 = ($rknumlow & 0x80000000) >> 31;
  5361. $mantissalow2 = ($rknumlow & 0x7fffffff);
  5362. $value = $mantissa / pow( 2 , (20 - $exp));
  5363. if ($mantissalow1 != 0) {
  5364. $value += 1 / pow (2 , (21 - $exp));
  5365. }
  5366. $value += $mantissalow2 / pow (2 , (52 - $exp));
  5367. if ($sign) {
  5368. $value *= -1;
  5369. }
  5370. return $value;
  5371. }
  5372. private static function _GetIEEE754($rknum)
  5373. {
  5374. if (($rknum & 0x02) != 0) {
  5375. $value = $rknum >> 2;
  5376. } else {
  5377. // changes by mmp, info on IEEE754 encoding from
  5378. // research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
  5379. // The RK format calls for using only the most significant 30 bits
  5380. // of the 64 bit floating point value. The other 34 bits are assumed
  5381. // to be 0 so we use the upper 30 bits of $rknum as follows...
  5382. $sign = ($rknum & 0x80000000) >> 31;
  5383. $exp = ($rknum & 0x7ff00000) >> 20;
  5384. $mantissa = (0x100000 | ($rknum & 0x000ffffc));
  5385. $value = $mantissa / pow( 2 , (20- ($exp - 1023)));
  5386. if ($sign) {
  5387. $value = -1 * $value;
  5388. }
  5389. //end of changes by mmp
  5390. }
  5391. if (($rknum & 0x01) != 0) {
  5392. $value /= 100;
  5393. }
  5394. return $value;
  5395. }
  5396. /**
  5397. * Get UTF-8 string from (compressed or uncompressed) UTF-16 string
  5398. *
  5399. * @param string $string
  5400. * @param bool $compressed
  5401. * @return string
  5402. */
  5403. private static function _encodeUTF16($string, $compressed = '')
  5404. {
  5405. if ($compressed) {
  5406. $string = self::_uncompressByteString($string);
  5407. }
  5408. return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', 'UTF-16LE');
  5409. }
  5410. /**
  5411. * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8.
  5412. *
  5413. * @param string $string
  5414. * @return string
  5415. */
  5416. private static function _uncompressByteString($string)
  5417. {
  5418. $uncompressedString = '';
  5419. $strLen = strlen($string);
  5420. for ($i = 0; $i < $strLen; ++$i) {
  5421. $uncompressedString .= $string[$i] . "\0";
  5422. }
  5423. return $uncompressedString;
  5424. }
  5425. /**
  5426. * Convert string to UTF-8. Only used for BIFF5.
  5427. *
  5428. * @param string $string
  5429. * @return string
  5430. */
  5431. private function _decodeCodepage($string)
  5432. {
  5433. return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', $this->_codepage);
  5434. }
  5435. /**
  5436. * Read 16-bit unsigned integer
  5437. *
  5438. * @param string $data
  5439. * @param int $pos
  5440. * @return int
  5441. */
  5442. public static function _GetInt2d($data, $pos)
  5443. {
  5444. return ord($data[$pos]) | (ord($data[$pos+1]) << 8);
  5445. }
  5446. /**
  5447. * Read 32-bit signed integer
  5448. *
  5449. * @param string $data
  5450. * @param int $pos
  5451. * @return int
  5452. */
  5453. public static function _GetInt4d($data, $pos)
  5454. {
  5455. // FIX: represent numbers correctly on 64-bit system
  5456. // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
  5457. // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
  5458. $_or_24 = ord($data[$pos + 3]);
  5459. if ($_or_24 >= 128) {
  5460. // negative number
  5461. $_ord_24 = -abs((256 - $_or_24) << 24);
  5462. } else {
  5463. $_ord_24 = ($_or_24 & 127) << 24;
  5464. }
  5465. return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | $_ord_24;
  5466. }
  5467. /**
  5468. * Read color
  5469. *
  5470. * @param int $color Indexed color
  5471. * @param array $palette Color palette
  5472. * @return array RGB color value, example: array('rgb' => 'FF0000')
  5473. */
  5474. private static function _readColor($color,$palette,$version)
  5475. {
  5476. if ($color <= 0x07 || $color >= 0x40) {
  5477. // special built-in color
  5478. return self::_mapBuiltInColor($color);
  5479. } elseif (isset($palette) && isset($palette[$color - 8])) {
  5480. // palette color, color index 0x08 maps to pallete index 0
  5481. return $palette[$color - 8];
  5482. } else {
  5483. // default color table
  5484. if ($version == self::XLS_BIFF8) {
  5485. return self::_mapColor($color);
  5486. } else {
  5487. // BIFF5
  5488. return self::_mapColorBIFF5($color);
  5489. }
  5490. }
  5491. return $color;
  5492. }
  5493. /**
  5494. * Map border style
  5495. * OpenOffice documentation: 2.5.11
  5496. *
  5497. * @param int $index
  5498. * @return string
  5499. */
  5500. private static function _mapBorderStyle($index)
  5501. {
  5502. switch ($index) {
  5503. case 0x00: return PHPExcel_Style_Border::BORDER_NONE;
  5504. case 0x01: return PHPExcel_Style_Border::BORDER_THIN;
  5505. case 0x02: return PHPExcel_Style_Border::BORDER_MEDIUM;
  5506. case 0x03: return PHPExcel_Style_Border::BORDER_DASHED;
  5507. case 0x04: return PHPExcel_Style_Border::BORDER_DOTTED;
  5508. case 0x05: return PHPExcel_Style_Border::BORDER_THICK;
  5509. case 0x06: return PHPExcel_Style_Border::BORDER_DOUBLE;
  5510. case 0x07: return PHPExcel_Style_Border::BORDER_HAIR;
  5511. case 0x08: return PHPExcel_Style_Border::BORDER_MEDIUMDASHED;
  5512. case 0x09: return PHPExcel_Style_Border::BORDER_DASHDOT;
  5513. case 0x0A: return PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT;
  5514. case 0x0B: return PHPExcel_Style_Border::BORDER_DASHDOTDOT;
  5515. case 0x0C: return PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT;
  5516. case 0x0D: return PHPExcel_Style_Border::BORDER_SLANTDASHDOT;
  5517. default: return PHPExcel_Style_Border::BORDER_NONE;
  5518. }
  5519. }
  5520. /**
  5521. * Get fill pattern from index
  5522. * OpenOffice documentation: 2.5.12
  5523. *
  5524. * @param int $index
  5525. * @return string
  5526. */
  5527. private static function _mapFillPattern($index)
  5528. {
  5529. switch ($index) {
  5530. case 0x00: return PHPExcel_Style_Fill::FILL_NONE;
  5531. case 0x01: return PHPExcel_Style_Fill::FILL_SOLID;
  5532. case 0x02: return PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY;
  5533. case 0x03: return PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY;
  5534. case 0x04: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY;
  5535. case 0x05: return PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL;
  5536. case 0x06: return PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL;
  5537. case 0x07: return PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN;
  5538. case 0x08: return PHPExcel_Style_Fill::FILL_PATTERN_DARKUP;
  5539. case 0x09: return PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID;
  5540. case 0x0A: return PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS;
  5541. case 0x0B: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL;
  5542. case 0x0C: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL;
  5543. case 0x0D: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN;
  5544. case 0x0E: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP;
  5545. case 0x0F: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID;
  5546. case 0x10: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS;
  5547. case 0x11: return PHPExcel_Style_Fill::FILL_PATTERN_GRAY125;
  5548. case 0x12: return PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625;
  5549. default: return PHPExcel_Style_Fill::FILL_NONE;
  5550. }
  5551. }
  5552. /**
  5553. * Map error code, e.g. '#N/A'
  5554. *
  5555. * @param int $subData
  5556. * @return string
  5557. */
  5558. private static function _mapErrorCode($subData)
  5559. {
  5560. switch ($subData) {
  5561. case 0x00: return '#NULL!'; break;
  5562. case 0x07: return '#DIV/0!'; break;
  5563. case 0x0F: return '#VALUE!'; break;
  5564. case 0x17: return '#REF!'; break;
  5565. case 0x1D: return '#NAME?'; break;
  5566. case 0x24: return '#NUM!'; break;
  5567. case 0x2A: return '#N/A'; break;
  5568. default: return false;
  5569. }
  5570. }
  5571. /**
  5572. * Map built-in color to RGB value
  5573. *
  5574. * @param int $color Indexed color
  5575. * @return array
  5576. */
  5577. private static function _mapBuiltInColor($color)
  5578. {
  5579. switch ($color) {
  5580. case 0x00: return array('rgb' => '000000');
  5581. case 0x01: return array('rgb' => 'FFFFFF');
  5582. case 0x02: return array('rgb' => 'FF0000');
  5583. case 0x03: return array('rgb' => '00FF00');
  5584. case 0x04: return array('rgb' => '0000FF');
  5585. case 0x05: return array('rgb' => 'FFFF00');
  5586. case 0x06: return array('rgb' => 'FF00FF');
  5587. case 0x07: return array('rgb' => '00FFFF');
  5588. case 0x40: return array('rgb' => '000000'); // system window text color
  5589. case 0x41: return array('rgb' => 'FFFFFF'); // system window background color
  5590. default: return array('rgb' => '000000');
  5591. }
  5592. }
  5593. /**
  5594. * Map color array from BIFF5 built-in color index
  5595. *
  5596. * @param int $subData
  5597. * @return array
  5598. */
  5599. private static function _mapColorBIFF5($subData)
  5600. {
  5601. switch ($subData) {
  5602. case 0x08: return array('rgb' => '000000');
  5603. case 0x09: return array('rgb' => 'FFFFFF');
  5604. case 0x0A: return array('rgb' => 'FF0000');
  5605. case 0x0B: return array('rgb' => '00FF00');
  5606. case 0x0C: return array('rgb' => '0000FF');
  5607. case 0x0D: return array('rgb' => 'FFFF00');
  5608. case 0x0E: return array('rgb' => 'FF00FF');
  5609. case 0x0F: return array('rgb' => '00FFFF');
  5610. case 0x10: return array('rgb' => '800000');
  5611. case 0x11: return array('rgb' => '008000');
  5612. case 0x12: return array('rgb' => '000080');
  5613. case 0x13: return array('rgb' => '808000');
  5614. case 0x14: return array('rgb' => '800080');
  5615. case 0x15: return array('rgb' => '008080');
  5616. case 0x16: return array('rgb' => 'C0C0C0');
  5617. case 0x17: return array('rgb' => '808080');
  5618. case 0x18: return array('rgb' => '8080FF');
  5619. case 0x19: return array('rgb' => '802060');
  5620. case 0x1A: return array('rgb' => 'FFFFC0');
  5621. case 0x1B: return array('rgb' => 'A0E0F0');
  5622. case 0x1C: return array('rgb' => '600080');
  5623. case 0x1D: return array('rgb' => 'FF8080');
  5624. case 0x1E: return array('rgb' => '0080C0');
  5625. case 0x1F: return array('rgb' => 'C0C0FF');
  5626. case 0x20: return array('rgb' => '000080');
  5627. case 0x21: return array('rgb' => 'FF00FF');
  5628. case 0x22: return array('rgb' => 'FFFF00');
  5629. case 0x23: return array('rgb' => '00FFFF');
  5630. case 0x24: return array('rgb' => '800080');
  5631. case 0x25: return array('rgb' => '800000');
  5632. case 0x26: return array('rgb' => '008080');
  5633. case 0x27: return array('rgb' => '0000FF');
  5634. case 0x28: return array('rgb' => '00CFFF');
  5635. case 0x29: return array('rgb' => '69FFFF');
  5636. case 0x2A: return array('rgb' => 'E0FFE0');
  5637. case 0x2B: return array('rgb' => 'FFFF80');
  5638. case 0x2C: return array('rgb' => 'A6CAF0');
  5639. case 0x2D: return array('rgb' => 'DD9CB3');
  5640. case 0x2E: return array('rgb' => 'B38FEE');
  5641. case 0x2F: return array('rgb' => 'E3E3E3');
  5642. case 0x30: return array('rgb' => '2A6FF9');
  5643. case 0x31: return array('rgb' => '3FB8CD');
  5644. case 0x32: return array('rgb' => '488436');
  5645. case 0x33: return array('rgb' => '958C41');
  5646. case 0x34: return array('rgb' => '8E5E42');
  5647. case 0x35: return array('rgb' => 'A0627A');
  5648. case 0x36: return array('rgb' => '624FAC');
  5649. case 0x37: return array('rgb' => '969696');
  5650. case 0x38: return array('rgb' => '1D2FBE');
  5651. case 0x39: return array('rgb' => '286676');
  5652. case 0x3A: return array('rgb' => '004500');
  5653. case 0x3B: return array('rgb' => '453E01');
  5654. case 0x3C: return array('rgb' => '6A2813');
  5655. case 0x3D: return array('rgb' => '85396A');
  5656. case 0x3E: return array('rgb' => '4A3285');
  5657. case 0x3F: return array('rgb' => '424242');
  5658. default: return array('rgb' => '000000');
  5659. }
  5660. }
  5661. /**
  5662. * Map color array from BIFF8 built-in color index
  5663. *
  5664. * @param int $subData
  5665. * @return array
  5666. */
  5667. private static function _mapColor($subData)
  5668. {
  5669. switch ($subData) {
  5670. case 0x08: return array('rgb' => '000000');
  5671. case 0x09: return array('rgb' => 'FFFFFF');
  5672. case 0x0A: return array('rgb' => 'FF0000');
  5673. case 0x0B: return array('rgb' => '00FF00');
  5674. case 0x0C: return array('rgb' => '0000FF');
  5675. case 0x0D: return array('rgb' => 'FFFF00');
  5676. case 0x0E: return array('rgb' => 'FF00FF');
  5677. case 0x0F: return array('rgb' => '00FFFF');
  5678. case 0x10: return array('rgb' => '800000');
  5679. case 0x11: return array('rgb' => '008000');
  5680. case 0x12: return array('rgb' => '000080');
  5681. case 0x13: return array('rgb' => '808000');
  5682. case 0x14: return array('rgb' => '800080');
  5683. case 0x15: return array('rgb' => '008080');
  5684. case 0x16: return array('rgb' => 'C0C0C0');
  5685. case 0x17: return array('rgb' => '808080');
  5686. case 0x18: return array('rgb' => '9999FF');
  5687. case 0x19: return array('rgb' => '993366');
  5688. case 0x1A: return array('rgb' => 'FFFFCC');
  5689. case 0x1B: return array('rgb' => 'CCFFFF');
  5690. case 0x1C: return array('rgb' => '660066');
  5691. case 0x1D: return array('rgb' => 'FF8080');
  5692. case 0x1E: return array('rgb' => '0066CC');
  5693. case 0x1F: return array('rgb' => 'CCCCFF');
  5694. case 0x20: return array('rgb' => '000080');
  5695. case 0x21: return array('rgb' => 'FF00FF');
  5696. case 0x22: return array('rgb' => 'FFFF00');
  5697. case 0x23: return array('rgb' => '00FFFF');
  5698. case 0x24: return array('rgb' => '800080');
  5699. case 0x25: return array('rgb' => '800000');
  5700. case 0x26: return array('rgb' => '008080');
  5701. case 0x27: return array('rgb' => '0000FF');
  5702. case 0x28: return array('rgb' => '00CCFF');
  5703. case 0x29: return array('rgb' => 'CCFFFF');
  5704. case 0x2A: return array('rgb' => 'CCFFCC');
  5705. case 0x2B: return array('rgb' => 'FFFF99');
  5706. case 0x2C: return array('rgb' => '99CCFF');
  5707. case 0x2D: return array('rgb' => 'FF99CC');
  5708. case 0x2E: return array('rgb' => 'CC99FF');
  5709. case 0x2F: return array('rgb' => 'FFCC99');
  5710. case 0x30: return array('rgb' => '3366FF');
  5711. case 0x31: return array('rgb' => '33CCCC');
  5712. case 0x32: return array('rgb' => '99CC00');
  5713. case 0x33: return array('rgb' => 'FFCC00');
  5714. case 0x34: return array('rgb' => 'FF9900');
  5715. case 0x35: return array('rgb' => 'FF6600');
  5716. case 0x36: return array('rgb' => '666699');
  5717. case 0x37: return array('rgb' => '969696');
  5718. case 0x38: return array('rgb' => '003366');
  5719. case 0x39: return array('rgb' => '339966');
  5720. case 0x3A: return array('rgb' => '003300');
  5721. case 0x3B: return array('rgb' => '333300');
  5722. case 0x3C: return array('rgb' => '993300');
  5723. case 0x3D: return array('rgb' => '993366');
  5724. case 0x3E: return array('rgb' => '333399');
  5725. case 0x3F: return array('rgb' => '333333');
  5726. default: return array('rgb' => '000000');
  5727. }
  5728. }
  5729. private function _parseRichText($is = '') {
  5730. $value = new PHPExcel_RichText();
  5731. $value->createText($is);
  5732. return $value;
  5733. }
  5734. }