Beispiel #1
0
	/**
	 * Get an instance of this class
	 *
	 * @return PHPExcel_Calculation
	 */
	public static function getInstance() {
		if (! isset ( self::$_instance ) || is_null ( self::$_instance )) {
			self::$_instance = new PHPExcel_Calculation ( );
		}

		return self::$_instance;
	}
 /**
  * @dataProvider providerBinaryComparisonOperation
  */
 public function testBinaryComparisonOperation($formula, $expectedResultExcel, $expectedResultOpenOffice)
 {
     PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
     $resultExcel = \PHPExcel_Calculation::getInstance()->_calculateFormulaValue($formula);
     $this->assertEquals($expectedResultExcel, $resultExcel, 'should be Excel compatible');
     PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE);
     $resultOpenOffice = \PHPExcel_Calculation::getInstance()->_calculateFormulaValue($formula);
     $this->assertEquals($expectedResultOpenOffice, $resultOpenOffice, 'should be OpenOffice compatible');
 }
 /**
  * Push a new entry onto the stack
  *
  * @param  mixed $type
  * @param  mixed $value
  * @param  mixed $reference
  */
 public function push($type, $value, $reference = null)
 {
     $this->_stack[$this->_count++] = array('type' => $type, 'value' => $value, 'reference' => $reference);
     if ($type == 'Function') {
         $localeFunction = PHPExcel_Calculation::_localeFunc($value);
         if ($localeFunction != $value) {
             $this->_stack[$this->_count - 1]['localeValue'] = $localeFunction;
         }
     }
 }
Beispiel #4
0
 /**
  * Get caluclated cell value
  *
  * @return mixed
  */
 public function getCalculatedValue($resetLog = true)
 {
     //		echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().'<br />';
     if (!is_null($this->_calculatedValue) && $this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) {
         try {
             //				echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value<br />';
             $result = PHPExcel_Calculation::getInstance()->calculateCellValue($this, $resetLog);
         } catch (Exception $ex) {
             //				echo 'Calculation Exception: '.$ex->getMessage().'<br />';
             $result = '#N/A';
         }
         if (is_string($result) && $result == '#Not Yet Implemented') {
             //				echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().'<br />';
             return $this->_calculatedValue;
             // Fallback if calculation engine does not support the formula.
         } else {
             //				echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().'<br />';
             return $result;
         }
     }
     if (is_null($this->_value)) {
         //			echo 'Cell '.$this->getCoordinate().' has no value, formula or otherwise<br />';
         return null;
     } else {
         if ($this->_dataType != PHPExcel_Cell_DataType::TYPE_FORMULA) {
             //			echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'<br />';
             return $this->_value;
         } else {
             //			echo 'Cell value is a formula: Calculating value<br />';
             return PHPExcel_Calculation::getInstance()->calculateCellValue($this, $resetLog);
         }
     }
 }
Beispiel #5
0
 /**
  * Save PHPExcel to file
  *
  * @param 	string 		$pFileName
  * @throws 	Exception
  */
 public function save($pFilename = null)
 {
     // Fetch sheet
     $sheet = $this->_phpExcel->getSheet($this->_sheetIndex);
     $saveDebugLog = PHPExcel_Calculation::getInstance()->writeDebugLog;
     PHPExcel_Calculation::getInstance()->writeDebugLog = false;
     $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
     PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
     // Open file
     $fileHandle = fopen($pFilename, 'w');
     if ($fileHandle === false) {
         throw new Exception("Could not open file {$pFilename} for writing.");
     }
     if ($this->_useBOM) {
         // Write the UTF-8 BOM code
         fwrite($fileHandle, "");
     }
     // Convert sheet to array
     $cellsArray = $sheet->toArray('', $this->_preCalculateFormulas);
     // Write rows to file
     foreach ($cellsArray as $row) {
         $this->_writeLine($fileHandle, $row);
     }
     // Close file
     fclose($fileHandle);
     PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
     PHPExcel_Calculation::getInstance()->writeDebugLog = $saveDebugLog;
 }
Beispiel #6
0
 /**
  *	MINIF
  *
  *	Returns the minimum value within a range of cells that contain numbers within the list of arguments
  *
  *	Excel Function:
  *		MINIF(value1[,value2[, ...]],condition)
  *
  *	@access	public
  *	@category Mathematical and Trigonometric Functions
  *	@param	mixed		$arg,...		Data values
  *	@param	string		$condition		The criteria that defines which cells will be checked.
  *	@return	float
  */
 public static function MINIF($aArgs, $condition, $sumArgs = array())
 {
     // Return value
     $returnValue = null;
     $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
     $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
     if (count($sumArgs) == 0) {
         $sumArgs = $aArgs;
     }
     $condition = PHPExcel_Calculation_Functions::_ifCondition($condition);
     // Loop through arguments
     foreach ($aArgs as $key => $arg) {
         if (!is_numeric($arg)) {
             $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg));
         }
         $testCondition = '=' . $arg . $condition;
         if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
             if (is_null($returnValue) || $arg < $returnValue) {
                 $returnValue = $arg;
             }
         }
     }
     // Return
     return $returnValue;
 }
Beispiel #7
0
 /**
  * Calculate the value of a formula
  *
  * @param	string		$formula		Formula to parse
  * @return	mixed
  * @throws	Exception
  */
 public function calculateFormula($formula, $cellID = null, PHPExcel_Cell $pCell = null)
 {
     //	Initialise the logging settings
     $this->formulaError = null;
     $this->debugLog = $this->debugLogStack = array();
     //	Disable calculation cacheing because it only applies to cell calculations, not straight formulae
     //	But don't actually flush any cache
     $resetCache = $this->getCalculationCacheEnabled();
     self::$_calculationCacheEnabled = false;
     //	Execute the calculation
     try {
         $result = self::_unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell));
     } catch (Exception $e) {
         throw new Exception($e->getMessage());
     }
     //	Reset calculation cacheing to its previous state
     self::$_calculationCacheEnabled = $resetCache;
     return $result;
 }
Beispiel #8
0
 /**
  * Save PHPExcel to file
  *
  * @param	string		$pFilename
  * @throws	PHPExcel_Writer_Exception
  */
 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);
 }
 /**
  * NOT
  *
  * Returns the boolean inverse of the argument.
  *
  * Excel Function:
  *        =NOT(logical)
  *
  *        The argument must evaluate to a logical value such as TRUE or FALSE
  *
  *        Boolean arguments are treated as True or False as appropriate
  *        Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
  *        If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
  *            the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
  *
  * @access    public
  * @category  Logical Functions
  *
  * @param    mixed $logical A value or expression that can be evaluated to TRUE or FALSE
  *
  * @return    boolean        The boolean inverse of the argument.
  */
 public static function NOT($logical = false)
 {
     $logical = PHPExcel_Calculation_Functions::flattenSingleValue($logical);
     if (is_string($logical)) {
         $logical = strtoupper($logical);
         if ($logical == 'TRUE' || $logical == PHPExcel_Calculation::getTRUE()) {
             return false;
         } elseif ($logical == 'FALSE' || $logical == PHPExcel_Calculation::getFALSE()) {
             return true;
         } else {
             return PHPExcel_Calculation_Functions::VALUE();
         }
     }
     return !$logical;
 }
Beispiel #10
0
 /**
  * Identify whether a string contains a fractional numeric value,
  *    and convert it to a numeric if it is
  *
  * @param string &$operand string value to test
  * @return boolean
  */
 public static function convertToNumberIfFraction(&$operand)
 {
     if (preg_match('/^' . self::STRING_REGEXP_FRACTION . '$/i', $operand, $match)) {
         $sign = $match[1] == '-' ? '-' : '+';
         $fractionFormula = '=' . $sign . $match[2] . $sign . $match[3];
         $operand = PHPExcel_Calculation::getInstance()->_calculateFormulaValue($fractionFormula);
         return true;
     }
     return false;
 }
