ReferenceHelper.php 43 KB

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