Excel2007.php 85 KB

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