Beispiel #11
0
 /**
  *	Get calculated cell value
  *
  *	@deprecated		Since version 1.7.8 for planned changes to cell for array formula handling
  *
  *	@return	mixed
  *	@throws	PHPExcel_Exception
  */
 public function getCalculatedValue($resetLog = TRUE)
 {
     //		echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().'<br />';
     if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) {
         try {
             //				echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value<br />';
             $result = PHPExcel_Calculation::getInstance()->calculateCellValue($this, $resetLog);
             //				echo $this->getCoordinate().' calculation result is '.$result.'<br />';
         } catch (Exception $ex) {
             if ($ex->getMessage() === 'Unable to access External Workbook' && $this->_calculatedValue !== NULL) {
                 //					echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().'<br />';
                 return $this->_calculatedValue;
                 // Fallback for calculations referencing external files.
             }
             //				echo 'Calculation Exception: '.$ex->getMessage().'<br />';
             $result = '#N/A';
             throw new PHPExcel_Exception($this->getParent()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage());
         }
         if ($result === '#Not Yet Implemented') {
             //				echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().'<br />';
             return $this->_calculatedValue;
             // Fallback if calculation engine does not support the formula.
         }
         //			echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().'<br />';
         return $result;
     }
     //		if ($this->_value === NULL) {
     //			echo 'Cell '.$this->getCoordinate().' has no value, formula or otherwise<br />';
     //			return NULL;
     //		}
     //		echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'<br />';
     return $this->_value;
 }
Beispiel #12
0
 /**
  * Save PHPExcel to file
  *
  * @param 	string 		$pFilename
  * @throws 	PHPExcel_Writer_Exception
  */
 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.");
     }
 }
Beispiel #13
0
 /**
  * Calculate the value of a cell formula
  *
  * @access	public
  * @param	PHPExcel_Cell	$pCell		Cell to calculate
  * @param	Boolean			$resetLog	Flag indicating whether the debug log should be reset or not
  * @return	mixed
  * @throws	PHPExcel_Calculation_Exception
  */
 public function calculateCellValue(PHPExcel_Cell $pCell = NULL, $resetLog = TRUE)
 {
     if ($pCell === NULL) {
         return NULL;
     }
     $returnArrayAsType = self::$returnArrayAsType;
     if ($resetLog) {
         //	Initialise the logging settings if requested
         $this->formulaError = null;
         $this->_debugLog->clearLog();
         $this->_cyclicReferenceStack->clear();
         $this->_cyclicFormulaCount = 1;
         self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY;
     }
     //	Execute the calculation for the cell formula
     $this->_cellStack[] = array('sheet' => $pCell->getWorksheet()->getTitle(), 'cell' => $pCell->getCoordinate());
     try {
         $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
         $cellAddress = array_pop($this->_cellStack);
         $this->_workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
     } catch (PHPExcel_Exception $e) {
         $cellAddress = array_pop($this->_cellStack);
         $this->_workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
         throw new PHPExcel_Calculation_Exception($e->getMessage());
     }
     if (is_array($result) && self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY) {
         self::$returnArrayAsType = $returnArrayAsType;
         $testResult = PHPExcel_Calculation_Functions::flattenArray($result);
         if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) {
             return PHPExcel_Calculation_Functions::VALUE();
         }
         //	If there's only a single cell in the array, then we allow it
         if (count($testResult) != 1) {
             //	If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it
             $r = array_keys($result);
             $r = array_shift($r);
             if (!is_numeric($r)) {
                 return PHPExcel_Calculation_Functions::VALUE();
             }
             if (is_array($result[$r])) {
                 $c = array_keys($result[$r]);
                 $c = array_shift($c);
                 if (!is_numeric($c)) {
                     return PHPExcel_Calculation_Functions::VALUE();
                 }
             }
         }
         $result = array_shift($testResult);
     }
     self::$returnArrayAsType = $returnArrayAsType;
     if ($result === NULL) {
         return 0;
     } elseif (is_float($result) && (is_nan($result) || is_infinite($result))) {
         return PHPExcel_Calculation_Functions::NaN();
     }
     return $result;
 }
 /**
  * PROPERCASE
  *
  * Converts a string value to upper case.
  *
  * @param	string		$mixedCaseString
  * @return	string
  */
 public static function PROPERCASE($mixedCaseString)
 {
     $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString);
     if (is_bool($mixedCaseString)) {
         $mixedCaseString = $mixedCaseString ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
     }
     return PHPExcel_Shared_String::StrToTitle($mixedCaseString);
 }
