Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)

@param   string     $pFilename
@throws   PHPExcel_Reader_Exception
340236
public function listWorksheetInfo($pFilename)
	{
		// Check if file exists
		if (!file_exists($pFilename)) {
			throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
		}

		$worksheetInfo = array();

		// Read the OLE file
		$this->_loadOLE($pFilename);

		// total byte size of Excel data (workbook global substream + sheet substreams)
		$this->_dataSize = strlen($this->_data);

		// initialize
		$this->_pos    = 0;
		$this->_sheets = array();

		// Parse Workbook Global Substream
		while ($this->_pos < $this->_dataSize) {
			$code = self::_GetInt2d($this->_data, $this->_pos);

			switch ($code) {
				case self::XLS_Type_BOF:        $this->_readBof();        break;
				case self::XLS_Type_SHEET:      $this->_readSheet();      break;
				case self::XLS_Type_EOF:        $this->_readDefault();    break 2;
				default:                        $this->_readDefault();    break;
			}
		}

		// Parse the individual sheets
		foreach ($this->_sheets as $sheet) {

			if ($sheet['sheetType'] != 0x00) {
				// 0x00: Worksheet
				// 0x02: Chart
				// 0x06: Visual Basic module
				continue;
			}

			$tmpInfo = array();
			$tmpInfo['worksheetName'] = $sheet['name'];
			$tmpInfo['lastColumnLetter'] = 'A';
			$tmpInfo['lastColumnIndex'] = 0;
			$tmpInfo['totalRows'] = 0;
			$tmpInfo['totalColumns'] = 0;

			$this->_pos = $sheet['offset'];

			while ($this->_pos <= $this->_dataSize - 4) {
				$code = self::_GetInt2d($this->_data, $this->_pos);

				switch ($code) {
					case self::XLS_Type_RK:
					case self::XLS_Type_LABELSST:
					case self::XLS_Type_NUMBER:
					case self::XLS_Type_FORMULA:
					case self::XLS_Type_BOOLERR:
					case self::XLS_Type_LABEL:
						$length = self::_GetInt2d($this->_data, $this->_pos + 2);
						$recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length);

						// move stream pointer to next record
						$this->_pos += 4 + $length;

						$rowIndex = self::_GetInt2d($recordData, 0) + 1;
						$columnIndex = self::_GetInt2d($recordData, 2);

						$tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
						$tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
						break;
					case self::XLS_Type_BOF:      $this->_readBof();          break;
					case self::XLS_Type_EOF:      $this->_readDefault();      break 2;
					default:                      $this->_readDefault();      break;
				}
			}

			$tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
			$tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;

			$worksheetInfo[] = $tmpInfo;
		}

		return $worksheetInfo;
	}
307383
public function listWorksheetNames($pFilename)
    {
        // Check if file exists
        if (!file_exists($pFilename)) {
            throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
        }

        $worksheetNames = array();

        // Read the OLE file
        $this->loadOLE($pFilename);

        // total byte size of Excel data (workbook global substream + sheet substreams)
        $this->dataSize = strlen($this->data);

        $this->pos        = 0;
        $this->sheets    = array();

        // Parse Workbook Global Substream
        while ($this->pos < $this->dataSize) {
            $code = self::getInt2d($this->data, $this->pos);

            switch ($code) {
                case self::XLS_TYPE_BOF:
                    $this->readBof();
                    break;
                case self::XLS_TYPE_SHEET:
                    $this->readSheet();
                    break;
                case self::XLS_TYPE_EOF:
                    $this->readDefault();
                    break 2;
                default:
                    $this->readDefault();
                    break;
            }
        }

        foreach ($this->sheets as $sheet) {
            if ($sheet['sheetType'] != 0x00) {
                // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
                continue;
            }

            $worksheetNames[] = $sheet['name'];
        }

        return $worksheetNames;
    }
1016572
public function save($pFilename = null)
    {
        if (!$this->spreadSheet) {
            throw new PHPExcel_Writer_Exception('PHPExcel object unassigned.');
        }

        // garbage collect
        $this->spreadSheet->garbageCollect();

        // If $pFilename is php://output or php://stdout, make it a temporary file...
        $originalFilename = $pFilename;
        if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
            $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp');
            if ($pFilename == '') {
                $pFilename = $originalFilename;
            }
        }

        $objZip = $this->createZip($pFilename);

        $objZip->addFromString('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest());
        $objZip->addFromString('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail());
        $objZip->addFromString('content.xml', $this->getWriterPart('content')->write());
        $objZip->addFromString('meta.xml', $this->getWriterPart('meta')->write());
        $objZip->addFromString('mimetype', $this->getWriterPart('mimetype')->write());
        $objZip->addFromString('settings.xml', $this->getWriterPart('settings')->write());
        $objZip->addFromString('styles.xml', $this->getWriterPart('styles')->write());

        // Close file
        if ($objZip->close() === false) {
            throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename.");
        }

        // If a temporary file was used, copy it to the correct file stream
        if ($originalFilename != $pFilename) {
            if (copy($pFilename, $originalFilename) === false) {
                throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
            }
            @unlink($pFilename);
        }
    }
180629
function includeContents($pFilename)
    {
        $returnValue = false;

        if (\is_file($pFilename)) {
            \ob_start();

            include $pFilename;

            $returnValue = \ob_get_clean();
        }

        return $returnValue;
    }
993350
protected function openFile($pFilename)
    {
        // Check if file exists
        if (!file_exists($pFilename) || !is_readable($pFilename)) {
            throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
        }

        // Open file
        $this->fileHandle = fopen($pFilename, 'r');
        if ($this->fileHandle === false) {
            throw new PHPExcel_Reader_Exception("Could not open file " . $pFilename . " for reading.");
        }
    }
1243514
public function listWorksheetInfo($pFilename)
    {
        // Check if file exists
        if (!file_exists($pFilename)) {
            throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
        }

        $worksheetInfo = array();

        // Read the OLE file
        $this->loadOLE($pFilename);

        // total byte size of Excel data (workbook global substream + sheet substreams)
        $this->dataSize = strlen($this->data);

        // initialize
        $this->pos    = 0;
        $this->sheets = array();

        // Parse Workbook Global Substream
        while ($this->pos < $this->dataSize) {
            $code = self::getInt2d($this->data, $this->pos);

            switch ($code) {
                case self::XLS_TYPE_BOF:
                    $this->readBof();
                    break;
                case self::XLS_TYPE_SHEET:
                    $this->readSheet();
                    break;
                case self::XLS_TYPE_EOF:
                    $this->readDefault();
                    break 2;
                default:
                    $this->readDefault();
                    break;
            }
        }

        // Parse the individual sheets
        foreach ($this->sheets as $sheet) {
            if ($sheet['sheetType'] != 0x00) {
                // 0x00: Worksheet
                // 0x02: Chart
                // 0x06: Visual Basic module
                continue;
            }

            $tmpInfo = array();
            $tmpInfo['worksheetName'] = $sheet['name'];
            $tmpInfo['lastColumnLetter'] = 'A';
            $tmpInfo['lastColumnIndex'] = 0;
            $tmpInfo['totalRows'] = 0;
            $tmpInfo['totalColumns'] = 0;

            $this->pos = $sheet['offset'];

            while ($this->pos <= $this->dataSize - 4) {
                $code = self::getInt2d($this->data, $this->pos);

                switch ($code) {
                    case self::XLS_TYPE_RK:
                    case self::XLS_TYPE_LABELSST:
                    case self::XLS_TYPE_NUMBER:
                    case self::XLS_TYPE_FORMULA:
                    case self::XLS_TYPE_BOOLERR:
                    case self::XLS_TYPE_LABEL:
                        $length = self::getInt2d($this->data, $this->pos + 2);
                        $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);

                        // move stream pointer to next record
                        $this->pos += 4 + $length;

                        $rowIndex = self::getInt2d($recordData, 0) + 1;
                        $columnIndex = self::getInt2d($recordData, 2);

                        $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
                        $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
                        break;
                    case self::XLS_TYPE_BOF:
                        $this->readBof();
                        break;
                    case self::XLS_TYPE_EOF:
                        $this->readDefault();
                        break 2;
                    default:
                        $this->readDefault();
                        break;
                }
            }

            $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
            $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;

            $worksheetInfo[] = $tmpInfo;
        }

        return $worksheetInfo;
    }
