ILIAS  Release_4_0_x_branch Revision 61816
 All Data Structures Namespaces Files Functions Variables Groups Pages
ReferenceHelper.php
Go to the documentation of this file.
1 <?php
30 if (!defined('PHPEXCEL_ROOT')) {
34  define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../');
35 }
36 
38 require_once PHPEXCEL_ROOT . 'PHPExcel/Worksheet.php';
39 
41 require_once PHPEXCEL_ROOT . 'PHPExcel/Cell.php';
42 
44 require_once PHPEXCEL_ROOT . 'PHPExcel/Cell/DataType.php';
45 
47 require_once PHPEXCEL_ROOT . 'PHPExcel/Style.php';
48 
50 require_once PHPEXCEL_ROOT . 'PHPExcel/Worksheet/Drawing.php';
51 
53 require_once PHPEXCEL_ROOT . 'PHPExcel/Calculation/FormulaParser.php';
54 
56 require_once PHPEXCEL_ROOT . 'PHPExcel/Calculation/FormulaToken.php';
57 
58 
67 {
73  private static $_instance;
74 
80  public static function getInstance() {
81  if (!isset(self::$_instance) || is_null(self::$_instance)) {
82  self::$_instance = new PHPExcel_ReferenceHelper();
83  }
84 
85  return self::$_instance;
86  }
87 
91  protected function __construct() {
92  }
93 
102  public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null) {
103  // Get a copy of the cell collection
104  /*$aTemp = $pSheet->getCellCollection();
105  $aCellCollection = array();
106  foreach ($aTemp as $key => $value) {
107  $aCellCollection[$key] = clone $value;
108  }*/
109  $aCellCollection = $pSheet->getCellCollection();
110 
111  // Get coordinates of $pBefore
112  $beforeColumn = 'A';
113  $beforeRow = 1;
114  list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore );
115 
116 
117  // Clear cells if we are removing columns or rows
118  $highestColumn = $pSheet->getHighestColumn();
119  $highestRow = $pSheet->getHighestRow();
120 
121  // 1. Clear column strips if we are removing columns
122  if ($pNumCols < 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols > 0) {
123  for ($i = 1; $i <= $highestRow - 1; ++$i) {
124  for ($j = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1 + $pNumCols; $j <= PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2; ++$j) {
125  $coordinate = PHPExcel_Cell::stringFromColumnIndex($j) . $i;
126  $pSheet->removeConditionalStyles($coordinate);
127  if ($pSheet->cellExists($coordinate)) {
128  $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL);
129  $pSheet->getCell($coordinate)->setXfIndex(0);
130  }
131  }
132  }
133  }
134 
135  // 2. Clear row strips if we are removing rows
136  if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) {
137  for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
138  for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) {
139  $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . $j;
140  $pSheet->removeConditionalStyles($coordinate);
141  if ($pSheet->cellExists($coordinate)) {
142  $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL);
143  $pSheet->getCell($coordinate)->setXfIndex(0);
144  }
145  }
146  }
147  }
148 
149 
150  // Loop through cells, bottom-up, and change cell coordinates
151  while ( ($cell = ($pNumCols < 0 || $pNumRows < 0) ? array_shift($aCellCollection) : array_pop($aCellCollection)) ) {
152  // New coordinates
153  $newCoordinates = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1 + $pNumCols ) . ($cell->getRow() + $pNumRows);
154 
155  // Should the cell be updated? Move value and cellXf index from one cell to another.
156  if (
157  (PHPExcel_Cell::columnIndexFromString( $cell->getColumn() ) >= PHPExcel_Cell::columnIndexFromString($beforeColumn)) &&
158  ($cell->getRow() >= $beforeRow)
159  ) {
160 
161  // Update cell styles
162  $pSheet->getCell($newCoordinates)->setXfIndex($cell->getXfIndex());
163  $cell->setXfIndex(0);
164 
165  // Insert this cell at its new location
166  if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
167  // Formula should be adjusted
168  $pSheet->setCellValue(
169  $newCoordinates
170  , $this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows)
171  );
172  } else {
173  // Formula should not be adjusted
174  $pSheet->setCellValue($newCoordinates, $cell->getValue());
175  }
176 
177  // Clear the original cell
178  $pSheet->setCellValue($cell->getCoordinate(), '');
179  }
180  }
181 
182 
183  // Duplicate styles for the newly inserted cells
184  $highestColumn = $pSheet->getHighestColumn();
185  $highestRow = $pSheet->getHighestRow();
186 
187  if ($pNumCols > 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 > 0) {
188  for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
189 
190  // Style
191  $coordinate = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 ) . $i;
192  if ($pSheet->cellExists($coordinate)) {
193  $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
194  $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ?
195  $pSheet->getConditionalStyles($coordinate) : false;
196  for ($j = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $j <= PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols; ++$j) {
197  $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
198  if ($conditionalStyles) {
199  $cloned = array();
200  foreach ($conditionalStyles as $conditionalStyle) {
201  $cloned[] = clone $conditionalStyle;
202  }
203  $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($j) . $i, $cloned);
204  }
205  }
206  }
207 
208  }
209  }
210 
211  if ($pNumRows > 0 && $beforeRow - 1 > 0) {
212  for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) {
213 
214  // Style
215  $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1);
216  if ($pSheet->cellExists($coordinate)) {
217  $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
218  $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ?
219  $pSheet->getConditionalStyles($coordinate) : false;
220  for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) {
221  $pSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
222  if ($conditionalStyles) {
223  $cloned = array();
224  foreach ($conditionalStyles as $conditionalStyle) {
225  $cloned[] = clone $conditionalStyle;
226  }
227  $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($i) . $j, $cloned);
228  }
229  }
230  }
231  }
232  }
233 
234 
235  // Update worksheet: column dimensions
236  $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true);
237  if (count($aColumnDimensions) > 0) {
238  foreach ($aColumnDimensions as $objColumnDimension) {
239  $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows);
240  list($newReference) = PHPExcel_Cell::coordinateFromString($newReference);
241  if ($objColumnDimension->getColumnIndex() != $newReference) {
242  $objColumnDimension->setColumnIndex($newReference);
243  }
244  }
245  $pSheet->refreshColumnDimensions();
246  }
247 
248 
249  // Update worksheet: row dimensions
250  $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);
251  if (count($aRowDimensions) > 0) {
252  foreach ($aRowDimensions as $objRowDimension) {
253  $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);
254  list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);
255  if ($objRowDimension->getRowIndex() != $newReference) {
256  $objRowDimension->setRowIndex($newReference);
257  }
258  }
259  $pSheet->refreshRowDimensions();
260 
261  $copyDimension = $pSheet->getRowDimension($beforeRow - 1);
262  for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) {
263  $newDimension = $pSheet->getRowDimension($i);
264  $newDimension->setRowHeight($copyDimension->getRowHeight());
265  $newDimension->setVisible($copyDimension->getVisible());
266  $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
267  $newDimension->setCollapsed($copyDimension->getCollapsed());
268  }
269  }
270 
271 
272  // Update worksheet: breaks
273  $aBreaks = array_reverse($pSheet->getBreaks(), true);
274  foreach ($aBreaks as $key => $value) {
275  $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
276  if ($key != $newReference) {
277  $pSheet->setBreak( $newReference, $value );
278  $pSheet->setBreak( $key, PHPExcel_Worksheet::BREAK_NONE );
279  }
280  }
281 
282 
283  // Update worksheet: hyperlinks
284  $aHyperlinkCollection = array_reverse($pSheet->getHyperlinkCollection(), true);
285  foreach ($aHyperlinkCollection as $key => $value) {
286  $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
287  if ($key != $newReference) {
288  $pSheet->setHyperlink( $newReference, $value );
289  $pSheet->setHyperlink( $key, null );
290  }
291  }
292 
293 
294  // Update worksheet: data validations
295  $aDataValidationCollection = array_reverse($pSheet->getDataValidationCollection(), true);
296  foreach ($aDataValidationCollection as $key => $value) {
297  $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
298  if ($key != $newReference) {
299  $pSheet->setDataValidation( $newReference, $value );
300  $pSheet->setDataValidation( $key, null );
301  }
302  }
303 
304 
305  // Update worksheet: merge cells
306  $aMergeCells = array_reverse($pSheet->getMergeCells(), true);
307  foreach ($aMergeCells as $key => $value) {
308  $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
309  if ($key != $newReference) {
310  $pSheet->mergeCells( $newReference );
311  $pSheet->unmergeCells( $key );
312  }
313  }
314 
315 
316  // Update worksheet: protected cells
317  $aProtectedCells = array_reverse($pSheet->getProtectedCells(), true);
318  foreach ($aProtectedCells as $key => $value) {
319  $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
320  if ($key != $newReference) {
321  $pSheet->protectCells( $newReference, $value, true );
322  $pSheet->unprotectCells( $key );
323  }
324  }
325 
326 
327  // Update worksheet: autofilter
328  if ($pSheet->getAutoFilter() != '') {
329  $pSheet->setAutoFilter( $this->updateCellReference($pSheet->getAutoFilter(), $pBefore, $pNumCols, $pNumRows) );
330  }
331 
332 
333  // Update worksheet: freeze pane
334  if ($pSheet->getFreezePane() != '') {
335  $pSheet->freezePane( $this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows) );
336  }
337 
338 
339  // Page setup
340  if ($pSheet->getPageSetup()->isPrintAreaSet()) {
341  $pSheet->getPageSetup()->setPrintArea( $this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows) );
342  }
343 
344 
345  // Update worksheet: drawings
346  $aDrawings = $pSheet->getDrawingCollection();
347  foreach ($aDrawings as $objDrawing) {
348  $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
349  if ($objDrawing->getCoordinates() != $newReference) {
350  $objDrawing->setCoordinates($newReference);
351  }
352  }
353 
354 
355  // Update workbook: named ranges
356  if (count($pSheet->getParent()->getNamedRanges()) > 0) {
357  foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) {
358  if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) {
359  $namedRange->setRange(
360  $this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)
361  );
362  }
363  }
364  }
365 
366  // Garbage collect
367  $pSheet->garbageCollect();
368  }
369 
380  public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
381  // Formula stack
382  $executableFormulaArray = array();
383 
384  // Parse formula into a tree of tokens
385  $tokenisedFormula = PHPExcel_Calculation::getInstance()->parseFormula($pFormula);
386  $newCellTokens = $cellTokens = array();
387  // Build the translation table of cell tokens
388  foreach($tokenisedFormula as $token) {
389  if (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
390  $newCellTokens[] = $this->updateCellReference($token, $pBefore, $pNumCols, $pNumRows);
391  $cellTokens[] = '/'.$token.'/';
392  }
393  }
394 
395  // Update cell references in the formula
396  $formulaBlocks = explode('"',$pFormula);
397  $i = 0;
398  foreach($formulaBlocks as $formulaBlockKey => $formulaBlock) {
399  // Only count/replace in alternate array entries
400  if (($i++ % 2) == 0) {
401  $formulaBlocks[$formulaBlockKey] = preg_replace($cellTokens,$newCellTokens,$formulaBlock);
402  }
403  }
404  // Then rebuild the formula string
405  return implode('"',$formulaBlocks);
406  }
407 
418  public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
419  // Is it in another worksheet? Will not have to update anything.
420  if (strpos($pCellRange, "!") !== false) {
421  return $pCellRange;
422  // Is it a range or a single cell?
423  } elseif (strpos($pCellRange, ':') === false && strpos($pCellRange, ',') === false) {
424  // Single cell
425  return $this->_updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows);
426  } else if (strpos($pCellRange, ':') !== false || strpos($pCellRange, ',') !== false) {
427  // Range
428  return $this->_updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows);
429  } else {
430  // Return original
431  return $pCellRange;
432  }
433  }
434 
442  public function updateNamedFormulas(PHPExcel $pPhpExcel, $oldName = '', $newName = '') {
443  foreach ($pPhpExcel->getWorksheetIterator() as $sheet) {
444  foreach ($sheet->getCellCollection(false) as $cell) {
445  if (!is_null($cell) && $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
446  $formula = $cell->getValue();
447  if (strpos($formula, $oldName) !== false) {
448  $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
449  $formula = str_replace($oldName . "!", $newName . "!", $formula);
450  $cell->setValueExplicit($formula, PHPExcel_Cell_DataType::TYPE_FORMULA);
451  }
452  }
453  }
454  }
455  }
456 
467  private function _updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
468  if (strpos($pCellRange,':') !== false || strpos($pCellRange, ',') !== false) {
469  // Update range
470  $range = PHPExcel_Cell::splitRange($pCellRange);
471  for ($i = 0; $i < count($range); $i++) {
472  for ($j = 0; $j < count($range[$i]); $j++) {
473  $range[$i][$j] = $this->_updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows);
474  }
475  }
476 
477  // Recreate range string
478  return PHPExcel_Cell::buildRange($range);
479  } else {
480  throw new Exception("Only cell ranges may be passed to this method.");
481  }
482  }
483 
494  private function _updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
495  if (strpos($pCellReference, ':') === false && strpos($pCellReference, ',') === false) {
496  // Get coordinates of $pBefore
497  $beforeColumn = 'A';
498  $beforeRow = 1;
499  list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore );
500 
501  // Get coordinates
502  $newColumn = 'A';
503  $newRow = 1;
504  list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString( $pCellReference );
505 
506  // Make sure the reference can be used
507  if ($newColumn == '' && $newRow == '')
508  {
509  return $pCellReference;
510  }
511 
512  // Verify which parts should be updated
513  $updateColumn = (PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn))
514  && (strpos($newColumn, '$') === false)
515  && (strpos($beforeColumn, '$') === false);
516 
517  $updateRow = ($newRow >= $beforeRow)
518  && (strpos($newRow, '$') === false)
519  && (strpos($beforeRow, '$') === false);
520 
521  // Create new column reference
522  if ($updateColumn) {
523  $newColumn = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols );
524  }
525 
526  // Create new row reference
527  if ($updateRow) {
528  $newRow = $newRow + $pNumRows;
529  }
530 
531  // Return new reference
532  return $newColumn . $newRow;
533  } else {
534  throw new Exception("Only single cell references may be passed to this method.");
535  }
536  }
537 
543  public final function __clone() {
544  throw new Exception("Cloning a Singleton is not allowed!");
545  }
546 }