Excel2007.php 91 KB

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