Source for file Worksheet.php
Documentation is available at Worksheet.php
* Copyright (c) 2006 - 2011 PHPExcel
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* @package PHPExcel_Worksheet
* @copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 1.7.6, 2011-02-27
* @package PHPExcel_Worksheet
* @copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
const SHEETSTATE_VISIBLE = 'visible';
const SHEETSTATE_HIDDEN = 'hidden';
const SHEETSTATE_VERYHIDDEN = 'veryHidden';
* Invalid characters in sheet title
private static $_invalidCharacters = array('*', ':', '/', '\\', '?', '[', ']');
* Cacheable collection of cells
* @var PHPExcel_CachedObjectStorage_xxx
private $_cellCollection = null;
* Collection of row dimensions
* @var PHPExcel_Worksheet_RowDimension[]
private $_rowDimensions = array();
* @var PHPExcel_Worksheet_RowDimension
private $_defaultRowDimension = null;
* Collection of column dimensions
* @var PHPExcel_Worksheet_ColumnDimension[]
private $_columnDimensions = array();
* Default column dimension
* @var PHPExcel_Worksheet_ColumnDimension
private $_defaultColumnDimension = null;
* @var PHPExcel_Worksheet_BaseDrawing[]
private $_drawingCollection = null;
* @var PHPExcel_Worksheet_PageSetup
* @var PHPExcel_Worksheet_PageMargins
* @var PHPExcel_Worksheet_HeaderFooter
* @var PHPExcel_Worksheet_SheetView
* @var PHPExcel_Worksheet_Protection
private $_styles = array();
* Conditional styles. Indexed by cell coordinate, e.g. 'A1'
private $_conditionalStylesCollection = array();
* Is the current cell collection sorted already?
private $_cellCollectionIsSorted = false;
private $_breaks = array();
* Collection of merged cell ranges
private $_mergeCells = array();
* Collection of protected cell ranges
private $_protectedCells = array();
private $_autoFilter = '';
private $_freezePane = '';
private $_showGridlines = true;
private $_printGridlines = false;
* Show row and column headers?
private $_showRowColHeaders = true;
* Show summary below? (Row/Column outline)
private $_showSummaryBelow = true;
* Show summary right? (Row/Column outline)
private $_showSummaryRight = true;
* @var PHPExcel_Comment[]
private $_comments = array();
* Active cell. (Only one!)
private $_activeCell = 'A1';
private $_selectedCells = 'A1';
private $_cachedHighestColumn = 'A';
private $_cachedHighestRow = 1;
private $_rightToLeft = false;
* Hyperlinks. Indexed by cell coordinate, e.g. 'A1'
private $_hyperlinkCollection = array();
* Data validation objects. Indexed by cell coordinate, e.g. 'A1'
private $_dataValidationCollection = array();
* @var PHPExcel_Style_Color
* @param PHPExcel $pParent
public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet')
$this->_parent = $pParent;
// Set page header/footer
$this->_drawingCollection = new ArrayObject();
// Default column dimension
$this->_cellCollection->unsetWorksheetCells();
$this->_cellCollection = null;
// detach ourself from the workbook, so that it can then delete this worksheet successfully
* Return the cache controller for the cell collection
* @return PHPExcel_CachedObjectStorage_xxx
return $this->_cellCollection;
} // function getCellCacheController()
* Get array of invalid characters for sheet title
return self::$_invalidCharacters;
* Check sheet title for valid Excel syntax
* @param string $pValue The string to check
* @return string The valid string
private static function _checkSheetTitle($pValue)
// Some of the printable ASCII characters are invalid: * : / \ ? [ ]
if (str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) {
throw new Exception('Invalid character found in sheet title');
// Maximum 31 characters allowed for sheet title
throw new Exception('Maximum 31 characters allowed in sheet title.');
* Get collection of cells
* @param boolean $pSorted Also sort the cell collection?
* @return PHPExcel_Cell[]
// Re-order cell collection
if (!is_null($this->_cellCollection)) {
return $this->_cellCollection->getCellList();
* Sort collection of cells
* @return PHPExcel_Worksheet
if (!is_null($this->_cellCollection)) {
return $this->_cellCollection->getSortedCellList();
* Get collection of row dimensions
* @return PHPExcel_Worksheet_RowDimension[]
return $this->_rowDimensions;
* Get default row dimension
* @return PHPExcel_Worksheet_RowDimension
return $this->_defaultRowDimension;
* Get collection of column dimensions
* @return PHPExcel_Worksheet_ColumnDimension[]
return $this->_columnDimensions;
* Get default column dimension
* @return PHPExcel_Worksheet_ColumnDimension
return $this->_defaultColumnDimension;
* Get collection of drawings
* @return PHPExcel_Worksheet_BaseDrawing[]
return $this->_drawingCollection;
* Refresh column dimensions
* @return PHPExcel_Worksheet
$newColumnDimensions = array();
foreach ($currentColumnDimensions as $objColumnDimension) {
$newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
$this->_columnDimensions = $newColumnDimensions;
* @return PHPExcel_Worksheet
$newRowDimensions = array();
foreach ($currentRowDimensions as $objRowDimension) {
$newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
$this->_rowDimensions = $newRowDimensions;
* Calculate worksheet dimension
* @return string String containing the dimension of this worksheet
* Calculate widths for auto-size columns
* @param boolean $calculateMergeCells Calculate merge cell width
* @return PHPExcel_Worksheet;
// initialize $autoSizes array
if ($colDimension->getAutoSize()) {
$autoSizes[$colDimension->getColumnIndex()] = - 1;
// There is only something to do if there are some auto-size columns
if (!empty($autoSizes)) {
// build list of cells references that participate in a merge
$isMergeCell[$cellReference] = true;
// loop through all cells in the worksheet
if (isset ($autoSizes[$cell->getColumn()])) {
// Determine width if cell does not participate in a merge
if (!isset ($isMergeCell[$cell->getCoordinate()])) {
$cellValue = $cell->getCalculatedValue();
$autoSizes[$cell->getColumn()] = max(
(float) $autoSizes[$cell->getColumn()],
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
foreach ($autoSizes as $columnIndex => $width) {
* @param PHPExcel $parent
* @return PHPExcel_Worksheet
$namedRanges = $this->_parent->getNamedRanges();
foreach ($namedRanges as $namedRange) {
$parent->addNamedRange($namedRange);
$this->_parent->removeSheetByIndex(
$this->_parent->getIndex($this)
$this->_parent = $parent;
* @param string $pValue String containing the dimension of this worksheet
* @return PHPExcel_Worksheet
public function setTitle($pValue = 'Worksheet')
// Is this a 'rename' or not?
self::_checkSheetTitle($pValue);
// Is there already such sheet name?
if ($this->getParent()->getSheetByName($pValue)) {
// Use name, but append with lowest possible integer
while ($this->getParent()->getSheetByName($pValue . ' ' . $i)) {
$altTitle = $pValue . ' ' . $i;
* @return string Sheet state (visible, hidden, veryHidden)
return $this->_sheetState;
* @param string $value Sheet state (visible, hidden, veryHidden)
* @return PHPExcel_Worksheet
public function setSheetState($value = PHPExcel_Worksheet::SHEETSTATE_VISIBLE) {
$this->_sheetState = $value;
* @return PHPExcel_Worksheet_PageSetup
return $this->_pageSetup;
* @param PHPExcel_Worksheet_PageSetup $pValue
* @return PHPExcel_Worksheet
public function setPageSetup(PHPExcel_Worksheet_PageSetup $pValue)
$this->_pageSetup = $pValue;
* @return PHPExcel_Worksheet_PageMargins
return $this->_pageMargins;
* @param PHPExcel_Worksheet_PageMargins $pValue
* @return PHPExcel_Worksheet
public function setPageMargins(PHPExcel_Worksheet_PageMargins $pValue)
$this->_pageMargins = $pValue;
* @return PHPExcel_Worksheet_HeaderFooter
return $this->_headerFooter;
* @param PHPExcel_Worksheet_HeaderFooter $pValue
* @return PHPExcel_Worksheet
$this->_headerFooter = $pValue;
* @return PHPExcel_Worksheet_HeaderFooter
return $this->_sheetView;
* @param PHPExcel_Worksheet_SheetView $pValue
* @return PHPExcel_Worksheet
public function setSheetView(PHPExcel_Worksheet_SheetView $pValue)
$this->_sheetView = $pValue;
* @return PHPExcel_Worksheet_Protection
return $this->_protection;
* @param PHPExcel_Worksheet_Protection $pValue
* @return PHPExcel_Worksheet
public function setProtection(PHPExcel_Worksheet_Protection $pValue)
$this->_protection = $pValue;
* Get highest worksheet column
* @return string Highest column name
return $this->_cachedHighestColumn;
* Get highest worksheet row
* @return int Highest row number
return $this->_cachedHighestRow;
* @param string $pCoordinate Coordinate of the cell
* @param mixed $pValue Value of the cell
* @param bool $returnCell Return the worksheet (false, default) or the cell (true)
* @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified
public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell = false)
$cell = $this->getCell($pCoordinate);
$cell->setValue($pValue);
* Set a cell value by using numeric cell coordinates
* @param string $pColumn Numeric column coordinate of the cell
* @param string $pRow Numeric row coordinate of the cell
* @param mixed $pValue Value of the cell
* @param bool $returnCell Return the worksheet (false, default) or the cell (true)
* @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified
$cell->setValue($pValue);
* @param string $pCoordinate Coordinate of the cell
* @param mixed $pValue Value of the cell
* @param string $pDataType Explicit data type
* @return PHPExcel_Worksheet
public function setCellValueExplicit($pCoordinate = 'A1', $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
$this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
* Set a cell value by using numeric cell coordinates
* @param string $pColumn Numeric column coordinate of the cell
* @param string $pRow Numeric row coordinate of the cell
* @param mixed $pValue Value of the cell
* @param string $pDataType Explicit data type
* @return PHPExcel_Worksheet
* Get cell at a specific coordinate
* @param string $pCoordinate Coordinate of the cell
* @return PHPExcel_Cell Cell that was found
public function getCell($pCoordinate = 'A1')
if ($this->_cellCollection->isDataSet($pCoordinate)) {
return $this->_cellCollection->getCacheData($pCoordinate);
if (strpos($pCoordinate, '!') !== false) {
return $this->getParent()->getSheetByName($worksheetReference[0])->getCell($worksheetReference[1]);
$pCoordinate = $namedRange->getRange();
return $namedRange->getWorksheet()->getCell($pCoordinate);
if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
throw new Exception('Cell coordinate can not be a range of cells.');
} elseif (strpos($pCoordinate,'$') !== false) {
throw new Exception('Cell coordinate must not be absolute.');
// Create new cell object
$this->_cellCollectionIsSorted = false;
$this->_cachedHighestColumn = $aCoordinates[0];
$this->_cachedHighestRow = max($this->_cachedHighestRow,$aCoordinates[1]);
// Cell needs appropriate xfIndex
if ( isset ($rowDimensions[$aCoordinates[1]]) && $rowDimensions[$aCoordinates[1]]->getXfIndex() !== null ) {
// then there is a row dimension with explicit style, assign it to the cell
$cell->setXfIndex($rowDimensions[$aCoordinates[1]]->getXfIndex());
} else if ( isset ($columnDimensions[$aCoordinates[0]]) ) {
// then there is a column dimension, assign it to the cell
$cell->setXfIndex($columnDimensions[$aCoordinates[0]]->getXfIndex());
* Get cell at a specific coordinate by using numeric cell coordinates
* @param string $pColumn Numeric column coordinate of the cell
* @param string $pRow Numeric row coordinate of the cell
* @return PHPExcel_Cell Cell that was found
$coordinate = $columnLetter . $pRow;
if (!$this->_cellCollection->isDataSet($coordinate)) {
$this->_cellCollectionIsSorted = false;
$this->_cachedHighestColumn = $columnLetter;
$this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow);
return $this->_cellCollection->getCacheData($coordinate);
* Cell at a specific coordinate exists?
* @param string $pCoordinate Coordinate of the cell
if (strpos($pCoordinate, '!') !== false) {
return $this->getParent()->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]);
$pCoordinate = $namedRange->getRange();
if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {
if (!$namedRange->getLocalOnly()) {
return $namedRange->getWorksheet()->cellExists($pCoordinate);
throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());
if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
throw new Exception('Cell coordinate can not be a range of cells.');
} elseif (strpos($pCoordinate,'$') !== false) {
throw new Exception('Cell coordinate must not be absolute.');
return $this->_cellCollection->isDataSet($pCoordinate);
* Cell at a specific coordinate by using numeric cell coordinates exists?
* @param string $pColumn Numeric column coordinate of the cell
* @param string $pRow Numeric row coordinate of the cell
* Get row dimension at a specific row
* @param int $pRow Numeric index of the row
* @return PHPExcel_Worksheet_RowDimension
if (!isset ($this->_rowDimensions[$pRow])) {
$this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow);
return $this->_rowDimensions[$pRow];
* Get column dimension at a specific column
* @param string $pColumn String index of the column
* @return PHPExcel_Worksheet_ColumnDimension
if (!isset ($this->_columnDimensions[$pColumn])) {
$this->_cachedHighestColumn = $pColumn;
return $this->_columnDimensions[$pColumn];
* Get column dimension at a specific column by using numeric cell coordinates
* @param string $pColumn Numeric column coordinate of the cell
* @param string $pRow Numeric row coordinate of the cell
* @return PHPExcel_Worksheet_ColumnDimension
* @return PHPExcel_Style[]
* Get default style of workbork.
return $this->_parent->getDefaultStyle();
* Set default style - should only be used by PHPExcel_IReader implementations!
* @param PHPExcel_Style $value
* @return PHPExcel_Worksheet
$this->_parent->getDefaultStyle()->applyFromArray(array(
'name' => $pValue->getFont()->getName(),
'size' => $pValue->getFont()->getSize(),
* @param string $pCellCoordinate Cell coordinate to get style for
public function getStyle($pCellCoordinate = 'A1')
// set this sheet as active
$this->_parent->setActiveSheetIndex($this->_parent->getIndex($this));
// set cell coordinate as active
return $this->_parent->getCellXfSupervisor();
* Get conditional styles for a cell
* @param string $pCoordinate
* @return PHPExcel_Style_Conditional[]
if (!isset ($this->_conditionalStylesCollection[$pCoordinate])) {
$this->_conditionalStylesCollection[$pCoordinate] = array();
return $this->_conditionalStylesCollection[$pCoordinate];
* Do conditional styles exist for this cell?
* @param string $pCoordinate
if (isset ($this->_conditionalStylesCollection[$pCoordinate])) {
* Removes conditional styles for a cell
* @param string $pCoordinate
* @return PHPExcel_Worksheet
unset ($this->_conditionalStylesCollection[$pCoordinate]);
* Get collection of conditional styles
return $this->_conditionalStylesCollection;
* @param $pCoordinate string E.g. 'A1'
* @param $pValue PHPExcel_Style_Conditional[]
* @return PHPExcel_Worksheet
$this->_conditionalStylesCollection[$pCoordinate] = $pValue;
* Get style for cell by using numeric cell coordinates
* @param int $pColumn Numeric column coordinate of the cell
* @param int $pRow Numeric row coordinate of the cell
* Set shared cell style to a range of cells
* Please note that this will overwrite existing cell styles for cells in range!
* @param PHPExcel_Style $pSharedCellStyle Cell style to share
* @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @return PHPExcel_Worksheet
public function setSharedStyle(PHPExcel_Style $pSharedCellStyle = null, $pRange = '')
* Duplicate cell style to a range of cells
* Please note that this will overwrite existing cell styles for cells in range!
* @param PHPExcel_Style $pCellStyle Cell style to duplicate
* @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @return PHPExcel_Worksheet
public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '')
// make sure we have a real style and not supervisor
$style = $pCellStyle->getIsSupervisor() ? $pCellStyle->getSharedComponent() : $pCellStyle;
// Add the style to the workbook if necessary
$workbook = $this->_parent;
if ($existingStyle = $this->_parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
// there is already such cell Xf in our collection
$xfIndex = $existingStyle->getIndex();
// we don't have such a cell Xf, need to add
$workbook->addCellXf($pCellStyle);
$xfIndex = $pCellStyle->getIndex();
// Is it a cell range or a single cell?
if (strpos($pRange, ':') === false) {
list ($rangeA, $rangeB) = explode(':', $pRange);
// Calculate range outer borders
// Translate column into index
// Make sure we can loop upwards on rows and columns
if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
// Loop through cells and apply styles
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++ $col) {
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++ $row) {
* Duplicate cell style array to a range of cells
* Please note that this will overwrite existing cell styles for cells in range,
* if they are in the styles array. For example, if you decide to set a range of
* cells to font bold, only include font bold in the styles array.
* @param array $pStyles Array containing style information
* @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @param boolean $pAdvanced Advanced mode for setting borders.
* @return PHPExcel_Worksheet
$this->getStyle($pRange)->applyFromArray($pStyles, $pAdvanced);
* @param string $pCell Cell coordinate (e.g. A1)
* @param int $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*)
* @return PHPExcel_Worksheet
public function setBreak($pCell = 'A1', $pBreak = PHPExcel_Worksheet::BREAK_NONE)
$this->_breaks[$pCell] = $pBreak;
throw new Exception('No cell coordinate specified.');
* Set break on a cell by using numeric cell coordinates
* @param integer $pColumn Numeric column coordinate of the cell
* @param integer $pRow Numeric row coordinate of the cell
* @param integer $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*)
* @return PHPExcel_Worksheet
* Set merge on a cell range
* @param string $pRange Cell range (e.g. A1:E1)
* @return PHPExcel_Worksheet
if (strpos($pRange,':') !== false) {
$this->_mergeCells[$pRange] = $pRange;
// make sure cells are created
// get the cells in the range
// create upper left cell if it does not already exist
$upperLeft = $aReferences[0];
// create or blank out the rest of the cells in the range
$count = count($aReferences);
for ($i = 1; $i < $count; $i++ ) {
throw new Exception('Merge must be set on a range of cells.');
* Set merge on a cell range by using numeric cell coordinates
* @param int $pColumn1 Numeric column coordinate of the first cell
* @param int $pRow1 Numeric row coordinate of the first cell
* @param int $pColumn2 Numeric column coordinate of the last cell
* @param int $pRow2 Numeric row coordinate of the last cell
* @return PHPExcel_Worksheet
* Remove merge on a cell range
* @param string $pRange Cell range (e.g. A1:E1)
* @return PHPExcel_Worksheet
if (strpos($pRange,':') !== false) {
if (isset ($this->_mergeCells[$pRange])) {
unset ($this->_mergeCells[$pRange]);
throw new Exception('Cell range ' . $pRange . ' not known as merged.');
throw new Exception('Merge can only be removed from a range of cells.');
* Remove merge on a cell range by using numeric cell coordinates
* @param int $pColumn1 Numeric column coordinate of the first cell
* @param int $pRow1 Numeric row coordinate of the first cell
* @param int $pColumn2 Numeric column coordinate of the last cell
* @param int $pRow2 Numeric row coordinate of the last cell
* @return PHPExcel_Worksheet
return $this->_mergeCells;
* Set merge cells array for the entire sheet. Use instead mergeCells() to merge
$this->_mergeCells = $pValue;
* Set protection on a cell range
* @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
* @param string $pPassword Password to unlock the protection
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @return PHPExcel_Worksheet
public function protectCells($pRange = 'A1', $pPassword = '', $pAlreadyHashed = false)
$this->_protectedCells[$pRange] = $pPassword;
* Set protection on a cell range by using numeric cell coordinates
* @param int $pColumn1 Numeric column coordinate of the first cell
* @param int $pRow1 Numeric row coordinate of the first cell
* @param int $pColumn2 Numeric column coordinate of the last cell
* @param int $pRow2 Numeric row coordinate of the last cell
* @param string $pPassword Password to unlock the protection
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @return PHPExcel_Worksheet
public function protectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false)
return $this->protectCells($cellRange, $pPassword, $pAlreadyHashed);
* Remove protection on a cell range
* @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
* @return PHPExcel_Worksheet
if (isset ($this->_protectedCells[$pRange])) {
unset ($this->_protectedCells[$pRange]);
throw new Exception('Cell range ' . $pRange . ' not known as protected.');
* Remove protection on a cell range by using numeric cell coordinates
* @param int $pColumn1 Numeric column coordinate of the first cell
* @param int $pRow1 Numeric row coordinate of the first cell
* @param int $pColumn2 Numeric column coordinate of the last cell
* @param int $pRow2 Numeric row coordinate of the last cell
* @param string $pPassword Password to unlock the protection
* @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @return PHPExcel_Worksheet
public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false)
return $this->unprotectCells($cellRange, $pPassword, $pAlreadyHashed);
return $this->_protectedCells;
return $this->_autoFilter;
* @param string $pRange Cell range (i.e. A1:E10)
* @return PHPExcel_Worksheet
if (strpos($pRange,':') !== false) {
$this->_autoFilter = $pRange;
throw new Exception('Autofilter must be set on a range of cells.');
* Set Autofilter Range by using numeric cell coordinates
* @param int $pColumn1 Numeric column coordinate of the first cell
* @param int $pRow1 Numeric row coordinate of the first cell
* @param int $pColumn2 Numeric column coordinate of the second cell
* @param int $pRow2 Numeric row coordinate of the second cell
* @return PHPExcel_Worksheet
* @return PHPExcel_Worksheet
return $this->_freezePane;
* @param string $pCell Cell (i.e. A1)
* @return PHPExcel_Worksheet
if (strpos($pCell,':') === false && strpos($pCell,',') === false) {
$this->_freezePane = $pCell;
throw new Exception('Freeze pane can not be set on a range of cells.');
* Freeze Pane by using numeric cell coordinates
* @param int $pColumn Numeric column coordinate of the cell
* @param int $pRow Numeric row coordinate of the cell
* @return PHPExcel_Worksheet
* @return PHPExcel_Worksheet
* Insert a new row, updating all possible related data
* @param int $pBefore Insert before this one
* @param int $pNumRows Number of rows to insert
* @return PHPExcel_Worksheet
$objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
throw new Exception("Rows can only be inserted before at least row 1.");
* Insert a new column, updating all possible related data
* @param int $pBefore Insert before this one
* @param int $pNumCols Number of columns to insert
* @return PHPExcel_Worksheet
$objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
throw new Exception("Column references should not be numeric.");
* Insert a new column, updating all possible related data
* @param int $pBefore Insert before this one (numeric column coordinate of the cell)
* @param int $pNumCols Number of columns to insert
* @return PHPExcel_Worksheet
throw new Exception("Columns can only be inserted before at least column A (0).");
* Delete a row, updating all possible related data
* @param int $pRow Remove starting with this one
* @param int $pNumRows Number of rows to remove
* @return PHPExcel_Worksheet
public function removeRow($pRow = 1, $pNumRows = 1) {
$objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, - $pNumRows, $this);
throw new Exception("Rows to be deleted should at least start from row 1.");
* Remove a column, updating all possible related data
* @param int $pColumn Remove starting with this one
* @param int $pNumCols Number of columns to remove
* @return PHPExcel_Worksheet
public function removeColumn($pColumn = 'A', $pNumCols = 1) {
$objReferenceHelper->insertNewBefore($pColumn . '1', - $pNumCols, 0, $this);
throw new Exception("Column references should not be numeric.");
* Remove a column, updating all possible related data
* @param int $pColumn Remove starting with this one (numeric column coordinate of the cell)
* @param int $pNumCols Number of columns to remove
* @return PHPExcel_Worksheet
throw new Exception("Columns to be deleted should at least start from column 0");
return $this->_showGridlines;
* @param boolean $pValue Show gridlines (true/false)
* @return PHPExcel_Worksheet
$this->_showGridlines = $pValue;
return $this->_printGridlines;
* @param boolean $pValue Print gridlines (true/false)
* @return PHPExcel_Worksheet
$this->_printGridlines = $pValue;
* Show row and column headers?
return $this->_showRowColHeaders;
* Set show row and column headers
* @param boolean $pValue Show row and column headers (true/false)
* @return PHPExcel_Worksheet
$this->_showRowColHeaders = $pValue;
* Show summary below? (Row/Column outlining)
return $this->_showSummaryBelow;
* @param boolean $pValue Show summary below (true/false)
* @return PHPExcel_Worksheet
$this->_showSummaryBelow = $pValue;
* Show summary right? (Row/Column outlining)
return $this->_showSummaryRight;
* @param boolean $pValue Show summary right (true/false)
* @return PHPExcel_Worksheet
$this->_showSummaryRight = $pValue;
* @return PHPExcel_Comment[]
* Set comments array for the entire sheet.
* @param array of PHPExcel_Comment
* @return PHPExcel_Worksheet
$this->_comments = $pValue;
* @param string $pCellCoordinate Cell coordinate to get comment for
* @return PHPExcel_Comment
public function getComment($pCellCoordinate = 'A1')
if (strpos($pCellCoordinate,':') !== false || strpos($pCellCoordinate,',') !== false) {
throw new Exception('Cell coordinate string can not be a range of cells.');
} else if (strpos($pCellCoordinate,'$') !== false) {
throw new Exception('Cell coordinate string must not be absolute.');
} else if ($pCellCoordinate == '') {
throw new Exception('Cell coordinate can not be zero-length string.');
// Check if we already have a comment for this cell.
// If not, create a new comment.
if (isset ($this->_comments[$pCellCoordinate])) {
return $this->_comments[$pCellCoordinate];
$this->_comments[$pCellCoordinate] = $newComment;
* Get comment for cell by using numeric cell coordinates
* @param int $pColumn Numeric column coordinate of the cell
* @param int $pRow Numeric row coordinate of the cell
* @return PHPExcel_Comment
* @return string Example: 'A1'
return $this->_activeCell;
return $this->_selectedCells;
* @param string $pCell Cell (i.e. A1)
* @return PHPExcel_Worksheet
* Select a range of cells.
* @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
* @return PHPExcel_Worksheet
$pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate);
$pCoordinate = preg_replace('/^([0-9]+)$/', '${1}:${1}', $pCoordinate);
// Convert 'A:C' to 'A1:C1048576'
$pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate);
// Convert '1:3' to 'A1:XFD3'
$pCoordinate = preg_replace('/^([0-9]+):([0-9]+)$/', 'A${1}:XFD${2}', $pCoordinate);
if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
$this->_activeCell = $first[0];
$this->_activeCell = $pCoordinate;
$this->_selectedCells = $pCoordinate;
* Selected cell by using numeric cell coordinates
* @param int $pColumn Numeric column coordinate of the cell
* @param int $pRow Numeric row coordinate of the cell
* @return PHPExcel_Worksheet
return $this->_rightToLeft;
* @param boolean $value Right-to-left true/false
* @return PHPExcel_Worksheet
$this->_rightToLeft = $value;
* Fill worksheet from values in array
* @param array $source Source array
* @param mixed $nullValue Value in source array that stands for blank cell
* @param string $startCell Insert array starting from this cell address as the top left coordinate
* @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array
* @return PHPExcel_Worksheet
public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) {
// Convert a 1-D array to 2-D (for ease of looping)
$source = array($source);
foreach ($source as $rowData) {
$currentColumn = $startColumn;
foreach($rowData as $cellValue) {
if ($strictNullComparison) {
if ($cellValue !== $nullValue) {
$this->getCell($currentColumn . $startRow)->setValue($cellValue);
if ($cellValue != $nullValue) {
$this->getCell($currentColumn . $startRow)->setValue($cellValue);
throw new Exception("Parameter \$source should be an array.");
* Create array from a range of cells
* @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param boolean $calculateFormulas Should formulas be calculated?
* @param boolean $formatData Should formatting be applied to cell values?
* @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Identify the range that we need to extract from the worksheet
$minRow = $rangeStart[1];
for ($row = $minRow; $row <= $maxRow; ++ $row) {
// Loop through columns in the current row
for ($col = $minCol; $col != $maxCol; ++ $col) {
$rRef = ($returnCellRef) ? $row : $row- 1;
$cRef = ($returnCellRef) ? $col : ++ $c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
// so we test and retrieve directly against _cellCollection
if ($this->_cellCollection->isDataSet($col. $row)) {
$cell = $this->_cellCollection->getCacheData($col. $row);
if ($cell->getValue() !== null) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
if ($calculateFormulas) {
$returnValue[$rRef][$cRef] = $cell->getCalculatedValue();
$returnValue[$rRef][$cRef] = $cell->getValue();
$style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = $nullValue;
$returnValue[$rRef][$cRef] = $nullValue;
* Create array from a range of cells
* @param string $pNamedRange Name of the Named Range
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param boolean $calculateFormulas Should formulas be calculated?
* @param boolean $formatData Should formatting be applied to cell values?
* @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
$pWorkSheet = $namedRange->getWorksheet();
$pCellRange = $namedRange->getRange();
return $pWorkSheet->rangeToArray( $pCellRange,
$nullValue, $calculateFormulas, $formatData, $returnCellRef);
throw new Exception('Named Range '. $pNamedRange. ' does not exist.');
* Create array from worksheet
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param boolean $calculateFormulas Should formulas be calculated?
* @param boolean $formatData Should formatting be applied to cell values?
* @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Identify the range that we need to extract from the worksheet
$nullValue, $calculateFormulas, $formatData, $returnCellRef);
* @return PHPExcel_Worksheet_RowIterator
* Run PHPExcel garabage collector.
* @return PHPExcel_Worksheet
// Build a reference table from images
// $imageCoordinates = array();
// $iterator = $this->getDrawingCollection()->getIterator();
// while ($iterator->valid()) {
// $imageCoordinates[$iterator->current()->getCoordinates()] = true;
// Lookup highest column and highest row if cells are cleaned
// Find cells that can be cleaned
foreach ($this->_cellCollection->getCellList() as $coord) {
list ($c,$r) = sscanf($coord,'%[A-Z]%d');
// Determine highest column and row
// Loop through column dimensions
foreach ($this->_columnDimensions as $dimension) {
// Loop through row dimensions
foreach ($this->_rowDimensions as $dimension) {
$highestRow = max($highestRow,$dimension->getRowIndex());
if ($highestColumn < 0) {
$this->_cachedHighestColumn = 'A';
$this->_cachedHighestRow = $highestRow;
* @return string Hash code
$this->_hash = md5( $this->_title .
* Extract worksheet title from range.
* Example: extractSheetTitle("testSheet!A1") ==> 'A1'
* Example: extractSheetTitle("'testSheet 1'!A1", true) ==> array('testSheet 1', 'A1');
* @param string $pRange Range to extract title from
* @param bool $returnRange Return range? (see example)
if (($sep = strpos($pRange, '!')) === false) {
return substr($pRange, $sep + 1);
* @param string $pCellCoordinate Cell coordinate to get hyperlink for
// return hyperlink if we already have one
if (isset ($this->_hyperlinkCollection[$pCellCoordinate])) {
return $this->_hyperlinkCollection[$pCellCoordinate];
return $this->_hyperlinkCollection[$pCellCoordinate];
* @param string $pCellCoordinate Cell coordinate to insert hyperlink
* @param PHPExcel_Cell_Hyperlink $pHyperlink
* @return PHPExcel_Worksheet
public function setHyperlink($pCellCoordinate = 'A1', PHPExcel_Cell_Hyperlink $pHyperlink = null)
if ($pHyperlink === null) {
unset ($this->_hyperlinkCollection[$pCellCoordinate]);
$this->_hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
* Hyperlink at a specific coordinate exists?
* @param string $pCellCoordinate
return isset ($this->_hyperlinkCollection[$pCoordinate]);
* Get collection of hyperlinks
* @return PHPExcel_Cell_Hyperlink[]
return $this->_hyperlinkCollection;
* @param string $pCellCoordinate Cell coordinate to get data validation for
// return data validation if we already have one
if (isset ($this->_dataValidationCollection[$pCellCoordinate])) {
return $this->_dataValidationCollection[$pCellCoordinate];
// else create data validation
return $this->_dataValidationCollection[$pCellCoordinate];
* @param string $pCellCoordinate Cell coordinate to insert data validation
* @param PHPExcel_Cell_DataValidation $pDataValidation
* @return PHPExcel_Worksheet
public function setDataValidation($pCellCoordinate = 'A1', PHPExcel_Cell_DataValidation $pDataValidation = null)
if ($pDataValidation === null) {
unset ($this->_dataValidationCollection[$pCellCoordinate]);
$this->_dataValidationCollection[$pCellCoordinate] = $pDataValidation;
* Data validation at a specific coordinate exists?
* @param string $pCellCoordinate
return isset ($this->_dataValidationCollection[$pCoordinate]);
* Get collection of data validations
* @return PHPExcel_Cell_DataValidation[]
return $this->_dataValidationCollection;
* Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet
* @return string Adjusted range value
$rangeBlocks = explode(' ',$range);
foreach ($rangeBlocks as &$rangeSet) {
if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; }
if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; }
$rangeSet = $rangeBoundaries[0][0]. $rangeBoundaries[0][1]. ':'. $rangeBoundaries[1][0]. $rangeBoundaries[1][1];
$stRange = implode(' ',$rangeBlocks);
* @return PHPExcel_Style_Color
* @return PHPExcel_Worksheet
* Copy worksheet (!= clone!)
* @return PHPExcel_Worksheet
* Implement PHP __clone to create a deep clone, not just a shallow copy.
foreach ($this as $key => $val) {
if ($key == '_cellCollection') {
$newCollection = clone $this->_cellCollection;
$newCollection->copyCellCollection($this);
$this->_cellCollection = $newCollection;
} elseif ($key == '_drawingCollection') {
$newCollection = clone $this->_drawingCollection;
$this->_drawingCollection = $newCollection;
|