Beispiel #15
0
 /**
  * Loads PHPExcel from file into PHPExcel instance
  *
  * @param 	string 		$pFilename
  * @param	PHPExcel	$objPHPExcel
  * @return 	PHPExcel
  * @throws 	PHPExcel_Reader_Exception
  */
 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');
     $zipClass = PHPExcel_Settings::getZipClass();
     $zip = new $zipClass();
     if (!$zip->open($pFilename)) {
         throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file.");
     }
     //		echo '<h1>Meta Information</h1>';
     $xml = simplexml_load_string($zip->getFromName("meta.xml"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
     $namespacesMeta = $xml->getNamespaces(true);
     //		echo '<pre>';
     //		print_r($namespacesMeta);
     //		echo '</pre><hr />';
     $docProps = $objPHPExcel->getProperties();
     $officeProperty = $xml->children($namespacesMeta['office']);
     foreach ($officeProperty 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($propertyValue);
                     break;
                 case 'subject':
                     $docProps->setSubject($propertyValue);
                     break;
                 case 'creator':
                     $docProps->setCreator($propertyValue);
                     $docProps->setLastModifiedBy($propertyValue);
                     break;
                 case 'date':
                     $creationDate = strtotime($propertyValue);
                     $docProps->setCreated($creationDate);
                     $docProps->setModified($creationDate);
                     break;
                 case 'description':
                     $docProps->setDescription($propertyValue);
                     break;
             }
         }
         $officePropertyMeta = array();
         if (isset($namespacesMeta['dc'])) {
             $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
         }
         foreach ($officePropertyMeta as $propertyName => $propertyValue) {
             $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
             $propertyValue = (string) $propertyValue;
             switch ($propertyName) {
                 case 'initial-creator':
                     $docProps->setCreator($propertyValue);
                     break;
                 case 'keyword':
                     $docProps->setKeywords($propertyValue);
                     break;
                 case 'creation-date':
                     $creationDate = strtotime($propertyValue);
                     $docProps->setCreated($creationDate);
                     break;
                 case 'user-defined':
                     $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
                     foreach ($propertyValueAttributes as $key => $value) {
                         if ($key == 'name') {
                             $propertyValueName = (string) $value;
                         } elseif ($key == 'value-type') {
                             switch ($value) {
                                 case 'date':
                                     $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'date');
                                     $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE;
                                     break;
                                 case 'boolean':
                                     $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'bool');
                                     $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN;
                                     break;
                                 case 'float':
                                     $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'r4');
                                     $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT;
                                     break;
                                 default:
                                     $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
                             }
                         }
                     }
                     $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType);
                     break;
             }
         }
     }
     //		echo '<h1>Workbook Content</h1>';
     $xml = simplexml_load_string($zip->getFromName("content.xml"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
     $namespacesContent = $xml->getNamespaces(true);
     //		echo '<pre>';
     //		print_r($namespacesContent);
     //		echo '</pre><hr />';
     $workbook = $xml->children($namespacesContent['office']);
     foreach ($workbook->body->spreadsheet as $workbookData) {
         $workbookData = $workbookData->children($namespacesContent['table']);
         $worksheetID = 0;
         foreach ($workbookData->table as $worksheetDataSet) {
             $worksheetData = $worksheetDataSet->children($namespacesContent['table']);
             //				print_r($worksheetData);
             //				echo '<br />';
             $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);
             //				print_r($worksheetDataAttributes);
             //				echo '<br />';
             if (isset($this->_loadSheetsOnly) && isset($worksheetDataAttributes['name']) && !in_array($worksheetDataAttributes['name'], $this->_loadSheetsOnly)) {
                 continue;
             }
             //				echo '<h2>Worksheet '.$worksheetDataAttributes['name'].'</h2>';
             // Create new Worksheet
             $objPHPExcel->createSheet();
             $objPHPExcel->setActiveSheetIndex($worksheetID);
             if (isset($worksheetDataAttributes['name'])) {
                 $worksheetName = (string) $worksheetDataAttributes['name'];
                 //	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);
             }
             $rowID = 1;
             foreach ($worksheetData as $key => $rowData) {
                 //					echo '<b>'.$key.'</b><br />';
                 switch ($key) {
                     case 'table-header-rows':
                         foreach ($rowData as $key => $cellData) {
                             $rowData = $cellData;
                             break;
                         }
                     case 'table-row':
                         $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']);
                         $rowRepeats = isset($rowDataTableAttributes['number-rows-repeated']) ? $rowDataTableAttributes['number-rows-repeated'] : 1;
                         $columnID = 'A';
                         foreach ($rowData as $key => $cellData) {
                             if ($this->getReadFilter() !== NULL) {
                                 if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
                                     continue;
                                 }
                             }
                             //								echo '<b>'.$columnID.$rowID.'</b><br />';
                             $cellDataText = isset($namespacesContent['text']) ? $cellData->children($namespacesContent['text']) : '';
                             $cellDataOffice = $cellData->children($namespacesContent['office']);
                             $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']);
                             $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']);
                             //								echo 'Office Attributes: ';
                             //								print_r($cellDataOfficeAttributes);
                             //								echo '<br />Table Attributes: ';
                             //								print_r($cellDataTableAttributes);
                             //								echo '<br />Cell Data Text';
                             //								print_r($cellDataText);
                             //								echo '<br />';
                             //
                             $type = $formatting = $hyperlink = null;
                             $hasCalculatedValue = false;
                             $cellDataFormula = '';
                             if (isset($cellDataTableAttributes['formula'])) {
                                 $cellDataFormula = $cellDataTableAttributes['formula'];
                                 $hasCalculatedValue = true;
                             }
                             if (isset($cellDataOffice->annotation)) {
                                 //									echo 'Cell has comment<br />';
                                 $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']);
                                 $textArray = array();
                                 foreach ($annotationText as $t) {
                                     foreach ($t->span as $text) {
                                         $textArray[] = (string) $text;
                                     }
                                 }
                                 $text = implode("\n", $textArray);
                                 //									echo $text,'<br />';
                                 $objPHPExcel->getActiveSheet()->getComment($columnID . $rowID)->setText($this->_parseRichText($text));
                             }
                             if (isset($cellDataText->p)) {
                                 // Consolidate if there are multiple p records (maybe with spans as well)
                                 $dataArray = array();
                                 // Text can have multiple text:p and within those, multiple text:span.
                                 // text:p newlines, but text:span does not.
                                 // Also, here we assume there is no text data is span fields are specified, since
                                 // we have no way of knowing proper positioning anyway.
                                 foreach ($cellDataText->p as $pData) {
                                     if (isset($pData->span)) {
                                         // span sections do not newline, so we just create one large string here
                                         $spanSection = "";
                                         foreach ($pData->span as $spanData) {
                                             $spanSection .= $spanData;
                                         }
                                         array_push($dataArray, $spanSection);
                                     } else {
                                         array_push($dataArray, $pData);
                                     }
                                 }
                                 $allCellDataText = implode($dataArray, "\n");
                                 //									echo 'Value Type is '.$cellDataOfficeAttributes['value-type'].'<br />';
                                 switch ($cellDataOfficeAttributes['value-type']) {
                                     case 'string':
                                         $type = PHPExcel_Cell_DataType::TYPE_STRING;
                                         $dataValue = $allCellDataText;
                                         if (isset($dataValue->a)) {
                                             $dataValue = $dataValue->a;
                                             $cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']);
                                             $hyperlink = $cellXLinkAttributes['href'];
                                         }
                                         break;
                                     case 'boolean':
                                         $type = PHPExcel_Cell_DataType::TYPE_BOOL;
                                         $dataValue = $allCellDataText == 'TRUE' ? True : False;
                                         break;
                                     case 'percentage':
                                         $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                         $dataValue = (double) $cellDataOfficeAttributes['value'];
                                         if (floor($dataValue) == $dataValue) {
                                             $dataValue = (int) $dataValue;
                                         }
                                         $formatting = PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00;
                                         break;
                                     case 'currency':
                                         $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                         $dataValue = (double) $cellDataOfficeAttributes['value'];
                                         if (floor($dataValue) == $dataValue) {
                                             $dataValue = (int) $dataValue;
                                         }
                                         $formatting = PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
                                         break;
                                     case 'float':
                                         $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                         $dataValue = (double) $cellDataOfficeAttributes['value'];
                                         if (floor($dataValue) == $dataValue) {
                                             if ($dataValue == (int) $dataValue) {
                                                 $dataValue = (int) $dataValue;
                                             } else {
                                                 $dataValue = (double) $dataValue;
                                             }
                                         }
                                         break;
                                     case 'date':
                                         $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                         $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT);
                                         $dateObj->setTimeZone($timezoneObj);
                                         list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s'));
                                         $dataValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hour, $minute, $second);
                                         if ($dataValue != floor($dataValue)) {
                                             $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 . ' ' . PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
                                         } else {
                                             $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15;
                                         }
                                         break;
                                     case 'time':
                                         $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                         $dataValue = PHPExcel_Shared_Date::PHPToExcel(strtotime('01-01-1970 ' . implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS'))));
                                         $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
                                         break;
                                 }
                                 //									echo 'Data value is '.$dataValue.'<br />';
                                 //									if ($hyperlink !== NULL) {
                                 //										echo 'Hyperlink is '.$hyperlink.'<br />';
                                 //									}
                             } else {
                                 $type = PHPExcel_Cell_DataType::TYPE_NULL;
                                 $dataValue = NULL;
                             }
                             if ($hasCalculatedValue) {
                                 $type = PHPExcel_Cell_DataType::TYPE_FORMULA;
                                 //									echo 'Formula: ', $cellDataFormula, PHP_EOL;
                                 $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
                                 $temp = explode('"', $cellDataFormula);
                                 $tKey = false;
                                 foreach ($temp as &$value) {
                                     //	Only replace in alternate array entries (i.e. non-quoted blocks)
                                     if ($tKey = !$tKey) {
                                         $value = preg_replace('/\\[([^\\.]+)\\.([^\\.]+):\\.([^\\.]+)\\]/Ui', '$1!$2:$3', $value);
                                         //  Cell range reference in another sheet
                                         $value = preg_replace('/\\[([^\\.]+)\\.([^\\.]+)\\]/Ui', '$1!$2', $value);
                                         //  Cell reference in another sheet
                                         $value = preg_replace('/\\[\\.([^\\.]+):\\.([^\\.]+)\\]/Ui', '$1:$2', $value);
                                         //  Cell range reference
                                         $value = preg_replace('/\\[\\.([^\\.]+)\\]/Ui', '$1', $value);
                                         //  Simple cell reference
                                         $value = PHPExcel_Calculation::_translateSeparator(';', ',', $value, $inBraces);
                                     }
                                 }
                                 unset($value);
                                 //	Then rebuild the formula string
                                 $cellDataFormula = implode('"', $temp);
                                 //									echo 'Adjusted Formula: ', $cellDataFormula, PHP_EOL;
                             }
                             $colRepeats = isset($cellDataTableAttributes['number-columns-repeated']) ? $cellDataTableAttributes['number-columns-repeated'] : 1;
                             if ($type !== NULL) {
                                 for ($i = 0; $i < $colRepeats; ++$i) {
                                     if ($i > 0) {
                                         ++$columnID;
                                     }
                                     if ($type !== PHPExcel_Cell_DataType::TYPE_NULL) {
                                         for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
                                             $rID = $rowID + $rowAdjust;
                                             $objPHPExcel->getActiveSheet()->getCell($columnID . $rID)->setValueExplicit($hasCalculatedValue ? $cellDataFormula : $dataValue, $type);
                                             if ($hasCalculatedValue) {
                                                 //													echo 'Forumla result is '.$dataValue.'<br />';
                                                 $objPHPExcel->getActiveSheet()->getCell($columnID . $rID)->setCalculatedValue($dataValue);
                                             }
                                             if ($formatting !== NULL) {
                                                 $objPHPExcel->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode($formatting);
                                             } else {
                                                 $objPHPExcel->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
                                             }
                                             if ($hyperlink !== NULL) {
                                                 $objPHPExcel->getActiveSheet()->getCell($columnID . $rID)->getHyperlink()->setUrl($hyperlink);
                                             }
                                         }
                                     }
                                 }
                             }
                             //	Merged cells
                             if (isset($cellDataTableAttributes['number-columns-spanned']) || isset($cellDataTableAttributes['number-rows-spanned'])) {
                                 if ($type !== PHPExcel_Cell_DataType::TYPE_NULL || !$this->_readDataOnly) {
                                     $columnTo = $columnID;
                                     if (isset($cellDataTableAttributes['number-columns-spanned'])) {
                                         $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] - 2);
                                     }
                                     $rowTo = $rowID;
                                     if (isset($cellDataTableAttributes['number-rows-spanned'])) {
                                         $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
                                     }
                                     $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
                                     $objPHPExcel->getActiveSheet()->mergeCells($cellRange);
                                 }
                             }
                             ++$columnID;
                         }
                         $rowID += $rowRepeats;
                         break;
                 }
             }
             ++$worksheetID;
         }
     }
     // Return
     return $objPHPExcel;
 }