12421
public function getSheetByName($pName = '')
    {
        $worksheetCount = count($this->_workSheetCollection);
        for ($i = 0; $i < $worksheetCount; ++$i) {
            if ($this->_workSheetCollection[$i]->getTitle() === $pName) {
                return $this->_workSheetCollection[$i];
            }
        }

        return NULL;
    }
538725
public function save($pFilename = null) {
		// garbage collect
		$this->_phpExcel->garbageCollect();

		$saveDebugLog = PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
		PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE);
		$saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
		PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);

		// Build CSS
		$this->buildCSS(!$this->_useInlineCss);

		// Open file
		$fileHandle = fopen($pFilename, 'wb+');
		if ($fileHandle === false) {
			throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing.");
		}

		// Write headers
		fwrite($fileHandle, $this->generateHTMLHeader(!$this->_useInlineCss));

		// Write navigation (tabs)
		if ((!$this->_isPdf) && ($this->_generateSheetNavigationBlock)) {
			fwrite($fileHandle, $this->generateNavigation());
		}

		// Write data
		fwrite($fileHandle, $this->generateSheetData());

		// Write footer
		fwrite($fileHandle, $this->generateHTMLFooter());

		// Close file
		fclose($fileHandle);

		PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
		PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
	}
825602
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
    {
        $fromFormats    = array('\-', '\ ');
        $toFormats      = array('-', ' ');

        $underlineStyles = array (
            PHPExcel_Style_Font::UNDERLINE_NONE,
            PHPExcel_Style_Font::UNDERLINE_DOUBLE,
            PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING,
            PHPExcel_Style_Font::UNDERLINE_SINGLE,
            PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING
        );
        $verticalAlignmentStyles = array (
            PHPExcel_Style_Alignment::VERTICAL_BOTTOM,
            PHPExcel_Style_Alignment::VERTICAL_TOP,
            PHPExcel_Style_Alignment::VERTICAL_CENTER,
            PHPExcel_Style_Alignment::VERTICAL_JUSTIFY
        );
        $horizontalAlignmentStyles = array (
            PHPExcel_Style_Alignment::HORIZONTAL_GENERAL,
            PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
            PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
            PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS,
            PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY
        );

        $timezoneObj = new DateTimeZone('Europe/London');
        $GMT = new DateTimeZone('UTC');

        // Check if file exists
        if (!file_exists($pFilename)) {
            throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
        }

        if (!$this->canRead($pFilename)) {
            throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
        }

        $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
        $namespaces = $xml->getNamespaces(true);

        $docProps = $objPHPExcel->getProperties();
        if (isset($xml->DocumentProperties[0])) {
            foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) {
                switch ($propertyName) {
                    case 'Title':
                        $docProps->setTitle(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Subject':
                        $docProps->setSubject(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Author':
                        $docProps->setCreator(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Created':
                        $creationDate = strtotime($propertyValue);
                        $docProps->setCreated($creationDate);
                        break;
                    case 'LastAuthor':
                        $docProps->setLastModifiedBy(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'LastSaved':
                        $lastSaveDate = strtotime($propertyValue);
                        $docProps->setModified($lastSaveDate);
                        break;
                    case 'Company':
                        $docProps->setCompany(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Category':
                        $docProps->setCategory(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Manager':
                        $docProps->setManager(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Keywords':
                        $docProps->setKeywords(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                    case 'Description':
                        $docProps->setDescription(self::convertStringEncoding($propertyValue, $this->charSet));
                        break;
                }
            }
        }
        if (isset($xml->CustomDocumentProperties)) {
            foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) {
                $propertyAttributes = $propertyValue->attributes($namespaces['dt']);
                $propertyName = preg_replace_callback('/_x([0-9a-z]{4})_/', 'PHPExcel_Reader_Excel2003XML::hex2str', $propertyName);
                $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_UNKNOWN;
                switch ((string) $propertyAttributes) {
                    case 'string':
                        $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
                        $propertyValue = trim($propertyValue);
                        break;
                    case 'boolean':
                        $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN;
                        $propertyValue = (bool) $propertyValue;
                        break;
                    case 'integer':
                        $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_INTEGER;
                        $propertyValue = intval($propertyValue);
                        break;
                    case 'float':
                        $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT;
                        $propertyValue = floatval($propertyValue);
                        break;
                    case 'dateTime.tz':
                        $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE;
                        $propertyValue = strtotime(trim($propertyValue));
                        break;
                }
                $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType);
            }
        }

        foreach ($xml->Styles[0] as $style) {
            $style_ss = $style->attributes($namespaces['ss']);
            $styleID = (string) $style_ss['ID'];
//            echo 'Style ID = '.$styleID.'<br />';
            if ($styleID == 'Default') {
                $this->styles['Default'] = array();
            } else {
                $this->styles[$styleID] = $this->styles['Default'];
            }
            foreach ($style as $styleType => $styleData) {
                $styleAttributes = $styleData->attributes($namespaces['ss']);
//                echo $styleType.'<br />';
                switch ($styleType) {
                    case 'Alignment':
                        foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
//                                echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
                            $styleAttributeValue = (string) $styleAttributeValue;
                            switch ($styleAttributeKey) {
                                case 'Vertical':
                                    if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) {
                                        $this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue;
                                    }
                                    break;
                                case 'Horizontal':
                                    if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) {
                                        $this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue;
                                    }
                                    break;
                                case 'WrapText':
                                    $this->styles[$styleID]['alignment']['wrap'] = true;
                                    break;
                            }
                        }
                        break;
                    case 'Borders':
                        foreach ($styleData->Border as $borderStyle) {
                            $borderAttributes = $borderStyle->attributes($namespaces['ss']);
                            $thisBorder = array();
                            foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) {
//                                    echo $borderStyleKey.' = '.$borderStyleValue.'<br />';
                                switch ($borderStyleKey) {
                                    case 'LineStyle':
                                        $thisBorder['style'] = PHPExcel_Style_Border::BORDER_MEDIUM;
//                                                $thisBorder['style'] = $borderStyleValue;
                                        break;
                                    case 'Weight':
//                                                $thisBorder['style'] = $borderStyleValue;
                                        break;
                                    case 'Position':
                                        $borderPosition = strtolower($borderStyleValue);
                                        break;
                                    case 'Color':
                                        $borderColour = substr($borderStyleValue, 1);
                                        $thisBorder['color']['rgb'] = $borderColour;
                                        break;
                                }
                            }
                            if (!empty($thisBorder)) {
                                if (($borderPosition == 'left') || ($borderPosition == 'right') || ($borderPosition == 'top') || ($borderPosition == 'bottom')) {
                                    $this->styles[$styleID]['borders'][$borderPosition] = $thisBorder;
                                }
                            }
                        }
                        break;
                    case 'Font':
                        foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
//                                echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
                            $styleAttributeValue = (string) $styleAttributeValue;
                            switch ($styleAttributeKey) {
                                case 'FontName':
                                    $this->styles[$styleID]['font']['name'] = $styleAttributeValue;
                                    break;
                                case 'Size':
                                    $this->styles[$styleID]['font']['size'] = $styleAttributeValue;
                                    break;
                                case 'Color':
                                    $this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1);
                                    break;
                                case 'Bold':
                                    $this->styles[$styleID]['font']['bold'] = true;
                                    break;
                                case 'Italic':
                                    $this->styles[$styleID]['font']['italic'] = true;
                                    break;
                                case 'Underline':
                                    if (self::identifyFixedStyleValue($underlineStyles, $styleAttributeValue)) {
                                        $this->styles[$styleID]['font']['underline'] = $styleAttributeValue;
                                    }
                                    break;
                            }
                        }
                        break;
                    case 'Interior':
                        foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
//                                echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
                            switch ($styleAttributeKey) {
                                case 'Color':
                                    $this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1);
                                    break;
                            }
                        }
                        break;
                    case 'NumberFormat':
                        foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
//                                echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
                            $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue);
                            switch ($styleAttributeValue) {
                                case 'Short Date':
                                    $styleAttributeValue = 'dd/mm/yyyy';
                                    break;
                            }
                            if ($styleAttributeValue > '') {
                                $this->styles[$styleID]['numberformat']['code'] = $styleAttributeValue;
                            }
                        }
                        break;
                    case 'Protection':
                        foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
