Cell.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Cell;
  3. use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
  4. use PhpOffice\PhpSpreadsheet\Collection\Cells;
  5. use PhpOffice\PhpSpreadsheet\Exception;
  6. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  7. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  8. use PhpOffice\PhpSpreadsheet\Style\Style;
  9. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  10. class Cell
  11. {
  12. /**
  13. * Value binder to use.
  14. *
  15. * @var IValueBinder
  16. */
  17. private static $valueBinder;
  18. /**
  19. * Value of the cell.
  20. *
  21. * @var mixed
  22. */
  23. private $value;
  24. /**
  25. * Calculated value of the cell (used for caching)
  26. * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
  27. * create the original spreadsheet file.
  28. * Note that this value is not guaranteed to reflect the actual calculated value because it is
  29. * possible that auto-calculation was disabled in the original spreadsheet, and underlying data
  30. * values used by the formula have changed since it was last calculated.
  31. *
  32. * @var mixed
  33. */
  34. private $calculatedValue;
  35. /**
  36. * Type of the cell data.
  37. *
  38. * @var string
  39. */
  40. private $dataType;
  41. /**
  42. * Collection of cells.
  43. *
  44. * @var Cells
  45. */
  46. private $parent;
  47. /**
  48. * Index to cellXf.
  49. *
  50. * @var int
  51. */
  52. private $xfIndex = 0;
  53. /**
  54. * Attributes of the formula.
  55. */
  56. private $formulaAttributes;
  57. /**
  58. * Update the cell into the cell collection.
  59. *
  60. * @return self
  61. */
  62. public function updateInCollection()
  63. {
  64. $this->parent->update($this);
  65. return $this;
  66. }
  67. public function detach()
  68. {
  69. $this->parent = null;
  70. }
  71. public function attach(Cells $parent)
  72. {
  73. $this->parent = $parent;
  74. }
  75. /**
  76. * Create a new Cell.
  77. *
  78. * @param mixed $pValue
  79. * @param string $pDataType
  80. * @param Worksheet $pSheet
  81. *
  82. * @throws Exception
  83. */
  84. public function __construct($pValue, $pDataType, Worksheet $pSheet)
  85. {
  86. // Initialise cell value
  87. $this->value = $pValue;
  88. // Set worksheet cache
  89. $this->parent = $pSheet->getCellCollection();
  90. // Set datatype?
  91. if ($pDataType !== null) {
  92. if ($pDataType == DataType::TYPE_STRING2) {
  93. $pDataType = DataType::TYPE_STRING;
  94. }
  95. $this->dataType = $pDataType;
  96. } elseif (!self::getValueBinder()->bindValue($this, $pValue)) {
  97. throw new Exception('Value could not be bound to cell.');
  98. }
  99. }
  100. /**
  101. * Get cell coordinate column.
  102. *
  103. * @return string
  104. */
  105. public function getColumn()
  106. {
  107. return $this->parent->getCurrentColumn();
  108. }
  109. /**
  110. * Get cell coordinate row.
  111. *
  112. * @return int
  113. */
  114. public function getRow()
  115. {
  116. return $this->parent->getCurrentRow();
  117. }
  118. /**
  119. * Get cell coordinate.
  120. *
  121. * @return string
  122. */
  123. public function getCoordinate()
  124. {
  125. return $this->parent->getCurrentCoordinate();
  126. }
  127. /**
  128. * Get cell value.
  129. *
  130. * @return mixed
  131. */
  132. public function getValue()
  133. {
  134. return $this->value;
  135. }
  136. /**
  137. * Get cell value with formatting.
  138. *
  139. * @return string
  140. */
  141. public function getFormattedValue()
  142. {
  143. return (string) NumberFormat::toFormattedString(
  144. $this->getCalculatedValue(),
  145. $this->getStyle()
  146. ->getNumberFormat()->getFormatCode()
  147. );
  148. }
  149. /**
  150. * Set cell value.
  151. *
  152. * Sets the value for a cell, automatically determining the datatype using the value binder
  153. *
  154. * @param mixed $pValue Value
  155. *
  156. * @throws Exception
  157. *
  158. * @return Cell
  159. */
  160. public function setValue($pValue)
  161. {
  162. if (!self::getValueBinder()->bindValue($this, $pValue)) {
  163. throw new Exception('Value could not be bound to cell.');
  164. }
  165. return $this;
  166. }
  167. /**
  168. * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder).
  169. *
  170. * @param mixed $pValue Value
  171. * @param string $pDataType Explicit data type, see DataType::TYPE_*
  172. *
  173. * @throws Exception
  174. *
  175. * @return Cell
  176. */
  177. public function setValueExplicit($pValue, $pDataType)
  178. {
  179. // set the value according to data type
  180. switch ($pDataType) {
  181. case DataType::TYPE_NULL:
  182. $this->value = $pValue;
  183. break;
  184. case DataType::TYPE_STRING2:
  185. $pDataType = DataType::TYPE_STRING;
  186. // no break
  187. case DataType::TYPE_STRING:
  188. // Synonym for string
  189. case DataType::TYPE_INLINE:
  190. // Rich text
  191. $this->value = DataType::checkString($pValue);
  192. break;
  193. case DataType::TYPE_NUMERIC:
  194. $this->value = (float) $pValue;
  195. break;
  196. case DataType::TYPE_FORMULA:
  197. $this->value = (string) $pValue;
  198. break;
  199. case DataType::TYPE_BOOL:
  200. $this->value = (bool) $pValue;
  201. break;
  202. case DataType::TYPE_ERROR:
  203. $this->value = DataType::checkErrorCode($pValue);
  204. break;
  205. default:
  206. throw new Exception('Invalid datatype: ' . $pDataType);
  207. break;
  208. }
  209. // set the datatype
  210. $this->dataType = $pDataType;
  211. return $this->updateInCollection();
  212. }
  213. /**
  214. * Get calculated cell value.
  215. *
  216. * @param bool $resetLog Whether the calculation engine logger should be reset or not
  217. *
  218. * @throws Exception
  219. *
  220. * @return mixed
  221. */
  222. public function getCalculatedValue($resetLog = true)
  223. {
  224. if ($this->dataType == DataType::TYPE_FORMULA) {
  225. try {
  226. $result = Calculation::getInstance(
  227. $this->getWorksheet()->getParent()
  228. )->calculateCellValue($this, $resetLog);
  229. // We don't yet handle array returns
  230. if (is_array($result)) {
  231. while (is_array($result)) {
  232. $result = array_pop($result);
  233. }
  234. }
  235. } catch (Exception $ex) {
  236. if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
  237. return $this->calculatedValue; // Fallback for calculations referencing external files.
  238. }
  239. throw new \PhpOffice\PhpSpreadsheet\Calculation\Exception(
  240. $this->getWorksheet()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage()
  241. );
  242. }
  243. if ($result === '#Not Yet Implemented') {
  244. return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
  245. }
  246. return $result;
  247. } elseif ($this->value instanceof RichText) {
  248. return $this->value->getPlainText();
  249. }
  250. return $this->value;
  251. }
  252. /**
  253. * Set old calculated value (cached).
  254. *
  255. * @param mixed $pValue Value
  256. *
  257. * @return Cell
  258. */
  259. public function setCalculatedValue($pValue)
  260. {
  261. if ($pValue !== null) {
  262. $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue;
  263. }
  264. return $this->updateInCollection();
  265. }
  266. /**
  267. * Get old calculated value (cached)
  268. * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
  269. * create the original spreadsheet file.
  270. * Note that this value is not guaranteed to reflect the actual calculated value because it is
  271. * possible that auto-calculation was disabled in the original spreadsheet, and underlying data
  272. * values used by the formula have changed since it was last calculated.
  273. *
  274. * @return mixed
  275. */
  276. public function getOldCalculatedValue()
  277. {
  278. return $this->calculatedValue;
  279. }
  280. /**
  281. * Get cell data type.
  282. *
  283. * @return string
  284. */
  285. public function getDataType()
  286. {
  287. return $this->dataType;
  288. }
  289. /**
  290. * Set cell data type.
  291. *
  292. * @param string $pDataType see DataType::TYPE_*
  293. *
  294. * @return Cell
  295. */
  296. public function setDataType($pDataType)
  297. {
  298. if ($pDataType == DataType::TYPE_STRING2) {
  299. $pDataType = DataType::TYPE_STRING;
  300. }
  301. $this->dataType = $pDataType;
  302. return $this->updateInCollection();
  303. }
  304. /**
  305. * Identify if the cell contains a formula.
  306. *
  307. * @return bool
  308. */
  309. public function isFormula()
  310. {
  311. return $this->dataType == DataType::TYPE_FORMULA;
  312. }
  313. /**
  314. * Does this cell contain Data validation rules?
  315. *
  316. * @throws Exception
  317. *
  318. * @return bool
  319. */
  320. public function hasDataValidation()
  321. {
  322. if (!isset($this->parent)) {
  323. throw new Exception('Cannot check for data validation when cell is not bound to a worksheet');
  324. }
  325. return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
  326. }
  327. /**
  328. * Get Data validation rules.
  329. *
  330. * @throws Exception
  331. *
  332. * @return DataValidation
  333. */
  334. public function getDataValidation()
  335. {
  336. if (!isset($this->parent)) {
  337. throw new Exception('Cannot get data validation for cell that is not bound to a worksheet');
  338. }
  339. return $this->getWorksheet()->getDataValidation($this->getCoordinate());
  340. }
  341. /**
  342. * Set Data validation rules.
  343. *
  344. * @param DataValidation $pDataValidation
  345. *
  346. * @throws Exception
  347. *
  348. * @return Cell
  349. */
  350. public function setDataValidation(DataValidation $pDataValidation = null)
  351. {
  352. if (!isset($this->parent)) {
  353. throw new Exception('Cannot set data validation for cell that is not bound to a worksheet');
  354. }
  355. $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation);
  356. return $this->updateInCollection();
  357. }
  358. /**
  359. * Does this cell contain valid value?
  360. *
  361. * @return bool
  362. */
  363. public function hasValidValue()
  364. {
  365. $validator = new DataValidator();
  366. return $validator->isValid($this);
  367. }
  368. /**
  369. * Does this cell contain a Hyperlink?
  370. *
  371. * @throws Exception
  372. *
  373. * @return bool
  374. */
  375. public function hasHyperlink()
  376. {
  377. if (!isset($this->parent)) {
  378. throw new Exception('Cannot check for hyperlink when cell is not bound to a worksheet');
  379. }
  380. return $this->getWorksheet()->hyperlinkExists($this->getCoordinate());
  381. }
  382. /**
  383. * Get Hyperlink.
  384. *
  385. * @throws Exception
  386. *
  387. * @return Hyperlink
  388. */
  389. public function getHyperlink()
  390. {
  391. if (!isset($this->parent)) {
  392. throw new Exception('Cannot get hyperlink for cell that is not bound to a worksheet');
  393. }
  394. return $this->getWorksheet()->getHyperlink($this->getCoordinate());
  395. }
  396. /**
  397. * Set Hyperlink.
  398. *
  399. * @param Hyperlink $pHyperlink
  400. *
  401. * @throws Exception
  402. *
  403. * @return Cell
  404. */
  405. public function setHyperlink(Hyperlink $pHyperlink = null)
  406. {
  407. if (!isset($this->parent)) {
  408. throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet');
  409. }
  410. $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink);
  411. return $this->updateInCollection();
  412. }
  413. /**
  414. * Get cell collection.
  415. *
  416. * @return Cells
  417. */
  418. public function getParent()
  419. {
  420. return $this->parent;
  421. }
  422. /**
  423. * Get parent worksheet.
  424. *
  425. * @return Worksheet
  426. */
  427. public function getWorksheet()
  428. {
  429. return $this->parent->getParent();
  430. }
  431. /**
  432. * Is this cell in a merge range.
  433. *
  434. * @return bool
  435. */
  436. public function isInMergeRange()
  437. {
  438. return (bool) $this->getMergeRange();
  439. }
  440. /**
  441. * Is this cell the master (top left cell) in a merge range (that holds the actual data value).
  442. *
  443. * @return bool
  444. */
  445. public function isMergeRangeValueCell()
  446. {
  447. if ($mergeRange = $this->getMergeRange()) {
  448. $mergeRange = Coordinate::splitRange($mergeRange);
  449. list($startCell) = $mergeRange[0];
  450. if ($this->getCoordinate() === $startCell) {
  451. return true;
  452. }
  453. }
  454. return false;
  455. }
  456. /**
  457. * If this cell is in a merge range, then return the range.
  458. *
  459. * @return string
  460. */
  461. public function getMergeRange()
  462. {
  463. foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) {
  464. if ($this->isInRange($mergeRange)) {
  465. return $mergeRange;
  466. }
  467. }
  468. return false;
  469. }
  470. /**
  471. * Get cell style.
  472. *
  473. * @return Style
  474. */
  475. public function getStyle()
  476. {
  477. return $this->getWorksheet()->getStyle($this->getCoordinate());
  478. }
  479. /**
  480. * Re-bind parent.
  481. *
  482. * @param Worksheet $parent
  483. *
  484. * @return Cell
  485. */
  486. public function rebindParent(Worksheet $parent)
  487. {
  488. $this->parent = $parent->getCellCollection();
  489. return $this->updateInCollection();
  490. }
  491. /**
  492. * Is cell in a specific range?
  493. *
  494. * @param string $pRange Cell range (e.g. A1:A1)
  495. *
  496. * @return bool
  497. */
  498. public function isInRange($pRange)
  499. {
  500. list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange);
  501. // Translate properties
  502. $myColumn = Coordinate::columnIndexFromString($this->getColumn());
  503. $myRow = $this->getRow();
  504. // Verify if cell is in range
  505. return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) &&
  506. ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow);
  507. }
  508. /**
  509. * Compare 2 cells.
  510. *
  511. * @param Cell $a Cell a
  512. * @param Cell $b Cell b
  513. *
  514. * @return int Result of comparison (always -1 or 1, never zero!)
  515. */
  516. public static function compareCells(self $a, self $b)
  517. {
  518. if ($a->getRow() < $b->getRow()) {
  519. return -1;
  520. } elseif ($a->getRow() > $b->getRow()) {
  521. return 1;
  522. } elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) {
  523. return -1;
  524. }
  525. return 1;
  526. }
  527. /**
  528. * Get value binder to use.
  529. *
  530. * @return IValueBinder
  531. */
  532. public static function getValueBinder()
  533. {
  534. if (self::$valueBinder === null) {
  535. self::$valueBinder = new DefaultValueBinder();
  536. }
  537. return self::$valueBinder;
  538. }
  539. /**
  540. * Set value binder to use.
  541. *
  542. * @param IValueBinder $binder
  543. */
  544. public static function setValueBinder(IValueBinder $binder)
  545. {
  546. self::$valueBinder = $binder;
  547. }
  548. /**
  549. * Implement PHP __clone to create a deep clone, not just a shallow copy.
  550. */
  551. public function __clone()
  552. {
  553. $vars = get_object_vars($this);
  554. foreach ($vars as $key => $value) {
  555. if ((is_object($value)) && ($key != 'parent')) {
  556. $this->$key = clone $value;
  557. } else {
  558. $this->$key = $value;
  559. }
  560. }
  561. }
  562. /**
  563. * Get index to cellXf.
  564. *
  565. * @return int
  566. */
  567. public function getXfIndex()
  568. {
  569. return $this->xfIndex;
  570. }
  571. /**
  572. * Set index to cellXf.
  573. *
  574. * @param int $pValue
  575. *
  576. * @return Cell
  577. */
  578. public function setXfIndex($pValue)
  579. {
  580. $this->xfIndex = $pValue;
  581. return $this->updateInCollection();
  582. }
  583. /**
  584. * Set the formula attributes.
  585. *
  586. * @param mixed $pAttributes
  587. *
  588. * @return Cell
  589. */
  590. public function setFormulaAttributes($pAttributes)
  591. {
  592. $this->formulaAttributes = $pAttributes;
  593. return $this;
  594. }
  595. /**
  596. * Get the formula attributes.
  597. */
  598. public function getFormulaAttributes()
  599. {
  600. return $this->formulaAttributes;
  601. }
  602. /**
  603. * Convert to string.
  604. *
  605. * @return string
  606. */
  607. public function __toString()
  608. {
  609. return (string) $this->getValue();
  610. }
  611. }