Beispiel #16
0
 public static function _ifCondition($condition)
 {
     $condition = PHPExcel_Calculation_Functions::flattenSingleValue($condition);
     if (!in_array($condition[0], array('>', '<', '='))) {
         if (!is_numeric($condition)) {
             $condition = PHPExcel_Calculation::_wrapResult(strtoupper($condition));
         }
         return '=' . $condition;
     } else {
         preg_match('/([<>=]+)(.*)/', $condition, $matches);
         list(, $operator, $operand) = $matches;
         if (!is_numeric($operand)) {
             $operand = PHPExcel_Calculation::_wrapResult(strtoupper($operand));
         }
         return $operator . $operand;
     }
 }
Beispiel #17
0
 /**
  *	Apply the AutoFilter rules to the AutoFilter Range
  *
  *	@throws	PHPExcel_Exception
  *	@return PHPExcel_Worksheet_AutoFilter
  */
 public function showHideRows()
 {
     list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range);
     //	The heading row should always be visible
     //		echo 'AutoFilter Heading Row ',$rangeStart[1],' is always SHOWN',PHP_EOL;
     $this->_workSheet->getRowDimension($rangeStart[1])->setVisible(TRUE);
     $columnFilterTests = array();
     foreach ($this->_columns as $columnID => $filterColumn) {
         $rules = $filterColumn->getRules();
         switch ($filterColumn->getFilterType()) {
             case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER:
                 $ruleValues = array();
                 //	Build a list of the filter value selections
                 foreach ($rules as $rule) {
                     $ruleType = $rule->getRuleType();
                     $ruleValues[] = $rule->getValue();
                 }
                 //	Test if we want to include blanks in our filter criteria
                 $blanks = FALSE;
                 $ruleDataSet = array_filter($ruleValues);
                 if (count($ruleValues) != count($ruleDataSet)) {
                     $blanks = TRUE;
                 }
                 if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER) {
                     //	Filter on absolute values
                     $columnFilterTests[$columnID] = array('method' => '_filterTestInSimpleDataSet', 'arguments' => array('filterValues' => $ruleDataSet, 'blanks' => $blanks));
                 } else {
                     //	Filter on date group values
                     $arguments = array('date' => array(), 'time' => array(), 'dateTime' => array());
                     foreach ($ruleDataSet as $ruleValue) {
                         $date = $time = '';
                         if (isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]) && $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') {
                             $date .= sprintf('%04d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]);
                         }
                         if (isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]) && $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') {
                             $date .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]);
                         }
                         if (isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]) && $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') {
                             $date .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]);
                         }
                         if (isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]) && $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') {
                             $time .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]);
                         }
                         if (isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]) && $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') {
                             $time .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]);
                         }
                         if (isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]) && $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') {
                             $time .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]);
                         }
                         $dateTime = $date . $time;
                         $arguments['date'][] = $date;
                         $arguments['time'][] = $time;
                         $arguments['dateTime'][] = $dateTime;
                     }
                     //	Remove empty elements
                     $arguments['date'] = array_filter($arguments['date']);
                     $arguments['time'] = array_filter($arguments['time']);
                     $arguments['dateTime'] = array_filter($arguments['dateTime']);
                     $columnFilterTests[$columnID] = array('method' => '_filterTestInDateGroupSet', 'arguments' => array('filterValues' => $arguments, 'blanks' => $blanks));
                 }
                 break;
             case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER:
                 $customRuleForBlanks = FALSE;
                 $ruleValues = array();
                 //	Build a list of the filter value selections
                 foreach ($rules as $rule) {
                     $ruleType = $rule->getRuleType();
                     $ruleValue = $rule->getValue();
                     if (!is_numeric($ruleValue)) {
                         //	Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards
                         $ruleValue = preg_quote($ruleValue);
                         $ruleValue = str_replace(self::$_fromReplace, self::$_toReplace, $ruleValue);
                         if (trim($ruleValue) == '') {
                             $customRuleForBlanks = TRUE;
                             $ruleValue = trim($ruleValue);
                         }
                     }
                     $ruleValues[] = array('operator' => $rule->getOperator(), 'value' => $ruleValue);
                 }
                 $join = $filterColumn->getJoin();
                 $columnFilterTests[$columnID] = array('method' => '_filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks));
                 break;
             case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER:
                 $ruleValues = array();
                 foreach ($rules as $rule) {
                     //	We should only ever have one Dynamic Filter Rule anyway
                     $dynamicRuleType = $rule->getGrouping();
                     if ($dynamicRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE || $dynamicRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) {
                         //	Number (Average) based
                         //	Calculate the average
                         $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')';
                         $average = PHPExcel_Calculation::getInstance()->calculateFormula($averageFormula, NULL, $this->_workSheet->getCell('A1'));
                         //	Set above/below rule based on greaterThan or LessTan
                         $operator = $dynamicRuleType === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
                         $ruleValues[] = array('operator' => $operator, 'value' => $average);
                         $columnFilterTests[$columnID] = array('method' => '_filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR));
                     } else {
                         //	Date based
                         if ($dynamicRuleType[0] == 'M' || $dynamicRuleType[0] == 'Q') {
                             //	Month or Quarter
                             sscanf($dynamicRuleType, '%[A-Z]%d', $periodType, $period);
                             if ($periodType == 'M') {
                                 $ruleValues = array($period);
                             } else {
                                 --$period;
                                 $periodEnd = (1 + $period) * 3;
                                 $periodStart = 1 + $period * 3;
                                 $ruleValues = range($periodStart, periodEnd);
                             }
                             $columnFilterTests[$columnID] = array('method' => '_filterTestInPeriodDateSet', 'arguments' => $ruleValues);
                             $filterColumn->setAttributes(array());
                         } else {
                             //	Date Range
                             $columnFilterTests[$columnID] = $this->_dynamicFilterDateRange($dynamicRuleType, $filterColumn);
                             break;
                         }
                     }
                 }
                 break;
             case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER:
                 $ruleValues = array();
                 $dataRowCount = $rangeEnd[1] - $rangeStart[1];
                 foreach ($rules as $rule) {
                     //	We should only ever have one Dynamic Filter Rule anyway
                     $toptenRuleType = $rule->getGrouping();
                     $ruleValue = $rule->getValue();
                     $ruleOperator = $rule->getOperator();
                 }
                 if ($ruleOperator === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) {
                     $ruleValue = floor($ruleValue * ($dataRowCount / 100));
                 }
                 if ($ruleValue < 1) {
                     $ruleValue = 1;
                 }
                 if ($ruleValue > 500) {
                     $ruleValue = 500;
                 }
                 $maxVal = $this->_calculateTopTenValue($columnID, $rangeStart[1] + 1, $rangeEnd[1], $toptenRuleType, $ruleValue);
                 $operator = $toptenRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL;
                 $ruleValues[] = array('operator' => $operator, 'value' => $maxVal);
                 $columnFilterTests[$columnID] = array('method' => '_filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR));
                 $filterColumn->setAttributes(array('maxVal' => $maxVal));
                 break;
         }
     }
     //		echo 'Column Filter Test CRITERIA',PHP_EOL;
     //		var_dump($columnFilterTests);
     //
     //	Execute the column tests for each row in the autoFilter range to determine show/hide,
     for ($row = $rangeStart[1] + 1; $row <= $rangeEnd[1]; ++$row) {
         //			echo 'Testing Row = ',$row,PHP_EOL;
         $result = TRUE;
         foreach ($columnFilterTests as $columnID => $columnFilterTest) {
             //				echo 'Testing cell ',$columnID.$row,PHP_EOL;
             $cellValue = $this->_workSheet->getCell($columnID . $row)->getCalculatedValue();
             //				echo 'Value is ',$cellValue,PHP_EOL;
             //	Execute the filter test
             $result = $result && call_user_func_array(array('PHPExcel_Worksheet_AutoFilter', $columnFilterTest['method']), array($cellValue, $columnFilterTest['arguments']));
             //				echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL;
             //	If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests
             if (!$result) {
                 break;
             }
         }
         //	Set show/hide for the row based on the result of the autoFilter result
         //			echo (($result) ? 'SHOW' : 'HIDE'),PHP_EOL;
         $this->_workSheet->getRowDimension($row)->setVisible($result);
     }
     return $this;
 }