//                                echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />';
                        }
                        break;
                }
            }
//            print_r($this->styles[$styleID]);
//            echo '<hr />';
        }
//        echo '<hr />';

        $worksheetID = 0;
        $xml_ss = $xml->children($namespaces['ss']);

        foreach ($xml_ss->Worksheet as $worksheet) {
            $worksheet_ss = $worksheet->attributes($namespaces['ss']);

            if ((isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) &&
                (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly))) {
                continue;
            }

//            echo '<h3>Worksheet: ', $worksheet_ss['Name'],'<h3>';
//
            // Create new Worksheet
            $objPHPExcel->createSheet();
            $objPHPExcel->setActiveSheetIndex($worksheetID);
            if (isset($worksheet_ss['Name'])) {
                $worksheetName = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet);
                //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
                //        formula cells... during the load, all formulae should be correct, and we're simply bringing
                //        the worksheet name in line with the formula, not the reverse
                $objPHPExcel->getActiveSheet()->setTitle($worksheetName, false);
            }

            $columnID = 'A';
            if (isset($worksheet->Table->Column)) {
                foreach ($worksheet->Table->Column as $columnData) {
                    $columnData_ss = $columnData->attributes($namespaces['ss']);
                    if (isset($columnData_ss['Index'])) {
                        $columnID = PHPExcel_Cell::stringFromColumnIndex($columnData_ss['Index']-1);
                    }
                    if (isset($columnData_ss['Width'])) {
                        $columnWidth = $columnData_ss['Width'];
//                        echo '<b>Setting column width for '.$columnID.' to '.$columnWidth.'</b><br />';
                        $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4);
                    }
                    ++$columnID;
                }
            }

            $rowID = 1;
            if (isset($worksheet->Table->Row)) {
                $additionalMergedCells = 0;
                foreach ($worksheet->Table->Row as $rowData) {
                    $rowHasData = false;
                    $row_ss = $rowData->attributes($namespaces['ss']);
                    if (isset($row_ss['Index'])) {
                        $rowID = (integer) $row_ss['Index'];
                    }
//                    echo '<b>Row '.$rowID.'</b><br />';

                    $columnID = 'A';
                    foreach ($rowData->Cell as $cell) {
                        $cell_ss = $cell->attributes($namespaces['ss']);
                        if (isset($cell_ss['Index'])) {
                            $columnID = PHPExcel_Cell::stringFromColumnIndex($cell_ss['Index']-1);
                        }
                        $cellRange = $columnID.$rowID;

                        if ($this->getReadFilter() !== null) {
                            if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
                                continue;
                            }
                        }

                        if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) {
                            $columnTo = $columnID;
                            if (isset($cell_ss['MergeAcross'])) {
                                $additionalMergedCells += (int)$cell_ss['MergeAcross'];
                                $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] -1);
                            }
                            $rowTo = $rowID;
                            if (isset($cell_ss['MergeDown'])) {
                                $rowTo = $rowTo + $cell_ss['MergeDown'];
                            }
                            $cellRange .= ':'.$columnTo.$rowTo;
                            $objPHPExcel->getActiveSheet()->mergeCells($cellRange);
                        }

                        $cellIsSet = $hasCalculatedValue = false;
                        $cellDataFormula = '';
                        if (isset($cell_ss['Formula'])) {
                            $cellDataFormula = $cell_ss['Formula'];
                            // added this as a check for array formulas
                            if (isset($cell_ss['ArrayRange'])) {
                                $cellDataCSEFormula = $cell_ss['ArrayRange'];
//                                echo "found an array formula at ".$columnID.$rowID."<br />";
                            }
                            $hasCalculatedValue = true;
                        }
                        if (isset($cell->Data)) {
                            $cellValue = $cellData = $cell->Data;
                            $type = PHPExcel_Cell_DataType::TYPE_NULL;
                            $cellData_ss = $cellData->attributes($namespaces['ss']);
                            if (isset($cellData_ss['Type'])) {
                                $cellDataType = $cellData_ss['Type'];
                                switch ($cellDataType) {
                                    /*
                                    const TYPE_STRING        = 's';
                                    const TYPE_FORMULA        = 'f';
                                    const TYPE_NUMERIC        = 'n';
                                    const TYPE_BOOL            = 'b';
                                    const TYPE_NULL            = 'null';
                                    const TYPE_INLINE        = 'inlineStr';
                                    const TYPE_ERROR        = 'e';
                                    */
                                    case 'String':
                                        $cellValue = self::convertStringEncoding($cellValue, $this->charSet);
                                        $type = PHPExcel_Cell_DataType::TYPE_STRING;
                                        break;
                                    case 'Number':
                                        $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                        $cellValue = (float) $cellValue;
                                        if (floor($cellValue) == $cellValue) {
                                            $cellValue = (integer) $cellValue;
                                        }
                                        break;
                                    case 'Boolean':
                                        $type = PHPExcel_Cell_DataType::TYPE_BOOL;
                                        $cellValue = ($cellValue != 0);
                                        break;
                                    case 'DateTime':
                                        $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                        $cellValue = PHPExcel_Shared_Date::PHPToExcel(strtotime($cellValue));
                                        break;
                                    case 'Error':
                                        $type = PHPExcel_Cell_DataType::TYPE_ERROR;
                                        break;
                                }
                            }

                            if ($hasCalculatedValue) {
//                                echo 'FORMULA<br />';
                                $type = PHPExcel_Cell_DataType::TYPE_FORMULA;
                                $columnNumber = PHPExcel_Cell::columnIndexFromString($columnID);
                                if (substr($cellDataFormula, 0, 3) == 'of:') {
                                    $cellDataFormula = substr($cellDataFormula, 3);
//                                    echo 'Before: ', $cellDataFormula,'<br />';
                                    $temp = explode('"', $cellDataFormula);
                                    $key = false;
                                    foreach ($temp as &$value) {
                                        //    Only replace in alternate array entries (i.e. non-quoted blocks)
                                        if ($key = !$key) {
                                            $value = str_replace(array('[.', '.', ']'), '', $value);
                                        }
                                    }
                                } else {
                                    //    Convert R1C1 style references to A1 style references (but only when not quoted)
//                                    echo 'Before: ', $cellDataFormula,'<br />';
                                    $temp = explode('"', $cellDataFormula);
                                    $key = false;
                                    foreach ($temp as &$value) {
                                        //    Only replace in alternate array entries (i.e. non-quoted blocks)
                                        if ($key = !$key) {
                                            preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
                                            //    Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
                                            //        through the formula from left to right. Reversing means that we work right to left.through
                                            //        the formula
                                            $cellReferences = array_reverse($cellReferences);
                                            //    Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
                                            //        then modify the formula to use that new reference
                                            foreach ($cellReferences as $cellReference) {
                                                $rowReference = $cellReference[2][0];
                                                //    Empty R reference is the current row
                                                if ($rowReference == '') {
                                                    $rowReference = $rowID;
                                                }
                                                //    Bracketed R references are relative to the current row
                                                if ($rowReference{0} == '[') {
                                                    $rowReference = $rowID + trim($rowReference, '[]');
                                                }
                                                $columnReference = $cellReference[4][0];
                                                //    Empty C reference is the current column
                                                if ($columnReference == '') {
                                                    $columnReference = $columnNumber;
                                                }
                                                //    Bracketed C references are relative to the current column
                                                if ($columnReference{0} == '[') {
                                                    $columnReference = $columnNumber + trim($columnReference, '[]');
                                                }
                                                $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference;
                                                $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
                                            }
                                        }
                                    }
                                }
                                unset($value);
                                //    Then rebuild the formula string
                                $cellDataFormula = implode('"', $temp);
//                                echo 'After: ', $cellDataFormula,'<br />';
                            }

//                            echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'<br />';
//
                            $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type);
                            if ($hasCalculatedValue) {
//                                echo 'Formula result is '.$cellValue.'<br />';
                                $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($cellValue);
                            }
                            $cellIsSet = $rowHasData = true;
                        }

                        if (isset($cell->Comment)) {
//                            echo '<b>comment found</b><br />';
                            $commentAttributes = $cell->Comment->attributes($namespaces['ss']);
                            $author = 'unknown';
                            if (isset($commentAttributes->Author)) {
                                $author = (string)$commentAttributes->Author;
//                                echo 'Author: ', $author,'<br />';
                            }
                            $node = $cell->Comment->Data->asXML();
//                            $annotation = str_replace('html:','',substr($node,49,-10));
//                            echo $annotation,'<br />';
                            $annotation = strip_tags($node);
//                            echo 'Annotation: ', $annotation,'<br />';
                            $objPHPExcel->getActiveSheet()->getComment($columnID.$rowID)->setAuthor(self::convertStringEncoding($author, $this->charSet))->setText($this->parseRichText($annotation));
                        }

                        if (($cellIsSet) && (isset($cell_ss['StyleID']))) {
                            $style = (string) $cell_ss['StyleID'];
//                            echo 'Cell style for '.$columnID.$rowID.' is '.$style.'<br />';
                            if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) {
//                                echo 'Cell '.$columnID.$rowID.'<br />';
//                                print_r($this->styles[$style]);
//                                echo '<br />';
                                if (!$objPHPExcel->getActiveSheet()->cellExists($columnID.$rowID)) {
                                    $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValue(null);
                                }
                                $objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]);
                            }
                        }
                        ++$columnID;
                        while ($additionalMergedCells > 0) {
                            ++$columnID;
                            $additionalMergedCells--;
                        }
                    }

                    if ($rowHasData) {
                        if (isset($row_ss['StyleID'])) {
                            $rowStyle = $row_ss['StyleID'];
                        }
                        if (isset($row_ss['Height'])) {
                            $rowHeight = $row_ss['Height'];
//                            echo '<b>Setting row height to '.$rowHeight.'</b><br />';
                            $objPHPExcel->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight);
                        }
                    }

                    ++$rowID;
                }
            }
            ++$worksheetID;
        }

        // Return
        return $objPHPExcel;
    }
