ReferenceHelper.php 50 KB

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