ReferenceHelper.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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. // Find missing coordinates. This is important when inserting column before the last column
  366. $missingCoordinates = array_filter(
  367. array_map(function ($row) use ($highestColumn) {
  368. return $highestColumn . $row;
  369. }, range(1, $highestRow)),
  370. function ($coordinate) use ($allCoordinates) {
  371. return !in_array($coordinate, $allCoordinates);
  372. }
  373. );
  374. // Create missing cells with null values
  375. if (!empty($missingCoordinates)) {
  376. foreach ($missingCoordinates as $coordinate) {
  377. $worksheet->createNewCell($coordinate);
  378. }
  379. // Refresh all coordinates
  380. $allCoordinates = $worksheet->getCoordinates();
  381. }
  382. // Loop through cells, bottom-up, and change cell coordinate
  383. if ($remove) {
  384. // It's faster to reverse and pop than to use unshift, especially with large cell collections
  385. $allCoordinates = array_reverse($allCoordinates);
  386. }
  387. while ($coordinate = array_pop($allCoordinates)) {
  388. $cell = $worksheet->getCell($coordinate);
  389. $cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
  390. if ($cellIndex - 1 + $numberOfColumns < 0) {
  391. continue;
  392. }
  393. // New coordinate
  394. $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows);
  395. // Should the cell be updated? Move value and cellXf index from one cell to another.
  396. if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
  397. // Update cell styles
  398. $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
  399. // Insert this cell at its new location
  400. if ($cell->getDataType() == DataType::TYPE_FORMULA) {
  401. // Formula should be adjusted
  402. $worksheet->getCell($newCoordinate)
  403. ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
  404. } else {
  405. // Formula should not be adjusted
  406. $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType());
  407. }
  408. // Clear the original cell
  409. $worksheet->getCellCollection()->delete($coordinate);
  410. } else {
  411. /* We don't need to update styles for rows/columns before our insertion position,
  412. but we do still need to adjust any formulae in those cells */
  413. if ($cell->getDataType() == DataType::TYPE_FORMULA) {
  414. // Formula should be adjusted
  415. $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
  416. }
  417. }
  418. }
  419. // Duplicate styles for the newly inserted cells
  420. $highestColumn = $worksheet->getHighestColumn();
  421. $highestRow = $worksheet->getHighestRow();
  422. if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) {
  423. for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
  424. // Style
  425. $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i;
  426. if ($worksheet->cellExists($coordinate)) {
  427. $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
  428. $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
  429. $worksheet->getConditionalStyles($coordinate) : false;
  430. for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
  431. $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
  432. if ($conditionalStyles) {
  433. $cloned = [];
  434. foreach ($conditionalStyles as $conditionalStyle) {
  435. $cloned[] = clone $conditionalStyle;
  436. }
  437. $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned);
  438. }
  439. }
  440. }
  441. }
  442. }
  443. if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
  444. for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) {
  445. // Style
  446. $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
  447. if ($worksheet->cellExists($coordinate)) {
  448. $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
  449. $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
  450. $worksheet->getConditionalStyles($coordinate) : false;
  451. for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
  452. $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
  453. if ($conditionalStyles) {
  454. $cloned = [];
  455. foreach ($conditionalStyles as $conditionalStyle) {
  456. $cloned[] = clone $conditionalStyle;
  457. }
  458. $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned);
  459. }
  460. }
  461. }
  462. }
  463. }
  464. // Update worksheet: column dimensions
  465. $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  466. // Update worksheet: row dimensions
  467. $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows);
  468. // Update worksheet: page breaks
  469. $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
  470. // Update worksheet: comments
  471. $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
  472. // Update worksheet: hyperlinks
  473. $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  474. // Update worksheet: data validations
  475. $this->adjustDataValidations($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  476. // Update worksheet: merge cells
  477. $this->adjustMergeCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  478. // Update worksheet: protected cells
  479. $this->adjustProtectedCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  480. // Update worksheet: autofilter
  481. $autoFilter = $worksheet->getAutoFilter();
  482. $autoFilterRange = $autoFilter->getRange();
  483. if (!empty($autoFilterRange)) {
  484. if ($numberOfColumns != 0) {
  485. $autoFilterColumns = $autoFilter->getColumns();
  486. if (count($autoFilterColumns) > 0) {
  487. $column = '';
  488. $row = 0;
  489. sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
  490. $columnIndex = Coordinate::columnIndexFromString($column);
  491. [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
  492. if ($columnIndex <= $rangeEnd[0]) {
  493. if ($numberOfColumns < 0) {
  494. // If we're actually deleting any columns that fall within the autofilter range,
  495. // then we delete any rules for those columns
  496. $deleteColumn = $columnIndex + $numberOfColumns - 1;
  497. $deleteCount = abs($numberOfColumns);
  498. for ($i = 1; $i <= $deleteCount; ++$i) {
  499. if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) {
  500. $autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1));
  501. }
  502. ++$deleteColumn;
  503. }
  504. }
  505. $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
  506. // Shuffle columns in autofilter range
  507. if ($numberOfColumns > 0) {
  508. $startColRef = $startCol;
  509. $endColRef = $rangeEnd[0];
  510. $toColRef = $rangeEnd[0] + $numberOfColumns;
  511. do {
  512. $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
  513. --$endColRef;
  514. --$toColRef;
  515. } while ($startColRef <= $endColRef);
  516. } else {
  517. // For delete, we shuffle from beginning to end to avoid overwriting
  518. $startColID = Coordinate::stringFromColumnIndex($startCol);
  519. $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
  520. $endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1);
  521. do {
  522. $autoFilter->shiftColumn($startColID, $toColID);
  523. ++$startColID;
  524. ++$toColID;
  525. } while ($startColID != $endColID);
  526. }
  527. }
  528. }
  529. }
  530. $worksheet->setAutoFilter($this->updateCellReference($autoFilterRange, $beforeCellAddress, $numberOfColumns, $numberOfRows));
  531. }
  532. // Update worksheet: freeze pane
  533. if ($worksheet->getFreezePane()) {
  534. $splitCell = $worksheet->getFreezePane() ?? '';
  535. $topLeftCell = $worksheet->getTopLeftCell() ?? '';
  536. $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  537. $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  538. $worksheet->freezePane($splitCell, $topLeftCell);
  539. }
  540. // Page setup
  541. if ($worksheet->getPageSetup()->isPrintAreaSet()) {
  542. $worksheet->getPageSetup()->setPrintArea($this->updateCellReference($worksheet->getPageSetup()->getPrintArea(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
  543. }
  544. // Update worksheet: drawings
  545. $aDrawings = $worksheet->getDrawingCollection();
  546. foreach ($aDrawings as $objDrawing) {
  547. $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
  548. if ($objDrawing->getCoordinates() != $newReference) {
  549. $objDrawing->setCoordinates($newReference);
  550. }
  551. }
  552. // Update workbook: define names
  553. if (count($worksheet->getParent()->getDefinedNames()) > 0) {
  554. foreach ($worksheet->getParent()->getDefinedNames() as $definedName) {
  555. if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
  556. $definedName->setValue($this->updateCellReference($definedName->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
  557. }
  558. }
  559. }
  560. // Garbage collect
  561. $worksheet->garbageCollect();
  562. }
  563. /**
  564. * Update references within formulas.
  565. *
  566. * @param string $formula Formula to update
  567. * @param string $beforeCellAddress Insert before this one
  568. * @param int $numberOfColumns Number of columns to insert
  569. * @param int $numberOfRows Number of rows to insert
  570. * @param string $worksheetName Worksheet name/title
  571. *
  572. * @return string Updated formula
  573. */
  574. public function updateFormulaReferences($formula = '', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0, $worksheetName = '')
  575. {
  576. // Update cell references in the formula
  577. $formulaBlocks = explode('"', $formula);
  578. $i = false;
  579. foreach ($formulaBlocks as &$formulaBlock) {
  580. // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
  581. if ($i = !$i) {
  582. $adjustCount = 0;
  583. $newCellTokens = $cellTokens = [];
  584. // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
  585. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  586. if ($matchCount > 0) {
  587. foreach ($matches as $match) {
  588. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  589. $fromString .= $match[3] . ':' . $match[4];
  590. $modified3 = substr($this->updateCellReference('$A' . $match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
  591. $modified4 = substr($this->updateCellReference('$A' . $match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
  592. if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
  593. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  594. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  595. $toString .= $modified3 . ':' . $modified4;
  596. // 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
  597. $column = 100000;
  598. $row = 10000000 + (int) trim($match[3], '$');
  599. $cellIndex = $column . $row;
  600. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  601. $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
  602. ++$adjustCount;
  603. }
  604. }
  605. }
  606. }
  607. // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
  608. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  609. if ($matchCount > 0) {
  610. foreach ($matches as $match) {
  611. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  612. $fromString .= $match[3] . ':' . $match[4];
  613. $modified3 = substr($this->updateCellReference($match[3] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
  614. $modified4 = substr($this->updateCellReference($match[4] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
  615. if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
  616. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  617. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  618. $toString .= $modified3 . ':' . $modified4;
  619. // 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
  620. $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000;
  621. $row = 10000000;
  622. $cellIndex = $column . $row;
  623. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  624. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i';
  625. ++$adjustCount;
  626. }
  627. }
  628. }
  629. }
  630. // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
  631. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  632. if ($matchCount > 0) {
  633. foreach ($matches as $match) {
  634. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  635. $fromString .= $match[3] . ':' . $match[4];
  636. $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  637. $modified4 = $this->updateCellReference($match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  638. if ($match[3] . $match[4] !== $modified3 . $modified4) {
  639. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  640. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  641. $toString .= $modified3 . ':' . $modified4;
  642. [$column, $row] = Coordinate::coordinateFromString($match[3]);
  643. // 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
  644. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  645. $row = (int) trim($row, '$') + 10000000;
  646. $cellIndex = $column . $row;
  647. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  648. $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
  649. ++$adjustCount;
  650. }
  651. }
  652. }
  653. }
  654. // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
  655. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  656. if ($matchCount > 0) {
  657. foreach ($matches as $match) {
  658. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  659. $fromString .= $match[3];
  660. $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  661. if ($match[3] !== $modified3) {
  662. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  663. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  664. $toString .= $modified3;
  665. [$column, $row] = Coordinate::coordinateFromString($match[3]);
  666. $columnAdditionalIndex = $column[0] === '$' ? 1 : 0;
  667. $rowAdditionalIndex = $row[0] === '$' ? 1 : 0;
  668. // 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
  669. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  670. $row = (int) trim($row, '$') + 10000000;
  671. $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex;
  672. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  673. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i';
  674. ++$adjustCount;
  675. }
  676. }
  677. }
  678. }
  679. if ($adjustCount > 0) {
  680. if ($numberOfColumns > 0 || $numberOfRows > 0) {
  681. krsort($cellTokens);
  682. krsort($newCellTokens);
  683. } else {
  684. ksort($cellTokens);
  685. ksort($newCellTokens);
  686. } // Update cell references in the formula
  687. $formulaBlock = str_replace('\\', '', preg_replace($cellTokens, $newCellTokens, $formulaBlock));
  688. }
  689. }
  690. }
  691. unset($formulaBlock);
  692. // Then rebuild the formula string
  693. return implode('"', $formulaBlocks);
  694. }
  695. /**
  696. * Update all cell references within a formula, irrespective of worksheet.
  697. */
  698. public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
  699. {
  700. $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
  701. if ($numberOfColumns !== 0) {
  702. $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
  703. }
  704. if ($numberOfRows !== 0) {
  705. $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
  706. }
  707. return $formula;
  708. }
  709. private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
  710. {
  711. $splitCount = preg_match_all(
  712. '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
  713. $formula,
  714. $splitRanges,
  715. PREG_OFFSET_CAPTURE
  716. );
  717. $columnLengths = array_map('strlen', array_column($splitRanges[6], 0));
  718. $rowLengths = array_map('strlen', array_column($splitRanges[7], 0));
  719. $columnOffsets = array_column($splitRanges[6], 1);
  720. $rowOffsets = array_column($splitRanges[7], 1);
  721. $columns = $splitRanges[6];
  722. $rows = $splitRanges[7];
  723. while ($splitCount > 0) {
  724. --$splitCount;
  725. $columnLength = $columnLengths[$splitCount];
  726. $rowLength = $rowLengths[$splitCount];
  727. $columnOffset = $columnOffsets[$splitCount];
  728. $rowOffset = $rowOffsets[$splitCount];
  729. $column = $columns[$splitCount][0];
  730. $row = $rows[$splitCount][0];
  731. if (!empty($column) && $column[0] !== '$') {
  732. $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns);
  733. $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
  734. }
  735. if (!empty($row) && $row[0] !== '$') {
  736. $row += $numberOfRows;
  737. $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
  738. }
  739. }
  740. return $formula;
  741. }
  742. private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
  743. {
  744. $splitCount = preg_match_all(
  745. '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
  746. $formula,
  747. $splitRanges,
  748. PREG_OFFSET_CAPTURE
  749. );
  750. $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0));
  751. $fromColumnOffsets = array_column($splitRanges[1], 1);
  752. $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0));
  753. $toColumnOffsets = array_column($splitRanges[2], 1);
  754. $fromColumns = $splitRanges[1];
  755. $toColumns = $splitRanges[2];
  756. while ($splitCount > 0) {
  757. --$splitCount;
  758. $fromColumnLength = $fromColumnLengths[$splitCount];
  759. $toColumnLength = $toColumnLengths[$splitCount];
  760. $fromColumnOffset = $fromColumnOffsets[$splitCount];
  761. $toColumnOffset = $toColumnOffsets[$splitCount];
  762. $fromColumn = $fromColumns[$splitCount][0];
  763. $toColumn = $toColumns[$splitCount][0];
  764. if (!empty($fromColumn) && $fromColumn[0] !== '$') {
  765. $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
  766. $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
  767. }
  768. if (!empty($toColumn) && $toColumn[0] !== '$') {
  769. $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
  770. $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
  771. }
  772. }
  773. return $formula;
  774. }
  775. private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
  776. {
  777. $splitCount = preg_match_all(
  778. '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
  779. $formula,
  780. $splitRanges,
  781. PREG_OFFSET_CAPTURE
  782. );
  783. $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0));
  784. $fromRowOffsets = array_column($splitRanges[1], 1);
  785. $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0));
  786. $toRowOffsets = array_column($splitRanges[2], 1);
  787. $fromRows = $splitRanges[1];
  788. $toRows = $splitRanges[2];
  789. while ($splitCount > 0) {
  790. --$splitCount;
  791. $fromRowLength = $fromRowLengths[$splitCount];
  792. $toRowLength = $toRowLengths[$splitCount];
  793. $fromRowOffset = $fromRowOffsets[$splitCount];
  794. $toRowOffset = $toRowOffsets[$splitCount];
  795. $fromRow = $fromRows[$splitCount][0];
  796. $toRow = $toRows[$splitCount][0];
  797. if (!empty($fromRow) && $fromRow[0] !== '$') {
  798. $fromRow += $numberOfRows;
  799. $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
  800. }
  801. if (!empty($toRow) && $toRow[0] !== '$') {
  802. $toRow += $numberOfRows;
  803. $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
  804. }
  805. }
  806. return $formula;
  807. }
  808. /**
  809. * Update cell reference.
  810. *
  811. * @param string $cellReference Cell address or range of addresses
  812. * @param string $beforeCellAddress Insert before this one
  813. * @param int $numberOfColumns Number of columns to increment
  814. * @param int $numberOfRows Number of rows to increment
  815. *
  816. * @return string Updated cell range
  817. */
  818. public function updateCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  819. {
  820. // Is it in another worksheet? Will not have to update anything.
  821. if (strpos($cellReference, '!') !== false) {
  822. return $cellReference;
  823. // Is it a range or a single cell?
  824. } elseif (!Coordinate::coordinateIsRange($cellReference)) {
  825. // Single cell
  826. return $this->updateSingleCellReference($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  827. } elseif (Coordinate::coordinateIsRange($cellReference)) {
  828. // Range
  829. return $this->updateCellRange($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  830. }
  831. // Return original
  832. return $cellReference;
  833. }
  834. /**
  835. * Update named formulas (i.e. containing worksheet references / named ranges).
  836. *
  837. * @param Spreadsheet $spreadsheet Object to update
  838. * @param string $oldName Old name (name to replace)
  839. * @param string $newName New name
  840. */
  841. public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $newName = ''): void
  842. {
  843. if ($oldName == '') {
  844. return;
  845. }
  846. foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
  847. foreach ($sheet->getCoordinates(false) as $coordinate) {
  848. $cell = $sheet->getCell($coordinate);
  849. if (($cell !== null) && ($cell->getDataType() == DataType::TYPE_FORMULA)) {
  850. $formula = $cell->getValue();
  851. if (strpos($formula, $oldName) !== false) {
  852. $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
  853. $formula = str_replace($oldName . '!', $newName . '!', $formula);
  854. $cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
  855. }
  856. }
  857. }
  858. }
  859. }
  860. /**
  861. * Update cell range.
  862. *
  863. * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
  864. * @param string $beforeCellAddress Insert before this one
  865. * @param int $numberOfColumns Number of columns to increment
  866. * @param int $numberOfRows Number of rows to increment
  867. *
  868. * @return string Updated cell range
  869. */
  870. private function updateCellRange($cellRange = 'A1:A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  871. {
  872. if (!Coordinate::coordinateIsRange($cellRange)) {
  873. throw new Exception('Only cell ranges may be passed to this method.');
  874. }
  875. // Update range
  876. $range = Coordinate::splitRange($cellRange);
  877. $ic = count($range);
  878. for ($i = 0; $i < $ic; ++$i) {
  879. $jc = count($range[$i]);
  880. for ($j = 0; $j < $jc; ++$j) {
  881. if (ctype_alpha($range[$i][$j])) {
  882. $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows));
  883. $range[$i][$j] = $r[0];
  884. } elseif (ctype_digit($range[$i][$j])) {
  885. $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows));
  886. $range[$i][$j] = $r[1];
  887. } else {
  888. $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  889. }
  890. }
  891. }
  892. // Recreate range string
  893. return Coordinate::buildRange($range);
  894. }
  895. /**
  896. * Update single cell reference.
  897. *
  898. * @param string $cellReference Single cell reference
  899. * @param string $beforeCellAddress Insert before this one
  900. * @param int $numberOfColumns Number of columns to increment
  901. * @param int $numberOfRows Number of rows to increment
  902. *
  903. * @return string Updated cell reference
  904. */
  905. private function updateSingleCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  906. {
  907. if (Coordinate::coordinateIsRange($cellReference)) {
  908. throw new Exception('Only single cell references may be passed to this method.');
  909. }
  910. // Get coordinate of $beforeCellAddress
  911. [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress);
  912. // Get coordinate of $cellReference
  913. [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference);
  914. // Verify which parts should be updated
  915. $updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn)));
  916. $updateRow = (($newRow[0] != '$') && ($beforeRow[0] != '$') && $newRow >= $beforeRow);
  917. // Create new column reference
  918. if ($updateColumn) {
  919. $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $numberOfColumns);
  920. }
  921. // Create new row reference
  922. if ($updateRow) {
  923. $newRow = (int) $newRow + $numberOfRows;
  924. }
  925. // Return new reference
  926. return $newColumn . $newRow;
  927. }
  928. /**
  929. * __clone implementation. Cloning should not be allowed in a Singleton!
  930. */
  931. final public function __clone()
  932. {
  933. throw new Exception('Cloning a Singleton is not allowed!');
  934. }
  935. }