截流自动化的商城平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ReferenceHelper.php 49KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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 $pBefore Insert/Delete before this cell address (e.g. 'A1')
  214. * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
  215. * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
  216. */
  217. protected function adjustDataValidations(Worksheet $worksheet, $pBefore, $pNumCols, $pNumRows): void
  218. {
  219. $aDataValidationCollection = $worksheet->getDataValidationCollection();
  220. ($pNumCols > 0 || $pNumRows > 0) ?
  221. uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']);
  222. foreach ($aDataValidationCollection as $key => $value) {
  223. $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
  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. // 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
  650. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  651. $row = (int) trim($row, '$') + 10000000;
  652. $cellIndex = $row . $column;
  653. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  654. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i';
  655. ++$adjustCount;
  656. }
  657. }
  658. }
  659. }
  660. if ($adjustCount > 0) {
  661. if ($numberOfColumns > 0 || $numberOfRows > 0) {
  662. krsort($cellTokens);
  663. krsort($newCellTokens);
  664. } else {
  665. ksort($cellTokens);
  666. ksort($newCellTokens);
  667. } // Update cell references in the formula
  668. $formulaBlock = str_replace('\\', '', preg_replace($cellTokens, $newCellTokens, $formulaBlock));
  669. }
  670. }
  671. }
  672. unset($formulaBlock);
  673. // Then rebuild the formula string
  674. return implode('"', $formulaBlocks);
  675. }
  676. /**
  677. * Update all cell references within a formula, irrespective of worksheet.
  678. */
  679. public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
  680. {
  681. $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
  682. if ($numberOfColumns !== 0) {
  683. $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
  684. }
  685. if ($numberOfRows !== 0) {
  686. $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
  687. }
  688. return $formula;
  689. }
  690. private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
  691. {
  692. $splitCount = preg_match_all(
  693. '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
  694. $formula,
  695. $splitRanges,
  696. PREG_OFFSET_CAPTURE
  697. );
  698. $columnLengths = array_map('strlen', array_column($splitRanges[6], 0));
  699. $rowLengths = array_map('strlen', array_column($splitRanges[7], 0));
  700. $columnOffsets = array_column($splitRanges[6], 1);
  701. $rowOffsets = array_column($splitRanges[7], 1);
  702. $columns = $splitRanges[6];
  703. $rows = $splitRanges[7];
  704. while ($splitCount > 0) {
  705. --$splitCount;
  706. $columnLength = $columnLengths[$splitCount];
  707. $rowLength = $rowLengths[$splitCount];
  708. $columnOffset = $columnOffsets[$splitCount];
  709. $rowOffset = $rowOffsets[$splitCount];
  710. $column = $columns[$splitCount][0];
  711. $row = $rows[$splitCount][0];
  712. if (!empty($column) && $column[0] !== '$') {
  713. $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns);
  714. $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
  715. }
  716. if (!empty($row) && $row[0] !== '$') {
  717. $row += $numberOfRows;
  718. $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
  719. }
  720. }
  721. return $formula;
  722. }
  723. private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
  724. {
  725. $splitCount = preg_match_all(
  726. '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
  727. $formula,
  728. $splitRanges,
  729. PREG_OFFSET_CAPTURE
  730. );
  731. $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0));
  732. $fromColumnOffsets = array_column($splitRanges[1], 1);
  733. $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0));
  734. $toColumnOffsets = array_column($splitRanges[2], 1);
  735. $fromColumns = $splitRanges[1];
  736. $toColumns = $splitRanges[2];
  737. while ($splitCount > 0) {
  738. --$splitCount;
  739. $fromColumnLength = $fromColumnLengths[$splitCount];
  740. $toColumnLength = $toColumnLengths[$splitCount];
  741. $fromColumnOffset = $fromColumnOffsets[$splitCount];
  742. $toColumnOffset = $toColumnOffsets[$splitCount];
  743. $fromColumn = $fromColumns[$splitCount][0];
  744. $toColumn = $toColumns[$splitCount][0];
  745. if (!empty($fromColumn) && $fromColumn[0] !== '$') {
  746. $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
  747. $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
  748. }
  749. if (!empty($toColumn) && $toColumn[0] !== '$') {
  750. $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
  751. $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
  752. }
  753. }
  754. return $formula;
  755. }
  756. private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
  757. {
  758. $splitCount = preg_match_all(
  759. '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
  760. $formula,
  761. $splitRanges,
  762. PREG_OFFSET_CAPTURE
  763. );
  764. $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0));
  765. $fromRowOffsets = array_column($splitRanges[1], 1);
  766. $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0));
  767. $toRowOffsets = array_column($splitRanges[2], 1);
  768. $fromRows = $splitRanges[1];
  769. $toRows = $splitRanges[2];
  770. while ($splitCount > 0) {
  771. --$splitCount;
  772. $fromRowLength = $fromRowLengths[$splitCount];
  773. $toRowLength = $toRowLengths[$splitCount];
  774. $fromRowOffset = $fromRowOffsets[$splitCount];
  775. $toRowOffset = $toRowOffsets[$splitCount];
  776. $fromRow = $fromRows[$splitCount][0];
  777. $toRow = $toRows[$splitCount][0];
  778. if (!empty($fromRow) && $fromRow[0] !== '$') {
  779. $fromRow += $numberOfRows;
  780. $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
  781. }
  782. if (!empty($toRow) && $toRow[0] !== '$') {
  783. $toRow += $numberOfRows;
  784. $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
  785. }
  786. }
  787. return $formula;
  788. }
  789. /**
  790. * Update cell reference.
  791. *
  792. * @param string $cellReference Cell address or range of addresses
  793. * @param string $beforeCellAddress Insert before this one
  794. * @param int $numberOfColumns Number of columns to increment
  795. * @param int $numberOfRows Number of rows to increment
  796. *
  797. * @return string Updated cell range
  798. */
  799. public function updateCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  800. {
  801. // Is it in another worksheet? Will not have to update anything.
  802. if (strpos($cellReference, '!') !== false) {
  803. return $cellReference;
  804. // Is it a range or a single cell?
  805. } elseif (!Coordinate::coordinateIsRange($cellReference)) {
  806. // Single cell
  807. return $this->updateSingleCellReference($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  808. } elseif (Coordinate::coordinateIsRange($cellReference)) {
  809. // Range
  810. return $this->updateCellRange($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  811. }
  812. // Return original
  813. return $cellReference;
  814. }
  815. /**
  816. * Update named formulas (i.e. containing worksheet references / named ranges).
  817. *
  818. * @param Spreadsheet $spreadsheet Object to update
  819. * @param string $oldName Old name (name to replace)
  820. * @param string $newName New name
  821. */
  822. public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $newName = ''): void
  823. {
  824. if ($oldName == '') {
  825. return;
  826. }
  827. foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
  828. foreach ($sheet->getCoordinates(false) as $coordinate) {
  829. $cell = $sheet->getCell($coordinate);
  830. if (($cell !== null) && ($cell->getDataType() == DataType::TYPE_FORMULA)) {
  831. $formula = $cell->getValue();
  832. if (strpos($formula, $oldName) !== false) {
  833. $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
  834. $formula = str_replace($oldName . '!', $newName . '!', $formula);
  835. $cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
  836. }
  837. }
  838. }
  839. }
  840. }
  841. /**
  842. * Update cell range.
  843. *
  844. * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
  845. * @param string $beforeCellAddress Insert before this one
  846. * @param int $numberOfColumns Number of columns to increment
  847. * @param int $numberOfRows Number of rows to increment
  848. *
  849. * @return string Updated cell range
  850. */
  851. private function updateCellRange($cellRange = 'A1:A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  852. {
  853. if (!Coordinate::coordinateIsRange($cellRange)) {
  854. throw new Exception('Only cell ranges may be passed to this method.');
  855. }
  856. // Update range
  857. $range = Coordinate::splitRange($cellRange);
  858. $ic = count($range);
  859. for ($i = 0; $i < $ic; ++$i) {
  860. $jc = count($range[$i]);
  861. for ($j = 0; $j < $jc; ++$j) {
  862. if (ctype_alpha($range[$i][$j])) {
  863. $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows));
  864. $range[$i][$j] = $r[0];
  865. } elseif (ctype_digit($range[$i][$j])) {
  866. $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows));
  867. $range[$i][$j] = $r[1];
  868. } else {
  869. $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows);
  870. }
  871. }
  872. }
  873. // Recreate range string
  874. return Coordinate::buildRange($range);
  875. }
  876. /**
  877. * Update single cell reference.
  878. *
  879. * @param string $cellReference Single cell reference
  880. * @param string $beforeCellAddress Insert before this one
  881. * @param int $numberOfColumns Number of columns to increment
  882. * @param int $numberOfRows Number of rows to increment
  883. *
  884. * @return string Updated cell reference
  885. */
  886. private function updateSingleCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
  887. {
  888. if (Coordinate::coordinateIsRange($cellReference)) {
  889. throw new Exception('Only single cell references may be passed to this method.');
  890. }
  891. // Get coordinate of $beforeCellAddress
  892. [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress);
  893. // Get coordinate of $cellReference
  894. [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference);
  895. // Verify which parts should be updated
  896. $updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn)));
  897. $updateRow = (($newRow[0] != '$') && ($beforeRow[0] != '$') && $newRow >= $beforeRow);
  898. // Create new column reference
  899. if ($updateColumn) {
  900. $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $numberOfColumns);
  901. }
  902. // Create new row reference
  903. if ($updateRow) {
  904. $newRow = (int) $newRow + $numberOfRows;
  905. }
  906. // Return new reference
  907. return $newColumn . $newRow;
  908. }
  909. /**
  910. * __clone implementation. Cloning should not be allowed in a Singleton!
  911. */
  912. final public function __clone()
  913. {
  914. throw new Exception('Cloning a Singleton is not allowed!');
  915. }
  916. }