1249295
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
	{
		// Check if file exists
		if (!file_exists($pFilename)) {
			throw new PHPExcel_Reader_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 '<pre>';
//		echo htmlentities($gFileData,ENT_QUOTES,'UTF-8');
//		echo '</pre><hr />';
//
		$xml = simplexml_load_string($gFileData, 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
		$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;
					switch ($propertyName) {
						case 'title' :
								$docProps->setTitle(trim($propertyValue));
								break;
						case 'subject' :
								$docProps->setSubject(trim($propertyValue));
								break;
						case 'creator' :
								$docProps->setCreator(trim($propertyValue));
								$docProps->setLastModifiedBy(trim($propertyValue));
								break;
						case 'date' :
								$creationDate = strtotime(trim($propertyValue));
								$docProps->setCreated($creationDate);
								$docProps->setModified($creationDate);
								break;
						case 'description' :
								$docProps->setDescription(trim($propertyValue));
								break;
					}
				}
				$officePropertyMeta = array();
				if (isset($namespacesMeta['meta'])) {
					$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
				}
				foreach($officePropertyMeta as $propertyName => $propertyValue) {
					$attributes = $propertyValue->attributes($namespacesMeta['meta']);
					$propertyValue = (string) $propertyValue;
					switch ($propertyName) {
						case 'keyword' :
								$docProps->setKeywords(trim($propertyValue));
								break;
						case 'initial-creator' :
								$docProps->setCreator(trim($propertyValue));
								$docProps->setLastModifiedBy(trim($propertyValue));
								break;
						case 'creation-date' :
								$creationDate = strtotime(trim($propertyValue));
								$docProps->setCreated($creationDate);
								$docProps->setModified($creationDate);
								break;
						case 'user-defined' :
								list(,$attrName) = explode(':',$attributes['name']);
								switch ($attrName) {
									case 'publisher' :
											$docProps->setCompany(trim($propertyValue));
											break;
									case 'category' :
											$docProps->setCategory(trim($propertyValue));
											break;
									case 'manager' :
											$docProps->setManager(trim($propertyValue));
											break;
								}
								break;
					}
				}
			}
		} elseif (isset($gnmXML->Summary)) {
			foreach($gnmXML->Summary->Item as $summaryItem) {
				$propertyName = $summaryItem->name;
				$propertyValue = $summaryItem->{'val-string'};
				switch ($propertyName) {
					case 'title' :
						$docProps->setTitle(trim($propertyValue));
						break;
					case 'comments' :
						$docProps->setDescription(trim($propertyValue));
						break;
					case 'keywords' :
						$docProps->setKeywords(trim($propertyValue));
						break;
					case 'category' :
						$docProps->setCategory(trim($propertyValue));
						break;
					case 'manager' :
						$docProps->setManager(trim($propertyValue));
						break;
					case 'author' :
						$docProps->setCreator(trim($propertyValue));
						$docProps->setLastModifiedBy(trim($propertyValue));
						break;
					case 'company' :
						$docProps->setCompany(trim($propertyValue));
						break;
				}
			}
		}

		$worksheetID = 0;
		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))) {
				continue;
			}

			$maxRow = $maxCol = 0;

			// Create new Worksheet
			$objPHPExcel->createSheet();
			$objPHPExcel->setActiveSheetIndex($worksheetID);
			//	Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula
			//		cells... during the load, all formulae should be correct, and we're simply bringing the worksheet
			//		name in line with the formula, not the reverse
			$objPHPExcel->getActiveSheet()->setTitle($worksheetName,false);

			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']) {
							case 'mm' :
								$marginSize = intval($marginAttributes['Points']) / 100;
								break;
						}
						switch($key) {
							case 'top' :
								$objPHPExcel->getActiveSheet()->getPageMargins()->setTop($marginSize);
								break;
							case 'bottom' :
								$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom($marginSize);
								break;
							case 'left' :
								$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft($marginSize);
								break;
							case 'right' :
								$objPHPExcel->getActiveSheet()->getPageMargins()->setRight($marginSize);
								break;
							case 'header' :
								$objPHPExcel->getActiveSheet()->getPageMargins()->setHeader($marginSize);
								break;
							case 'footer' :
								$objPHPExcel->getActiveSheet()->getPageMargins()->setFooter($marginSize);
								break;
						}
					}
				}
			}

			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;

				$column = PHPExcel_Cell::stringFromColumnIndex($column);

				// Read cell?
				if ($this->getReadFilter() !== NULL) {
					if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) {
						continue;
					}
				}

				$ValueType = $cellAttributes->ValueType;
				$ExprID = (string) $cellAttributes->ExprID;
