ReferenceHelper.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2013 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 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version 1.7.9, 2013-06-02
  26. */
  27. /**
  28. * PHPExcel_ReferenceHelper (Singleton)
  29. *
  30. * @category PHPExcel
  31. * @package PHPExcel
  32. * @copyright Copyright (c) 2006 - 2013 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. while (($cellID = $remove ? array_shift($aCellCollection) : array_pop($aCellCollection))) {
  397. $cell = $pSheet->getCell($cellID);
  398. $cellIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
  399. if ($cellIndex-1 + $pNumCols < 0) {
  400. continue;
  401. }
  402. // New coordinates
  403. $newCoordinates = PHPExcel_Cell::stringFromColumnIndex($cellIndex-1 + $pNumCols) . ($cell->getRow() + $pNumRows);
  404. // Should the cell be updated? Move value and cellXf index from one cell to another.
  405. if (($cellIndex >= $beforeColumnIndex) &&
  406. ($cell->getRow() >= $beforeRow)) {
  407. // Update cell styles
  408. $pSheet->getCell($newCoordinates)->setXfIndex($cell->getXfIndex());
  409. // Insert this cell at its new location
  410. if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
  411. // Formula should be adjusted
  412. $pSheet->getCell($newCoordinates)
  413. ->setValue($this->updateFormulaReferences($cell->getValue(),
  414. $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle()));
  415. } else {
  416. // Formula should not be adjusted
  417. $pSheet->getCell($newCoordinates)->setValue($cell->getValue());
  418. }
  419. // Clear the original cell
  420. $pSheet->getCellCacheController()->deleteCacheData($cellID);
  421. } else {
  422. /* We don't need to update styles for rows/columns before our insertion position,
  423. but we do still need to adjust any formulae in those cells */
  424. if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
  425. // Formula should be adjusted
  426. $cell->setValue($this->updateFormulaReferences($cell->getValue(),
  427. $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle()));
  428. }
  429. }
  430. }
  431. // Duplicate styles for the newly inserted cells
  432. $highestColumn = $pSheet->getHighestColumn();
  433. $highestRow = $pSheet->getHighestRow();
  434. if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) {
  435. for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
  436. // Style
  437. $coordinate = PHPExcel_Cell::stringFromColumnIndex( $beforeColumnIndex - 2 ) . $i;
  438. if ($pSheet->cellExists($coordinate)) {
  439. $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
  440. $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ?
  441. $pSheet->getConditionalStyles($coordinate) : false;
  442. for ($j = $beforeColumnIndex - 1; $j <= $beforeColumnIndex - 2 + $pNumCols; ++$j) {
  443. $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
  444. if ($conditionalStyles) {
  445. $cloned = array();
  446. foreach ($conditionalStyles as $conditionalStyle) {
  447. $cloned[] = clone $conditionalStyle;
  448. }
  449. $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($j) . $i, $cloned);
  450. }
  451. }
  452. }
  453. }
  454. }
  455. if ($pNumRows > 0 && $beforeRow - 1 > 0) {
  456. for ($i = $beforeColumnIndex - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
  457. // Style
  458. $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1);
  459. if ($pSheet->cellExists($coordinate)) {
  460. $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
  461. $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ?
  462. $pSheet->getConditionalStyles($coordinate) : false;
  463. for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) {
  464. $pSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
  465. if ($conditionalStyles) {
  466. $cloned = array();
  467. foreach ($conditionalStyles as $conditionalStyle) {
  468. $cloned[] = clone $conditionalStyle;
  469. }
  470. $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($i) . $j, $cloned);
  471. }
  472. }
  473. }
  474. }
  475. }
  476. // Update worksheet: column dimensions
  477. $this->_adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  478. // Update worksheet: row dimensions
  479. $this->_adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  480. // Update worksheet: page breaks
  481. $this->_adjustPageBreaks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  482. // Update worksheet: comments
  483. $this->_adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  484. // Update worksheet: hyperlinks
  485. $this->_adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  486. // Update worksheet: data validations
  487. $this->_adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  488. // Update worksheet: merge cells
  489. $this->_adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  490. // Update worksheet: protected cells
  491. $this->_adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
  492. // Update worksheet: autofilter
  493. $autoFilter = $pSheet->getAutoFilter();
  494. $autoFilterRange = $autoFilter->getRange();
  495. if (!empty($autoFilterRange)) {
  496. if ($pNumCols != 0) {
  497. $autoFilterColumns = array_keys($autoFilter->getColumns());
  498. if (count($autoFilterColumns) > 0) {
  499. sscanf($pBefore,'%[A-Z]%d', $column, $row);
  500. $columnIndex = PHPExcel_Cell::columnIndexFromString($column);
  501. list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($autoFilterRange);
  502. if ($columnIndex <= $rangeEnd[0]) {
  503. if ($pNumCols < 0) {
  504. // If we're actually deleting any columns that fall within the autofilter range,
  505. // then we delete any rules for those columns
  506. $deleteColumn = $columnIndex + $pNumCols - 1;
  507. $deleteCount = abs($pNumCols);
  508. for ($i = 1; $i <= $deleteCount; ++$i) {
  509. if (in_array(PHPExcel_Cell::stringFromColumnIndex($deleteColumn),$autoFilterColumns)) {
  510. $autoFilter->clearColumn(PHPExcel_Cell::stringFromColumnIndex($deleteColumn));
  511. }
  512. ++$deleteColumn;
  513. }
  514. }
  515. $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
  516. // Shuffle columns in autofilter range
  517. if ($pNumCols > 0) {
  518. // For insert, we shuffle from end to beginning to avoid overwriting
  519. $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
  520. $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol+$pNumCols-1);
  521. $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]);
  522. $startColRef = $startCol;
  523. $endColRef = $rangeEnd[0];
  524. $toColRef = $rangeEnd[0]+$pNumCols;
  525. do {
  526. $autoFilter->shiftColumn(PHPExcel_Cell::stringFromColumnIndex($endColRef-1),PHPExcel_Cell::stringFromColumnIndex($toColRef-1));
  527. --$endColRef;
  528. --$toColRef;
  529. } while ($startColRef <= $endColRef);
  530. } else {
  531. // For delete, we shuffle from beginning to end to avoid overwriting
  532. $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
  533. $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol+$pNumCols-1);
  534. $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]);
  535. do {
  536. $autoFilter->shiftColumn($startColID,$toColID);
  537. ++$startColID;
  538. ++$toColID;
  539. } while ($startColID != $endColID);
  540. }
  541. }
  542. }
  543. }
  544. $pSheet->setAutoFilter( $this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows) );
  545. }
  546. // Update worksheet: freeze pane
  547. if ($pSheet->getFreezePane() != '') {
  548. $pSheet->freezePane( $this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows) );
  549. }
  550. // Page setup
  551. if ($pSheet->getPageSetup()->isPrintAreaSet()) {
  552. $pSheet->getPageSetup()->setPrintArea( $this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows) );
  553. }
  554. // Update worksheet: drawings
  555. $aDrawings = $pSheet->getDrawingCollection();
  556. foreach ($aDrawings as $objDrawing) {
  557. $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
  558. if ($objDrawing->getCoordinates() != $newReference) {
  559. $objDrawing->setCoordinates($newReference);
  560. }
  561. }
  562. // Update workbook: named ranges
  563. if (count($pSheet->getParent()->getNamedRanges()) > 0) {
  564. foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) {
  565. if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) {
  566. $namedRange->setRange(
  567. $this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)
  568. );
  569. }
  570. }
  571. }
  572. // Garbage collect
  573. $pSheet->garbageCollect();
  574. }
  575. /**
  576. * Update references within formulas
  577. *
  578. * @param string $pFormula Formula to update
  579. * @param int $pBefore Insert before this one
  580. * @param int $pNumCols Number of columns to insert
  581. * @param int $pNumRows Number of rows to insert
  582. * @param string $sheetName Worksheet name/title
  583. * @return string Updated formula
  584. * @throws PHPExcel_Exception
  585. */
  586. public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') {
  587. // Update cell references in the formula
  588. $formulaBlocks = explode('"',$pFormula);
  589. $i = false;
  590. foreach($formulaBlocks as &$formulaBlock) {
  591. // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
  592. if ($i = !$i) {
  593. $adjustCount = 0;
  594. $newCellTokens = $cellTokens = array();
  595. // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
  596. $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_ROWRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER);
  597. if ($matchCount > 0) {
  598. foreach($matches as $match) {
  599. $fromString = ($match[2] > '') ? $match[2].'!' : '';
  600. $fromString .= $match[3].':'.$match[4];
  601. $modified3 = substr($this->updateCellReference('$A'.$match[3],$pBefore,$pNumCols,$pNumRows),2);
  602. $modified4 = substr($this->updateCellReference('$A'.$match[4],$pBefore,$pNumCols,$pNumRows),2);
  603. if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) {
  604. if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) {
  605. $toString = ($match[2] > '') ? $match[2].'!' : '';
  606. $toString .= $modified3.':'.$modified4;
  607. // 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
  608. $column = 100000;
  609. $row = 10000000+trim($match[3],'$');
  610. $cellIndex = $column.$row;
  611. $newCellTokens[$cellIndex] = preg_quote($toString);
  612. $cellTokens[$cellIndex] = '/(?<!\d)'.preg_quote($fromString).'(?!\d)/i';
  613. ++$adjustCount;
  614. }
  615. }
  616. }
  617. }
  618. // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
  619. $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_COLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER);
  620. if ($matchCount > 0) {
  621. foreach($matches as $match) {
  622. $fromString = ($match[2] > '') ? $match[2].'!' : '';
  623. $fromString .= $match[3].':'.$match[4];
  624. $modified3 = substr($this->updateCellReference($match[3].'$1',$pBefore,$pNumCols,$pNumRows),0,-2);
  625. $modified4 = substr($this->updateCellReference($match[4].'$1',$pBefore,$pNumCols,$pNumRows),0,-2);
  626. if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) {
  627. if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) {
  628. $toString = ($match[2] > '') ? $match[2].'!' : '';
  629. $toString .= $modified3.':'.$modified4;
  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($match[3],'$')) + 100000;
  632. $row = 10000000;
  633. $cellIndex = $column.$row;
  634. $newCellTokens[$cellIndex] = preg_quote($toString);
  635. $cellTokens[$cellIndex] = '/(?<![A-Z])'.preg_quote($fromString).'(?![A-Z])/i';
  636. ++$adjustCount;
  637. }
  638. }
  639. }
  640. }
  641. // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
  642. $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLRANGE.'/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].':'.$match[4];
  647. $modified3 = $this->updateCellReference($match[3],$pBefore,$pNumCols,$pNumRows);
  648. $modified4 = $this->updateCellReference($match[4],$pBefore,$pNumCols,$pNumRows);
  649. if ($match[3].$match[4] !== $modified3.$modified4) {
  650. if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) {
  651. $toString = ($match[2] > '') ? $match[2].'!' : '';
  652. $toString .= $modified3.':'.$modified4;
  653. list($column,$row) = PHPExcel_Cell::coordinateFromString($match[3]);
  654. // 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
  655. $column = PHPExcel_Cell::columnIndexFromString(trim($column,'$')) + 100000;
  656. $row = trim($row,'$') + 10000000;
  657. $cellIndex = $column.$row;
  658. $newCellTokens[$cellIndex] = preg_quote($toString);
  659. $cellTokens[$cellIndex] = '/(?<![A-Z])'.preg_quote($fromString).'(?!\d)/i';
  660. ++$adjustCount;
  661. }
  662. }
  663. }
  664. }
  665. // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
  666. $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLREF.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER);
  667. if ($matchCount > 0) {
  668. foreach($matches as $match) {
  669. $fromString = ($match[2] > '') ? $match[2].'!' : '';
  670. $fromString .= $match[3];
  671. $modified3 = $this->updateCellReference($match[3],$pBefore,$pNumCols,$pNumRows);
  672. if ($match[3] !== $modified3) {
  673. if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) {
  674. $toString = ($match[2] > '') ? $match[2].'!' : '';
  675. $toString .= $modified3;
  676. list($column,$row) = PHPExcel_Cell::coordinateFromString($match[3]);
  677. // 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
  678. $column = PHPExcel_Cell::columnIndexFromString(trim($column,'$')) + 100000;
  679. $row = trim($row,'$') + 10000000;
  680. $cellIndex = $column.$row;
  681. $newCellTokens[$cellIndex] = preg_quote($toString);
  682. $cellTokens[$cellIndex] = '/(?<![A-Z])'.preg_quote($fromString).'(?!\d)/i';
  683. ++$adjustCount;
  684. }
  685. }
  686. }
  687. }
  688. if ($adjustCount > 0) {
  689. if ($pNumCols > 0) {
  690. krsort($cellTokens);
  691. krsort($newCellTokens);
  692. } else {
  693. ksort($cellTokens);
  694. ksort($newCellTokens);
  695. }
  696. // Update cell references in the formula
  697. $formulaBlock = str_replace('\\','',preg_replace($cellTokens,$newCellTokens,$formulaBlock));
  698. }
  699. }
  700. }
  701. unset($formulaBlock);
  702. // Then rebuild the formula string
  703. return implode('"',$formulaBlocks);
  704. }
  705. /**
  706. * Update cell reference
  707. *
  708. * @param string $pCellRange Cell range
  709. * @param int $pBefore Insert before this one
  710. * @param int $pNumCols Number of columns to increment
  711. * @param int $pNumRows Number of rows to increment
  712. * @return string Updated cell range
  713. * @throws PHPExcel_Exception
  714. */
  715. public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
  716. // Is it in another worksheet? Will not have to update anything.
  717. if (strpos($pCellRange, "!") !== false) {
  718. return $pCellRange;
  719. // Is it a range or a single cell?
  720. } elseif (strpos($pCellRange, ':') === false && strpos($pCellRange, ',') === false) {
  721. // Single cell
  722. return $this->_updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows);
  723. } elseif (strpos($pCellRange, ':') !== false || strpos($pCellRange, ',') !== false) {
  724. // Range
  725. return $this->_updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows);
  726. } else {
  727. // Return original
  728. return $pCellRange;
  729. }
  730. }
  731. /**
  732. * Update named formulas (i.e. containing worksheet references / named ranges)
  733. *
  734. * @param PHPExcel $pPhpExcel Object to update
  735. * @param string $oldName Old name (name to replace)
  736. * @param string $newName New name
  737. */
  738. public function updateNamedFormulas(PHPExcel $pPhpExcel, $oldName = '', $newName = '') {
  739. if ($oldName == '') {
  740. return;
  741. }
  742. foreach ($pPhpExcel->getWorksheetIterator() as $sheet) {
  743. foreach ($sheet->getCellCollection(false) as $cellID) {
  744. $cell = $sheet->getCell($cellID);
  745. if (($cell !== NULL) && ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA)) {
  746. $formula = $cell->getValue();
  747. if (strpos($formula, $oldName) !== false) {
  748. $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
  749. $formula = str_replace($oldName . "!", $newName . "!", $formula);
  750. $cell->setValueExplicit($formula, PHPExcel_Cell_DataType::TYPE_FORMULA);
  751. }
  752. }
  753. }
  754. }
  755. }
  756. /**
  757. * Update cell range
  758. *
  759. * @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
  760. * @param int $pBefore Insert before this one
  761. * @param int $pNumCols Number of columns to increment
  762. * @param int $pNumRows Number of rows to increment
  763. * @return string Updated cell range
  764. * @throws PHPExcel_Exception
  765. */
  766. private function _updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
  767. if (strpos($pCellRange,':') !== false || strpos($pCellRange, ',') !== false) {
  768. // Update range
  769. $range = PHPExcel_Cell::splitRange($pCellRange);
  770. $ic = count($range);
  771. for ($i = 0; $i < $ic; ++$i) {
  772. $jc = count($range[$i]);
  773. for ($j = 0; $j < $jc; ++$j) {
  774. if (ctype_alpha($range[$i][$j])) {
  775. $r = PHPExcel_Cell::coordinateFromString($this->_updateSingleCellReference($range[$i][$j].'1', $pBefore, $pNumCols, $pNumRows));
  776. $range[$i][$j] = $r[0];
  777. } elseif(ctype_digit($range[$i][$j])) {
  778. $r = PHPExcel_Cell::coordinateFromString($this->_updateSingleCellReference('A'.$range[$i][$j], $pBefore, $pNumCols, $pNumRows));
  779. $range[$i][$j] = $r[1];
  780. } else {
  781. $range[$i][$j] = $this->_updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows);
  782. }
  783. }
  784. }
  785. // Recreate range string
  786. return PHPExcel_Cell::buildRange($range);
  787. } else {
  788. throw new PHPExcel_Exception("Only cell ranges may be passed to this method.");
  789. }
  790. }
  791. /**
  792. * Update single cell reference
  793. *
  794. * @param string $pCellReference Single cell reference
  795. * @param int $pBefore Insert before this one
  796. * @param int $pNumCols Number of columns to increment
  797. * @param int $pNumRows Number of rows to increment
  798. * @return string Updated cell reference
  799. * @throws PHPExcel_Exception
  800. */
  801. private function _updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
  802. if (strpos($pCellReference, ':') === false && strpos($pCellReference, ',') === false) {
  803. // Get coordinates of $pBefore
  804. list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore );
  805. // Get coordinates of $pCellReference
  806. list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString( $pCellReference );
  807. // Verify which parts should be updated
  808. $updateColumn = (($newColumn{0} != '$') && ($beforeColumn{0} != '$') &&
  809. PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn));
  810. $updateRow = (($newRow{0} != '$') && ($beforeRow{0} != '$') &&
  811. $newRow >= $beforeRow);
  812. // Create new column reference
  813. if ($updateColumn) {
  814. $newColumn = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols );
  815. }
  816. // Create new row reference
  817. if ($updateRow) {
  818. $newRow = $newRow + $pNumRows;
  819. }
  820. // Return new reference
  821. return $newColumn . $newRow;
  822. } else {
  823. throw new PHPExcel_Exception("Only single cell references may be passed to this method.");
  824. }
  825. }
  826. /**
  827. * __clone implementation. Cloning should not be allowed in a Singleton!
  828. *
  829. * @throws PHPExcel_Exception
  830. */
  831. public final function __clone() {
  832. throw new PHPExcel_Exception("Cloning a Singleton is not allowed!");
  833. }
  834. }