ReferenceHelper.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet;
  3. use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
  4. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  5. use PhpOffice\PhpSpreadsheet\Cell\DataType;
  6. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  7. class ReferenceHelper
  8. {
  9. /** Constants */
  10. /** Regular Expressions */
  11. const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])';
  12. const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)';
  13. const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)';
  14. const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
  15. /**
  16. * Instance of this class.
  17. *
  18. * @var ReferenceHelper
  19. */
  20. private static $instance;
  21. /**
  22. * Get an instance of this class.
  23. *
  24. * @return ReferenceHelper
  25. */
  26. public static function getInstance()
  27. {
  28. if (!isset(self::$instance) || (self::$instance === null)) {
  29. self::$instance = new self();
  30. }
  31. return self::$instance;
  32. }
  33. /**
  34. * Create a new ReferenceHelper.
  35. */
  36. protected function __construct()
  37. {
  38. }
  39. /**
  40. * Compare two column addresses
  41. * Intended for use as a Callback function for sorting column addresses by column.
  42. *
  43. * @param string $a First column to test (e.g. 'AA')
  44. * @param string $b Second column to test (e.g. 'Z')
  45. *
  46. * @return int
  47. */
  48. public static function columnSort($a, $b)
  49. {
  50. return strcasecmp(strlen($a) . $a, strlen($b) . $b);
  51. }
  52. /**
  53. * Compare two column addresses
  54. * Intended for use as a Callback function for reverse sorting column addresses by column.
  55. *
  56. * @param string $a First column to test (e.g. 'AA')
  57. * @param string $b Second column to test (e.g. 'Z')
  58. *
  59. * @return int
  60. */
  61. public static function columnReverseSort($a, $b)
  62. {
  63. return -strcasecmp(strlen($a) . $a, strlen($b) . $b);
  64. }
  65. /**
  66. * Compare two cell addresses
  67. * Intended for use as a Callback function for sorting cell addresses by column and row.
  68. *
  69. * @param string $a First cell to test (e.g. 'AA1')
  70. * @param string $b Second cell to test (e.g. 'Z1')
  71. *
  72. * @return int
  73. */
  74. public static function cellSort($a, $b)
  75. {
  76. [$ac, $ar] = sscanf($a, '%[A-Z]%d');
  77. [$bc, $br] = sscanf($b, '%[A-Z]%d');
  78. if ($ar === $br) {
  79. return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
  80. }
  81. return ($ar < $br) ? -1 : 1;
  82. }
  83. /**
  84. * Compare two cell addresses
  85. * Intended for use as a Callback function for sorting cell addresses by column and row.
  86. *
  87. * @param string $a First cell to test (e.g. 'AA1')
  88. * @param string $b Second cell to test (e.g. 'Z1')
  89. *
  90. * @return int
  91. */
  92. public static function cellReverseSort($a, $b)
  93. {
  94. [$ac, $ar] = sscanf($a, '%[A-Z]%d');
  95. [$bc, $br] = sscanf($b, '%[A-Z]%d');
  96. if ($ar === $br) {
  97. return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
  98. }
  99. return ($ar < $br) ? 1 : -1;
  100. }
  101. /**
  102. * Test whether a cell address falls within a defined range of cells.
  103. *
  104. * @param string $cellAddress Address of the cell we're testing
  105. * @param int $beforeRow Number of the row we're inserting/deleting before
  106. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  107. * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
  108. * @param int $numberOfCols Number of columns to insert/delete (negative values indicate deletion)
  109. *
  110. * @return bool
  111. */
  112. private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfCols)
  113. {
  114. [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress);
  115. $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn);
  116. // Is cell within the range of rows/columns if we're deleting
  117. if (
  118. $numberOfRows < 0 &&
  119. ($cellRow >= ($beforeRow + $numberOfRows)) &&
  120. ($cellRow < $beforeRow)
  121. ) {
  122. return true;
  123. } elseif (
  124. $numberOfCols < 0 &&
  125. ($cellColumnIndex >= ($beforeColumnIndex + $numberOfCols)) &&
  126. ($cellColumnIndex < $beforeColumnIndex)
  127. ) {
  128. return true;
  129. }
  130. return false;
  131. }
  132. /**
  133. * Update page breaks when inserting/deleting rows/columns.
  134. *
  135. * @param Worksheet $worksheet The worksheet that we're editing
  136. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  137. * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
  138. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  139. * @param int $beforeRow Number of the row we're inserting/deleting before
  140. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  141. */
  142. protected function adjustPageBreaks(Worksheet $worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void
  143. {
  144. $aBreaks = $worksheet->getBreaks();
  145. ($numberOfColumns > 0 || $numberOfRows > 0) ?
  146. uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']);
  147. foreach ($aBreaks as $key => $value) {
  148. if (self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) {
  149. // If we're deleting, then clear any defined breaks that are within the range
  150. // of rows/columns that we're deleting
  151. $worksheet->setBreak($key, Worksheet::BREAK_NONE);
  152. } else {
  153. // Otherwise update any affected breaks by inserting a new break at the appropriate point
  154. // and removing the old affected break
  155. $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  156. if ($key != $newReference) {
  157. $worksheet->setBreak($newReference, $value)
  158. ->setBreak($key, Worksheet::BREAK_NONE);
  159. }
  160. }
  161. }
  162. }
  163. /**
  164. * Update cell comments when inserting/deleting rows/columns.
  165. *
  166. * @param Worksheet $worksheet The worksheet that we're editing
  167. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  168. * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
  169. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  170. * @param int $beforeRow Number of the row we're inserting/deleting before
  171. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  172. */
  173. protected function adjustComments($worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void
  174. {
  175. $aComments = $worksheet->getComments();
  176. $aNewComments = []; // the new array of all comments
  177. foreach ($aComments as $key => &$value) {
  178. // Any comments inside a deleted range will be ignored
  179. if (!self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) {
  180. // Otherwise build a new array of comments indexed by the adjusted cell reference
  181. $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  182. $aNewComments[$newReference] = $value;
  183. }
  184. }
  185. // Replace the comments array with the new set of comments
  186. $worksheet->setComments($aNewComments);
  187. }
  188. /**
  189. * Update hyperlinks when inserting/deleting rows/columns.
  190. *
  191. * @param Worksheet $worksheet The worksheet that we're editing
  192. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  193. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  194. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  195. */
  196. protected function adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
  197. {
  198. $aHyperlinkCollection = $worksheet->getHyperlinkCollection();
  199. ($numberOfColumns > 0 || $numberOfRows > 0) ?
  200. uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']);
  201. foreach ($aHyperlinkCollection as $key => $value) {
  202. $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  203. if ($key != $newReference) {
  204. $worksheet->setHyperlink($newReference, $value);
  205. $worksheet->setHyperlink($key, null);
  206. }
  207. }
  208. }
  209. /**
  210. * Update data validations when inserting/deleting rows/columns.
  211. *
  212. * @param Worksheet $worksheet The worksheet that we're editing
  213. * @param string $before Insert/Delete before this cell address (e.g. 'A1')
  214. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  215. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  216. */
  217. protected function adjustDataValidations(Worksheet $worksheet, $before, $numberOfColumns, $numberOfRows): void
  218. {
  219. $aDataValidationCollection = $worksheet->getDataValidationCollection();
  220. ($numberOfColumns > 0 || $numberOfRows > 0) ?
  221. uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']);
  222. foreach ($aDataValidationCollection as $key => $value) {
  223. $newReference = $this->updateCellReference($key, $before, $numberOfColumns, $numberOfRows);
  224. if ($key != $newReference) {
  225. $worksheet->setDataValidation($newReference, $value);
  226. $worksheet->setDataValidation($key, null);
  227. }
  228. }
  229. }
  230. /**
  231. * Update merged cells when inserting/deleting rows/columns.
  232. *
  233. * @param Worksheet $worksheet The worksheet that we're editing
  234. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  235. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  236. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  237. */
  238. protected function adjustMergeCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
  239. {
  240. $aMergeCells = $worksheet->getMergeCells();
  241. $aNewMergeCells = []; // the new array of all merge cells
  242. foreach ($aMergeCells as $key => &$value) {
  243. $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  244. $aNewMergeCells[$newReference] = $newReference;
  245. }
  246. $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
  247. }
  248. /**
  249. * Update protected cells when inserting/deleting rows/columns.
  250. *
  251. * @param Worksheet $worksheet The worksheet that we're editing
  252. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  253. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  254. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  255. */
  256. protected function adjustProtectedCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
  257. {
  258. $aProtectedCells = $worksheet->getProtectedCells();
  259. ($numberOfColumns > 0 || $numberOfRows > 0) ?
  260. uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']);
  261. foreach ($aProtectedCells as $key => $value) {
  262. $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  263. if ($key != $newReference) {
  264. $worksheet->protectCells($newReference, $value, true);
  265. $worksheet->unprotectCells($key);
  266. }
  267. }
  268. }
  269. /**
  270. * Update column dimensions when inserting/deleting rows/columns.
  271. *
  272. * @param Worksheet $worksheet The worksheet that we're editing
  273. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  274. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  275. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  276. */
  277. protected function adjustColumnDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
  278. {
  279. $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
  280. if (!empty($aColumnDimensions)) {
  281. foreach ($aColumnDimensions as $objColumnDimension) {
  282. $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows);
  283. [$newReference] = Coordinate::coordinateFromString($newReference);
  284. if ($objColumnDimension->getColumnIndex() != $newReference) {
  285. $objColumnDimension->setColumnIndex($newReference);
  286. }
  287. }
  288. $worksheet->refreshColumnDimensions();
  289. }
  290. }
  291. /**
  292. * Update row dimensions when inserting/deleting rows/columns.
  293. *
  294. * @param Worksheet $worksheet The worksheet that we're editing
  295. * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
  296. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  297. * @param int $beforeRow Number of the row we're inserting/deleting before
  298. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  299. */
  300. protected function adjustRowDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows): void
  301. {
  302. $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true);
  303. if (!empty($aRowDimensions)) {
  304. foreach ($aRowDimensions as $objRowDimension) {
  305. $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
  306. [, $newReference] = Coordinate::coordinateFromString($newReference);
  307. if ($objRowDimension->getRowIndex() != $newReference) {
  308. $objRowDimension->setRowIndex($newReference);
  309. }
  310. }
  311. $worksheet->refreshRowDimensions();
  312. $copyDimension = $worksheet->getRowDimension($beforeRow - 1);
  313. for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) {
  314. $newDimension = $worksheet->getRowDimension($i);
  315. $newDimension->setRowHeight($copyDimension->getRowHeight());
  316. $newDimension->setVisible($copyDimension->getVisible());
  317. $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
  318. $newDimension->setCollapsed($copyDimension->getCollapsed());
  319. }
  320. }
  321. }
  322. /**
  323. * Insert a new column or row, updating all possible related data.
  324. *
  325. * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1')
  326. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  327. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  328. * @param Worksheet $worksheet The worksheet that we're editing
  329. */
  330. public function insertNewBefore($beforeCellAddress, $numberOfColumns, $numberOfRows, Worksheet $worksheet): void
  331. {
  332. $remove = ($numberOfColumns < 0 || $numberOfRows < 0);
  333. $allCoordinates = $worksheet->getCoordinates();
  334. // Get coordinate of $beforeCellAddress
  335. [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress);
  336. // Clear cells if we are removing columns or rows
  337. $highestColumn = $worksheet->getHighestColumn();
  338. $highestRow = $worksheet->getHighestRow();
  339. // 1. Clear column strips if we are removing columns
  340. if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) {
  341. for ($i = 1; $i <= $highestRow - 1; ++$i) {
  342. for ($j = $beforeColumn - 1 + $numberOfColumns; $j <= $beforeColumn - 2; ++$j) {
  343. $coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i;
  344. $worksheet->removeConditionalStyles($coordinate);
  345. if ($worksheet->cellExists($coordinate)) {
  346. $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
  347. $worksheet->getCell($coordinate)->setXfIndex(0);
  348. }
  349. }
  350. }
  351. }
  352. // 2. Clear row strips if we are removing rows
  353. if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) {
  354. for ($i = $beforeColumn - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) {
  355. for ($j = $beforeRow + $numberOfRows; $j <= $beforeRow - 1; ++$j) {
  356. $coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j;
  357. $worksheet->removeConditionalStyles($coordinate);
  358. if ($worksheet->cellExists($coordinate)) {
  359. $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
  360. $worksheet->getCell($coordinate)->setXfIndex(0);
  361. }
  362. }
  363. }
  364. }
  365. // Loop through cells, bottom-up, and change cell coordinate
  366. if ($remove) {
  367. // It's faster to reverse and pop than to use unshift, especially with large cell collections
  368. $allCoordinates = array_reverse($allCoordinates);
  369. }
  370. while ($coordinate = array_pop($allCoordinates)) {
  371. $cell = $worksheet->getCell($coordinate);
  372. $cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
  373. if ($cellIndex - 1 + $numberOfColumns < 0) {
  374. continue;
  375. }
  376. // New coordinate
  377. $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows);
  378. // Should the cell be updated? Move value and cellXf index from one cell to another.
  379. if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
  380. // Update cell styles
  381. $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
  382. // Insert this cell at its new location
  383. if ($cell->getDataType() == DataType::TYPE_FORMULA) {
  384. // Formula should be adjusted
  385. $worksheet->getCell($newCoordinate)
  386. ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
  387. } else {
  388. // Formula should not be adjusted
  389. $worksheet->getCell($newCoordinate)->setValue($cell->getValue());
  390. }
  391. // Clear the original cell
  392. $worksheet->getCellCollection()->delete($coordinate);
  393. } else {
  394. /* We don't need to update styles for rows/columns before our insertion position,
  395. but we do still need to adjust any formulae in those cells */
  396. if ($cell->getDataType() == DataType::TYPE_FORMULA) {
  397. // Formula should be adjusted
  398. $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
  399. }
  400. }
  401. }
  402. // Duplicate styles for the newly inserted cells
  403. $highestColumn = $worksheet->getHighestColumn();
  404. $highestRow = $worksheet->getHighestRow();
  405. if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) {
  406. for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
  407. // Style
  408. $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i;
  409. if ($worksheet->cellExists($coordinate)) {
  410. $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
  411. $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
  412. $worksheet->getConditionalStyles($coordinate) : false;
  413. for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
  414. $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
  415. if ($conditionalStyles) {
  416. $cloned = [];
  417. foreach ($conditionalStyles as $conditionalStyle) {
  418. $cloned[] = clone $conditionalStyle;
  419. }
  420. $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned);
  421. }
  422. }
  423. }
  424. }
  425. }
  426. if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
  427. for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) {
  428. // Style
  429. $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
  430. if ($worksheet->cellExists($coordinate)) {
  431. $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
  432. $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
  433. $worksheet->getConditionalStyles($coordinate) : false;
  434. for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
  435. $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
  436. if ($conditionalStyles) {
  437. $cloned = [];
  438. foreach ($conditionalStyles as $conditionalStyle) {
  439. $cloned[] = clone $conditionalStyle;
  440. }
  441. $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned);
  442. }
  443. }
  444. }
  445. }
  446. }
  447. // Update worksheet: column dimensions
  448. $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  449. // Update worksheet: row dimensions
  450. $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows);
  451. // Update worksheet: page breaks
  452. $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
  453. // Update worksheet: comments
  454. $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
  455. // Update worksheet: hyperlinks
  456. $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  457. // Update worksheet: data validations
  458. $this->adjustDataValidations($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  459. // Update worksheet: merge cells
  460. $this->adjustMergeCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  461. // Update worksheet: protected cells
  462. $this->adjustProtectedCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  463. // Update worksheet: autofilter
  464. $autoFilter = $worksheet->getAutoFilter();
  465. $autoFilterRange = $autoFilter->getRange();
  466. if (!empty($autoFilterRange)) {
  467. if ($numberOfColumns != 0) {
  468. $autoFilterColumns = $autoFilter->getColumns();
  469. if (count($autoFilterColumns) > 0) {
  470. $column = '';
  471. $row = 0;
  472. sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
  473. $columnIndex = Coordinate::columnIndexFromString($column);
  474. [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
  475. if ($columnIndex <= $rangeEnd[0]) {
  476. if ($numberOfColumns < 0) {
  477. // If we're actually deleting any columns that fall within the autofilter range,
  478. // then we delete any rules for those columns
  479. $deleteColumn = $columnIndex + $numberOfColumns - 1;
  480. $deleteCount = abs($numberOfColumns);
  481. for ($i = 1; $i <= $deleteCount; ++$i) {
  482. if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) {
  483. $autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1));
  484. }
  485. ++$deleteColumn;
  486. }
  487. }
  488. $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
  489. // Shuffle columns in autofilter range
  490. if ($numberOfColumns > 0) {
  491. $startColRef = $startCol;
  492. $endColRef = $rangeEnd[0];
  493. $toColRef = $rangeEnd[0] + $numberOfColumns;
  494. do {
  495. $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
  496. --$endColRef;
  497. --$toColRef;
  498. } while ($startColRef <= $endColRef);
  499. } else {
  500. // For delete, we shuffle from beginning to end to avoid overwriting
  501. $startColID = Coordinate::stringFromColumnIndex($startCol);
  502. $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
  503. $endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1);
  504. do {
  505. $autoFilter->shiftColumn($startColID, $toColID);
  506. ++$startColID;
  507. ++$toColID;
  508. } while ($startColID != $endColID);
  509. }
  510. }
  511. }
  512. }
  513. $worksheet->setAutoFilter($this->updateCellReference($autoFilterRange, $beforeCellAddress, $numberOfColumns, $numberOfRows));
  514. }
  515. // Update worksheet: freeze pane
  516. if ($worksheet->getFreezePane()) {
  517. $splitCell = $worksheet->getFreezePane() ?? '';
  518. $topLeftCell = $worksheet->getTopLeftCell() ?? '';
  519. $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  520. $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  521. $worksheet->freezePane($splitCell, $topLeftCell);
  522. }
  523. // Page setup
  524. if ($worksheet->getPageSetup()->isPrintAreaSet()) {
  525. $worksheet->getPageSetup()->setPrintArea($this->updateCellReference($worksheet->getPageSetup()->getPrintArea(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
  526. }
  527. // Update worksheet: drawings
  528. $aDrawings = $worksheet->getDrawingCollection();
  529. foreach ($aDrawings as $objDrawing) {
  530. $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
  531. if ($objDrawing->getCoordinates() != $newReference) {
  532. $objDrawing->setCoordinates($newReference);
  533. }
  534. }
  535. // Update workbook: define names
  536. if (count($worksheet->getParent()->getDefinedNames()) > 0) {
  537. foreach ($worksheet->getParent()->getDefinedNames() as $definedName) {
  538. if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
  539. $definedName->setValue($this->updateCellReference($definedName->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
  540. }
  541. }
  542. }
  543. // Garbage collect
  544. $worksheet->garbageCollect();
  545. }
  546. /**
  547. * Update references within formulas.
  548. *
  549. * @param string $formula Formula to update
  550. * @param string $beforeCellAddress Insert before this one
  551. * @param int $numberOfColumns Number of columns to insert
  552. * @param int $numberOfRows Number of rows to insert
  553. * @param string $worksheetName Worksheet name/title
  554. *
  555. * @return string Updated formula
  556. */
  557. public function updateFormulaReferences($formula = '', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0, $worksheetName = '')
  558. {
  559. // Update cell references in the formula
  560. $formulaBlocks = explode('"', $formula);
  561. $i = false;
  562. foreach ($formulaBlocks as &$formulaBlock) {
  563. // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
  564. if ($i = !$i) {
  565. $adjustCount = 0;
  566. $newCellTokens = $cellTokens = [];
  567. // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
  568. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  569. if ($matchCount > 0) {
  570. foreach ($matches as $match) {
  571. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  572. $fromString .= $match[3] . ':' . $match[4];
  573. $modified3 = substr($this->updateCellReference('$A' . $match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
  574. $modified4 = substr($this->updateCellReference('$A' . $match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
  575. if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
  576. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  577. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  578. $toString .= $modified3 . ':' . $modified4;
  579. // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
  580. $column = 100000;
  581. $row = 10000000 + (int) trim($match[3], '$');
  582. $cellIndex = $column . $row;
  583. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  584. $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
  585. ++$adjustCount;
  586. }
  587. }
  588. }
  589. }
  590. // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
  591. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  592. if ($matchCount > 0) {
  593. foreach ($matches as $match) {
  594. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  595. $fromString .= $match[3] . ':' . $match[4];
  596. $modified3 = substr($this->updateCellReference($match[3] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
  597. $modified4 = substr($this->updateCellReference($match[4] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
  598. if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
  599. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  600. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  601. $toString .= $modified3 . ':' . $modified4;
  602. // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
  603. $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000;
  604. $row = 10000000;
  605. $cellIndex = $column . $row;
  606. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  607. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i';
  608. ++$adjustCount;
  609. }
  610. }
  611. }
  612. }
  613. // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
  614. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  615. if ($matchCount > 0) {
  616. foreach ($matches as $match) {
  617. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  618. $fromString .= $match[3] . ':' . $match[4];
  619. $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  620. $modified4 = $this->updateCellReference($match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  621. if ($match[3] . $match[4] !== $modified3 . $modified4) {
  622. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  623. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  624. $toString .= $modified3 . ':' . $modified4;
  625. [$column, $row] = Coordinate::coordinateFromString($match[3]);
  626. // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
  627. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  628. $row = (int) trim($row, '$') + 10000000;
  629. $cellIndex = $column . $row;
  630. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  631. $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
  632. ++$adjustCount;
  633. }
  634. }
  635. }
  636. }
  637. // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
  638. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  639. if ($matchCount > 0) {
  640. foreach ($matches as $match) {
  641. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  642. $fromString .= $match[3];
  643. $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  644. if ($match[3] !== $modified3) {
  645. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  646. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  647. $toString .= $modified3;
  648. [$column, $row] = Coordinate::coordinateFromString($match[3]);
  649. $columnAdditionalIndex = $column[0] === '$' ? 1 : 0;
  650. $rowAdditionalIndex = $row[0] === '$' ? 1 : 0;
  651. // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
  652. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  653. $row = (int) trim($row, '$') + 10000000;
  654. $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex;
  655. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  656. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i';
  657. ++$adjustCount;
  658. }
  659. }
  660. }
  661. }
  662. if ($adjustCount > 0) {
  663. if ($numberOfColumns > 0 || $numberOfRows > 0) {
  664. krsort($cellTokens);
  665. krsort($newCellTokens);
  666. } else {
  667. ksort($cellTokens);
  668. ksort($newCellTokens);
  669. } // Update cell references in the formula
  670. $formulaBlock = str_replace('\\', '', preg_replace($cellTokens, $newCellTokens, $formulaBlock));
  671. }
  672. }
  673. }
  674. unset($formulaBlock);
  675. // Then rebuild the formula string
  676. return implode('"', $formulaBlocks);
  677. }
  678. /**
  679. * Update all cell references within a formula, irrespective of worksheet.
  680. */
  681. public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
  682. {
  683. $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
  684. if ($numberOfColumns !== 0) {
  685. $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
  686. }
  687. if ($numberOfRows !== 0) {
  688. $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
  689. }
  690. return $formula;
  691. }
  692. private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
  693. {
  694. $splitCount = preg_match_all(
  695. '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
  696. $formula,
  697. $splitRanges,
  698. PREG_OFFSET_CAPTURE
  699. );
  700. $columnLengths = array_map('strlen', array_column($splitRanges[6], 0));
  701. $rowLengths = array_map('strlen', array_column($splitRanges[7], 0));
  702. $columnOffsets = array_column($splitRanges[6], 1);
  703. $rowOffsets = array_column($splitRanges[7], 1);
  704. $columns = $splitRanges[6];
  705. $rows = $splitRanges[7];
  706. while ($splitCount > 0) {
  707. --$splitCount;
  708. $columnLength = $columnLengths[$splitCount];
  709. $rowLength = $rowLengths[$splitCount];
  710. $columnOffset = $columnOffsets[$splitCount];
  711. $rowOffset = $rowOffsets[$splitCount];
  712. $column = $columns[$splitCount][0];
  713. $row = $rows[$splitCount][0];
  714. if (!empty($column) && $column[0] !== '$') {
  715. $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns);
  716. $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
  717. }
  718. if (!empty($row) && $row[0] !== '$') {
  719. $row += $numberOfRows;
  720. $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
  721. }
  722. }
  723. return $formula;
  724. }
  725. private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
  726. {
  727. $splitCount = preg_match_all(
  728. '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
  729. $formula,
  730. $splitRanges,
  731. PREG_OFFSET_CAPTURE
  732. );
  733. $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0));
  734. $fromColumnOffsets = array_column($splitRanges[1], 1);
  735. $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0));
  736. $toColumnOffsets = array_column($splitRanges[2], 1);
  737. $fromColumns = $splitRanges[1];
  738. $toColumns = $splitRanges[2];
  739. while ($splitCount > 0) {
  740. --$splitCount;
  741. $fromColumnLength = $fromColumnLengths[$splitCount];
  742. $toColumnLength = $toColumnLengths[$splitCount];
  743. $fromColumnOffset = $fromColumnOffsets[$splitCount];
  744. $toColumnOffset = $toColumnOffsets[$splitCount];
  745. $fromColumn = $fromColumns[$splitCount][0];
  746. $toColumn = $toColumns[$splitCount][0];
  747. if (!empty($fromColumn) && $fromColumn[0] !== '$') {
  748. $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
  749. $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
  750. }
  751. if (!empty($toColumn) && $toColumn[0] !== '$') {
  752. $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
  753. $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
  754. }
  755. }
  756. return $formula;
  757. }
  758. private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
  759. {
  760. $splitCount = preg_match_all(
  761. '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
  762. $formula,
  763. $splitRanges,
  764. PREG_OFFSET_CAPTURE
  765. );
  766. $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0));
  767. $fromRowOffsets = array_column($splitRanges[1], 1);
  768. $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0));
  769. $toRowOffsets = array_column($splitRanges[2], 1);
  770. $fromRows = $splitRanges[1];
  771. $toRows = $splitRanges[2];
  772. while ($splitCount > 0) {
  773. --$splitCount;
  774. $fromRowLength = $fromRowLengths[$splitCount];
  775. $toRowLength = $toRowLengths[$splitCount];
  776. $fromRowOffset = $fromRowOffsets[$splitCount];
  777. $toRowOffset = $toRowOffsets[$splitCount];
  778. $fromRow = $fromRows[$splitCount][0];
  779. $toRow = $toRows[$splitCount][0];
  780. if (!empty($fromRow) && $fromRow[0] !== '$') {
  781. $fromRow += $numberOfRows;
  782. $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
  783. }
  784. if (!empty($toRow) && $toRow[0] !== '$') {
  785. $toRow += $numberOfRows;
  786. $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
  787. }
  788. }
  789. return $formula;
  790. }
  791. /**
  792. * Update cell reference.
  793. *
  794. * @param string $cellReference Cell address or range of addresses
  795. * @param string $beforeCellAddress Insert before this one
  796. * @param int $numberOfColumns Number of columns to increment
  797. * @param int $numberOfRows Number of rows to increment
  798. *
  799. * @return string Updated cell range
  800. */
  801. public function updateCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  802. {
  803. // Is it in another worksheet? Will not have to update anything.
  804. if (strpos($cellReference, '!') !== false) {
  805. return $cellReference;
  806. // Is it a range or a single cell?
  807. } elseif (!Coordinate::coordinateIsRange($cellReference)) {
  808. // Single cell
  809. return $this->updateSingleCellReference($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  810. } elseif (Coordinate::coordinateIsRange($cellReference)) {
  811. // Range
  812. return $this->updateCellRange($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  813. }
  814. // Return original
  815. return $cellReference;
  816. }
  817. /**
  818. * Update named formulas (i.e. containing worksheet references / named ranges).
  819. *
  820. * @param Spreadsheet $spreadsheet Object to update
  821. * @param string $oldName Old name (name to replace)
  822. * @param string $newName New name
  823. */
  824. public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $newName = ''): void
  825. {
  826. if ($oldName == '') {
  827. return;
  828. }
  829. foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
  830. foreach ($sheet->getCoordinates(false) as $coordinate) {
  831. $cell = $sheet->getCell($coordinate);
  832. if (($cell !== null) && ($cell->getDataType() == DataType::TYPE_FORMULA)) {
  833. $formula = $cell->getValue();
  834. if (strpos($formula, $oldName) !== false) {
  835. $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
  836. $formula = str_replace($oldName . '!', $newName . '!', $formula);
  837. $cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
  838. }
  839. }
  840. }
  841. }
  842. }
  843. /**
  844. * Update cell range.
  845. *
  846. * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
  847. * @param string $beforeCellAddress Insert before this one
  848. * @param int $numberOfColumns Number of columns to increment
  849. * @param int $numberOfRows Number of rows to increment
  850. *
  851. * @return string Updated cell range
  852. */
  853. private function updateCellRange($cellRange = 'A1:A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  854. {
  855. if (!Coordinate::coordinateIsRange($cellRange)) {
  856. throw new Exception('Only cell ranges may be passed to this method.');
  857. }
  858. // Update range
  859. $range = Coordinate::splitRange($cellRange);
  860. $ic = count($range);
  861. for ($i = 0; $i < $ic; ++$i) {
  862. $jc = count($range[$i]);
  863. for ($j = 0; $j < $jc; ++$j) {
  864. if (ctype_alpha($range[$i][$j])) {
  865. $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows));
  866. $range[$i][$j] = $r[0];
  867. } elseif (ctype_digit($range[$i][$j])) {
  868. $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows));
  869. $range[$i][$j] = $r[1];
  870. } else {
  871. $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  872. }
  873. }
  874. }
  875. // Recreate range string
  876. return Coordinate::buildRange($range);
  877. }
  878. /**
  879. * Update single cell reference.
  880. *
  881. * @param string $cellReference Single cell reference
  882. * @param string $beforeCellAddress Insert before this one
  883. * @param int $numberOfColumns Number of columns to increment
  884. * @param int $numberOfRows Number of rows to increment
  885. *
  886. * @return string Updated cell reference
  887. */
  888. private function updateSingleCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  889. {
  890. if (Coordinate::coordinateIsRange($cellReference)) {
  891. throw new Exception('Only single cell references may be passed to this method.');
  892. }
  893. // Get coordinate of $beforeCellAddress
  894. [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress);
  895. // Get coordinate of $cellReference
  896. [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference);
  897. // Verify which parts should be updated
  898. $updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn)));
  899. $updateRow = (($newRow[0] != '$') && ($beforeRow[0] != '$') && $newRow >= $beforeRow);
  900. // Create new column reference
  901. if ($updateColumn) {
  902. $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $numberOfColumns);
  903. }
  904. // Create new row reference
  905. if ($updateRow) {
  906. $newRow = (int) $newRow + $numberOfRows;
  907. }
  908. // Return new reference
  909. return $newColumn . $newRow;
  910. }
  911. /**
  912. * __clone implementation. Cloning should not be allowed in a Singleton!
  913. */
  914. final public function __clone()
  915. {
  916. throw new Exception('Cloning a Singleton is not allowed!');
  917. }
  918. }