ReferenceHelper.php 48 KB

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