Source for file Gnumeric.php
Documentation is available at Gnumeric.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_Reader
* @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
/** PHPExcel root directory */
define('PHPEXCEL_ROOT', dirname(__FILE__ ) . '/../../');
require (PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
* PHPExcel_Reader_Gnumeric
* @package PHPExcel_Reader
* @copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
* Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
* or whether it should read both data and formatting
private $_readDataOnly = false;
* Restrict which sheets should be loaded?
* This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
private $_loadSheetsOnly = null;
private $_styles = array();
private $_expressions = array();
private $_referenceHelper = null;
* PHPExcel_Reader_IReadFilter instance
* @var PHPExcel_Reader_IReadFilter
private $_readFilter = null;
* If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
* If false (the default) it will read data and formatting.
return $this->_readDataOnly;
* Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
* Set to false (the default) to advise the Reader to read both data and formatting for cells.
* @return PHPExcel_Reader_Gnumeric
$this->_readDataOnly = $pValue;
* Get which sheets to load
* Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
* indicating that all worksheets in the workbook should be loaded.
return $this->_loadSheetsOnly;
* Set which sheets to load
* This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
* If NULL, then it tells the Reader to read all worksheets in the workbook
* @return PHPExcel_Reader_Gnumeric
$this->_loadSheetsOnly = is_array($value) ?
* Tells the Reader to load all worksheets from the workbook.
* @return PHPExcel_Reader_Gnumeric
$this->_loadSheetsOnly = null;
* @return PHPExcel_Reader_IReadFilter
return $this->_readFilter;
* @param PHPExcel_Reader_IReadFilter $pValue
* @return PHPExcel_Reader_Gnumeric
public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
$this->_readFilter = $pValue;
* Create a new PHPExcel_Reader_Gnumeric
* Can the current PHPExcel_Reader_IReader read the file?
* @param string $pFileName
public function canRead($pFilename)
// Check if gzlib functions are available
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
// Read signature data (first 3 bytes)
$fh = fopen($pFilename, 'r');
if ($data != chr(0x1F). chr(0x8B)) {
* Loads PHPExcel from file
* @param string $pFilename
public function load($pFilename)
// Load into this instance
private function _gzfileGetContents($filename) {
$file = @gzopen($filename, 'rb');
* Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
* @param string $pFilename
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
$gFileData = $this->_gzfileGetContents($pFilename);
$namespacesMeta = $xml->getNamespaces(true);
$gnmXML = $xml->children($namespacesMeta['gnm']);
$worksheetNames = array();
foreach($gnmXML->Sheets->Sheet as $sheet) {
$worksheetNames[] = (string) $sheet->Name;
* Loads PHPExcel from file into PHPExcel instance
* @param string $pFilename
* @param PHPExcel $objPHPExcel
throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
$timezoneObj = new DateTimeZone('Europe/London');
$GMT = new DateTimeZone('UTC');
$gFileData = $this->_gzfileGetContents($pFilename);
// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8');
$namespacesMeta = $xml->getNamespaces(true);
// var_dump($namespacesMeta);
$gnmXML = $xml->children($namespacesMeta['gnm']);
$docProps = $objPHPExcel->getProperties();
// Document Properties are held differently, depending on the version of Gnumeric
if (isset ($namespacesMeta['office'])) {
$officeXML = $xml->children($namespacesMeta['office']);
$officeDocXML = $officeXML->{'document-meta'};
$officeDocMetaXML = $officeDocXML->meta;
foreach($officeDocMetaXML as $officePropertyData) {
$officePropertyDC = array();
if (isset ($namespacesMeta['dc'])) {
$officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
foreach($officePropertyDC as $propertyName => $propertyValue) {
$propertyValue = (string) $propertyValue;
$docProps->setTitle(trim($propertyValue));
$docProps->setSubject(trim($propertyValue));
$docProps->setCreator(trim($propertyValue));
$docProps->setLastModifiedBy(trim($propertyValue));
$docProps->setCreated($creationDate);
$docProps->setModified($creationDate);
$docProps->setDescription(trim($propertyValue));
$officePropertyMeta = array();
if (isset ($namespacesMeta['meta'])) {
$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
foreach($officePropertyMeta as $propertyName => $propertyValue) {
$attributes = $propertyValue->attributes($namespacesMeta['meta']);
$propertyValue = (string) $propertyValue;
$docProps->setKeywords(trim($propertyValue));
$docProps->setCreator(trim($propertyValue));
$docProps->setLastModifiedBy(trim($propertyValue));
$docProps->setCreated($creationDate);
$docProps->setModified($creationDate);
list (,$attrName) = explode(':',$attributes['name']);
$docProps->setCompany(trim($propertyValue));
$docProps->setCategory(trim($propertyValue));
$docProps->setManager(trim($propertyValue));
} elseif (isset ($gnmXML->Summary)) {
foreach($gnmXML->Summary->Item as $summaryItem) {
$propertyName = $summaryItem->name;
$propertyValue = $summaryItem->{'val-string'};
$docProps->setTitle(trim($propertyValue));
$docProps->setDescription(trim($propertyValue));
$docProps->setKeywords(trim($propertyValue));
$docProps->setCategory(trim($propertyValue));
$docProps->setManager(trim($propertyValue));
$docProps->setCreator(trim($propertyValue));
$docProps->setLastModifiedBy(trim($propertyValue));
$docProps->setCompany(trim($propertyValue));
foreach($gnmXML->Sheets->Sheet as $sheet) {
$worksheetName = (string) $sheet->Name;
// echo '<b>Worksheet: ',$worksheetName,'</b><br />';
if ((isset ($this->_loadSheetsOnly)) && (!in_array($worksheetName, $this->_loadSheetsOnly))) {
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex($worksheetID);
$objPHPExcel->getActiveSheet()->setTitle($worksheetName);
if ((!$this->_readDataOnly) && (isset ($sheet->PrintInformation))) {
if (isset ($sheet->PrintInformation->Margins)) {
foreach($sheet->PrintInformation->Margins->children('gnm',TRUE) as $key => $margin) {
$marginAttributes = $margin->attributes();
$marginSize = 72 / 100; // Default
switch($marginAttributes['PrefUnit']) {
$marginSize = intval($marginAttributes['Points']) / 100;
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop($marginSize);
$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom($marginSize);
$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft($marginSize);
$objPHPExcel->getActiveSheet()->getPageMargins()->setRight($marginSize);
$objPHPExcel->getActiveSheet()->getPageMargins()->setHeader($marginSize);
$objPHPExcel->getActiveSheet()->getPageMargins()->setFooter($marginSize);
foreach($sheet->Cells->Cell as $cell) {
$cellAttributes = $cell->attributes();
$row = (int) $cellAttributes->Row + 1;
$column = (int) $cellAttributes->Col;
if ($row > $maxRow) $maxRow = $row;
if ($column > $maxCol) $maxCol = $column;
if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) {
$ValueType = $cellAttributes->ValueType;
$ExprID = (string) $cellAttributes->ExprID;
// echo 'Cell ',$column,$row,'<br />';
// echo 'Type is ',$ValueType,'<br />';
// echo 'Value is ',$cell,'<br />';
if (((string) $cell) > '') {
$this->_expressions[$ExprID] = array( 'column' => $cellAttributes->Col,
'row' => $cellAttributes->Row,
'formula' => (string) $cell
// echo 'NEW EXPRESSION ',$ExprID,'<br />';
$expression = $this->_expressions[$ExprID];
$cell = $this->_referenceHelper->updateFormulaReferences( $expression['formula'],
$cellAttributes->Col - $expression['column'],
$cellAttributes->Row - $expression['row'],
// echo 'SHARED EXPRESSION ',$ExprID,'<br />';
// echo 'New Value is ',$cell,'<br />';
$cell = ($cell == 'TRUE') ? True : False;
case '70' : // Cell Range
$objPHPExcel->getActiveSheet()->getCell($column. $row)->setValueExplicit($cell,$type);
if ((!$this->_readDataOnly) && (isset ($sheet->Objects))) {
foreach($sheet->Objects->children('gnm',TRUE) as $key => $comment) {
$commentAttributes = $comment->attributes();
// Only comment objects are handled at the moment
if ($commentAttributes->Text) {
$objPHPExcel->getActiveSheet()->getComment( (string) $commentAttributes->ObjectBound )
->setAuthor( (string) $commentAttributes->Author )
->setText($this->_parseRichText((string) $commentAttributes->Text) );
// echo '$maxCol=',$maxCol,'; $maxRow=',$maxRow,'<br />';
foreach($sheet->Styles->StyleRegion as $styleRegion) {
$styleAttributes = $styleRegion->attributes();
// var_dump($styleAttributes);
if (($styleAttributes['startRow'] <= $maxRow) &&
($styleAttributes['startCol'] <= $maxCol)) {
$startRow = $styleAttributes['startRow'] + 1;
$endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : $styleAttributes['endCol'];
$endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow'];
$cellRange = $startColumn. $startRow. ':'. $endColumn. $endRow;
// echo $cellRange,'<br />';
$styleAttributes = $styleRegion->Style->attributes();
// var_dump($styleAttributes);
// We still set the number format mask for date/time values, even if _readDataOnly is true
if ((!$this->_readDataOnly) ||
$styleArray['numberformat']['code'] = (string) $styleAttributes['Format'];
// If _readDataOnly is false, we set all formatting information
if (!$this->_readDataOnly) {
switch($styleAttributes['HAlign']) {
switch($styleAttributes['VAlign']) {
$styleArray['alignment']['wrap'] = ($styleAttributes['WrapText'] == '1') ? True : False;
$styleArray['alignment']['shrinkToFit'] = ($styleAttributes['ShrinkToFit'] == '1') ? True : False;
$styleArray['alignment']['indent'] = (intval($styleAttributes["Indent"]) > 0) ? $styleAttributes["indent"] : 0;
$RGB = self::_parseGnumericColour($styleAttributes["Fore"]);
$styleArray['font']['color']['rgb'] = $RGB;
$RGB = self::_parseGnumericColour($styleAttributes["Back"]);
$shade = $styleAttributes["Shade"];
if (($RGB != '000000') || ($shade != '0')) {
$styleArray['fill']['color']['rgb'] = $styleArray['fill']['startcolor']['rgb'] = $RGB;
$RGB2 = self::_parseGnumericColour($styleAttributes["PatternColor"]);
$styleArray['fill']['endcolor']['rgb'] = $RGB2;
$fontAttributes = $styleRegion->Style->Font->attributes();
// var_dump($fontAttributes);
$styleArray['font']['name'] = (string) $styleRegion->Style->Font;
$styleArray['font']['size'] = intval($fontAttributes['Unit']);
$styleArray['font']['bold'] = ($fontAttributes['Bold'] == '1') ? True : False;
$styleArray['font']['italic'] = ($fontAttributes['Italic'] == '1') ? True : False;
$styleArray['font']['strike'] = ($fontAttributes['StrikeThrough'] == '1') ? True : False;
switch($fontAttributes['Underline']) {
switch($fontAttributes['Script']) {
$styleArray['font']['superScript'] = True;
$styleArray['font']['subScript'] = True;
if (isset ($styleRegion->Style->StyleBorder)) {
if (isset ($styleRegion->Style->StyleBorder->Top)) {
$styleArray['borders']['top'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Top->attributes());
if (isset ($styleRegion->Style->StyleBorder->Bottom)) {
$styleArray['borders']['bottom'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Bottom->attributes());
if (isset ($styleRegion->Style->StyleBorder->Left)) {
$styleArray['borders']['left'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Left->attributes());
if (isset ($styleRegion->Style->StyleBorder->Right)) {
$styleArray['borders']['right'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Right->attributes());
if ((isset ($styleRegion->Style->StyleBorder->Diagonal)) && (isset ($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}))) {
$styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes());
} elseif (isset ($styleRegion->Style->StyleBorder->Diagonal)) {
$styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes());
} elseif (isset ($styleRegion->Style->StyleBorder->{'Rev-Diagonal'})) {
$styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}->attributes());
if (isset ($styleRegion->Style->HyperLink)) {
$hyperlink = $styleRegion->Style->HyperLink->attributes();
// var_dump($styleArray);
$objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray);
if ((!$this->_readDataOnly) && (isset ($sheet->Cols))) {
$columnAttributes = $sheet->Cols->attributes();
$defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4;
foreach($sheet->Cols->ColInfo as $columnOverride) {
$columnAttributes = $columnOverride->attributes();
$column = $columnAttributes['No'];
$columnWidth = $columnAttributes['Unit'] / 5.4;
$hidden = ((isset ($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1')) ? true : false;
$columnCount = (isset ($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1;
while (($c < ($column+ $columnCount)) && ($c <= $maxCol)) {
if ((!$this->_readDataOnly) && (isset ($sheet->Rows))) {
$rowAttributes = $sheet->Rows->attributes();
$defaultHeight = $rowAttributes['DefaultSizePts'];
foreach($sheet->Rows->RowInfo as $rowOverride) {
$rowAttributes = $rowOverride->attributes();
$row = $rowAttributes['No'];
$rowHeight = $rowAttributes['Unit'];
$hidden = ((isset ($rowAttributes['Hidden'])) && ($rowAttributes['Hidden'] == '1')) ? true : false;
$rowCount = (isset ($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1;
$objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
while (($r < ($row+ $rowCount)) && ($r < $maxRow)) {
$objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight);
$objPHPExcel->getActiveSheet()->getRowDimension($r)->setVisible(false);
$objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
// Handle Merged Cells in this worksheet
if (isset ($sheet->MergedRegions)) {
foreach($sheet->MergedRegions->Merge as $mergeCells) {
$objPHPExcel->getActiveSheet()->mergeCells($mergeCells);
// Loop through definedNames (global named ranges)
if (isset ($gnmXML->Names)) {
foreach($gnmXML->Names->Name as $namedRange) {
$name = (string) $namedRange->name;
$range = (string) $namedRange->value;
if (stripos($range, '#REF!') !== false) {
$range[0] = trim($range[0],"'");;
if ($worksheet = $objPHPExcel->getSheetByName($range[0])) {
private static function _parseBorderAttributes($borderAttributes) {
if (isset ($borderAttributes["Color"])) {
$RGB = self::_parseGnumericColour($borderAttributes["Color"]);
$styleArray['color']['rgb'] = $RGB;
switch ($borderAttributes["Style"]) {
private function _parseRichText($is = '') {
private static function _parseGnumericColour($gnmColour) {
list ($gnmR,$gnmG,$gnmB) = explode(':',$gnmColour);
$RGB = $gnmR. $gnmG. $gnmB;
// echo 'Excel Colour: ',$RGB,'<br />';
|