//				echo 'Cell ',$column,$row,'<br />';
//				echo 'Type is ',$ValueType,'<br />';
//				echo 'Value is ',$cell,'<br />';
				$type = PHPExcel_Cell_DataType::TYPE_FORMULA;
				if ($ExprID > '') {
					if (((string) $cell) > '') {

						$this->_expressions[$ExprID] = array( 'column'	=> $cellAttributes->Col,
															  'row'		=> $cellAttributes->Row,
															  'formula'	=> (string) $cell
															);
//						echo 'NEW EXPRESSION ',$ExprID,'<br />';
					} else {
						$expression = $this->_expressions[$ExprID];

						$cell = $this->_referenceHelper->updateFormulaReferences( $expression['formula'],
																				  'A1',
																				  $cellAttributes->Col - $expression['column'],
																				  $cellAttributes->Row - $expression['row'],
																				  $worksheetName
																				);
//						echo 'SHARED EXPRESSION ',$ExprID,'<br />';
//						echo 'New Value is ',$cell,'<br />';
					}
					$type = PHPExcel_Cell_DataType::TYPE_FORMULA;
				} else {
					switch($ValueType) {
						case '10' :		//	NULL
							$type = PHPExcel_Cell_DataType::TYPE_NULL;
							break;
						case '20' :		//	Boolean
							$type = PHPExcel_Cell_DataType::TYPE_BOOL;
							$cell = ($cell == 'TRUE') ? True : False;
							break;
						case '30' :		//	Integer
							$cell = intval($cell);
						case '40' :		//	Float
							$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
							break;
						case '50' :		//	Error
							$type = PHPExcel_Cell_DataType::TYPE_ERROR;
							break;
						case '60' :		//	String
							$type = PHPExcel_Cell_DataType::TYPE_STRING;
							break;
						case '70' :		//	Cell Range
						case '80' :		//	Array
					}
				}
				$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();
				if (($styleAttributes['startRow'] <= $maxRow) &&
					($styleAttributes['startCol'] <= $maxCol)) {

					$startColumn = PHPExcel_Cell::stringFromColumnIndex((int) $styleAttributes['startCol']);
					$startRow = $styleAttributes['startRow'] + 1;

					$endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol'];
					$endColumn = PHPExcel_Cell::stringFromColumnIndex($endColumn);
					$endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow'];
					$endRow += 1;
					$cellRange = $startColumn.$startRow.':'.$endColumn.$endRow;
//					echo $cellRange,'<br />';

					$styleAttributes = $styleRegion->Style->attributes();
//					var_dump($styleAttributes);
//					echo '<br />';

					//	We still set the number format mask for date/time values, even if _readDataOnly is true
					if ((!$this->_readDataOnly) ||
						(PHPExcel_Shared_Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) {
						$styleArray = array();
						$styleArray['numberformat']['code'] = (string) $styleAttributes['Format'];
						//	If _readDataOnly is false, we set all formatting information
						if (!$this->_readDataOnly) {
							switch($styleAttributes['HAlign']) {
								case '1' :
									$styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL;
									break;
								case '2' :
									$styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
									break;
								case '4' :
									$styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT;
									break;
								case '8' :
									$styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
									break;
								case '16' :
								case '64' :
									$styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS;
									break;
								case '32' :
									$styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY;
									break;
							}

							switch($styleAttributes['VAlign']) {
								case '1' :
									$styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_TOP;
									break;
								case '2' :
									$styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_BOTTOM;
									break;
								case '4' :
									$styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_CENTER;
									break;
								case '8' :
									$styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_JUSTIFY;
									break;
							}

							$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;
								switch($shade) {
									case '1' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_SOLID;
										break;
									case '2' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR;
										break;
									case '3' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_GRADIENT_PATH;
										break;
									case '4' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN;
										break;
									case '5' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY;
										break;
									case '6' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID;
										break;
									case '7' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL;
										break;
									case '8' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS;
										break;
									case '9' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKUP;
										break;
									case '10' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL;
										break;
									case '11' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625;
										break;
									case '12' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_GRAY125;
										break;
									case '13' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN;
										break;
									case '14' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY;
										break;
									case '15' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID;
										break;
									case '16' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL;
										break;
									case '17' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS;
										break;
									case '18' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP;
										break;
									case '19' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL;
										break;
									case '20' :
										$styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY;
										break;
								}
							}

							$fontAttributes = $styleRegion->Style->Font->attributes();
//							var_dump($fontAttributes);
//							echo '<br />';
							$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']) {
								case '1' :
									$styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_SINGLE;
									break;
								case '2' :
									$styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_DOUBLE;
									break;
								case '3' :
									$styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING;
									break;
								case '4' :
									$styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING;
									break;
								default :
									$styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_NONE;
									break;
							}
							switch($fontAttributes['Script']) {
								case '1' :
									$styleArray['font']['superScript'] = True;
									break;
								case '-1' :
									$styleArray['font']['subScript'] = True;
									break;
							}

							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());
									$styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_BOTH;
								} elseif (isset($styleRegion->Style->StyleBorder->Diagonal)) {
									$styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes());
									$styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_UP;
								} elseif (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'})) {
									$styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}->attributes());
									$styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_DOWN;
								}
							}
							if (isset($styleRegion->Style->HyperLink)) {
								//	TO DO
								$hyperlink = $styleRegion->Style->HyperLink->attributes();
							}
						}