Beispiel #18
0
 /**
  * Loads PHPExcel from file into PHPExcel instance
  *
  * @param 	string 		$pFilename
  * @param	PHPExcel	$objPHPExcel
  * @return 	PHPExcel
  * @throws 	Exception
  */
 public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
 {
     // Check if file exists
     if (!file_exists($pFilename)) {
         throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
     }
     $timezoneObj = new DateTimeZone('Europe/London');
     $GMT = new DateTimeZone('UTC');
     $zip = new ZipArchive();
     if ($zip->open($pFilename) === true) {
         //			echo '<h1>Meta Information</h1>';
         $xml = simplexml_load_string($zip->getFromName("meta.xml"));
         $namespacesMeta = $xml->getNamespaces(true);
         //			echo '<pre>';
         //			print_r($namespacesMeta);
         //			echo '</pre><hr />';
         $docProps = $objPHPExcel->getProperties();
         $officeProperty = $xml->children($namespacesMeta['office']);
         foreach ($officeProperty as $officePropertyData) {
             $officePropertyDC = array();
             if (isset($namespacesMeta['dc'])) {
                 $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
             }
             foreach ($officePropertyDC as $propertyName => $propertyValue) {
                 switch ($propertyName) {
                     case 'title':
                         $docProps->setTitle($propertyValue);
                         break;
                     case 'subject':
                         $docProps->setSubject($propertyValue);
                         break;
                     case 'creator':
                         $docProps->setCreator($propertyValue);
                         $docProps->setLastModifiedBy($propertyValue);
                         break;
                     case 'date':
                         $creationDate = strtotime($propertyValue);
                         $docProps->setCreated($creationDate);
                         $docProps->setModified($creationDate);
                         break;
                     case 'description':
                         $docProps->setDescription($propertyValue);
                         break;
                 }
             }
             $officePropertyMeta = array();
             if (isset($namespacesMeta['dc'])) {
                 $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
             }
             foreach ($officePropertyMeta as $propertyName => $propertyValue) {
                 $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
                 switch ($propertyName) {
                     case 'initial-creator':
                         $docProps->setCreator($propertyValue);
                         break;
                     case 'keyword':
                         $docProps->setKeywords($propertyValue);
                         break;
                     case 'creation-date':
                         $creationDate = strtotime($propertyValue);
                         $docProps->setCreated($creationDate);
                         break;
                     case 'user-defined':
                         $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
                         foreach ($propertyValueAttributes as $key => $value) {
                             if ($key == 'name') {
                                 $propertyValueName = (string) $value;
                             } elseif ($key == 'value-type') {
                                 switch ($value) {
                                     case 'date':
                                         $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'date');
                                         $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE;
                                         break;
                                     case 'boolean':
                                         $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'bool');
                                         $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN;
                                         break;
                                     case 'float':
                                         $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'r4');
                                         $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT;
                                         break;
                                     default:
                                         $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
                                 }
                             }
                         }
                         $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType);
                         break;
                 }
             }
         }
         //			echo '<h1>Workbook Content</h1>';
         $xml = simplexml_load_string($zip->getFromName("content.xml"));
         $namespacesContent = $xml->getNamespaces(true);
         //			echo '<pre>';
         //			print_r($namespacesContent);
         //			echo '</pre><hr />';
         $workbook = $xml->children($namespacesContent['office']);
         foreach ($workbook->body->spreadsheet as $workbookData) {
             $workbookData = $workbookData->children($namespacesContent['table']);
             $worksheetID = 0;
             foreach ($workbookData->table as $worksheetDataSet) {
                 $worksheetData = $worksheetDataSet->children($namespacesContent['table']);
                 //					print_r($worksheetData);
                 //					echo '<br />';
                 $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);
                 //					print_r($worksheetDataAttributes);
                 //					echo '<br />';
                 if (isset($this->_loadSheetsOnly) && isset($worksheetDataAttributes['name']) && !in_array($worksheetDataAttributes['name'], $this->_loadSheetsOnly)) {
                     continue;
                 }
                 //					echo '<h2>Worksheet '.$worksheetDataAttributes['name'].'</h2>';
                 // Create new Worksheet
                 $objPHPExcel->createSheet();
                 $objPHPExcel->setActiveSheetIndex($worksheetID);
                 if (isset($worksheetDataAttributes['name'])) {
                     $worksheetName = (string) $worksheetDataAttributes['name'];
                     $objPHPExcel->getActiveSheet()->setTitle($worksheetName);
                 }
                 $rowID = 1;
                 foreach ($worksheetData as $key => $rowData) {
                     //						echo '<b>'.$key.'</b><br />';
                     switch ($key) {
                         case 'table-header-rows':
                             foreach ($rowData as $key => $cellData) {
                                 $rowData = $cellData;
                                 break;
                             }
                         case 'table-row':
                             $columnID = 'A';
                             foreach ($rowData as $key => $cellData) {
                                 if (!is_null($this->getReadFilter())) {
                                     if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
                                         continue;
                                     }
                                 }
                                 //									echo '<b>'.$columnID.$rowID.'</b><br />';
                                 $cellDataText = $cellData->children($namespacesContent['text']);
                                 $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']);
                                 $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']);
                                 //									echo 'Office Attributes: ';
                                 //									print_r($cellDataOfficeAttributes);
                                 //									echo '<br />Table Attributes: ';
                                 //									print_r($cellDataTableAttributes);
                                 //									echo '<br />Cell Data Text';
                                 //									print_r($cellDataText);
                                 //									echo '<br />';
                                 //
                                 $type = $formatting = $hyperlink = null;
                                 $hasCalculatedValue = false;
                                 $cellDataFormula = '';
                                 if (isset($cellDataTableAttributes['formula'])) {
                                     $cellDataFormula = $cellDataTableAttributes['formula'];
                                     $hasCalculatedValue = true;
                                 }
                                 if (isset($cellDataText->p)) {
                                     //										echo 'Value Type is '.$cellDataOfficeAttributes['value-type'].'<br />';
                                     switch ($cellDataOfficeAttributes['value-type']) {
                                         case 'string':
                                             $type = PHPExcel_Cell_DataType::TYPE_STRING;
                                             $dataValue = $cellDataText->p;
                                             if (isset($dataValue->a)) {
                                                 $dataValue = $dataValue->a;
                                                 $cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']);
                                                 $hyperlink = $cellXLinkAttributes['href'];
                                             }
                                             break;
                                         case 'boolean':
                                             $type = PHPExcel_Cell_DataType::TYPE_BOOL;
                                             $dataValue = $cellDataText->p == 'TRUE' ? True : False;
                                             break;
                                         case 'float':
                                             $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                             $dataValue = (double) $cellDataOfficeAttributes['value'];
                                             if (floor($dataValue) == $dataValue) {
                                                 $dataValue = (int) $dataValue;
                                             }
                                             break;
                                         case 'date':
                                             $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                             $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT);
                                             $dateObj->setTimeZone($timezoneObj);
                                             list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s'));
                                             $dataValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hour, $minute, $second);
                                             if ($dataValue != floor($dataValue)) {
                                                 $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 . ' ' . PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
                                             } else {
                                                 $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15;
                                             }
                                             break;
                                         case 'time':
                                             $type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                                             $dataValue = PHPExcel_Shared_Date::PHPToExcel(strtotime('01-01-1970 ' . implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS'))));
                                             $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
                                             break;
                                     }
                                     //										echo 'Data value is '.$dataValue.'<br />';
                                     //										if (!is_null($hyperlink)) {
                                     //											echo 'Hyperlink is '.$hyperlink.'<br />';
                                     //										}
                                 }
                                 if ($hasCalculatedValue) {
                                     $type = PHPExcel_Cell_DataType::TYPE_FORMULA;
                                     //										echo 'Formula: '.$cellDataFormula.'<br />';
                                     $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
                                     $temp = explode('"', $cellDataFormula);
                                     foreach ($temp as $key => &$value) {
                                         //	Only replace in alternate array entries (i.e. non-quoted blocks)
                                         if ($key % 2 == 0) {
                                             $value = preg_replace('/\\[\\.(.*):\\.(.*)\\]/Ui', '$1:$2', $value);
                                             $value = preg_replace('/\\[\\.(.*)\\]/Ui', '$1', $value);
                                             $value = PHPExcel_Calculation::_translateSeparator(';', ',', $value, $inBraces);
                                         }
                                     }
                                     unset($value);
                                     //	Then rebuild the formula string
                                     $cellDataFormula = implode('"', $temp);
                                     //										echo 'Adjusted Formula: '.$cellDataFormula.'<br />';
                                 }
                                 if (!is_null($type)) {
                                     $objPHPExcel->getActiveSheet()->getCell($columnID . $rowID)->setValueExplicit($hasCalculatedValue ? $cellDataFormula : $dataValue, $type);
                                     if ($hasCalculatedValue) {
                                         //											echo 'Forumla result is '.$dataValue.'<br />';
                                         $objPHPExcel->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($dataValue);
                                     }
                                     if ($cellDataOfficeAttributes['value-type'] == 'date' || $cellDataOfficeAttributes['value-type'] == 'time') {
                                         $objPHPExcel->getActiveSheet()->getStyle($columnID . $rowID)->getNumberFormat()->setFormatCode($formatting);
                                     }
                                     if (!is_null($hyperlink)) {
                                         $objPHPExcel->getActiveSheet()->getCell($columnID . $rowID)->getHyperlink()->setUrl($hyperlink);
                                     }
                                 }
                                 //	Merged cells
                                 if (isset($cellDataTableAttributes['number-columns-spanned']) || isset($cellDataTableAttributes['number-rows-spanned'])) {
                                     $columnTo = $columnID;
                                     if (isset($cellDataTableAttributes['number-columns-spanned'])) {
                                         $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] - 2);
                                     }
                                     $rowTo = $rowID;
                                     if (isset($cellDataTableAttributes['number-rows-spanned'])) {
                                         $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
                                     }
                                     $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
                                     $objPHPExcel->getActiveSheet()->mergeCells($cellRange);
                                 }
                                 if (isset($cellDataTableAttributes['number-columns-repeated'])) {
                                     //										echo 'Repeated '.$cellDataTableAttributes['number-columns-repeated'].' times<br />';
                                     $columnID = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-repeated'] - 2);
                                 }
                                 ++$columnID;
                             }
                             ++$rowID;
                             break;
                     }
                 }
                 ++$worksheetID;
             }
         }
     }
     // Return
     return $objPHPExcel;
 }
 /**
  * __filter
  *
  * Parses the selection criteria, extracts the database rows that match those criteria, and
  * returns that subset of rows.
  *
  * @access    private
  * @param    mixed[] $database The range of cells that makes up the list or database.
  *                                        A database is a list of related data in which rows of related
  *                                        information are records, and columns of data are fields. The
  *                                        first row of the list contains labels for each column.
  * @param    mixed[] $criteria The range of cells that contains the conditions you specify.
  *                                        You can use any range for the criteria argument, as long as it
  *                                        includes at least one column label and at least one cell below
  *                                        the column label in which you specify a condition for the
  *                                        column.
  * @return    array of mixed
  *
  */
 private static function __filter($database, $criteria)
 {
     $fieldNames = array_shift($database);
     $criteriaNames = array_shift($criteria);
     //	Convert the criteria into a set of AND/OR conditions with [:placeholders]
     $testConditions = $testValues = array();
     $testConditionsCount = 0;
     foreach ($criteriaNames as $key => $criteriaName) {
         $testCondition = array();
         $testConditionCount = 0;
         foreach ($criteria as $row => $criterion) {
             if ($criterion[$key] > '') {
                 $testCondition[] = '[:' . $criteriaName . ']' . PHPExcel_Calculation_Functions::_ifCondition($criterion[$key]);
                 $testConditionCount++;
             }
         }
         if ($testConditionCount > 1) {
             $testConditions[] = 'OR(' . implode(',', $testCondition) . ')';
             $testConditionsCount++;
         } elseif ($testConditionCount == 1) {
             $testConditions[] = $testCondition[0];
             $testConditionsCount++;
         }
     }
     if ($testConditionsCount > 1) {
         $testConditionSet = 'AND(' . implode(',', $testConditions) . ')';
     } elseif ($testConditionsCount == 1) {
         $testConditionSet = $testConditions[0];
     }
     //	Loop through each row of the database
     foreach ($database as $dataRow => $dataValues) {
         //	Substitute actual values from the database row for our [:placeholders]
         $testConditionList = $testConditionSet;
         foreach ($criteriaNames as $key => $criteriaName) {
             $k = array_search($criteriaName, $fieldNames);
             if (isset($dataValues[$k])) {
                 $dataValue = $dataValues[$k];
                 $dataValue = is_string($dataValue) ? PHPExcel_Calculation::_wrapResult(strtoupper($dataValue)) : $dataValue;
                 $testConditionList = str_replace('[:' . $criteriaName . ']', $dataValue, $testConditionList);
             }
         }
         //	evaluate the criteria against the row data
         $result = PHPExcel_Calculation::getInstance()->_calculateFormulaValue('=' . $testConditionList);
         //	If the row failed to meet the criteria, remove it from the database
         if (!$result) {
             unset($database[$dataRow]);
         }
     }
     return $database;
 }
