ReferenceHelper.php 46 KB

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