Excel2007.Class.php 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: phperstar
  5. * Date: 2020/8/10
  6. * Time: 4:22 PM
  7. */
  8. namespace Util\PHPExcel\Reader;
  9. use Mall\Framework\Core\ResultWrapper;
  10. use Mall\Framework\Core\ErrorCode;
  11. use Util\PHPExcel\Shared\PHPExcelDate;
  12. use Util\PHPExcel\Shared\PHPExcelString;
  13. use Util\PHPExcel\Reader\Excel2007Theme;
  14. use Util\PHPExcel\Reader\ReaderAbstract;
  15. use Util\PHPExcel\Reader\IReader;
  16. use Util\PHPExcel\PHPExcel;
  17. use Util\PHPExcel\Settings;
  18. use Util\PHPExcel\DocumentProperties;
  19. class Excel2007 extends ReaderAbstract implements IReader
  20. {
  21. /**
  22. * PHPExcel_ReferenceHelper instance
  23. *
  24. * @var ReferenceHelper
  25. */
  26. private $referenceHelper = null;
  27. /**
  28. * PHPExcel_Reader_Excel2007_Theme instance
  29. *
  30. * @var Theme
  31. */
  32. private static $theme = null;
  33. /**
  34. * Create a new PHPExcel_Reader_Excel2007 instance
  35. */
  36. public function __construct()
  37. {
  38. //$this->readFilter = new PHPExcel_Reader_DefaultReadFilter();
  39. //$this->referenceHelper = PHPExcel_ReferenceHelper::getInstance();
  40. }
  41. /**
  42. * Can the current IReader read the file?
  43. *
  44. * @param string $pFilename
  45. * @return boolean
  46. * @throws ResultWrapper
  47. */
  48. public function canRead($pFilename)
  49. {
  50. // Check if file exists
  51. if (!file_exists($pFilename)) {
  52. return ResultWrapper::fail('文件不存在',$pFilename, ErrorCode::$notAllowAccess);
  53. }
  54. /*
  55. $zipClass = Settings::getZipClass();
  56. // Check if zip class exists
  57. if (!class_exists($zipClass, false)) {
  58. throw new PHPExcel_Reader_Exception($zipClass . " library is not enabled");
  59. }
  60. $xl = false;
  61. // Load file
  62. $zip = new $zipClass;
  63. if ($zip->open($pFilename) === true) {
  64. // check if it is an OOXML archive
  65. $rels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  66. if ($rels !== false) {
  67. foreach ($rels->Relationship as $rel) {
  68. switch ($rel["Type"]) {
  69. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  70. if (basename($rel["Target"]) == 'workbook.xml') {
  71. $xl = true;
  72. }
  73. break;
  74. }
  75. }
  76. }
  77. $zip->close();
  78. }
  79. return $xl;
  80. */
  81. return true;
  82. }
  83. /**
  84. * Loads PHPExcel from file
  85. * 每个文件对应的作用参考 https://www.cnblogs.com/zlcom/archive/2013/09/21/3332060.html
  86. *
  87. * @param string $pFilename
  88. * @return PHPExcel
  89. * @throws PHPExcel_Reader_Exception
  90. */
  91. public function load($pFilename)
  92. {
  93. // Initialisations
  94. $excel = new PHPExcel;
  95. $excel->removeSheetByIndex(0);
  96. if (!$this->readDataOnly) {
  97. $excel->removeCellStyleXfByIndex(0); // remove the default style
  98. $excel->removeCellXfByIndex(0); // remove the default style
  99. }
  100. $zipClass = Settings::getZipClass();
  101. $zip = new $zipClass;
  102. $zip->open($pFilename);
  103. // 读取工作表id对应的内容存放配置和样式和主题配置
  104. $wbRels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  105. foreach ($wbRels->Relationship as $rel) {
  106. switch ($rel["Type"]) {
  107. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme":
  108. $themeOrderArray = array('lt1', 'dk1', 'lt2', 'dk2');
  109. $themeOrderAdditional = count($themeOrderArray);
  110. $xmlTheme = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  111. if (is_object($xmlTheme)) {
  112. $xmlThemeName = $xmlTheme->attributes();
  113. $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main");
  114. $themeName = (string)$xmlThemeName['name'];
  115. $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
  116. $colourSchemeName = (string)$colourScheme['name'];
  117. $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main");
  118. $themeColours = array();
  119. foreach ($colourScheme as $k => $xmlColour) {
  120. $themePos = array_search($k, $themeOrderArray);
  121. if ($themePos === false) {
  122. $themePos = $themeOrderAdditional++;
  123. }
  124. if (isset($xmlColour->sysClr)) {
  125. $xmlColourData = $xmlColour->sysClr->attributes();
  126. $themeColours[$themePos] = $xmlColourData['lastClr'];
  127. } elseif (isset($xmlColour->srgbClr)) {
  128. $xmlColourData = $xmlColour->srgbClr->attributes();
  129. $themeColours[$themePos] = $xmlColourData['val'];
  130. }
  131. }
  132. self::$theme = new Excel2007Theme($themeName, $colourSchemeName, $themeColours);
  133. }
  134. break;
  135. }
  136. }
  137. // 关于程序包关系的信息
  138. $rels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  139. foreach ($rels->Relationship as $rel) {
  140. switch ($rel["Type"]) {
  141. // Excel文件的元信息
  142. case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties":
  143. $xmlCore = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  144. if (is_object($xmlCore)) {
  145. $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/");
  146. $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/");
  147. $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties");
  148. $docProps = $excel->getProperties();
  149. $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath("dc:creator")));
  150. $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath("cp:lastModifiedBy")));
  151. $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath("dcterms:created")))); //! respect xsi:type
  152. $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type
  153. $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath("dc:title")));
  154. $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath("dc:description")));
  155. $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath("dc:subject")));
  156. $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath("cp:keywords")));
  157. $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath("cp:category")));
  158. }
  159. break;
  160. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties":
  161. $xmlCore = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  162. if (is_object($xmlCore)) {
  163. $docProps = $excel->getProperties();
  164. if (isset($xmlCore->Company)) {
  165. $docProps->setCompany((string) $xmlCore->Company);
  166. }
  167. if (isset($xmlCore->Manager)) {
  168. $docProps->setManager((string) $xmlCore->Manager);
  169. }
  170. }
  171. break;
  172. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties":
  173. $xmlCore = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  174. if (is_object($xmlCore)) {
  175. $docProps = $excel->getProperties();
  176. foreach ($xmlCore as $xmlProperty) {
  177. $cellDataOfficeAttributes = $xmlProperty->attributes();
  178. if (isset($cellDataOfficeAttributes['name'])) {
  179. $propertyName = (string) $cellDataOfficeAttributes['name'];
  180. $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
  181. $attributeType = $cellDataOfficeChildren->getName();
  182. $attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
  183. $attributeValue = DocumentProperties::convertProperty($attributeValue, $attributeType);
  184. $attributeType = DocumentProperties::convertPropertyType($attributeType);
  185. $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
  186. }
  187. }
  188. }
  189. break;
  190. //Ribbon
  191. case "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility":
  192. $customUI = $rel['Target'];
  193. if (!is_null($customUI)) {
  194. $this->readRibbon($excel, $customUI, $zip);
  195. }
  196. break;
  197. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
  198. $dir = dirname($rel["Target"]);
  199. $relsWorkbook = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  200. $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
  201. $sharedStrings = array();
  202. $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
  203. $xmlStrings = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  204. if (isset($xmlStrings) && isset($xmlStrings->si)) {
  205. // 所有共享文字
  206. foreach ($xmlStrings->si as $val) {
  207. if (isset($val->t)) {
  208. $sharedStrings[] = PHPExcelString::ControlCharacterOOXML2PHP((string) $val->t);
  209. } elseif (isset($val->r)) {
  210. //$sharedStrings[] = $this->parseRichText($val);
  211. }
  212. }
  213. }
  214. // 提取所有的工作表rId
  215. $worksheets = array();
  216. $macros = $customUI = null;
  217. foreach ($relsWorkbook->Relationship as $ele) {
  218. switch ($ele['Type']) {
  219. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet":
  220. $worksheets[(string) $ele["Id"]] = $ele["Target"];
  221. break;
  222. case "http://schemas.microsoft.com/office/2006/relationships/vbaProject":
  223. $macros = $ele["Target"];
  224. break;
  225. }
  226. }
  227. if (!is_null($macros)) {
  228. $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin');//vbaProject.bin always in 'xl' dir and always named vbaProject.bin
  229. if ($macrosCode !== false) {
  230. $excel->setMacrosCode($macrosCode);
  231. $excel->setHasMacros(true);
  232. //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
  233. $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
  234. if ($Certificate !== false) {
  235. $excel->setMacrosCertificate($Certificate);
  236. }
  237. }
  238. }
  239. $styles = array();
  240. $cellStyles = array();
  241. $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
  242. $xmlStyles = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  243. $numFmts = null;
  244. if ($xmlStyles && $xmlStyles->numFmts[0]) {
  245. $numFmts = $xmlStyles->numFmts[0];
  246. }
  247. if (isset($numFmts) && ($numFmts !== null)) {
  248. $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  249. }
  250. if (!$this->readDataOnly && $xmlStyles) {
  251. foreach ($xmlStyles->cellXfs->xf as $xf) {
  252. $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  253. if ($xf["numFmtId"]) {
  254. if (isset($numFmts)) {
  255. $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
  256. if (isset($tmpNumFmt["formatCode"])) {
  257. $numFmt = (string) $tmpNumFmt["formatCode"];
  258. }
  259. }
  260. // We shouldn't override any of the built-in MS Excel values (values below id 164)
  261. // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
  262. // So we make allowance for them rather than lose formatting masks
  263. if ((int)$xf["numFmtId"] < 164 && PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]) !== '') {
  264. $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
  265. }
  266. }
  267. $quotePrefix = false;
  268. if (isset($xf["quotePrefix"])) {
  269. $quotePrefix = (boolean) $xf["quotePrefix"];
  270. }
  271. $style = (object) array(
  272. "numFmt" => $numFmt,
  273. "font" => $xmlStyles->fonts->font[intval($xf["fontId"])],
  274. "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])],
  275. "border" => $xmlStyles->borders->border[intval($xf["borderId"])],
  276. "alignment" => $xf->alignment,
  277. "protection" => $xf->protection,
  278. "quotePrefix" => $quotePrefix,
  279. );
  280. $styles[] = $style;
  281. // add style to cellXf collection
  282. $objStyle = new PHPExcel_Style;
  283. self::readStyle($objStyle, $style);
  284. $excel->addCellXf($objStyle);
  285. }
  286. foreach ($xmlStyles->cellStyleXfs->xf as $xf) {
  287. $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  288. if ($numFmts && $xf["numFmtId"]) {
  289. $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
  290. if (isset($tmpNumFmt["formatCode"])) {
  291. $numFmt = (string) $tmpNumFmt["formatCode"];
  292. } elseif ((int)$xf["numFmtId"] < 165) {
  293. $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
  294. }
  295. }
  296. $cellStyle = (object) array(
  297. "numFmt" => $numFmt,
  298. "font" => $xmlStyles->fonts->font[intval($xf["fontId"])],
  299. "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])],
  300. "border" => $xmlStyles->borders->border[intval($xf["borderId"])],
  301. "alignment" => $xf->alignment,
  302. "protection" => $xf->protection,
  303. "quotePrefix" => $quotePrefix,
  304. );
  305. $cellStyles[] = $cellStyle;
  306. // add style to cellStyleXf collection
  307. $objStyle = new PHPExcel_Style;
  308. self::readStyle($objStyle, $cellStyle);
  309. $excel->addCellStyleXf($objStyle);
  310. }
  311. }
  312. $dxfs = array();
  313. if (!$this->readDataOnly && $xmlStyles) {
  314. // Conditional Styles
  315. if ($xmlStyles->dxfs) {
  316. foreach ($xmlStyles->dxfs->dxf as $dxf) {
  317. $style = new PHPExcel_Style(false, true);
  318. self::readStyle($style, $dxf);
  319. $dxfs[] = $style;
  320. }
  321. }
  322. // Cell Styles
  323. if ($xmlStyles->cellStyles) {
  324. foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
  325. if (intval($cellStyle['builtinId']) == 0) {
  326. if (isset($cellStyles[intval($cellStyle['xfId'])])) {
  327. // Set default style
  328. $style = new PHPExcel_Style;
  329. self::readStyle($style, $cellStyles[intval($cellStyle['xfId'])]);
  330. // normal style, currently not using it for anything
  331. }
  332. }
  333. }
  334. }
  335. }
  336. $xmlWorkbook = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  337. // Set base date
  338. if ($xmlWorkbook->workbookPr) {
  339. PHPExcelDate::setExcelCalendar(PHPExcelDate::CALENDAR_WINDOWS_1900);
  340. if (isset($xmlWorkbook->workbookPr['date1904'])) {
  341. if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) {
  342. PHPExcelDate::setExcelCalendar(PHPExcelDate::CALENDAR_MAC_1904);
  343. }
  344. }
  345. }
  346. $sheetId = 0; // keep track of new sheet id in final workbook
  347. $oldSheetId = -1; // keep track of old sheet id in final workbook
  348. $countSkippedSheets = 0; // keep track of number of skipped sheets
  349. $mapSheetId = array(); // mapping of sheet ids from old to new
  350. $charts = $chartDetails = array();
  351. // 处理每个工作表
  352. if ($xmlWorkbook->sheets) {
  353. foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
  354. ++$oldSheetId;
  355. // Check if sheet should be skipped
  356. if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->loadSheetsOnly)) {
  357. ++$countSkippedSheets;
  358. $mapSheetId[$oldSheetId] = null;
  359. continue;
  360. }
  361. // Map old sheet id in original workbook to new sheet id.
  362. // They will differ if loadSheetsOnly() is being used
  363. $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
  364. // Load sheet
  365. $docSheet = $excel->createSheet();
  366. $docSheet->setTitle((string) $eleSheet["name"], false);
  367. $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  368. $xmlSheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  369. $sharedFormulas = array();
  370. if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') {
  371. $docSheet->setSheetState((string) $eleSheet["state"]);
  372. }
  373. if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) {
  374. if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
  375. $docSheet->getSheetView()->setZoomScale(intval($xmlSheet->sheetViews->sheetView['zoomScale']));
  376. }
  377. if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
  378. $docSheet->getSheetView()->setZoomScaleNormal(intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal']));
  379. }
  380. if (isset($xmlSheet->sheetViews->sheetView['view'])) {
  381. $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
  382. }
  383. if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
  384. $docSheet->setShowGridLines(self::boolean((string)$xmlSheet->sheetViews->sheetView['showGridLines']));
  385. }
  386. if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
  387. $docSheet->setShowRowColHeaders(self::boolean((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders']));
  388. }
  389. if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
  390. $docSheet->setRightToLeft(self::boolean((string)$xmlSheet->sheetViews->sheetView['rightToLeft']));
  391. }
  392. if (isset($xmlSheet->sheetViews->sheetView->pane)) {
  393. if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
  394. $docSheet->freezePane((string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell']);
  395. } else {
  396. $xSplit = 0;
  397. $ySplit = 0;
  398. if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
  399. $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']);
  400. }
  401. if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
  402. $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']);
  403. }
  404. $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit);
  405. }
  406. }
  407. if (isset($xmlSheet->sheetViews->sheetView->selection)) {
  408. if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
  409. $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref'];
  410. $sqref = explode(' ', $sqref);
  411. $sqref = $sqref[0];
  412. $docSheet->setSelectedCells($sqref);
  413. }
  414. }
  415. }
  416. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) {
  417. if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
  418. $docSheet->getTabColor()->setARGB((string)$xmlSheet->sheetPr->tabColor['rgb']);
  419. }
  420. }
  421. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr['codeName'])) {
  422. $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName']);
  423. }
  424. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) {
  425. if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
  426. !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
  427. $docSheet->setShowSummaryRight(false);
  428. } else {
  429. $docSheet->setShowSummaryRight(true);
  430. }
  431. if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
  432. !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
  433. $docSheet->setShowSummaryBelow(false);
  434. } else {
  435. $docSheet->setShowSummaryBelow(true);
  436. }
  437. }
  438. if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) {
  439. if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) &&
  440. !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) {
  441. $docSheet->getPageSetup()->setFitToPage(false);
  442. } else {
  443. $docSheet->getPageSetup()->setFitToPage(true);
  444. }
  445. }
  446. if (isset($xmlSheet->sheetFormatPr)) {
  447. if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
  448. self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
  449. isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
  450. $docSheet->getDefaultRowDimension()->setRowHeight((float)$xmlSheet->sheetFormatPr['defaultRowHeight']);
  451. }
  452. if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
  453. $docSheet->getDefaultColumnDimension()->setWidth((float)$xmlSheet->sheetFormatPr['defaultColWidth']);
  454. }
  455. if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
  456. ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
  457. $docSheet->getDefaultRowDimension()->setZeroHeight(true);
  458. }
  459. }
  460. if (isset($xmlSheet->cols) && !$this->readDataOnly) {
  461. foreach ($xmlSheet->cols->col as $col) {
  462. for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) {
  463. if ($col["style"] && !$this->readDataOnly) {
  464. $docSheet->getColumnDimension(Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"]));
  465. }
  466. if (self::boolean($col["bestFit"])) {
  467. //$docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(true);
  468. }
  469. if (self::boolean($col["hidden"])) {
  470. // echo PHPExcel_Cell::stringFromColumnIndex($i), ': HIDDEN COLUMN',PHP_EOL;
  471. $docSheet->getColumnDimension(Cell::stringFromColumnIndex($i))->setVisible(false);
  472. }
  473. if (self::boolean($col["collapsed"])) {
  474. $docSheet->getColumnDimension(Cell::stringFromColumnIndex($i))->setCollapsed(true);
  475. }
  476. if ($col["outlineLevel"] > 0) {
  477. $docSheet->getColumnDimension(Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"]));
  478. }
  479. $docSheet->getColumnDimension(Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"]));
  480. if (intval($col["max"]) == 16384) {
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
  487. if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
  488. $docSheet->setShowGridlines(true);
  489. }
  490. if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
  491. $docSheet->setPrintGridlines(true);
  492. }
  493. if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
  494. $docSheet->getPageSetup()->setHorizontalCentered(true);
  495. }
  496. if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
  497. $docSheet->getPageSetup()->setVerticalCentered(true);
  498. }
  499. }
  500. if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
  501. foreach ($xmlSheet->sheetData->row as $row) {
  502. if ($row["ht"] && !$this->readDataOnly) {
  503. $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"]));
  504. }
  505. if (self::boolean($row["hidden"]) && !$this->readDataOnly) {
  506. $docSheet->getRowDimension(intval($row["r"]))->setVisible(false);
  507. }
  508. if (self::boolean($row["collapsed"])) {
  509. $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(true);
  510. }
  511. if ($row["outlineLevel"] > 0) {
  512. $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"]));
  513. }
  514. if ($row["s"] && !$this->readDataOnly) {
  515. $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"]));
  516. }
  517. foreach ($row->c as $c) {
  518. $r = (string) $c["r"];
  519. $cellDataType = (string) $c["t"];
  520. $value = null;
  521. $calculatedValue = null;
  522. // Read cell?
  523. if ($this->getReadFilter() !== null) {
  524. $coordinates = Cell::coordinateFromString($r);
  525. if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) {
  526. continue;
  527. }
  528. }
  529. // echo 'Reading cell ', $coordinates[0], $coordinates[1], PHP_EOL;
  530. // print_r($c);
  531. // echo PHP_EOL;
  532. // echo 'Cell Data Type is ', $cellDataType, ': ';
  533. //
  534. // Read cell!
  535. switch ($cellDataType) {
  536. case "s":
  537. // echo 'String', PHP_EOL;
  538. if ((string)$c->v != '') {
  539. $value = $sharedStrings[intval($c->v)];
  540. if ($value instanceof RichText) {
  541. $value = clone $value;
  542. }
  543. } else {
  544. $value = '';
  545. }
  546. break;
  547. case "b":
  548. // echo 'Boolean', PHP_EOL;
  549. if (!isset($c->f)) {
  550. $value = self::castToBoolean($c);
  551. } else {
  552. // Formula
  553. $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
  554. if (isset($c->f['t'])) {
  555. $att = array();
  556. $att = $c->f;
  557. $docSheet->getCell($r)->setFormulaAttributes($att);
  558. }
  559. // echo '$calculatedValue = ', $calculatedValue, PHP_EOL;
  560. }
  561. break;
  562. case "inlineStr":
  563. // echo 'Inline String', PHP_EOL;
  564. if (isset($c->f)) {
  565. $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
  566. } else {
  567. $value = $this->parseRichText($c->is);
  568. }
  569. break;
  570. case "e":
  571. // echo 'Error', PHP_EOL;
  572. if (!isset($c->f)) {
  573. $value = self::castToError($c);
  574. } else {
  575. // Formula
  576. $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
  577. // echo '$calculatedValue = ', $calculatedValue, PHP_EOL;
  578. }
  579. break;
  580. default:
  581. // echo 'Default', PHP_EOL;
  582. if (!isset($c->f)) {
  583. // echo 'Not a Formula', PHP_EOL;
  584. $value = self::castToString($c);
  585. } else {
  586. // echo 'Treat as Formula', PHP_EOL;
  587. // Formula
  588. $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
  589. // echo '$calculatedValue = ', $calculatedValue, PHP_EOL;
  590. }
  591. break;
  592. }
  593. // echo 'Value is ', $value, PHP_EOL;
  594. // Check for numeric values
  595. if (is_numeric($value) && $cellDataType != 's') {
  596. if ($value == (int)$value) {
  597. $value = (int)$value;
  598. } elseif ($value == (float)$value) {
  599. $value = (float)$value;
  600. } elseif ($value == (double)$value) {
  601. $value = (double)$value;
  602. }
  603. }
  604. // Rich text?
  605. if ($value instanceof RichText && $this->readDataOnly) {
  606. $value = $value->getPlainText();
  607. }
  608. $cell = $docSheet->getCell($r);
  609. // Assign value
  610. if ($cellDataType != '') {
  611. $cell->setValueExplicit($value, $cellDataType);
  612. } else {
  613. $cell->setValue($value);
  614. }
  615. if ($calculatedValue !== null) {
  616. $cell->setCalculatedValue($calculatedValue);
  617. }
  618. // Style information?
  619. if ($c["s"] && !$this->readDataOnly) {
  620. // no style index means 0, it seems
  621. $cell->setXfIndex(isset($styles[intval($c["s"])]) ?
  622. intval($c["s"]) : 0);
  623. }
  624. }
  625. }
  626. }
  627. $conditionals = array();
  628. if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
  629. foreach ($xmlSheet->conditionalFormatting as $conditional) {
  630. foreach ($conditional->cfRule as $cfRule) {
  631. if (((string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_NONE || (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CELLIS || (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT || (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) && isset($dxfs[intval($cfRule["dxfId"])])) {
  632. $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule;
  633. }
  634. }
  635. }
  636. foreach ($conditionals as $ref => $cfRules) {
  637. ksort($cfRules);
  638. $conditionalStyles = array();
  639. foreach ($cfRules as $cfRule) {
  640. $objConditional = new PHPExcel_Style_Conditional();
  641. $objConditional->setConditionType((string)$cfRule["type"]);
  642. $objConditional->setOperatorType((string)$cfRule["operator"]);
  643. if ((string)$cfRule["text"] != '') {
  644. $objConditional->setText((string)$cfRule["text"]);
  645. }
  646. if (count($cfRule->formula) > 1) {
  647. foreach ($cfRule->formula as $formula) {
  648. $objConditional->addCondition((string)$formula);
  649. }
  650. } else {
  651. $objConditional->addCondition((string)$cfRule->formula);
  652. }
  653. $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]);
  654. $conditionalStyles[] = $objConditional;
  655. }
  656. // Extract all cell references in $ref
  657. $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
  658. foreach ($cellBlocks as $cellBlock) {
  659. $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
  660. }
  661. }
  662. }
  663. $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells");
  664. if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  665. foreach ($aKeys as $key) {
  666. $method = "set" . ucfirst($key);
  667. $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
  668. }
  669. }
  670. if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  671. $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], true);
  672. if ($xmlSheet->protectedRanges->protectedRange) {
  673. foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
  674. $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true);
  675. }
  676. }
  677. }
  678. if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
  679. $autoFilterRange = (string) $xmlSheet->autoFilter["ref"];
  680. if (strpos($autoFilterRange, ':') !== false) {
  681. $autoFilter = $docSheet->getAutoFilter();
  682. $autoFilter->setRange($autoFilterRange);
  683. foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
  684. $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]);
  685. // Check for standard filters
  686. if ($filterColumn->filters) {
  687. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER);
  688. $filters = $filterColumn->filters;
  689. if ((isset($filters["blank"])) && ($filters["blank"] == 1)) {
  690. // Operator is undefined, but always treated as EQUAL
  691. $column->createRule()->setRule(null, '')->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER);
  692. }
  693. // Standard filters are always an OR join, so no join rule needs to be set
  694. // Entries can be either filter elements
  695. foreach ($filters->filter as $filterRule) {
  696. // Operator is undefined, but always treated as EQUAL
  697. $column->createRule()->setRule(null, (string) $filterRule["val"])->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER);
  698. }
  699. // Or Date Group elements
  700. foreach ($filters->dateGroupItem as $dateGroupItem) {
  701. $column->createRule()->setRule(
  702. // Operator is undefined, but always treated as EQUAL
  703. null,
  704. array(
  705. 'year' => (string) $dateGroupItem["year"],
  706. 'month' => (string) $dateGroupItem["month"],
  707. 'day' => (string) $dateGroupItem["day"],
  708. 'hour' => (string) $dateGroupItem["hour"],
  709. 'minute' => (string) $dateGroupItem["minute"],
  710. 'second' => (string) $dateGroupItem["second"],
  711. ),
  712. (string) $dateGroupItem["dateTimeGrouping"]
  713. )
  714. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP);
  715. }
  716. }
  717. // Check for custom filters
  718. if ($filterColumn->customFilters) {
  719. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
  720. $customFilters = $filterColumn->customFilters;
  721. // Custom filters can an AND or an OR join;
  722. // and there should only ever be one or two entries
  723. if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) {
  724. $column->setJoin(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
  725. }
  726. foreach ($customFilters->customFilter as $filterRule) {
  727. $column->createRule()->setRule(
  728. (string) $filterRule["operator"],
  729. (string) $filterRule["val"]
  730. )
  731. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
  732. }
  733. }
  734. // Check for dynamic filters
  735. if ($filterColumn->dynamicFilter) {
  736. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
  737. // We should only ever have one dynamic filter
  738. foreach ($filterColumn->dynamicFilter as $filterRule) {
  739. $column->createRule()->setRule(
  740. // Operator is undefined, but always treated as EQUAL
  741. null,
  742. (string) $filterRule["val"],
  743. (string) $filterRule["type"]
  744. )
  745. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
  746. if (isset($filterRule["val"])) {
  747. $column->setAttribute('val', (string) $filterRule["val"]);
  748. }
  749. if (isset($filterRule["maxVal"])) {
  750. $column->setAttribute('maxVal', (string) $filterRule["maxVal"]);
  751. }
  752. }
  753. }
  754. // Check for dynamic filters
  755. if ($filterColumn->top10) {
  756. $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
  757. // We should only ever have one top10 filter
  758. foreach ($filterColumn->top10 as $filterRule) {
  759. $column->createRule()->setRule(
  760. (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1))
  761. ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
  762. : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
  763. ),
  764. (string) $filterRule["val"],
  765. (((isset($filterRule["top"])) && ($filterRule["top"] == 1))
  766. ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
  767. : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
  768. )
  769. )
  770. ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
  771. }
  772. }
  773. }
  774. }
  775. }
  776. if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
  777. foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
  778. $mergeRef = (string) $mergeCell["ref"];
  779. if (strpos($mergeRef, ':') !== false) {
  780. $docSheet->mergeCells((string) $mergeCell["ref"]);
  781. }
  782. }
  783. }
  784. if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
  785. $docPageMargins = $docSheet->getPageMargins();
  786. $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"]));
  787. $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"]));
  788. $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"]));
  789. $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"]));
  790. $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"]));
  791. $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"]));
  792. }
  793. if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
  794. $docPageSetup = $docSheet->getPageSetup();
  795. if (isset($xmlSheet->pageSetup["orientation"])) {
  796. $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]);
  797. }
  798. if (isset($xmlSheet->pageSetup["paperSize"])) {
  799. $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"]));
  800. }
  801. if (isset($xmlSheet->pageSetup["scale"])) {
  802. $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), false);
  803. }
  804. if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) {
  805. $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), false);
  806. }
  807. if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) {
  808. $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), false);
  809. }
  810. if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) &&
  811. self::boolean((string) $xmlSheet->pageSetup["useFirstPageNumber"])) {
  812. $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"]));
  813. }
  814. }
  815. if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
  816. $docHeaderFooter = $docSheet->getHeaderFooter();
  817. if (isset($xmlSheet->headerFooter["differentOddEven"]) &&
  818. self::boolean((string)$xmlSheet->headerFooter["differentOddEven"])) {
  819. $docHeaderFooter->setDifferentOddEven(true);
  820. } else {
  821. $docHeaderFooter->setDifferentOddEven(false);
  822. }
  823. if (isset($xmlSheet->headerFooter["differentFirst"]) &&
  824. self::boolean((string)$xmlSheet->headerFooter["differentFirst"])) {
  825. $docHeaderFooter->setDifferentFirst(true);
  826. } else {
  827. $docHeaderFooter->setDifferentFirst(false);
  828. }
  829. if (isset($xmlSheet->headerFooter["scaleWithDoc"]) &&
  830. !self::boolean((string)$xmlSheet->headerFooter["scaleWithDoc"])) {
  831. $docHeaderFooter->setScaleWithDocument(false);
  832. } else {
  833. $docHeaderFooter->setScaleWithDocument(true);
  834. }
  835. if (isset($xmlSheet->headerFooter["alignWithMargins"]) &&
  836. !self::boolean((string)$xmlSheet->headerFooter["alignWithMargins"])) {
  837. $docHeaderFooter->setAlignWithMargins(false);
  838. } else {
  839. $docHeaderFooter->setAlignWithMargins(true);
  840. }
  841. $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
  842. $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
  843. $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
  844. $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
  845. $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
  846. $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
  847. }
  848. if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
  849. foreach ($xmlSheet->rowBreaks->brk as $brk) {
  850. if ($brk["man"]) {
  851. $docSheet->setBreak("A$brk[id]", PHPExcel_Worksheet::BREAK_ROW);
  852. }
  853. }
  854. }
  855. if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
  856. foreach ($xmlSheet->colBreaks->brk as $brk) {
  857. if ($brk["man"]) {
  858. $docSheet->setBreak(PHPExcel_Cell::stringFromColumnIndex((string) $brk["id"]) . "1", PHPExcel_Worksheet::BREAK_COLUMN);
  859. }
  860. }
  861. }
  862. if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
  863. foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
  864. // Uppercase coordinate
  865. $range = strtoupper($dataValidation["sqref"]);
  866. $rangeSet = explode(' ', $range);
  867. foreach ($rangeSet as $range) {
  868. $stRange = $docSheet->shrinkRangeToFit($range);
  869. // Extract all cell references in $range
  870. foreach (PHPExcel_Cell::extractAllCellReferencesInRange($stRange) as $reference) {
  871. // Create validation
  872. $docValidation = $docSheet->getCell($reference)->getDataValidation();
  873. $docValidation->setType((string) $dataValidation["type"]);
  874. $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]);
  875. $docValidation->setOperator((string) $dataValidation["operator"]);
  876. $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0);
  877. $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0);
  878. $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0);
  879. $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0);
  880. $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]);
  881. $docValidation->setError((string) $dataValidation["error"]);
  882. $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]);
  883. $docValidation->setPrompt((string) $dataValidation["prompt"]);
  884. $docValidation->setFormula1((string) $dataValidation->formula1);
  885. $docValidation->setFormula2((string) $dataValidation->formula2);
  886. }
  887. }
  888. }
  889. }
  890. // Add hyperlinks
  891. $hyperlinks = array();
  892. if (!$this->readDataOnly) {
  893. // Locate hyperlink relations
  894. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  895. $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  896. foreach ($relsWorksheet->Relationship as $ele) {
  897. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") {
  898. $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"];
  899. }
  900. }
  901. }
  902. // Loop through hyperlinks
  903. if ($xmlSheet && $xmlSheet->hyperlinks) {
  904. foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
  905. // Link url
  906. $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  907. foreach (PHPExcel_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
  908. $cell = $docSheet->getCell($cellReference);
  909. if (isset($linkRel['id'])) {
  910. $hyperlinkUrl = $hyperlinks[ (string)$linkRel['id'] ];
  911. if (isset($hyperlink['location'])) {
  912. $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
  913. }
  914. $cell->getHyperlink()->setUrl($hyperlinkUrl);
  915. } elseif (isset($hyperlink['location'])) {
  916. $cell->getHyperlink()->setUrl('sheet://' . (string)$hyperlink['location']);
  917. }
  918. // Tooltip
  919. if (isset($hyperlink['tooltip'])) {
  920. $cell->getHyperlink()->setTooltip((string)$hyperlink['tooltip']);
  921. }
  922. }
  923. }
  924. }
  925. }
  926. // Add comments
  927. $comments = array();
  928. $vmlComments = array();
  929. if (!$this->readDataOnly) {
  930. // Locate comment relations
  931. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  932. $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  933. foreach ($relsWorksheet->Relationship as $ele) {
  934. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") {
  935. $comments[(string)$ele["Id"]] = (string)$ele["Target"];
  936. }
  937. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  938. $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"];
  939. }
  940. }
  941. }
  942. // Loop through comments
  943. foreach ($comments as $relName => $relPath) {
  944. // Load comments file
  945. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  946. $commentsFile = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $relPath)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  947. // Utility variables
  948. $authors = array();
  949. // Loop through authors
  950. foreach ($commentsFile->authors->author as $author) {
  951. $authors[] = (string)$author;
  952. }
  953. // Loop through contents
  954. foreach ($commentsFile->commentList->comment as $comment) {
  955. if (!empty($comment['authorId'])) {
  956. $docSheet->getComment((string)$comment['ref'])->setAuthor($authors[(string)$comment['authorId']]);
  957. }
  958. $docSheet->getComment((string)$comment['ref'])->setText($this->parseRichText($comment->text));
  959. }
  960. }
  961. // Loop through VML comments
  962. foreach ($vmlComments as $relName => $relPath) {
  963. // Load VML comments file
  964. $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath);
  965. $vmlCommentsFile = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $relPath)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  966. $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  967. $shapes = $vmlCommentsFile->xpath('//v:shape');
  968. foreach ($shapes as $shape) {
  969. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  970. if (isset($shape['style'])) {
  971. $style = (string)$shape['style'];
  972. $fillColor = strtoupper(substr((string)$shape['fillcolor'], 1));
  973. $column = null;
  974. $row = null;
  975. $clientData = $shape->xpath('.//x:ClientData');
  976. if (is_array($clientData) && !empty($clientData)) {
  977. $clientData = $clientData[0];
  978. if (isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note') {
  979. $temp = $clientData->xpath('.//x:Row');
  980. if (is_array($temp)) {
  981. $row = $temp[0];
  982. }
  983. $temp = $clientData->xpath('.//x:Column');
  984. if (is_array($temp)) {
  985. $column = $temp[0];
  986. }
  987. }
  988. }
  989. if (($column !== null) && ($row !== null)) {
  990. // Set comment properties
  991. $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1);
  992. $comment->getFillColor()->setRGB($fillColor);
  993. // Parse style
  994. $styleArray = explode(';', str_replace(' ', '', $style));
  995. foreach ($styleArray as $stylePair) {
  996. $stylePair = explode(':', $stylePair);
  997. if ($stylePair[0] == 'margin-left') {
  998. $comment->setMarginLeft($stylePair[1]);
  999. }
  1000. if ($stylePair[0] == 'margin-top') {
  1001. $comment->setMarginTop($stylePair[1]);
  1002. }
  1003. if ($stylePair[0] == 'width') {
  1004. $comment->setWidth($stylePair[1]);
  1005. }
  1006. if ($stylePair[0] == 'height') {
  1007. $comment->setHeight($stylePair[1]);
  1008. }
  1009. if ($stylePair[0] == 'visibility') {
  1010. $comment->setVisible($stylePair[1] == 'visible');
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. // Header/footer images
  1018. if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
  1019. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1020. $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1021. $vmlRelationship = '';
  1022. foreach ($relsWorksheet->Relationship as $ele) {
  1023. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") {
  1024. $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele["Target"]);
  1025. }
  1026. }
  1027. if ($vmlRelationship != '') {
  1028. // Fetch linked images
  1029. $relsVML = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1030. $drawings = array();
  1031. foreach ($relsVML->Relationship as $ele) {
  1032. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1033. $drawings[(string) $ele["Id"]] = self::dirAdd($vmlRelationship, $ele["Target"]);
  1034. }
  1035. }
  1036. // Fetch VML document
  1037. $vmlDrawing = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  1038. $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1039. $hfImages = array();
  1040. $shapes = $vmlDrawing->xpath('//v:shape');
  1041. foreach ($shapes as $idx => $shape) {
  1042. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1043. $imageData = $shape->xpath('//v:imagedata');
  1044. $imageData = $imageData[$idx];
  1045. $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
  1046. $style = self::toCSSArray((string)$shape['style']);
  1047. $hfImages[ (string)$shape['id'] ] = new PHPExcel_Worksheet_HeaderFooterDrawing();
  1048. if (isset($imageData['title'])) {
  1049. $hfImages[ (string)$shape['id'] ]->setName((string)$imageData['title']);
  1050. }
  1051. $hfImages[ (string)$shape['id'] ]->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $drawings[(string)$imageData['relid']], false);
  1052. $hfImages[ (string)$shape['id'] ]->setResizeProportional(false);
  1053. $hfImages[ (string)$shape['id'] ]->setWidth($style['width']);
  1054. $hfImages[ (string)$shape['id'] ]->setHeight($style['height']);
  1055. if (isset($style['margin-left'])) {
  1056. $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']);
  1057. }
  1058. $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']);
  1059. $hfImages[ (string)$shape['id'] ]->setResizeProportional(true);
  1060. }
  1061. $docSheet->getHeaderFooter()->setImages($hfImages);
  1062. }
  1063. }
  1064. }
  1065. }
  1066. // TODO: Autoshapes from twoCellAnchors!
  1067. if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) {
  1068. $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1069. $drawings = array();
  1070. foreach ($relsWorksheet->Relationship as $ele) {
  1071. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") {
  1072. $drawings[(string) $ele["Id"]] = self::dirAdd("$dir/$fileWorksheet", $ele["Target"]);
  1073. }
  1074. }
  1075. if ($xmlSheet->drawing && !$this->readDataOnly) {
  1076. foreach ($xmlSheet->drawing as $drawing) {
  1077. $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")];
  1078. $relsDrawing = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships");
  1079. $images = array();
  1080. if ($relsDrawing && $relsDrawing->Relationship) {
  1081. foreach ($relsDrawing->Relationship as $ele) {
  1082. if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") {
  1083. $images[(string) $ele["Id"]] = self::dirAdd($fileDrawing, $ele["Target"]);
  1084. } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") {
  1085. if ($this->includeCharts) {
  1086. $charts[self::dirAdd($fileDrawing, $ele["Target"])] = array(
  1087. 'id' => (string) $ele["Id"],
  1088. 'sheet' => $docSheet->getTitle()
  1089. );
  1090. }
  1091. }
  1092. }
  1093. }
  1094. $xmlDrawing = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $fileDrawing)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions())->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
  1095. if ($xmlDrawing->oneCellAnchor) {
  1096. foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
  1097. if ($oneCellAnchor->pic->blipFill) {
  1098. $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1099. $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1100. $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1101. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1102. $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1103. $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1104. $objDrawing->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $images[(string) self::getArrayItem($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1105. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1));
  1106. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff));
  1107. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
  1108. $objDrawing->setResizeProportional(false);
  1109. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cx")));
  1110. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cy")));
  1111. if ($xfrm) {
  1112. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), "rot")));
  1113. }
  1114. if ($outerShdw) {
  1115. $shadow = $objDrawing->getShadow();
  1116. $shadow->setVisible(true);
  1117. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "blurRad")));
  1118. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "dist")));
  1119. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), "dir")));
  1120. $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), "algn"));
  1121. $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), "val"));
  1122. $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1123. }
  1124. $objDrawing->setWorksheet($docSheet);
  1125. } else {
  1126. // ? Can charts be positioned with a oneCellAnchor ?
  1127. $coordinates = PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1);
  1128. $offsetX = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff);
  1129. $offsetY = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
  1130. $width = PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cx"));
  1131. $height = PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cy"));
  1132. }
  1133. }
  1134. }
  1135. if ($xmlDrawing->twoCellAnchor) {
  1136. foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
  1137. if ($twoCellAnchor->pic->blipFill) {
  1138. $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip;
  1139. $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm;
  1140. $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw;
  1141. $objDrawing = new PHPExcel_Worksheet_Drawing;
  1142. $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name"));
  1143. $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr"));
  1144. $objDrawing->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $images[(string) self::getArrayItem($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false);
  1145. $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1));
  1146. $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff));
  1147. $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
  1148. $objDrawing->setResizeProportional(false);
  1149. if ($xfrm) {
  1150. $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), "cx")));
  1151. $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), "cy")));
  1152. $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), "rot")));
  1153. }
  1154. if ($outerShdw) {
  1155. $shadow = $objDrawing->getShadow();
  1156. $shadow->setVisible(true);
  1157. $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "blurRad")));
  1158. $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "dist")));
  1159. $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), "dir")));
  1160. $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), "algn"));
  1161. $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), "val"));
  1162. $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), "val") / 1000);
  1163. }
  1164. $objDrawing->setWorksheet($docSheet);
  1165. } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
  1166. $fromCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1);
  1167. $fromOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff);
  1168. $fromOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
  1169. $toCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1);
  1170. $toOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff);
  1171. $toOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
  1172. $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic;
  1173. $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart;
  1174. $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships");
  1175. $chartDetails[$docSheet->getTitle().'!'.$thisChart] = array(
  1176. 'fromCoordinate' => $fromCoordinate,
  1177. 'fromOffsetX' => $fromOffsetX,
  1178. 'fromOffsetY' => $fromOffsetY,
  1179. 'toCoordinate' => $toCoordinate,
  1180. 'toOffsetX' => $toOffsetX,
  1181. 'toOffsetY' => $toOffsetY,
  1182. 'worksheetTitle' => $docSheet->getTitle()
  1183. );
  1184. }
  1185. }
  1186. }
  1187. }
  1188. }
  1189. }
  1190. // Loop through definedNames
  1191. if ($xmlWorkbook->definedNames) {
  1192. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1193. // Extract range
  1194. $extractedRange = (string)$definedName;
  1195. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1196. if (($spos = strpos($extractedRange, '!')) !== false) {
  1197. $extractedRange = substr($extractedRange, 0, $spos).str_replace('$', '', substr($extractedRange, $spos));
  1198. } else {
  1199. $extractedRange = str_replace('$', '', $extractedRange);
  1200. }
  1201. // Valid range?
  1202. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1203. continue;
  1204. }
  1205. // Some definedNames are only applicable if we are on the same sheet...
  1206. if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) {
  1207. // Switch on type
  1208. switch ((string)$definedName['name']) {
  1209. case '_xlnm._FilterDatabase':
  1210. if ((string)$definedName['hidden'] !== '1') {
  1211. $extractedRange = explode(',', $extractedRange);
  1212. foreach ($extractedRange as $range) {
  1213. $autoFilterRange = $range;
  1214. if (strpos($autoFilterRange, ':') !== false) {
  1215. $docSheet->getAutoFilter()->setRange($autoFilterRange);
  1216. }
  1217. }
  1218. }
  1219. break;
  1220. case '_xlnm.Print_Titles':
  1221. // Split $extractedRange
  1222. $extractedRange = explode(',', $extractedRange);
  1223. // Set print titles
  1224. foreach ($extractedRange as $range) {
  1225. $matches = array();
  1226. $range = str_replace('$', '', $range);
  1227. // check for repeating columns, e g. 'A:A' or 'A:D'
  1228. if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
  1229. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2]));
  1230. } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
  1231. // check for repeating rows, e.g. '1:1' or '1:5'
  1232. $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2]));
  1233. }
  1234. }
  1235. break;
  1236. case '_xlnm.Print_Area':
  1237. $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma?
  1238. $newRangeSets = array();
  1239. foreach ($rangeSets as $rangeSet) {
  1240. $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark?
  1241. $rangeSet = isset($range[1]) ? $range[1] : $range[0];
  1242. if (strpos($rangeSet, ':') === false) {
  1243. $rangeSet = $rangeSet . ':' . $rangeSet;
  1244. }
  1245. $newRangeSets[] = str_replace('$', '', $rangeSet);
  1246. }
  1247. $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
  1248. break;
  1249. default:
  1250. break;
  1251. }
  1252. }
  1253. }
  1254. }
  1255. // Next sheet id
  1256. ++$sheetId;
  1257. }
  1258. // Loop through definedNames
  1259. if ($xmlWorkbook->definedNames) {
  1260. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1261. // Extract range
  1262. $extractedRange = (string)$definedName;
  1263. $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange);
  1264. if (($spos = strpos($extractedRange, '!')) !== false) {
  1265. $extractedRange = substr($extractedRange, 0, $spos).str_replace('$', '', substr($extractedRange, $spos));
  1266. } else {
  1267. $extractedRange = str_replace('$', '', $extractedRange);
  1268. }
  1269. // Valid range?
  1270. if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') {
  1271. continue;
  1272. }
  1273. // Some definedNames are only applicable if we are on the same sheet...
  1274. if ((string)$definedName['localSheetId'] != '') {
  1275. // Local defined name
  1276. // Switch on type
  1277. switch ((string)$definedName['name']) {
  1278. case '_xlnm._FilterDatabase':
  1279. case '_xlnm.Print_Titles':
  1280. case '_xlnm.Print_Area':
  1281. break;
  1282. default:
  1283. if ($mapSheetId[(integer) $definedName['localSheetId']] !== null) {
  1284. $range = explode('!', (string)$definedName);
  1285. if (count($range) == 2) {
  1286. $range[0] = str_replace("''", "'", $range[0]);
  1287. $range[0] = str_replace("'", "", $range[0]);
  1288. if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
  1289. $extractedRange = str_replace('$', '', $range[1]);
  1290. $scope = $docSheet->getParent()->getSheet($mapSheetId[(integer) $definedName['localSheetId']]);
  1291. $excel->addNamedRange(new PHPExcel_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope));
  1292. }
  1293. }
  1294. }
  1295. break;
  1296. }
  1297. } elseif (!isset($definedName['localSheetId'])) {
  1298. // "Global" definedNames
  1299. $locatedSheet = null;
  1300. $extractedSheetName = '';
  1301. if (strpos((string)$definedName, '!') !== false) {
  1302. // Extract sheet name
  1303. $extractedSheetName = PHPExcel_Worksheet::extractSheetTitle((string)$definedName, true);
  1304. $extractedSheetName = $extractedSheetName[0];
  1305. // Locate sheet
  1306. $locatedSheet = $excel->getSheetByName($extractedSheetName);
  1307. // Modify range
  1308. $range = explode('!', $extractedRange);
  1309. $extractedRange = isset($range[1]) ? $range[1] : $range[0];
  1310. }
  1311. if ($locatedSheet !== null) {
  1312. $excel->addNamedRange(new PHPExcel_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false));
  1313. }
  1314. }
  1315. }
  1316. }
  1317. }
  1318. if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) {
  1319. // active sheet index
  1320. $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index
  1321. // keep active sheet index if sheet is still loaded, else first sheet is set as the active
  1322. if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
  1323. $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
  1324. } else {
  1325. if ($excel->getSheetCount() == 0) {
  1326. $excel->createSheet();
  1327. }
  1328. $excel->setActiveSheetIndex(0);
  1329. }
  1330. }
  1331. break;
  1332. }
  1333. }
  1334. if (!$this->readDataOnly) {
  1335. $contentTypes = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "[Content_Types].xml")), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  1336. foreach ($contentTypes->Override as $contentType) {
  1337. switch ($contentType["ContentType"]) {
  1338. case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml":
  1339. if ($this->includeCharts) {
  1340. $chartEntryRef = ltrim($contentType['PartName'], '/');
  1341. $chartElements = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $chartEntryRef)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
  1342. $objChart = PHPExcel_Reader_Excel2007_Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
  1343. // echo 'Chart ', $chartEntryRef, '<br />';
  1344. // var_dump($charts[$chartEntryRef]);
  1345. //
  1346. if (isset($charts[$chartEntryRef])) {
  1347. $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id'];
  1348. // echo 'Position Ref ', $chartPositionRef, '<br />';
  1349. if (isset($chartDetails[$chartPositionRef])) {
  1350. // var_dump($chartDetails[$chartPositionRef]);
  1351. $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
  1352. $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
  1353. $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
  1354. $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
  1355. }
  1356. }
  1357. }
  1358. }
  1359. }
  1360. }
  1361. $zip->close();
  1362. return $excel;
  1363. }
  1364. private function getFromZipArchive($archive, $fileName = '')
  1365. {
  1366. // Root-relative paths
  1367. if (strpos($fileName, '//') !== false) {
  1368. $fileName = substr($fileName, strpos($fileName, '//') + 1);
  1369. }
  1370. $fileName = self::realpath($fileName);
  1371. // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
  1372. // so we need to load case-insensitively from the zip file
  1373. // Apache POI fixes
  1374. $contents = $archive->getFromIndex(
  1375. $archive->locateName($fileName, \ZIPARCHIVE::FL_NOCASE)
  1376. );
  1377. if ($contents === false) {
  1378. $contents = $archive->getFromIndex(
  1379. $archive->locateName(substr($fileName, 1), \ZIPARCHIVE::FL_NOCASE)
  1380. );
  1381. }
  1382. return $contents;
  1383. }
  1384. /**
  1385. * Returns canonicalized absolute pathname, also for ZIP archives
  1386. *
  1387. * @param string $pFilename
  1388. * @return string
  1389. */
  1390. public static function realpath($pFilename)
  1391. {
  1392. // Returnvalue
  1393. $returnValue = '';
  1394. // Try using realpath()
  1395. if (file_exists($pFilename)) {
  1396. $returnValue = realpath($pFilename);
  1397. }
  1398. // Found something?
  1399. if ($returnValue == '' || ($returnValue === null)) {
  1400. $pathArray = explode('/', $pFilename);
  1401. while (in_array('..', $pathArray) && $pathArray[0] != '..') {
  1402. for ($i = 0; $i < count($pathArray); ++$i) {
  1403. if ($pathArray[$i] == '..' && $i > 0) {
  1404. unset($pathArray[$i]);
  1405. unset($pathArray[$i - 1]);
  1406. break;
  1407. }
  1408. }
  1409. }
  1410. $returnValue = implode('/', $pathArray);
  1411. }
  1412. // Return
  1413. return $returnValue;
  1414. }
  1415. /**
  1416. * Verify if a file exists
  1417. *
  1418. * @param string $pFilename Filename
  1419. * @return bool
  1420. */
  1421. public static function file_exists($pFilename)
  1422. {
  1423. // Sick construction, but it seems that
  1424. // file_exists returns strange values when
  1425. // doing the original file_exists on ZIP archives...
  1426. if (strtolower(substr($pFilename, 0, 3)) == 'zip') {
  1427. // Open ZIP file and verify if the file exists
  1428. $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
  1429. $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
  1430. $zip = new \ZipArchive();
  1431. if ($zip->open($zipFile) === true) {
  1432. $returnValue = ($zip->getFromName($archiveFile) !== false);
  1433. $zip->close();
  1434. return $returnValue;
  1435. } else {
  1436. return false;
  1437. }
  1438. } else {
  1439. // Regular file_exists
  1440. return file_exists($pFilename);
  1441. }
  1442. }
  1443. private static function getArrayItem($array, $key = 0)
  1444. {
  1445. return (isset($array[$key]) ? $array[$key] : null);
  1446. }
  1447. private function parseRichText($is = null)
  1448. {
  1449. $value = new PHPExcel_RichText();
  1450. if (isset($is->t)) {
  1451. $value->createText(PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $is->t));
  1452. } else {
  1453. if (is_object($is->r)) {
  1454. foreach ($is->r as $run) {
  1455. if (!isset($run->rPr)) {
  1456. $objText = $value->createText(PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $run->t));
  1457. } else {
  1458. $objText = $value->createTextRun(PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $run->t));
  1459. if (isset($run->rPr->rFont["val"])) {
  1460. $objText->getFont()->setName((string) $run->rPr->rFont["val"]);
  1461. }
  1462. if (isset($run->rPr->sz["val"])) {
  1463. $objText->getFont()->setSize((string) $run->rPr->sz["val"]);
  1464. }
  1465. if (isset($run->rPr->color)) {
  1466. $objText->getFont()->setColor(new PHPExcel_Style_Color(self::readColor($run->rPr->color)));
  1467. }
  1468. if ((isset($run->rPr->b["val"]) && self::boolean((string) $run->rPr->b["val"])) ||
  1469. (isset($run->rPr->b) && !isset($run->rPr->b["val"]))) {
  1470. $objText->getFont()->setBold(true);
  1471. }
  1472. if ((isset($run->rPr->i["val"]) && self::boolean((string) $run->rPr->i["val"])) ||
  1473. (isset($run->rPr->i) && !isset($run->rPr->i["val"]))) {
  1474. $objText->getFont()->setItalic(true);
  1475. }
  1476. if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) {
  1477. $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]);
  1478. if ($vertAlign == 'superscript') {
  1479. $objText->getFont()->setSuperScript(true);
  1480. }
  1481. if ($vertAlign == 'subscript') {
  1482. $objText->getFont()->setSubScript(true);
  1483. }
  1484. }
  1485. if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) {
  1486. $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  1487. } elseif (isset($run->rPr->u) && isset($run->rPr->u["val"])) {
  1488. $objText->getFont()->setUnderline((string)$run->rPr->u["val"]);
  1489. }
  1490. if ((isset($run->rPr->strike["val"]) && self::boolean((string) $run->rPr->strike["val"])) ||
  1491. (isset($run->rPr->strike) && !isset($run->rPr->strike["val"]))) {
  1492. $objText->getFont()->setStrikethrough(true);
  1493. }
  1494. }
  1495. }
  1496. }
  1497. }
  1498. return $value;
  1499. }
  1500. private static function boolean($value = null)
  1501. {
  1502. if (is_object($value)) {
  1503. $value = (string) $value;
  1504. }
  1505. if (is_numeric($value)) {
  1506. return (bool) $value;
  1507. }
  1508. return ($value === 'true' || $value === 'TRUE');
  1509. }
  1510. private static function castToString($c)
  1511. {
  1512. return isset($c->v) ? (string) $c->v : null;
  1513. }
  1514. }