Beispiel #20
0
 /**
  *    Get calculated cell value
  *
  * @deprecated        Since version 1.7.8 for planned changes to cell for array formula handling
  *
  * @param    boolean $resetLog Whether the calculation engine logger should be reset or not
  *
  * @return    mixed
  * @throws    PHPExcel_Exception
  */
 public function getCalculatedValue($resetLog = true)
 {
     //echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().PHP_EOL;
     if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) {
         try {
             //echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL;
             $result = PHPExcel_Calculation::getInstance($this->getWorksheet()->getParent())->calculateCellValue($this, $resetLog);
             //echo $this->getCoordinate().' calculation result is '.$result.PHP_EOL;
             //	We don't yet handle array returns
             if (is_array($result)) {
                 while (is_array($result)) {
                     $result = array_pop($result);
                 }
             }
         } catch (PHPExcel_Exception $ex) {
             if ($ex->getMessage() === 'Unable to access External Workbook' && $this->_calculatedValue !== null) {
                 //echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
                 return $this->_calculatedValue;
                 // Fallback for calculations referencing external files.
             }
             //echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL;
             $result = '#N/A';
             throw new PHPExcel_Calculation_Exception($this->getWorksheet()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage());
         }
         if ($result === '#Not Yet Implemented') {
             //echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
             return $this->_calculatedValue;
             // Fallback if calculation engine does not support the formula.
         }
         //echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL;
         return $result;
     } elseif ($this->_value instanceof PHPExcel_RichText) {
         //		echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->_value.'<br />';
         return $this->_value->getPlainText();
     }
     //		echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'<br />';
     return $this->_value;
 }
Beispiel #21
0
 /**
  *	SUMIF
  *
  *	Counts the number of cells that contain numbers within the list of arguments
  *
  *	Excel Function:
  *		SUMIF(value1[,value2[, ...]],condition)
  *
  *	@access	public
  *	@category Mathematical and Trigonometric Functions
  *	@param	mixed		$arg,...		Data values
  *	@param	string		$condition		The criteria that defines which cells will be summed.
  *	@return	float
  */
 public static function SUMIF($aArgs, $condition, $sumArgs = array())
 {
     // Return value
     $returnValue = 0;
     $aArgs = self::flattenArray($aArgs);
     $sumArgs = self::flattenArray($sumArgs);
     if (count($sumArgs) == 0) {
         $sumArgs = $aArgs;
     }
     if (!in_array($condition[0], array('>', '<', '='))) {
         if (!is_numeric($condition)) {
             $condition = PHPExcel_Calculation::_wrapResult(strtoupper($condition));
         }
         $condition = '=' . $condition;
     }
     // Loop through arguments
     foreach ($aArgs as $key => $arg) {
         if (!is_numeric($arg)) {
             $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg));
         }
         $testCondition = '=' . $arg . $condition;
         if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
             // Is it a value within our criteria
             $returnValue += $sumArgs[$key];
         }
     }
     // Return
     return $returnValue;
 }
