PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/PHPExcel_1.7.8-with_documentation-msoffice_format/PHPExcel_1.7.8-with_documentation-msoffice_format/Classes/PHPExcel/Reader/Excel2007.php

https://bitbucket.org/izubizarreta/https-bitbucket.org-bityvip
PHP | 2112 lines | 1527 code | 267 blank | 318 comment | 533 complexity | 8d632fdcaab17321dd4135d13772901d MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.0, JSON, GPL-2.0, BSD-3-Clause, LGPL-2.1, MIT

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

  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2012 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Reader
  23. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.7.8, 2012-10-12
  26. */
  27. /** PHPExcel root directory */
  28. if (!defined('PHPEXCEL_ROOT')) {
  29. /**
  30. * @ignore
  31. */
  32. define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
  33. require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
  34. }
  35. /**
  36. * PHPExcel_Reader_Excel2007
  37. *
  38. * @category PHPExcel
  39. * @package PHPExcel_Reader
  40. * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
  41. */
  42. class PHPExcel_Reader_Excel2007 implements PHPExcel_Reader_IReader
  43. {
  44. /**
  45. * Read data only?
  46. * Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
  47. * or whether it should read both data and formatting
  48. *
  49. * @var boolean
  50. */
  51. private $_readDataOnly = FALSE;
  52. /**
  53. * Read charts that are defined in the workbook?
  54. * Identifies whether the Reader should read the definitions for any charts that exist in the workbook;
  55. *
  56. * @var boolean
  57. */
  58. private $_includeCharts = FALSE;
  59. /**
  60. * Restrict which sheets should be loaded?
  61. * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
  62. *
  63. * @var array of string
  64. */
  65. private $_loadSheetsOnly = NULL;
  66. /**
  67. * PHPExcel_Reader_IReadFilter instance
  68. *
  69. * @var PHPExcel_Reader_IReadFilter
  70. */
  71. private $_readFilter = NULL;
  72. /**
  73. * PHPExcel_ReferenceHelper instance
  74. *
  75. * @var PHPExcel_ReferenceHelper
  76. */
  77. private $_referenceHelper = NULL;
  78. /**
  79. * PHPExcel_Reader_Excel2007_Theme instance
  80. *
  81. * @var PHPExcel_Reader_Excel2007_Theme
  82. */
  83. private static $_theme = NULL;
  84. /**
  85. * Create a new PHPExcel_Reader_Excel2007 instance
  86. */
  87. public function __construct() {
  88. $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter();
  89. $this->_referenceHelper = PHPExcel_ReferenceHelper::getInstance();
  90. }
  91. /**
  92. * Read data only?
  93. * If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
  94. * If false (the default) it will read data and formatting.
  95. *
  96. * @return boolean
  97. */
  98. public function getReadDataOnly() {
  99. return $this->_readDataOnly;
  100. }
  101. /**
  102. * Set read data only
  103. * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
  104. * Set to false (the default) to advise the Reader to read both data and formatting for cells.
  105. *
  106. * @param boolean $pValue
  107. *
  108. * @return PHPExcel_Reader_Excel2007
  109. */
  110. public function setReadDataOnly($pValue = FALSE) {
  111. $this->_readDataOnly = $pValue;
  112. return $this;
  113. }
  114. /**
  115. * Read charts in workbook?
  116. * If this is true, then the Reader will include any charts that exist in the workbook.
  117. * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
  118. * If false (the default) it will ignore any charts defined in the workbook file.
  119. *
  120. * @return boolean
  121. */
  122. public function getIncludeCharts() {
  123. return $this->_includeCharts;
  124. }
  125. /**
  126. * Set read charts in workbook
  127. * Set to true, to advise the Reader to include any charts that exist in the workbook.
  128. * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
  129. * Set to false (the default) to discard charts.
  130. *
  131. * @param boolean $pValue
  132. *
  133. * @return PHPExcel_Reader_Excel2007
  134. */
  135. public function setIncludeCharts($pValue = FALSE) {
  136. $this->_includeCharts = (boolean) $pValue;
  137. return $this;
  138. }
  139. /**
  140. * Get which sheets to load
  141. * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
  142. * indicating that all worksheets in the workbook should be loaded.
  143. *
  144. * @return mixed
  145. */
  146. public function getLoadSheetsOnly()
  147. {
  148. return $this->_loadSheetsOnly;
  149. }
  150. /**
  151. * Set which sheets to load
  152. *
  153. * @param mixed $value
  154. * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
  155. * If NULL, then it tells the Reader to read all worksheets in the workbook
  156. *
  157. * @return PHPExcel_Reader_Excel2007
  158. */
  159. public function setLoadSheetsOnly($value = NULL)
  160. {
  161. $this->_loadSheetsOnly = is_array($value) ?
  162. $value : array($value);
  163. return $this;
  164. }
  165. /**
  166. * Set all sheets to load
  167. * Tells the Reader to load all worksheets from the workbook.
  168. *
  169. * @return PHPExcel_Reader_Excel2007
  170. */
  171. public function setLoadAllSheets()
  172. {
  173. $this->_loadSheetsOnly = NULL;
  174. return $this;
  175. }
  176. /**
  177. * Read filter
  178. *
  179. * @return PHPExcel_Reader_IReadFilter
  180. */
  181. public function getReadFilter() {
  182. return $this->_readFilter;
  183. }
  184. /**
  185. * Set read filter
  186. *
  187. * @param PHPExcel_Reader_IReadFilter $pValue
  188. * @return PHPExcel_Reader_Excel2007
  189. */
  190. public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
  191. $this->_readFilter = $pValue;
  192. return $this;
  193. }
  194. /**
  195. * Can the current PHPExcel_Reader_IReader read the file?
  196. *
  197. * @param string $pFileName
  198. * @return boolean
  199. * @throws Exception
  200. */
  201. public function canRead($pFilename)
  202. {
  203. // Check if file exists
  204. if (!file_exists($pFilename)) {
  205. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  206. }
  207. // Check if zip class exists
  208. if (!class_exists('ZipArchive',FALSE)) {
  209. throw new Exception("ZipArchive library is not enabled");
  210. }
  211. $xl = false;
  212. // Load file
  213. $zip = new ZipArchive;
  214. if ($zip->open($pFilename) === true) {
  215. // check if it is an OOXML archive
  216. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels"));
  217. if ($rels !== false) {
  218. foreach ($rels->Relationship as $rel) {
  219. switch ($rel["Type"]) {
  220. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  221. if (basename($rel["Target"]) == 'workbook.xml') {
  222. $xl = true;
  223. }
  224. break;
  225. }
  226. }
  227. }
  228. $zip->close();
  229. }
  230. return $xl;
  231. }
  232. /**
  233. * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
  234. *
  235. * @param string $pFilename
  236. * @throws Exception
  237. */
  238. public function listWorksheetInfo($pFilename)
  239. {
  240. // Check if file exists
  241. if (!file_exists($pFilename)) {
  242. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  243. }
  244. $worksheetInfo = array();
  245. $zip = new ZipArchive;
  246. $zip->open($pFilename);
  247. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  248. foreach ($rels->Relationship as $rel) {
  249. if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") {
  250. $dir = dirname($rel["Target"]);
  251. $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  252. $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
  253. $worksheets = array();
  254. foreach ($relsWorkbook->Relationship as $ele) {
  255. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") {
  256. $worksheets[(string) $ele["Id"]] = $ele["Target"];
  257. }
  258. }
  259. $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  260. if ($xmlWorkbook->sheets) {
  261. $dir = dirname($rel["Target"]);
  262. foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
  263. $tmpInfo = array();
  264. $tmpInfo['worksheetName'] = (string) $eleSheet["name"];
  265. $tmpInfo['lastColumnLetter'] = 'A';
  266. $tmpInfo['lastColumnIndex'] = 0;
  267. $tmpInfo['totalRows'] = 0;
  268. $tmpInfo['totalColumns'] = 0;
  269. $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  270. $xmlSheet = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$fileWorksheet")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  271. if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
  272. foreach ($xmlSheet->sheetData->row as $row) {
  273. foreach ($row->c as $c) {
  274. $r = (string) $c["r"];
  275. $coordinates = PHPExcel_Cell::coordinateFromString($r);
  276. $rowIndex = $coordinates[1];
  277. $columnIndex = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1;
  278. $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
  279. $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
  280. }
  281. }
  282. }
  283. $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
  284. $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;
  285. $worksheetInfo[] = $tmpInfo;
  286. }
  287. }
  288. }
  289. }
  290. $zip->close();
  291. return $worksheetInfo;
  292. }
  293. private static function _castToBool($c) {
  294. // echo 'Initial Cast to Boolean<br />';
  295. $value = isset($c->v) ? (string) $c->v : NULL;
  296. if ($value == '0') {
  297. return FALSE;
  298. } elseif ($value == '1') {
  299. return TRUE;
  300. } else {
  301. return (bool)$c->v;
  302. }
  303. return $value;
  304. } // function _castToBool()
  305. private static function _castToError($c) {
  306. // echo 'Initial Cast to Error<br />';
  307. return isset($c->v) ? (string) $c->v : NULL;
  308. } // function _castToError()
  309. private static function _castToString($c) {
  310. // echo 'Initial Cast to String<br />';
  311. return isset($c->v) ? (string) $c->v : NULL;
  312. } // function _castToString()
  313. private function _castToFormula($c,$r,&$cellDataType,&$value,&$calculatedValue,&$sharedFormulas,$castBaseType) {
  314. // echo 'Formula<br />';
  315. // echo '$c->f is '.$c->f.'<br />';
  316. $cellDataType = 'f';
  317. $value = "={$c->f}";
  318. $calculatedValue = self::$castBaseType($c);
  319. // Shared formula?
  320. if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') {
  321. // echo 'SHARED FORMULA<br />';
  322. $instance = (string)$c->f['si'];
  323. // echo 'Instance ID = '.$instance.'<br />';
  324. //
  325. // echo 'Shared Formula Array:<pre>';
  326. // print_r($sharedFormulas);
  327. // echo '</pre>';
  328. if (!isset($sharedFormulas[(string)$c->f['si']])) {
  329. // echo 'SETTING NEW SHARED FORMULA<br />';
  330. // echo 'Master is '.$r.'<br />';
  331. // echo 'Formula is '.$value.'<br />';
  332. $sharedFormulas[$instance] = array( 'master' => $r,
  333. 'formula' => $value
  334. );
  335. // echo 'New Shared Formula Array:<pre>';
  336. // print_r($sharedFormulas);
  337. // echo '</pre>';
  338. } else {
  339. // echo 'GETTING SHARED FORMULA<br />';
  340. // echo 'Master is '.$sharedFormulas[$instance]['master'].'<br />';
  341. // echo 'Formula is '.$sharedFormulas[$instance]['formula'].'<br />';
  342. $master = PHPExcel_Cell::coordinateFromString($sharedFormulas[$instance]['master']);
  343. $current = PHPExcel_Cell::coordinateFromString($r);
  344. $difference = array(0, 0);
  345. $difference[0] = PHPExcel_Cell::columnIndexFromString($current[0]) - PHPExcel_Cell::columnIndexFromString($master[0]);
  346. $difference[1] = $current[1] - $master[1];
  347. $value = $this->_referenceHelper->updateFormulaReferences( $sharedFormulas[$instance]['formula'],
  348. 'A1',
  349. $difference[0],
  350. $difference[1]
  351. );
  352. // echo 'Adjusted Formula is '.$value.'<br />';
  353. }
  354. }
  355. }
  356. public function _getFromZipArchive(ZipArchive $archive, $fileName = '')
  357. {
  358. // Root-relative paths
  359. if (strpos($fileName, '//') !== false)
  360. {
  361. $fileName = substr($fileName, strpos($fileName, '//') + 1);
  362. }
  363. $fileName = PHPExcel_Shared_File::realpath($fileName);
  364. // Apache POI fixes
  365. $contents = $archive->getFromName($fileName);
  366. if ($contents === false)
  367. {
  368. $contents = $archive->getFromName(substr($fileName, 1));
  369. }
  370. return $contents;
  371. }
  372. /**
  373. * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
  374. *
  375. * @param string $pFilename
  376. * @throws Exception
  377. */
  378. public function listWorksheetNames($pFilename)
  379. {
  380. // Check if file exists
  381. if (!file_exists($pFilename)) {
  382. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  383. }
  384. $worksheetNames = array();
  385. $zip = new ZipArchive;
  386. $zip->open($pFilename);
  387. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  388. foreach ($rels->Relationship as $rel) {
  389. switch ($rel["Type"]) {
  390. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  391. $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  392. if ($xmlWorkbook->sheets) {
  393. foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
  394. // Check if sheet should be skipped
  395. $worksheetNames[] = (string) $eleSheet["name"];
  396. }
  397. }
  398. }
  399. }
  400. $zip->close();
  401. return $worksheetNames;
  402. }
  403. /**
  404. * Loads PHPExcel from file
  405. *
  406. * @param string $pFilename
  407. * @throws Exception
  408. */
  409. public function load($pFilename)
  410. {
  411. // Check if file exists
  412. if (!file_exists($pFilename)) {
  413. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  414. }
  415. // Initialisations
  416. $excel = new PHPExcel;
  417. $excel->removeSheetByIndex(0);
  418. if (!$this->_readDataOnly) {
  419. $excel->removeCellStyleXfByIndex(0); // remove the default style
  420. $excel->removeCellXfByIndex(0); // remove the default style
  421. }
  422. $zip = new ZipArchive;
  423. $zip->open($pFilename);
  424. // Read the theme first, because we need the colour scheme when reading the styles
  425. $wbRels = simplexml_load_string($this->_getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  426. foreach ($wbRels->Relationship as $rel) {
  427. switch ($rel["Type"]) {
  428. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme":
  429. $themeOrderArray = array('lt1','dk1','lt2','dk2');
  430. $themeOrderAdditional = count($themeOrderArray);
  431. $xmlTheme = simplexml_load_string($this->_getFromZipArchive($zip, "xl/{$rel['Target']}"));
  432. if (is_object($xmlTheme)) {
  433. $xmlThemeName = $xmlTheme->attributes();
  434. $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main");
  435. $themeName = (string)$xmlThemeName['name'];
  436. $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
  437. $colourSchemeName = (string)$colourScheme['name'];
  438. $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main");
  439. $themeColours = array();
  440. foreach ($colourScheme as $k => $xmlColour) {
  441. $themePos = array_search($k,$themeOrderArray);
  442. if ($themePos === false) {
  443. $themePos = $themeOrderAdditional++;
  444. }
  445. if (isset($xmlColour->sysClr)) {
  446. $xmlColourData = $xmlColour->sysClr->attributes();
  447. $themeColours[$themePos] = $xmlColourData['lastClr'];
  448. } elseif (isset($xmlColour->srgbClr)) {
  449. $xmlColourData = $xmlColour->srgbClr->attributes();
  450. $themeColours[$themePos] = $xmlColourData['val'];
  451. }
  452. }
  453. self::$_theme = new PHPExcel_Reader_Excel2007_Theme($themeName,$colourSchemeName,$themeColours);
  454. }
  455. break;
  456. }
  457. }
  458. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  459. foreach ($rels->Relationship as $rel) {
  460. switch ($rel["Type"]) {
  461. case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties":
  462. $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));
  463. if (is_object($xmlCore)) {
  464. $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/");
  465. $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/");
  466. $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties");
  467. $docProps = $excel->getProperties();
  468. $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator")));
  469. $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy")));
  470. $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); //! respect xsi:type
  471. $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type
  472. $docProps->setTitle((string) self::array_item($xmlCore->xpath("dc:title")));
  473. $docProps->setDescription((string) self::array_item($xmlCore->xpath("dc:description")));
  474. $docProps->setSubject((string) self::array_item($xmlCore->xpath("dc:subject")));
  475. $docProps->setKeywords((string) self::array_item($xmlCore->xpath("cp:keywords")));
  476. $docProps->setCategory((string) self::array_item($xmlCore->xpath("cp:category")));
  477. }
  478. break;
  479. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties":
  480. $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));
  481. if (is_object($xmlCore)) {
  482. $docProps = $excel->getProperties();
  483. if (isset($xmlCore->Company))
  484. $docProps->setCompany((string) $xmlCore->Company);
  485. if (isset($xmlCore->Manager))
  486. $docProps->setManager((string) $xmlCore->Manager);
  487. }
  488. break;
  489. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties":
  490. $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));
  491. if (is_object($xmlCore)) {
  492. $docProps = $excel->getProperties();
  493. foreach ($xmlCore as $xmlProperty) {
  494. $cellDataOfficeAttributes = $xmlProperty->attributes();
  495. if (isset($cellDataOfficeAttributes['name'])) {
  496. $propertyName = (string) $cellDataOfficeAttributes['name'];
  497. $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
  498. $attributeType = $cellDataOfficeChildren->getName();
  499. $attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
  500. $attributeValue = PHPExcel_DocumentProperties::convertProperty($attributeValue,$attributeType);
  501. $attributeType = PHPExcel_DocumentProperties::convertPropertyType($attributeType);
  502. $docProps->setCustomProperty($propertyName,$attributeValue,$attributeType);
  503. }
  504. }
  505. }
  506. break;
  507. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  508. $dir = dirname($rel["Target"]);
  509. $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  510. $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
  511. $sharedStrings = array();
  512. $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
  513. $xmlStrings = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  514. if (isset($xmlStrings) && isset($xmlStrings->si)) {
  515. foreach ($xmlStrings->si as $val) {
  516. if (isset($val->t)) {
  517. $sharedStrings[] = PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $val->t );
  518. } elseif (isset($val->r)) {
  519. $sharedStrings[] = $this->_parseRichText($val);
  520. }
  521. }
  522. }
  523. $worksheets = array();
  524. foreach ($relsWorkbook->Relationship as $ele) {
  525. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") {
  526. $worksheets[(string) $ele["Id"]] = $ele["Target"];
  527. }
  528. }
  529. $styles = array();
  530. $cellStyles = array();
  531. $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
  532. $xmlStyles = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  533. $numFmts = null;
  534. if ($xmlStyles && $xmlStyles->numFmts[0]) {
  535. $numFmts = $xmlStyles->numFmts[0];
  536. }
  537. if (isset($numFmts) && ($numFmts !== NULL)) {
  538. $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  539. }
  540. if (!$this->_readDataOnly && $xmlStyles) {
  541. foreach ($xmlStyles->cellXfs->xf as $xf) {
  542. $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  543. if ($xf["numFmtId"]) {
  544. if (isset($numFmts)) {
  545. $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
  546. if (isset($tmpNumFmt["formatCode"])) {
  547. $numFmt = (string) $tmpNumFmt["formatCode"];
  548. }
  549. }
  550. if ((int)$xf["numFmtId"] < 164) {
  551. $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
  552. }
  553. }
  554. //$numFmt = str_replace('mm', 'i', $numFmt);
  555. //$numFmt = str_replace('h', 'H', $numFmt);
  556. $style = (object) array(
  557. "numFmt" => $numFmt,
  558. "font" => $xmlStyles->fonts->font[intval($xf["fontId"])],
  559. "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])],
  560. "border" => $xmlStyles->borders->border[intval($xf["borderId"])],
  561. "alignment" => $xf->alignment,
  562. "protection" => $xf->protection,
  563. );
  564. $styles[] = $style;
  565. // add style to cellXf collection
  566. $objStyle = new PHPExcel_Style;
  567. self::_readStyle($objStyle, $style);
  568. $excel->addCellXf($objStyle);
  569. }
  570. foreach ($xmlStyles->cellStyleXfs->xf as $xf) {
  571. $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  572. if ($numFmts && $xf["numFmtId"]) {
  573. $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
  574. if (isset($tmpNumFmt["formatCode"])) {
  575. $numFmt = (string) $tmpNumFmt["formatCode"];
  576. } else if ((int)$xf["numFmtId"] < 165) {
  577. $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
  578. }
  579. }
  580. $cellStyle = (object) array(
  581. "numFmt" => $numFmt,
  582. "font" => $xmlStyles->fonts->font[intval($xf["fontId"])],
  583. "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])],
  584. "border" => $xmlStyles->borders->border[intval($xf["borderId"])],
  585. "alignment" => $xf->alignment,
  586. "protection" => $xf->protection,
  587. );
  588. $cellStyles[] = $cellStyle;
  589. // add style to cellStyleXf collection
  590. $objStyle = new PHPExcel_Style;
  591. self::_readStyle($objStyle, $cellStyle);
  592. $excel->addCellStyleXf($objStyle);
  593. }
  594. }
  595. $dxfs = array();
  596. if (!$this->_readDataOnly && $xmlStyles) {
  597. // Conditional Styles
  598. if ($xmlStyles->dxfs) {
  599. foreach ($xmlStyles->dxfs->dxf as $dxf) {
  600. $style = new PHPExcel_Style(FALSE, TRUE);
  601. self::_readStyle($style, $dxf);
  602. $dxfs[] = $style;
  603. }
  604. }
  605. // Cell Styles
  606. if ($xmlStyles->cellStyles) {
  607. foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
  608. if (intval($cellStyle['builtinId']) == 0) {
  609. if (isset($cellStyles[intval($cellStyle['xfId'])])) {
  610. // Set default style
  611. $style = new PHPExcel_Style;
  612. self::_readStyle($style, $cellStyles[intval($cellStyle['xfId'])]);
  613. // normal style, currently not using it for anything
  614. }
  615. }
  616. }
  617. }
  618. }
  619. $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  620. // Set base date
  621. if ($xmlWorkbook->workbookPr) {
  622. PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
  623. if (isset($xmlWorkbook->workbookPr['date1904'])) {
  624. $date1904 = (string)$xmlWorkbook->workbookPr['date1904'];
  625. if ($date1904 == "true" || $date1904 == "1") {
  626. PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
  627. }
  628. }
  629. }
  630. $sheetId = 0; // keep track of new sheet id in final workbook
  631. $oldSheetId = -1; // keep track of old sheet id in final workbook
  632. $countSkippedSheets = 0; // keep track of number of skipped sheets
  633. $mapSheetId = array(); // mapping of sheet ids from old to new
  634. $charts = $chartDetails = array();
  635. if ($xmlWorkbook->sheets) {
  636. foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
  637. ++$oldSheetId;
  638. // Check if sheet should be skipped
  639. if (isset($this->_loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->_loadSheetsOnly)) {
  640. ++$countSkippedSheets;
  641. $mapSheetId[$oldSheetId] = null;
  642. continue;
  643. }
  644. // Map old sheet id in original workbook to new sheet id.
  645. // They will differ if loadSheetsOnly() is being used
  646. $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
  647. // Load sheet
  648. $docSheet = $excel->createSheet();
  649. // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
  650. // references in formula cells... during the load, all formulae should be correct,
  651. // and we're simply bringing the worksheet name in line with the formula, not the
  652. // reverse
  653. $docSheet->setTitle((string) $eleSheet["name"],false);
  654. $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  655. $xmlSheet = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$fileWorksheet")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  656. $sharedFormulas = array();
  657. if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') {
  658. $docSheet->setSheetState( (string) $eleSheet["state"] );
  659. }
  660. if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) {
  661. if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
  662. $docSheet->getSheetView()->setZoomScale( intval($xmlSheet->sheetViews->sheetView['zoomScale']) );
  663. }
  664. if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
  665. $docSheet->getSheetView()->setZoomScaleNormal( intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal']) );
  666. }
  667. if (isset($xmlSheet->sheetViews->sheetView['view'])) {
  668. $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
  669. }
  670. if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
  671. $docSheet->setShowGridLines((string)$xmlSheet->sheetViews->sheetView['showGridLines'] ? true : false);
  672. }
  673. if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
  674. $docSheet->setShowRowColHeaders((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'] ? true : false);
  675. }
  676. if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
  677. $docSheet->setRightToLeft((string)$xmlSheet->sheetViews->sheetView['rightToLeft'] ? true : false);
  678. }
  679. if (isset($xmlSheet->sheetViews->sheetView->pane)) {
  680. if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
  681. $docSheet->freezePane( (string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell'] );
  682. } else {
  683. $xSplit = 0;
  684. $ySplit = 0;
  685. if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
  686. $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']);
  687. }
  688. if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
  689. $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']);
  690. }
  691. $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit);
  692. }
  693. }
  694. if (isset($xmlSheet->sheetViews->sheetView->selection)) {
  695. if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
  696. $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref'];
  697. $sqref = explode(' ', $sqref);
  698. $sqref = $sqref[0];
  699. $docSheet->setSelectedCells($sqref);
  700. }
  701. }
  702. }
  703. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) {
  704. if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
  705. $docSheet->getTabColor()->setARGB( (string)$xmlSheet->sheetPr->tabColor['rgb'] );
  706. }
  707. }
  708. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) {
  709. if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && $xmlSheet->sheetPr->outlinePr['summaryRight'] == false) {
  710. $docSheet->setShowSummaryRight(false);
  711. } else {
  712. $docSheet->setShowSummaryRight(true);
  713. }
  714. if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && $xmlSheet->sheetPr->outlinePr['summaryBelow'] == false) {
  715. $docSheet->setShowSummaryBelow(false);
  716. } else {
  717. $docSheet->setShowSummaryBelow(true);
  718. }
  719. }
  720. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) {
  721. if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && $xmlSheet->sheetPr->pageSetUpPr['fitToPage'] == false) {
  722. $docSheet->getPageSetup()->setFitToPage(false);
  723. } else {
  724. $docSheet->getPageSetup()->setFitToPage(true);
  725. }
  726. }
  727. if (isset($xmlSheet->sheetFormatPr)) {
  728. if (isset($xmlSheet->sheetFormatPr['customHeight']) && ((string)$xmlSheet->sheetFormatPr['customHeight'] == '1' || strtolower((string)$xmlSheet->sheetFormatPr['customHeight']) == 'true') && isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
  729. $docSheet->getDefaultRowDimension()->setRowHeight( (float)$xmlSheet->sheetFormatPr['defaultRowHeight'] );
  730. }
  731. if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
  732. $docSheet->getDefaultColumnDimension()->setWidth( (float)$xmlSheet->sheetFormatPr['defaultColWidth'] );
  733. }
  734. if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
  735. ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
  736. $docSheet->getDefaultRowDimension()->setzeroHeight(true);
  737. }
  738. }
  739. if (isset($xmlSheet->cols) && !$this->_readDataOnly) {
  740. foreach ($xmlSheet->cols->col as $col) {
  741. for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) {
  742. if ($col["style"] && !$this->_readDataOnly) {
  743. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"]));
  744. }
  745. if ($col["bestFit"]) {
  746. //$docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(true);
  747. }
  748. if ($col["hidden"]) {
  749. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setVisible(false);
  750. }
  751. if ($col["collapsed"]) {
  752. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setCollapsed(true);
  753. }
  754. if ($col["outlineLevel"] > 0) {
  755. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"]));
  756. }
  757. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"]));
  758. if (intval($col["max"]) == 16384) {
  759. break;
  760. }
  761. }
  762. }
  763. }
  764. if (isset($xmlSheet->printOptions) && !$this->_readDataOnly) {
  765. if ($xmlSheet->printOptions['gridLinesSet'] == 'true' && $xmlSheet->printOptions['gridLinesSet'] == '1') {
  766. $docSheet->setShowGridlines(true);
  767. }
  768. if ($xmlSheet->printOptions['gridLines'] == 'true' || $xmlSheet->printOptions['gridLines'] == '1') {
  769. $docSheet->setPrintGridlines(true);
  770. }
  771. if ($xmlSheet->printOptions['horizontalCentered']) {
  772. $docSheet->getPageSetup()->setHorizontalCentered(true);
  773. }
  774. if ($xmlSheet->printOptions['verticalCentered']) {
  775. $docSheet->getPageSetup()->setVerticalCentered(true);
  776. }
  777. }
  778. if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
  779. foreach ($xmlSheet->sheetData->row as $row) {
  780. if ($row["ht"] && !$this->_readDataOnly) {
  781. $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"]));
  782. }
  783. if ($row["hidden"] && !$this->_readDataOnly) {
  784. $docSheet->getRowDimension(intval($row["r"]))->setVisible(false);
  785. }
  786. if ($row["collapsed"]) {
  787. $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(true);
  788. }
  789. if ($row["outlineLevel"] > 0) {
  790. $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"]));
  791. }
  792. if ($row["s"] && !$this->_readDataOnly) {
  793. $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"]));
  794. }
  795. foreach ($row->c as $c) {
  796. $r = (string) $c["r"];
  797. $cellDataType = (string) $c["t"];
  798. $value = null;
  799. $calculatedValue = null;
  800. // Read cell?
  801. if ($this->getReadFilter() !== NULL) {
  802. $coordinates = PHPExcel_Cell::coordinateFromString($r);
  803. if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) {
  804. continue;
  805. }
  806. }
  807. // echo '<b>Reading cell '.$coordinates[0].$coordinates[1].'</b><br />';
  808. // print_r($c);
  809. // echo '<br />';
  810. // echo 'Cell Data Type is '.$cellDataType.': ';
  811. //
  812. // Read cell!
  813. switch ($cellDataType) {
  814. case "s":
  815. // echo 'String<br />';
  816. if ((string)$c->v != '') {
  817. $value = $sharedStrings[intval($c->v)];
  818. if ($value instanceof PHPExcel_RichText) {
  819. $value = clone $value;
  820. }
  821. } else {
  822. $value = '';
  823. }
  824. break;
  825. case "b":
  826. // echo 'Boolean<br />';
  827. if (!isset($c->f)) {
  828. $value = self::_castToBool($c);
  829. } else {
  830. // Formula
  831. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToBool');
  832. if (isset($c->f['t'])) {
  833. $att = array();
  834. $att = $c->f;
  835. $docSheet->getCell($r)->setFormulaAttributes($att);
  836. }
  837. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  838. }
  839. break;
  840. case "inlineStr":
  841. // echo 'Inline String<br />';
  842. $value = $this->_parseRichText($c->is);
  843. break;
  844. case "e":
  845. // echo 'Error<br />';
  846. if (!isset($c->f)) {
  847. $value = self::_castToError($c);
  848. } else {
  849. // Formula
  850. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToError');
  851. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  852. }
  853. break;
  854. default:
  855. // echo 'Default<br />';
  856. if (!isset($c->f)) {
  857. // echo 'Not a Formula<br />';
  858. $value = self::_castToString($c);
  859. } else {
  860. // echo 'Treat as Formula<br />';
  861. // Formula
  862. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToString');
  863. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  864. }
  865. break;
  866. }
  867. // echo 'Value is '.$value.'<br />';
  868. // Check for numeric values
  869. if (is_numeric($value) && $cellDataType != 's') {
  870. if ($value == (int)$value) $value = (int)$value;
  871. elseif ($value == (float)$value) $value = (float)$value;
  872. elseif ($value == (double)$value) $value = (double)$value;
  873. }
  874. // Rich text?
  875. if ($value instanceof PHPExcel_RichText && $this->_readDataOnly) {
  876. $value = $value->getPlainText();
  877. }
  878. $cell = $docSheet->getCell($r);
  879. // Assign value
  880. if ($cellDataType != '') {
  881. $cell->setValueExplicit($value, $cellDataType);
  882. } else {
  883. $cell->setValue($value);
  884. }
  885. if ($calculatedValue !== NULL) {
  886. $cell->setCalculatedValue($calculatedValue);
  887. }
  888. // Style information?
  889. if ($c["s"] && !$this->_readDataOnly) {
  890. // no style index means 0, it seems
  891. $cell->setXfIndex(isset($styles[intval($c["s"])]) ?
  892. intval($c["s"]) : 0);
  893. }
  894. }
  895. }
  896. }
  897. $conditionals = array();
  898. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
  899. foreach ($xmlSheet->conditionalFormatting as $conditional) {
  900. foreach ($conditional->cfRule as $cfRule) {
  901. if (
  902. (
  903. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_NONE ||
  904. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CELLIS ||
  905. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT ||
  906. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
  907. ) && isset($dxfs[intval($cfRule["dxfId"])])
  908. ) {
  909. $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule;
  910. }
  911. }
  912. }
  913. foreach ($conditionals as $ref => $cfRules) {
  914. ksort($cfRules);
  915. $conditionalStyles = array();
  916. foreach ($cfRules as $cfRule) {
  917. $objConditional = new PHPExcel_Style_Conditional();
  918. $objConditional->setConditionType((string)$cfRule["type"]);
  919. $objConditional->setOperatorType((string)$cfRule["operator"]);
  920. if ((string)$cfRule["text"] != '') {
  921. $objConditional->setText((string)$cfRule["text"]);
  922. }
  923. if (count($cfRule->formula) > 1) {
  924. foreach ($cfRule->formula as $formula) {
  925. $objConditional->addCondition((string)$formula);
  926. }
  927. } else {
  928. $objConditional->addCondition((string)$cfRule->formula);
  929. }
  930. $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]);
  931. $conditionalStyles[] = $objConditional;
  932. }
  933. // Extract all cell references in $ref
  934. $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($ref);
  935. foreach ($aReferences as $reference) {
  936. $docSheet->getStyle($reference)->setConditionalStyles($conditionalStyles);
  937. }
  938. }
  939. }
  940. $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells");
  941. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  942. foreach ($aKeys as $key) {
  943. $method = "set" . ucfirst($key);
  944. $docSheet->getProtection()->$method($xmlSheet->sheetProtection[$key] == "true");
  945. }
  946. }
  947. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  948. $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], true);
  949. if ($xmlSheet->protectedRanges->protectedRange) {
  950. foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
  951. $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true);
  952. }
  953. }
  954. }
  955. if ($xmlSheet && $xmlSheet->autoFilter && !$this->_readDataOnly) {
  956. $autoFilter = $docSheet->getAutoFilter();
  957. $autoFilter->setRange((string) $xmlSheet->autoFilter["ref"]);
  958. foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
  959. $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]);
  960. // Check for standard filters
  961. if ($filterColumn->filters) {
  962. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER);
  963. $filters = $filterColumn->filters;
  964. if ((isset($filters["blank"])) && ($filters["blank"] == 1)) {
  965. $column->createRule()->setRule(
  966. NULL, // Operator is undefined, but always treated as EQUAL
  967. ''
  968. )
  969. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER);
  970. }
  971. // Standard filters are always an OR join, so no join rule needs to be set
  972. // Entries can be either filter elements
  973. foreach ($filters->filter as $filterRule) {
  974. $column->createRule()->setRule(
  975. NULL, // Operator is undefined, but always treated as EQUAL
  976. (string) $filterRule["val"]
  977. )
  978. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER);
  979. }
  980. // Or Date Group elements
  981. foreach ($filters->dateGroupItem as $dateGroupItem) {
  982. $column->createRule()->setRule(
  983. NULL, // Operator is undefined, but always treated as EQUAL
  984. array(
  985. 'year' => (string) $dateGroupItem["year"],
  986. 'month' => (string) $dateGroupItem["month"],
  987. 'day' => (string) $dateGroupItem["day"],
  988. 'hour' => (string) $dateGroupItem["hour"],
  989. 'minute' => (string) $dateGroupItem["minute"],
  990. 'second' => (string) $dateGroupItem["second"],
  991. ),
  992. (string) $dateGroupItem["dateTimeGrouping"]
  993. )
  994. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP);
  995. }
  996. }
  997. // Check for custom filters
  998. if ($filterColumn->customFilters) {
  999. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
  1000. $customFilters = $filterColumn->customFilters;
  1001. // Custom filters can an AND or an OR join;
  1002. // and there should only ever be one or two entries
  1003. if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) {
  1004. $column->setJoin(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
  1005. }
  1006. foreach ($customFilters->customFilter as $filterRule) {
  1007. $column->createRule()->setRule(
  1008. (string) $filterRule["operator"],
  1009. (string) $filterRule["val"]
  1010. )
  1011. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
  1012. }
  1013. }
  1014. // Check for dynamic filters
  1015. if ($filterColumn->dynamicFilter) {
  1016. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
  1017. // We should only ever have one dynamic filter
  1018. foreach ($filterColumn->dynamicFilter as $filterRule) {
  1019. $column->createRule()->setRule(
  1020. NULL, // Operator is undefined, but always treated as EQUAL
  1021. (string) $filterRule["val"],
  1022. (string) $filterRule["type"]
  1023. )
  1024. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
  1025. if (isset($filterRule["val"])) {
  1026. $column->setAttribute('val',(string) $filterRule["val"]);
  1027. }
  1028. if (isset($filterRule["maxVal"])) {
  1029. $column->setAttribute('maxVal',(string) $filterRule["maxVal"]);
  1030. }
  1031. }
  1032. }
  1033. // Check for dynamic filters
  1034. if ($filterColumn->top10) {
  1035. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
  1036. // We should only ever have one top10 filter
  1037. foreach ($filterColumn->top10 as $filterRule) {
  1038. $column->createRule()->setRule(
  1039. (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1))
  1040. ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
  1041. : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
  1042. ),
  1043. (string) $filterRule["val"],
  1044. (((isset($filterRule["top"])) && ($filterRule["top"] == 1))
  1045. ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
  1046. : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
  1047. )
  1048. )
  1049. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
  1050. }
  1051. }
  1052. }
  1053. }
  1054. if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->_readDataOnly) {
  1055. foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
  1056. $mergeRef = (string) $mergeCell["ref"];
  1057. if (strpos($mergeRef,':') !== FALSE) {
  1058. $docSheet->mergeCells((string) $mergeCell["ref"]);
  1059. }
  1060. }
  1061. }
  1062. if ($xmlSheet && $xmlSheet->pageMargins && !$this->_readDataOnly) {
  1063. $docPageMargins = $docSheet->getPageMargins();
  1064. $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"]));
  1065. $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"]));
  1066. $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"]));
  1067. $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"]));
  1068. $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"]));
  1069. $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"]));
  1070. }
  1071. if ($xmlSheet && $xmlSheet->pageSetup && !$this->_readDataOnly) {
  1072. $docPageSetup = $docSheet->getPageSetup();
  1073. if (isset($xmlSheet->pageSetup["orientation"])) {
  1074. $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]);
  1075. }
  1076. if (isset($xmlSheet->pageSetup["paperSize"])) {
  1077. $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"]));
  1078. }
  1079. if (isset($xmlSheet->pageSetup["scale"])) {
  1080. $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), false);
  1081. }
  1082. if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) {
  1083. $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), false);
  1084. }
  1085. if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) {
  1086. $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), false);
  1087. }
  1088. if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) &&
  1089. ((string)$xmlSheet->pageSetup["useFirstPageNumber"] == 'true' || (string)$xmlSheet->pageSetup["useFirstPageNumber"] == '1')) {
  1090. $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"]));
  1091. }
  1092. }
  1093. if ($xmlSheet && $xmlSheet->headerFooter && !$this->_readDataOnly) {
  1094. $docHeaderFooter = $docSheet->getHeaderFooter();
  1095. if (isset($xmlSheet->headerFooter["differentOddEven"]) &&
  1096. ((string)$xmlSheet->headerFooter["differentOddEven"] == 'true' || (string)$xmlSheet->headerFooter["differentOddEven"] == '1')) {
  1097. $docHeaderFooter->setDifferentOddEven(true);
  1098. } else {
  1099. $docHeaderFooter->setDifferentOddEven(false);
  1100. }
  1101. if (isset($xmlSheet->headerFooter["differentFirst"]) &&
  1102. ((string)$xmlSheet->headerFooter["differentFirst"] == 'true' || (string)$xmlSheet->headerFooter["differentFirst"] == '1')) {
  1103. $docHeaderFooter->setDifferentFirst(true);
  1104. } else {
  1105. $docHeaderFooter->setDifferentFirst(false);
  1106. }
  1107. if (isset($xmlSheet->headerFooter["scaleWithDoc"]) &&
  1108. ((string)$xmlSheet->headerFooter["scaleWithDoc"] == 'false' || (string)$xmlSheet->headerFooter["scaleWithDoc"] == '0')) {
  1109. $docHeaderFooter->setScaleWithDocument(false);
  1110. } else {
  1111. $docHeaderFooter->setScaleWithDocument(true);
  1112. }
  1113. if (isset($xmlSheet->headerFooter["alignWithMargins"]) &&
  1114. ((string)$xmlSheet->headerFooter["align…

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