PageRenderTime 60ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/Classes/PHPExcel/Reader/Excel2007.php

https://bitbucket.org/crowdguru/phpexcel
PHP | 1999 lines | 1432 code | 267 blank | 300 comment | 512 complexity | 8e1b5c9284a9862d530cbd905e8ffbc7 MD5 | raw file
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2012 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Reader
  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 ##VERSION##, ##DATE##
  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')) {
  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 '<font color="darkgreen">Formula</font><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 '<font color="darkgreen">SHARED FORMULA</font><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 '<font color="darkgreen">SETTING NEW SHARED FORMULA</font><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 '<font color="darkgreen">GETTING SHARED FORMULA</font><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['showGridLines'])) {
  668. $docSheet->setShowGridLines((string)$xmlSheet->sheetViews->sheetView['showGridLines'] ? true : false);
  669. }
  670. if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
  671. $docSheet->setShowRowColHeaders((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'] ? true : false);
  672. }
  673. if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
  674. $docSheet->setRightToLeft((string)$xmlSheet->sheetViews->sheetView['rightToLeft'] ? true : false);
  675. }
  676. if (isset($xmlSheet->sheetViews->sheetView->pane)) {
  677. if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
  678. $docSheet->freezePane( (string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell'] );
  679. } else {
  680. $xSplit = 0;
  681. $ySplit = 0;
  682. if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
  683. $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']);
  684. }
  685. if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
  686. $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']);
  687. }
  688. $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit);
  689. }
  690. }
  691. if (isset($xmlSheet->sheetViews->sheetView->selection)) {
  692. if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
  693. $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref'];
  694. $sqref = explode(' ', $sqref);
  695. $sqref = $sqref[0];
  696. $docSheet->setSelectedCells($sqref);
  697. }
  698. }
  699. }
  700. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) {
  701. if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
  702. $docSheet->getTabColor()->setARGB( (string)$xmlSheet->sheetPr->tabColor['rgb'] );
  703. }
  704. }
  705. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) {
  706. if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && $xmlSheet->sheetPr->outlinePr['summaryRight'] == false) {
  707. $docSheet->setShowSummaryRight(false);
  708. } else {
  709. $docSheet->setShowSummaryRight(true);
  710. }
  711. if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && $xmlSheet->sheetPr->outlinePr['summaryBelow'] == false) {
  712. $docSheet->setShowSummaryBelow(false);
  713. } else {
  714. $docSheet->setShowSummaryBelow(true);
  715. }
  716. }
  717. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) {
  718. if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && $xmlSheet->sheetPr->pageSetUpPr['fitToPage'] == false) {
  719. $docSheet->getPageSetup()->setFitToPage(false);
  720. } else {
  721. $docSheet->getPageSetup()->setFitToPage(true);
  722. }
  723. }
  724. if (isset($xmlSheet->sheetFormatPr)) {
  725. if (isset($xmlSheet->sheetFormatPr['customHeight']) && ((string)$xmlSheet->sheetFormatPr['customHeight'] == '1' || strtolower((string)$xmlSheet->sheetFormatPr['customHeight']) == 'true') && isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
  726. $docSheet->getDefaultRowDimension()->setRowHeight( (float)$xmlSheet->sheetFormatPr['defaultRowHeight'] );
  727. }
  728. if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
  729. $docSheet->getDefaultColumnDimension()->setWidth( (float)$xmlSheet->sheetFormatPr['defaultColWidth'] );
  730. }
  731. }
  732. if (isset($xmlSheet->cols) && !$this->_readDataOnly) {
  733. foreach ($xmlSheet->cols->col as $col) {
  734. for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) {
  735. if ($col["style"] && !$this->_readDataOnly) {
  736. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"]));
  737. }
  738. if ($col["bestFit"]) {
  739. //$docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(true);
  740. }
  741. if ($col["hidden"]) {
  742. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setVisible(false);
  743. }
  744. if ($col["collapsed"]) {
  745. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setCollapsed(true);
  746. }
  747. if ($col["outlineLevel"] > 0) {
  748. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"]));
  749. }
  750. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"]));
  751. if (intval($col["max"]) == 16384) {
  752. break;
  753. }
  754. }
  755. }
  756. }
  757. if (isset($xmlSheet->printOptions) && !$this->_readDataOnly) {
  758. if ($xmlSheet->printOptions['gridLinesSet'] == 'true' && $xmlSheet->printOptions['gridLinesSet'] == '1') {
  759. $docSheet->setShowGridlines(true);
  760. }
  761. if ($xmlSheet->printOptions['gridLines'] == 'true' || $xmlSheet->printOptions['gridLines'] == '1') {
  762. $docSheet->setPrintGridlines(true);
  763. }
  764. if ($xmlSheet->printOptions['horizontalCentered']) {
  765. $docSheet->getPageSetup()->setHorizontalCentered(true);
  766. }
  767. if ($xmlSheet->printOptions['verticalCentered']) {
  768. $docSheet->getPageSetup()->setVerticalCentered(true);
  769. }
  770. }
  771. if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
  772. foreach ($xmlSheet->sheetData->row as $row) {
  773. if ($row["ht"] && !$this->_readDataOnly) {
  774. $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"]));
  775. }
  776. if ($row["hidden"] && !$this->_readDataOnly) {
  777. $docSheet->getRowDimension(intval($row["r"]))->setVisible(false);
  778. }
  779. if ($row["collapsed"]) {
  780. $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(true);
  781. }
  782. if ($row["outlineLevel"] > 0) {
  783. $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"]));
  784. }
  785. if ($row["s"] && !$this->_readDataOnly) {
  786. $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"]));
  787. }
  788. foreach ($row->c as $c) {
  789. $r = (string) $c["r"];
  790. $cellDataType = (string) $c["t"];
  791. $value = null;
  792. $calculatedValue = null;
  793. // Read cell?
  794. if ($this->getReadFilter() !== NULL) {
  795. $coordinates = PHPExcel_Cell::coordinateFromString($r);
  796. if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) {
  797. continue;
  798. }
  799. }
  800. // echo '<b>Reading cell '.$coordinates[0].$coordinates[1].'</b><br />';
  801. // print_r($c);
  802. // echo '<br />';
  803. // echo 'Cell Data Type is '.$cellDataType.': ';
  804. //
  805. // Read cell!
  806. switch ($cellDataType) {
  807. case "s":
  808. // echo 'String<br />';
  809. if ((string)$c->v != '') {
  810. $value = $sharedStrings[intval($c->v)];
  811. if ($value instanceof PHPExcel_RichText) {
  812. $value = clone $value;
  813. }
  814. } else {
  815. $value = '';
  816. }
  817. break;
  818. case "b":
  819. // echo 'Boolean<br />';
  820. if (!isset($c->f)) {
  821. $value = self::_castToBool($c);
  822. } else {
  823. // Formula
  824. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToBool');
  825. if (isset($c->f['t'])) {
  826. $att = array();
  827. $att = $c->f;
  828. $docSheet->getCell($r)->setFormulaAttributes($att);
  829. }
  830. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  831. }
  832. break;
  833. case "inlineStr":
  834. // echo 'Inline String<br />';
  835. $value = $this->_parseRichText($c->is);
  836. break;
  837. case "e":
  838. // echo 'Error<br />';
  839. if (!isset($c->f)) {
  840. $value = self::_castToError($c);
  841. } else {
  842. // Formula
  843. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToError');
  844. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  845. }
  846. break;
  847. default:
  848. // echo 'Default<br />';
  849. if (!isset($c->f)) {
  850. // echo 'Not a Formula<br />';
  851. $value = self::_castToString($c);
  852. } else {
  853. // echo 'Treat as Formula<br />';
  854. // Formula
  855. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToString');
  856. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  857. }
  858. break;
  859. }
  860. // echo 'Value is '.$value.'<br />';
  861. // Check for numeric values
  862. if (is_numeric($value) && $cellDataType != 's') {
  863. if ($value == (int)$value) $value = (int)$value;
  864. elseif ($value == (float)$value) $value = (float)$value;
  865. elseif ($value == (double)$value) $value = (double)$value;
  866. }
  867. // Rich text?
  868. if ($value instanceof PHPExcel_RichText && $this->_readDataOnly) {
  869. $value = $value->getPlainText();
  870. }
  871. $cell = $docSheet->getCell($r);
  872. // Assign value
  873. if ($cellDataType != '') {
  874. $cell->setValueExplicit($value, $cellDataType);
  875. } else {
  876. $cell->setValue($value);
  877. }
  878. if ($calculatedValue !== NULL) {
  879. $cell->setCalculatedValue($calculatedValue);
  880. }
  881. // Style information?
  882. if ($c["s"] && !$this->_readDataOnly) {
  883. // no style index means 0, it seems
  884. $cell->setXfIndex(isset($styles[intval($c["s"])]) ?
  885. intval($c["s"]) : 0);
  886. }
  887. }
  888. }
  889. }
  890. $conditionals = array();
  891. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
  892. foreach ($xmlSheet->conditionalFormatting as $conditional) {
  893. foreach ($conditional->cfRule as $cfRule) {
  894. if (
  895. (
  896. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_NONE ||
  897. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CELLIS ||
  898. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT ||
  899. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
  900. ) && isset($dxfs[intval($cfRule["dxfId"])])
  901. ) {
  902. $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule;
  903. }
  904. }
  905. }
  906. foreach ($conditionals as $ref => $cfRules) {
  907. ksort($cfRules);
  908. $conditionalStyles = array();
  909. foreach ($cfRules as $cfRule) {
  910. $objConditional = new PHPExcel_Style_Conditional();
  911. $objConditional->setConditionType((string)$cfRule["type"]);
  912. $objConditional->setOperatorType((string)$cfRule["operator"]);
  913. if ((string)$cfRule["text"] != '') {
  914. $objConditional->setText((string)$cfRule["text"]);
  915. }
  916. if (count($cfRule->formula) > 1) {
  917. foreach ($cfRule->formula as $formula) {
  918. $objConditional->addCondition((string)$formula);
  919. }
  920. } else {
  921. $objConditional->addCondition((string)$cfRule->formula);
  922. }
  923. $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]);
  924. $conditionalStyles[] = $objConditional;
  925. }
  926. // Extract all cell references in $ref
  927. $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($ref);
  928. foreach ($aReferences as $reference) {
  929. $docSheet->getStyle($reference)->setConditionalStyles($conditionalStyles);
  930. }
  931. }
  932. }
  933. $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells");
  934. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  935. foreach ($aKeys as $key) {
  936. $method = "set" . ucfirst($key);
  937. $docSheet->getProtection()->$method($xmlSheet->sheetProtection[$key] == "true");
  938. }
  939. }
  940. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  941. $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], true);
  942. if ($xmlSheet->protectedRanges->protectedRange) {
  943. foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
  944. $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true);
  945. }
  946. }
  947. }
  948. if ($xmlSheet && $xmlSheet->autoFilter && !$this->_readDataOnly) {
  949. $docSheet->setAutoFilter((string) $xmlSheet->autoFilter["ref"]);
  950. }
  951. if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->_readDataOnly) {
  952. foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
  953. $docSheet->mergeCells((string) $mergeCell["ref"]);
  954. }
  955. }
  956. if ($xmlSheet && $xmlSheet->pageMargins && !$this->_readDataOnly) {
  957. $docPageMargins = $docSheet->getPageMargins();
  958. $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"]));
  959. $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"]));
  960. $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"]));
  961. $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"]));
  962. $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"]));
  963. $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"]));
  964. }
  965. if ($xmlSheet && $xmlSheet->pageSetup && !$this->_readDataOnly) {
  966. $docPageSetup = $docSheet->getPageSetup();
  967. if (isset($xmlSheet->pageSetup["orientation"])) {
  968. $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]);
  969. }
  970. if (isset($xmlSheet->pageSetup["paperSize"])) {
  971. $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"]));
  972. }
  973. if (isset($xmlSheet->pageSetup["scale"])) {
  974. $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), false);
  975. }
  976. if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) {
  977. $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), false);
  978. }
  979. if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) {
  980. $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), false);
  981. }
  982. if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) &&
  983. ((string)$xmlSheet->pageSetup["useFirstPageNumber"] == 'true' || (string)$xmlSheet->pageSetup["useFirstPageNumber"] == '1')) {
  984. $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"]));
  985. }
  986. }
  987. if ($xmlSheet && $xmlSheet->headerFooter && !$this->_readDataOnly) {
  988. $docHeaderFooter = $docSheet->getHeaderFooter();
  989. if (isset($xmlSheet->headerFooter["differentOddEven"]) &&
  990. ((string)$xmlSheet->headerFooter["differentOddEven"] == 'true' || (string)$xmlSheet->headerFooter["differentOddEven"] == '1')) {
  991. $docHeaderFooter->setDifferentOddEven(true);
  992. } else {
  993. $docHeaderFooter->setDifferentOddEven(false);
  994. }
  995. if (isset($xmlSheet->headerFooter["differentFirst"]) &&
  996. ((string)$xmlSheet->headerFooter["differentFirst"] == 'true' || (string)$xmlSheet->headerFooter["differentFirst"] == '1')) {
  997. $docHeaderFooter->setDifferentFirst(true);
  998. } else {
  999. $docHeaderFooter->setDifferentFirst(false);
  1000. }
  1001. if (isset($xmlSheet->headerFooter["scaleWithDoc"]) &&
  1002. ((string)$xmlSheet->headerFooter["scaleWithDoc"] == 'false' || (string)$xmlSheet->headerFooter["scaleWithDoc"] == '0')) {
  1003. $docHeaderFooter->setScaleWithDocument(false);
  1004. } else {
  1005. $docHeaderFooter->setScaleWithDocument(true);
  1006. }
  1007. if (isset($xmlSheet->headerFooter["alignWithMargins"]) &&
  1008. ((string)$xmlSheet->headerFooter["alignWithMargins"] == 'false' || (string)$xmlSheet->headerFooter["alignWithMargins"] == '0')) {
  1009. $docHeaderFooter->setAlignWithMargins(false);
  1010. } else {
  1011. $docHeaderFooter->setAlignWithMargins(true);
  1012. }
  1013. $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
  1014. $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
  1015. $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
  1016. $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
  1017. $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
  1018. $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
  1019. }
  1020. if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->_readDataOnly) {
  1021. foreach ($xmlSheet->rowBreaks->brk as $brk) {
  1022. if ($brk["man"]) {
  1023. $docSheet->setBreak("A$brk[id]", PHPExcel_Worksheet::BREAK_ROW);
  1024. }
  1025. }
  1026. }
  1027. if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->_readDataOnly) {
  1028. foreach ($xmlSheet->colBreaks->brk as $brk) {
  1029. if ($brk["man"]) {
  1030. $docSheet->setBreak(PHPExcel_Cell::stringFromColumnIndex($brk["id"]) . "1", PHPExcel_Worksheet::BREAK_COLUMN);
  1031. }
  1032. }
  1033. }
  1034. if ($xmlSheet && $xmlSheet->dataValidations && !$this->_readDataOnly) {
  1035. foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
  1036. // Uppercase coordinate
  1037. $range = strtoupper($dataValidation["sqref"]);
  1038. $rangeSet = explode(' ',$range);
  1039. foreach($rangeSet as $range) {
  1040. $stRange = $docSheet->shrinkRangeToFit($range);
  1041. // Extract all cell references in $range
  1042. $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($stRange);
  1043. foreach ($aReferences as $reference) {
  1044. // Create validation
  1045. $docValidation = $docSheet->getCell($reference)->getDataValidation();
  1046. $docValidation->setType((string) $dataValidation["type"]);
  1047. $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]);
  1048. $docValidation->setOperator((string) $dataValidation["operator"]);
  1049. $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0);
  1050. $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0);
  1051. $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0);
  1052. $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0);
  1053. $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]);
  1054. $docValidation->setError((string) $dataValidation["error"]);
  1055. $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]);
  1056. $docValidation->setPrompt((string) $dataValidation["prompt"]);
  1057. $docValidation->setFormula1((string) $dataValidation->formula1);
  1058. $docValidation->setFormula2((string) $dataValidation->formula2);
  1059. }
  1060. }
  1061. }
  1062. }
  1063. // Add hyperlinks
  1064. $hyperlinks = array();
  1065. if (!$this->_readDataOnly) {
  1066. // Locate hyperlink relations
  1067. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1068. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1069. foreach ($relsWorksheet->Relationship as $ele) {
  1070. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") {
  1071. $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"];
  1072. }
  1073. }
  1074. }
  1075. // Loop through hyperlinks
  1076. if ($xmlSheet && $xmlSheet->hyperlinks) {
  1077. foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
  1078. // Link url
  1079. $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  1080. foreach (PHPExcel_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
  1081. $cell = $docSheet->getCell( $cellReference );
  1082. if (isset($linkRel['id'])) {
  1083. $cell->getHyperlink()->setUrl( $hyperlinks[ (string)$linkRel['id'] ] );
  1084. }
  1085. if (isset($hyperlink['location'])) {
  1086. $cell->getHyperlink()->setUrl( 'sheet://' . (string)$hyperlink['location'] );
  1087. }
  1088. // Tooltip
  1089. if (isset($hyperlink['tooltip'])) {
  1090. $cell->getHyperlink()->setTooltip( (string)$hyperlink['tooltip'] );
  1091. }
  1092. }
  1093. }
  1094. }
  1095. }
  1096. // Add comments
  1097. $comments = array();
  1098. $vmlComments = array();
  1099. if (!$this->_readDataOnly) {
  1100. // Locate comment relations
  1101. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1102. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1103. foreach ($relsWorksheet->Relationship as $ele) {
  1104. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") {
  1105. $comments[(string)$ele["Id"]] = (string)$ele["Target"];
  1106. }
  1107. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1108. $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"];
  1109. }
  1110. }
  1111. }
  1112. // Loop through comments
  1113. foreach ($comments as $relName => $relPath) {
  1114. // Load comments file
  1115. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  1116. $commentsFile = simplexml_load_string($this->_getFromZipArchive($zip, $relPath) );
  1117. // Utility variables
  1118. $authors = array();
  1119. // Loop through authors
  1120. foreach ($commentsFile->authors->author as $author) {
  1121. $authors[] = (string)$author;
  1122. }
  1123. // Loop through contents
  1124. foreach ($commentsFile->commentList->comment as $comment) {
  1125. $docSheet->getComment( (string)$comment['ref'] )->setAuthor( $authors[(string)$comment['authorId']] );
  1126. $docSheet->getComment( (string)$comment['ref'] )->setText( $this->_parseRichText($comment->text) );
  1127. }
  1128. }
  1129. // Loop through VML comments
  1130. foreach ($vmlComments as $relName => $relPath) {
  1131. // Load VML comments file
  1132. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  1133. $vmlCommentsFile = simplexml_load_string( $this->_getFromZipArchive($zip, $relPath) );
  1134. $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1135. $shapes = $vmlCommentsFile->xpath('//v:shape');
  1136. foreach ($shapes as $shape) {
  1137. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1138. if (isset($shape['style'])) {
  1139. $style = (string)$shape['style'];
  1140. $fillColor = strtoupper( substr( (string)$shape['fillcolor'], 1 ) );
  1141. $column = null;
  1142. $row = null;
  1143. $clientData = $shape->xpath('.//x:ClientData');
  1144. if (is_array($clientData) && !empty($clientData)) {
  1145. $clientData = $clientData[0];
  1146. if ( isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note' ) {
  1147. $temp = $clientData->xpath('.//x:Row');
  1148. if (is_array($temp)) $row = $temp[0];
  1149. $temp = $clientData->xpath('.//x:Column');
  1150. if (is_array($temp)) $column = $temp[0];
  1151. }
  1152. }
  1153. if (($column !== NULL) && ($row !== NULL)) {
  1154. // Set comment properties
  1155. $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1);
  1156. $comment->getFillColor()->setRGB( $fillColor );
  1157. // Parse style
  1158. $styleArray = explode(';', str_replace(' ', '', $style));
  1159. foreach ($styleArray as $stylePair) {
  1160. $stylePair = explode(':', $stylePair);
  1161. if ($stylePair[0] == 'margin-left') $comment->setMarginLeft($stylePair[1]);
  1162. if ($stylePair[0] == 'margin-top') $comment->setMarginTop($stylePair[1]);
  1163. if ($stylePair[0] == 'width') $comment->setWidth($stylePair[1]);
  1164. if ($stylePair[0] == 'height') $comment->setHeight($stylePair[1]);
  1165. if ($stylePair[0] == 'visibility') $comment->setVisible( $stylePair[1] == 'visible' );
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. // Header/footer images
  1172. if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->_readDataOnly) {
  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. $vmlRelationship = '';
  1176. foreach ($relsWorksheet->Relationship as $ele) {
  1177. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1178. $vmlRelationship = self::dir_add("$dir/$fileWorksheet", $ele["Target"]);
  1179. }
  1180. }
  1181. if ($vmlRelationship != '') {
  1182. // Fetch linked images
  1183. $relsVML = simplexml_load_string($this->_getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels' )); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1184. $drawings = array();
  1185. foreach ($relsVML->Relationship as $ele) {
  1186. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1187. $drawings[(string) $ele["Id"]] = self::dir_add($vmlRelationship, $ele["Target"]);
  1188. }
  1189. }
  1190. // Fetch VML document
  1191. $vmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $vmlRelationship));
  1192. $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1193. $hfImages = array();
  1194. $shapes = $vmlDrawing->xpath('//v:shape');
  1195. foreach ($shapes as $shape) {
  1196. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1197. $imageData = $shape->xpath('//v:imagedata');
  1198. $imageData = $imageData[0];
  1199. $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
  1200. $style = self::toCSSArray( (string)$shape['style'] );
  1201. $hfImages[ (string)$shape['id'] ] = new PHPExcel_Worksheet_HeaderFooterDrawing();
  1202. if (isset($imageData['title'])) {
  1203. $hfImages[ (string)$shape['id'] ]->setName( (string)$imageData['title'] );
  1204. }
  1205. $hfImages[ (string)$shape['id'] ]->setPath("zip://$pFilename#" . $drawings[(string)$imageData['relid']], false);
  1206. $hfImages[ (string)$shape['id'] ]->setResizeProportional(false);
  1207. $hfImages[ (string)$shape['id'] ]->setWidth($style['width']);
  1208. $hfImages[ (string)$shape['id'] ]->setHeight($style['height']);
  1209. $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']);
  1210. $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']);
  1211. $hfImages[ (string)$shape['id'] ]->setResizeProportional(true);
  1212. }
  1213. $docSheet->getHeaderFooter()->setImages($hfImages);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. // TODO: Make sure drawings and graph are loaded differently!
  1219. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1220. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1221. $drawings = array();
  1222. foreach ($relsWorksheet->Relationship as $ele) {
  1223. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") {
  1224. $drawings[(string) $ele["Id"]] = self::dir_add("$dir/$fileWorksheet", $ele["Target"]);
  1225. }
  1226. }
  1227. if ($xmlSheet->drawing && !$this->_readDataOnly) {
  1228. foreach ($xmlSheet->drawing as $drawing) {
  1229. $fileDrawing = $drawings[(string) self::array_item($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  1230. $relsDrawing = simplexml_load_string($this->_getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1231. $images = array();
  1232. if ($relsDrawing && $relsDrawing->Relationship) {
  1233. foreach ($relsDrawing->Relationship as $ele) {
  1234. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1235. $images[(string) $ele["Id"]] = self::dir_add($fileDrawing, $ele["Target"]);
  1236. } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") {
  1237. if ($this->_includeCharts) {
  1238. $charts[self::dir_add($fileDrawing, $ele["Target"])] = array('id' => (string) $ele["Id"],
  1239. 'sheet' => $docSheet->getTitle()
  1240. );
  1241. }
  1242. }
  1243. }
  1244. }
  1245. $xmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $fileDrawing))->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
  1246. if ($xmlDrawing->oneCellAnchor) {
  1247. foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
  1248. if ($oneCellAnchor->pic->blipFill) {
  1249. $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1250. $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1251. $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1252. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1253. $objDrawing->setName((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1254. $objDrawing->setDescription((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1255. $objDrawing->setPath("zip://$pFilename#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1256. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1));
  1257. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff));
  1258. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
  1259. $objDrawing->setResizeProportional(false);
  1260. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx")));
  1261. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy")));
  1262. if ($xfrm) {
  1263. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot")));
  1264. }
  1265. if ($outerShdw) {
  1266. $shadow = $objDrawing->getShadow();
  1267. $shadow->setVisible(true);
  1268. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad")));
  1269. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist")));
  1270. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir")));
  1271. $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn"));
  1272. $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val"));
  1273. $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1274. }
  1275. $objDrawing->setWorksheet($docSheet);
  1276. } else {
  1277. $coordinates = PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1);
  1278. $offsetX = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff);
  1279. $offsetY = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
  1280. $width = PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx"));
  1281. $height = PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy"));
  1282. }
  1283. }
  1284. }
  1285. if ($xmlDrawing->twoCellAnchor) {
  1286. foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
  1287. if ($twoCellAnchor->pic->blipFill) {
  1288. $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1289. $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1290. $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1291. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1292. $objDrawing->setName((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1293. $objDrawing->setDescription((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1294. $objDrawing->setPath("zip://$pFilename#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1295. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1));
  1296. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff));
  1297. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
  1298. $objDrawing->setResizeProportional(false);
  1299. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cx")));
  1300. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cy")));
  1301. if ($xfrm) {
  1302. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot")));
  1303. }
  1304. if ($outerShdw) {
  1305. $shadow = $objDrawing->getShadow();
  1306. $shadow->setVisible(true);
  1307. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad")));
  1308. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist")));
  1309. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir")));
  1310. $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn"));
  1311. $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val"));
  1312. $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1313. }
  1314. $objDrawing->setWorksheet($docSheet);
  1315. } elseif($this->_includeCharts) {
  1316. $fromCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1);
  1317. $fromOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff);
  1318. $fromOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
  1319. $toCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1);
  1320. $toOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff);
  1321. $toOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
  1322. $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic;
  1323. $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart;
  1324. $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships");
  1325. $chartDetails[$docSheet->getTitle().'!'.$thisChart] =
  1326. array( 'fromCoordinate' => $fromCoordinate,
  1327. 'fromOffsetX' => $fromOffsetX,
  1328. 'fromOffsetY' => $fromOffsetY,
  1329. 'toCoordinate' => $toCoordinate,
  1330. 'toOffsetX' => $toOffsetX,
  1331. 'toOffsetY' => $toOffsetY,
  1332. 'worksheetTitle' => $docSheet->getTitle()
  1333. );
  1334. }
  1335. }
  1336. }
  1337. }
  1338. }
  1339. }
  1340. // Loop through definedNames
  1341. if ($xmlWorkbook->definedNames) {
  1342. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1343. // Extract range
  1344. $extractedRange = (string)$definedName;
  1345. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1346. if (($spos = strpos($extractedRange,'!')) !== false) {
  1347. $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos));
  1348. } else {
  1349. $extractedRange = str_replace('$', '', $extractedRange);
  1350. }
  1351. // Valid range?
  1352. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1353. continue;
  1354. }
  1355. // Some definedNames are only applicable if we are on the same sheet...
  1356. if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) {
  1357. // Switch on type
  1358. switch ((string)$definedName['name']) {
  1359. case '_xlnm._FilterDatabase':
  1360. $docSheet->setAutoFilter($extractedRange);
  1361. break;
  1362. case '_xlnm.Print_Titles':
  1363. // Split $extractedRange
  1364. $extractedRange = explode(',', $extractedRange);
  1365. // Set print titles
  1366. foreach ($extractedRange as $range) {
  1367. $matches = array();
  1368. // check for repeating columns, e g. 'A:A' or 'A:D'
  1369. if (preg_match('/^([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
  1370. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2]));
  1371. }
  1372. // check for repeating rows, e.g. '1:1' or '1:5'
  1373. elseif (preg_match('/^(\d+)\:(\d+)$/', $range, $matches)) {
  1374. $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2]));
  1375. }
  1376. }
  1377. break;
  1378. case '_xlnm.Print_Area':
  1379. $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma?
  1380. $newRangeSets = array();
  1381. foreach($rangeSets as $rangeSet) {
  1382. $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark?
  1383. $rangeSet = isset($range[1]) ? $range[1] : $range[0];
  1384. $newRangeSets[] = str_replace('$', '', $rangeSet);
  1385. }
  1386. $docSheet->getPageSetup()->setPrintArea(implode(',',$newRangeSets));
  1387. break;
  1388. default:
  1389. break;
  1390. }
  1391. }
  1392. }
  1393. }
  1394. // Next sheet id
  1395. ++$sheetId;
  1396. }
  1397. // Loop through definedNames
  1398. if ($xmlWorkbook->definedNames) {
  1399. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1400. // Extract range
  1401. $extractedRange = (string)$definedName;
  1402. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1403. if (($spos = strpos($extractedRange,'!')) !== false) {
  1404. $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos));
  1405. } else {
  1406. $extractedRange = str_replace('$', '', $extractedRange);
  1407. }
  1408. // Valid range?
  1409. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1410. continue;
  1411. }
  1412. // Some definedNames are only applicable if we are on the same sheet...
  1413. if ((string)$definedName['localSheetId'] != '') {
  1414. // Local defined name
  1415. // Switch on type
  1416. switch ((string)$definedName['name']) {
  1417. case '_xlnm._FilterDatabase':
  1418. case '_xlnm.Print_Titles':
  1419. case '_xlnm.Print_Area':
  1420. break;
  1421. default:
  1422. $range = explode('!', (string)$definedName);
  1423. if (count($range) == 2) {
  1424. $range[0] = str_replace("''", "'", $range[0]);
  1425. $range[0] = str_replace("'", "", $range[0]);
  1426. if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
  1427. $extractedRange = str_replace('$', '', $range[1]);
  1428. $scope = $docSheet->getParent()->getSheet((string)$definedName['localSheetId']);
  1429. $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope) );
  1430. }
  1431. }
  1432. break;
  1433. }
  1434. } else if (!isset($definedName['localSheetId'])) {
  1435. // "Global" definedNames
  1436. $locatedSheet = null;
  1437. $extractedSheetName = '';
  1438. if (strpos( (string)$definedName, '!' ) !== false) {
  1439. // Extract sheet name
  1440. $extractedSheetName = PHPExcel_Worksheet::extractSheetTitle( (string)$definedName, true );
  1441. $extractedSheetName = $extractedSheetName[0];
  1442. // Locate sheet
  1443. $locatedSheet = $excel->getSheetByName($extractedSheetName);
  1444. // Modify range
  1445. $range = explode('!', $extractedRange);
  1446. $extractedRange = isset($range[1]) ? $range[1] : $range[0];
  1447. }
  1448. if ($locatedSheet !== NULL) {
  1449. $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false) );
  1450. }
  1451. }
  1452. }
  1453. }
  1454. }
  1455. if (!$this->_readDataOnly) {
  1456. // active sheet index
  1457. $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index
  1458. // keep active sheet index if sheet is still loaded, else first sheet is set as the active
  1459. if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
  1460. $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
  1461. } else {
  1462. if ($excel->getSheetCount() == 0) {
  1463. $excel->createSheet();
  1464. }
  1465. $excel->setActiveSheetIndex(0);
  1466. }
  1467. }
  1468. break;
  1469. }
  1470. }
  1471. if (!$this->_readDataOnly) {
  1472. $contentTypes = simplexml_load_string($this->_getFromZipArchive($zip, "[Content_Types].xml"));
  1473. foreach ($contentTypes->Override as $contentType) {
  1474. switch ($contentType["ContentType"]) {
  1475. case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml":
  1476. if ($this->_includeCharts) {
  1477. $chartEntryRef = ltrim($contentType['PartName'],'/');
  1478. $chartElements = simplexml_load_string($this->_getFromZipArchive($zip, $chartEntryRef));
  1479. $objChart = PHPExcel_Reader_Excel2007_Chart::readChart($chartElements,basename($chartEntryRef,'.xml'));
  1480. // echo 'Chart ',$chartEntryRef,'<br />';
  1481. // var_dump($charts[$chartEntryRef]);
  1482. //
  1483. if (isset($charts[$chartEntryRef])) {
  1484. $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id'];
  1485. // echo 'Position Ref ',$chartPositionRef,'<br />';
  1486. if (isset($chartDetails[$chartPositionRef])) {
  1487. // var_dump($chartDetails[$chartPositionRef]);
  1488. $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
  1489. $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
  1490. $objChart->setTopLeftPosition( $chartDetails[$chartPositionRef]['fromCoordinate'],
  1491. $chartDetails[$chartPositionRef]['fromOffsetX'],
  1492. $chartDetails[$chartPositionRef]['fromOffsetY']
  1493. );
  1494. $objChart->setBottomRightPosition( $chartDetails[$chartPositionRef]['toCoordinate'],
  1495. $chartDetails[$chartPositionRef]['toOffsetX'],
  1496. $chartDetails[$chartPositionRef]['toOffsetY']
  1497. );
  1498. }
  1499. }
  1500. }
  1501. }
  1502. }
  1503. }
  1504. $zip->close();
  1505. return $excel;
  1506. }
  1507. private static function _readColor($color, $background=false) {
  1508. if (isset($color["rgb"])) {
  1509. return (string)$color["rgb"];
  1510. } else if (isset($color["indexed"])) {
  1511. return PHPExcel_Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB();
  1512. } else if (isset($color["theme"])) {
  1513. if (self::$_theme !== NULL) {
  1514. $returnColour = self::$_theme->getColourByIndex((int)$color["theme"]);
  1515. if (isset($color["tint"])) {
  1516. $tintAdjust = (float) $color["tint"];
  1517. $returnColour = PHPExcel_Style_Color::changeBrightness($returnColour, $tintAdjust);
  1518. }
  1519. return 'FF'.$returnColour;
  1520. }
  1521. }
  1522. if ($background) {
  1523. return 'FFFFFFFF';
  1524. }
  1525. return 'FF000000';
  1526. }
  1527. private static function _readStyle($docStyle, $style) {
  1528. // format code
  1529. if (isset($style->numFmt)) {
  1530. $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
  1531. }
  1532. // font
  1533. if (isset($style->font)) {
  1534. $docStyle->getFont()->setName((string) $style->font->name["val"]);
  1535. $docStyle->getFont()->setSize((string) $style->font->sz["val"]);
  1536. if (isset($style->font->b)) {
  1537. $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || $style->font->b["val"] == 'true' || $style->font->b["val"] == '1');
  1538. }
  1539. if (isset($style->font->i)) {
  1540. $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || $style->font->i["val"] == 'true' || $style->font->i["val"] == '1');
  1541. }
  1542. if (isset($style->font->strike)) {
  1543. $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || $style->font->strike["val"] == 'true' || $style->font->strike["val"] == '1');
  1544. }
  1545. $docStyle->getFont()->getColor()->setARGB(self::_readColor($style->font->color));
  1546. if (isset($style->font->u) && !isset($style->font->u["val"])) {
  1547. $docStyle->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1548. } else if (isset($style->font->u) && isset($style->font->u["val"])) {
  1549. $docStyle->getFont()->setUnderline((string)$style->font->u["val"]);
  1550. }
  1551. if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) {
  1552. $vertAlign = strtolower((string)$style->font->vertAlign["val"]);
  1553. if ($vertAlign == 'superscript') {
  1554. $docStyle->getFont()->setSuperScript(true);
  1555. }
  1556. if ($vertAlign == 'subscript') {
  1557. $docStyle->getFont()->setSubScript(true);
  1558. }
  1559. }
  1560. }
  1561. // fill
  1562. if (isset($style->fill)) {
  1563. if ($style->fill->gradientFill) {
  1564. $gradientFill = $style->fill->gradientFill[0];
  1565. if(!empty($gradientFill["type"])) {
  1566. $docStyle->getFill()->setFillType((string) $gradientFill["type"]);
  1567. }
  1568. $docStyle->getFill()->setRotation(floatval($gradientFill["degree"]));
  1569. $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  1570. $docStyle->getFill()->getStartColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=0]"))->color) );
  1571. $docStyle->getFill()->getEndColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=1]"))->color) );
  1572. } elseif ($style->fill->patternFill) {
  1573. $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid';
  1574. $docStyle->getFill()->setFillType($patternType);
  1575. if ($style->fill->patternFill->fgColor) {
  1576. $docStyle->getFill()->getStartColor()->setARGB(self::_readColor($style->fill->patternFill->fgColor,true));
  1577. } else {
  1578. $docStyle->getFill()->getStartColor()->setARGB('FF000000');
  1579. }
  1580. if ($style->fill->patternFill->bgColor) {
  1581. $docStyle->getFill()->getEndColor()->setARGB(self::_readColor($style->fill->patternFill->bgColor,true));
  1582. }
  1583. }
  1584. }
  1585. // border
  1586. if (isset($style->border)) {
  1587. $diagonalUp = false;
  1588. $diagonalDown = false;
  1589. if ($style->border["diagonalUp"] == 'true' || $style->border["diagonalUp"] == 1) {
  1590. $diagonalUp = true;
  1591. }
  1592. if ($style->border["diagonalDown"] == 'true' || $style->border["diagonalDown"] == 1) {
  1593. $diagonalDown = true;
  1594. }
  1595. if ($diagonalUp == false && $diagonalDown == false) {
  1596. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE);
  1597. } elseif ($diagonalUp == true && $diagonalDown == false) {
  1598. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP);
  1599. } elseif ($diagonalUp == false && $diagonalDown == true) {
  1600. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN);
  1601. } elseif ($diagonalUp == true && $diagonalDown == true) {
  1602. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH);
  1603. }
  1604. self::_readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
  1605. self::_readBorder($docStyle->getBorders()->getRight(), $style->border->right);
  1606. self::_readBorder($docStyle->getBorders()->getTop(), $style->border->top);
  1607. self::_readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
  1608. self::_readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
  1609. }
  1610. // alignment
  1611. if (isset($style->alignment)) {
  1612. $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]);
  1613. $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]);
  1614. $textRotation = 0;
  1615. if ((int)$style->alignment["textRotation"] <= 90) {
  1616. $textRotation = (int)$style->alignment["textRotation"];
  1617. } else if ((int)$style->alignment["textRotation"] > 90) {
  1618. $textRotation = 90 - (int)$style->alignment["textRotation"];
  1619. }
  1620. $docStyle->getAlignment()->setTextRotation(intval($textRotation));
  1621. $docStyle->getAlignment()->setWrapText( (string)$style->alignment["wrapText"] == "true" || (string)$style->alignment["wrapText"] == "1" );
  1622. $docStyle->getAlignment()->setShrinkToFit( (string)$style->alignment["shrinkToFit"] == "true" || (string)$style->alignment["shrinkToFit"] == "1" );
  1623. $docStyle->getAlignment()->setIndent( intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0 );
  1624. }
  1625. // protection
  1626. if (isset($style->protection)) {
  1627. if (isset($style->protection['locked'])) {
  1628. if ((string)$style->protection['locked'] == 'true') {
  1629. $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_PROTECTED);
  1630. } else {
  1631. $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1632. }
  1633. }
  1634. if (isset($style->protection['hidden'])) {
  1635. if ((string)$style->protection['hidden'] == 'true') {
  1636. $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_PROTECTED);
  1637. } else {
  1638. $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1639. }
  1640. }
  1641. }
  1642. }
  1643. private static function _readBorder($docBorder, $eleBorder) {
  1644. if (isset($eleBorder["style"])) {
  1645. $docBorder->setBorderStyle((string) $eleBorder["style"]);
  1646. }
  1647. if (isset($eleBorder->color)) {
  1648. $docBorder->getColor()->setARGB(self::_readColor($eleBorder->color));
  1649. }
  1650. }
  1651. private function _parseRichText($is = null) {
  1652. $value = new PHPExcel_RichText();
  1653. if (isset($is->t)) {
  1654. $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $is->t ) );
  1655. } else {
  1656. foreach ($is->r as $run) {
  1657. if (!isset($run->rPr)) {
  1658. $objText = $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) );
  1659. } else {
  1660. $objText = $value->createTextRun( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) );
  1661. if (isset($run->rPr->rFont["val"])) {
  1662. $objText->getFont()->setName((string) $run->rPr->rFont["val"]);
  1663. }
  1664. if (isset($run->rPr->sz["val"])) {
  1665. $objText->getFont()->setSize((string) $run->rPr->sz["val"]);
  1666. }
  1667. if (isset($run->rPr->color)) {
  1668. $objText->getFont()->setColor( new PHPExcel_Style_Color( self::_readColor($run->rPr->color) ) );
  1669. }
  1670. if ( (isset($run->rPr->b["val"]) && ((string) $run->rPr->b["val"] == 'true' || (string) $run->rPr->b["val"] == '1'))
  1671. || (isset($run->rPr->b) && !isset($run->rPr->b["val"])) ) {
  1672. $objText->getFont()->setBold(true);
  1673. }
  1674. if ( (isset($run->rPr->i["val"]) && ((string) $run->rPr->i["val"] == 'true' || (string) $run->rPr->i["val"] == '1'))
  1675. || (isset($run->rPr->i) && !isset($run->rPr->i["val"])) ) {
  1676. $objText->getFont()->setItalic(true);
  1677. }
  1678. if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) {
  1679. $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]);
  1680. if ($vertAlign == 'superscript') {
  1681. $objText->getFont()->setSuperScript(true);
  1682. }
  1683. if ($vertAlign == 'subscript') {
  1684. $objText->getFont()->setSubScript(true);
  1685. }
  1686. }
  1687. if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) {
  1688. $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1689. } else if (isset($run->rPr->u) && isset($run->rPr->u["val"])) {
  1690. $objText->getFont()->setUnderline((string)$run->rPr->u["val"]);
  1691. }
  1692. if ( (isset($run->rPr->strike["val"]) && ((string) $run->rPr->strike["val"] == 'true' || (string) $run->rPr->strike["val"] == '1'))
  1693. || (isset($run->rPr->strike) && !isset($run->rPr->strike["val"])) ) {
  1694. $objText->getFont()->setStrikethrough(true);
  1695. }
  1696. }
  1697. }
  1698. }
  1699. return $value;
  1700. }
  1701. private static function array_item($array, $key = 0) {
  1702. return (isset($array[$key]) ? $array[$key] : null);
  1703. }
  1704. private static function dir_add($base, $add) {
  1705. return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
  1706. }
  1707. private static function toCSSArray($style) {
  1708. $style = str_replace(array("\r","\n"), "", $style);
  1709. $temp = explode(';', $style);
  1710. $style = array();
  1711. foreach ($temp as $item) {
  1712. $item = explode(':', $item);
  1713. if (strpos($item[1], 'px') !== false) {
  1714. $item[1] = str_replace('px', '', $item[1]);
  1715. }
  1716. if (strpos($item[1], 'pt') !== false) {
  1717. $item[1] = str_replace('pt', '', $item[1]);
  1718. $item[1] = PHPExcel_Shared_Font::fontSizeToPixels($item[1]);
  1719. }
  1720. if (strpos($item[1], 'in') !== false) {
  1721. $item[1] = str_replace('in', '', $item[1]);
  1722. $item[1] = PHPExcel_Shared_Font::inchSizeToPixels($item[1]);
  1723. }
  1724. if (strpos($item[1], 'cm') !== false) {
  1725. $item[1] = str_replace('cm', '', $item[1]);
  1726. $item[1] = PHPExcel_Shared_Font::centimeterSizeToPixels($item[1]);
  1727. }
  1728. $style[$item[0]] = $item[1];
  1729. }
  1730. return $style;
  1731. }
  1732. }