ReferenceHelper.php 43 KB

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