Excel2007.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2011 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 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.7.6, 2011-02-27
  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 - 2011 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. * Restrict which sheets should be loaded?
  54. * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
  55. *
  56. * @var array of string
  57. */
  58. private $_loadSheetsOnly = null;
  59. /**
  60. * PHPExcel_Reader_IReadFilter instance
  61. *
  62. * @var PHPExcel_Reader_IReadFilter
  63. */
  64. private $_readFilter = null;
  65. /**
  66. * PHPExcel_ReferenceHelper instance
  67. *
  68. * @var PHPExcel_ReferenceHelper
  69. */
  70. private $_referenceHelper = null;
  71. /**
  72. * PHPExcel_Reader_Excel2007_Theme instance
  73. *
  74. * @var PHPExcel_Reader_Excel2007_Theme
  75. */
  76. private static $_theme = null;
  77. /**
  78. * Read data only?
  79. * If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
  80. * If false (the default) it will read data and formatting.
  81. *
  82. * @return boolean
  83. */
  84. public function getReadDataOnly() {
  85. return $this->_readDataOnly;
  86. }
  87. /**
  88. * Set read data only
  89. * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
  90. * Set to false (the default) to advise the Reader to read both data and formatting for cells.
  91. *
  92. * @param boolean $pValue
  93. *
  94. * @return PHPExcel_Reader_Excel2007
  95. */
  96. public function setReadDataOnly($pValue = false) {
  97. $this->_readDataOnly = $pValue;
  98. return $this;
  99. }
  100. /**
  101. * Get which sheets to load
  102. * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
  103. * indicating that all worksheets in the workbook should be loaded.
  104. *
  105. * @return mixed
  106. */
  107. public function getLoadSheetsOnly()
  108. {
  109. return $this->_loadSheetsOnly;
  110. }
  111. /**
  112. * Set which sheets to load
  113. *
  114. * @param mixed $value
  115. * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
  116. * If NULL, then it tells the Reader to read all worksheets in the workbook
  117. *
  118. * @return PHPExcel_Reader_Excel2007
  119. */
  120. public function setLoadSheetsOnly($value = null)
  121. {
  122. $this->_loadSheetsOnly = is_array($value) ?
  123. $value : array($value);
  124. return $this;
  125. }
  126. /**
  127. * Set all sheets to load
  128. * Tells the Reader to load all worksheets from the workbook.
  129. *
  130. * @return PHPExcel_Reader_Excel2007
  131. */
  132. public function setLoadAllSheets()
  133. {
  134. $this->_loadSheetsOnly = null;
  135. return $this;
  136. }
  137. /**
  138. * Read filter
  139. *
  140. * @return PHPExcel_Reader_IReadFilter
  141. */
  142. public function getReadFilter() {
  143. return $this->_readFilter;
  144. }
  145. /**
  146. * Set read filter
  147. *
  148. * @param PHPExcel_Reader_IReadFilter $pValue
  149. * @return PHPExcel_Reader_Excel2007
  150. */
  151. public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
  152. $this->_readFilter = $pValue;
  153. return $this;
  154. }
  155. /**
  156. * Create a new PHPExcel_Reader_Excel2007 instance
  157. */
  158. public function __construct() {
  159. $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter();
  160. $this->_referenceHelper = PHPExcel_ReferenceHelper::getInstance();
  161. }
  162. /**
  163. * Can the current PHPExcel_Reader_IReader read the file?
  164. *
  165. * @param string $pFileName
  166. * @return boolean
  167. */
  168. public function canRead($pFilename)
  169. {
  170. // Check if zip class exists
  171. if (!class_exists('ZipArchive')) {
  172. return false;
  173. }
  174. // Check if file exists
  175. if (!file_exists($pFilename)) {
  176. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  177. }
  178. $xl = false;
  179. // Load file
  180. $zip = new ZipArchive;
  181. if ($zip->open($pFilename) === true) {
  182. // check if it is an OOXML archive
  183. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels"));
  184. foreach ($rels->Relationship as $rel) {
  185. switch ($rel["Type"]) {
  186. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  187. if (basename($rel["Target"]) == 'workbook.xml') {
  188. $xl = true;
  189. }
  190. break;
  191. }
  192. }
  193. $zip->close();
  194. }
  195. return $xl;
  196. }
  197. private static function _castToBool($c) {
  198. // echo 'Initial Cast to Boolean<br />';
  199. $value = isset($c->v) ? (string) $c->v : null;
  200. if ($value == '0') {
  201. return false;
  202. } elseif ($value == '1') {
  203. return true;
  204. } else {
  205. return (bool)$c->v;
  206. }
  207. return $value;
  208. } // function _castToBool()
  209. private static function _castToError($c) {
  210. // echo 'Initial Cast to Error<br />';
  211. return isset($c->v) ? (string) $c->v : null;;
  212. } // function _castToError()
  213. private static function _castToString($c) {
  214. // echo 'Initial Cast to String<br />';
  215. return isset($c->v) ? (string) $c->v : null;;
  216. } // function _castToString()
  217. private function _castToFormula($c,$r,&$cellDataType,&$value,&$calculatedValue,&$sharedFormulas,$castBaseType) {
  218. // echo '<font color="darkgreen">Formula</font><br />';
  219. // echo '$c->f is '.$c->f.'<br />';
  220. $cellDataType = 'f';
  221. $value = "={$c->f}";
  222. $calculatedValue = self::$castBaseType($c);
  223. // Shared formula?
  224. if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') {
  225. // echo '<font color="darkgreen">SHARED FORMULA</font><br />';
  226. $instance = (string)$c->f['si'];
  227. // echo 'Instance ID = '.$instance.'<br />';
  228. //
  229. // echo 'Shared Formula Array:<pre>';
  230. // print_r($sharedFormulas);
  231. // echo '</pre>';
  232. if (!isset($sharedFormulas[(string)$c->f['si']])) {
  233. // echo '<font color="darkgreen">SETTING NEW SHARED FORMULA</font><br />';
  234. // echo 'Master is '.$r.'<br />';
  235. // echo 'Formula is '.$value.'<br />';
  236. $sharedFormulas[$instance] = array( 'master' => $r,
  237. 'formula' => $value
  238. );
  239. // echo 'New Shared Formula Array:<pre>';
  240. // print_r($sharedFormulas);
  241. // echo '</pre>';
  242. } else {
  243. // echo '<font color="darkgreen">GETTING SHARED FORMULA</font><br />';
  244. // echo 'Master is '.$sharedFormulas[$instance]['master'].'<br />';
  245. // echo 'Formula is '.$sharedFormulas[$instance]['formula'].'<br />';
  246. $master = PHPExcel_Cell::coordinateFromString($sharedFormulas[$instance]['master']);
  247. $current = PHPExcel_Cell::coordinateFromString($r);
  248. $difference = array(0, 0);
  249. $difference[0] = PHPExcel_Cell::columnIndexFromString($current[0]) - PHPExcel_Cell::columnIndexFromString($master[0]);
  250. $difference[1] = $current[1] - $master[1];
  251. $value = $this->_referenceHelper->updateFormulaReferences( $sharedFormulas[$instance]['formula'],
  252. 'A1',
  253. $difference[0],
  254. $difference[1]
  255. );
  256. // echo 'Adjusted Formula is '.$value.'<br />';
  257. }
  258. }
  259. }
  260. public function _getFromZipArchive(ZipArchive $archive, $fileName = '')
  261. {
  262. // Root-relative paths
  263. if (strpos($fileName, '//') !== false)
  264. {
  265. $fileName = substr($fileName, strpos($fileName, '//') + 1);
  266. }
  267. $fileName = PHPExcel_Shared_File::realpath($fileName);
  268. // Apache POI fixes
  269. $contents = $archive->getFromName($fileName);
  270. if ($contents === false)
  271. {
  272. $contents = $archive->getFromName(substr($fileName, 1));
  273. }
  274. return $contents;
  275. }
  276. /**
  277. * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
  278. *
  279. * @param string $pFilename
  280. * @throws Exception
  281. */
  282. public function listWorksheetNames($pFilename)
  283. {
  284. // Check if file exists
  285. if (!file_exists($pFilename)) {
  286. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  287. }
  288. $worksheetNames = array();
  289. $zip = new ZipArchive;
  290. $zip->open($pFilename);
  291. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  292. foreach ($rels->Relationship as $rel) {
  293. switch ($rel["Type"]) {
  294. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  295. $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  296. if ($xmlWorkbook->sheets) {
  297. foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
  298. // Check if sheet should be skipped
  299. $worksheetNames[] = (string) $eleSheet["name"];
  300. }
  301. }
  302. }
  303. }
  304. $zip->close();
  305. return $worksheetNames;
  306. }
  307. /**
  308. * Loads PHPExcel from file
  309. *
  310. * @param string $pFilename
  311. * @throws Exception
  312. */
  313. public function load($pFilename)
  314. {
  315. // Check if file exists
  316. if (!file_exists($pFilename)) {
  317. throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
  318. }
  319. // Initialisations
  320. $excel = new PHPExcel;
  321. $excel->removeSheetByIndex(0);
  322. if (!$this->_readDataOnly) {
  323. $excel->removeCellStyleXfByIndex(0); // remove the default style
  324. $excel->removeCellXfByIndex(0); // remove the default style
  325. }
  326. $zip = new ZipArchive;
  327. $zip->open($pFilename);
  328. // Read the theme first, because we need the colour scheme when reading the styles
  329. $wbRels = simplexml_load_string($this->_getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  330. foreach ($wbRels->Relationship as $rel) {
  331. switch ($rel["Type"]) {
  332. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme":
  333. $themeOrderArray = array('lt1','dk1','lt2','dk2');
  334. $themeOrderAdditional = count($themeOrderArray);
  335. $xmlTheme = simplexml_load_string($this->_getFromZipArchive($zip, "xl/{$rel['Target']}"));
  336. if (is_object($xmlTheme)) {
  337. $xmlThemeName = $xmlTheme->attributes();
  338. $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main");
  339. $themeName = (string)$xmlThemeName['name'];
  340. $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
  341. $colourSchemeName = (string)$colourScheme['name'];
  342. $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main");
  343. $themeColours = array();
  344. foreach ($colourScheme as $k => $xmlColour) {
  345. $themePos = array_search($k,$themeOrderArray);
  346. if ($themePos === false) {
  347. $themePos = $themeOrderAdditional++;
  348. }
  349. if (isset($xmlColour->sysClr)) {
  350. $xmlColourData = $xmlColour->sysClr->attributes();
  351. $themeColours[$themePos] = $xmlColourData['lastClr'];
  352. } elseif (isset($xmlColour->srgbClr)) {
  353. $xmlColourData = $xmlColour->srgbClr->attributes();
  354. $themeColours[$themePos] = $xmlColourData['val'];
  355. }
  356. }
  357. self::$_theme = new PHPExcel_Reader_Excel2007_Theme($themeName,$colourSchemeName,$themeColours);
  358. }
  359. break;
  360. }
  361. }
  362. $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  363. foreach ($rels->Relationship as $rel) {
  364. switch ($rel["Type"]) {
  365. case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties":
  366. $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));
  367. if (is_object($xmlCore)) {
  368. $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/");
  369. $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/");
  370. $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties");
  371. $docProps = $excel->getProperties();
  372. $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator")));
  373. $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy")));
  374. $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); //! respect xsi:type
  375. $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type
  376. $docProps->setTitle((string) self::array_item($xmlCore->xpath("dc:title")));
  377. $docProps->setDescription((string) self::array_item($xmlCore->xpath("dc:description")));
  378. $docProps->setSubject((string) self::array_item($xmlCore->xpath("dc:subject")));
  379. $docProps->setKeywords((string) self::array_item($xmlCore->xpath("cp:keywords")));
  380. $docProps->setCategory((string) self::array_item($xmlCore->xpath("cp:category")));
  381. }
  382. break;
  383. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties":
  384. $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));
  385. if (is_object($xmlCore)) {
  386. $docProps = $excel->getProperties();
  387. if (isset($xmlCore->Company))
  388. $docProps->setCompany((string) $xmlCore->Company);
  389. if (isset($xmlCore->Manager))
  390. $docProps->setManager((string) $xmlCore->Manager);
  391. }
  392. break;
  393. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties":
  394. $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));
  395. if (is_object($xmlCore)) {
  396. $docProps = $excel->getProperties();
  397. foreach ($xmlCore as $xmlProperty) {
  398. $cellDataOfficeAttributes = $xmlProperty->attributes();
  399. if (isset($cellDataOfficeAttributes['name'])) {
  400. $propertyName = (string) $cellDataOfficeAttributes['name'];
  401. $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
  402. $attributeType = $cellDataOfficeChildren->getName();
  403. $attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
  404. $attributeValue = PHPExcel_DocumentProperties::convertProperty($attributeValue,$attributeType);
  405. $attributeType = PHPExcel_DocumentProperties::convertPropertyType($attributeType);
  406. $docProps->setCustomProperty($propertyName,$attributeValue,$attributeType);
  407. }
  408. }
  409. }
  410. break;
  411. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  412. $dir = dirname($rel["Target"]);
  413. $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  414. $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
  415. $sharedStrings = array();
  416. $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
  417. $xmlStrings = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  418. if (isset($xmlStrings) && isset($xmlStrings->si)) {
  419. foreach ($xmlStrings->si as $val) {
  420. if (isset($val->t)) {
  421. $sharedStrings[] = PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $val->t );
  422. } elseif (isset($val->r)) {
  423. $sharedStrings[] = $this->_parseRichText($val);
  424. }
  425. }
  426. }
  427. $worksheets = array();
  428. foreach ($relsWorkbook->Relationship as $ele) {
  429. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") {
  430. $worksheets[(string) $ele["Id"]] = $ele["Target"];
  431. }
  432. }
  433. $styles = array();
  434. $cellStyles = array();
  435. $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
  436. $xmlStyles = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  437. $numFmts = null;
  438. if ($xmlStyles && $xmlStyles->numFmts[0]) {
  439. $numFmts = $xmlStyles->numFmts[0];
  440. }
  441. if (isset($numFmts) && !is_null($numFmts)) {
  442. $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  443. }
  444. if (!$this->_readDataOnly && $xmlStyles) {
  445. foreach ($xmlStyles->cellXfs->xf as $xf) {
  446. $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  447. if ($xf["numFmtId"]) {
  448. if (isset($numFmts)) {
  449. $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
  450. if (isset($tmpNumFmt["formatCode"])) {
  451. $numFmt = (string) $tmpNumFmt["formatCode"];
  452. }
  453. }
  454. if ((int)$xf["numFmtId"] < 164) {
  455. $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
  456. }
  457. }
  458. //$numFmt = str_replace('mm', 'i', $numFmt);
  459. //$numFmt = str_replace('h', 'H', $numFmt);
  460. $style = (object) array(
  461. "numFmt" => $numFmt,
  462. "font" => $xmlStyles->fonts->font[intval($xf["fontId"])],
  463. "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])],
  464. "border" => $xmlStyles->borders->border[intval($xf["borderId"])],
  465. "alignment" => $xf->alignment,
  466. "protection" => $xf->protection,
  467. );
  468. $styles[] = $style;
  469. // add style to cellXf collection
  470. $objStyle = new PHPExcel_Style;
  471. self::_readStyle($objStyle, $style);
  472. $excel->addCellXf($objStyle);
  473. }
  474. foreach ($xmlStyles->cellStyleXfs->xf as $xf) {
  475. $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  476. if ($numFmts && $xf["numFmtId"]) {
  477. $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
  478. if (isset($tmpNumFmt["formatCode"])) {
  479. $numFmt = (string) $tmpNumFmt["formatCode"];
  480. } else if ((int)$xf["numFmtId"] < 165) {
  481. $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
  482. }
  483. }
  484. $cellStyle = (object) array(
  485. "numFmt" => $numFmt,
  486. "font" => $xmlStyles->fonts->font[intval($xf["fontId"])],
  487. "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])],
  488. "border" => $xmlStyles->borders->border[intval($xf["borderId"])],
  489. "alignment" => $xf->alignment,
  490. "protection" => $xf->protection,
  491. );
  492. $cellStyles[] = $cellStyle;
  493. // add style to cellStyleXf collection
  494. $objStyle = new PHPExcel_Style;
  495. self::_readStyle($objStyle, $cellStyle);
  496. $excel->addCellStyleXf($objStyle);
  497. }
  498. }
  499. $dxfs = array();
  500. if (!$this->_readDataOnly && $xmlStyles) {
  501. if ($xmlStyles->dxfs) {
  502. foreach ($xmlStyles->dxfs->dxf as $dxf) {
  503. $style = new PHPExcel_Style;
  504. self::_readStyle($style, $dxf);
  505. $dxfs[] = $style;
  506. }
  507. }
  508. if ($xmlStyles->cellStyles)
  509. {
  510. foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
  511. if (intval($cellStyle['builtinId']) == 0) {
  512. if (isset($cellStyles[intval($cellStyle['xfId'])])) {
  513. // Set default style
  514. $style = new PHPExcel_Style;
  515. self::_readStyle($style, $cellStyles[intval($cellStyle['xfId'])]);
  516. // normal style, currently not using it for anything
  517. }
  518. }
  519. }
  520. }
  521. }
  522. $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  523. // Set base date
  524. if ($xmlWorkbook->workbookPr) {
  525. PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
  526. if (isset($xmlWorkbook->workbookPr['date1904'])) {
  527. $date1904 = (string)$xmlWorkbook->workbookPr['date1904'];
  528. if ($date1904 == "true" || $date1904 == "1") {
  529. PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
  530. }
  531. }
  532. }
  533. $sheetId = 0; // keep track of new sheet id in final workbook
  534. $oldSheetId = -1; // keep track of old sheet id in final workbook
  535. $countSkippedSheets = 0; // keep track of number of skipped sheets
  536. $mapSheetId = array(); // mapping of sheet ids from old to new
  537. if ($xmlWorkbook->sheets)
  538. {
  539. foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
  540. ++$oldSheetId;
  541. // Check if sheet should be skipped
  542. if (isset($this->_loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->_loadSheetsOnly)) {
  543. ++$countSkippedSheets;
  544. $mapSheetId[$oldSheetId] = null;
  545. continue;
  546. }
  547. // Map old sheet id in original workbook to new sheet id.
  548. // They will differ if loadSheetsOnly() is being used
  549. $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
  550. // Load sheet
  551. $docSheet = $excel->createSheet();
  552. $docSheet->setTitle((string) $eleSheet["name"]);
  553. $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  554. $xmlSheet = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$fileWorksheet")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  555. $sharedFormulas = array();
  556. if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') {
  557. $docSheet->setSheetState( (string) $eleSheet["state"] );
  558. }
  559. if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) {
  560. if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
  561. $docSheet->getSheetView()->setZoomScale( intval($xmlSheet->sheetViews->sheetView['zoomScale']) );
  562. }
  563. if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
  564. $docSheet->getSheetView()->setZoomScaleNormal( intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal']) );
  565. }
  566. if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
  567. $docSheet->setShowGridLines((string)$xmlSheet->sheetViews->sheetView['showGridLines'] ? true : false);
  568. }
  569. if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
  570. $docSheet->setShowRowColHeaders((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'] ? true : false);
  571. }
  572. if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
  573. $docSheet->setRightToLeft((string)$xmlSheet->sheetViews->sheetView['rightToLeft'] ? true : false);
  574. }
  575. if (isset($xmlSheet->sheetViews->sheetView->pane)) {
  576. if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
  577. $docSheet->freezePane( (string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell'] );
  578. } else {
  579. $xSplit = 0;
  580. $ySplit = 0;
  581. if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
  582. $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']);
  583. }
  584. if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
  585. $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']);
  586. }
  587. $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit);
  588. }
  589. }
  590. if (isset($xmlSheet->sheetViews->sheetView->selection)) {
  591. if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
  592. $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref'];
  593. $sqref = explode(' ', $sqref);
  594. $sqref = $sqref[0];
  595. $docSheet->setSelectedCells($sqref);
  596. }
  597. }
  598. }
  599. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) {
  600. if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
  601. $docSheet->getTabColor()->setARGB( (string)$xmlSheet->sheetPr->tabColor['rgb'] );
  602. }
  603. }
  604. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) {
  605. if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && $xmlSheet->sheetPr->outlinePr['summaryRight'] == false) {
  606. $docSheet->setShowSummaryRight(false);
  607. } else {
  608. $docSheet->setShowSummaryRight(true);
  609. }
  610. if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && $xmlSheet->sheetPr->outlinePr['summaryBelow'] == false) {
  611. $docSheet->setShowSummaryBelow(false);
  612. } else {
  613. $docSheet->setShowSummaryBelow(true);
  614. }
  615. }
  616. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) {
  617. if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && $xmlSheet->sheetPr->pageSetUpPr['fitToPage'] == false) {
  618. $docSheet->getPageSetup()->setFitToPage(false);
  619. } else {
  620. $docSheet->getPageSetup()->setFitToPage(true);
  621. }
  622. }
  623. if (isset($xmlSheet->sheetFormatPr)) {
  624. if (isset($xmlSheet->sheetFormatPr['customHeight']) && ((string)$xmlSheet->sheetFormatPr['customHeight'] == '1' || strtolower((string)$xmlSheet->sheetFormatPr['customHeight']) == 'true') && isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
  625. $docSheet->getDefaultRowDimension()->setRowHeight( (float)$xmlSheet->sheetFormatPr['defaultRowHeight'] );
  626. }
  627. if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
  628. $docSheet->getDefaultColumnDimension()->setWidth( (float)$xmlSheet->sheetFormatPr['defaultColWidth'] );
  629. }
  630. }
  631. if (isset($xmlSheet->cols) && !$this->_readDataOnly) {
  632. foreach ($xmlSheet->cols->col as $col) {
  633. for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) {
  634. if ($col["style"] && !$this->_readDataOnly) {
  635. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"]));
  636. }
  637. if ($col["bestFit"]) {
  638. //$docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(true);
  639. }
  640. if ($col["hidden"]) {
  641. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setVisible(false);
  642. }
  643. if ($col["collapsed"]) {
  644. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setCollapsed(true);
  645. }
  646. if ($col["outlineLevel"] > 0) {
  647. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"]));
  648. }
  649. $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"]));
  650. if (intval($col["max"]) == 16384) {
  651. break;
  652. }
  653. }
  654. }
  655. }
  656. if (isset($xmlSheet->printOptions) && !$this->_readDataOnly) {
  657. if ($xmlSheet->printOptions['gridLinesSet'] == 'true' && $xmlSheet->printOptions['gridLinesSet'] == '1') {
  658. $docSheet->setShowGridlines(true);
  659. }
  660. if ($xmlSheet->printOptions['gridLines'] == 'true' || $xmlSheet->printOptions['gridLines'] == '1') {
  661. $docSheet->setPrintGridlines(true);
  662. }
  663. if ($xmlSheet->printOptions['horizontalCentered']) {
  664. $docSheet->getPageSetup()->setHorizontalCentered(true);
  665. }
  666. if ($xmlSheet->printOptions['verticalCentered']) {
  667. $docSheet->getPageSetup()->setVerticalCentered(true);
  668. }
  669. }
  670. if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
  671. foreach ($xmlSheet->sheetData->row as $row) {
  672. if ($row["ht"] && !$this->_readDataOnly) {
  673. $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"]));
  674. }
  675. if ($row["hidden"] && !$this->_readDataOnly) {
  676. $docSheet->getRowDimension(intval($row["r"]))->setVisible(false);
  677. }
  678. if ($row["collapsed"]) {
  679. $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(true);
  680. }
  681. if ($row["outlineLevel"] > 0) {
  682. $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"]));
  683. }
  684. if ($row["s"] && !$this->_readDataOnly) {
  685. $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"]));
  686. }
  687. foreach ($row->c as $c) {
  688. $r = (string) $c["r"];
  689. $cellDataType = (string) $c["t"];
  690. $value = null;
  691. $calculatedValue = null;
  692. // Read cell?
  693. if (!is_null($this->getReadFilter())) {
  694. $coordinates = PHPExcel_Cell::coordinateFromString($r);
  695. if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) {
  696. continue;
  697. }
  698. }
  699. // echo '<b>Reading cell '.$coordinates[0].$coordinates[1].'</b><br />';
  700. // print_r($c);
  701. // echo '<br />';
  702. // echo 'Cell Data Type is '.$cellDataType.': ';
  703. //
  704. // Read cell!
  705. switch ($cellDataType) {
  706. case "s":
  707. // echo 'String<br />';
  708. if ((string)$c->v != '') {
  709. $value = $sharedStrings[intval($c->v)];
  710. if ($value instanceof PHPExcel_RichText) {
  711. $value = clone $value;
  712. }
  713. } else {
  714. $value = '';
  715. }
  716. break;
  717. case "b":
  718. // echo 'Boolean<br />';
  719. if (!isset($c->f)) {
  720. $value = self::_castToBool($c);
  721. } else {
  722. // Formula
  723. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToBool');
  724. if (isset($c->f['t'])) {
  725. $att = array();
  726. $att = $c->f;
  727. $docSheet->getCell($r)->setFormulaAttributes($att);
  728. }
  729. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  730. }
  731. break;
  732. case "inlineStr":
  733. // echo 'Inline String<br />';
  734. $value = $this->_parseRichText($c->is);
  735. break;
  736. case "e":
  737. // echo 'Error<br />';
  738. if (!isset($c->f)) {
  739. $value = self::_castToError($c);
  740. } else {
  741. // Formula
  742. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToError');
  743. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  744. }
  745. break;
  746. default:
  747. // echo 'Default<br />';
  748. if (!isset($c->f)) {
  749. // echo 'Not a Formula<br />';
  750. $value = self::_castToString($c);
  751. } else {
  752. // echo 'Treat as Formula<br />';
  753. // Formula
  754. $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToString');
  755. // echo '$calculatedValue = '.$calculatedValue.'<br />';
  756. }
  757. break;
  758. }
  759. // echo 'Value is '.$value.'<br />';
  760. // Check for numeric values
  761. if (is_numeric($value) && $cellDataType != 's') {
  762. if ($value == (int)$value) $value = (int)$value;
  763. elseif ($value == (float)$value) $value = (float)$value;
  764. elseif ($value == (double)$value) $value = (double)$value;
  765. }
  766. // Rich text?
  767. if ($value instanceof PHPExcel_RichText && $this->_readDataOnly) {
  768. $value = $value->getPlainText();
  769. }
  770. $cell = $docSheet->getCell($r);
  771. // Assign value
  772. if ($cellDataType != '') {
  773. $cell->setValueExplicit($value, $cellDataType);
  774. } else {
  775. $cell->setValue($value);
  776. }
  777. if (!is_null($calculatedValue)) {
  778. $cell->setCalculatedValue($calculatedValue);
  779. }
  780. // Style information?
  781. if ($c["s"] && !$this->_readDataOnly) {
  782. // no style index means 0, it seems
  783. $cell->setXfIndex(isset($styles[intval($c["s"])]) ?
  784. intval($c["s"]) : 0);
  785. }
  786. }
  787. }
  788. }
  789. $conditionals = array();
  790. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
  791. foreach ($xmlSheet->conditionalFormatting as $conditional) {
  792. foreach ($conditional->cfRule as $cfRule) {
  793. if (
  794. (
  795. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_NONE ||
  796. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CELLIS ||
  797. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT ||
  798. (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
  799. ) && isset($dxfs[intval($cfRule["dxfId"])])
  800. ) {
  801. $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule;
  802. }
  803. }
  804. }
  805. foreach ($conditionals as $ref => $cfRules) {
  806. ksort($cfRules);
  807. $conditionalStyles = array();
  808. foreach ($cfRules as $cfRule) {
  809. $objConditional = new PHPExcel_Style_Conditional();
  810. $objConditional->setConditionType((string)$cfRule["type"]);
  811. $objConditional->setOperatorType((string)$cfRule["operator"]);
  812. if ((string)$cfRule["text"] != '') {
  813. $objConditional->setText((string)$cfRule["text"]);
  814. }
  815. if (count($cfRule->formula) > 1) {
  816. foreach ($cfRule->formula as $formula) {
  817. $objConditional->addCondition((string)$formula);
  818. }
  819. } else {
  820. $objConditional->addCondition((string)$cfRule->formula);
  821. }
  822. $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]);
  823. $conditionalStyles[] = $objConditional;
  824. }
  825. // Extract all cell references in $ref
  826. $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($ref);
  827. foreach ($aReferences as $reference) {
  828. $docSheet->getStyle($reference)->setConditionalStyles($conditionalStyles);
  829. }
  830. }
  831. }
  832. $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells");
  833. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  834. foreach ($aKeys as $key) {
  835. $method = "set" . ucfirst($key);
  836. $docSheet->getProtection()->$method($xmlSheet->sheetProtection[$key] == "true");
  837. }
  838. }
  839. if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  840. $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], true);
  841. if ($xmlSheet->protectedRanges->protectedRange) {
  842. foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
  843. $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true);
  844. }
  845. }
  846. }
  847. if ($xmlSheet && $xmlSheet->autoFilter && !$this->_readDataOnly) {
  848. $docSheet->setAutoFilter((string) $xmlSheet->autoFilter["ref"]);
  849. }
  850. if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->_readDataOnly) {
  851. foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
  852. $docSheet->mergeCells((string) $mergeCell["ref"]);
  853. }
  854. }
  855. if ($xmlSheet && $xmlSheet->pageMargins && !$this->_readDataOnly) {
  856. $docPageMargins = $docSheet->getPageMargins();
  857. $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"]));
  858. $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"]));
  859. $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"]));
  860. $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"]));
  861. $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"]));
  862. $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"]));
  863. }
  864. if ($xmlSheet && $xmlSheet->pageSetup && !$this->_readDataOnly) {
  865. $docPageSetup = $docSheet->getPageSetup();
  866. if (isset($xmlSheet->pageSetup["orientation"])) {
  867. $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]);
  868. }
  869. if (isset($xmlSheet->pageSetup["paperSize"])) {
  870. $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"]));
  871. }
  872. if (isset($xmlSheet->pageSetup["scale"])) {
  873. $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), false);
  874. }
  875. if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) {
  876. $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), false);
  877. }
  878. if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) {
  879. $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), false);
  880. }
  881. if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) &&
  882. ((string)$xmlSheet->pageSetup["useFirstPageNumber"] == 'true' || (string)$xmlSheet->pageSetup["useFirstPageNumber"] == '1')) {
  883. $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"]));
  884. }
  885. }
  886. if ($xmlSheet && $xmlSheet->headerFooter && !$this->_readDataOnly) {
  887. $docHeaderFooter = $docSheet->getHeaderFooter();
  888. if (isset($xmlSheet->headerFooter["differentOddEven"]) &&
  889. ((string)$xmlSheet->headerFooter["differentOddEven"] == 'true' || (string)$xmlSheet->headerFooter["differentOddEven"] == '1')) {
  890. $docHeaderFooter->setDifferentOddEven(true);
  891. } else {
  892. $docHeaderFooter->setDifferentOddEven(false);
  893. }
  894. if (isset($xmlSheet->headerFooter["differentFirst"]) &&
  895. ((string)$xmlSheet->headerFooter["differentFirst"] == 'true' || (string)$xmlSheet->headerFooter["differentFirst"] == '1')) {
  896. $docHeaderFooter->setDifferentFirst(true);
  897. } else {
  898. $docHeaderFooter->setDifferentFirst(false);
  899. }
  900. if (isset($xmlSheet->headerFooter["scaleWithDoc"]) &&
  901. ((string)$xmlSheet->headerFooter["scaleWithDoc"] == 'false' || (string)$xmlSheet->headerFooter["scaleWithDoc"] == '0')) {
  902. $docHeaderFooter->setScaleWithDocument(false);
  903. } else {
  904. $docHeaderFooter->setScaleWithDocument(true);
  905. }
  906. if (isset($xmlSheet->headerFooter["alignWithMargins"]) &&
  907. ((string)$xmlSheet->headerFooter["alignWithMargins"] == 'false' || (string)$xmlSheet->headerFooter["alignWithMargins"] == '0')) {
  908. $docHeaderFooter->setAlignWithMargins(false);
  909. } else {
  910. $docHeaderFooter->setAlignWithMargins(true);
  911. }
  912. $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
  913. $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
  914. $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
  915. $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
  916. $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
  917. $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
  918. }
  919. if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->_readDataOnly) {
  920. foreach ($xmlSheet->rowBreaks->brk as $brk) {
  921. if ($brk["man"]) {
  922. $docSheet->setBreak("A$brk[id]", PHPExcel_Worksheet::BREAK_ROW);
  923. }
  924. }
  925. }
  926. if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->_readDataOnly) {
  927. foreach ($xmlSheet->colBreaks->brk as $brk) {
  928. if ($brk["man"]) {
  929. $docSheet->setBreak(PHPExcel_Cell::stringFromColumnIndex($brk["id"]) . "1", PHPExcel_Worksheet::BREAK_COLUMN);
  930. }
  931. }
  932. }
  933. if ($xmlSheet && $xmlSheet->dataValidations && !$this->_readDataOnly) {
  934. foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
  935. // Uppercase coordinate
  936. $range = strtoupper($dataValidation["sqref"]);
  937. $rangeSet = explode(' ',$range);
  938. foreach($rangeSet as $range) {
  939. $stRange = $docSheet->shrinkRangeToFit($range);
  940. // Extract all cell references in $range
  941. $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($stRange);
  942. foreach ($aReferences as $reference) {
  943. // Create validation
  944. $docValidation = $docSheet->getCell($reference)->getDataValidation();
  945. $docValidation->setType((string) $dataValidation["type"]);
  946. $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]);
  947. $docValidation->setOperator((string) $dataValidation["operator"]);
  948. $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0);
  949. $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0);
  950. $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0);
  951. $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0);
  952. $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]);
  953. $docValidation->setError((string) $dataValidation["error"]);
  954. $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]);
  955. $docValidation->setPrompt((string) $dataValidation["prompt"]);
  956. $docValidation->setFormula1((string) $dataValidation->formula1);
  957. $docValidation->setFormula2((string) $dataValidation->formula2);
  958. }
  959. }
  960. }
  961. }
  962. // Add hyperlinks
  963. $hyperlinks = array();
  964. if (!$this->_readDataOnly) {
  965. // Locate hyperlink relations
  966. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  967. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  968. foreach ($relsWorksheet->Relationship as $ele) {
  969. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") {
  970. $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"];
  971. }
  972. }
  973. }
  974. // Loop through hyperlinks
  975. if ($xmlSheet && $xmlSheet->hyperlinks) {
  976. foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
  977. // Link url
  978. $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  979. foreach (PHPExcel_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
  980. $cell = $docSheet->getCell( $cellReference );
  981. if (isset($linkRel['id'])) {
  982. $cell->getHyperlink()->setUrl( $hyperlinks[ (string)$linkRel['id'] ] );
  983. }
  984. if (isset($hyperlink['location'])) {
  985. $cell->getHyperlink()->setUrl( 'sheet://' . (string)$hyperlink['location'] );
  986. }
  987. // Tooltip
  988. if (isset($hyperlink['tooltip'])) {
  989. $cell->getHyperlink()->setTooltip( (string)$hyperlink['tooltip'] );
  990. }
  991. }
  992. }
  993. }
  994. }
  995. // Add comments
  996. $comments = array();
  997. $vmlComments = array();
  998. if (!$this->_readDataOnly) {
  999. // Locate comment relations
  1000. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1001. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1002. foreach ($relsWorksheet->Relationship as $ele) {
  1003. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") {
  1004. $comments[(string)$ele["Id"]] = (string)$ele["Target"];
  1005. }
  1006. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1007. $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"];
  1008. }
  1009. }
  1010. }
  1011. // Loop through comments
  1012. foreach ($comments as $relName => $relPath) {
  1013. // Load comments file
  1014. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  1015. $commentsFile = simplexml_load_string($this->_getFromZipArchive($zip, $relPath) );
  1016. // Utility variables
  1017. $authors = array();
  1018. // Loop through authors
  1019. foreach ($commentsFile->authors->author as $author) {
  1020. $authors[] = (string)$author;
  1021. }
  1022. // Loop through contents
  1023. foreach ($commentsFile->commentList->comment as $comment) {
  1024. $docSheet->getComment( (string)$comment['ref'] )->setAuthor( $authors[(string)$comment['authorId']] );
  1025. $docSheet->getComment( (string)$comment['ref'] )->setText( $this->_parseRichText($comment->text) );
  1026. }
  1027. }
  1028. // Loop through VML comments
  1029. foreach ($vmlComments as $relName => $relPath) {
  1030. // Load VML comments file
  1031. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  1032. $vmlCommentsFile = simplexml_load_string( $this->_getFromZipArchive($zip, $relPath) );
  1033. $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1034. $shapes = $vmlCommentsFile->xpath('//v:shape');
  1035. foreach ($shapes as $shape) {
  1036. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1037. if (isset($shape['style'])) {
  1038. $style = (string)$shape['style'];
  1039. $fillColor = strtoupper( substr( (string)$shape['fillcolor'], 1 ) );
  1040. $column = null;
  1041. $row = null;
  1042. $clientData = $shape->xpath('.//x:ClientData');
  1043. if (is_array($clientData) && count($clientData) > 0) {
  1044. $clientData = $clientData[0];
  1045. if ( isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note' ) {
  1046. $temp = $clientData->xpath('.//x:Row');
  1047. if (is_array($temp)) $row = $temp[0];
  1048. $temp = $clientData->xpath('.//x:Column');
  1049. if (is_array($temp)) $column = $temp[0];
  1050. }
  1051. }
  1052. if (!is_null($column) && !is_null($row)) {
  1053. // Set comment properties
  1054. $comment = $docSheet->getCommentByColumnAndRow($column, $row + 1);
  1055. $comment->getFillColor()->setRGB( $fillColor );
  1056. // Parse style
  1057. $styleArray = explode(';', str_replace(' ', '', $style));
  1058. foreach ($styleArray as $stylePair) {
  1059. $stylePair = explode(':', $stylePair);
  1060. if ($stylePair[0] == 'margin-left') $comment->setMarginLeft($stylePair[1]);
  1061. if ($stylePair[0] == 'margin-top') $comment->setMarginTop($stylePair[1]);
  1062. if ($stylePair[0] == 'width') $comment->setWidth($stylePair[1]);
  1063. if ($stylePair[0] == 'height') $comment->setHeight($stylePair[1]);
  1064. if ($stylePair[0] == 'visibility') $comment->setVisible( $stylePair[1] == 'visible' );
  1065. }
  1066. }
  1067. }
  1068. }
  1069. }
  1070. // Header/footer images
  1071. if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->_readDataOnly) {
  1072. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1073. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1074. $vmlRelationship = '';
  1075. foreach ($relsWorksheet->Relationship as $ele) {
  1076. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1077. $vmlRelationship = self::dir_add("$dir/$fileWorksheet", $ele["Target"]);
  1078. }
  1079. }
  1080. if ($vmlRelationship != '') {
  1081. // Fetch linked images
  1082. $relsVML = simplexml_load_string($this->_getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels' )); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1083. $drawings = array();
  1084. foreach ($relsVML->Relationship as $ele) {
  1085. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1086. $drawings[(string) $ele["Id"]] = self::dir_add($vmlRelationship, $ele["Target"]);
  1087. }
  1088. }
  1089. // Fetch VML document
  1090. $vmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $vmlRelationship));
  1091. $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1092. $hfImages = array();
  1093. $shapes = $vmlDrawing->xpath('//v:shape');
  1094. foreach ($shapes as $shape) {
  1095. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1096. $imageData = $shape->xpath('//v:imagedata');
  1097. $imageData = $imageData[0];
  1098. $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
  1099. $style = self::toCSSArray( (string)$shape['style'] );
  1100. $hfImages[ (string)$shape['id'] ] = new PHPExcel_Worksheet_HeaderFooterDrawing();
  1101. if (isset($imageData['title'])) {
  1102. $hfImages[ (string)$shape['id'] ]->setName( (string)$imageData['title'] );
  1103. }
  1104. $hfImages[ (string)$shape['id'] ]->setPath("zip://$pFilename#" . $drawings[(string)$imageData['relid']], false);
  1105. $hfImages[ (string)$shape['id'] ]->setResizeProportional(false);
  1106. $hfImages[ (string)$shape['id'] ]->setWidth($style['width']);
  1107. $hfImages[ (string)$shape['id'] ]->setHeight($style['height']);
  1108. $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']);
  1109. $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']);
  1110. $hfImages[ (string)$shape['id'] ]->setResizeProportional(true);
  1111. }
  1112. $docSheet->getHeaderFooter()->setImages($hfImages);
  1113. }
  1114. }
  1115. }
  1116. }
  1117. // TODO: Make sure drawings and graph are loaded differently!
  1118. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1119. $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1120. $drawings = array();
  1121. foreach ($relsWorksheet->Relationship as $ele) {
  1122. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") {
  1123. $drawings[(string) $ele["Id"]] = self::dir_add("$dir/$fileWorksheet", $ele["Target"]);
  1124. }
  1125. }
  1126. if ($xmlSheet->drawing && !$this->_readDataOnly) {
  1127. foreach ($xmlSheet->drawing as $drawing) {
  1128. $fileDrawing = $drawings[(string) self::array_item($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  1129. $relsDrawing = simplexml_load_string($this->_getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1130. $images = array();
  1131. if ($relsDrawing && $relsDrawing->Relationship) {
  1132. foreach ($relsDrawing->Relationship as $ele) {
  1133. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1134. $images[(string) $ele["Id"]] = self::dir_add($fileDrawing, $ele["Target"]);
  1135. }
  1136. }
  1137. }
  1138. $xmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $fileDrawing))->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
  1139. if ($xmlDrawing->oneCellAnchor) {
  1140. foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
  1141. if ($oneCellAnchor->pic->blipFill) {
  1142. $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1143. $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1144. $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1145. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1146. $objDrawing->setName((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1147. $objDrawing->setDescription((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1148. $objDrawing->setPath("zip://$pFilename#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1149. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex($oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1));
  1150. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff));
  1151. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
  1152. $objDrawing->setResizeProportional(false);
  1153. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx")));
  1154. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy")));
  1155. if ($xfrm) {
  1156. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot")));
  1157. }
  1158. if ($outerShdw) {
  1159. $shadow = $objDrawing->getShadow();
  1160. $shadow->setVisible(true);
  1161. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad")));
  1162. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist")));
  1163. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir")));
  1164. $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn"));
  1165. $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val"));
  1166. $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1167. }
  1168. $objDrawing->setWorksheet($docSheet);
  1169. }
  1170. }
  1171. }
  1172. if ($xmlDrawing->twoCellAnchor) {
  1173. foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
  1174. if ($twoCellAnchor->pic->blipFill) {
  1175. $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1176. $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1177. $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1178. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1179. $objDrawing->setName((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1180. $objDrawing->setDescription((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1181. $objDrawing->setPath("zip://$pFilename#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1182. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex($twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1));
  1183. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff));
  1184. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
  1185. $objDrawing->setResizeProportional(false);
  1186. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cx")));
  1187. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cy")));
  1188. if ($xfrm) {
  1189. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot")));
  1190. }
  1191. if ($outerShdw) {
  1192. $shadow = $objDrawing->getShadow();
  1193. $shadow->setVisible(true);
  1194. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad")));
  1195. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist")));
  1196. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir")));
  1197. $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn"));
  1198. $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val"));
  1199. $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1200. }
  1201. $objDrawing->setWorksheet($docSheet);
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. // Loop through definedNames
  1209. if ($xmlWorkbook->definedNames) {
  1210. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1211. // Extract range
  1212. $extractedRange = (string)$definedName;
  1213. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1214. if (($spos = strpos($extractedRange,'!')) !== false) {
  1215. $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos));
  1216. } else {
  1217. $extractedRange = str_replace('$', '', $extractedRange);
  1218. }
  1219. // Valid range?
  1220. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1221. continue;
  1222. }
  1223. // Some definedNames are only applicable if we are on the same sheet...
  1224. if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) {
  1225. // Switch on type
  1226. switch ((string)$definedName['name']) {
  1227. case '_xlnm._FilterDatabase':
  1228. $docSheet->setAutoFilter($extractedRange);
  1229. break;
  1230. case '_xlnm.Print_Titles':
  1231. // Split $extractedRange
  1232. $extractedRange = explode(',', $extractedRange);
  1233. // Set print titles
  1234. foreach ($extractedRange as $range) {
  1235. $matches = array();
  1236. // check for repeating columns, e g. 'A:A' or 'A:D'
  1237. if (preg_match('/^([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
  1238. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2]));
  1239. }
  1240. // check for repeating rows, e.g. '1:1' or '1:5'
  1241. elseif (preg_match('/^(\d+)\:(\d+)$/', $range, $matches)) {
  1242. $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2]));
  1243. }
  1244. }
  1245. break;
  1246. case '_xlnm.Print_Area':
  1247. $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma?
  1248. $newRangeSets = array();
  1249. foreach($rangeSets as $rangeSet) {
  1250. $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark?
  1251. $rangeSet = isset($range[1]) ? $range[1] : $range[0];
  1252. $newRangeSets[] = str_replace('$', '', $rangeSet);
  1253. }
  1254. $docSheet->getPageSetup()->setPrintArea(implode(',',$newRangeSets));
  1255. break;
  1256. default:
  1257. break;
  1258. }
  1259. }
  1260. }
  1261. }
  1262. // Next sheet id
  1263. ++$sheetId;
  1264. }
  1265. // Loop through definedNames
  1266. if ($xmlWorkbook->definedNames) {
  1267. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1268. // Extract range
  1269. $extractedRange = (string)$definedName;
  1270. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1271. if (($spos = strpos($extractedRange,'!')) !== false) {
  1272. $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos));
  1273. } else {
  1274. $extractedRange = str_replace('$', '', $extractedRange);
  1275. }
  1276. // Valid range?
  1277. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1278. continue;
  1279. }
  1280. // Some definedNames are only applicable if we are on the same sheet...
  1281. if ((string)$definedName['localSheetId'] != '') {
  1282. // Local defined name
  1283. // Switch on type
  1284. switch ((string)$definedName['name']) {
  1285. case '_xlnm._FilterDatabase':
  1286. case '_xlnm.Print_Titles':
  1287. case '_xlnm.Print_Area':
  1288. break;
  1289. default:
  1290. $range = explode('!', (string)$definedName);
  1291. if (count($range) == 2) {
  1292. $range[0] = str_replace("''", "'", $range[0]);
  1293. $range[0] = str_replace("'", "", $range[0]);
  1294. if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
  1295. $extractedRange = str_replace('$', '', $range[1]);
  1296. $scope = $docSheet->getParent()->getSheet((string)$definedName['localSheetId']);
  1297. $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope) );
  1298. }
  1299. }
  1300. break;
  1301. }
  1302. } else if (!isset($definedName['localSheetId'])) {
  1303. // "Global" definedNames
  1304. $locatedSheet = null;
  1305. $extractedSheetName = '';
  1306. if (strpos( (string)$definedName, '!' ) !== false) {
  1307. // Extract sheet name
  1308. $extractedSheetName = PHPExcel_Worksheet::extractSheetTitle( (string)$definedName, true );
  1309. $extractedSheetName = $extractedSheetName[0];
  1310. // Locate sheet
  1311. $locatedSheet = $excel->getSheetByName($extractedSheetName);
  1312. // Modify range
  1313. $range = explode('!', $extractedRange);
  1314. $extractedRange = isset($range[1]) ? $range[1] : $range[0];
  1315. }
  1316. if (!is_null($locatedSheet)) {
  1317. $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false) );
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. if (!$this->_readDataOnly) {
  1324. // active sheet index
  1325. $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index
  1326. // keep active sheet index if sheet is still loaded, else first sheet is set as the active
  1327. if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
  1328. $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
  1329. } else {
  1330. if ($excel->getSheetCount() == 0)
  1331. {
  1332. $excel->createSheet();
  1333. }
  1334. $excel->setActiveSheetIndex(0);
  1335. }
  1336. }
  1337. break;
  1338. }
  1339. }
  1340. $zip->close();
  1341. return $excel;
  1342. }
  1343. private static function _readColor($color, $background=false) {
  1344. if (isset($color["rgb"])) {
  1345. return (string)$color["rgb"];
  1346. } else if (isset($color["indexed"])) {
  1347. return PHPExcel_Style_Color::indexedColor($color["indexed"],$background)->getARGB();
  1348. } else if (isset($color["theme"])) {
  1349. if (!is_null(self::$_theme)) {
  1350. $returnColour = self::$_theme->getColourByIndex((int)$color["theme"]);
  1351. if (isset($color["tint"])) {
  1352. $tintAdjust = (float) $color["tint"];
  1353. $returnColour = PHPExcel_Style_Color::changeBrightness($returnColour, $tintAdjust);
  1354. }
  1355. return 'FF'.$returnColour;
  1356. }
  1357. }
  1358. if ($background) {
  1359. return 'FFFFFFFF';
  1360. }
  1361. return 'FF000000';
  1362. }
  1363. private static function _readStyle($docStyle, $style) {
  1364. // format code
  1365. if (isset($style->numFmt)) {
  1366. $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
  1367. }
  1368. // font
  1369. if (isset($style->font)) {
  1370. $docStyle->getFont()->setName((string) $style->font->name["val"]);
  1371. $docStyle->getFont()->setSize((string) $style->font->sz["val"]);
  1372. if (isset($style->font->b)) {
  1373. $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || $style->font->b["val"] == 'true' || $style->font->b["val"] == '1');
  1374. }
  1375. if (isset($style->font->i)) {
  1376. $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || $style->font->i["val"] == 'true' || $style->font->i["val"] == '1');
  1377. }
  1378. if (isset($style->font->strike)) {
  1379. $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || $style->font->strike["val"] == 'true' || $style->font->strike["val"] == '1');
  1380. }
  1381. $docStyle->getFont()->getColor()->setARGB(self::_readColor($style->font->color));
  1382. if (isset($style->font->u) && !isset($style->font->u["val"])) {
  1383. $docStyle->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1384. } else if (isset($style->font->u) && isset($style->font->u["val"])) {
  1385. $docStyle->getFont()->setUnderline((string)$style->font->u["val"]);
  1386. }
  1387. if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) {
  1388. $vertAlign = strtolower((string)$style->font->vertAlign["val"]);
  1389. if ($vertAlign == 'superscript') {
  1390. $docStyle->getFont()->setSuperScript(true);
  1391. }
  1392. if ($vertAlign == 'subscript') {
  1393. $docStyle->getFont()->setSubScript(true);
  1394. }
  1395. }
  1396. }
  1397. // fill
  1398. if (isset($style->fill)) {
  1399. if ($style->fill->gradientFill) {
  1400. $gradientFill = $style->fill->gradientFill[0];
  1401. if(!empty($gradientFill["type"])) {
  1402. $docStyle->getFill()->setFillType((string) $gradientFill["type"]);
  1403. }
  1404. $docStyle->getFill()->setRotation(floatval($gradientFill["degree"]));
  1405. $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  1406. $docStyle->getFill()->getStartColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=0]"))->color) );
  1407. $docStyle->getFill()->getEndColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=1]"))->color) );
  1408. } elseif ($style->fill->patternFill) {
  1409. $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid';
  1410. $docStyle->getFill()->setFillType($patternType);
  1411. if ($style->fill->patternFill->fgColor) {
  1412. $docStyle->getFill()->getStartColor()->setARGB(self::_readColor($style->fill->patternFill->fgColor,true));
  1413. } else {
  1414. $docStyle->getFill()->getStartColor()->setARGB('FF000000');
  1415. }
  1416. if ($style->fill->patternFill->bgColor) {
  1417. $docStyle->getFill()->getEndColor()->setARGB(self::_readColor($style->fill->patternFill->bgColor,true));
  1418. }
  1419. }
  1420. }
  1421. // border
  1422. if (isset($style->border)) {
  1423. $diagonalUp = false;
  1424. $diagonalDown = false;
  1425. if ($style->border["diagonalUp"] == 'true' || $style->border["diagonalUp"] == 1) {
  1426. $diagonalUp = true;
  1427. }
  1428. if ($style->border["diagonalDown"] == 'true' || $style->border["diagonalDown"] == 1) {
  1429. $diagonalDown = true;
  1430. }
  1431. if ($diagonalUp == false && $diagonalDown == false) {
  1432. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE);
  1433. } elseif ($diagonalUp == true && $diagonalDown == false) {
  1434. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP);
  1435. } elseif ($diagonalUp == false && $diagonalDown == true) {
  1436. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN);
  1437. } elseif ($diagonalUp == true && $diagonalDown == true) {
  1438. $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH);
  1439. }
  1440. self::_readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
  1441. self::_readBorder($docStyle->getBorders()->getRight(), $style->border->right);
  1442. self::_readBorder($docStyle->getBorders()->getTop(), $style->border->top);
  1443. self::_readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
  1444. self::_readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
  1445. }
  1446. // alignment
  1447. if (isset($style->alignment)) {
  1448. $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]);
  1449. $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]);
  1450. $textRotation = 0;
  1451. if ((int)$style->alignment["textRotation"] <= 90) {
  1452. $textRotation = (int)$style->alignment["textRotation"];
  1453. } else if ((int)$style->alignment["textRotation"] > 90) {
  1454. $textRotation = 90 - (int)$style->alignment["textRotation"];
  1455. }
  1456. $docStyle->getAlignment()->setTextRotation(intval($textRotation));
  1457. $docStyle->getAlignment()->setWrapText( (string)$style->alignment["wrapText"] == "true" || (string)$style->alignment["wrapText"] == "1" );
  1458. $docStyle->getAlignment()->setShrinkToFit( (string)$style->alignment["shrinkToFit"] == "true" || (string)$style->alignment["shrinkToFit"] == "1" );
  1459. $docStyle->getAlignment()->setIndent( intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0 );
  1460. }
  1461. // protection
  1462. if (isset($style->protection)) {
  1463. if (isset($style->protection['locked'])) {
  1464. if ((string)$style->protection['locked'] == 'true') {
  1465. $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_PROTECTED);
  1466. } else {
  1467. $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1468. }
  1469. }
  1470. if (isset($style->protection['hidden'])) {
  1471. if ((string)$style->protection['hidden'] == 'true') {
  1472. $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_PROTECTED);
  1473. } else {
  1474. $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
  1475. }
  1476. }
  1477. }
  1478. }
  1479. private static function _readBorder($docBorder, $eleBorder) {
  1480. if (isset($eleBorder["style"])) {
  1481. $docBorder->setBorderStyle((string) $eleBorder["style"]);
  1482. }
  1483. if (isset($eleBorder->color)) {
  1484. $docBorder->getColor()->setARGB(self::_readColor($eleBorder->color));
  1485. }
  1486. }
  1487. private function _parseRichText($is = null) {
  1488. $value = new PHPExcel_RichText();
  1489. if (isset($is->t)) {
  1490. $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $is->t ) );
  1491. } else {
  1492. foreach ($is->r as $run) {
  1493. if (!isset($run->rPr)) {
  1494. $objText = $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) );
  1495. } else {
  1496. $objText = $value->createTextRun( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) );
  1497. if (isset($run->rPr->rFont["val"])) {
  1498. $objText->getFont()->setName((string) $run->rPr->rFont["val"]);
  1499. }
  1500. if (isset($run->rPr->sz["val"])) {
  1501. $objText->getFont()->setSize((string) $run->rPr->sz["val"]);
  1502. }
  1503. if (isset($run->rPr->color)) {
  1504. $objText->getFont()->setColor( new PHPExcel_Style_Color( self::_readColor($run->rPr->color) ) );
  1505. }
  1506. if ( (isset($run->rPr->b["val"]) && ((string) $run->rPr->b["val"] == 'true' || (string) $run->rPr->b["val"] == '1'))
  1507. || (isset($run->rPr->b) && !isset($run->rPr->b["val"])) ) {
  1508. $objText->getFont()->setBold(true);
  1509. }
  1510. if ( (isset($run->rPr->i["val"]) && ((string) $run->rPr->i["val"] == 'true' || (string) $run->rPr->i["val"] == '1'))
  1511. || (isset($run->rPr->i) && !isset($run->rPr->i["val"])) ) {
  1512. $objText->getFont()->setItalic(true);
  1513. }
  1514. if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) {
  1515. $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]);
  1516. if ($vertAlign == 'superscript') {
  1517. $objText->getFont()->setSuperScript(true);
  1518. }
  1519. if ($vertAlign == 'subscript') {
  1520. $objText->getFont()->setSubScript(true);
  1521. }
  1522. }
  1523. if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) {
  1524. $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1525. } else if (isset($run->rPr->u) && isset($run->rPr->u["val"])) {
  1526. $objText->getFont()->setUnderline((string)$run->rPr->u["val"]);
  1527. }
  1528. if ( (isset($run->rPr->strike["val"]) && ((string) $run->rPr->strike["val"] == 'true' || (string) $run->rPr->strike["val"] == '1'))
  1529. || (isset($run->rPr->strike) && !isset($run->rPr->strike["val"])) ) {
  1530. $objText->getFont()->setStrikethrough(true);
  1531. }
  1532. }
  1533. }
  1534. }
  1535. return $value;
  1536. }
  1537. private static function array_item($array, $key = 0) {
  1538. return (isset($array[$key]) ? $array[$key] : null);
  1539. }
  1540. private static function dir_add($base, $add) {
  1541. return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
  1542. }
  1543. private static function toCSSArray($style) {
  1544. $style = str_replace(array("\r","\n"), "", $style);
  1545. $temp = explode(';', $style);
  1546. $style = array();
  1547. foreach ($temp as $item) {
  1548. $item = explode(':', $item);
  1549. if (strpos($item[1], 'px') !== false) {
  1550. $item[1] = str_replace('px', '', $item[1]);
  1551. }
  1552. if (strpos($item[1], 'pt') !== false) {
  1553. $item[1] = str_replace('pt', '', $item[1]);
  1554. $item[1] = PHPExcel_Shared_Font::fontSizeToPixels($item[1]);
  1555. }
  1556. if (strpos($item[1], 'in') !== false) {
  1557. $item[1] = str_replace('in', '', $item[1]);
  1558. $item[1] = PHPExcel_Shared_Font::inchSizeToPixels($item[1]);
  1559. }
  1560. if (strpos($item[1], 'cm') !== false) {
  1561. $item[1] = str_replace('cm', '', $item[1]);
  1562. $item[1] = PHPExcel_Shared_Font::centimeterSizeToPixels($item[1]);
  1563. }
  1564. $style[$item[0]] = $item[1];
  1565. }
  1566. return $style;
  1567. }
  1568. }