Cell.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. class PHPExcel_Cell
  8. {
  9. /**
  10. * Default range variable constant
  11. *
  12. * @var string
  13. */
  14. const DEFAULT_RANGE = 'A1:A1';
  15. /**
  16. * Value binder to use
  17. *
  18. * @var PHPExcel_Cell_IValueBinder
  19. */
  20. private static $valueBinder;
  21. /**
  22. * Value of the cell
  23. *
  24. * @var mixed
  25. */
  26. private $value;
  27. /**
  28. * Calculated value of the cell (used for caching)
  29. * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
  30. * create the original spreadsheet file.
  31. * Note that this value is not guaranteed to reflect the actual calculated value because it is
  32. * possible that auto-calculation was disabled in the original spreadsheet, and underlying data
  33. * values used by the formula have changed since it was last calculated.
  34. *
  35. * @var mixed
  36. */
  37. private $calculatedValue;
  38. /**
  39. * Type of the cell data
  40. *
  41. * @var string
  42. */
  43. private $dataType;
  44. /**
  45. * Parent worksheet
  46. *
  47. * @var PHPExcel_CachedObjectStorage_CacheBase
  48. */
  49. private $parent;
  50. /**
  51. * Index to cellXf
  52. *
  53. * @var int
  54. */
  55. private $xfIndex = 0;
  56. /**
  57. * Attributes of the formula
  58. *
  59. */
  60. private $formulaAttributes;
  61. /**
  62. * Send notification to the cache controller
  63. *
  64. * @return void
  65. **/
  66. public function notifyCacheController()
  67. {
  68. $this->parent->updateCacheData($this);
  69. return $this;
  70. }
  71. public function detach()
  72. {
  73. $this->parent = null;
  74. }
  75. public function attach(PHPExcel_CachedObjectStorage_CacheBase $parent)
  76. {
  77. $this->parent = $parent;
  78. }
  79. /**
  80. * Create a new Cell
  81. *
  82. * @param mixed $pValue
  83. * @param string $pDataType
  84. * @param PHPExcel_Worksheet $pSheet
  85. * @throws PHPExcel_Exception
  86. */
  87. public function __construct($pValue = null, $pDataType = null, PHPExcel_Worksheet $pSheet = null)
  88. {
  89. // Initialise cell value
  90. $this->value = $pValue;
  91. // Set worksheet cache
  92. $this->parent = $pSheet->getCellCacheController();
  93. // Set datatype?
  94. if ($pDataType !== null) {
  95. if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) {
  96. $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
  97. }
  98. $this->dataType = $pDataType;
  99. } elseif (!self::getValueBinder()->bindValue($this, $pValue)) {
  100. throw new PHPExcel_Exception("Value could not be bound to cell.");
  101. }
  102. }
  103. /**
  104. * Get cell coordinate column
  105. *
  106. * @return string
  107. */
  108. public function getColumn()
  109. {
  110. return $this->parent->getCurrentColumn();
  111. }
  112. /**
  113. * Get cell coordinate row
  114. *
  115. * @return int
  116. */
  117. public function getRow()
  118. {
  119. return $this->parent->getCurrentRow();
  120. }
  121. /**
  122. * Get cell coordinate
  123. *
  124. * @return string
  125. */
  126. public function getCoordinate()
  127. {
  128. return $this->parent->getCurrentAddress();
  129. }
  130. /**
  131. * Get cell value
  132. *
  133. * @return mixed
  134. */
  135. public function getValue()
  136. {
  137. return $this->value;
  138. }
  139. /**
  140. * Get cell value with formatting
  141. *
  142. * @return string
  143. */
  144. public function getFormattedValue()
  145. {
  146. return (string) PHPExcel_Style_NumberFormat::toFormattedString(
  147. $this->getCalculatedValue(),
  148. $this->getStyle()
  149. ->getNumberFormat()->getFormatCode()
  150. );
  151. }
  152. /**
  153. * Set cell value
  154. *
  155. * Sets the value for a cell, automatically determining the datatype using the value binder
  156. *
  157. * @param mixed $pValue Value
  158. * @return PHPExcel_Cell
  159. * @throws PHPExcel_Exception
  160. */
  161. public function setValue($pValue = null)
  162. {
  163. if (!self::getValueBinder()->bindValue($this, $pValue)) {
  164. throw new PHPExcel_Exception("Value could not be bound to cell.");
  165. }
  166. return $this;
  167. }
  168. /**
  169. * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder)
  170. *
  171. * @param mixed $pValue Value
  172. * @param string $pDataType Explicit data type
  173. * @return PHPExcel_Cell
  174. * @throws PHPExcel_Exception
  175. */
  176. public function setValueExplicit($pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
  177. {
  178. // set the value according to data type
  179. switch ($pDataType) {
  180. case PHPExcel_Cell_DataType::TYPE_NULL:
  181. $this->value = $pValue;
  182. break;
  183. case PHPExcel_Cell_DataType::TYPE_STRING2:
  184. $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
  185. // no break
  186. case PHPExcel_Cell_DataType::TYPE_STRING:
  187. // Synonym for string
  188. case PHPExcel_Cell_DataType::TYPE_INLINE:
  189. // Rich text
  190. $this->value = PHPExcel_Cell_DataType::checkString($pValue);
  191. break;
  192. case PHPExcel_Cell_DataType::TYPE_NUMERIC:
  193. $this->value = (float) $pValue;
  194. break;
  195. case PHPExcel_Cell_DataType::TYPE_FORMULA:
  196. $this->value = (string) $pValue;
  197. break;
  198. case PHPExcel_Cell_DataType::TYPE_BOOL:
  199. $this->value = (bool) $pValue;
  200. break;
  201. case PHPExcel_Cell_DataType::TYPE_ERROR:
  202. $this->value = PHPExcel_Cell_DataType::checkErrorCode($pValue);
  203. break;
  204. default:
  205. throw new PHPExcel_Exception('Invalid datatype: ' . $pDataType);
  206. break;
  207. }
  208. // set the datatype
  209. $this->dataType = $pDataType;
  210. return $this->notifyCacheController();
  211. }
  212. /**
  213. * Get calculated cell value
  214. *
  215. * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
  216. *
  217. * @param boolean $resetLog Whether the calculation engine logger should be reset or not
  218. * @return mixed
  219. * @throws PHPExcel_Exception
  220. */
  221. public function getCalculatedValue($resetLog = true)
  222. {
  223. //echo 'Cell '.$this->getCoordinate().' value is a '.$this->dataType.' with a value of '.$this->getValue().PHP_EOL;
  224. if ($this->dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) {
  225. try {
  226. //echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL;
  227. $result = PHPExcel_Calculation::getInstance(
  228. $this->getWorksheet()->getParent()
  229. )->calculateCellValue($this, $resetLog);
  230. //echo $this->getCoordinate().' calculation result is '.$result.PHP_EOL;
  231. // We don't yet handle array returns
  232. if (is_array($result)) {
  233. while (is_array($result)) {
  234. $result = array_pop($result);
  235. }
  236. }
  237. } catch (PHPExcel_Exception $ex) {
  238. if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
  239. //echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
  240. return $this->calculatedValue; // Fallback for calculations referencing external files.
  241. }
  242. //echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL;
  243. $result = '#N/A';
  244. throw new PHPExcel_Calculation_Exception(
  245. $this->getWorksheet()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage()
  246. );
  247. }
  248. if ($result === '#Not Yet Implemented') {
  249. //echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
  250. return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
  251. }
  252. //echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL;
  253. return $result;
  254. } elseif ($this->value instanceof PHPExcel_RichText) {
  255. // echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'<br />';
  256. return $this->value->getPlainText();
  257. }
  258. // echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->value.'<br />';
  259. return $this->value;
  260. }
  261. /**
  262. * Set old calculated value (cached)
  263. *
  264. * @param mixed $pValue Value
  265. * @return PHPExcel_Cell
  266. */
  267. public function setCalculatedValue($pValue = null)
  268. {
  269. if ($pValue !== null) {
  270. $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue;
  271. }
  272. return $this->notifyCacheController();
  273. }
  274. /**
  275. * Get old calculated value (cached)
  276. * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
  277. * create the original spreadsheet file.
  278. * Note that this value is not guaranteed to refelect the actual calculated value because it is
  279. * possible that auto-calculation was disabled in the original spreadsheet, and underlying data
  280. * values used by the formula have changed since it was last calculated.
  281. *
  282. * @return mixed
  283. */
  284. public function getOldCalculatedValue()
  285. {
  286. return $this->calculatedValue;
  287. }
  288. /**
  289. * Get cell data type
  290. *
  291. * @return string
  292. */
  293. public function getDataType()
  294. {
  295. return $this->dataType;
  296. }
  297. /**
  298. * Set cell data type
  299. *
  300. * @param string $pDataType
  301. * @return PHPExcel_Cell
  302. */
  303. public function setDataType($pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
  304. {
  305. if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) {
  306. $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
  307. }
  308. $this->dataType = $pDataType;
  309. return $this->notifyCacheController();
  310. }
  311. /**
  312. * Identify if the cell contains a formula
  313. *
  314. * @return boolean
  315. */
  316. public function isFormula()
  317. {
  318. return $this->dataType == PHPExcel_Cell_DataType::TYPE_FORMULA;
  319. }
  320. /**
  321. * Does this cell contain Data validation rules?
  322. *
  323. * @return boolean
  324. * @throws PHPExcel_Exception
  325. */
  326. public function hasDataValidation()
  327. {
  328. if (!isset($this->parent)) {
  329. throw new PHPExcel_Exception('Cannot check for data validation when cell is not bound to a worksheet');
  330. }
  331. return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
  332. }
  333. /**
  334. * Get Data validation rules
  335. *
  336. * @return PHPExcel_Cell_DataValidation
  337. * @throws PHPExcel_Exception
  338. */
  339. public function getDataValidation()
  340. {
  341. if (!isset($this->parent)) {
  342. throw new PHPExcel_Exception('Cannot get data validation for cell that is not bound to a worksheet');
  343. }
  344. return $this->getWorksheet()->getDataValidation($this->getCoordinate());
  345. }
  346. /**
  347. * Set Data validation rules
  348. *
  349. * @param PHPExcel_Cell_DataValidation $pDataValidation
  350. * @return PHPExcel_Cell
  351. * @throws PHPExcel_Exception
  352. */
  353. public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = null)
  354. {
  355. if (!isset($this->parent)) {
  356. throw new PHPExcel_Exception('Cannot set data validation for cell that is not bound to a worksheet');
  357. }
  358. $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation);
  359. return $this->notifyCacheController();
  360. }
  361. /**
  362. * Does this cell contain a Hyperlink?
  363. *
  364. * @return boolean
  365. * @throws PHPExcel_Exception
  366. */
  367. public function hasHyperlink()
  368. {
  369. if (!isset($this->parent)) {
  370. throw new PHPExcel_Exception('Cannot check for hyperlink when cell is not bound to a worksheet');
  371. }
  372. return $this->getWorksheet()->hyperlinkExists($this->getCoordinate());
  373. }
  374. /**
  375. * Get Hyperlink
  376. *
  377. * @return PHPExcel_Cell_Hyperlink
  378. * @throws PHPExcel_Exception
  379. */
  380. public function getHyperlink()
  381. {
  382. if (!isset($this->parent)) {
  383. throw new PHPExcel_Exception('Cannot get hyperlink for cell that is not bound to a worksheet');
  384. }
  385. return $this->getWorksheet()->getHyperlink($this->getCoordinate());
  386. }
  387. /**
  388. * Set Hyperlink
  389. *
  390. * @param PHPExcel_Cell_Hyperlink $pHyperlink
  391. * @return PHPExcel_Cell
  392. * @throws PHPExcel_Exception
  393. */
  394. public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = null)
  395. {
  396. if (!isset($this->parent)) {
  397. throw new PHPExcel_Exception('Cannot set hyperlink for cell that is not bound to a worksheet');
  398. }
  399. $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink);
  400. return $this->notifyCacheController();
  401. }
  402. /**
  403. * Get parent worksheet
  404. *
  405. * @return PHPExcel_CachedObjectStorage_CacheBase
  406. */
  407. public function getParent()
  408. {
  409. return $this->parent;
  410. }
  411. /**
  412. * Get parent worksheet
  413. *
  414. * @return PHPExcel_Worksheet
  415. */
  416. public function getWorksheet()
  417. {
  418. return $this->parent->getParent();
  419. }
  420. /**
  421. * Is this cell in a merge range
  422. *
  423. * @return boolean
  424. */
  425. public function isInMergeRange()
  426. {
  427. return (boolean) $this->getMergeRange();
  428. }
  429. /**
  430. * Is this cell the master (top left cell) in a merge range (that holds the actual data value)
  431. *
  432. * @return boolean
  433. */
  434. public function isMergeRangeValueCell()
  435. {
  436. if ($mergeRange = $this->getMergeRange()) {
  437. $mergeRange = PHPExcel_Cell::splitRange($mergeRange);
  438. list($startCell) = $mergeRange[0];
  439. if ($this->getCoordinate() === $startCell) {
  440. return true;
  441. }
  442. }
  443. return false;
  444. }
  445. /**
  446. * If this cell is in a merge range, then return the range
  447. *
  448. * @return string
  449. */
  450. public function getMergeRange()
  451. {
  452. foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) {
  453. if ($this->isInRange($mergeRange)) {
  454. return $mergeRange;
  455. }
  456. }
  457. return false;
  458. }
  459. /**
  460. * Get cell style
  461. *
  462. * @return PHPExcel_Style
  463. */
  464. public function getStyle()
  465. {
  466. return $this->getWorksheet()->getStyle($this->getCoordinate());
  467. }
  468. /**
  469. * Re-bind parent
  470. *
  471. * @param PHPExcel_Worksheet $parent
  472. * @return PHPExcel_Cell
  473. */
  474. public function rebindParent(PHPExcel_Worksheet $parent)
  475. {
  476. $this->parent = $parent->getCellCacheController();
  477. return $this->notifyCacheController();
  478. }
  479. /**
  480. * Is cell in a specific range?
  481. *
  482. * @param string $pRange Cell range (e.g. A1:A1)
  483. * @return boolean
  484. */
  485. public function isInRange($pRange = 'A1:A1')
  486. {
  487. list($rangeStart, $rangeEnd) = self::rangeBoundaries($pRange);
  488. // Translate properties
  489. $myColumn = self::columnIndexFromString($this->getColumn());
  490. $myRow = $this->getRow();
  491. // Verify if cell is in range
  492. return (($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) &&
  493. ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow)
  494. );
  495. }
  496. /**
  497. * Coordinate from string
  498. *
  499. * @param string $pCoordinateString
  500. * @return array Array containing column and row (indexes 0 and 1)
  501. * @throws PHPExcel_Exception
  502. */
  503. public static function coordinateFromString($pCoordinateString = 'A1')
  504. {
  505. if (preg_match("/^([$]?[A-Z]{1,3})([$]?\d{1,7})$/", $pCoordinateString, $matches)) {
  506. return array($matches[1],$matches[2]);
  507. } elseif ((strpos($pCoordinateString, ':') !== false) || (strpos($pCoordinateString, ',') !== false)) {
  508. throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
  509. } elseif ($pCoordinateString == '') {
  510. throw new PHPExcel_Exception('Cell coordinate can not be zero-length string');
  511. }
  512. throw new PHPExcel_Exception('Invalid cell coordinate '.$pCoordinateString);
  513. }
  514. /**
  515. * Make string row, column or cell coordinate absolute
  516. *
  517. * @param string $pCoordinateString e.g. 'A' or '1' or 'A1'
  518. * Note that this value can be a row or column reference as well as a cell reference
  519. * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
  520. * @throws PHPExcel_Exception
  521. */
  522. public static function absoluteReference($pCoordinateString = 'A1')
  523. {
  524. if (strpos($pCoordinateString, ':') === false && strpos($pCoordinateString, ',') === false) {
  525. // Split out any worksheet name from the reference
  526. $worksheet = '';
  527. $cellAddress = explode('!', $pCoordinateString);
  528. if (count($cellAddress) > 1) {
  529. list($worksheet, $pCoordinateString) = $cellAddress;
  530. }
  531. if ($worksheet > '') {
  532. $worksheet .= '!';
  533. }
  534. // Create absolute coordinate
  535. if (ctype_digit($pCoordinateString)) {
  536. return $worksheet . '$' . $pCoordinateString;
  537. } elseif (ctype_alpha($pCoordinateString)) {
  538. return $worksheet . '$' . strtoupper($pCoordinateString);
  539. }
  540. return $worksheet . self::absoluteCoordinate($pCoordinateString);
  541. }
  542. throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
  543. }
  544. /**
  545. * Make string coordinate absolute
  546. *
  547. * @param string $pCoordinateString e.g. 'A1'
  548. * @return string Absolute coordinate e.g. '$A$1'
  549. * @throws PHPExcel_Exception
  550. */
  551. public static function absoluteCoordinate($pCoordinateString = 'A1')
  552. {
  553. if (strpos($pCoordinateString, ':') === false && strpos($pCoordinateString, ',') === false) {
  554. // Split out any worksheet name from the coordinate
  555. $worksheet = '';
  556. $cellAddress = explode('!', $pCoordinateString);
  557. if (count($cellAddress) > 1) {
  558. list($worksheet, $pCoordinateString) = $cellAddress;
  559. }
  560. if ($worksheet > '') {
  561. $worksheet .= '!';
  562. }
  563. // Create absolute coordinate
  564. list($column, $row) = self::coordinateFromString($pCoordinateString);
  565. $column = ltrim($column, '$');
  566. $row = ltrim($row, '$');
  567. return $worksheet . '$' . $column . '$' . $row;
  568. }
  569. throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
  570. }
  571. /**
  572. * Split range into coordinate strings
  573. *
  574. * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
  575. * @return array Array containg one or more arrays containing one or two coordinate strings
  576. * e.g. array('B4','D9') or array(array('B4','D9'),array('H2','O11'))
  577. * or array('B4')
  578. */
  579. public static function splitRange($pRange = 'A1:A1')
  580. {
  581. // Ensure $pRange is a valid range
  582. if (empty($pRange)) {
  583. $pRange = self::DEFAULT_RANGE;
  584. }
  585. $exploded = explode(',', $pRange);
  586. $counter = count($exploded);
  587. for ($i = 0; $i < $counter; ++$i) {
  588. $exploded[$i] = explode(':', $exploded[$i]);
  589. }
  590. return $exploded;
  591. }
  592. /**
  593. * Build range from coordinate strings
  594. *
  595. * @param array $pRange Array containg one or more arrays containing one or two coordinate strings
  596. * @return string String representation of $pRange
  597. * @throws PHPExcel_Exception
  598. */
  599. public static function buildRange($pRange)
  600. {
  601. // Verify range
  602. if (!is_array($pRange) || empty($pRange) || !is_array($pRange[0])) {
  603. throw new PHPExcel_Exception('Range does not contain any information');
  604. }
  605. // Build range
  606. $imploded = array();
  607. $counter = count($pRange);
  608. for ($i = 0; $i < $counter; ++$i) {
  609. $pRange[$i] = implode(':', $pRange[$i]);
  610. }
  611. $imploded = implode(',', $pRange);
  612. return $imploded;
  613. }
  614. /**
  615. * Calculate range boundaries
  616. *
  617. * @param string $pRange Cell range (e.g. A1:A1)
  618. * @return array Range coordinates array(Start Cell, End Cell)
  619. * where Start Cell and End Cell are arrays (Column Number, Row Number)
  620. */
  621. public static function rangeBoundaries($pRange = 'A1:A1')
  622. {
  623. // Ensure $pRange is a valid range
  624. if (empty($pRange)) {
  625. $pRange = self::DEFAULT_RANGE;
  626. }
  627. // Uppercase coordinate
  628. $pRange = strtoupper($pRange);
  629. // Extract range
  630. if (strpos($pRange, ':') === false) {
  631. $rangeA = $rangeB = $pRange;
  632. } else {
  633. list($rangeA, $rangeB) = explode(':', $pRange);
  634. }
  635. // Calculate range outer borders
  636. $rangeStart = self::coordinateFromString($rangeA);
  637. $rangeEnd = self::coordinateFromString($rangeB);
  638. // Translate column into index
  639. $rangeStart[0] = self::columnIndexFromString($rangeStart[0]);
  640. $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]);
  641. return array($rangeStart, $rangeEnd);
  642. }
  643. /**
  644. * Calculate range dimension
  645. *
  646. * @param string $pRange Cell range (e.g. A1:A1)
  647. * @return array Range dimension (width, height)
  648. */
  649. public static function rangeDimension($pRange = 'A1:A1')
  650. {
  651. // Calculate range outer borders
  652. list($rangeStart, $rangeEnd) = self::rangeBoundaries($pRange);
  653. return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) );
  654. }
  655. /**
  656. * Calculate range boundaries
  657. *
  658. * @param string $pRange Cell range (e.g. A1:A1)
  659. * @return array Range coordinates array(Start Cell, End Cell)
  660. * where Start Cell and End Cell are arrays (Column ID, Row Number)
  661. */
  662. public static function getRangeBoundaries($pRange = 'A1:A1')
  663. {
  664. // Ensure $pRange is a valid range
  665. if (empty($pRange)) {
  666. $pRange = self::DEFAULT_RANGE;
  667. }
  668. // Uppercase coordinate
  669. $pRange = strtoupper($pRange);
  670. // Extract range
  671. if (strpos($pRange, ':') === false) {
  672. $rangeA = $rangeB = $pRange;
  673. } else {
  674. list($rangeA, $rangeB) = explode(':', $pRange);
  675. }
  676. return array( self::coordinateFromString($rangeA), self::coordinateFromString($rangeB));
  677. }
  678. /**
  679. * Column index from string
  680. *
  681. * @param string $pString
  682. * @return int Column index (base 1 !!!)
  683. */
  684. public static function columnIndexFromString($pString = 'A')
  685. {
  686. // Using a lookup cache adds a slight memory overhead, but boosts speed
  687. // caching using a static within the method is faster than a class static,
  688. // though it's additional memory overhead
  689. static $_indexCache = array();
  690. if (isset($_indexCache[$pString])) {
  691. return $_indexCache[$pString];
  692. }
  693. // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord()
  694. // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant
  695. // memory overhead either
  696. static $_columnLookup = array(
  697. 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13,
  698. 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26,
  699. 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13,
  700. 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26
  701. );
  702. // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString
  703. // for improved performance
  704. if (isset($pString{0})) {
  705. if (!isset($pString{1})) {
  706. $_indexCache[$pString] = $_columnLookup[$pString];
  707. return $_indexCache[$pString];
  708. } elseif (!isset($pString{2})) {
  709. $_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}];
  710. return $_indexCache[$pString];
  711. } elseif (!isset($pString{3})) {
  712. $_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}];
  713. return $_indexCache[$pString];
  714. }
  715. }
  716. throw new PHPExcel_Exception("Column string index can not be " . ((isset($pString{0})) ? "longer than 3 characters" : "empty"));
  717. }
  718. /**
  719. * String from columnindex
  720. *
  721. * @param int $pColumnIndex Column index (base 0 !!!)
  722. * @return string
  723. */
  724. public static function stringFromColumnIndex($pColumnIndex = 0)
  725. {
  726. // Using a lookup cache adds a slight memory overhead, but boosts speed
  727. // caching using a static within the method is faster than a class static,
  728. // though it's additional memory overhead
  729. static $_indexCache = array();
  730. if (!isset($_indexCache[$pColumnIndex])) {
  731. // Determine column string
  732. if ($pColumnIndex < 26) {
  733. $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex);
  734. } elseif ($pColumnIndex < 702) {
  735. $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) .
  736. chr(65 + $pColumnIndex % 26);
  737. } else {
  738. $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) .
  739. chr(65 + ((($pColumnIndex - 26) % 676) / 26)) .
  740. chr(65 + $pColumnIndex % 26);
  741. }
  742. }
  743. return $_indexCache[$pColumnIndex];
  744. }
  745. /**
  746. * Extract all cell references in range
  747. *
  748. * @param string $pRange Range (e.g. A1 or A1:C10 or A1:E10 A20:E25)
  749. * @return array Array containing single cell references
  750. */
  751. public static function extractAllCellReferencesInRange($pRange = 'A1')
  752. {
  753. // Returnvalue
  754. $returnValue = array();
  755. // Explode spaces
  756. $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange)));
  757. foreach ($cellBlocks as $cellBlock) {
  758. // Single cell?
  759. if (strpos($cellBlock, ':') === false && strpos($cellBlock, ',') === false) {
  760. $returnValue[] = $cellBlock;
  761. continue;
  762. }
  763. // Range...
  764. $ranges = self::splitRange($cellBlock);
  765. foreach ($ranges as $range) {
  766. // Single cell?
  767. if (!isset($range[1])) {
  768. $returnValue[] = $range[0];
  769. continue;
  770. }
  771. // Range...
  772. list($rangeStart, $rangeEnd) = $range;
  773. sscanf($rangeStart, '%[A-Z]%d', $startCol, $startRow);
  774. sscanf($rangeEnd, '%[A-Z]%d', $endCol, $endRow);
  775. ++$endCol;
  776. // Current data
  777. $currentCol = $startCol;
  778. $currentRow = $startRow;
  779. // Loop cells
  780. while ($currentCol != $endCol) {
  781. while ($currentRow <= $endRow) {
  782. $returnValue[] = $currentCol.$currentRow;
  783. ++$currentRow;
  784. }
  785. ++$currentCol;
  786. $currentRow = $startRow;
  787. }
  788. }
  789. }
  790. // Sort the result by column and row
  791. $sortKeys = array();
  792. foreach (array_unique($returnValue) as $coord) {
  793. sscanf($coord, '%[A-Z]%d', $column, $row);
  794. $sortKeys[sprintf('%3s%09d', $column, $row)] = $coord;
  795. }
  796. ksort($sortKeys);
  797. // Return value
  798. return array_values($sortKeys);
  799. }
  800. /**
  801. * Compare 2 cells
  802. *
  803. * @param PHPExcel_Cell $a Cell a
  804. * @param PHPExcel_Cell $b Cell b
  805. * @return int Result of comparison (always -1 or 1, never zero!)
  806. */
  807. public static function compareCells(PHPExcel_Cell $a, PHPExcel_Cell $b)
  808. {
  809. if ($a->getRow() < $b->getRow()) {
  810. return -1;
  811. } elseif ($a->getRow() > $b->getRow()) {
  812. return 1;
  813. } elseif (self::columnIndexFromString($a->getColumn()) < self::columnIndexFromString($b->getColumn())) {
  814. return -1;
  815. } else {
  816. return 1;
  817. }
  818. }
  819. /**
  820. * Get value binder to use
  821. *
  822. * @return PHPExcel_Cell_IValueBinder
  823. */
  824. public static function getValueBinder()
  825. {
  826. if (self::$valueBinder === null) {
  827. self::$valueBinder = new PHPExcel_Cell_DefaultValueBinder();
  828. }
  829. return self::$valueBinder;
  830. }
  831. /**
  832. * Set value binder to use
  833. *
  834. * @param PHPExcel_Cell_IValueBinder $binder
  835. * @throws PHPExcel_Exception
  836. */
  837. public static function setValueBinder(PHPExcel_Cell_IValueBinder $binder = null)
  838. {
  839. if ($binder === null) {
  840. throw new PHPExcel_Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly.");
  841. }
  842. self::$valueBinder = $binder;
  843. }
  844. /**
  845. * Implement PHP __clone to create a deep clone, not just a shallow copy.
  846. */
  847. public function __clone()
  848. {
  849. $vars = get_object_vars($this);
  850. foreach ($vars as $key => $value) {
  851. if ((is_object($value)) && ($key != 'parent')) {
  852. $this->$key = clone $value;
  853. } else {
  854. $this->$key = $value;
  855. }
  856. }
  857. }
  858. /**
  859. * Get index to cellXf
  860. *
  861. * @return int
  862. */
  863. public function getXfIndex()
  864. {
  865. return $this->xfIndex;
  866. }
  867. /**
  868. * Set index to cellXf
  869. *
  870. * @param int $pValue
  871. * @return PHPExcel_Cell
  872. */
  873. public function setXfIndex($pValue = 0)
  874. {
  875. $this->xfIndex = $pValue;
  876. return $this->notifyCacheController();
  877. }
  878. /**
  879. * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
  880. */
  881. public function setFormulaAttributes($pAttributes)
  882. {
  883. $this->formulaAttributes = $pAttributes;
  884. return $this;
  885. }
  886. /**
  887. * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
  888. */
  889. public function getFormulaAttributes()
  890. {
  891. return $this->formulaAttributes;
  892. }
  893. /**
  894. * Convert to string
  895. *
  896. * @return string
  897. */
  898. public function __toString()
  899. {
  900. return (string) $this->getValue();
  901. }
  902. }