Beispiel #22
0
 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    1.8.0, 2014-03-02
 */
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
define('EOL', PHP_SAPI == 'cli' ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../PHPExcel/PHPExcel.php';
// List functions
echo date('H:i:s'), " List implemented functions", EOL;
$objCalc = PHPExcel_Calculation::getInstance();
print_r($objCalc->listFunctionNames());
// Create new PHPExcel object
echo date('H:i:s'), " Create new PHPExcel object", EOL;
$objPHPExcel = new PHPExcel();
// Add some data, we will use some formulas here
echo date('H:i:s'), " Add some data and formulas", EOL;
$objPHPExcel->getActiveSheet()->setCellValue('A14', 'Count:')->setCellValue('A15', 'Sum:')->setCellValue('A16', 'Max:')->setCellValue('A17', 'Min:')->setCellValue('A18', 'Average:')->setCellValue('A19', 'Median:')->setCellValue('A20', 'Mode:');
$objPHPExcel->getActiveSheet()->setCellValue('A22', 'CountA:')->setCellValue('A23', 'MaxA:')->setCellValue('A24', 'MinA:');
$objPHPExcel->getActiveSheet()->setCellValue('A26', 'StDev:')->setCellValue('A27', 'StDevA:')->setCellValue('A28', 'StDevP:')->setCellValue('A29', 'StDevPA:');
$objPHPExcel->getActiveSheet()->setCellValue('A31', 'DevSq:')->setCellValue('A32', 'Var:')->setCellValue('A33', 'VarA:')->setCellValue('A34', 'VarP:')->setCellValue('A35', 'VarPA:');
$objPHPExcel->getActiveSheet()->setCellValue('A37', 'Date:');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Range 1')->setCellValue('B2', 2)->setCellValue('B3', 8)->setCellValue('B4', 10)->setCellValue('B5', True)->setCellValue('B6', False)->setCellValue('B7', 'Text String')->setCellValue('B9', '22')->setCellValue('B10', 4)->setCellValue('B11', 6)->setCellValue('B12', 12);
$objPHPExcel->getActiveSheet()->setCellValue('B14', '=COUNT(B2:B12)')->setCellValue('B15', '=SUM(B2:B12)')->setCellValue('B16', '=MAX(B2:B12)')->setCellValue('B17', '=MIN(B2:B12)')->setCellValue('B18', '=AVERAGE(B2:B12)')->setCellValue('B19', '=MEDIAN(B2:B12)')->setCellValue('B20', '=MODE(B2:B12)');
$objPHPExcel->getActiveSheet()->setCellValue('B22', '=COUNTA(B2:B12)')->setCellValue('B23', '=MAXA(B2:B12)')->setCellValue('B24', '=MINA(B2:B12)');
$objPHPExcel->getActiveSheet()->setCellValue('B26', '=STDEV(B2:B12)')->setCellValue('B27', '=STDEVA(B2:B12)')->setCellValue('B28', '=STDEVP(B2:B12)')->setCellValue('B29', '=STDEVPA(B2:B12)');
Beispiel #23
0
 /**
  * Update references within formulas
  *
  * @param	string	$pFormula	Formula to update
  * @param	int		$pBefore	Insert before this one
  * @param	int		$pNumCols	Number of columns to insert
  * @param	int		$pNumRows	Number of rows to insert
  * @return	string	Updated formula
  * @throws	Exception
  */
 public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
 {
     // Parse formula into a tree of tokens
     $tokenisedFormula = PHPExcel_Calculation::getInstance()->parseFormula($pFormula);
     $newCellTokens = $cellTokens = array();
     $adjustCount = 0;
     //	Build the translation table of cell tokens
     foreach ($tokenisedFormula as $token) {
         $token = $token['value'];
         if (preg_match('/^' . PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $token, $matches)) {
             list($column, $row) = PHPExcel_Cell::coordinateFromString($token);
             //	Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
             $column = PHPExcel_Cell::columnIndexFromString($column) + 100000;
             $row += 10000000;
             $cellIndex = $column . $row;
             if (!isset($cellTokens[$cellIndex])) {
                 $newReference = $this->updateCellReference($token, $pBefore, $pNumCols, $pNumRows);
                 if ($newReference !== $token) {
                     $newCellTokens[$cellIndex] = preg_quote($newReference);
                     $cellTokens[$cellIndex] = '/(?<![A-Z])' . preg_quote($token) . '(?!\\d)/i';
                     ++$adjustCount;
                 }
             }
         }
     }
     if ($adjustCount == 0) {
         return $pFormula;
     }
     krsort($cellTokens);
     krsort($newCellTokens);
     //	Update cell references in the formula
     $formulaBlocks = explode('"', $pFormula);
     foreach ($formulaBlocks as $i => &$formulaBlock) {
         //	Only count/replace in alternate array entries
         if ($i % 2 == 0) {
             $formulaBlock = preg_replace($cellTokens, $newCellTokens, $formulaBlock);
         }
     }
     unset($formulaBlock);
     //	Then rebuild the formula string
     return implode('"', $formulaBlocks);
 }
Beispiel #24
0
 /**
  * Save PHPExcel to file
  *
  * @param	string		$pFilename
  * @throws	PHPExcel_Writer_Exception
  */
 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, "");
         //	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, "");
     }
     //	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);
 }
Beispiel #25
0
 /**
  * Code to execute when this worksheet is unset()
  *
  */
 public function __destruct()
 {
     PHPExcel_Calculation::unsetInstance($this);
     $this->disconnectWorksheets();
 }
Beispiel #26
0
 /**
  * Loads PHPExcel from file into PHPExcel instance
  *
  * @param 	string 		$pFilename
  * @param	PHPExcel	$objPHPExcel
  * @return 	PHPExcel
  * @throws 	Exception
  */
 public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
 {
     // Check if file exists
     if (!file_exists($pFilename)) {
         throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
     }
     // Create new PHPExcel
     while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
         $objPHPExcel->createSheet();
     }
     $objPHPExcel->setActiveSheetIndex($this->_sheetIndex);
     $fromFormats = array('\\-', '\\ ');
     $toFormats = array('-', ' ');
     // Open file
     $fileHandle = fopen($pFilename, 'r');
     if ($fileHandle === false) {
         throw new Exception("Could not open file {$pFilename} for reading.");
     }
     // Loop through file
     $rowData = array();
     $column = $row = '';
     // loop through one row (line) at a time in the file
     while (($rowData = fgets($fileHandle)) !== FALSE) {
         // convert SYLK encoded $rowData to UTF-8
         $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
         // explode each row at semicolons while taking into account that literal semicolon (;)
         // is escaped like this (;;)
         $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
         $dataType = array_shift($rowData);
         //	Read shared styles
         if ($dataType == 'P') {
             $formatArray = array();
             foreach ($rowData as $rowDatum) {
                 switch ($rowDatum[0]) {
                     case 'P':
                         $formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));
                         break;
                     case 'E':
                     case 'F':
                         $formatArray['font']['name'] = substr($rowDatum, 1);
                         break;
                     case 'L':
                         $formatArray['font']['size'] = substr($rowDatum, 1);
                         break;
                     case 'S':
                         $styleSettings = substr($rowDatum, 1);
                         for ($i = 0; $i < strlen($styleSettings); ++$i) {
                             switch ($styleSettings[$i]) {
                                 case 'I':
                                     $formatArray['font']['italic'] = true;
                                     break;
                                 case 'D':
                                     $formatArray['font']['bold'] = true;
                                     break;
                                 case 'T':
                                     $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                                 case 'B':
                                     $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                                 case 'L':
                                     $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                                 case 'R':
                                     $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                             }
                         }
                         break;
                 }
             }
             $this->_formats['P' . $this->_format++] = $formatArray;
             //	Read cell value data
         } elseif ($dataType == 'C') {
             $hasCalculatedValue = false;
             $cellData = $cellDataFormula = '';
             foreach ($rowData as $rowDatum) {
                 switch ($rowDatum[0]) {
                     case 'C':
                     case 'X':
                         $column = substr($rowDatum, 1);
                         break;
                     case 'R':
                     case 'Y':
                         $row = substr($rowDatum, 1);
                         break;
                     case 'K':
                         $cellData = substr($rowDatum, 1);
                         break;
                     case 'E':
                         $cellDataFormula = '=' . substr($rowDatum, 1);
                         //	Convert R1C1 style references to A1 style references (but only when not quoted)
                         $temp = explode('"', $cellDataFormula);
                         foreach ($temp as $key => &$value) {
                             //	Only count/replace in alternate array entries
                             if ($key % 2 == 0) {
                                 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 = $row;
                                     }
                                     //	Bracketed R references are relative to the current row
                                     if ($rowReference[0] == '[') {
                                         $rowReference = $row + trim($rowReference, '[]');
                                     }
                                     $columnReference = $cellReference[4][0];
                                     //	Empty C reference is the current column
                                     if ($columnReference == '') {
                                         $columnReference = $column;
                                     }
                                     //	Bracketed C references are relative to the current column
                                     if ($columnReference[0] == '[') {
                                         $columnReference = $column + 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);
                         $hasCalculatedValue = true;
                         break;
                 }
             }
             $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column - 1);
             $cellData = PHPExcel_Calculation::_unwrapResult($cellData);
             // Set cell value
             $objPHPExcel->getActiveSheet()->getCell($columnLetter . $row)->setValue($hasCalculatedValue ? $cellDataFormula : $cellData);
             if ($hasCalculatedValue) {
                 $cellData = PHPExcel_Calculation::_unwrapResult($cellData);
                 $objPHPExcel->getActiveSheet()->getCell($columnLetter . $row)->setCalculatedValue($cellData);
             }
             //	Read cell formatting
         } elseif ($dataType == 'F') {
             $formatStyle = $columnWidth = $styleSettings = '';
             $styleData = array();
             foreach ($rowData as $rowDatum) {
                 switch ($rowDatum[0]) {
                     case 'C':
                     case 'X':
                         $column = substr($rowDatum, 1);
                         break;
                     case 'R':
                     case 'Y':
                         $row = substr($rowDatum, 1);
                         break;
                     case 'P':
                         $formatStyle = $rowDatum;
                         break;
                     case 'W':
                         list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1));
                         break;
                     case 'S':
                         $styleSettings = substr($rowDatum, 1);
                         for ($i = 0; $i < strlen($styleSettings); ++$i) {
                             switch ($styleSettings[$i]) {
                                 case 'I':
                                     $styleData['font']['italic'] = true;
                                     break;
                                 case 'D':
                                     $styleData['font']['bold'] = true;
                                     break;
                                 case 'T':
                                     $styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                                 case 'B':
                                     $styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                                 case 'L':
                                     $styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                                 case 'R':
                                     $styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
                                     break;
                             }
                         }
                         break;
                 }
             }
             if ($formatStyle > '' && $column > '' && $row > '') {
                 $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column - 1);
                 $objPHPExcel->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->_formats[$formatStyle]);
             }
             if (count($styleData) > 0 && $column > '' && $row > '') {
                 $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column - 1);
                 $objPHPExcel->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData);
             }
             if ($columnWidth > '') {
                 if ($startCol == $endCol) {
                     $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol - 1);
                     $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
                 } else {
                     $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol - 1);
                     $endCol = PHPExcel_Cell::stringFromColumnIndex($endCol - 1);
                     $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
                     do {
                         $objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
                     } while ($startCol != $endCol);
                 }
             }
         } else {
             foreach ($rowData as $rowDatum) {
                 switch ($rowDatum[0]) {
                     case 'C':
                     case 'X':
                         $column = substr($rowDatum, 1);
                         break;
                     case 'R':
                     case 'Y':
                         $row = substr($rowDatum, 1);
                         break;
                 }
             }
         }
     }
     // Close file
     fclose($fileHandle);
     // Return
     return $objPHPExcel;
 }
