PageRenderTime 117ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 1ms

/pma/libraries/PHPExcel/PHPExcel/Reader/Excel5.php

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