//						var_dump($styleArray);
//						echo '<br />';
						$objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray);
					}
				}
			}

			if ((!$this->_readDataOnly) && (isset($sheet->Cols))) {
				//	Column Widths
				$columnAttributes = $sheet->Cols->attributes();
				$defaultWidth = $columnAttributes['DefaultSizePts']  / 5.4;
				$c = 0;
				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) {
						$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($defaultWidth);
						++$c;
					}
					while (($c < ($column+$columnCount)) && ($c <= $maxCol)) {
						$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($columnWidth);
						if ($hidden) {
							$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setVisible(false);
						}
						++$c;
					}
				}
				while ($c <= $maxCol) {
					$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($defaultWidth);
					++$c;
				}
			}

			if ((!$this->_readDataOnly) && (isset($sheet->Rows))) {
				//	Row Heights
				$rowAttributes = $sheet->Rows->attributes();
				$defaultHeight = $rowAttributes['DefaultSizePts'];
				$r = 0;

				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;
					while ($r < $row) {
						++$r;
						$objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
					}
					while (($r < ($row+$rowCount)) && ($r < $maxRow)) {
						++$r;
						$objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight);
						if ($hidden) {
							$objPHPExcel->getActiveSheet()->getRowDimension($r)->setVisible(false);
						}
					}
				}
				while ($r < $maxRow) {
					++$r;
					$objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
				}
			}

			//	Handle Merged Cells in this worksheet
			if (isset($sheet->MergedRegions)) {
				foreach($sheet->MergedRegions->Merge as $mergeCells) {
					if (strpos($mergeCells,':') !== FALSE) {
						$objPHPExcel->getActiveSheet()->mergeCells($mergeCells);
					}
				}
			}

			$worksheetID++;
		}

		//	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) {
					continue;
				}

				$range = explode('!',$range);
				$range[0] = trim($range[0],"'");;
				if ($worksheet = $objPHPExcel->getSheetByName($range[0])) {
					$extractedRange = str_replace('$', '', $range[1]);
					$objPHPExcel->addNamedRange( new PHPExcel_NamedRange($name, $worksheet, $extractedRange) );
				}
			}
		}


		// Return
		return $objPHPExcel;
	}
