PHPExcel
[ class tree: PHPExcel ] [ index: PHPExcel ] [ all elements ]

Source for file ReferenceHelper.php

Documentation is available at ReferenceHelper.php

  1. <?php
  2. /**
  3.  * PHPExcel
  4.  *
  5.  * Copyright (c) 2006 - 2008 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 - 2008 PHPExcel (http://www.codeplex.com/PHPExcel)
  24.  * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
  25.  * @version    1.6.3, 2008-08-25
  26.  */
  27.  
  28.  
  29. /** PHPExcel_Worksheet */
  30. require_once 'PHPExcel/Worksheet.php';
  31.  
  32. /** PHPExcel_Cell */
  33. require_once 'PHPExcel/Cell.php';
  34.  
  35. /** PHPExcel_Cell_DataType */
  36. require_once 'PHPExcel/Cell/DataType.php';
  37.  
  38. /** PHPExcel_Style */
  39. require_once 'PHPExcel/Style.php';
  40.  
  41. /** PHPExcel_Worksheet_Drawing */
  42. require_once 'PHPExcel/Worksheet/Drawing.php';
  43.  
  44. /** PHPExcel_Calculation_FormulaParser */
  45. require_once 'PHPExcel/Calculation/FormulaParser.php';
  46.  
  47. /** PHPExcel_Calculation_FormulaToken */
  48. require_once 'PHPExcel/Calculation/FormulaToken.php';
  49.  
  50.  
  51. /**
  52.  * PHPExcel_ReferenceHelper (Singleton)
  53.  *
  54.  * @category   PHPExcel
  55.  * @package    PHPExcel
  56.  * @copyright  Copyright (c) 2006 - 2008 PHPExcel (http://www.codeplex.com/PHPExcel)
  57.  */
  58. {
  59.     /**
  60.      * Instance of this class
  61.      *
  62.      * @var PHPExcel_ReferenceHelper 
  63.      */
  64.     private static $_instance;
  65.     
  66.     /**
  67.      * Get an instance of this class
  68.      *
  69.      * @return PHPExcel_ReferenceHelper 
  70.      */
  71.     public static function getInstance() {
  72.         if (!isset(self::$_instance) || is_null(self::$_instance)) {
  73.             self::$_instance = new PHPExcel_ReferenceHelper();
  74.         }
  75.         
  76.         return self::$_instance;
  77.     }
  78.     
  79.     /**
  80.      * Create a new PHPExcel_Calculation
  81.      */
  82.     protected function __construct() {
  83.     }
  84.     
  85.     /**
  86.      * Insert a new column, updating all possible related data
  87.      *
  88.      * @param     int    $pBefore    Insert before this one
  89.      * @param     int    $pNumCols    Number of columns to insert
  90.      * @param     int    $pNumRows    Number of rows to insert
  91.      * @throws     Exception
  92.      */
  93.     public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null) {
  94.         // Get a copy of the cell collection
  95.         /*$aTemp = $pSheet->getCellCollection();
  96.         $aCellCollection = array();
  97.         foreach ($aTemp as $key => $value) {
  98.             $aCellCollection[$key] = clone $value;
  99.         }*/
  100.         $aCellCollection = $pSheet->getCellCollection();
  101.             
  102.         // Get coordinates of $pBefore
  103.         $beforeColumn     = 'A';
  104.         $beforeRow        = 1;
  105.         list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore );
  106.             
  107.             
  108.         // Remove cell styles?
  109.         $highestColumn     = $pSheet->getHighestColumn();
  110.         $highestRow     = $pSheet->getHighestRow();
  111.  
  112.         if ($pNumCols < 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols > 0) {
  113.             for ($i = 1; $i <= $highestRow - 1; $i++) {
  114.  
  115.                 $pSheet->duplicateStyle(
  116.                     new PHPExcel_Style(),
  117.                     (PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1 + $pNumCols ) . $i) . ':' . (PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 ) . $i)
  118.                 );    
  119.                     
  120.             }
  121.         }
  122.  
  123.         if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) {
  124.             for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; $i++) {
  125.                     
  126.                 $pSheet->duplicateStyle(
  127.                     new PHPExcel_Style(),
  128.                     (PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow + $pNumRows)) . ':' . (PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1))
  129.                 );
  130.                     
  131.             }
  132.         }
  133.             
  134.             
  135.            // Loop trough cells, bottom-up, and change cell coordinates
  136.         while ( ($cell = ($pNumCols < 0 || $pNumRows < 0) ? array_shift($aCellCollection) : array_pop($aCellCollection)) ) {
  137.             // New coordinates
  138.             $newCoordinates = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1 + $pNumCols ) . ($cell->getRow() + $pNumRows);
  139.                                 
  140.             // Should the cell be updated?
  141.             if ( 
  142.                     (PHPExcel_Cell::columnIndexFromString( $cell->getColumn() ) >= PHPExcel_Cell::columnIndexFromString($beforeColumn)) &&
  143.                      ($cell->getRow() >= $beforeRow)
  144.                  ) {
  145.  
  146.                 // Update cell styles
  147.                 $pSheet->duplicateStyle( $pSheet->getStyle($cell->getCoordinate()), $newCoordinates . ':' . $newCoordinates );
  148.                 $pSheet->duplicateStyle( $pSheet->getDefaultStyle(), $cell->getCoordinate() . ':' . $cell->getCoordinate() );
  149.                     
  150.                 // Insert this cell at its new location
  151.                 if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
  152.                     // Formula should be adjusted
  153.                     $pSheet->setCellValue(
  154.                           $newCoordinates
  155.                         , $this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows)
  156.                     );
  157.                 } else {
  158.                     // Formula should not be adjusted
  159.                     $pSheet->setCellValue($newCoordinates, $cell->getValue());
  160.                 }
  161.                 
  162.                 // Clear the original cell
  163.                 $pSheet->setCellValue($cell->getCoordinate(), '');
  164.             }
  165.         }
  166.             
  167.             
  168.         // Duplicate styles for the newly inserted cells
  169.         $highestColumn     = $pSheet->getHighestColumn();
  170.         $highestRow     = $pSheet->getHighestRow();
  171.             
  172.         if ($pNumCols > 0 && PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 > 0) {
  173.             for ($i = $beforeRow; $i <= $highestRow - 1; $i++) {
  174.                 
  175.                 // Style
  176.                 $pSheet->duplicateStyle(
  177.                     $pSheet->getStyle(
  178.                         (PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 ) . $i)
  179.                     ),
  180.                     ($beforeColumn . $i) . ':' . (PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($beforeColumn) - 2 + $pNumCols ) . $i)
  181.                 );
  182.                 
  183.             }
  184.         }
  185.             
  186.         if ($pNumRows > 0 && $beforeRow - 1 > 0) {
  187.             for ($i = PHPExcel_Cell::columnIndexFromString($beforeColumn) - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; $i++) {
  188.                     
  189.                 // Style
  190.                 $pSheet->duplicateStyle(
  191.                     $pSheet->getStyle(
  192.                         (PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1))
  193.                     ),
  194.                     (PHPExcel_Cell::stringFromColumnIndex($i) . $beforeRow) . ':' . (PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1 + $pNumRows))
  195.                 );
  196.                 
  197.             }
  198.         }
  199.     
  200.             
  201.         // Update worksheet: column dimensions
  202.         $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true);
  203.         foreach ($aColumnDimensions as $objColumnDimension) {
  204.             $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows);
  205.             list($newReference) = PHPExcel_Cell::coordinateFromString($newReference);
  206.             if ($objColumnDimension->getColumnIndex() != $newReference) {
  207.                 $objColumnDimension->setColumnIndex($newReference);
  208.             }
  209.         }
  210.         $pSheet->refreshColumnDimensions();
  211.         
  212.         
  213.         // Update worksheet: row dimensions
  214.         $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);
  215.         foreach ($aRowDimensions as $objRowDimension) {
  216.             $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);
  217.             list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);
  218.             if ($objRowDimension->getRowIndex() != $newReference) {
  219.                 $objRowDimension->setRowIndex($newReference);
  220.             }
  221.         }
  222.         $pSheet->refreshRowDimensions();
  223.  
  224.         $copyDimension = $pSheet->getRowDimension($beforeRow - 1);
  225.         for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; $i++) {
  226.             $newDimension = $pSheet->getRowDimension($i);
  227.             $newDimension->setRowHeight($copyDimension->getRowHeight());
  228.             $newDimension->setVisible($copyDimension->getVisible());
  229.             $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
  230.             $newDimension->setCollapsed($copyDimension->getCollapsed());
  231.         }
  232.             
  233.             
  234.         // Update worksheet: breaks
  235.         $aBreaks = array_reverse($pSheet->getBreaks(), true);
  236.         foreach ($aBreaks as $key => $value) {
  237.             $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
  238.             if ($key != $newReference) {
  239.                 $pSheet->setBreak( $newReference, $value );
  240.                 $pSheet->setBreak( $key, PHPExcel_Worksheet::BREAK_NONE );
  241.             }
  242.         }
  243.             
  244.             
  245.         // Update worksheet: merge cells
  246.         $aMergeCells = array_reverse($pSheet->getMergeCells(), true);
  247.         foreach ($aMergeCells as $key => $value) {
  248.             $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
  249.             if ($key != $newReference) {
  250.                 $pSheet->mergeCells( $newReference );
  251.                 $pSheet->unmergeCells( $key );
  252.             }
  253.         }
  254.             
  255.             
  256.         // Update worksheet: protected cells
  257.         $aProtectedCells = array_reverse($pSheet->getProtectedCells(), true);
  258.         foreach ($aProtectedCells as $key => $value) {
  259.             $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
  260.             if ($key != $newReference) {
  261.                 $pSheet->protectCells( $newReference, $value, true );
  262.                 $pSheet->unprotectCells( $key );
  263.             }
  264.         }
  265.             
  266.             
  267.         // Update worksheet: autofilter
  268.         if ($pSheet->getAutoFilter() != '') {
  269.             $pSheet->setAutoFilter( $this->updateCellReference($pSheet->getAutoFilter(), $pBefore, $pNumCols, $pNumRows) );
  270.         }
  271.             
  272.         
  273.         // Update worksheet: freeze pane
  274.         if ($pSheet->getFreezePane() != '') {
  275.             $pSheet->setFreezePane( $this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows) );
  276.         }
  277.         
  278.  
  279.         // Page setup
  280.         if ($pSheet->getPageSetup()->isPrintAreaSet()) {
  281.             $pSheet->getPageSetup()->setPrintArea( $this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows) );
  282.         }
  283.         
  284.             
  285.         // Update worksheet: drawings
  286.         $aDrawings = $pSheet->getDrawingCollection();
  287.         foreach ($aDrawings as $objDrawing) {
  288.             $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
  289.             if ($objDrawing->getCoordinates() != $newReference) {
  290.                 $objDrawing->setCoordinates($newReference);
  291.             }
  292.         }
  293.                 
  294.             
  295.         // Update workbook: named ranges
  296.         if (count($pSheet->getParent()->getNamedRanges()) > 0) {
  297.             foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) {
  298.                 if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) {
  299.                     $namedRange->setRange(
  300.                         $this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)
  301.                     );
  302.                 }
  303.             }
  304.         }
  305.         
  306.         
  307.         // Garbage collect
  308.         $pSheet->garbageCollect();
  309.     }
  310.         
  311.     /**
  312.      * Update references within formulas
  313.      *
  314.      * @param     string    $pFormula    Formula to update
  315.      * @param     int        $pBefore    Insert before this one
  316.      * @param     int        $pNumCols    Number of columns to insert
  317.      * @param     int        $pNumRows    Number of rows to insert
  318.      * @return     string    Updated formula
  319.      * @throws     Exception
  320.      */
  321.     public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {    
  322.         // Formula stack
  323.         $executableFormulaArray = array();
  324.         
  325.         // Parse formula into a tree of tokens
  326.         $objParser = new PHPExcel_Calculation_FormulaParser($pFormula);
  327.         
  328.         // Loop trough parsed tokens and create an executable formula
  329.         $inFunction = false;
  330.         $token         = null;
  331.         for ($i = 0; $i < $objParser->getTokenCount(); $i++) {
  332.             $token = $objParser->getToken($i);
  333.  
  334.             // Is it a cell reference? Not a cell range?
  335.             if ( ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) &&
  336.                  ($token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE) ) {
  337.                      // New cell reference
  338.                      $newCellReference = $this->updateCellReference($token->getValue(), $pBefore, $pNumCols, $pNumRows);
  339.                      
  340.                      // Add adjusted cell coordinate to executable formula array
  341.                      array_push($executableFormulaArray, $newCellReference);
  342.                          
  343.                      continue;
  344.             }
  345.             
  346.             // Is it a subexpression?
  347.             if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) {
  348.                 // Temporary variable
  349.                 $tmp = '';
  350.                 switch($token->getTokenSubType()) {
  351.                     case PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START:
  352.                         $tmp = '(';
  353.                         break;
  354.                     case PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP:
  355.                         $tmp = ')';
  356.                         break;
  357.                 }
  358.                     
  359.                 // Add to executable formula array
  360.                 array_push($executableFormulaArray, $tmp);
  361.                          
  362.                 continue;
  363.             }
  364.                 
  365.             // Is it a function?
  366.             if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
  367.                 // Temporary variable
  368.                 $tmp = '';
  369.                     
  370.                 // Check the function type
  371.                 if ($token->getValue() == 'ARRAY' || $token->getValue() == 'ARRAYROW') {
  372.                     // An array or an array row...
  373.                     $tmp = '(';
  374.                 } else {
  375.                     // A regular function call...
  376.                     switch($token->getTokenSubType()) {
  377.                         case PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START:
  378.                             $tmp = strtoupper($token->getValue()) . '(';
  379.                             $inFunction = true;
  380.                             break;
  381.                         case PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP:
  382.                             $tmp = ')';
  383.                             break;
  384.                     }
  385.                 }
  386.                     
  387.                 // Add to executable formula array
  388.                 array_push($executableFormulaArray, $tmp);
  389.                      
  390.                 continue;
  391.             }
  392.                 
  393.             // Is it text?
  394.             if ( ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) &&
  395.                  ($token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT) ) {
  396.                      // Add to executable formula array
  397.                      array_push($executableFormulaArray, '"' . $token->getValue() . '"');
  398.                          
  399.                      continue;
  400.             }
  401.                 
  402.             // Is it something else?
  403.             array_push($executableFormulaArray, $token->getValue());
  404.         }
  405.         
  406.         // Return result
  407.         return '=' . implode(' ', $executableFormulaArray);
  408.     }
  409.     
  410.     /**
  411.      * Update cell reference
  412.      *
  413.      * @param     string    $pCellRange            Cell range
  414.      * @param     int        $pBefore            Insert before this one
  415.      * @param     int        $pNumCols            Number of columns to increment
  416.      * @param     int        $pNumRows            Number of rows to increment
  417.      * @return     string    Updated cell range
  418.      * @throws     Exception
  419.      */
  420.     public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
  421.         // Is it a range or a single cell?
  422.         if (strpos($pCellRange, ':') === false) {
  423.             // Single cell
  424.             return $this->_updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows);
  425.         } else {
  426.             // Range
  427.             return $this->_updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows);
  428.         }
  429.     }
  430.     
  431.     /**
  432.      * Update cell range
  433.      *
  434.      * @param     string    $pCellRange            Cell range
  435.      * @param     int        $pBefore            Insert before this one
  436.      * @param     int        $pNumCols            Number of columns to increment
  437.      * @param     int        $pNumRows            Number of rows to increment
  438.      * @return     string    Updated cell range
  439.      * @throws     Exception
  440.      */
  441.     private function _updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
  442.         if (eregi(':', $pCellRange)) {
  443.             // Range
  444.             $referenceA = '';
  445.             $referenceB = '';
  446.             list($referenceA, $referenceB) = PHPExcel_Cell::splitRange($pCellRange);
  447.                          
  448.             return $this->_updateSingleCellReference($referenceA, $pBefore, $pNumCols, $pNumRows) . ':' . $this->_updateSingleCellReference($referenceB, $pBefore, $pNumCols, $pNumRows);
  449.         } else {
  450.             throw new Exception("Only cell ranges may be passed to this method.");
  451.         }
  452.     }
  453.     
  454.     /**
  455.      * Update single cell reference
  456.      *
  457.      * @param     string    $pCellReference        Single cell reference
  458.      * @param     int        $pBefore            Insert before this one
  459.      * @param     int        $pNumCols            Number of columns to increment
  460.      * @param     int        $pNumRows            Number of rows to increment
  461.      * @return     string    Updated cell reference
  462.      * @throws     Exception
  463.      */
  464.     private function _updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) {
  465.         if (strpos($pCellReference, ':') === false) {
  466.             // Get coordinates of $pBefore
  467.             $beforeColumn     = 'A';
  468.             $beforeRow        = 1;
  469.             list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore );
  470.             
  471.             // Get coordinates
  472.             $newColumn     = 'A';
  473.             $newRow     = 1;
  474.             list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString( $pCellReference );
  475.             
  476.             // Verify which parts should be updated
  477.             $updateColumn = (PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn))
  478.                             && (strpos($newColumn, '$') === false)
  479.                             && (strpos($beforeColumn, '$') === false);
  480.             
  481.             $updateRow = ($newRow >= $beforeRow)
  482.                             && (strpos($newRow, '$') === false) 
  483.                             && (strpos($beforeRow, '$') === false);
  484.                 
  485.             // Create new column reference
  486.             if ($updateColumn) {
  487.                 $newColumn     = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols );
  488.             }
  489.                  
  490.             // Create new row reference
  491.             if ($updateRow) {
  492.                 $newRow     = $newRow + $pNumRows;
  493.             }
  494.                 
  495.             // Return new reference
  496.             return $newColumn . $newRow;
  497.         } else {
  498.             throw new Exception("Only single cell references may be passed to this method.");
  499.         }
  500.     }
  501.  
  502.     /**
  503.      * __clone implementation. Cloning should not be allowed in a Singleton!
  504.      *
  505.      * @throws    Exception
  506.      */
  507.     public final function __clone() {
  508.         throw new Exception("Cloning a Singleton is not allowed!");
  509.     }
  510. }

Documentation generated on Mon, 25 Aug 2008 13:48:18 +0200 by phpDocumentor 1.4.1