Beispiel #27
0
 /**
  * Set title
  *
  * @param string $pValue String containing the dimension of this worksheet
  * @param string $updateFormulaCellReferences boolean Flag indicating whether cell references in formulae should
  *        	be updated to reflect the new sheet name.
  *          This should be left as the default true, unless you are
  *          certain that no formula cells on any worksheet contain
  *          references to this worksheet
  * @return PHPExcel_Worksheet
  */
 public function setTitle($pValue = 'Worksheet', $updateFormulaCellReferences = true)
 {
     // Is this a 'rename' or not?
     if ($this->getTitle() == $pValue) {
         return $this;
     }
     // Syntax check
     self::_checkSheetTitle($pValue);
     // Old title
     $oldTitle = $this->getTitle();
     if ($this->_parent) {
         // Is there already such sheet name?
         if ($this->_parent->sheetNameExists($pValue)) {
             // Use name, but append with lowest possible integer
             if (PHPExcel_Shared_String::CountCharacters($pValue) > 29) {
                 $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 29);
             }
             $i = 1;
             while ($this->_parent->sheetNameExists($pValue . ' ' . $i)) {
                 ++$i;
                 if ($i == 10) {
                     if (PHPExcel_Shared_String::CountCharacters($pValue) > 28) {
                         $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 28);
                     }
                 } elseif ($i == 100) {
                     if (PHPExcel_Shared_String::CountCharacters($pValue) > 27) {
                         $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 27);
                     }
                 }
             }
             $altTitle = $pValue . ' ' . $i;
             return $this->setTitle($altTitle, $updateFormulaCellReferences);
         }
     }
     // Set title
     $this->_title = $pValue;
     $this->_dirty = true;
     if ($this->_parent) {
         // New title
         $newTitle = $this->getTitle();
         PHPExcel_Calculation::getInstance($this->_parent)->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
         if ($updateFormulaCellReferences) {
             PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->_parent, $oldTitle, $newTitle);
         }
     }
     return $this;
 }
Beispiel #28
0
 /**
  *	OFFSET
  *
  *	Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
  *	The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
  *	the number of columns to be returned.
  *
  *	@param	cellAddress		The reference from which you want to base the offset. Reference must refer to a cell or
  *								range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
  *	@param	rows			The number of rows, up or down, that you want the upper-left cell to refer to.
  *								Using 5 as the rows argument specifies that the upper-left cell in the reference is
  *								five rows below reference. Rows can be positive (which means below the starting reference)
  *								or negative (which means above the starting reference).
  *	@param	cols			The number of columns, to the left or right, that you want the upper-left cell of the result
  *								to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
  *								reference is five columns to the right of reference. Cols can be positive (which means
  *								to the right of the starting reference) or negative (which means to the left of the
  *								starting reference).
  *	@param	height			The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
  *	@param	width			The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
  *	@return	string			A reference to a cell or range of cells
  */
 public static function OFFSET($cellAddress = Null, $rows = 0, $columns = 0, $height = null, $width = null)
 {
     $rows = PHPExcel_Calculation_Functions::flattenSingleValue($rows);
     $columns = PHPExcel_Calculation_Functions::flattenSingleValue($columns);
     $height = PHPExcel_Calculation_Functions::flattenSingleValue($height);
     $width = PHPExcel_Calculation_Functions::flattenSingleValue($width);
     if ($cellAddress == Null) {
         return 0;
     }
     $args = func_get_args();
     $pCell = array_pop($args);
     if (!is_object($pCell)) {
         return PHPExcel_Calculation_Functions::REF();
     }
     $sheetName = null;
     if (strpos($cellAddress, "!")) {
         list($sheetName, $cellAddress) = explode("!", $cellAddress);
     }
     if (strpos($cellAddress, ":")) {
         list($startCell, $endCell) = explode(":", $cellAddress);
     } else {
         $startCell = $endCell = $cellAddress;
     }
     list($startCellColumn, $startCellRow) = PHPExcel_Cell::coordinateFromString($startCell);
     list($endCellColumn, $endCellRow) = PHPExcel_Cell::coordinateFromString($endCell);
     $startCellRow += $rows;
     $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1;
     $startCellColumn += $columns;
     if ($startCellRow <= 0 || $startCellColumn < 0) {
         return PHPExcel_Calculation_Functions::REF();
     }
     $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1;
     if ($width != null && !is_object($width)) {
         $endCellColumn = $startCellColumn + $width - 1;
     } else {
         $endCellColumn += $columns;
     }
     $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn);
     if ($height != null && !is_object($height)) {
         $endCellRow = $startCellRow + $height - 1;
     } else {
         $endCellRow += $rows;
     }
     if ($endCellRow <= 0 || $endCellColumn < 0) {
         return PHPExcel_Calculation_Functions::REF();
     }
     $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn);
     $cellAddress = $startCellColumn . $startCellRow;
     if ($startCellColumn != $endCellColumn || $startCellRow != $endCellRow) {
         $cellAddress .= ':' . $endCellColumn . $endCellRow;
     }
     if ($sheetName !== null) {
         $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
     } else {
         $pSheet = $pCell->getParent();
     }
     return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
 }
Beispiel #29
0
 /**
  *  Save PHPExcel to PDF file, post-save
  *
  *  @param     resource      $fileHandle
  *  @throws    PHPExcel_Writer_Exception
  */
 protected function restoreStateAfterSave($fileHandle)
 {
     //  Close file
     fclose($fileHandle);
     PHPExcel_Calculation::setArrayReturnType($this->_saveArrayReturnType);
 }
Beispiel #30
0
 /**
  * Set the locale code to use for formula translations and any special formatting
  *
  * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk")
  * @return boolean Success or failure
  */
 public static function setLocale($locale = 'en_us')
 {
     return PHPExcel_Calculation::getInstance()->setLocale($locale);
 }