SpreadsheetReader_XLSX.php 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. <?php
  2. class SpreadsheetReader_XLSX implements Iterator, Countable {
  3. const CELL_TYPE_BOOL = 'b';
  4. const CELL_TYPE_NUMBER = 'n';
  5. const CELL_TYPE_ERROR = 'e';
  6. const CELL_TYPE_SHARED_STR = 's';
  7. const CELL_TYPE_STR = 'str';
  8. const CELL_TYPE_INLINE_STR = 'inlineStr';
  9. /**
  10. * Number of shared strings that can be reasonably cached, i.e., that aren't read from file but stored in memory.
  11. * If the total number of shared strings is higher than this, caching is not used.
  12. * If this value is null, shared strings are cached regardless of amount.
  13. * With large shared string caches there are huge performance gains, however a lot of memory could be used which
  14. * can be a problem, especially on shared hosting.
  15. */
  16. const SHARED_STRING_CACHE_LIMIT = 50000;
  17. private $Options = array(
  18. 'TempDir' => '',
  19. 'ReturnDateTimeObjects' => false
  20. );
  21. private static $RuntimeInfo = array(
  22. 'GMPSupported' => false
  23. );
  24. private $Valid = false;
  25. /**
  26. * @var SpreadsheetReader_* Handle for the reader object
  27. */
  28. private $Handle = false;
  29. // Worksheet file
  30. /**
  31. * @var string Path to the worksheet XML file
  32. */
  33. private $WorksheetPath = false;
  34. /**
  35. * @var XMLReader XML reader object for the worksheet XML file
  36. */
  37. private $Worksheet = false;
  38. // Shared strings file
  39. /**
  40. * @var string Path to shared strings XML file
  41. */
  42. private $SharedStringsPath = false;
  43. /**
  44. * @var XMLReader XML reader object for the shared strings XML file
  45. */
  46. private $SharedStrings = false;
  47. /**
  48. * @var array Shared strings cache, if the number of shared strings is low enough
  49. */
  50. private $SharedStringCache = array();
  51. // Workbook data
  52. /**
  53. * @var SimpleXMLElement XML object for the workbook XML file
  54. */
  55. private $WorkbookXML = false;
  56. // Style data
  57. /**
  58. * @var SimpleXMLElement XML object for the styles XML file
  59. */
  60. private $StylesXML = false;
  61. /**
  62. * @var array Container for cell value style data
  63. */
  64. private $Styles = array();
  65. private $TempDir = '';
  66. private $TempFiles = array();
  67. private $CurrentRow = false;
  68. private $rowCount = null;
  69. // Runtime parsing data
  70. /**
  71. * @var int Current row in the file
  72. */
  73. private $Index = 0;
  74. /**
  75. * @var array Data about separate sheets in the file
  76. */
  77. private $Sheets = false;
  78. private $SharedStringCount = 0;
  79. private $SharedStringIndex = 0;
  80. private $LastSharedStringValue = null;
  81. private $RowOpen = false;
  82. private $SSOpen = false;
  83. private $SSForwarded = false;
  84. private static $BuiltinFormats = array(
  85. 0 => '',
  86. 1 => '0',
  87. 2 => '0.00',
  88. 3 => '#,##0',
  89. 4 => '#,##0.00',
  90. 9 => '0%',
  91. 10 => '0.00%',
  92. 11 => '0.00E+00',
  93. 12 => '# ?/?',
  94. 13 => '# ??/??',
  95. 14 => 'mm-dd-yy',
  96. 15 => 'd-mmm-yy',
  97. 16 => 'd-mmm',
  98. 17 => 'mmm-yy',
  99. 18 => 'h:mm AM/PM',
  100. 19 => 'h:mm:ss AM/PM',
  101. 20 => 'h:mm',
  102. 21 => 'h:mm:ss',
  103. 22 => 'm/d/yy h:mm',
  104. 37 => '#,##0 ;(#,##0)',
  105. 38 => '#,##0 ;[Red](#,##0)',
  106. 39 => '#,##0.00;(#,##0.00)',
  107. 40 => '#,##0.00;[Red](#,##0.00)',
  108. 45 => 'mm:ss',
  109. 46 => '[h]:mm:ss',
  110. 47 => 'mmss.0',
  111. 48 => '##0.0E+0',
  112. 49 => '@',
  113. // CHT & CHS
  114. 27 => '[$-404]e/m/d',
  115. 30 => 'm/d/yy',
  116. 36 => '[$-404]e/m/d',
  117. 50 => '[$-404]e/m/d',
  118. 57 => '[$-404]e/m/d',
  119. // THA
  120. 59 => 't0',
  121. 60 => 't0.00',
  122. 61 =>'t#,##0',
  123. 62 => 't#,##0.00',
  124. 67 => 't0%',
  125. 68 => 't0.00%',
  126. 69 => 't# ?/?',
  127. 70 => 't# ??/??'
  128. );
  129. private $Formats = array();
  130. private static $DateReplacements = array(
  131. 'All' => array(
  132. '\\' => '',
  133. 'am/pm' => 'A',
  134. 'yyyy' => 'Y',
  135. 'yy' => 'y',
  136. 'mmmmm' => 'M',
  137. 'mmmm' => 'F',
  138. 'mmm' => 'M',
  139. ':mm' => ':i',
  140. 'mm' => 'm',
  141. 'm' => 'n',
  142. 'dddd' => 'l',
  143. 'ddd' => 'D',
  144. 'dd' => 'd',
  145. 'd' => 'j',
  146. 'ss' => 's',
  147. '.s' => ''
  148. ),
  149. '24H' => array(
  150. 'hh' => 'H',
  151. 'h' => 'G'
  152. ),
  153. '12H' => array(
  154. 'hh' => 'h',
  155. 'h' => 'G'
  156. )
  157. );
  158. private static $BaseDate = false;
  159. private static $DecimalSeparator = '.';
  160. private static $ThousandSeparator = '';
  161. private static $CurrencyCode = '';
  162. /**
  163. * @var array Cache for already processed format strings
  164. */
  165. private $ParsedFormatCache = array();
  166. /**
  167. * @param string Path to file
  168. * @param array Options:
  169. * TempDir => string Temporary directory path
  170. * ReturnDateTimeObjects => bool True => dates and times will be returned as PHP DateTime objects, false => as strings
  171. */
  172. public function __construct($Filepath, array $Options = null)
  173. {
  174. if (!is_readable($Filepath))
  175. {
  176. throw new Exception('SpreadsheetReader_XLSX: File not readable ('.$Filepath.')');
  177. }
  178. $this -> TempDir = isset($Options['TempDir']) && is_writable($Options['TempDir']) ?
  179. $Options['TempDir'] :
  180. sys_get_temp_dir();
  181. $this -> TempDir = rtrim($this -> TempDir, DIRECTORY_SEPARATOR);
  182. $this -> TempDir = $this -> TempDir.DIRECTORY_SEPARATOR.uniqid().DIRECTORY_SEPARATOR;
  183. $Zip = new ZipArchive;
  184. $Status = $Zip -> open($Filepath);
  185. if ($Status !== true)
  186. {
  187. throw new Exception('SpreadsheetReader_XLSX: File not readable ('.$Filepath.') (Error '.$Status.')');
  188. }
  189. // Getting the general workbook information
  190. if ($Zip -> locateName('xl/workbook.xml') !== false)
  191. {
  192. $this -> WorkbookXML = new SimpleXMLElement($Zip -> getFromName('xl/workbook.xml'));
  193. }
  194. // Extracting the XMLs from the XLSX zip file
  195. if ($Zip -> locateName('xl/sharedStrings.xml') !== false)
  196. {
  197. $this -> SharedStringsPath = $this -> TempDir.'xl'.DIRECTORY_SEPARATOR.'sharedStrings.xml';
  198. $Zip -> extractTo($this -> TempDir, 'xl/sharedStrings.xml');
  199. $this -> TempFiles[] = $this -> TempDir.'xl'.DIRECTORY_SEPARATOR.'sharedStrings.xml';
  200. if (is_readable($this -> SharedStringsPath))
  201. {
  202. $this -> SharedStrings = new XMLReader;
  203. $this -> SharedStrings -> open($this -> SharedStringsPath);
  204. $this -> PrepareSharedStringCache();
  205. }
  206. }
  207. $Sheets = $this -> Sheets();
  208. foreach ($this -> Sheets as $Index => $Name)
  209. {
  210. if ($Zip -> locateName('xl/worksheets/sheet'.$Index.'.xml') !== false)
  211. {
  212. $Zip -> extractTo($this -> TempDir, 'xl/worksheets/sheet'.$Index.'.xml');
  213. $this -> TempFiles[] = $this -> TempDir.'xl'.DIRECTORY_SEPARATOR.'worksheets'.DIRECTORY_SEPARATOR.'sheet'.$Index.'.xml';
  214. }
  215. }
  216. $this -> ChangeSheet(0);
  217. // If worksheet is present and is OK, parse the styles already
  218. if ($Zip -> locateName('xl/styles.xml') !== false)
  219. {
  220. $this -> StylesXML = new SimpleXMLElement($Zip -> getFromName('xl/styles.xml'));
  221. if ($this -> StylesXML && $this -> StylesXML -> cellXfs && $this -> StylesXML -> cellXfs -> xf)
  222. {
  223. foreach ($this -> StylesXML -> cellXfs -> xf as $Index => $XF)
  224. {
  225. // Format #0 is a special case - it is the "General" format that is applied regardless of applyNumberFormat
  226. if ($XF -> attributes() -> applyNumberFormat || (0 == (int)$XF -> attributes() -> numFmtId))
  227. {
  228. $FormatId = (int)$XF -> attributes() -> numFmtId;
  229. // If format ID >= 164, it is a custom format and should be read from styleSheet\numFmts
  230. $this -> Styles[] = $FormatId;
  231. }
  232. else
  233. {
  234. // 0 for "General" format
  235. $this -> Styles[] = 0;
  236. }
  237. }
  238. }
  239. if ($this -> StylesXML -> numFmts && $this -> StylesXML -> numFmts -> numFmt)
  240. {
  241. foreach ($this -> StylesXML -> numFmts -> numFmt as $Index => $NumFmt)
  242. {
  243. $this -> Formats[(int)$NumFmt -> attributes() -> numFmtId] = (string)$NumFmt -> attributes() -> formatCode;
  244. }
  245. }
  246. unset($this -> StylesXML);
  247. }
  248. $Zip -> close();
  249. // Setting base date
  250. if (!self::$BaseDate)
  251. {
  252. self::$BaseDate = new DateTime;
  253. self::$BaseDate -> setTimezone(new DateTimeZone('UTC'));
  254. self::$BaseDate -> setDate(1900, 1, 0);
  255. self::$BaseDate -> setTime(0, 0, 0);
  256. }
  257. // Decimal and thousand separators
  258. if (!self::$DecimalSeparator && !self::$ThousandSeparator && !self::$CurrencyCode)
  259. {
  260. $Locale = localeconv();
  261. self::$DecimalSeparator = $Locale['decimal_point'];
  262. self::$ThousandSeparator = $Locale['thousands_sep'];
  263. self::$CurrencyCode = $Locale['int_curr_symbol'];
  264. }
  265. if (function_exists('gmp_gcd'))
  266. {
  267. self::$RuntimeInfo['GMPSupported'] = true;
  268. }
  269. }
  270. /**
  271. * Destructor, destroys all that remains (closes and deletes temp files)
  272. */
  273. public function __destruct()
  274. {
  275. foreach ($this -> TempFiles as $TempFile)
  276. {
  277. @unlink($TempFile);
  278. }
  279. // Better safe than sorry - shouldn't try deleting '.' or '/', or '..'.
  280. if (strlen($this -> TempDir) > 2)
  281. {
  282. @rmdir($this -> TempDir.'xl'.DIRECTORY_SEPARATOR.'worksheets');
  283. @rmdir($this -> TempDir.'xl');
  284. @rmdir($this -> TempDir);
  285. }
  286. if ($this -> Worksheet && $this -> Worksheet instanceof XMLReader)
  287. {
  288. $this -> Worksheet -> close();
  289. unset($this -> Worksheet);
  290. }
  291. unset($this -> WorksheetPath);
  292. if ($this -> SharedStrings && $this -> SharedStrings instanceof XMLReader)
  293. {
  294. $this -> SharedStrings -> close();
  295. unset($this -> SharedStrings);
  296. }
  297. unset($this -> SharedStringsPath);
  298. if (isset($this -> StylesXML))
  299. {
  300. unset($this -> StylesXML);
  301. }
  302. if ($this -> WorkbookXML)
  303. {
  304. unset($this -> WorkbookXML);
  305. }
  306. }
  307. /**
  308. * Retrieves an array with information about sheets in the current file
  309. *
  310. * @return array List of sheets (key is sheet index, value is name)
  311. */
  312. public function Sheets()
  313. {
  314. if ($this -> Sheets === false)
  315. {
  316. $this -> Sheets = array();
  317. foreach ($this -> WorkbookXML -> sheets -> sheet as $Index => $Sheet)
  318. {
  319. $Attributes = $Sheet -> attributes('r', true);
  320. foreach ($Attributes as $Name => $Value)
  321. {
  322. if ($Name == 'id')
  323. {
  324. $SheetID = (int)str_replace('rId', '', (string)$Value);
  325. break;
  326. }
  327. }
  328. $this -> Sheets[$SheetID] = (string)$Sheet['name'];
  329. }
  330. ksort($this -> Sheets);
  331. }
  332. return array_values($this -> Sheets);
  333. }
  334. /**
  335. * Changes the current sheet in the file to another
  336. *
  337. * @param int Sheet index
  338. *
  339. * @return bool True if sheet was successfully changed, false otherwise.
  340. */
  341. public function ChangeSheet($Index)
  342. {
  343. $RealSheetIndex = false;
  344. $Sheets = $this -> Sheets();
  345. if (isset($Sheets[$Index]))
  346. {
  347. $SheetIndexes = array_keys($this -> Sheets);
  348. $RealSheetIndex = $SheetIndexes[$Index];
  349. }
  350. $TempWorksheetPath = $this -> TempDir.'xl/worksheets/sheet'.$RealSheetIndex.'.xml';
  351. if ($RealSheetIndex !== false && is_readable($TempWorksheetPath))
  352. {
  353. $this -> WorksheetPath = $TempWorksheetPath;
  354. $this -> rewind();
  355. return true;
  356. }
  357. return false;
  358. }
  359. /**
  360. * Creating shared string cache if the number of shared strings is acceptably low (or there is no limit on the amount
  361. */
  362. private function PrepareSharedStringCache()
  363. {
  364. while ($this -> SharedStrings -> read())
  365. {
  366. if ($this -> SharedStrings -> name == 'sst')
  367. {
  368. $this -> SharedStringCount = $this -> SharedStrings -> getAttribute('count');
  369. break;
  370. }
  371. }
  372. if (!$this -> SharedStringCount || (self::SHARED_STRING_CACHE_LIMIT < $this -> SharedStringCount && self::SHARED_STRING_CACHE_LIMIT !== null))
  373. {
  374. return false;
  375. }
  376. $CacheIndex = 0;
  377. $CacheValue = '';
  378. while ($this -> SharedStrings -> read())
  379. {
  380. switch ($this -> SharedStrings -> name)
  381. {
  382. case 'si':
  383. if ($this -> SharedStrings -> nodeType == XMLReader::END_ELEMENT)
  384. {
  385. $this -> SharedStringCache[$CacheIndex] = $CacheValue;
  386. $CacheIndex++;
  387. $CacheValue = '';
  388. }
  389. break;
  390. case 't':
  391. if ($this -> SharedStrings -> nodeType == XMLReader::END_ELEMENT)
  392. {
  393. continue;
  394. }
  395. $CacheValue .= $this -> SharedStrings -> readString();
  396. break;
  397. }
  398. }
  399. $this -> SharedStrings -> close();
  400. return true;
  401. }
  402. /**
  403. * Retrieves a shared string value by its index
  404. *
  405. * @param int Shared string index
  406. *
  407. * @return string Value
  408. */
  409. private function GetSharedString($Index)
  410. {
  411. if ((self::SHARED_STRING_CACHE_LIMIT === null || self::SHARED_STRING_CACHE_LIMIT > 0) && !empty($this -> SharedStringCache))
  412. {
  413. if (isset($this -> SharedStringCache[$Index]))
  414. {
  415. return $this -> SharedStringCache[$Index];
  416. }
  417. else
  418. {
  419. return '';
  420. }
  421. }
  422. // If the desired index is before the current, rewind the XML
  423. if ($this -> SharedStringIndex > $Index)
  424. {
  425. $this -> SSOpen = false;
  426. $this -> SharedStrings -> close();
  427. $this -> SharedStrings -> open($this -> SharedStringsPath);
  428. $this -> SharedStringIndex = 0;
  429. $this -> LastSharedStringValue = null;
  430. $this -> SSForwarded = false;
  431. }
  432. // Finding the unique string count (if not already read)
  433. if ($this -> SharedStringIndex == 0 && !$this -> SharedStringCount)
  434. {
  435. while ($this -> SharedStrings -> read())
  436. {
  437. if ($this -> SharedStrings -> name == 'sst')
  438. {
  439. $this -> SharedStringCount = $this -> SharedStrings -> getAttribute('uniqueCount');
  440. break;
  441. }
  442. }
  443. }
  444. // If index of the desired string is larger than possible, don't even bother.
  445. if ($this -> SharedStringCount && ($Index >= $this -> SharedStringCount))
  446. {
  447. return '';
  448. }
  449. // If an index with the same value as the last already fetched is requested
  450. // (any further traversing the tree would get us further away from the node)
  451. if (($Index == $this -> SharedStringIndex) && ($this -> LastSharedStringValue !== null))
  452. {
  453. return $this -> LastSharedStringValue;
  454. }
  455. // Find the correct <si> node with the desired index
  456. while ($this -> SharedStringIndex <= $Index)
  457. {
  458. // SSForwarded is set further to avoid double reading in case nodes are skipped.
  459. if ($this -> SSForwarded)
  460. {
  461. $this -> SSForwarded = false;
  462. }
  463. else
  464. {
  465. $ReadStatus = $this -> SharedStrings -> read();
  466. if (!$ReadStatus)
  467. {
  468. break;
  469. }
  470. }
  471. if ($this -> SharedStrings -> name == 'si')
  472. {
  473. if ($this -> SharedStrings -> nodeType == XMLReader::END_ELEMENT)
  474. {
  475. $this -> SSOpen = false;
  476. $this -> SharedStringIndex++;
  477. }
  478. else
  479. {
  480. $this -> SSOpen = true;
  481. if ($this -> SharedStringIndex < $Index)
  482. {
  483. $this -> SSOpen = false;
  484. $this -> SharedStrings -> next('si');
  485. $this -> SSForwarded = true;
  486. $this -> SharedStringIndex++;
  487. continue;
  488. }
  489. else
  490. {
  491. break;
  492. }
  493. }
  494. }
  495. }
  496. $Value = '';
  497. // Extract the value from the shared string
  498. if ($this -> SSOpen && ($this -> SharedStringIndex == $Index))
  499. {
  500. while ($this -> SharedStrings -> read())
  501. {
  502. switch ($this -> SharedStrings -> name)
  503. {
  504. case 't':
  505. if ($this -> SharedStrings -> nodeType == XMLReader::END_ELEMENT)
  506. {
  507. continue;
  508. }
  509. $Value .= $this -> SharedStrings -> readString();
  510. break;
  511. case 'si':
  512. if ($this -> SharedStrings -> nodeType == XMLReader::END_ELEMENT)
  513. {
  514. $this -> SSOpen = false;
  515. $this -> SSForwarded = true;
  516. break 2;
  517. }
  518. break;
  519. }
  520. }
  521. }
  522. if ($Value)
  523. {
  524. $this -> LastSharedStringValue = $Value;
  525. }
  526. return $Value;
  527. }
  528. /**
  529. * Formats the value according to the index
  530. *
  531. * @param string Cell value
  532. * @param int Format index
  533. *
  534. * @return string Formatted cell value
  535. */
  536. private function FormatValue($Value, $Index)
  537. {
  538. if (!is_numeric($Value))
  539. {
  540. return $Value;
  541. }
  542. if (isset($this -> Styles[$Index]) && ($this -> Styles[$Index] !== false))
  543. {
  544. $Index = $this -> Styles[$Index];
  545. }
  546. else
  547. {
  548. return $Value;
  549. }
  550. // A special case for the "General" format
  551. if ($Index == 0)
  552. {
  553. return $this -> GeneralFormat($Value);
  554. }
  555. $Format = array();
  556. if (isset($this -> ParsedFormatCache[$Index]))
  557. {
  558. $Format = $this -> ParsedFormatCache[$Index];
  559. }
  560. if (!$Format)
  561. {
  562. $Format = array(
  563. 'Code' => false,
  564. 'Type' => false,
  565. 'Scale' => 1,
  566. 'Thousands' => false,
  567. 'Currency' => false
  568. );
  569. if (isset(self::$BuiltinFormats[$Index]))
  570. {
  571. $Format['Code'] = self::$BuiltinFormats[$Index];
  572. }
  573. elseif (isset($this -> Formats[$Index]))
  574. {
  575. $Format['Code'] = $this -> Formats[$Index];
  576. }
  577. // Format code found, now parsing the format
  578. if ($Format['Code'])
  579. {
  580. $Sections = explode(';', $Format['Code']);
  581. $Format['Code'] = $Sections[0];
  582. switch (count($Sections))
  583. {
  584. case 2:
  585. if ($Value < 0)
  586. {
  587. $Format['Code'] = $Sections[1];
  588. }
  589. $Value = abs($Value);
  590. break;
  591. case 3:
  592. case 4:
  593. if ($Value < 0)
  594. {
  595. $Format['Code'] = $Sections[1];
  596. }
  597. elseif ($Value == 0)
  598. {
  599. $Format['Code'] = $Sections[2];
  600. }
  601. $Value = abs($Value);
  602. break;
  603. }
  604. }
  605. // Stripping colors
  606. $Format['Code'] = trim(preg_replace('/^\\[[a-zA-Z]+\\]/', '', $Format['Code']));
  607. // Percentages
  608. if (substr($Format['Code'], -1) == '%')
  609. {
  610. $Format['Type'] = 'Percentage';
  611. }
  612. elseif (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $Format['Code']))
  613. {
  614. $Format['Type'] = 'DateTime';
  615. $Format['Code'] = trim(preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $Format['Code']));
  616. $Format['Code'] = strtolower($Format['Code']);
  617. $Format['Code'] = strtr($Format['Code'], self::$DateReplacements['All']);
  618. if (strpos($Format['Code'], 'A') === false)
  619. {
  620. $Format['Code'] = strtr($Format['Code'], self::$DateReplacements['24H']);
  621. }
  622. else
  623. {
  624. $Format['Code'] = strtr($Format['Code'], self::$DateReplacements['12H']);
  625. }
  626. }
  627. elseif ($Format['Code'] == '[$EUR ]#,##0.00_-')
  628. {
  629. $Format['Type'] = 'Euro';
  630. }
  631. else
  632. {
  633. // Removing skipped characters
  634. $Format['Code'] = preg_replace('/_./', '', $Format['Code']);
  635. // Removing unnecessary escaping
  636. $Format['Code'] = preg_replace("/\\\\/", '', $Format['Code']);
  637. // Removing string quotes
  638. $Format['Code'] = str_replace(array('"', '*'), '', $Format['Code']);
  639. // Removing thousands separator
  640. if (strpos($Format['Code'], '0,0') !== false || strpos($Format['Code'], '#,#') !== false)
  641. {
  642. $Format['Thousands'] = true;
  643. }
  644. $Format['Code'] = str_replace(array('0,0', '#,#'), array('00', '##'), $Format['Code']);
  645. // Scaling (Commas indicate the power)
  646. $Scale = 1;
  647. $Matches = array();
  648. if (preg_match('/(0|#)(,+)/', $Format['Code'], $Matches))
  649. {
  650. $Scale = pow(1000, strlen($Matches[2]));
  651. // Removing the commas
  652. $Format['Code'] = preg_replace(array('/0,+/', '/#,+/'), array('0', '#'), $Format['Code']);
  653. }
  654. $Format['Scale'] = $Scale;
  655. if (preg_match('/#?.*\?\/\?/', $Format['Code']))
  656. {
  657. $Format['Type'] = 'Fraction';
  658. }
  659. else
  660. {
  661. $Format['Code'] = str_replace('#', '', $Format['Code']);
  662. $Matches = array();
  663. if (preg_match('/(0+)(\.?)(0*)/', preg_replace('/\[[^\]]+\]/', '', $Format['Code']), $Matches))
  664. {
  665. $Integer = $Matches[1];
  666. $DecimalPoint = $Matches[2];
  667. $Decimals = $Matches[3];
  668. $Format['MinWidth'] = strlen($Integer) + strlen($DecimalPoint) + strlen($Decimals);
  669. $Format['Decimals'] = $Decimals;
  670. $Format['Precision'] = strlen($Format['Decimals']);
  671. $Format['Pattern'] = '%0'.$Format['MinWidth'].'.'.$Format['Precision'].'f';
  672. }
  673. }
  674. $Matches = array();
  675. if (preg_match('/\[\$(.*)\]/u', $Format['Code'], $Matches))
  676. {
  677. $CurrFormat = $Matches[0];
  678. $CurrCode = $Matches[1];
  679. $CurrCode = explode('-', $CurrCode);
  680. if ($CurrCode)
  681. {
  682. $CurrCode = $CurrCode[0];
  683. }
  684. if (!$CurrCode)
  685. {
  686. $CurrCode = self::$CurrencyCode;
  687. }
  688. $Format['Currency'] = $CurrCode;
  689. }
  690. $Format['Code'] = trim($Format['Code']);
  691. }
  692. $this -> ParsedFormatCache[$Index] = $Format;
  693. }
  694. // Applying format to value
  695. if ($Format)
  696. {
  697. if ($Format['Code'] == '@')
  698. {
  699. return (string)$Value;
  700. }
  701. // Percentages
  702. elseif ($Format['Type'] == 'Percentage')
  703. {
  704. if ($Format['Code'] === '0%')
  705. {
  706. $Value = round(100 * $Value, 0).'%';
  707. }
  708. else
  709. {
  710. $Value = sprintf('%.2f%%', round(100 * $Value, 2));
  711. }
  712. }
  713. // Dates and times
  714. elseif ($Format['Type'] == 'DateTime')
  715. {
  716. $Days = (int)$Value;
  717. // Correcting for Feb 29, 1900
  718. if ($Days > 60)
  719. {
  720. $Days--;
  721. }
  722. // At this point time is a fraction of a day
  723. $Time = ($Value - (int)$Value);
  724. $Seconds = 0;
  725. if ($Time)
  726. {
  727. // Here time is converted to seconds
  728. // Some loss of precision will occur
  729. $Seconds = (int)($Time * 86400);
  730. }
  731. $Value = clone self::$BaseDate;
  732. $Value -> add(new DateInterval('P'.$Days.'D'.($Seconds ? 'T'.$Seconds.'S' : '')));
  733. if (!$this -> Options['ReturnDateTimeObjects'])
  734. {
  735. $Value = $Value -> format($Format['Code']);
  736. }
  737. else
  738. {
  739. // A DateTime object is returned
  740. }
  741. }
  742. elseif ($Format['Type'] == 'Euro')
  743. {
  744. $Value = 'EUR '.sprintf('%1.2f', $Value);
  745. }
  746. else
  747. {
  748. // Fractional numbers
  749. if ($Format['Type'] == 'Fraction' && ($Value != (int)$Value))
  750. {
  751. $Integer = floor(abs($Value));
  752. $Decimal = fmod(abs($Value), 1);
  753. // Removing the integer part and decimal point
  754. $Decimal *= pow(10, strlen($Decimal) - 2);
  755. $DecimalDivisor = pow(10, strlen($Decimal));
  756. if (self::$RuntimeInfo['GMPSupported'])
  757. {
  758. $GCD = gmp_strval(gmp_gcd($Decimal, $DecimalDivisor));
  759. }
  760. else
  761. {
  762. $GCD = self::GCD($Decimal, $DecimalDivisor);
  763. }
  764. $AdjDecimal = $DecimalPart/$GCD;
  765. $AdjDecimalDivisor = $DecimalDivisor/$GCD;
  766. if (
  767. strpos($Format['Code'], '0') !== false ||
  768. strpos($Format['Code'], '#') !== false ||
  769. substr($Format['Code'], 0, 3) == '? ?'
  770. )
  771. {
  772. // The integer part is shown separately apart from the fraction
  773. $Value = ($Value < 0 ? '-' : '').
  774. $Integer ? $Integer.' ' : ''.
  775. $AdjDecimal.'/'.
  776. $AdjDecimalDivisor;
  777. }
  778. else
  779. {
  780. // The fraction includes the integer part
  781. $AdjDecimal += $Integer * $AdjDecimalDivisor;
  782. $Value = ($Value < 0 ? '-' : '').
  783. $AdjDecimal.'/'.
  784. $AdjDecimalDivisor;
  785. }
  786. }
  787. else
  788. {
  789. // Scaling
  790. $Value = $Value / $Format['Scale'];
  791. if (!empty($Format['MinWidth']) && $Format['Decimals'])
  792. {
  793. if ($Format['Thousands'])
  794. {
  795. $Value = number_format($Value, $Format['Precision'],
  796. self::$DecimalSeparator, self::$ThousandSeparator);
  797. $Value = preg_replace('/(0+)(\.?)(0*)/', $Value, $Format['Code']);
  798. }
  799. else{
  800. if (preg_match('/[0#]E[+-]0/i', $Format['Code'])) {
  801. // Scientific format
  802. $Value = sprintf('%5.2E', $Value);
  803. }
  804. else {
  805. $Value = sprintf($Format['Pattern'], $Value);
  806. $Value = preg_replace('/(0+)(\.?)(0*)/', $Value, $Format['Code']);
  807. }
  808. }
  809. }
  810. }
  811. // Currency/Accounting
  812. if ($Format['Currency'])
  813. {
  814. $Value = preg_replace('', $Format['Currency'], $Value);
  815. }
  816. }
  817. }
  818. return $Value;
  819. }
  820. /**
  821. * Attempts to approximate Excel's "general" format.
  822. *
  823. * @param mixed Value
  824. *
  825. * @return mixed Result
  826. */
  827. public function GeneralFormat($Value)
  828. {
  829. // Numeric format
  830. if (is_numeric($Value))
  831. {
  832. $Value = (float)$Value;
  833. }
  834. return $Value;
  835. }
  836. // !Iterator interface methods
  837. /**
  838. * Rewind the Iterator to the first element.
  839. * Similar to the reset() function for arrays in PHP
  840. */
  841. public function rewind()
  842. {
  843. // Removed the check whether $this -> Index == 0 otherwise ChangeSheet doesn't work properly
  844. // If the worksheet was already iterated, XML file is reopened.
  845. // Otherwise it should be at the beginning anyway
  846. if ($this -> Worksheet instanceof XMLReader)
  847. {
  848. $this -> Worksheet -> close();
  849. }
  850. else
  851. {
  852. $this -> Worksheet = new XMLReader;
  853. }
  854. $this -> Worksheet -> open($this -> WorksheetPath);
  855. $this -> Valid = true;
  856. $this -> RowOpen = false;
  857. $this -> CurrentRow = false;
  858. $this -> Index = 0;
  859. }
  860. /**
  861. * Return the current element.
  862. * Similar to the current() function for arrays in PHP
  863. *
  864. * @return mixed current element from the collection
  865. */
  866. public function current()
  867. {
  868. if ($this -> Index == 0 && $this -> CurrentRow === false)
  869. {
  870. $this -> rewind();
  871. $this -> next();
  872. $this -> Index--;
  873. }
  874. return $this -> CurrentRow;
  875. }
  876. /**
  877. * Move forward to next element.
  878. * Similar to the next() function for arrays in PHP
  879. */
  880. public function next()
  881. {
  882. $this -> Index++;
  883. $this -> CurrentRow = array();
  884. if (!$this -> RowOpen)
  885. {
  886. while ($this -> Valid = $this -> Worksheet -> read())
  887. {
  888. if ($this -> Worksheet -> name == 'row')
  889. {
  890. // Getting the row spanning area (stored as e.g., 1:12)
  891. // so that the last cells will be present, even if empty
  892. $RowSpans = $this -> Worksheet -> getAttribute('spans');
  893. if ($RowSpans)
  894. {
  895. $RowSpans = explode(':', $RowSpans);
  896. $CurrentRowColumnCount = $RowSpans[1];
  897. }
  898. else
  899. {
  900. $CurrentRowColumnCount = 0;
  901. }
  902. if ($CurrentRowColumnCount > 0)
  903. {
  904. $this -> CurrentRow = array_fill(0, $CurrentRowColumnCount, '');
  905. }
  906. $this -> RowOpen = true;
  907. break;
  908. }
  909. }
  910. }
  911. // Reading the necessary row, if found
  912. if ($this -> RowOpen)
  913. {
  914. // These two are needed to control for empty cells
  915. $MaxIndex = 0;
  916. $CellCount = 0;
  917. $CellHasSharedString = false;
  918. while ($this -> Valid = $this -> Worksheet -> read())
  919. {
  920. switch ($this -> Worksheet -> name)
  921. {
  922. // End of row
  923. case 'row':
  924. if ($this -> Worksheet -> nodeType == XMLReader::END_ELEMENT)
  925. {
  926. $this -> RowOpen = false;
  927. break 2;
  928. }
  929. break;
  930. // Cell
  931. case 'c':
  932. // If it is a closing tag, skip it
  933. if ($this -> Worksheet -> nodeType == XMLReader::END_ELEMENT)
  934. {
  935. continue;
  936. }
  937. $StyleId = (int)$this -> Worksheet -> getAttribute('s');
  938. // Get the index of the cell
  939. $Index = $this -> Worksheet -> getAttribute('r');
  940. $Letter = preg_replace('{[^[:alpha:]]}S', '', $Index);
  941. $Index = self::IndexFromColumnLetter($Letter);
  942. // Determine cell type
  943. if ($this -> Worksheet -> getAttribute('t') == self::CELL_TYPE_SHARED_STR)
  944. {
  945. $CellHasSharedString = true;
  946. }
  947. else
  948. {
  949. $CellHasSharedString = false;
  950. }
  951. $this -> CurrentRow[$Index] = '';
  952. $CellCount++;
  953. if ($Index > $MaxIndex)
  954. {
  955. $MaxIndex = $Index;
  956. }
  957. break;
  958. // Cell value
  959. case 'v':
  960. case 'is':
  961. if ($this -> Worksheet -> nodeType == XMLReader::END_ELEMENT)
  962. {
  963. continue;
  964. }
  965. $Value = $this -> Worksheet -> readString();
  966. if ($CellHasSharedString)
  967. {
  968. $Value = $this -> GetSharedString($Value);
  969. }
  970. // Format value if necessary
  971. if ($Value !== '' && $StyleId && isset($this -> Styles[$StyleId]))
  972. {
  973. $Value = $this -> FormatValue($Value, $StyleId);
  974. }
  975. elseif ($Value)
  976. {
  977. $Value = $this -> GeneralFormat($Value);
  978. }
  979. $this -> CurrentRow[$Index] = $Value;
  980. break;
  981. }
  982. }
  983. // Adding empty cells, if necessary
  984. // Only empty cells inbetween and on the left side are added
  985. if ($MaxIndex + 1 > $CellCount)
  986. {
  987. $this -> CurrentRow = $this -> CurrentRow + array_fill(0, $MaxIndex + 1, '');
  988. ksort($this -> CurrentRow);
  989. }
  990. }
  991. return $this -> CurrentRow;
  992. }
  993. /**
  994. * Return the identifying key of the current element.
  995. * Similar to the key() function for arrays in PHP
  996. *
  997. * @return mixed either an integer or a string
  998. */
  999. public function key()
  1000. {
  1001. return $this -> Index;
  1002. }
  1003. /**
  1004. * Check if there is a current element after calls to rewind() or next().
  1005. * Used to check if we've iterated to the end of the collection
  1006. *
  1007. * @return boolean FALSE if there's nothing more to iterate over
  1008. */
  1009. public function valid()
  1010. {
  1011. return $this -> Valid;
  1012. }
  1013. // !Countable interface method
  1014. /**
  1015. * Ostensibly should return the count of the contained items but this just returns the number
  1016. * of rows read so far. It's not really correct but at least coherent.
  1017. */
  1018. public function count()
  1019. {
  1020. if(is_null($this->rowCount)){
  1021. $total = 0;
  1022. while($this -> Worksheet -> read()){
  1023. if ($this -> Worksheet -> name == 'row' && $this -> Worksheet -> nodeType != XMLReader::END_ELEMENT){
  1024. $total++;
  1025. }
  1026. }
  1027. $this->rowCount = $total;
  1028. }
  1029. return $this->rowCount;
  1030. }
  1031. /**
  1032. * Takes the column letter and converts it to a numerical index (0-based)
  1033. *
  1034. * @param string Letter(s) to convert
  1035. *
  1036. * @return mixed Numeric index (0-based) or boolean false if it cannot be calculated
  1037. */
  1038. public static function IndexFromColumnLetter($Letter)
  1039. {
  1040. $Powers = array();
  1041. $Letter = strtoupper($Letter);
  1042. $Result = 0;
  1043. for ($i = strlen($Letter) - 1, $j = 0; $i >= 0; $i--, $j++)
  1044. {
  1045. $Ord = ord($Letter[$i]) - 64;
  1046. if ($Ord > 26)
  1047. {
  1048. // Something is very, very wrong
  1049. return false;
  1050. }
  1051. $Result += $Ord * pow(26, $j);
  1052. }
  1053. return $Result - 1;
  1054. }
  1055. /**
  1056. * Helper function for greatest common divisor calculation in case GMP extension is not enabled
  1057. *
  1058. * @param int Number #1
  1059. * @param int Number #2
  1060. *
  1061. * @param int Greatest common divisor
  1062. */
  1063. public static function GCD($A, $B)
  1064. {
  1065. $A = abs($A);
  1066. $B = abs($B);
  1067. if ($A + $B == 0)
  1068. {
  1069. return 0;
  1070. }
  1071. else
  1072. {
  1073. $C = 1;
  1074. while ($A > 0)
  1075. {
  1076. $C = $A;
  1077. $A = $B % $A;
  1078. $B = $C;
  1079. }
  1080. return $C;
  1081. }
  1082. }
  1083. }