663892
public function canRead($pFilename)
    {

        //    Office                    xmlns:o="urn:schemas-microsoft-com:office:office"
        //    Excel                    xmlns:x="urn:schemas-microsoft-com:office:excel"
        //    XML Spreadsheet            xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
        //    Spreadsheet component    xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet"
        //    XML schema                 xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
        //    XML data type            xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
        //    MS-persist recordset    xmlns:rs="urn:schemas-microsoft-com:rowset"
        //    Rowset                    xmlns:z="#RowsetSchema"
        //

        $signature = array(
                '<?xml version="1.0"',
                '<?mso-application progid="Excel.Sheet"?>'
            );

        // Open file
        $this->openFile($pFilename);
        $fileHandle = $this->fileHandle;
        
        // Read sample data (first 2 KB will do)
        $data = fread($fileHandle, 2048);
        fclose($fileHandle);

        $valid = true;
        foreach ($signature as $match) {
            // every part of the signature must be present
            if (strpos($data, $match) === false) {
                $valid = false;
                break;
            }
        }

        //    Retrieve charset encoding
        if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/um', $data, $matches)) {
            $this->charSet = strtoupper($matches[1]);
        }
//        echo 'Character Set is ', $this->charSet,'<br />';

        return $valid;
    }
1368927
public function getNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null)
    {
        $returnValue = null;

        if ($namedRange != '' && ($namedRange !== null)) {
            // first look for global defined name
            if (isset($this->namedRanges[$namedRange])) {
                $returnValue = $this->namedRanges[$namedRange];
            }

            // then look for local defined name (has priority over global defined name if both names exist)
            if (($pSheet !== null) && isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
                $returnValue = $this->namedRanges[$pSheet->getTitle() . '!' . $namedRange];
            }
        }

        return $returnValue;
    }
566916
public function getComment($cellName)
    {
        //check whether workshett name is set or not
        if ($this->worksheetName == '')
            throw new Exception('Worksheet name not specified');
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() .
            '/worksheets/' . $this->worksheetName . '/comments/' . $cellName;
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');
        $json = json_decode($responseStream);
        return $json->Comment->HtmlNote;

    }
403507
public function save($pFilename = null) {
		// Fetch sheet
		$sheet = $this->_phpExcel->getSheet($this->_sheetIndex);

		$saveDebugLog = PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog();
		PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE);
		$saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
		PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);

		// Open file
		$fileHandle = fopen($pFilename, 'wb+');
		if ($fileHandle === false) {
			throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing.");
		}

		if ($this->_excelCompatibility) {
			fwrite($fileHandle, "\xEF\xBB\xBF");	//	Enforce UTF-8 BOM Header
			$this->setEnclosure('"');				//	Set enclosure to "
			$this->setDelimiter(";");			    //	Set delimiter to a semi-colon
            $this->setLineEnding("\r\n");
			fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->_lineEnding);
		} elseif ($this->_useBOM) {
			// Write the UTF-8 BOM code if required
			fwrite($fileHandle, "\xEF\xBB\xBF");
		}

		//	Identify the range that we need to extract from the worksheet
		$maxCol = $sheet->getHighestDataColumn();
		$maxRow = $sheet->getHighestDataRow();

		// Write rows to file
		for($row = 1; $row <= $maxRow; ++$row) {
			// Convert the row to an array...
			$cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row,'', $this->_preCalculateFormulas);
			// ... and write to the file
			$this->_writeLine($fileHandle, $cellsArray[0]);
		}

		// Close file
		fclose($fileHandle);

		PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
		PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
	}
124980
protected function prepareForSave($pFilename = null)
    {
        //  garbage collect
        $this->phpExcel->garbageCollect();

        $this->saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
        PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);

        //  Open file
        $fileHandle = fopen($pFilename, 'w');
        if ($fileHandle === false) {
            throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing.");
        }

        //  Set PDF
        $this->isPdf = true;
        //  Build CSS
        $this->buildCSS(true);

        return $fileHandle;
    }
