PageRenderTime 35ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 1ms

/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
  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["alignWithMargins"] == 'false' || (string)$xmlSheet->headerFooter["alignWithMargins"] == '0')) {
  1115. $docHeaderFooter->setAlignWithMargins(false);
  1116. } else {
  1117. $docHeaderFooter->setAlignWithMargins(true);
  1118. }
  1119. $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
  1120. $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
  1121. $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
  1122. $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
  1123. $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
  1124. $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
  1125. }
  1126. if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->_readDataOnly) {
  1127. foreach ($xmlSheet->rowBreaks->brk as $brk) {
  1128. if ($brk["man"]) {
  1129. $docSheet->setBreak("A$brk[id]", PHPExcel_Worksheet::BREAK_ROW);
  1130. }
  1131. }
  1132. }
  1133. if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->_readDataOnly) {
  1134. foreach ($xmlSheet->colBreaks->brk as $brk) {
  1135. if ($brk["man"]) {
  1136. $docSheet->setBreak(PHPExcel_Cell::stringFromColumnIndex((string) $brk["id"]) . "1", PHPExcel_Worksheet::BREAK_COLUMN);
  1137. }
  1138. }
  1139. }
  1140. if ($xmlSheet && $xmlSheet->dataValidations && !$this->_readDataOnly) {
  1141. foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
  1142. // Uppercase coordinate
  1143. $range = strtoupper($dataValidation["sqref"]);
  1144. $rangeSet = explode(' ',$range);
  1145. foreach($rangeSet as $range) {
  1146. $stRange = $docSheet->shrinkRangeToFit($range);
  1147. // Extract all cell references in $range
  1148. $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($stRange);
  1149. foreach ($aReferences as $reference) {
  1150. // Create validation
  1151. $docValidation = $docSheet->getCell($reference)->getDataValidation();
  1152. $docValidation->setType((string) $dataValidation["type"]);
  1153. $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]);
  1154. $docValidation->setOperator((string) $dataValidation["operator"]);
  1155. $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0);
  1156. $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0);
  1157. $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0);
  1158. $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0);
  1159. $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]);
  1160. $docValidation->setError((string) $dataValidation["error"]);
  1161. $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]);
  1162. $docValidation->setPrompt((string) $dataValidation["prompt"]);
  1163. $docValidation->setFormula1((string) $dataValidation->formula1);
  1164. $docValidation->setFormula2((string) $dataValidation->formula2);
  1165. }
  1166. }
  1167. }
  1168. }
  1169. // Add hyperlinks
  1170. $hyperlinks = array();
  1171. if (!$this->_readDataOnly) {
  1172. // Locate hyperlink relations
  1173. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1174. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1175. foreach ($relsWorksheet->Relationship as $ele) {
  1176. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") {
  1177. $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"];
  1178. }
  1179. }
  1180. }
  1181. // Loop through hyperlinks
  1182. if ($xmlSheet && $xmlSheet->hyperlinks) {
  1183. foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
  1184. // Link url
  1185. $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  1186. foreach (PHPExcel_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
  1187. $cell = $docSheet->getCell( $cellReference );
  1188. if (isset($linkRel['id'])) {
  1189. $cell->getHyperlink()->setUrl( $hyperlinks[ (string)$linkRel['id'] ] );
  1190. }
  1191. if (isset($hyperlink['location'])) {
  1192. $cell->getHyperlink()->setUrl( 'sheet://' . (string)$hyperlink['location'] );
  1193. }
  1194. // Tooltip
  1195. if (isset($hyperlink['tooltip'])) {
  1196. $cell->getHyperlink()->setTooltip( (string)$hyperlink['tooltip'] );
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. // Add comments
  1203. $comments = array();
  1204. $vmlComments = array();
  1205. if (!$this->_readDataOnly) {
  1206. // Locate comment relations
  1207. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1208. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1209. foreach ($relsWorksheet->Relationship as $ele) {
  1210. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") {
  1211. $comments[(string)$ele["Id"]] = (string)$ele["Target"];
  1212. }
  1213. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1214. $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"];
  1215. }
  1216. }
  1217. }
  1218. // Loop through comments
  1219. foreach ($comments as $relName => $relPath) {
  1220. // Load comments file
  1221. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  1222. $commentsFile = simplexml_load_string($this->_getFromZipArchive($zip, $relPath) );
  1223. // Utility variables
  1224. $authors = array();
  1225. // Loop through authors
  1226. foreach ($commentsFile->authors->author as $author) {
  1227. $authors[] = (string)$author;
  1228. }
  1229. // Loop through contents
  1230. foreach ($commentsFile->commentList->comment as $comment) {
  1231. $docSheet->getComment( (string)$comment['ref'] )->setAuthor( $authors[(string)$comment['authorId']] );
  1232. $docSheet->getComment( (string)$comment['ref'] )->setText( $this->_parseRichText($comment->text) );
  1233. }
  1234. }
  1235. // Loop through VML comments
  1236. foreach ($vmlComments as $relName => $relPath) {
  1237. // Load VML comments file
  1238. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  1239. $vmlCommentsFile = simplexml_load_string( $this->_getFromZipArchive($zip, $relPath) );
  1240. $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1241. $shapes = $vmlCommentsFile->xpath('//v:shape');
  1242. foreach ($shapes as $shape) {
  1243. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1244. if (isset($shape['style'])) {
  1245. $style = (string)$shape['style'];
  1246. $fillColor = strtoupper( substr( (string)$shape['fillcolor'], 1 ) );
  1247. $column = null;
  1248. $row = null;
  1249. $clientData = $shape->xpath('.//x:ClientData');
  1250. if (is_array($clientData) && !empty($clientData)) {
  1251. $clientData = $clientData[0];
  1252. if ( isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note' ) {
  1253. $temp = $clientData->xpath('.//x:Row');
  1254. if (is_array($temp)) $row = $temp[0];
  1255. $temp = $clientData->xpath('.//x:Column');
  1256. if (is_array($temp)) $column = $temp[0];
  1257. }
  1258. }
  1259. if (($column !== NULL) && ($row !== NULL)) {
  1260. // Set comment properties
  1261. $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1);
  1262. $comment->getFillColor()->setRGB( $fillColor );
  1263. // Parse style
  1264. $styleArray = explode(';', str_replace(' ', '', $style));
  1265. foreach ($styleArray as $stylePair) {
  1266. $stylePair = explode(':', $stylePair);
  1267. if ($stylePair[0] == 'margin-left') $comment->setMarginLeft($stylePair[1]);
  1268. if ($stylePair[0] == 'margin-top') $comment->setMarginTop($stylePair[1]);
  1269. if ($stylePair[0] == 'width') $comment->setWidth($stylePair[1]);
  1270. if ($stylePair[0] == 'height') $comment->setHeight($stylePair[1]);
  1271. if ($stylePair[0] == 'visibility') $comment->setVisible( $stylePair[1] == 'visible' );
  1272. }
  1273. }
  1274. }
  1275. }
  1276. }
  1277. // Header/footer images
  1278. if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->_readDataOnly) {
  1279. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1280. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1281. $vmlRelationship = '';
  1282. foreach ($relsWorksheet->Relationship as $ele) {
  1283. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1284. $vmlRelationship = self::dir_add("$dir/$fileWorksheet", $ele["Target"]);
  1285. }
  1286. }
  1287. if ($vmlRelationship != '') {
  1288. // Fetch linked images
  1289. $relsVML = simplexml_load_string($this->_getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels' )); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1290. $drawings = array();
  1291. foreach ($relsVML->Relationship as $ele) {
  1292. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1293. $drawings[(string) $ele["Id"]] = self::dir_add($vmlRelationship, $ele["Target"]);
  1294. }
  1295. }
  1296. // Fetch VML document
  1297. $vmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $vmlRelationship));
  1298. $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1299. $hfImages = array();
  1300. $shapes = $vmlDrawing->xpath('//v:shape');
  1301. foreach ($shapes as $shape) {
  1302. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1303. $imageData = $shape->xpath('//v:imagedata');
  1304. $imageData = $imageData[0];
  1305. $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
  1306. $style = self::toCSSArray( (string)$shape['style'] );
  1307. $hfImages[ (string)$shape['id'] ] = new PHPExcel_Worksheet_HeaderFooterDrawing();
  1308. if (isset($imageData['title'])) {
  1309. $hfImages[ (string)$shape['id'] ]->setName( (string)$imageData['title'] );
  1310. }
  1311. $hfImages[ (string)$shape['id'] ]->setPath("zip://$pFilename#" . $drawings[(string)$imageData['relid']], false);
  1312. $hfImages[ (string)$shape['id'] ]->setResizeProportional(false);
  1313. $hfImages[ (string)$shape['id'] ]->setWidth($style['width']);
  1314. $hfImages[ (string)$shape['id'] ]->setHeight($style['height']);
  1315. $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']);
  1316. $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']);
  1317. $hfImages[ (string)$shape['id'] ]->setResizeProportional(true);
  1318. }
  1319. $docSheet->getHeaderFooter()->setImages($hfImages);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. // TODO: Autoshapes from twoCellAnchors!
  1325. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1326. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1327. $drawings = array();
  1328. foreach ($relsWorksheet->Relationship as $ele) {
  1329. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") {
  1330. $drawings[(string) $ele["Id"]] = self::dir_add("$dir/$fileWorksheet", $ele["Target"]);
  1331. }
  1332. }
  1333. if ($xmlSheet->drawing && !$this->_readDataOnly) {
  1334. foreach ($xmlSheet->drawing as $drawing) {
  1335. $fileDrawing = $drawings[(string) self::array_item($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  1336. $relsDrawing = simplexml_load_string($this->_getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1337. $images = array();
  1338. if ($relsDrawing && $relsDrawing->Relationship) {
  1339. foreach ($relsDrawing->Relationship as $ele) {
  1340. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1341. $images[(string) $ele["Id"]] = self::dir_add($fileDrawing, $ele["Target"]);
  1342. } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") {
  1343. if ($this->_includeCharts) {
  1344. $charts[self::dir_add($fileDrawing, $ele["Target"])] = array('id' => (string) $ele["Id"],
  1345. 'sheet' => $docSheet->getTitle()
  1346. );
  1347. }
  1348. }
  1349. }
  1350. }
  1351. $xmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $fileDrawing))->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
  1352. if ($xmlDrawing->oneCellAnchor) {
  1353. foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
  1354. if ($oneCellAnchor->pic->blipFill) {
  1355. $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1356. $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1357. $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1358. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1359. $objDrawing->setName((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1360. $objDrawing->setDescription((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1361. $objDrawing->setPath("zip://$pFilename#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1362. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1));
  1363. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff));
  1364. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
  1365. $objDrawing->setResizeProportional(false);
  1366. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx")));
  1367. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy")));
  1368. if ($xfrm) {
  1369. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot")));
  1370. }
  1371. if ($outerShdw) {
  1372. $shadow = $objDrawing->getShadow();
  1373. $shadow->setVisible(true);
  1374. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad")));
  1375. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist")));
  1376. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir")));
  1377. $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn"));
  1378. $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val"));
  1379. $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1380. }
  1381. $objDrawing->setWorksheet($docSheet);
  1382. } else {
  1383. // ? Can charts be positioned with a oneCellAnchor ?
  1384. $coordinates = PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1);
  1385. $offsetX = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff);
  1386. $offsetY = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
  1387. $width = PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx"));
  1388. $height = PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy"));
  1389. }
  1390. }
  1391. }
  1392. if ($xmlDrawing->twoCellAnchor) {
  1393. foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
  1394. if ($twoCellAnchor->pic->blipFill) {
  1395. $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1396. $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1397. $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1398. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1399. $objDrawing->setName((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1400. $objDrawing->setDescription((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1401. $objDrawing->setPath("zip://$pFilename#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1402. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1));
  1403. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff));
  1404. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
  1405. $objDrawing->setResizeProportional(false);
  1406. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cx")));
  1407. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cy")));
  1408. if ($xfrm) {
  1409. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot")));
  1410. }
  1411. if ($outerShdw) {
  1412. $shadow = $objDrawing->getShadow();
  1413. $shadow->setVisible(true);
  1414. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad")));
  1415. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist")));
  1416. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir")));
  1417. $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn"));
  1418. $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val"));
  1419. $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1420. }
  1421. $objDrawing->setWorksheet($docSheet);
  1422. } elseif(($this->_includeCharts) && ($twoCellAnchor->graphicFrame)) {
  1423. $fromCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1);
  1424. $fromOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff);
  1425. $fromOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
  1426. $toCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1);
  1427. $toOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff);
  1428. $toOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
  1429. $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic;
  1430. $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart;
  1431. $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships");
  1432. $chartDetails[$docSheet->getTitle().'!'.$thisChart] =
  1433. array( 'fromCoordinate' => $fromCoordinate,
  1434. 'fromOffsetX' => $fromOffsetX,
  1435. 'fromOffsetY' => $fromOffsetY,
  1436. 'toCoordinate' => $toCoordinate,
  1437. 'toOffsetX' => $toOffsetX,
  1438. 'toOffsetY' => $toOffsetY,
  1439. 'worksheetTitle' => $docSheet->getTitle()
  1440. );
  1441. }
  1442. }
  1443. }
  1444. }
  1445. }
  1446. }
  1447. // Loop through definedNames
  1448. if ($xmlWorkbook->definedNames) {
  1449. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1450. // Extract range
  1451. $extractedRange = (string)$definedName;
  1452. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1453. if (($spos = strpos($extractedRange,'!')) !== false) {
  1454. $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos));
  1455. } else {
  1456. $extractedRange = str_replace('$', '', $extractedRange);
  1457. }
  1458. // Valid range?
  1459. if (stripos((string)$definedName, '#REF!') !== FALSE || $extractedRange == '') {
  1460. continue;
  1461. }
  1462. // Some definedNames are only applicable if we are on the same sheet...
  1463. if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) {
  1464. // Switch on type
  1465. switch ((string)$definedName['name']) {
  1466. case '_xlnm._FilterDatabase':
  1467. if ((string)$definedName['hidden'] !== '1') {
  1468. $docSheet->getAutoFilter()->setRange($extractedRange);
  1469. }
  1470. break;
  1471. case '_xlnm.Print_Titles':
  1472. // Split $extractedRange
  1473. $extractedRange = explode(',', $extractedRange);
  1474. // Set print titles
  1475. foreach ($extractedRange as $range) {
  1476. $matches = array();
  1477. // check for repeating columns, e g. 'A:A' or 'A:D'
  1478. if (preg_match('/^([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
  1479. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2]));
  1480. }
  1481. // check for repeating rows, e.g. '1:1' or '1:5'
  1482. elseif (preg_match('/^(\d+)\:(\d+)$/', $range, $matches)) {
  1483. $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2]));
  1484. }
  1485. }
  1486. break;
  1487. case '_xlnm.Print_Area':
  1488. $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma?
  1489. $newRangeSets = array();
  1490. foreach($rangeSets as $rangeSet) {
  1491. $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark?
  1492. $rangeSet = isset($range[1]) ? $range[1] : $range[0];
  1493. $newRangeSets[] = str_replace('$', '', $rangeSet);
  1494. }
  1495. $docSheet->getPageSetup()->setPrintArea(implode(',',$newRangeSets));
  1496. break;
  1497. default:
  1498. break;
  1499. }
  1500. }
  1501. }
  1502. }
  1503. // Next sheet id
  1504. ++$sheetId;
  1505. }
  1506. // Loop through definedNames
  1507. if ($xmlWorkbook->definedNames) {
  1508. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1509. // Extract range
  1510. $extractedRange = (string)$definedName;
  1511. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1512. if (($spos = strpos($extractedRange,'!')) !== false) {
  1513. $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos));
  1514. } else {
  1515. $extractedRange = str_replace('$', '', $extractedRange);
  1516. }
  1517. // Valid range?
  1518. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1519. continue;
  1520. }
  1521. // Some definedNames are only applicable if we are on the same sheet...
  1522. if ((string)$definedName['localSheetId'] != '') {
  1523. // Local defined name
  1524. // Switch on type
  1525. switch ((string)$definedName['name']) {
  1526. case '_xlnm._FilterDatabase':
  1527. case '_xlnm.Print_Titles':
  1528. case '_xlnm.Print_Area':
  1529. break;
  1530. default:
  1531. $range = explode('!', (string)$definedName);
  1532. if (count($range) == 2) {
  1533. $range[0] = str_replace("''", "'", $range[0]);
  1534. $range[0] = str_replace("'", "", $range[0]);
  1535. if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
  1536. $extractedRange = str_replace('$', '', $range[1]);
  1537. $scope = $docSheet->getParent()->getSheet((string)$definedName['localSheetId']);
  1538. $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope) );
  1539. }
  1540. }
  1541. break;
  1542. }
  1543. } else if (!isset($definedName['localSheetId'])) {
  1544. // "Global" definedNames
  1545. $locatedSheet = null;
  1546. $extractedSheetName = '';
  1547. if (strpos( (string)$definedName, '!' ) !== false) {
  1548. // Extract sheet name
  1549. $extractedSheetName = PHPExcel_Worksheet::extractSheetTitle( (string)$definedName, true );
  1550. $extractedSheetName = $extractedSheetName[0];
  1551. // Locate sheet
  1552. $locatedSheet = $excel->getSheetByName($extractedSheetName);
  1553. // Modify range
  1554. $range = explode('!', $extractedRange);
  1555. $extractedRange = isset($range[1]) ? $range[1] : $range[0];
  1556. }
  1557. if ($locatedSheet !== NULL) {
  1558. $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false) );
  1559. }
  1560. }
  1561. }
  1562. }
  1563. }
  1564. if (!$this->_readDataOnly) {
  1565. // active sheet index
  1566. $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index
  1567. // keep active sheet index if sheet is still loaded, else first sheet is set as the active
  1568. if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
  1569. $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
  1570. } else {
  1571. if ($excel->getSheetCount() == 0) {
  1572. $excel->createSheet();
  1573. }
  1574. $excel->setActiveSheetIndex(0);
  1575. }
  1576. }
  1577. break;
  1578. }
  1579. }
  1580. if (!$this->_readDataOnly) {
  1581. $contentTypes = simplexml_load_string($this->_getFromZipArchive($zip, "[Content_Types].xml"));
  1582. foreach ($contentTypes->Override as $contentType) {
  1583. switch ($contentType["ContentType"]) {
  1584. case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml":
  1585. if ($this->_includeCharts) {
  1586. $chartEntryRef = ltrim($contentType['PartName'],'/');
  1587. $chartElements = simplexml_load_string($this->_getFromZipArchive($zip, $chartEntryRef));
  1588. $objChart = PHPExcel_Reader_Excel2007_Chart::readChart($chartElements,basename($chartEntryRef,'.xml'));
  1589. // echo 'Chart ',$chartEntryRef,'<br />';
  1590. // var_dump($charts[$chartEntryRef]);
  1591. //
  1592. if (isset($charts[$chartEntryRef])) {
  1593. $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id'];
  1594. // echo 'Position Ref ',$chartPositionRef,'<br />';
  1595. if (isset($chartDetails[$chartPositionRef])) {
  1596. // var_dump($chartDetails[$chartPositionRef]);
  1597. $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
  1598. $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
  1599. $objChart->setTopLeftPosition( $chartDetails[$chartPositionRef]['fromCoordinate'],
  1600. $chartDetails[$chartPositionRef]['fromOffsetX'],
  1601. $chartDetails[$chartPositionRef]['fromOffsetY']
  1602. );
  1603. $objChart->setBottomRightPosition( $chartDetails[$chartPositionRef]['toCoordinate'],
  1604. $chartDetails[$chartPositionRef]['toOffsetX'],
  1605. $chartDetails[$chartPositionRef]['toOffsetY']
  1606. );
  1607. }
  1608. }
  1609. }
  1610. }
  1611. }
  1612. }
  1613. $zip->close();
  1614. return $excel;
  1615. }
  1616. private static function _readColor($color, $background=FALSE) {
  1617. if (isset($color["rgb"])) {
  1618. return (string)$color["rgb"];
  1619. } else if (isset($color["indexed"])) {
  1620. return PHPExcel_Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB();
  1621. } else if (isset($color["theme"])) {
  1622. if (self::$_theme !== NULL) {
  1623. $returnColour = self::$_theme->getColourByIndex((int)$color["theme"]);
  1624. if (isset($color["tint"])) {
  1625. $tintAdjust = (float) $color["tint"];
  1626. $returnColour = PHPExcel_Style_Color::changeBrightness($returnColour, $tintAdjust);
  1627. }
  1628. return 'FF'.$returnColour;
  1629. }
  1630. }
  1631. if ($background) {
  1632. return 'FFFFFFFF';
  1633. }
  1634. return 'FF000000';
  1635. }
  1636. private static function _readStyle($docStyle, $style) {
  1637. // format code
  1638. // if (isset($style->numFmt)) {
  1639. // if (isset($style->numFmt['formatCode'])) {
  1640. // $docStyle->getNumberFormat()->setFormatCode((string) $style->numFmt['formatCode']);
  1641. // } else {
  1642. $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
  1643. // }
  1644. // }
  1645. // font
  1646. if (isset($style->font)) {
  1647. $docStyle->getFont()->setName((string) $style->font->name["val"]);
  1648. $docStyle->getFont()->setSize((string) $style->font->sz["val"]);
  1649. if (isset($style->font->b)) {
  1650. $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || $style->font->b["val"] == 'true' || $style->font->b["val"] == '1');
  1651. }
  1652. if (isset($style->font->i)) {
  1653. $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || $style->font->i["val"] == 'true' || $style->font->i["val"] == '1');
  1654. }
  1655. if (isset($style->font->strike)) {
  1656. $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || $style->font->strike["val"] == 'true' || $style->font->strike["val"] == '1');
  1657. }
  1658. $docStyle->getFont()->getColor()->setARGB(self::_readColor($style->font->color));
  1659. if (isset($style->font->u) && !isset($style->font->u["val"])) {
  1660. $docStyle->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1661. } else if (isset($style->font->u) && isset($style->font->u["val"])) {
  1662. $docStyle->getFont()->setUnderline((string)$style->font->u["val"]);
  1663. }
  1664. if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) {
  1665. $vertAlign = strtolower((string)$style->font->vertAlign["val"]);
  1666. if ($vertAlign == 'superscript') {
  1667. $docStyle->getFont()->setSuperScript(true);
  1668. }
  1669. if ($vertAlign == 'subscript') {
  1670. $docStyle->getFont()->setSubScript(true);
  1671. }
  1672. }
  1673. }
  1674. // fill
  1675. if (isset($style->fill)) {
  1676. if ($style->fill->gradientFill) {
  1677. $gradientFill = $style->fill->gradientFill[0];
  1678. if(!empty($gradientFill["type"])) {
  1679. $docStyle->getFill()->setFillType((string) $gradientFill["type"]);
  1680. }
  1681. $docStyle->getFill()->setRotation(floatval($gradientFill["degree"]));
  1682. $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  1683. $docStyle->getFill()->getStartColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=0]"))->color) );
  1684. $docStyle->getFill()->getEndColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=1]"))->color) );
  1685. } elseif ($style->fill->patternFill) {
  1686. $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid';
  1687. $docStyle->getFill()->setFillType($patternType);
  1688. if ($style->fill->patternFill->fgColor) {
  1689. $docStyle->getFill()->getStartColor()->setARGB(self::_readColor($style->fill->patternFill->fgColor,true));
  1690. } else {
  1691. $docStyle->getFill()->getStartColor()->setARGB('FF000000');
  1692. }
  1693. if ($style->fill->patternFill->bgColor) {
  1694. $docStyle->getFill()->getEndColor()->setARGB(self::_readColor($style->fill->patternFill->bgColor,true));
  1695. }
  1696. }
  1697. }
  1698. // border
  1699. if (isset($style->border)) {
  1700. $diagonalUp = false;
  1701. $diagonalDown = false;
  1702. if ($style->border["diagonalUp"] == 'true' || $style->border["diagonalUp"] == 1) {
  1703. $diagonalUp = true;
  1704. }
  1705. if ($style->border["diagonalDown"] == 'true' || $style->border["diagonalDown"] == 1) {
  1706. $diagonalDown = true;
  1707. }
  1708. if ($diagonalUp == false && $diagonalDown == false) {
  1709. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE);
  1710. } elseif ($diagonalUp == true && $diagonalDown == false) {
  1711. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP);
  1712. } elseif ($diagonalUp == false && $diagonalDown == true) {
  1713. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN);
  1714. } elseif ($diagonalUp == true && $diagonalDown == true) {
  1715. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH);
  1716. }
  1717. self::_readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
  1718. self::_readBorder($docStyle->getBorders()->getRight(), $style->border->right);
  1719. self::_readBorder($docStyle->getBorders()->getTop(), $style->border->top);
  1720. self::_readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
  1721. self::_readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
  1722. }
  1723. // alignment
  1724. if (isset($style->alignment)) {
  1725. $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]);
  1726. $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]);
  1727. $textRotation = 0;
  1728. if ((int)$style->alignment["textRotation"] <= 90) {
  1729. $textRotation = (int)$style->alignment["textRotation"];
  1730. } else if ((int)$style->alignment["textRotation"] > 90) {
  1731. $textRotation = 90 - (int)$style->alignment["textRotation"];
  1732. }
  1733. $docStyle->getAlignment()->setTextRotation(intval($textRotation));
  1734. $docStyle->getAlignment()->setWrapText( (string)$style->alignment["wrapText"] == "true" || (string)$style->alignment["wrapText"] == "1" );
  1735. $docStyle->getAlignment()->setShrinkToFit( (string)$style->alignment["shrinkToFit"] == "true" || (string)$style->alignment["shrinkToFit"] == "1" );
  1736. $docStyle->getAlignment()->setIndent( intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0 );
  1737. }
  1738. // protection
  1739. if (isset($style->protection)) {
  1740. if (isset($style->protection['locked'])) {
  1741. if ((string)$style->protection['locked'] == 'true') {
  1742. $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_PROTECTED);
  1743. } else {
  1744. $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1745. }
  1746. }
  1747. if (isset($style->protection['hidden'])) {
  1748. if ((string)$style->protection['hidden'] == 'true') {
  1749. $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_PROTECTED);
  1750. } else {
  1751. $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1752. }
  1753. }
  1754. }
  1755. }
  1756. private static function _readBorder($docBorder, $eleBorder) {
  1757. if (isset($eleBorder["style"])) {
  1758. $docBorder->setBorderStyle((string) $eleBorder["style"]);
  1759. }
  1760. if (isset($eleBorder->color)) {
  1761. $docBorder->getColor()->setARGB(self::_readColor($eleBorder->color));
  1762. }
  1763. }
  1764. private function _parseRichText($is = null) {
  1765. $value = new PHPExcel_RichText();
  1766. if (isset($is->t)) {
  1767. $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $is->t ) );
  1768. } else {
  1769. foreach ($is->r as $run) {
  1770. if (!isset($run->rPr)) {
  1771. $objText = $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) );
  1772. } else {
  1773. $objText = $value->createTextRun( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) );
  1774. if (isset($run->rPr->rFont["val"])) {
  1775. $objText->getFont()->setName((string) $run->rPr->rFont["val"]);
  1776. }
  1777. if (isset($run->rPr->sz["val"])) {
  1778. $objText->getFont()->setSize((string) $run->rPr->sz["val"]);
  1779. }
  1780. if (isset($run->rPr->color)) {
  1781. $objText->getFont()->setColor( new PHPExcel_Style_Color( self::_readColor($run->rPr->color) ) );
  1782. }
  1783. if ( (isset($run->rPr->b["val"]) && ((string) $run->rPr->b["val"] == 'true' || (string) $run->rPr->b["val"] == '1'))
  1784. || (isset($run->rPr->b) && !isset($run->rPr->b["val"])) ) {
  1785. $objText->getFont()->setBold(true);
  1786. }
  1787. if ( (isset($run->rPr->i["val"]) && ((string) $run->rPr->i["val"] == 'true' || (string) $run->rPr->i["val"] == '1'))
  1788. || (isset($run->rPr->i) && !isset($run->rPr->i["val"])) ) {
  1789. $objText->getFont()->setItalic(true);
  1790. }
  1791. if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) {
  1792. $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]);
  1793. if ($vertAlign == 'superscript') {
  1794. $objText->getFont()->setSuperScript(true);
  1795. }
  1796. if ($vertAlign == 'subscript') {
  1797. $objText->getFont()->setSubScript(true);
  1798. }
  1799. }
  1800. if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) {
  1801. $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1802. } else if (isset($run->rPr->u) && isset($run->rPr->u["val"])) {
  1803. $objText->getFont()->setUnderline((string)$run->rPr->u["val"]);
  1804. }
  1805. if ( (isset($run->rPr->strike["val"]) && ((string) $run->rPr->strike["val"] == 'true' || (string) $run->rPr->strike["val"] == '1'))
  1806. || (isset($run->rPr->strike) && !isset($run->rPr->strike["val"])) ) {
  1807. $objText->getFont()->setStrikethrough(true);
  1808. }
  1809. }
  1810. }
  1811. }
  1812. return $value;
  1813. }
  1814. private static function array_item($array, $key = 0) {
  1815. return (isset($array[$key]) ? $array[$key] : null);
  1816. }
  1817. private static function dir_add($base, $add) {
  1818. return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
  1819. }
  1820. private static function toCSSArray($style) {
  1821. $style = str_replace(array("\r","\n"), "", $style);
  1822. $temp = explode(';', $style);
  1823. $style = array();
  1824. foreach ($temp as $item) {
  1825. $item = explode(':', $item);
  1826. if (strpos($item[1], 'px') !== false) {
  1827. $item[1] = str_replace('px', '', $item[1]);
  1828. }
  1829. if (strpos($item[1], 'pt') !== false) {
  1830. $item[1] = str_replace('pt', '', $item[1]);
  1831. $item[1] = PHPExcel_Shared_Font::fontSizeToPixels($item[1]);
  1832. }
  1833. if (strpos($item[1], 'in') !== false) {
  1834. $item[1] = str_replace('in', '', $item[1]);
  1835. $item[1] = PHPExcel_Shared_Font::inchSizeToPixels($item[1]);
  1836. }
  1837. if (strpos($item[1], 'cm') !== false) {
  1838. $item[1] = str_replace('cm', '', $item[1]);
  1839. $item[1] = PHPExcel_Shared_Font::centimeterSizeToPixels($item[1]);
  1840. }
  1841. $style[$item[0]] = $item[1];
  1842. }
  1843. return $style;
  1844. }
  1845. }