ReferenceHelper.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 => $dataValidation) {
  230. $newReference = $this->updateCellReference($cellAddress);
  231. if ($cellAddress !== $newReference) {
  232. $dataValidation->setSqref($newReference);
  233. $worksheet->setDataValidation($newReference, $dataValidation);
  234. $worksheet->setDataValidation($cellAddress, null);
  235. }
  236. }
  237. }
  238. /**
  239. * Update merged cells when inserting/deleting rows/columns.
  240. *
  241. * @param Worksheet $worksheet The worksheet that we're editing
  242. */
  243. protected function adjustMergeCells(Worksheet $worksheet): void
  244. {
  245. $aMergeCells = $worksheet->getMergeCells();
  246. $aNewMergeCells = []; // the new array of all merge cells
  247. foreach ($aMergeCells as $cellAddress => &$value) {
  248. $newReference = $this->updateCellReference($cellAddress);
  249. $aNewMergeCells[$newReference] = $newReference;
  250. }
  251. $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
  252. }
  253. /**
  254. * Update protected cells when inserting/deleting rows/columns.
  255. *
  256. * @param Worksheet $worksheet The worksheet that we're editing
  257. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  258. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  259. */
  260. protected function adjustProtectedCells(Worksheet $worksheet, $numberOfColumns, $numberOfRows): void
  261. {
  262. $aProtectedCells = $worksheet->getProtectedCells();
  263. ($numberOfColumns > 0 || $numberOfRows > 0)
  264. ? uksort($aProtectedCells, [self::class, 'cellReverseSort'])
  265. : uksort($aProtectedCells, [self::class, 'cellSort']);
  266. foreach ($aProtectedCells as $cellAddress => $value) {
  267. $newReference = $this->updateCellReference($cellAddress);
  268. if ($cellAddress !== $newReference) {
  269. $worksheet->protectCells($newReference, $value, true);
  270. $worksheet->unprotectCells($cellAddress);
  271. }
  272. }
  273. }
  274. /**
  275. * Update column dimensions when inserting/deleting rows/columns.
  276. *
  277. * @param Worksheet $worksheet The worksheet that we're editing
  278. */
  279. protected function adjustColumnDimensions(Worksheet $worksheet): void
  280. {
  281. $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
  282. if (!empty($aColumnDimensions)) {
  283. foreach ($aColumnDimensions as $objColumnDimension) {
  284. $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1');
  285. [$newReference] = Coordinate::coordinateFromString($newReference);
  286. if ($objColumnDimension->getColumnIndex() !== $newReference) {
  287. $objColumnDimension->setColumnIndex($newReference);
  288. }
  289. }
  290. $worksheet->refreshColumnDimensions();
  291. }
  292. }
  293. /**
  294. * Update row dimensions when inserting/deleting rows/columns.
  295. *
  296. * @param Worksheet $worksheet The worksheet that we're editing
  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, $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());
  306. [, $newReference] = Coordinate::coordinateFromString($newReference);
  307. $newRoweference = (int) $newReference;
  308. if ($objRowDimension->getRowIndex() !== $newRoweference) {
  309. $objRowDimension->setRowIndex($newRoweference);
  310. }
  311. }
  312. $worksheet->refreshRowDimensions();
  313. $copyDimension = $worksheet->getRowDimension($beforeRow - 1);
  314. for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) {
  315. $newDimension = $worksheet->getRowDimension($i);
  316. $newDimension->setRowHeight($copyDimension->getRowHeight());
  317. $newDimension->setVisible($copyDimension->getVisible());
  318. $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
  319. $newDimension->setCollapsed($copyDimension->getCollapsed());
  320. }
  321. }
  322. }
  323. /**
  324. * Insert a new column or row, updating all possible related data.
  325. *
  326. * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1')
  327. * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
  328. * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
  329. * @param Worksheet $worksheet The worksheet that we're editing
  330. */
  331. public function insertNewBefore(
  332. string $beforeCellAddress,
  333. int $numberOfColumns,
  334. int $numberOfRows,
  335. Worksheet $worksheet
  336. ): void {
  337. $remove = ($numberOfColumns < 0 || $numberOfRows < 0);
  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. $cellCollection = $worksheet->getCellCollection();
  359. $missingCoordinates = array_filter(
  360. array_map(function ($row) use ($highestColumn) {
  361. return $highestColumn . $row;
  362. }, range(1, $highestRow)),
  363. function ($coordinate) use ($cellCollection) {
  364. return $cellCollection->has($coordinate) === false;
  365. }
  366. );
  367. // Create missing cells with null values
  368. if (!empty($missingCoordinates)) {
  369. foreach ($missingCoordinates as $coordinate) {
  370. $worksheet->createNewCell($coordinate);
  371. }
  372. }
  373. $allCoordinates = $worksheet->getCoordinates();
  374. if ($remove) {
  375. // It's faster to reverse and pop than to use unshift, especially with large cell collections
  376. $allCoordinates = array_reverse($allCoordinates);
  377. }
  378. // Loop through cells, bottom-up, and change cell coordinate
  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. if ($objDrawing->getCoordinates2() !== '') {
  464. $newReference = $this->updateCellReference($objDrawing->getCoordinates2());
  465. if ($objDrawing->getCoordinates2() != $newReference) {
  466. $objDrawing->setCoordinates2($newReference);
  467. }
  468. }
  469. }
  470. // Update workbook: define names
  471. if (count($worksheet->getParent()->getDefinedNames()) > 0) {
  472. $this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  473. }
  474. // Garbage collect
  475. $worksheet->garbageCollect();
  476. }
  477. /**
  478. * Update references within formulas.
  479. *
  480. * @param string $formula Formula to update
  481. * @param string $beforeCellAddress Insert before this one
  482. * @param int $numberOfColumns Number of columns to insert
  483. * @param int $numberOfRows Number of rows to insert
  484. * @param string $worksheetName Worksheet name/title
  485. *
  486. * @return string Updated formula
  487. */
  488. public function updateFormulaReferences(
  489. $formula = '',
  490. $beforeCellAddress = 'A1',
  491. $numberOfColumns = 0,
  492. $numberOfRows = 0,
  493. $worksheetName = '',
  494. bool $includeAbsoluteReferences = false
  495. ) {
  496. if (
  497. $this->cellReferenceHelper === null ||
  498. $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
  499. ) {
  500. $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
  501. }
  502. // Update cell references in the formula
  503. $formulaBlocks = explode('"', $formula);
  504. $i = false;
  505. foreach ($formulaBlocks as &$formulaBlock) {
  506. // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
  507. if ($i = !$i) {
  508. $adjustCount = 0;
  509. $newCellTokens = $cellTokens = [];
  510. // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
  511. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  512. if ($matchCount > 0) {
  513. foreach ($matches as $match) {
  514. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  515. $fromString .= $match[3] . ':' . $match[4];
  516. $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences), 2);
  517. $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences), 2);
  518. if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
  519. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  520. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  521. $toString .= $modified3 . ':' . $modified4;
  522. // 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
  523. $column = 100000;
  524. $row = 10000000 + (int) trim($match[3], '$');
  525. $cellIndex = $column . $row;
  526. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  527. $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
  528. ++$adjustCount;
  529. }
  530. }
  531. }
  532. }
  533. // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
  534. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  535. if ($matchCount > 0) {
  536. foreach ($matches as $match) {
  537. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  538. $fromString .= $match[3] . ':' . $match[4];
  539. $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences), 0, -2);
  540. $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences), 0, -2);
  541. if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
  542. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  543. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  544. $toString .= $modified3 . ':' . $modified4;
  545. // 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
  546. $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000;
  547. $row = 10000000;
  548. $cellIndex = $column . $row;
  549. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  550. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i';
  551. ++$adjustCount;
  552. }
  553. }
  554. }
  555. }
  556. // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
  557. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  558. if ($matchCount > 0) {
  559. foreach ($matches as $match) {
  560. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  561. $fromString .= $match[3] . ':' . $match[4];
  562. $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences);
  563. $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences);
  564. if ($match[3] . $match[4] !== $modified3 . $modified4) {
  565. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  566. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  567. $toString .= $modified3 . ':' . $modified4;
  568. [$column, $row] = Coordinate::coordinateFromString($match[3]);
  569. // 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
  570. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  571. $row = (int) trim($row, '$') + 10000000;
  572. $cellIndex = $column . $row;
  573. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  574. $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
  575. ++$adjustCount;
  576. }
  577. }
  578. }
  579. }
  580. // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
  581. $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER);
  582. if ($matchCount > 0) {
  583. foreach ($matches as $match) {
  584. $fromString = ($match[2] > '') ? $match[2] . '!' : '';
  585. $fromString .= $match[3];
  586. $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences);
  587. if ($match[3] !== $modified3) {
  588. if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) {
  589. $toString = ($match[2] > '') ? $match[2] . '!' : '';
  590. $toString .= $modified3;
  591. [$column, $row] = Coordinate::coordinateFromString($match[3]);
  592. $columnAdditionalIndex = $column[0] === '$' ? 1 : 0;
  593. $rowAdditionalIndex = $row[0] === '$' ? 1 : 0;
  594. // 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
  595. $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
  596. $row = (int) trim($row, '$') + 10000000;
  597. $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex;
  598. $newCellTokens[$cellIndex] = preg_quote($toString, '/');
  599. $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i';
  600. ++$adjustCount;
  601. }
  602. }
  603. }
  604. }
  605. if ($adjustCount > 0) {
  606. if ($numberOfColumns > 0 || $numberOfRows > 0) {
  607. krsort($cellTokens);
  608. krsort($newCellTokens);
  609. } else {
  610. ksort($cellTokens);
  611. ksort($newCellTokens);
  612. } // Update cell references in the formula
  613. $formulaBlock = str_replace('\\', '', (string) preg_replace($cellTokens, $newCellTokens, $formulaBlock));
  614. }
  615. }
  616. }
  617. unset($formulaBlock);
  618. // Then rebuild the formula string
  619. return implode('"', $formulaBlocks);
  620. }
  621. /**
  622. * Update all cell references within a formula, irrespective of worksheet.
  623. */
  624. public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
  625. {
  626. $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
  627. if ($numberOfColumns !== 0) {
  628. $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
  629. }
  630. if ($numberOfRows !== 0) {
  631. $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
  632. }
  633. return $formula;
  634. }
  635. private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
  636. {
  637. $splitCount = preg_match_all(
  638. '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
  639. $formula,
  640. $splitRanges,
  641. PREG_OFFSET_CAPTURE
  642. );
  643. $columnLengths = array_map('strlen', array_column($splitRanges[6], 0));
  644. $rowLengths = array_map('strlen', array_column($splitRanges[7], 0));
  645. $columnOffsets = array_column($splitRanges[6], 1);
  646. $rowOffsets = array_column($splitRanges[7], 1);
  647. $columns = $splitRanges[6];
  648. $rows = $splitRanges[7];
  649. while ($splitCount > 0) {
  650. --$splitCount;
  651. $columnLength = $columnLengths[$splitCount];
  652. $rowLength = $rowLengths[$splitCount];
  653. $columnOffset = $columnOffsets[$splitCount];
  654. $rowOffset = $rowOffsets[$splitCount];
  655. $column = $columns[$splitCount][0];
  656. $row = $rows[$splitCount][0];
  657. if (!empty($column) && $column[0] !== '$') {
  658. $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns);
  659. $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
  660. }
  661. if (!empty($row) && $row[0] !== '$') {
  662. $row += $numberOfRows;
  663. $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
  664. }
  665. }
  666. return $formula;
  667. }
  668. private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
  669. {
  670. $splitCount = preg_match_all(
  671. '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
  672. $formula,
  673. $splitRanges,
  674. PREG_OFFSET_CAPTURE
  675. );
  676. $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0));
  677. $fromColumnOffsets = array_column($splitRanges[1], 1);
  678. $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0));
  679. $toColumnOffsets = array_column($splitRanges[2], 1);
  680. $fromColumns = $splitRanges[1];
  681. $toColumns = $splitRanges[2];
  682. while ($splitCount > 0) {
  683. --$splitCount;
  684. $fromColumnLength = $fromColumnLengths[$splitCount];
  685. $toColumnLength = $toColumnLengths[$splitCount];
  686. $fromColumnOffset = $fromColumnOffsets[$splitCount];
  687. $toColumnOffset = $toColumnOffsets[$splitCount];
  688. $fromColumn = $fromColumns[$splitCount][0];
  689. $toColumn = $toColumns[$splitCount][0];
  690. if (!empty($fromColumn) && $fromColumn[0] !== '$') {
  691. $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
  692. $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
  693. }
  694. if (!empty($toColumn) && $toColumn[0] !== '$') {
  695. $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
  696. $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
  697. }
  698. }
  699. return $formula;
  700. }
  701. private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
  702. {
  703. $splitCount = preg_match_all(
  704. '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
  705. $formula,
  706. $splitRanges,
  707. PREG_OFFSET_CAPTURE
  708. );
  709. $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0));
  710. $fromRowOffsets = array_column($splitRanges[1], 1);
  711. $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0));
  712. $toRowOffsets = array_column($splitRanges[2], 1);
  713. $fromRows = $splitRanges[1];
  714. $toRows = $splitRanges[2];
  715. while ($splitCount > 0) {
  716. --$splitCount;
  717. $fromRowLength = $fromRowLengths[$splitCount];
  718. $toRowLength = $toRowLengths[$splitCount];
  719. $fromRowOffset = $fromRowOffsets[$splitCount];
  720. $toRowOffset = $toRowOffsets[$splitCount];
  721. $fromRow = $fromRows[$splitCount][0];
  722. $toRow = $toRows[$splitCount][0];
  723. if (!empty($fromRow) && $fromRow[0] !== '$') {
  724. $fromRow += $numberOfRows;
  725. $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
  726. }
  727. if (!empty($toRow) && $toRow[0] !== '$') {
  728. $toRow += $numberOfRows;
  729. $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
  730. }
  731. }
  732. return $formula;
  733. }
  734. /**
  735. * Update cell reference.
  736. *
  737. * @param string $cellReference Cell address or range of addresses
  738. *
  739. * @return string Updated cell range
  740. */
  741. private function updateCellReference($cellReference = 'A1', bool $includeAbsoluteReferences = false)
  742. {
  743. // Is it in another worksheet? Will not have to update anything.
  744. if (strpos($cellReference, '!') !== false) {
  745. return $cellReference;
  746. // Is it a range or a single cell?
  747. } elseif (!Coordinate::coordinateIsRange($cellReference)) {
  748. // Single cell
  749. return $this->cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences);
  750. } elseif (Coordinate::coordinateIsRange($cellReference)) {
  751. // Range
  752. return $this->updateCellRange($cellReference, $includeAbsoluteReferences);
  753. }
  754. // Return original
  755. return $cellReference;
  756. }
  757. /**
  758. * Update named formulae (i.e. containing worksheet references / named ranges).
  759. *
  760. * @param Spreadsheet $spreadsheet Object to update
  761. * @param string $oldName Old name (name to replace)
  762. * @param string $newName New name
  763. */
  764. public function updateNamedFormulae(Spreadsheet $spreadsheet, $oldName = '', $newName = ''): void
  765. {
  766. if ($oldName == '') {
  767. return;
  768. }
  769. foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
  770. foreach ($sheet->getCoordinates(false) as $coordinate) {
  771. $cell = $sheet->getCell($coordinate);
  772. if ($cell->getDataType() === DataType::TYPE_FORMULA) {
  773. $formula = $cell->getValue();
  774. if (strpos($formula, $oldName) !== false) {
  775. $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
  776. $formula = str_replace($oldName . '!', $newName . '!', $formula);
  777. $cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
  778. }
  779. }
  780. }
  781. }
  782. }
  783. private function updateDefinedNames(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
  784. {
  785. foreach ($worksheet->getParent()->getDefinedNames() as $definedName) {
  786. if ($definedName->isFormula() === false) {
  787. $this->updateNamedRange($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  788. } else {
  789. $this->updateNamedFormula($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
  790. }
  791. }
  792. }
  793. private function updateNamedRange(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
  794. {
  795. $cellAddress = $definedName->getValue();
  796. $asFormula = ($cellAddress[0] === '=');
  797. if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
  798. if ($asFormula === true) {
  799. $formula = $this->updateFormulaReferences($cellAddress, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle());
  800. $definedName->setValue($formula);
  801. } else {
  802. $definedName->setValue($this->updateCellReference(ltrim($cellAddress, '=')));
  803. }
  804. }
  805. }
  806. private function updateNamedFormula(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
  807. {
  808. if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
  809. $formula = $definedName->getValue();
  810. $formula = $this->updateFormulaReferences($formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle());
  811. $definedName->setValue($formula);
  812. }
  813. }
  814. /**
  815. * Update cell range.
  816. *
  817. * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
  818. *
  819. * @return string Updated cell range
  820. */
  821. private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false): string
  822. {
  823. if (!Coordinate::coordinateIsRange($cellRange)) {
  824. throw new Exception('Only cell ranges may be passed to this method.');
  825. }
  826. // Update range
  827. $range = Coordinate::splitRange($cellRange);
  828. $ic = count($range);
  829. for ($i = 0; $i < $ic; ++$i) {
  830. $jc = count($range[$i]);
  831. for ($j = 0; $j < $jc; ++$j) {
  832. if (ctype_alpha($range[$i][$j])) {
  833. $range[$i][$j] = Coordinate::coordinateFromString(
  834. $this->cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences)
  835. )[0];
  836. } elseif (ctype_digit($range[$i][$j])) {
  837. $range[$i][$j] = Coordinate::coordinateFromString(
  838. $this->cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences)
  839. )[1];
  840. } else {
  841. $range[$i][$j] = $this->cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences);
  842. }
  843. }
  844. }
  845. // Recreate range string
  846. return Coordinate::buildRange($range);
  847. }
  848. private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void
  849. {
  850. $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn + $numberOfColumns);
  851. $endColumnId = Coordinate::stringFromColumnIndex($beforeColumn);
  852. for ($row = 1; $row <= $highestRow - 1; ++$row) {
  853. for ($column = $startColumnId; $column !== $endColumnId; ++$column) {
  854. $coordinate = $column . $row;
  855. $this->clearStripCell($worksheet, $coordinate);
  856. }
  857. }
  858. }
  859. private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void
  860. {
  861. $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn);
  862. ++$highestColumn;
  863. for ($column = $startColumnId; $column !== $highestColumn; ++$column) {
  864. for ($row = $beforeRow + $numberOfRows; $row <= $beforeRow - 1; ++$row) {
  865. $coordinate = $column . $row;
  866. $this->clearStripCell($worksheet, $coordinate);
  867. }
  868. }
  869. }
  870. private function clearStripCell(Worksheet $worksheet, string $coordinate): void
  871. {
  872. $worksheet->removeConditionalStyles($coordinate);
  873. $worksheet->setHyperlink($coordinate);
  874. $worksheet->setDataValidation($coordinate);
  875. $worksheet->removeComment($coordinate);
  876. if ($worksheet->cellExists($coordinate)) {
  877. $worksheet->getCell($coordinate)->setValueExplicit(null, DataType::TYPE_NULL);
  878. $worksheet->getCell($coordinate)->setXfIndex(0);
  879. }
  880. }
  881. private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void
  882. {
  883. $autoFilter = $worksheet->getAutoFilter();
  884. $autoFilterRange = $autoFilter->getRange();
  885. if (!empty($autoFilterRange)) {
  886. if ($numberOfColumns !== 0) {
  887. $autoFilterColumns = $autoFilter->getColumns();
  888. if (count($autoFilterColumns) > 0) {
  889. $column = '';
  890. $row = 0;
  891. sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
  892. $columnIndex = Coordinate::columnIndexFromString($column);
  893. [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
  894. if ($columnIndex <= $rangeEnd[0]) {
  895. if ($numberOfColumns < 0) {
  896. $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter);
  897. }
  898. $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
  899. // Shuffle columns in autofilter range
  900. if ($numberOfColumns > 0) {
  901. $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter);
  902. } else {
  903. $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter);
  904. }
  905. }
  906. }
  907. }
  908. $worksheet->setAutoFilter(
  909. $this->updateCellReference($autoFilterRange)
  910. );
  911. }
  912. }
  913. private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void
  914. {
  915. // If we're actually deleting any columns that fall within the autofilter range,
  916. // then we delete any rules for those columns
  917. $deleteColumn = $columnIndex + $numberOfColumns - 1;
  918. $deleteCount = abs($numberOfColumns);
  919. for ($i = 1; $i <= $deleteCount; ++$i) {
  920. $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1);
  921. if (isset($autoFilterColumns[$columnName])) {
  922. $autoFilter->clearColumn($columnName);
  923. }
  924. ++$deleteColumn;
  925. }
  926. }
  927. private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void
  928. {
  929. $startColRef = $startCol;
  930. $endColRef = $rangeEnd;
  931. $toColRef = $rangeEnd + $numberOfColumns;
  932. do {
  933. $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
  934. --$endColRef;
  935. --$toColRef;
  936. } while ($startColRef <= $endColRef);
  937. }
  938. private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void
  939. {
  940. // For delete, we shuffle from beginning to end to avoid overwriting
  941. $startColID = Coordinate::stringFromColumnIndex($startCol);
  942. $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
  943. $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1);
  944. do {
  945. $autoFilter->shiftColumn($startColID, $toColID);
  946. ++$startColID;
  947. ++$toColID;
  948. } while ($startColID !== $endColID);
  949. }
  950. private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void
  951. {
  952. $tableCollection = $worksheet->getTableCollection();
  953. foreach ($tableCollection as $table) {
  954. $tableRange = $table->getRange();
  955. if (!empty($tableRange)) {
  956. if ($numberOfColumns !== 0) {
  957. $tableColumns = $table->getColumns();
  958. if (count($tableColumns) > 0) {
  959. $column = '';
  960. $row = 0;
  961. sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
  962. $columnIndex = Coordinate::columnIndexFromString($column);
  963. [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange);
  964. if ($columnIndex <= $rangeEnd[0]) {
  965. if ($numberOfColumns < 0) {
  966. $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table);
  967. }
  968. $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
  969. // Shuffle columns in table range
  970. if ($numberOfColumns > 0) {
  971. $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table);
  972. } else {
  973. $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table);
  974. }
  975. }
  976. }
  977. }
  978. $table->setRange($this->updateCellReference($tableRange));
  979. }
  980. }
  981. }
  982. private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void
  983. {
  984. // If we're actually deleting any columns that fall within the table range,
  985. // then we delete any rules for those columns
  986. $deleteColumn = $columnIndex + $numberOfColumns - 1;
  987. $deleteCount = abs($numberOfColumns);
  988. for ($i = 1; $i <= $deleteCount; ++$i) {
  989. $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1);
  990. if (isset($tableColumns[$columnName])) {
  991. $table->clearColumn($columnName);
  992. }
  993. ++$deleteColumn;
  994. }
  995. }
  996. private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void
  997. {
  998. $startColRef = $startCol;
  999. $endColRef = $rangeEnd;
  1000. $toColRef = $rangeEnd + $numberOfColumns;
  1001. do {
  1002. $table->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
  1003. --$endColRef;
  1004. --$toColRef;
  1005. } while ($startColRef <= $endColRef);
  1006. }
  1007. private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void
  1008. {
  1009. // For delete, we shuffle from beginning to end to avoid overwriting
  1010. $startColID = Coordinate::stringFromColumnIndex($startCol);
  1011. $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
  1012. $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1);
  1013. do {
  1014. $table->shiftColumn($startColID, $toColID);
  1015. ++$startColID;
  1016. ++$toColID;
  1017. } while ($startColID !== $endColID);
  1018. }
  1019. private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void
  1020. {
  1021. $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1);
  1022. for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
  1023. // Style
  1024. $coordinate = $beforeColumnName . $i;
  1025. if ($worksheet->cellExists($coordinate)) {
  1026. $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
  1027. for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
  1028. $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
  1029. }
  1030. }
  1031. }
  1032. }
  1033. private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void
  1034. {
  1035. $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
  1036. for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) {
  1037. // Style
  1038. $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
  1039. if ($worksheet->cellExists($coordinate)) {
  1040. $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
  1041. for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
  1042. $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
  1043. }
  1044. }
  1045. }
  1046. }
  1047. /**
  1048. * __clone implementation. Cloning should not be allowed in a Singleton!
  1049. */
  1050. final public function __clone()
  1051. {
  1052. throw new Exception('Cloning a Singleton is not allowed!');
  1053. }
  1054. }