ReferenceHelper.php 39 KB

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