1309427
public function save($pFilename = null)
	{
		if ($this->_spreadSheet !== NULL) {
			// garbage collect
			$this->_spreadSheet->garbageCollect();

			// If $pFilename is php://output or php://stdout, make it a temporary file...
			$originalFilename = $pFilename;
			if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
				$pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp');
				if ($pFilename == '') {
					$pFilename = $originalFilename;
				}
			}

			$saveDebugLog = PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->getWriteDebugLog();
			PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(FALSE);
			$saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
			PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);

			// Create string lookup table
			$this->_stringTable = array();
			for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
				$this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable);
			}

			// Create styles dictionaries
			$this->_styleHashTable->addFromSource( 	            $this->getWriterPart('Style')->allStyles($this->_spreadSheet) 			);
			$this->_stylesConditionalHashTable->addFromSource( 	$this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet) 			);
			$this->_fillHashTable->addFromSource( 				$this->getWriterPart('Style')->allFills($this->_spreadSheet) 			);
			$this->_fontHashTable->addFromSource( 				$this->getWriterPart('Style')->allFonts($this->_spreadSheet) 			);
			$this->_bordersHashTable->addFromSource( 			$this->getWriterPart('Style')->allBorders($this->_spreadSheet) 			);
			$this->_numFmtHashTable->addFromSource( 			$this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet) 	);

			// Create drawing dictionary
			$this->_drawingHashTable->addFromSource( 			$this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet) 		);

			// Create new ZIP file and open it for writing
			$zipClass = PHPExcel_Settings::getZipClass();
			$objZip = new $zipClass();

			//	Retrieve OVERWRITE and CREATE constants from the instantiated zip class
			//	This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP
			$ro = new ReflectionObject($objZip);
			$zipOverWrite = $ro->getConstant('OVERWRITE');
			$zipCreate = $ro->getConstant('CREATE');

			if (file_exists($pFilename)) {
				unlink($pFilename);
			}
			// Try opening the ZIP file
			if ($objZip->open($pFilename, $zipOverWrite) !== true) {
				if ($objZip->open($pFilename, $zipCreate) !== true) {
					throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing.");
				}
			}

			// Add [Content_Types].xml to ZIP file
			$objZip->addFromString('[Content_Types].xml', 			$this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts));

			//if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
			if($this->_spreadSheet->hasMacros()){
				$macrosCode=$this->_spreadSheet->getMacrosCode();
				if(!is_null($macrosCode)){// we have the code ?
					$objZip->addFromString('xl/vbaProject.bin', $macrosCode);//allways in 'xl', allways named vbaProject.bin
					if($this->_spreadSheet->hasMacrosCertificate()){//signed macros ?
						// Yes : add the certificate file and the related rels file
						$objZip->addFromString('xl/vbaProjectSignature.bin', $this->_spreadSheet->getMacrosCertificate());
						$objZip->addFromString('xl/_rels/vbaProject.bin.rels',
							$this->getWriterPart('RelsVBA')->writeVBARelationships($this->_spreadSheet));
					}
				}
			}
			//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
			if($this->_spreadSheet->hasRibbon()){
				$tmpRibbonTarget=$this->_spreadSheet->getRibbonXMLData('target');
				$objZip->addFromString($tmpRibbonTarget, $this->_spreadSheet->getRibbonXMLData('data'));
				if($this->_spreadSheet->hasRibbonBinObjects()){
					$tmpRootPath=dirname($tmpRibbonTarget).'/';
					$ribbonBinObjects=$this->_spreadSheet->getRibbonBinObjects('data');//the files to write
					foreach($ribbonBinObjects as $aPath=>$aContent){
						$objZip->addFromString($tmpRootPath.$aPath, $aContent);
					}
					//the rels for files
					$objZip->addFromString($tmpRootPath.'_rels/'.basename($tmpRibbonTarget).'.rels',
						$this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->_spreadSheet));
				}
			}
			
			// Add relationships to ZIP file
			$objZip->addFromString('_rels/.rels', 					$this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet));
			$objZip->addFromString('xl/_rels/workbook.xml.rels', 	$this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet));

			// Add document properties to ZIP file
			$objZip->addFromString('docProps/app.xml', 				$this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet));
			$objZip->addFromString('docProps/core.xml', 			$this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet));
			$customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet);
			if ($customPropertiesPart !== NULL) {
				$objZip->addFromString('docProps/custom.xml', 		$customPropertiesPart);
			}

			// Add theme to ZIP file
			$objZip->addFromString('xl/theme/theme1.xml', 			$this->getWriterPart('Theme')->writeTheme($this->_spreadSheet));

			// Add string table to ZIP file
			$objZip->addFromString('xl/sharedStrings.xml', 			$this->getWriterPart('StringTable')->writeStringTable($this->_stringTable));

			// Add styles to ZIP file
			$objZip->addFromString('xl/styles.xml', 				$this->getWriterPart('Style')->writeStyles($this->_spreadSheet));

			// Add workbook to ZIP file
			$objZip->addFromString('xl/workbook.xml', 				$this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas));

			$chartCount = 0;
			// Add worksheets
			for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
				$objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts));
				if ($this->_includeCharts) {
					$charts = $this->_spreadSheet->getSheet($i)->getChartCollection();
					if (count($charts) > 0) {
						foreach($charts as $chart) {
							$objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart));
							$chartCount++;
						}
					}
				}
			}

			$chartRef1 = $chartRef2 = 0;
			// Add worksheet relationships (drawings, ...)
			for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {

				// Add relationships
				$objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', 	$this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), ($i + 1), $this->_includeCharts));

				$drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection();
				$drawingCount = count($drawings);
				if ($this->_includeCharts) {
					$chartCount = $this->_spreadSheet->getSheet($i)->getChartCount();
				}

				// Add drawing and image relationship parts
				if (($drawingCount > 0) || ($chartCount > 0)) {
					// Drawing relationships
					$objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i),$chartRef1, $this->_includeCharts));

					// Drawings
					$objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i),$chartRef2,$this->_includeCharts));
				}

				// Add comment relationship parts
				if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) {
					// VML Comments
					$objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i)));

					// Comments
					$objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i)));
				}

				// Add header/footer relationship parts
				if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
					// VML Drawings
					$objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i)));

					// VML Drawing relationships
					$objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i)));

					// Media
					foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
						$objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
					}
				}
			}

			// Add media
			for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
				if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {
					$imageContents = null;
					$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
					if (strpos($imagePath, 'zip://') !== false) {
						$imagePath = substr($imagePath, 6);
						$imagePathSplitted = explode('#', $imagePath);

						$imageZip = new ZipArchive();
						$imageZip->open($imagePathSplitted[0]);
						$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
						$imageZip->close();
						unset($imageZip);
					} else {
						$imageContents = file_get_contents($imagePath);
					}

					$objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
				} else if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) {
					ob_start();
					call_user_func(
						$this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
						$this->getDrawingHashTable()->getByIndex($i)->getImageResource()
					);
					$imageContents = ob_get_contents();
					ob_end_clean();

					$objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
				}
			}

			PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);
			PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);

			// Close file
			if ($objZip->close() === false) {
				throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename.");
			}

			// If a temporary file was used, copy it to the correct file stream
			if ($originalFilename != $pFilename) {
				if (copy($pFilename, $originalFilename) === false) {
					throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
				}
				@unlink($pFilename);
			}
		} else {
			throw new PHPExcel_Writer_Exception("PHPExcel object unassigned.");
		}
	}
408848
public function save($pFilename = null)
    {
        // garbage collect
        $this->phpExcel->garbageCollect();

        $saveDebugLog = PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->getWriteDebugLog();
        PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog(false);
        $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
        PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);

        // Build CSS
        $this->buildCSS(!$this->useInlineCss);

        // Open file
        $fileHandle = fopen($pFilename, 'wb+');
        if ($fileHandle === false) {
            throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing.");
        }

        // Write headers
        fwrite($fileHandle, $this->generateHTMLHeader(!$this->useInlineCss));

        // Write navigation (tabs)
        if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) {
            fwrite($fileHandle, $this->generateNavigation());
        }

        // Write data
        fwrite($fileHandle, $this->generateSheetData());

        // Write footer
        fwrite($fileHandle, $this->generateHTMLFooter());

        // Close file
        fclose($fileHandle);

        PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
        PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
    }