diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..58182f254
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+/Build export-ignore
+/unitTests export-ignore
+README.md export-ignore
diff --git a/.travis.yml b/.travis.yml
index 532f05164..99e9e8da6 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,13 +1,29 @@
language: php
php:
- - 5.2
- - 5.3.3
- - 5.3
- 5.4
+ - 5.5
+ - 5.6
+ - 7.0
+ - hhvm
+
+matrix:
+ allow_failures:
+ - php: hhvm
+
+before_script:
+ ## Packages
+ - sudo apt-get -qq update > /dev/null
+ ## Composer
+ - composer self-update
+ - composer install --prefer-source --dev
+ - phpenv global "$TRAVIS_PHP_VERSION"
script:
- - phpunit -c ./unitTests/
+ ## PHP_CodeSniffer
+ - ./vendor/bin/phpcs --report-width=200 --report-summary --report-full Classes/ unitTests/ --standard=PSR2 -n
+ ## PHPUnit
+ - phpunit -c ./unitTests/
notifications:
email: false
diff --git a/Build/build.xml b/Build/build.xml
index 568ff89ed..be49be3c5 100644
--- a/Build/build.xml
+++ b/Build/build.xml
@@ -1,30 +1,37 @@
';
+ $stack->push('Brace', '(');
+ ++$index;
+
+ } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number?
+ $expectingOperator = true;
+ $expectingOperand = false;
+ $val = $match[1];
+ $length = strlen($val);
+// echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function
';
+
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) {
+ $val = preg_replace('/\s/u', '', $val);
+// echo 'Element '.$val.' is a Function
';
+ if (isset(self::$PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function
+ $stack->push('Function', strtoupper($val));
+ $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index+$length), $amatch);
+ if ($ax) {
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 0);
+ $expectingOperator = true;
+ } else {
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 1);
+ $expectingOperator = false;
+ }
+ $stack->push('Brace', '(');
+ } else { // it's a var w/ implicit multiplication
+ $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => null);
+ }
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) {
+// echo 'Element '.$val.' is a Cell reference
';
+ // Watch for this case-change when modifying to allow cell references in different worksheets...
+ // Should only be applied to the actual cell column, not the worksheet name
+
+ // If the last entry on the stack was a : operator, then we have a cell range reference
+ $testPrevOp = $stack->last(1);
+ if ($testPrevOp['value'] == ':') {
+ // If we have a worksheet reference, then we're playing with a 3D reference
+ if ($matches[2] == '') {
+ // Otherwise, we 'inherit' the worksheet reference from the start cell reference
+ // The start of the cell range reference should be the last entry in $output
+ $startCellRef = $output[count($output)-1]['value'];
+ preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches);
+ if ($startMatches[2] > '') {
+ $val = $startMatches[2].'!'.$val;
+ }
+ } else {
+ return $this->raiseFormulaError("3D Range references are not yet supported");
+ }
+ }
+
+ $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val);
+// $expectingOperator = FALSE;
+ } else { // it's a variable, constant, string, number or boolean
+// echo 'Element is a Variable, Constant, String, Number or Boolean
';
+ // If the last entry on the stack was a : operator, then we may have a row or column range reference
+ $testPrevOp = $stack->last(1);
+ if ($testPrevOp['value'] == ':') {
+ $startRowColRef = $output[count($output)-1]['value'];
+ $rangeWS1 = '';
+ if (strpos('!', $startRowColRef) !== false) {
+ list($rangeWS1, $startRowColRef) = explode('!', $startRowColRef);
+ }
+ if ($rangeWS1 != '') {
+ $rangeWS1 .= '!';
+ }
+ $rangeWS2 = $rangeWS1;
+ if (strpos('!', $val) !== false) {
+ list($rangeWS2, $val) = explode('!', $val);
+ }
+ if ($rangeWS2 != '') {
+ $rangeWS2 .= '!';
+ }
+ if ((is_integer($startRowColRef)) && (ctype_digit($val)) &&
+ ($startRowColRef <= 1048576) && ($val <= 1048576)) {
+ // Row range
+ $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
+ $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef;
+ $val = $rangeWS2.$endRowColRef.$val;
+ } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
+ (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) {
+ // Column range
+ $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
+ $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1';
+ $val = $rangeWS2.$val.$endRowColRef;
+ }
+ }
+
+ $localeConstant = false;
+ if ($opCharacter == '"') {
+// echo 'Element is a String
';
+ // UnEscape any quotes within the string
+ $val = self::wrapResult(str_replace('""', '"', self::unwrapResult($val)));
+ } elseif (is_numeric($val)) {
+// echo 'Element is a Number
';
+ if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
+// echo 'Casting '.$val.' to float
';
+ $val = (float) $val;
+ } else {
+// echo 'Casting '.$val.' to integer
';
+ $val = (integer) $val;
+ }
+ } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) {
+ $excelConstant = trim(strtoupper($val));
+// echo 'Element '.$excelConstant.' is an Excel Constant
';
+ $val = self::$excelConstants[$excelConstant];
+ } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
+// echo 'Element '.$localeConstant.' is an Excel Constant
';
+ $val = self::$excelConstants[$localeConstant];
+ }
+ $details = array('type' => 'Value', 'value' => $val, 'reference' => null);
+ if ($localeConstant) {
+ $details['localeValue'] = $localeConstant;
+ }
+ $output[] = $details;
+ }
+ $index += $length;
+
+ } elseif ($opCharacter == '$') { // absolute row or column range
+ ++$index;
+ } elseif ($opCharacter == ')') { // miscellaneous error checking
+ if ($expectingOperand) {
+ $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null);
+ $expectingOperand = false;
+ $expectingOperator = true;
+ } else {
+ return $this->raiseFormulaError("Formula Error: Unexpected ')'");
+ }
+ } elseif (isset(self::$operators[$opCharacter]) && !$expectingOperator) {
+ return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
+ } else { // I don't even want to know what you did to get here
+ return $this->raiseFormulaError("Formula Error: An unexpected error occured");
+ }
+ // Test for end of formula string
+ if ($index == strlen($formula)) {
+ // Did we end with an operator?.
+ // Only valid for the % unary operator
+ if ((isset(self::$operators[$opCharacter])) && ($opCharacter != '%')) {
+ return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
+ } else {
+ break;
+ }
+ }
+ // Ignore white space
+ while (($formula{$index} == "\n") || ($formula{$index} == "\r")) {
+ ++$index;
+ }
+ if ($formula{$index} == ' ') {
+ while ($formula{$index} == ' ') {
+ ++$index;
+ }
+ // If we're expecting an operator, but only have a space between the previous and next operands (and both are
+ // Cell References) then we have an INTERSECTION operator
+// echo 'Possible Intersect Operator
';
+ if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) &&
+ ($output[count($output)-1]['type'] == 'Cell Reference')) {
+// echo 'Element is an Intersect Operator
';
+ while ($stack->count() > 0 &&
+ ($o2 = $stack->last()) &&
+ isset(self::$operators[$o2['value']]) &&
+ @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) {
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
+ }
+ $stack->push('Binary Operator', '|'); // Put an Intersect Operator on the stack
+ $expectingOperator = false;
+ }
+ }
+ }
+
+ while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output
+ if ((is_array($op) && $op['value'] == '(') || ($op === '(')) {
+ return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
+ }
+ $output[] = $op;
+ }
+ return $output;
+ }
+
+
+ private static function dataTestReference(&$operandData)
+ {
+ $operand = $operandData['value'];
+ if (($operandData['reference'] === null) && (is_array($operand))) {
+ $rKeys = array_keys($operand);
+ $rowKey = array_shift($rKeys);
+ $cKeys = array_keys(array_keys($operand[$rowKey]));
+ $colKey = array_shift($cKeys);
+ if (ctype_upper($colKey)) {
+ $operandData['reference'] = $colKey.$rowKey;
+ }
+ }
+ return $operand;
+ }
+
+ // evaluate postfix notation
+ private function processTokenStack($tokens, $cellID = null, PHPExcel_Cell $pCell = null)
+ {
+ if ($tokens == false) {
+ return false;
+ }
+
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
+ // so we store the parent cell collection so that we can re-attach it when necessary
+ $pCellWorksheet = ($pCell !== null) ? $pCell->getWorksheet() : null;
+ $pCellParent = ($pCell !== null) ? $pCell->getParent() : null;
+ $stack = new PHPExcel_Calculation_Token_Stack;
+
+ // Loop through each token in turn
+ foreach ($tokens as $tokenData) {
+// print_r($tokenData);
+// echo '
';
+ $token = $tokenData['value'];
+// echo 'Token is '.$token.'
';
+ // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack
+ if (isset(self::$binaryOperators[$token])) {
+// echo 'Token is a binary operator
';
+ // We must have two operands, error if we don't
+ if (($operand2Data = $stack->pop()) === null) {
+ return $this->raiseFormulaError('Internal error - Operand value missing from stack');
+ }
+ if (($operand1Data = $stack->pop()) === null) {
+ return $this->raiseFormulaError('Internal error - Operand value missing from stack');
+ }
+
+ $operand1 = self::dataTestReference($operand1Data);
+ $operand2 = self::dataTestReference($operand2Data);
+
+ // Log what we're doing
+ if ($token == ':') {
+ $this->_debugLog->writeDebugLog('Evaluating Range ', $this->showValue($operand1Data['reference']), ' ', $token, ' ', $this->showValue($operand2Data['reference']));
+ } else {
+ $this->_debugLog->writeDebugLog('Evaluating ', $this->showValue($operand1), ' ', $token, ' ', $this->showValue($operand2));
+ }
+
+ // Process the operation in the appropriate manner
+ switch ($token) {
+ // Comparison (Boolean) Operators
+ case '>': // Greater than
+ case '<': // Less than
+ case '>=': // Greater than or Equal to
+ case '<=': // Less than or Equal to
+ case '=': // Equality
+ case '<>': // Inequality
+ $this->executeBinaryComparisonOperation($cellID, $operand1, $operand2, $token, $stack);
+ break;
+ // Binary Operators
+ case ':': // Range
+ $sheet1 = $sheet2 = '';
+ if (strpos($operand1Data['reference'], '!') !== false) {
+ list($sheet1, $operand1Data['reference']) = explode('!', $operand1Data['reference']);
+ } else {
+ $sheet1 = ($pCellParent !== null) ? $pCellWorksheet->getTitle() : '';
+ }
+ if (strpos($operand2Data['reference'], '!') !== false) {
+ list($sheet2, $operand2Data['reference']) = explode('!', $operand2Data['reference']);
+ } else {
+ $sheet2 = $sheet1;
+ }
+ if ($sheet1 == $sheet2) {
+ if ($operand1Data['reference'] === null) {
+ if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
+ $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value'];
+ } elseif (trim($operand1Data['reference']) == '') {
+ $operand1Data['reference'] = $pCell->getCoordinate();
+ } else {
+ $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow();
+ }
+ }
+ if ($operand2Data['reference'] === null) {
+ if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
+ $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value'];
+ } elseif (trim($operand2Data['reference']) == '') {
+ $operand2Data['reference'] = $pCell->getCoordinate();
+ } else {
+ $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow();
+ }
+ }
+
+ $oData = array_merge(explode(':', $operand1Data['reference']), explode(':', $operand2Data['reference']));
+ $oCol = $oRow = array();
+ foreach ($oData as $oDatum) {
+ $oCR = PHPExcel_Cell::coordinateFromString($oDatum);
+ $oCol[] = PHPExcel_Cell::columnIndexFromString($oCR[0]) - 1;
+ $oRow[] = $oCR[1];
+ }
+ $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
+ if ($pCellParent !== null) {
+ $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($sheet1), false);
+ } else {
+ return $this->raiseFormulaError('Unable to access Cell Reference');
+ }
+ $stack->push('Cell Reference', $cellValue, $cellRef);
+ } else {
+ $stack->push('Error', PHPExcel_Calculation_Functions::REF(), null);
+ }
+ break;
+ case '+': // Addition
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'plusEquals', $stack);
+ break;
+ case '-': // Subtraction
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'minusEquals', $stack);
+ break;
+ case '*': // Multiplication
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'arrayTimesEquals', $stack);
+ break;
+ case '/': // Division
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'arrayRightDivide', $stack);
+ break;
+ case '^': // Exponential
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'power', $stack);
+ break;
+ case '&': // Concatenation
+ // If either of the operands is a matrix, we need to treat them both as matrices
+ // (converting the other operand to a matrix if need be); then perform the required
+ // matrix operation
+ if (is_bool($operand1)) {
+ $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
+ }
+ if (is_bool($operand2)) {
+ $operand2 = ($operand2) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
+ }
+ if ((is_array($operand1)) || (is_array($operand2))) {
+ // Ensure that both operands are arrays/matrices
+ self::checkMatrixOperands($operand1, $operand2, 2);
+ try {
+ // Convert operand 1 from a PHP array to a matrix
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
+ $matrixResult = $matrix->concat($operand2);
+ $result = $matrixResult->getArray();
+ } catch (PHPExcel_Exception $ex) {
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
+ $result = '#VALUE!';
+ }
+ } else {
+ $result = '"'.str_replace('""', '"', self::unwrapResult($operand1, '"').self::unwrapResult($operand2, '"')).'"';
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
+ $stack->push('Value', $result);
+ break;
+ case '|': // Intersect
+ $rowIntersect = array_intersect_key($operand1, $operand2);
+ $cellIntersect = $oCol = $oRow = array();
+ foreach (array_keys($rowIntersect) as $row) {
+ $oRow[] = $row;
+ foreach ($rowIntersect[$row] as $col => $data) {
+ $oCol[] = PHPExcel_Cell::columnIndexFromString($col) - 1;
+ $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
+ }
+ }
+ $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($cellIntersect));
+ $stack->push('Value', $cellIntersect, $cellRef);
+ break;
+ }
+
+ // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
+ } elseif (($token === '~') || ($token === '%')) {
+// echo 'Token is a unary operator
';
+ if (($arg = $stack->pop()) === null) {
+ return $this->raiseFormulaError('Internal error - Operand value missing from stack');
+ }
+ $arg = $arg['value'];
+ if ($token === '~') {
+// echo 'Token is a negation operator
';
+ $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->showValue($arg));
+ $multiplier = -1;
+ } else {
+// echo 'Token is a percentile operator
';
+ $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->showValue($arg));
+ $multiplier = 0.01;
+ }
+ if (is_array($arg)) {
+ self::checkMatrixOperands($arg, $multiplier, 2);
+ try {
+ $matrix1 = new PHPExcel_Shared_JAMA_Matrix($arg);
+ $matrixResult = $matrix1->arrayTimesEquals($multiplier);
+ $result = $matrixResult->getArray();
+ } catch (PHPExcel_Exception $ex) {
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
+ $result = '#VALUE!';
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
+ $stack->push('Value', $result);
+ } else {
+ $this->executeNumericBinaryOperation($cellID, $multiplier, $arg, '*', 'arrayTimesEquals', $stack);
+ }
+
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
+ $cellRef = null;
+// echo 'Element '.$token.' is a Cell reference
';
+ if (isset($matches[8])) {
+// echo 'Reference is a Range of cells
';
+ if ($pCell === null) {
+// We can't access the range, so return a REF error
+ $cellValue = PHPExcel_Calculation_Functions::REF();
+ } else {
+ $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10];
+ if ($matches[2] > '') {
+ $matches[2] = trim($matches[2], "\"'");
+ if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) {
+ // It's a Reference to an external workbook (not currently supported)
+ return $this->raiseFormulaError('Unable to access External Workbook');
+ }
+ $matches[2] = trim($matches[2], "\"'");
+// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]);
+ if ($pCellParent !== null) {
+ $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false);
+ } else {
+ return $this->raiseFormulaError('Unable to access Cell Reference');
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue));
+// $cellRef = $matches[2].'!'.$cellRef;
+ } else {
+// echo '$cellRef='.$cellRef.' in current worksheet
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet');
+ if ($pCellParent !== null) {
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
+ } else {
+ return $this->raiseFormulaError('Unable to access Cell Reference');
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->showTypeDetails($cellValue));
+ }
+ }
+ } else {
+// echo 'Reference is a single Cell
';
+ if ($pCell === null) {
+// We can't access the cell, so return a REF error
+ $cellValue = PHPExcel_Calculation_Functions::REF();
+ } else {
+ $cellRef = $matches[6].$matches[7];
+ if ($matches[2] > '') {
+ $matches[2] = trim($matches[2], "\"'");
+ if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) {
+ // It's a Reference to an external workbook (not currently supported)
+ return $this->raiseFormulaError('Unable to access External Workbook');
+ }
+// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]);
+ if ($pCellParent !== null) {
+ $cellSheet = $this->workbook->getSheetByName($matches[2]);
+ if ($cellSheet && $cellSheet->cellExists($cellRef)) {
+ $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false);
+ $pCell->attach($pCellParent);
+ } else {
+ $cellValue = null;
+ }
+ } else {
+ return $this->raiseFormulaError('Unable to access Cell Reference');
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue));
+// $cellRef = $matches[2].'!'.$cellRef;
+ } else {
+// echo '$cellRef='.$cellRef.' in current worksheet
';
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet');
+ if ($pCellParent->isDataSet($cellRef)) {
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
+ $pCell->attach($pCellParent);
+ } else {
+ $cellValue = null;
+ }
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->showTypeDetails($cellValue));
+ }
+ }
+ }
+ $stack->push('Value', $cellValue, $cellRef);
+
+ // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) {
+// echo 'Token is a function
';
+ $functionName = $matches[1];
+ $argCount = $stack->pop();
+ $argCount = $argCount['value'];
+ if ($functionName != 'MKMATRIX') {
+ $this->_debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's'));
+ }
+ if ((isset(self::$PHPExcelFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function
+ if (isset(self::$PHPExcelFunctions[$functionName])) {
+ $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall'];
+ $passByReference = isset(self::$PHPExcelFunctions[$functionName]['passByReference']);
+ $passCellReference = isset(self::$PHPExcelFunctions[$functionName]['passCellReference']);
+ } elseif (isset(self::$controlFunctions[$functionName])) {
+ $functionCall = self::$controlFunctions[$functionName]['functionCall'];
+ $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
+ $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
+ }
+ // get the arguments for this function
+// echo 'Function '.$functionName.' expects '.$argCount.' arguments
';
+ $args = $argArrayVals = array();
+ for ($i = 0; $i < $argCount; ++$i) {
+ $arg = $stack->pop();
+ $a = $argCount - $i - 1;
+ if (($passByReference) &&
+ (isset(self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) &&
+ (self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) {
+ if ($arg['reference'] === null) {
+ $args[] = $cellID;
+ if ($functionName != 'MKMATRIX') {
+ $argArrayVals[] = $this->showValue($cellID);
+ }
+ } else {
+ $args[] = $arg['reference'];
+ if ($functionName != 'MKMATRIX') {
+ $argArrayVals[] = $this->showValue($arg['reference']);
+ }
+ }
+ } else {
+ $args[] = self::unwrapResult($arg['value']);
+ if ($functionName != 'MKMATRIX') {
+ $argArrayVals[] = $this->showValue($arg['value']);
+ }
+ }
+ }
+ // Reverse the order of the arguments
+ krsort($args);
+ if (($passByReference) && ($argCount == 0)) {
+ $args[] = $cellID;
+ $argArrayVals[] = $this->showValue($cellID);
+ }
+// echo 'Arguments are: ';
+// print_r($args);
+// echo '
';
+ if ($functionName != 'MKMATRIX') {
+ if ($this->_debugLog->getWriteDebugLog()) {
+ krsort($argArrayVals);
+ $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator.' ', PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )');
+ }
+ }
+ // Process each argument in turn, building the return value as an array
+// if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) {
+// $operand1 = $args[1];
+// $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->showValue($operand1));
+// $result = array();
+// $row = 0;
+// foreach($operand1 as $args) {
+// if (is_array($args)) {
+// foreach($args as $arg) {
+// $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->showValue($arg), ' )');
+// $r = call_user_func_array($functionCall, $arg);
+// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($r));
+// $result[$row][] = $r;
+// }
+// ++$row;
+// } else {
+// $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->showValue($args), ' )');
+// $r = call_user_func_array($functionCall, $args);
+// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($r));
+// $result[] = $r;
+// }
+// }
+// } else {
+ // Process the argument with the appropriate function call
+ if ($passCellReference) {
+ $args[] = $pCell;
+ }
+ if (strpos($functionCall, '::') !== false) {
+ $result = call_user_func_array(explode('::', $functionCall), $args);
+ } else {
+ foreach ($args as &$arg) {
+ $arg = PHPExcel_Calculation_Functions::flattenSingleValue($arg);
+ }
+ unset($arg);
+ $result = call_user_func_array($functionCall, $args);
+ }
+ if ($functionName != 'MKMATRIX') {
+ $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($result));
+ }
+ $stack->push('Value', self::wrapResult($result));
+ }
+
+ } else {
+ // if the token is a number, boolean, string or an Excel error, push it onto the stack
+ if (isset(self::$excelConstants[strtoupper($token)])) {
+ $excelConstant = strtoupper($token);
+// echo 'Token is a PHPExcel constant: '.$excelConstant.'
';
+ $stack->push('Constant Value', self::$excelConstants[$excelConstant]);
+ $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->showTypeDetails(self::$excelConstants[$excelConstant]));
+ } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) {
+// echo 'Token is a number, boolean, string, null or an Excel error
';
+ $stack->push('Value', $token);
+ // if the token is a named range, push the named range name onto the stack
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) {
+// echo 'Token is a named range
';
+ $namedRange = $matches[6];
+// echo 'Named Range is '.$namedRange.'
';
+ $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange);
+ $cellValue = $this->extractNamedRange($namedRange, ((null !== $pCell) ? $pCellWorksheet : null), false);
+ $pCell->attach($pCellParent);
+ $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->showTypeDetails($cellValue));
+ $stack->push('Named Range', $cellValue, $namedRange);
+ } else {
+ return $this->raiseFormulaError("undefined variable '$token'");
+ }
+ }
+ }
+ // when we're out of tokens, the stack should have a single element, the final result
+ if ($stack->count() != 1) {
+ return $this->raiseFormulaError("internal error");
+ }
+ $output = $stack->pop();
+ $output = $output['value'];
+
+// if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
+// return array_shift(PHPExcel_Calculation_Functions::flattenArray($output));
+// }
+ return $output;
+ }
+
+
+ private function validateBinaryOperand($cellID, &$operand, &$stack)
+ {
+ if (is_array($operand)) {
+ if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
+ do {
+ $operand = array_pop($operand);
+ } while (is_array($operand));
+ }
+ }
+ // Numbers, matrices and booleans can pass straight through, as they're already valid
+ if (is_string($operand)) {
+ // We only need special validations for the operand if it is a string
+ // Start by stripping off the quotation marks we use to identify true excel string values internally
+ if ($operand > '' && $operand{0} == '"') {
+ $operand = self::unwrapResult($operand);
+ }
+ // If the string is a numeric value, we treat it as a numeric, so no further testing
+ if (!is_numeric($operand)) {
+ // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
+ if ($operand > '' && $operand{0} == '#') {
+ $stack->push('Value', $operand);
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($operand));
+ return false;
+ } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) {
+ // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations
+ $stack->push('Value', '#VALUE!');
+ $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->showTypeDetails('#VALUE!'));
+ return false;
+ }
+ }
+ }
+
+ // return a true if the value of the operand is one that we can use in normal binary operations
+ return true;
+ }
+
+
+ private function executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays = false)
+ {
+ // If we're dealing with matrix operations, we want a matrix result
+ if ((is_array($operand1)) || (is_array($operand2))) {
+ $result = array();
+ if ((is_array($operand1)) && (!is_array($operand2))) {
+ foreach ($operand1 as $x => $operandData) {
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2));
+ $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ } elseif ((!is_array($operand1)) && (is_array($operand2))) {
+ foreach ($operand2 as $x => $operandData) {
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData));
+ $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ } else {
+ if (!$recursingArrays) {
+ self::checkMatrixOperands($operand1, $operand2, 2);
+ }
+ foreach ($operand1 as $x => $operandData) {
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x]));
+ $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ }
+ // Log the result details
+ $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Array', $result);
+ return true;
+ }
+
+ // Simple validate the two operands if they are string values
+ if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') {
+ $operand1 = self::unwrapResult($operand1);
+ }
+ if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') {
+ $operand2 = self::unwrapResult($operand2);
+ }
+
+ // Use case insensitive comparaison if not OpenOffice mode
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ if (is_string($operand1)) {
+ $operand1 = strtoupper($operand1);
+ }
+ if (is_string($operand2)) {
+ $operand2 = strtoupper($operand2);
+ }
+ }
+
+ $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE;
+
+ // execute the necessary operation
+ switch ($operation) {
+ // Greater than
+ case '>':
+ if ($useLowercaseFirstComparison) {
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) > 0;
+ } else {
+ $result = ($operand1 > $operand2);
+ }
+ break;
+ // Less than
+ case '<':
+ if ($useLowercaseFirstComparison) {
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) < 0;
+ } else {
+ $result = ($operand1 < $operand2);
+ }
+ break;
+ // Equality
+ case '=':
+ if (is_numeric($operand1) && is_numeric($operand2)) {
+ $result = (abs($operand1 - $operand2) < $this->delta);
+ } else {
+ $result = strcmp($operand1, $operand2) == 0;
+ }
+ break;
+ // Greater than or equal
+ case '>=':
+ if (is_numeric($operand1) && is_numeric($operand2)) {
+ $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 > $operand2));
+ } elseif ($useLowercaseFirstComparison) {
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0;
+ } else {
+ $result = strcmp($operand1, $operand2) >= 0;
+ }
+ break;
+ // Less than or equal
+ case '<=':
+ if (is_numeric($operand1) && is_numeric($operand2)) {
+ $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 < $operand2));
+ } elseif ($useLowercaseFirstComparison) {
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0;
+ } else {
+ $result = strcmp($operand1, $operand2) <= 0;
+ }
+ break;
+ // Inequality
+ case '<>':
+ if (is_numeric($operand1) && is_numeric($operand2)) {
+ $result = (abs($operand1 - $operand2) > 1E-14);
+ } else {
+ $result = strcmp($operand1, $operand2) != 0;
+ }
+ break;
+ }
+
+ // Log the result details
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Value', $result);
+ return true;
+ }
+
+ /**
+ * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters
+ * @param string $str1 First string value for the comparison
+ * @param string $str2 Second string value for the comparison
+ * @return integer
+ */
+ private function strcmpLowercaseFirst($str1, $str2)
+ {
+ $inversedStr1 = PHPExcel_Shared_String::StrCaseReverse($str1);
+ $inversedStr2 = PHPExcel_Shared_String::StrCaseReverse($str2);
+
+ return strcmp($inversedStr1, $inversedStr2);
+ }
+
+ private function executeNumericBinaryOperation($cellID, $operand1, $operand2, $operation, $matrixFunction, &$stack)
+ {
+ // Validate the two operands
+ if (!$this->validateBinaryOperand($cellID, $operand1, $stack)) {
+ return false;
+ }
+ if (!$this->validateBinaryOperand($cellID, $operand2, $stack)) {
+ return false;
+ }
+
+ // If either of the operands is a matrix, we need to treat them both as matrices
+ // (converting the other operand to a matrix if need be); then perform the required
+ // matrix operation
+ if ((is_array($operand1)) || (is_array($operand2))) {
+ // Ensure that both operands are arrays/matrices of the same size
+ self::checkMatrixOperands($operand1, $operand2, 2);
+
+ try {
+ // Convert operand 1 from a PHP array to a matrix
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
+ $matrixResult = $matrix->$matrixFunction($operand2);
+ $result = $matrixResult->getArray();
+ } catch (PHPExcel_Exception $ex) {
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
+ $result = '#VALUE!';
+ }
+ } else {
+ if ((PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) &&
+ ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1)>0) ||
+ (is_string($operand2) && !is_numeric($operand2) && strlen($operand2)>0))) {
+ $result = PHPExcel_Calculation_Functions::VALUE();
+ } else {
+ // If we're dealing with non-matrix operations, execute the necessary operation
+ switch ($operation) {
+ // Addition
+ case '+':
+ $result = $operand1 + $operand2;
+ break;
+ // Subtraction
+ case '-':
+ $result = $operand1 - $operand2;
+ break;
+ // Multiplication
+ case '*':
+ $result = $operand1 * $operand2;
+ break;
+ // Division
+ case '/':
+ if ($operand2 == 0) {
+ // Trap for Divide by Zero error
+ $stack->push('Value', '#DIV/0!');
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails('#DIV/0!'));
+ return false;
+ } else {
+ $result = $operand1 / $operand2;
+ }
+ break;
+ // Power
+ case '^':
+ $result = pow($operand1, $operand2);
+ break;
+ }
+ }
+ }
+
+ // Log the result details
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Value', $result);
+ return true;
+ }
+
+
+ // trigger an error, but nicely, if need be
+ protected function raiseFormulaError($errorMessage)
+ {
+ $this->formulaError = $errorMessage;
+ $this->cyclicReferenceStack->clear();
+ if (!$this->suppressFormulaErrors) {
+ throw new PHPExcel_Calculation_Exception($errorMessage);
+ }
+ trigger_error($errorMessage, E_USER_ERROR);
+ }
+
+
+ /**
+ * Extract range values
+ *
+ * @param string &$pRange String based range representation
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
+ * @throws PHPExcel_Calculation_Exception
+ */
+ public function extractCellRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog = true)
+ {
+ // Return value
+ $returnValue = array ();
+
+// echo 'extractCellRange('.$pRange.')', PHP_EOL;
+ if ($pSheet !== null) {
+ $pSheetName = $pSheet->getTitle();
+// echo 'Passed sheet name is '.$pSheetName.PHP_EOL;
+// echo 'Range reference is '.$pRange.PHP_EOL;
+ if (strpos($pRange, '!') !== false) {
+// echo '$pRange reference includes sheet reference', PHP_EOL;
+ list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
+// echo 'New sheet name is '.$pSheetName, PHP_EOL;
+// echo 'Adjusted Range reference is '.$pRange, PHP_EOL;
+ $pSheet = $this->workbook->getSheetByName($pSheetName);
+ }
+
+ // Extract range
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
+ $pRange = $pSheetName.'!'.$pRange;
+ if (!isset($aReferences[1])) {
+ // Single cell in range
+ sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
+ $cellValue = null;
+ if ($pSheet->cellExists($aReferences[0])) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ } else {
+ // Extract cell data for all cells in the range
+ foreach ($aReferences as $reference) {
+ // Extract range
+ sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
+ $cellValue = null;
+ if ($pSheet->cellExists($reference)) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ }
+ }
+ }
+
+ return $returnValue;
+ }
+
+
+ /**
+ * Extract range values
+ *
+ * @param string &$pRange String based range representation
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
+ * @throws PHPExcel_Calculation_Exception
+ */
+ public function extractNamedRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog = true)
+ {
+ // Return value
+ $returnValue = array ();
+
+// echo 'extractNamedRange('.$pRange.')
';
+ if ($pSheet !== null) {
+ $pSheetName = $pSheet->getTitle();
+// echo 'Current sheet name is '.$pSheetName.'
';
+// echo 'Range reference is '.$pRange.'
';
+ if (strpos($pRange, '!') !== false) {
+// echo '$pRange reference includes sheet reference', PHP_EOL;
+ list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
+// echo 'New sheet name is '.$pSheetName, PHP_EOL;
+// echo 'Adjusted Range reference is '.$pRange, PHP_EOL;
+ $pSheet = $this->workbook->getSheetByName($pSheetName);
+ }
+
+ // Named range?
+ $namedRange = PHPExcel_NamedRange::resolveRange($pRange, $pSheet);
+ if ($namedRange !== null) {
+ $pSheet = $namedRange->getWorksheet();
+// echo 'Named Range '.$pRange.' (';
+ $pRange = $namedRange->getRange();
+ $splitRange = PHPExcel_Cell::splitRange($pRange);
+ // Convert row and column references
+ if (ctype_alpha($splitRange[0][0])) {
+ $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
+ } elseif (ctype_digit($splitRange[0][0])) {
+ $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
+ }
+// echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'
';
+
+// if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) {
+// if (!$namedRange->getLocalOnly()) {
+// $pSheet = $namedRange->getWorksheet();
+// } else {
+// return $returnValue;
+// }
+// }
+ } else {
+ return PHPExcel_Calculation_Functions::REF();
+ }
+
+ // Extract range
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
+// var_dump($aReferences);
+ if (!isset($aReferences[1])) {
+ // Single cell (or single column or row) in range
+ list($currentCol, $currentRow) = PHPExcel_Cell::coordinateFromString($aReferences[0]);
+ $cellValue = null;
+ if ($pSheet->cellExists($aReferences[0])) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ } else {
+ // Extract cell data for all cells in the range
+ foreach ($aReferences as $reference) {
+ // Extract range
+ list($currentCol, $currentRow) = PHPExcel_Cell::coordinateFromString($reference);
+// echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'
';
+ $cellValue = null;
+ if ($pSheet->cellExists($reference)) {
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
+ } else {
+ $returnValue[$currentRow][$currentCol] = null;
+ }
+ }
+ }
+// print_r($returnValue);
+// echo '
';
+ }
+
+ return $returnValue;
+ }
+
+
+ /**
+ * Is a specific function implemented?
+ *
+ * @param string $pFunction Function Name
+ * @return boolean
+ */
+ public function isImplemented($pFunction = '')
+ {
+ $pFunction = strtoupper($pFunction);
+ if (isset(self::$PHPExcelFunctions[$pFunction])) {
+ return (self::$PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY');
+ } else {
+ return false;
+ }
+ }
+
+
+ /**
+ * Get a list of all implemented functions as an array of function objects
+ *
+ * @return array of PHPExcel_Calculation_Function
+ */
+ public function listFunctions()
+ {
+ $returnValue = array();
+
+ foreach (self::$PHPExcelFunctions as $functionName => $function) {
+ if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
+ $returnValue[$functionName] = new PHPExcel_Calculation_Function(
+ $function['category'],
+ $functionName,
+ $function['functionCall']
+ );
+ }
+ }
+
+ return $returnValue;
+ }
+
+
+ /**
+ * Get a list of all Excel function names
+ *
+ * @return array
+ */
+ public function listAllFunctionNames()
+ {
+ return array_keys(self::$PHPExcelFunctions);
+ }
+
+ /**
+ * Get a list of implemented Excel function names
+ *
+ * @return array
+ */
+ public function listFunctionNames()
+ {
+ $returnValue = array();
+ foreach (self::$PHPExcelFunctions as $functionName => $function) {
+ if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
+ $returnValue[] = $functionName;
+ }
+ }
+
+ return $returnValue;
+ }
}
-
-
-/**
- * PHPExcel_Calculation (Singleton)
- *
- * @category PHPExcel
- * @package PHPExcel_Calculation
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- */
-class PHPExcel_Calculation {
-
- /** Constants */
- /** Regular Expressions */
- // Numeric operand
- const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
- // String operand
- const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
- // Opening bracket
- const CALCULATION_REGEXP_OPENBRACE = '\(';
- // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
- const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\(';
- // Cell reference (cell or range of cells, with or without a sheet reference)
- const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF;
- // Named Range of cells
- const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE;
- // Error
- const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
-
-
- /** constants */
- const RETURN_ARRAY_AS_ERROR = 'error';
- const RETURN_ARRAY_AS_VALUE = 'value';
- const RETURN_ARRAY_AS_ARRAY = 'array';
-
- private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
-
-
- /**
- * Instance of this class
- *
- * @access private
- * @var PHPExcel_Calculation
- */
- private static $_instance;
-
-
- /**
- * Calculation cache
- *
- * @access private
- * @var array
- */
- private static $_calculationCache = array ();
-
-
- /**
- * Calculation cache enabled
- *
- * @access private
- * @var boolean
- */
- private static $_calculationCacheEnabled = true;
-
-
- /**
- * List of operators that can be used within formulae
- * The true/false value indicates whether it is a binary operator or a unary operator
- *
- * @access private
- * @var array
- */
- private static $_operators = array('+' => true, '-' => true, '*' => true, '/' => true,
- '^' => true, '&' => true, '%' => false, '~' => false,
- '>' => true, '<' => true, '=' => true, '>=' => true,
- '<=' => true, '<>' => true, '|' => true, ':' => true
- );
-
-
- /**
- * List of binary operators (those that expect two operands)
- *
- * @access private
- * @var array
- */
- private static $_binaryOperators = array('+' => true, '-' => true, '*' => true, '/' => true,
- '^' => true, '&' => true, '>' => true, '<' => true,
- '=' => true, '>=' => true, '<=' => true, '<>' => true,
- '|' => true, ':' => true
- );
-
- /**
- * Flag to determine how formula errors should be handled
- * If true, then a user error will be triggered
- * If false, then an exception will be thrown
- *
- * @access public
- * @var boolean
- *
- */
- public $suppressFormulaErrors = false;
-
- /**
- * Error message for any error that was raised/thrown by the calculation engine
- *
- * @access public
- * @var string
- *
- */
- public $formulaError = null;
-
- /**
- * Flag to determine whether a debug log should be generated by the calculation engine
- * If true, then a debug log will be generated
- * If false, then a debug log will not be generated
- *
- * @access public
- * @var boolean
- *
- */
- public $writeDebugLog = false;
-
- /**
- * Flag to determine whether a debug log should be echoed by the calculation engine
- * If true, then a debug log will be echoed
- * If false, then a debug log will not be echoed
- * A debug log can only be echoed if it is generated
- *
- * @access public
- * @var boolean
- *
- */
- public $echoDebugLog = false;
-
-
- /**
- * An array of the nested cell references accessed by the calculation engine, used for the debug log
- *
- * @access private
- * @var array of string
- *
- */
- private $debugLogStack = array();
-
- /**
- * The debug log generated by the calculation engine
- *
- * @access public
- * @var array of string
- *
- */
- public $debugLog = array();
- private $_cyclicFormulaCount = 0;
- private $_cyclicFormulaCell = '';
- public $cyclicFormulaCount = 0;
-
-
- private $_savedPrecision = 12;
-
-
- private static $_localeLanguage = 'en_us'; // US English (default locale)
- private static $_validLocaleLanguages = array( 'en' // English (default language)
- );
- private static $_localeArgumentSeparator = ',';
- private static $_localeFunctions = array();
- public static $_localeBoolean = array( 'TRUE' => 'TRUE',
- 'FALSE' => 'FALSE',
- 'NULL' => 'NULL'
- );
-
-
- // Constant conversion from text name/value to actual (datatyped) value
- private static $_ExcelConstants = array('TRUE' => true,
- 'FALSE' => false,
- 'NULL' => null
- );
-
- // PHPExcel functions
- private static $_PHPExcelFunctions = array( // PHPExcel functions
- 'ABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'abs',
- 'argumentCount' => '1'
- ),
- 'ACCRINT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINT',
- 'argumentCount' => '4-7'
- ),
- 'ACCRINTM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINTM',
- 'argumentCount' => '3-5'
- ),
- 'ACOS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'acos',
- 'argumentCount' => '1'
- ),
- 'ACOSH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'acosh',
- 'argumentCount' => '1'
- ),
- 'ADDRESS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::CELL_ADDRESS',
- 'argumentCount' => '2-5'
- ),
- 'AMORDEGRC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::AMORDEGRC',
- 'argumentCount' => '6,7'
- ),
- 'AMORLINC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::AMORLINC',
- 'argumentCount' => '6,7'
- ),
- 'AND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_AND',
- 'argumentCount' => '1+'
- ),
- 'AREAS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'ASC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'ASIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'asin',
- 'argumentCount' => '1'
- ),
- 'ASINH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'asinh',
- 'argumentCount' => '1'
- ),
- 'ATAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'atan',
- 'argumentCount' => '1'
- ),
- 'ATAN2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::ATAN2',
- 'argumentCount' => '2'
- ),
- 'ATANH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'atanh',
- 'argumentCount' => '1'
- ),
- 'AVEDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::AVEDEV',
- 'argumentCount' => '1+'
- ),
- 'AVERAGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGE',
- 'argumentCount' => '1+'
- ),
- 'AVERAGEA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEA',
- 'argumentCount' => '1+'
- ),
- 'AVERAGEIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEIF',
- 'argumentCount' => '2,3'
- ),
- 'AVERAGEIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '3+'
- ),
- 'BAHTTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'BESSELI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELI',
- 'argumentCount' => '2'
- ),
- 'BESSELJ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELJ',
- 'argumentCount' => '2'
- ),
- 'BESSELK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELK',
- 'argumentCount' => '2'
- ),
- 'BESSELY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELY',
- 'argumentCount' => '2'
- ),
- 'BETADIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::BETADIST',
- 'argumentCount' => '3-5'
- ),
- 'BETAINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::BETAINV',
- 'argumentCount' => '3-5'
- ),
- 'BIN2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTODEC',
- 'argumentCount' => '1'
- ),
- 'BIN2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOHEX',
- 'argumentCount' => '1,2'
- ),
- 'BIN2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOOCT',
- 'argumentCount' => '1,2'
- ),
- 'BINOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::BINOMDIST',
- 'argumentCount' => '4'
- ),
- 'CEILING' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::CEILING',
- 'argumentCount' => '2'
- ),
- 'CELL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1,2'
- ),
- 'CHAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::CHARACTER',
- 'argumentCount' => '1'
- ),
- 'CHIDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIDIST',
- 'argumentCount' => '2'
- ),
- 'CHIINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIINV',
- 'argumentCount' => '2'
- ),
- 'CHITEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'CHOOSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::CHOOSE',
- 'argumentCount' => '2+'
- ),
- 'CLEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMNONPRINTABLE',
- 'argumentCount' => '1'
- ),
- 'CODE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::ASCIICODE',
- 'argumentCount' => '1'
- ),
- 'COLUMN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMN',
- 'argumentCount' => '-1',
- 'passByReference' => array(true)
- ),
- 'COLUMNS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMNS',
- 'argumentCount' => '1'
- ),
- 'COMBIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::COMBIN',
- 'argumentCount' => '2'
- ),
- 'COMPLEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::COMPLEX',
- 'argumentCount' => '2,3'
- ),
- 'CONCATENATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::CONCATENATE',
- 'argumentCount' => '1+'
- ),
- 'CONFIDENCE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::CONFIDENCE',
- 'argumentCount' => '3'
- ),
- 'CONVERT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::CONVERTUOM',
- 'argumentCount' => '3'
- ),
- 'CORREL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL',
- 'argumentCount' => '2'
- ),
- 'COS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'cos',
- 'argumentCount' => '1'
- ),
- 'COSH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'cosh',
- 'argumentCount' => '1'
- ),
- 'COUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNT',
- 'argumentCount' => '1+'
- ),
- 'COUNTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTA',
- 'argumentCount' => '1+'
- ),
- 'COUNTBLANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTBLANK',
- 'argumentCount' => '1'
- ),
- 'COUNTIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTIF',
- 'argumentCount' => '2'
- ),
- 'COUNTIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'COUPDAYBS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYBS',
- 'argumentCount' => '3,4'
- ),
- 'COUPDAYS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYS',
- 'argumentCount' => '3,4'
- ),
- 'COUPDAYSNC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYSNC',
- 'argumentCount' => '3,4'
- ),
- 'COUPNCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNCD',
- 'argumentCount' => '3,4'
- ),
- 'COUPNUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNUM',
- 'argumentCount' => '3,4'
- ),
- 'COUPPCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::COUPPCD',
- 'argumentCount' => '3,4'
- ),
- 'COVAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::COVAR',
- 'argumentCount' => '2'
- ),
- 'CRITBINOM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::CRITBINOM',
- 'argumentCount' => '3'
- ),
- 'CUBEKPIMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBEMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBEMEMBERPROPERTY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBERANKEDMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBESET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBESETCOUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUBEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'CUMIPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::CUMIPMT',
- 'argumentCount' => '6'
- ),
- 'CUMPRINC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::CUMPRINC',
- 'argumentCount' => '6'
- ),
- 'DATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DATE',
- 'argumentCount' => '3'
- ),
- 'DATEDIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEDIF',
- 'argumentCount' => '2,3'
- ),
- 'DATEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEVALUE',
- 'argumentCount' => '1'
- ),
- 'DAVERAGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DAVERAGE',
- 'argumentCount' => '3'
- ),
- 'DAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFMONTH',
- 'argumentCount' => '1'
- ),
- 'DAYS360' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYS360',
- 'argumentCount' => '2,3'
- ),
- 'DB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::DB',
- 'argumentCount' => '4,5'
- ),
- 'DCOUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNT',
- 'argumentCount' => '3'
- ),
- 'DCOUNTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNTA',
- 'argumentCount' => '3'
- ),
- 'DDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::DDB',
- 'argumentCount' => '4,5'
- ),
- 'DEC2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOBIN',
- 'argumentCount' => '1,2'
- ),
- 'DEC2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOHEX',
- 'argumentCount' => '1,2'
- ),
- 'DEC2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOOCT',
- 'argumentCount' => '1,2'
- ),
- 'DEGREES' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'rad2deg',
- 'argumentCount' => '1'
- ),
- 'DELTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::DELTA',
- 'argumentCount' => '1,2'
- ),
- 'DEVSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::DEVSQ',
- 'argumentCount' => '1+'
- ),
- 'DGET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DGET',
- 'argumentCount' => '3'
- ),
- 'DISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::DISC',
- 'argumentCount' => '4,5'
- ),
- 'DMAX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DMAX',
- 'argumentCount' => '3'
- ),
- 'DMIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DMIN',
- 'argumentCount' => '3'
- ),
- 'DOLLAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::DOLLAR',
- 'argumentCount' => '1,2'
- ),
- 'DOLLARDE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARDE',
- 'argumentCount' => '2'
- ),
- 'DOLLARFR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARFR',
- 'argumentCount' => '2'
- ),
- 'DPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DPRODUCT',
- 'argumentCount' => '3'
- ),
- 'DSTDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEV',
- 'argumentCount' => '3'
- ),
- 'DSTDEVP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEVP',
- 'argumentCount' => '3'
- ),
- 'DSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DSUM',
- 'argumentCount' => '3'
- ),
- 'DURATION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '5,6'
- ),
- 'DVAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DVAR',
- 'argumentCount' => '3'
- ),
- 'DVARP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
- 'functionCall' => 'PHPExcel_Calculation_Database::DVARP',
- 'argumentCount' => '3'
- ),
- 'EDATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::EDATE',
- 'argumentCount' => '2'
- ),
- 'EFFECT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::EFFECT',
- 'argumentCount' => '2'
- ),
- 'EOMONTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::EOMONTH',
- 'argumentCount' => '2'
- ),
- 'ERF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::ERF',
- 'argumentCount' => '1,2'
- ),
- 'ERFC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::ERFC',
- 'argumentCount' => '1'
- ),
- 'ERROR.TYPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::ERROR_TYPE',
- 'argumentCount' => '1'
- ),
- 'EVEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::EVEN',
- 'argumentCount' => '1'
- ),
- 'EXACT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'EXP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'exp',
- 'argumentCount' => '1'
- ),
- 'EXPONDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::EXPONDIST',
- 'argumentCount' => '3'
- ),
- 'FACT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACT',
- 'argumentCount' => '1'
- ),
- 'FACTDOUBLE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACTDOUBLE',
- 'argumentCount' => '1'
- ),
- 'FALSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::FALSE',
- 'argumentCount' => '0'
- ),
- 'FDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '3'
- ),
- 'FIND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'FINDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'FINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '3'
- ),
- 'FISHER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHER',
- 'argumentCount' => '1'
- ),
- 'FISHERINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHERINV',
- 'argumentCount' => '1'
- ),
- 'FIXED' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::FIXEDFORMAT',
- 'argumentCount' => '1-3'
- ),
- 'FLOOR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::FLOOR',
- 'argumentCount' => '2'
- ),
- 'FORECAST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::FORECAST',
- 'argumentCount' => '3'
- ),
- 'FREQUENCY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'FTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'FV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::FV',
- 'argumentCount' => '3-5'
- ),
- 'FVSCHEDULE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::FVSCHEDULE',
- 'argumentCount' => '2'
- ),
- 'GAMMADIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMADIST',
- 'argumentCount' => '4'
- ),
- 'GAMMAINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMAINV',
- 'argumentCount' => '3'
- ),
- 'GAMMALN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMALN',
- 'argumentCount' => '1'
- ),
- 'GCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::GCD',
- 'argumentCount' => '1+'
- ),
- 'GEOMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::GEOMEAN',
- 'argumentCount' => '1+'
- ),
- 'GESTEP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::GESTEP',
- 'argumentCount' => '1,2'
- ),
- 'GETPIVOTDATA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2+'
- ),
- 'GROWTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::GROWTH',
- 'argumentCount' => '1-4'
- ),
- 'HARMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::HARMEAN',
- 'argumentCount' => '1+'
- ),
- 'HEX2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOBIN',
- 'argumentCount' => '1,2'
- ),
- 'HEX2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTODEC',
- 'argumentCount' => '1'
- ),
- 'HEX2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOOCT',
- 'argumentCount' => '1,2'
- ),
- 'HLOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '3,4'
- ),
- 'HOUR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::HOUROFDAY',
- 'argumentCount' => '1'
- ),
- 'HYPERLINK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::HYPERLINK',
- 'argumentCount' => '1,2',
- 'passCellReference'=> true
- ),
- 'HYPGEOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::HYPGEOMDIST',
- 'argumentCount' => '4'
- ),
- 'IF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::STATEMENT_IF',
- 'argumentCount' => '1-3'
- ),
- 'IFERROR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::IFERROR',
- 'argumentCount' => '2'
- ),
- 'IMABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMABS',
- 'argumentCount' => '1'
- ),
- 'IMAGINARY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMAGINARY',
- 'argumentCount' => '1'
- ),
- 'IMARGUMENT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMARGUMENT',
- 'argumentCount' => '1'
- ),
- 'IMCONJUGATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCONJUGATE',
- 'argumentCount' => '1'
- ),
- 'IMCOS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCOS',
- 'argumentCount' => '1'
- ),
- 'IMDIV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMDIV',
- 'argumentCount' => '2'
- ),
- 'IMEXP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMEXP',
- 'argumentCount' => '1'
- ),
- 'IMLN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLN',
- 'argumentCount' => '1'
- ),
- 'IMLOG10' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG10',
- 'argumentCount' => '1'
- ),
- 'IMLOG2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG2',
- 'argumentCount' => '1'
- ),
- 'IMPOWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPOWER',
- 'argumentCount' => '2'
- ),
- 'IMPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPRODUCT',
- 'argumentCount' => '1+'
- ),
- 'IMREAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMREAL',
- 'argumentCount' => '1'
- ),
- 'IMSIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSIN',
- 'argumentCount' => '1'
- ),
- 'IMSQRT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSQRT',
- 'argumentCount' => '1'
- ),
- 'IMSUB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUB',
- 'argumentCount' => '2'
- ),
- 'IMSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUM',
- 'argumentCount' => '1+'
- ),
- 'INDEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDEX',
- 'argumentCount' => '1-4'
- ),
- 'INDIRECT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDIRECT',
- 'argumentCount' => '1,2',
- 'passCellReference'=> true
- ),
- 'INFO' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'INT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::INT',
- 'argumentCount' => '1'
- ),
- 'INTERCEPT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::INTERCEPT',
- 'argumentCount' => '2'
- ),
- 'INTRATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::INTRATE',
- 'argumentCount' => '4,5'
- ),
- 'IPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::IPMT',
- 'argumentCount' => '4-6'
- ),
- 'IRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::IRR',
- 'argumentCount' => '1,2'
- ),
- 'ISBLANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_BLANK',
- 'argumentCount' => '1'
- ),
- 'ISERR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERR',
- 'argumentCount' => '1'
- ),
- 'ISERROR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERROR',
- 'argumentCount' => '1'
- ),
- 'ISEVEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_EVEN',
- 'argumentCount' => '1'
- ),
- 'ISLOGICAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_LOGICAL',
- 'argumentCount' => '1'
- ),
- 'ISNA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NA',
- 'argumentCount' => '1'
- ),
- 'ISNONTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NONTEXT',
- 'argumentCount' => '1'
- ),
- 'ISNUMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NUMBER',
- 'argumentCount' => '1'
- ),
- 'ISODD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ODD',
- 'argumentCount' => '1'
- ),
- 'ISPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::ISPMT',
- 'argumentCount' => '4'
- ),
- 'ISREF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'ISTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::IS_TEXT',
- 'argumentCount' => '1'
- ),
- 'JIS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'KURT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::KURT',
- 'argumentCount' => '1+'
- ),
- 'LARGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::LARGE',
- 'argumentCount' => '2'
- ),
- 'LCM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::LCM',
- 'argumentCount' => '1+'
- ),
- 'LEFT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT',
- 'argumentCount' => '1,2'
- ),
- 'LEFTB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT',
- 'argumentCount' => '1,2'
- ),
- 'LEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH',
- 'argumentCount' => '1'
- ),
- 'LENB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH',
- 'argumentCount' => '1'
- ),
- 'LINEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::LINEST',
- 'argumentCount' => '1-4'
- ),
- 'LN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'log',
- 'argumentCount' => '1'
- ),
- 'LOG' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::LOG_BASE',
- 'argumentCount' => '1,2'
- ),
- 'LOG10' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'log10',
- 'argumentCount' => '1'
- ),
- 'LOGEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGEST',
- 'argumentCount' => '1-4'
- ),
- 'LOGINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGINV',
- 'argumentCount' => '3'
- ),
- 'LOGNORMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGNORMDIST',
- 'argumentCount' => '3'
- ),
- 'LOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::LOOKUP',
- 'argumentCount' => '2,3'
- ),
- 'LOWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::LOWERCASE',
- 'argumentCount' => '1'
- ),
- 'MATCH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::MATCH',
- 'argumentCount' => '2,3'
- ),
- 'MAX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MAX',
- 'argumentCount' => '1+'
- ),
- 'MAXA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXA',
- 'argumentCount' => '1+'
- ),
- 'MAXIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXIF',
- 'argumentCount' => '2+'
- ),
- 'MDETERM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::MDETERM',
- 'argumentCount' => '1'
- ),
- 'MDURATION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '5,6'
- ),
- 'MEDIAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MEDIAN',
- 'argumentCount' => '1+'
- ),
- 'MEDIANIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2+'
- ),
- 'MID' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::MID',
- 'argumentCount' => '3'
- ),
- 'MIDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::MID',
- 'argumentCount' => '3'
- ),
- 'MIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MIN',
- 'argumentCount' => '1+'
- ),
- 'MINA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MINA',
- 'argumentCount' => '1+'
- ),
- 'MINIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MINIF',
- 'argumentCount' => '2+'
- ),
- 'MINUTE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::MINUTEOFHOUR',
- 'argumentCount' => '1'
- ),
- 'MINVERSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::MINVERSE',
- 'argumentCount' => '1'
- ),
- 'MIRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::MIRR',
- 'argumentCount' => '3'
- ),
- 'MMULT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::MMULT',
- 'argumentCount' => '2'
- ),
- 'MOD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::MOD',
- 'argumentCount' => '2'
- ),
- 'MODE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::MODE',
- 'argumentCount' => '1+'
- ),
- 'MONTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::MONTHOFYEAR',
- 'argumentCount' => '1'
- ),
- 'MROUND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::MROUND',
- 'argumentCount' => '2'
- ),
- 'MULTINOMIAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::MULTINOMIAL',
- 'argumentCount' => '1+'
- ),
- 'N' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::N',
- 'argumentCount' => '1'
- ),
- 'NA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::NA',
- 'argumentCount' => '0'
- ),
- 'NEGBINOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::NEGBINOMDIST',
- 'argumentCount' => '3'
- ),
- 'NETWORKDAYS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::NETWORKDAYS',
- 'argumentCount' => '2+'
- ),
- 'NOMINAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::NOMINAL',
- 'argumentCount' => '2'
- ),
- 'NORMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMDIST',
- 'argumentCount' => '4'
- ),
- 'NORMINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMINV',
- 'argumentCount' => '3'
- ),
- 'NORMSDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSDIST',
- 'argumentCount' => '1'
- ),
- 'NORMSINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSINV',
- 'argumentCount' => '1'
- ),
- 'NOT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::NOT',
- 'argumentCount' => '1'
- ),
- 'NOW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DATETIMENOW',
- 'argumentCount' => '0'
- ),
- 'NPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::NPER',
- 'argumentCount' => '3-5'
- ),
- 'NPV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::NPV',
- 'argumentCount' => '2+'
- ),
- 'OCT2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOBIN',
- 'argumentCount' => '1,2'
- ),
- 'OCT2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTODEC',
- 'argumentCount' => '1'
- ),
- 'OCT2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
- 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOHEX',
- 'argumentCount' => '1,2'
- ),
- 'ODD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::ODD',
- 'argumentCount' => '1'
- ),
- 'ODDFPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '8,9'
- ),
- 'ODDFYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '8,9'
- ),
- 'ODDLPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '7,8'
- ),
- 'ODDLYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '7,8'
- ),
- 'OFFSET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::OFFSET',
- 'argumentCount' => '3,5',
- 'passCellReference'=> true,
- 'passByReference' => array(true)
- ),
- 'OR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_OR',
- 'argumentCount' => '1+'
- ),
- 'PEARSON' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL',
- 'argumentCount' => '2'
- ),
- 'PERCENTILE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTILE',
- 'argumentCount' => '2'
- ),
- 'PERCENTRANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTRANK',
- 'argumentCount' => '2,3'
- ),
- 'PERMUT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::PERMUT',
- 'argumentCount' => '2'
- ),
- 'PHONETIC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'PI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'pi',
- 'argumentCount' => '0'
- ),
- 'PMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::PMT',
- 'argumentCount' => '3-5'
- ),
- 'POISSON' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::POISSON',
- 'argumentCount' => '3'
- ),
- 'POWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::POWER',
- 'argumentCount' => '2'
- ),
- 'PPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::PPMT',
- 'argumentCount' => '4-6'
- ),
- 'PRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::PRICE',
- 'argumentCount' => '6,7'
- ),
- 'PRICEDISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEDISC',
- 'argumentCount' => '4,5'
- ),
- 'PRICEMAT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEMAT',
- 'argumentCount' => '5,6'
- ),
- 'PROB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '3,4'
- ),
- 'PRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::PRODUCT',
- 'argumentCount' => '1+'
- ),
- 'PROPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::PROPERCASE',
- 'argumentCount' => '1'
- ),
- 'PV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::PV',
- 'argumentCount' => '3-5'
- ),
- 'QUARTILE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::QUARTILE',
- 'argumentCount' => '2'
- ),
- 'QUOTIENT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::QUOTIENT',
- 'argumentCount' => '2'
- ),
- 'RADIANS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'deg2rad',
- 'argumentCount' => '1'
- ),
- 'RAND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND',
- 'argumentCount' => '0'
- ),
- 'RANDBETWEEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND',
- 'argumentCount' => '2'
- ),
- 'RANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::RANK',
- 'argumentCount' => '2,3'
- ),
- 'RATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::RATE',
- 'argumentCount' => '3-6'
- ),
- 'RECEIVED' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::RECEIVED',
- 'argumentCount' => '4-5'
- ),
- 'REPLACE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE',
- 'argumentCount' => '4'
- ),
- 'REPLACEB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE',
- 'argumentCount' => '4'
- ),
- 'REPT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'str_repeat',
- 'argumentCount' => '2'
- ),
- 'RIGHT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT',
- 'argumentCount' => '1,2'
- ),
- 'RIGHTB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT',
- 'argumentCount' => '1,2'
- ),
- 'ROMAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROMAN',
- 'argumentCount' => '1,2'
- ),
- 'ROUND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'round',
- 'argumentCount' => '2'
- ),
- 'ROUNDDOWN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDDOWN',
- 'argumentCount' => '2'
- ),
- 'ROUNDUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDUP',
- 'argumentCount' => '2'
- ),
- 'ROW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROW',
- 'argumentCount' => '-1',
- 'passByReference' => array(true)
- ),
- 'ROWS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROWS',
- 'argumentCount' => '1'
- ),
- 'RSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::RSQ',
- 'argumentCount' => '2'
- ),
- 'RTD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1+'
- ),
- 'SEARCH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'SEARCHB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE',
- 'argumentCount' => '2,3'
- ),
- 'SECOND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::SECONDOFMINUTE',
- 'argumentCount' => '1'
- ),
- 'SERIESSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SERIESSUM',
- 'argumentCount' => '4'
- ),
- 'SIGN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SIGN',
- 'argumentCount' => '1'
- ),
- 'SIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sin',
- 'argumentCount' => '1'
- ),
- 'SINH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sinh',
- 'argumentCount' => '1'
- ),
- 'SKEW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::SKEW',
- 'argumentCount' => '1+'
- ),
- 'SLN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::SLN',
- 'argumentCount' => '3'
- ),
- 'SLOPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::SLOPE',
- 'argumentCount' => '2'
- ),
- 'SMALL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::SMALL',
- 'argumentCount' => '2'
- ),
- 'SQRT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sqrt',
- 'argumentCount' => '1'
- ),
- 'SQRTPI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SQRTPI',
- 'argumentCount' => '1'
- ),
- 'STANDARDIZE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::STANDARDIZE',
- 'argumentCount' => '3'
- ),
- 'STDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEV',
- 'argumentCount' => '1+'
- ),
- 'STDEVA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVA',
- 'argumentCount' => '1+'
- ),
- 'STDEVP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVP',
- 'argumentCount' => '1+'
- ),
- 'STDEVPA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVPA',
- 'argumentCount' => '1+'
- ),
- 'STEYX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::STEYX',
- 'argumentCount' => '2'
- ),
- 'SUBSTITUTE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::SUBSTITUTE',
- 'argumentCount' => '3,4'
- ),
- 'SUBTOTAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUBTOTAL',
- 'argumentCount' => '2+'
- ),
- 'SUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUM',
- 'argumentCount' => '1+'
- ),
- 'SUMIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIF',
- 'argumentCount' => '2,3'
- ),
- 'SUMIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '?'
- ),
- 'SUMPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMPRODUCT',
- 'argumentCount' => '1+'
- ),
- 'SUMSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMSQ',
- 'argumentCount' => '1+'
- ),
- 'SUMX2MY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2MY2',
- 'argumentCount' => '2'
- ),
- 'SUMX2PY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2PY2',
- 'argumentCount' => '2'
- ),
- 'SUMXMY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMXMY2',
- 'argumentCount' => '2'
- ),
- 'SYD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::SYD',
- 'argumentCount' => '4'
- ),
- 'T' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::RETURNSTRING',
- 'argumentCount' => '1'
- ),
- 'TAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'tan',
- 'argumentCount' => '1'
- ),
- 'TANH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'tanh',
- 'argumentCount' => '1'
- ),
- 'TBILLEQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLEQ',
- 'argumentCount' => '3'
- ),
- 'TBILLPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLPRICE',
- 'argumentCount' => '3'
- ),
- 'TBILLYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLYIELD',
- 'argumentCount' => '3'
- ),
- 'TDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::TDIST',
- 'argumentCount' => '3'
- ),
- 'TEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::TEXTFORMAT',
- 'argumentCount' => '2'
- ),
- 'TIME' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::TIME',
- 'argumentCount' => '3'
- ),
- 'TIMEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::TIMEVALUE',
- 'argumentCount' => '1'
- ),
- 'TINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::TINV',
- 'argumentCount' => '2'
- ),
- 'TODAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DATENOW',
- 'argumentCount' => '0'
- ),
- 'TRANSPOSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::TRANSPOSE',
- 'argumentCount' => '1'
- ),
- 'TREND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::TREND',
- 'argumentCount' => '1-4'
- ),
- 'TRIM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMSPACES',
- 'argumentCount' => '1'
- ),
- 'TRIMMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::TRIMMEAN',
- 'argumentCount' => '2'
- ),
- 'TRUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
- 'functionCall' => 'PHPExcel_Calculation_Logical::TRUE',
- 'argumentCount' => '0'
- ),
- 'TRUNC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'PHPExcel_Calculation_MathTrig::TRUNC',
- 'argumentCount' => '1,2'
- ),
- 'TTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '4'
- ),
- 'TYPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::TYPE',
- 'argumentCount' => '1'
- ),
- 'UPPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_TextData::UPPERCASE',
- 'argumentCount' => '1'
- ),
- 'USDOLLAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '2'
- ),
- 'VALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '1'
- ),
- 'VAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::VARFunc',
- 'argumentCount' => '1+'
- ),
- 'VARA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::VARA',
- 'argumentCount' => '1+'
- ),
- 'VARP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::VARP',
- 'argumentCount' => '1+'
- ),
- 'VARPA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::VARPA',
- 'argumentCount' => '1+'
- ),
- 'VDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '5-7'
- ),
- 'VERSION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
- 'functionCall' => 'PHPExcel_Calculation_Functions::VERSION',
- 'argumentCount' => '0'
- ),
- 'VLOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => 'PHPExcel_Calculation_LookupRef::VLOOKUP',
- 'argumentCount' => '3,4'
- ),
- 'WEEKDAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFWEEK',
- 'argumentCount' => '1,2'
- ),
- 'WEEKNUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::WEEKOFYEAR',
- 'argumentCount' => '1,2'
- ),
- 'WEIBULL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::WEIBULL',
- 'argumentCount' => '4'
- ),
- 'WORKDAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::WORKDAY',
- 'argumentCount' => '2+'
- ),
- 'XIRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::XIRR',
- 'argumentCount' => '2,3'
- ),
- 'XNPV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::XNPV',
- 'argumentCount' => '3'
- ),
- 'YEAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::YEAR',
- 'argumentCount' => '1'
- ),
- 'YEARFRAC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
- 'functionCall' => 'PHPExcel_Calculation_DateTime::YEARFRAC',
- 'argumentCount' => '2,3'
- ),
- 'YIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
- 'argumentCount' => '6,7'
- ),
- 'YIELDDISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDDISC',
- 'argumentCount' => '4,5'
- ),
- 'YIELDMAT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
- 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDMAT',
- 'argumentCount' => '5,6'
- ),
- 'ZTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
- 'functionCall' => 'PHPExcel_Calculation_Statistical::ZTEST',
- 'argumentCount' => '2-3'
- )
- );
-
-
- // Internal functions used for special control purposes
- private static $_controlFunctions = array(
- 'MKMATRIX' => array('argumentCount' => '*',
- 'functionCall' => 'self::_mkMatrix'
- )
- );
-
-
-
-
- private function __construct() {
- $setPrecision = (PHP_INT_SIZE == 4) ? 12 : 16;
- $this->_savedPrecision = ini_get('precision');
- if ($this->_savedPrecision < $setPrecision) {
- ini_set('precision',$setPrecision);
- }
- } // function __construct()
-
-
- public function __destruct() {
- if ($this->_savedPrecision != ini_get('precision')) {
- ini_set('precision',$this->_savedPrecision);
- }
- }
-
- private static function _loadLocales() {
- $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/';
- foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) {
- $filename = substr($filename,strlen($localeFileDirectory)+1);
- if ($filename != 'en') {
- self::$_validLocaleLanguages[] = $filename;
- }
- }
- }
-
- /**
- * Get an instance of this class
- *
- * @access public
- * @return PHPExcel_Calculation
- */
- public static function getInstance() {
- if (!isset(self::$_instance) || (self::$_instance === NULL)) {
- self::$_instance = new PHPExcel_Calculation();
- }
-
- return self::$_instance;
- } // function getInstance()
-
-
- /**
- * Flush the calculation cache for any existing instance of this class
- * but only if a PHPExcel_Calculation instance exists
- *
- * @access public
- * @return null
- */
- public static function flushInstance() {
- if (isset(self::$_instance) && (self::$_instance !== NULL)) {
- self::$_instance->clearCalculationCache();
- }
- } // function flushInstance()
-
-
- /**
- * __clone implementation. Cloning should not be allowed in a Singleton!
- *
- * @access public
- * @throws PHPExcel_Calculation_Exception
- */
- public final function __clone() {
- throw new PHPExcel_Calculation_Exception ('Cloning a Singleton is not allowed!');
- } // function __clone()
-
-
- /**
- * Return the locale-specific translation of TRUE
- *
- * @access public
- * @return string locale-specific translation of TRUE
- */
- public static function getTRUE() {
- return self::$_localeBoolean['TRUE'];
- }
-
- /**
- * Return the locale-specific translation of FALSE
- *
- * @access public
- * @return string locale-specific translation of FALSE
- */
- public static function getFALSE() {
- return self::$_localeBoolean['FALSE'];
- }
-
- /**
- * Set the Array Return Type (Array or Value of first element in the array)
- *
- * @access public
- * @param string $returnType Array return type
- * @return boolean Success or failure
- */
- public static function setArrayReturnType($returnType) {
- if (($returnType == self::RETURN_ARRAY_AS_VALUE) ||
- ($returnType == self::RETURN_ARRAY_AS_ERROR) ||
- ($returnType == self::RETURN_ARRAY_AS_ARRAY)) {
- self::$returnArrayAsType = $returnType;
- return true;
- }
- return false;
- } // function setExcelCalendar()
-
-
- /**
- * Return the Array Return Type (Array or Value of first element in the array)
- *
- * @access public
- * @return string $returnType Array return type
- */
- public static function getArrayReturnType() {
- return self::$returnArrayAsType;
- } // function getExcelCalendar()
-
-
- /**
- * Is calculation caching enabled?
- *
- * @access public
- * @return boolean
- */
- public function getCalculationCacheEnabled() {
- return self::$_calculationCacheEnabled;
- } // function getCalculationCacheEnabled()
-
-
- /**
- * Enable/disable calculation cache
- *
- * @access public
- * @param boolean $pValue
- */
- public function setCalculationCacheEnabled($pValue = true) {
- self::$_calculationCacheEnabled = $pValue;
- $this->clearCalculationCache();
- } // function setCalculationCacheEnabled()
-
-
- /**
- * Enable calculation cache
- */
- public function enableCalculationCache() {
- $this->setCalculationCacheEnabled(true);
- } // function enableCalculationCache()
-
-
- /**
- * Disable calculation cache
- */
- public function disableCalculationCache() {
- $this->setCalculationCacheEnabled(false);
- } // function disableCalculationCache()
-
-
- /**
- * Clear calculation cache
- */
- public function clearCalculationCache() {
- self::$_calculationCache = array();
- } // function clearCalculationCache()
-
-
- /**
- * Get the currently defined locale code
- *
- * @return string
- */
- public function getLocale() {
- return self::$_localeLanguage;
- } // function getLocale()
-
-
- /**
- * Set the locale code
- *
- * @return boolean
- */
- public function setLocale($locale='en_us') {
- // Identify our locale and language
- $language = $locale = strtolower($locale);
- if (strpos($locale,'_') !== false) {
- list($language) = explode('_',$locale);
- }
-
- if (count(self::$_validLocaleLanguages) == 1)
- self::_loadLocales();
-
- // Test whether we have any language data for this language (any locale)
- if (in_array($language,self::$_validLocaleLanguages)) {
- // initialise language/locale settings
- self::$_localeFunctions = array();
- self::$_localeArgumentSeparator = ',';
- self::$_localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL');
- // Default is English, if user isn't requesting english, then read the necessary data from the locale files
- if ($locale != 'en_us') {
- // Search for a file with a list of function names for locale
- $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'functions';
- if (!file_exists($functionNamesFile)) {
- // If there isn't a locale specific function file, look for a language specific function file
- $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions';
- if (!file_exists($functionNamesFile)) {
- return false;
- }
- }
- // Retrieve the list of locale or language specific function names
- $localeFunctions = file($functionNamesFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($localeFunctions as $localeFunction) {
- list($localeFunction) = explode('##',$localeFunction); // Strip out comments
- if (strpos($localeFunction,'=') !== false) {
- list($fName,$lfName) = explode('=',$localeFunction);
- $fName = trim($fName);
- $lfName = trim($lfName);
- if ((isset(self::$_PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
- self::$_localeFunctions[$fName] = $lfName;
- }
- }
- }
- // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
- if (isset(self::$_localeFunctions['TRUE'])) { self::$_localeBoolean['TRUE'] = self::$_localeFunctions['TRUE']; }
- if (isset(self::$_localeFunctions['FALSE'])) { self::$_localeBoolean['FALSE'] = self::$_localeFunctions['FALSE']; }
-
- $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'config';
- if (!file_exists($configFile)) {
- $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config';
- }
- if (file_exists($configFile)) {
- $localeSettings = file($configFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($localeSettings as $localeSetting) {
- list($localeSetting) = explode('##',$localeSetting); // Strip out comments
- if (strpos($localeSetting,'=') !== false) {
- list($settingName,$settingValue) = explode('=',$localeSetting);
- $settingName = strtoupper(trim($settingName));
- switch ($settingName) {
- case 'ARGUMENTSEPARATOR' :
- self::$_localeArgumentSeparator = trim($settingValue);
- break;
- }
- }
- }
- }
- }
-
- self::$functionReplaceFromExcel = self::$functionReplaceToExcel =
- self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null;
- self::$_localeLanguage = $locale;
- return true;
- }
- return false;
- } // function setLocale()
-
-
-
- public static function _translateSeparator($fromSeparator,$toSeparator,$formula,&$inBraces) {
- $strlen = mb_strlen($formula);
- for ($i = 0; $i < $strlen; ++$i) {
- $chr = mb_substr($formula,$i,1);
- switch ($chr) {
- case '{' : $inBraces = true;
- break;
- case '}' : $inBraces = false;
- break;
- case $fromSeparator :
- if (!$inBraces) {
- $formula = mb_substr($formula,0,$i).$toSeparator.mb_substr($formula,$i+1);
- }
- }
- }
- return $formula;
- }
-
- private static function _translateFormula($from,$to,$formula,$fromSeparator,$toSeparator) {
- // Convert any Excel function names to the required language
- if (self::$_localeLanguage !== 'en_us') {
- $inBraces = false;
- // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
- if (strpos($formula,'"') !== false) {
- // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
- // the formula
- $temp = explode('"',$formula);
- $i = false;
- foreach($temp as &$value) {
- // Only count/replace in alternating array entries
- if ($i = !$i) {
- $value = preg_replace($from,$to,$value);
- $value = self::_translateSeparator($fromSeparator,$toSeparator,$value,$inBraces);
- }
- }
- unset($value);
- // Then rebuild the formula string
- $formula = implode('"',$temp);
- } else {
- // If there's no quoted strings, then we do a simple count/replace
- $formula = preg_replace($from,$to,$formula);
- $formula = self::_translateSeparator($fromSeparator,$toSeparator,$formula,$inBraces);
- }
- }
-
- return $formula;
- }
-
- private static $functionReplaceFromExcel = null;
- private static $functionReplaceToLocale = null;
-
- public function _translateFormulaToLocale($formula) {
- if (self::$functionReplaceFromExcel === NULL) {
- self::$functionReplaceFromExcel = array();
- foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
- self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui';
- }
- foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
- self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
- }
-
- }
-
- if (self::$functionReplaceToLocale === NULL) {
- self::$functionReplaceToLocale = array();
- foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
- self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2';
- }
- foreach(array_values(self::$_localeBoolean) as $localeBoolean) {
- self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2';
- }
- }
-
- return self::_translateFormula(self::$functionReplaceFromExcel,self::$functionReplaceToLocale,$formula,',',self::$_localeArgumentSeparator);
- } // function _translateFormulaToLocale()
-
-
- private static $functionReplaceFromLocale = null;
- private static $functionReplaceToExcel = null;
-
- public function _translateFormulaToEnglish($formula) {
- if (self::$functionReplaceFromLocale === NULL) {
- self::$functionReplaceFromLocale = array();
- foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
- self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui';
- }
- foreach(array_values(self::$_localeBoolean) as $excelBoolean) {
- self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
- }
- }
-
- if (self::$functionReplaceToExcel === NULL) {
- self::$functionReplaceToExcel = array();
- foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
- self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2';
- }
- foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
- self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2';
- }
- }
-
- return self::_translateFormula(self::$functionReplaceFromLocale,self::$functionReplaceToExcel,$formula,self::$_localeArgumentSeparator,',');
- } // function _translateFormulaToEnglish()
-
-
- public static function _localeFunc($function) {
- if (self::$_localeLanguage !== 'en_us') {
- $functionName = trim($function,'(');
- if (isset(self::$_localeFunctions[$functionName])) {
- $brace = ($functionName != $function);
- $function = self::$_localeFunctions[$functionName];
- if ($brace) { $function .= '('; }
- }
- }
- return $function;
- }
-
-
-
-
- /**
- * Wrap string values in quotes
- *
- * @param mixed $value
- * @return mixed
- */
- public static function _wrapResult($value) {
- if (is_string($value)) {
- // Error values cannot be "wrapped"
- if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) {
- // Return Excel errors "as is"
- return $value;
- }
- // Return strings wrapped in quotes
- return '"'.$value.'"';
- // Convert numeric errors to NaN error
- } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return $value;
- } // function _wrapResult()
-
-
- /**
- * Remove quotes used as a wrapper to identify string values
- *
- * @param mixed $value
- * @return mixed
- */
- public static function _unwrapResult($value) {
- if (is_string($value)) {
- if ((isset($value{0})) && ($value{0} == '"') && (substr($value,-1) == '"')) {
- return substr($value,1,-1);
- }
- // Convert numeric errors to NaN error
- } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return $value;
- } // function _unwrapResult()
-
-
-
-
- /**
- * Calculate cell value (using formula from a cell ID)
- * Retained for backward compatibility
- *
- * @access public
- * @param PHPExcel_Cell $pCell Cell to calculate
- * @return mixed
- * @throws PHPExcel_Calculation_Exception
- */
- public function calculate(PHPExcel_Cell $pCell = null) {
- try {
- return $this->calculateCellValue($pCell);
- } catch (PHPExcel_Exception $e) {
- throw(new PHPExcel_Calculation_Exception($e->getMessage()));
- }
- } // function calculate()
-
-
- /**
- * 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 ($resetLog) {
- // Initialise the logging settings if requested
- $this->formulaError = null;
- $this->debugLog = $this->debugLogStack = array();
- $this->_cyclicFormulaCount = 1;
-
- $returnArrayAsType = self::$returnArrayAsType;
- self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY;
- }
-
- // Read the formula from the cell
- if ($pCell === NULL) {
- return NULL;
- }
-
- if ($resetLog) {
- self::$returnArrayAsType = $returnArrayAsType;
- }
- // Execute the calculation for the cell formula
- try {
- $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
- } catch (PHPExcel_Exception $e) {
- throw(new PHPExcel_Calculation_Exception($e->getMessage()));
- }
-
- if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
- $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);
- }
-
- if ($result === NULL) {
- return 0;
- } elseif((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return $result;
- } // function calculateCellValue(
-
-
- /**
- * Validate and parse a formula string
- *
- * @param string $formula Formula to parse
- * @return array
- * @throws PHPExcel_Calculation_Exception
- */
- public function parseFormula($formula) {
- // Basic validation that this is indeed a formula
- // We return an empty array if not
- $formula = trim($formula);
- if ((!isset($formula{0})) || ($formula{0} != '=')) return array();
- $formula = ltrim(substr($formula,1));
- if (!isset($formula{0})) return array();
-
- // Parse the formula and return the token stack
- return $this->_parseFormula($formula);
- } // function parseFormula()
-
-
- /**
- * Calculate the value of a formula
- *
- * @param string $formula Formula to parse
- * @return mixed
- * @throws PHPExcel_Calculation_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 (PHPExcel_Exception $e) {
- throw(new PHPExcel_Calculation_Exception($e->getMessage()));
- }
-
- // Reset calculation cacheing to its previous state
- self::$_calculationCacheEnabled = $resetCache;
-
- return $result;
- } // function calculateFormula()
-
-
- /**
- * Parse a cell formula and calculate its value
- *
- * @param string $formula The formula to parse and calculate
- * @param string $cellID The ID (e.g. A3) of the cell that we are calculating
- * @param PHPExcel_Cell $pCell Cell to calculate
- * @return mixed
- * @throws PHPExcel_Calculation_Exception
- */
- public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) {
-// echo ''.$cellID.'
';
- $cellValue = '';
-
- // Basic validation that this is indeed a formula
- // We simply return the "cell value" (formula) if not
- $formula = trim($formula);
- if ($formula{0} != '=') return self::_wrapResult($formula);
- $formula = ltrim(substr($formula,1));
- if (!isset($formula{0})) return self::_wrapResult($formula);
-
- $wsTitle = "\x00Wrk";
- if ($pCell !== NULL) {
- $pCellParent = $pCell->getParent();
- if ($pCellParent !== NULL) {
- $wsTitle = $pCellParent->getTitle();
- }
- }
- // Is calculation cacheing enabled?
- if ($cellID !== NULL) {
- if (self::$_calculationCacheEnabled) {
- // Is the value present in calculation cache?
- $this->_writeDebug('Testing cache value for cell ', $cellID);
-// echo 'Testing cache value
';
- if (isset(self::$_calculationCache[$wsTitle][$cellID])) {
-// echo 'Value is in cache
';
- $this->_writeDebug('Retrieving value for ', $cellID, ' from cache');
- // Return the cached result
- $returnValue = self::$_calculationCache[$wsTitle][$cellID];
-// echo 'Retrieving data value of '.$returnValue.' for '.$cellID.' from cache
';
- if (is_array($returnValue)) {
- $returnValue = PHPExcel_Calculation_Functions::flattenArray($returnValue);
- return array_shift($returnValue);
- }
- return $returnValue;
- }
- }
- }
-
- if ((in_array($wsTitle.'!'.$cellID,$this->debugLogStack)) && ($wsTitle != "\x00Wrk")) {
- if ($this->cyclicFormulaCount <= 0) {
- return $this->_raiseFormulaError('Cyclic Reference in Formula');
- } elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
- ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
- return $cellValue;
- } elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
- ++$this->_cyclicFormulaCount;
- if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
- return $cellValue;
- }
- } elseif ($this->_cyclicFormulaCell == '') {
- $this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
- if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
- return $cellValue;
- }
- }
- }
- $this->debugLogStack[] = $wsTitle.'!'.$cellID;
- // Parse the formula onto the token stack and calculate the value
- $cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
- array_pop($this->debugLogStack);
-
- // Save to calculation cache
- if ($cellID !== NULL) {
- if (self::$_calculationCacheEnabled) {
- self::$_calculationCache[$wsTitle][$cellID] = $cellValue;
- }
- }
-
- // Return the calculated value
- return $cellValue;
- } // function _calculateFormulaValue()
-
-
- /**
- * Ensure that paired matrix operands are both matrices and of the same size
- *
- * @param mixed &$operand1 First matrix operand
- * @param mixed &$operand2 Second matrix operand
- * @param integer $resize Flag indicating whether the matrices should be resized to match
- * and (if so), whether the smaller dimension should grow or the
- * larger should shrink.
- * 0 = no resize
- * 1 = shrink to fit
- * 2 = extend to fit
- */
- private static function _checkMatrixOperands(&$operand1,&$operand2,$resize = 1) {
- // Examine each of the two operands, and turn them into an array if they aren't one already
- // Note that this function should only be called if one or both of the operand is already an array
- if (!is_array($operand1)) {
- list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand2);
- $operand1 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand1));
- $resize = 0;
- } elseif (!is_array($operand2)) {
- list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand1);
- $operand2 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand2));
- $resize = 0;
- }
-
- list($matrix1Rows,$matrix1Columns) = self::_getMatrixDimensions($operand1);
- list($matrix2Rows,$matrix2Columns) = self::_getMatrixDimensions($operand2);
- if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
- $resize = 1;
- }
-
- if ($resize == 2) {
- // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
- self::_resizeMatricesExtend($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
- } elseif ($resize == 1) {
- // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
- self::_resizeMatricesShrink($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
- }
- return array( $matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
- } // function _checkMatrixOperands()
-
-
- /**
- * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0
- *
- * @param mixed &$matrix matrix operand
- * @return array An array comprising the number of rows, and number of columns
- */
- public static function _getMatrixDimensions(&$matrix) {
- $matrixRows = count($matrix);
- $matrixColumns = 0;
- foreach($matrix as $rowKey => $rowValue) {
- $matrixColumns = max(count($rowValue),$matrixColumns);
- if (!is_array($rowValue)) {
- $matrix[$rowKey] = array($rowValue);
- } else {
- $matrix[$rowKey] = array_values($rowValue);
- }
- }
- $matrix = array_values($matrix);
- return array($matrixRows,$matrixColumns);
- } // function _getMatrixDimensions()
-
-
- /**
- * Ensure that paired matrix operands are both matrices of the same size
- *
- * @param mixed &$matrix1 First matrix operand
- * @param mixed &$matrix2 Second matrix operand
- */
- private static function _resizeMatricesShrink(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
- if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
- if ($matrix2Columns < $matrix1Columns) {
- for ($i = 0; $i < $matrix1Rows; ++$i) {
- for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
- unset($matrix1[$i][$j]);
- }
- }
- }
- if ($matrix2Rows < $matrix1Rows) {
- for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
- unset($matrix1[$i]);
- }
- }
- }
-
- if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
- if ($matrix1Columns < $matrix2Columns) {
- for ($i = 0; $i < $matrix2Rows; ++$i) {
- for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
- unset($matrix2[$i][$j]);
- }
- }
- }
- if ($matrix1Rows < $matrix2Rows) {
- for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
- unset($matrix2[$i]);
- }
- }
- }
- } // function _resizeMatricesShrink()
-
-
- /**
- * Ensure that paired matrix operands are both matrices of the same size
- *
- * @param mixed &$matrix1 First matrix operand
- * @param mixed &$matrix2 Second matrix operand
- */
- private static function _resizeMatricesExtend(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
- if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
- if ($matrix2Columns < $matrix1Columns) {
- for ($i = 0; $i < $matrix2Rows; ++$i) {
- $x = $matrix2[$i][$matrix2Columns-1];
- for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
- $matrix2[$i][$j] = $x;
- }
- }
- }
- if ($matrix2Rows < $matrix1Rows) {
- $x = $matrix2[$matrix2Rows-1];
- for ($i = 0; $i < $matrix1Rows; ++$i) {
- $matrix2[$i] = $x;
- }
- }
- }
-
- if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
- if ($matrix1Columns < $matrix2Columns) {
- for ($i = 0; $i < $matrix1Rows; ++$i) {
- $x = $matrix1[$i][$matrix1Columns-1];
- for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
- $matrix1[$i][$j] = $x;
- }
- }
- }
- if ($matrix1Rows < $matrix2Rows) {
- $x = $matrix1[$matrix1Rows-1];
- for ($i = 0; $i < $matrix2Rows; ++$i) {
- $matrix1[$i] = $x;
- }
- }
- }
- } // function _resizeMatricesExtend()
-
-
- /**
- * Format details of an operand for display in the log (based on operand type)
- *
- * @param mixed $value First matrix operand
- * @return mixed
- */
- private function _showValue($value) {
- if ($this->writeDebugLog) {
- $testArray = PHPExcel_Calculation_Functions::flattenArray($value);
- if (count($testArray) == 1) {
- $value = array_pop($testArray);
- }
-
- if (is_array($value)) {
- $returnMatrix = array();
- $pad = $rpad = ', ';
- foreach($value as $row) {
- if (is_array($row)) {
- $returnMatrix[] = implode($pad,array_map(array($this,'_showValue'),$row));
- $rpad = '; ';
- } else {
- $returnMatrix[] = $this->_showValue($row);
- }
- }
- return '{ '.implode($rpad,$returnMatrix).' }';
- } elseif(is_string($value) && (trim($value,'"') == $value)) {
- return '"'.$value.'"';
- } elseif(is_bool($value)) {
- return ($value) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
- }
- }
- return PHPExcel_Calculation_Functions::flattenSingleValue($value);
- } // function _showValue()
-
-
- /**
- * Format type and details of an operand for display in the log (based on operand type)
- *
- * @param mixed $value First matrix operand
- * @return mixed
- */
- private function _showTypeDetails($value) {
- if ($this->writeDebugLog) {
- $testArray = PHPExcel_Calculation_Functions::flattenArray($value);
- if (count($testArray) == 1) {
- $value = array_pop($testArray);
- }
-
- if ($value === NULL) {
- return 'a NULL value';
- } elseif (is_float($value)) {
- $typeString = 'a floating point number';
- } elseif(is_int($value)) {
- $typeString = 'an integer number';
- } elseif(is_bool($value)) {
- $typeString = 'a boolean';
- } elseif(is_array($value)) {
- $typeString = 'a matrix';
- } else {
- if ($value == '') {
- return 'an empty string';
- } elseif ($value{0} == '#') {
- return 'a '.$value.' error';
- } else {
- $typeString = 'a string';
- }
- }
- return $typeString.' with a value of '.$this->_showValue($value);
- }
- } // function _showTypeDetails()
-
-
- private static function _convertMatrixReferences($formula) {
- static $matrixReplaceFrom = array('{',';','}');
- static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(','),MKMATRIX(','))');
-
- // Convert any Excel matrix references to the MKMATRIX() function
- if (strpos($formula,'{') !== false) {
- // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
- if (strpos($formula,'"') !== false) {
- // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
- // the formula
- $temp = explode('"',$formula);
- // Open and Closed counts used for trapping mismatched braces in the formula
- $openCount = $closeCount = 0;
- $i = false;
- foreach($temp as &$value) {
- // Only count/replace in alternating array entries
- if ($i = !$i) {
- $openCount += substr_count($value,'{');
- $closeCount += substr_count($value,'}');
- $value = str_replace($matrixReplaceFrom,$matrixReplaceTo,$value);
- }
- }
- unset($value);
- // Then rebuild the formula string
- $formula = implode('"',$temp);
- } else {
- // If there's no quoted strings, then we do a simple count/replace
- $openCount = substr_count($formula,'{');
- $closeCount = substr_count($formula,'}');
- $formula = str_replace($matrixReplaceFrom,$matrixReplaceTo,$formula);
- }
- // Trap for mismatched braces and trigger an appropriate error
- if ($openCount < $closeCount) {
- if ($openCount > 0) {
- return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
- } else {
- return $this->_raiseFormulaError("Formula Error: Unexpected '}' encountered");
- }
- } elseif ($openCount > $closeCount) {
- if ($closeCount > 0) {
- return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
- } else {
- return $this->_raiseFormulaError("Formula Error: Unexpected '{' encountered");
- }
- }
- }
-
- return $formula;
- } // function _convertMatrixReferences()
-
-
- private static function _mkMatrix() {
- return func_get_args();
- } // function _mkMatrix()
-
-
- // Convert infix to postfix notation
- private function _parseFormula($formula, PHPExcel_Cell $pCell = null) {
- if (($formula = self::_convertMatrixReferences(trim($formula))) === false) {
- return FALSE;
- }
-
- // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
- // so we store the parent worksheet so that we can re-attach it when necessary
- $pCellParent = ($pCell !== NULL) ? $pCell->getParent() : NULL;
-
- // Binary Operators
- // These operators always work on two values
- // Array key is the operator, the value indicates whether this is a left or right associative operator
- $operatorAssociativity = array('^' => 0, // Exponentiation
- '*' => 0, '/' => 0, // Multiplication and Division
- '+' => 0, '-' => 0, // Addition and Subtraction
- '&' => 0, // Concatenation
- '|' => 0, ':' => 0, // Intersect and Range
- '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
- );
- // Comparison (Boolean) Operators
- // These operators work on two values, but always return a boolean result
- $comparisonOperators = array('>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true);
-
- // Operator Precedence
- // This list includes all valid operators, whether binary (including boolean) or unary (such as %)
- // Array key is the operator, the value is its precedence
- $operatorPrecedence = array(':' => 8, // Range
- '|' => 7, // Intersect
- '~' => 6, // Negation
- '%' => 5, // Percentage
- '^' => 4, // Exponentiation
- '*' => 3, '/' => 3, // Multiplication and Division
- '+' => 2, '-' => 2, // Addition and Subtraction
- '&' => 1, // Concatenation
- '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
- );
-
- $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION.
- '|'.self::CALCULATION_REGEXP_NUMBER.
- '|'.self::CALCULATION_REGEXP_STRING.
- '|'.self::CALCULATION_REGEXP_OPENBRACE.
- '|'.self::CALCULATION_REGEXP_CELLREF.
- '|'.self::CALCULATION_REGEXP_NAMEDRANGE.
- '|'.self::CALCULATION_REGEXP_ERROR.
- ')/si';
-
- // Start with initialisation
- $index = 0;
- $stack = new PHPExcel_Calculation_Token_Stack;
- $output = array();
- $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a
- // - is a negation or + is a positive operator rather than an operation
- $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand
- // should be null in a function call
- // The guts of the lexical parser
- // Loop through the formula extracting each operator and operand in turn
- while(true) {
-// echo 'Assessing Expression '.substr($formula, $index).'
';
- $opCharacter = $formula{$index}; // Get the first character of the value at the current index position
-// echo 'Initial character of expression block is '.$opCharacter.'
';
- if ((isset($comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset($comparisonOperators[$formula{$index+1}]))) {
- $opCharacter .= $formula{++$index};
-// echo 'Initial character of expression block is comparison operator '.$opCharacter.'
';
- }
-
- // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand
- $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match);
-// echo '$isOperandOrFunction is '.(($isOperandOrFunction) ? 'True' : 'False').'
';
-// var_dump($match);
-
- if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus?
-// echo 'Element is a Negation operator
';
- $stack->push('Unary Operator','~'); // Put a negation on the stack
- ++$index; // and drop the negation symbol
- } elseif ($opCharacter == '%' && $expectingOperator) {
-// echo 'Element is a Percentage operator
';
- $stack->push('Unary Operator','%'); // Put a percentage on the stack
- ++$index;
- } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded?
-// echo 'Element is a Positive number, not Plus operator
';
- ++$index; // Drop the redundant plus symbol
- } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal
- return $this->_raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression
-
- } elseif ((isset(self::$_operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack?
-// echo 'Element with value '.$opCharacter.' is an Operator
';
- while($stack->count() > 0 &&
- ($o2 = $stack->last()) &&
- isset(self::$_operators[$o2['value']]) &&
- @($operatorAssociativity[$opCharacter] ? $operatorPrecedence[$opCharacter] < $operatorPrecedence[$o2['value']] : $operatorPrecedence[$opCharacter] <= $operatorPrecedence[$o2['value']])) {
- $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
- }
- $stack->push('Binary Operator',$opCharacter); // Finally put our current operator onto the stack
- ++$index;
- $expectingOperator = false;
-
- } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis?
-// echo 'Element is a Closing bracket
';
- $expectingOperand = false;
- while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
- if ($o2 === NULL) return $this->_raiseFormulaError('Formula Error: Unexpected closing brace ")"');
- else $output[] = $o2;
- }
- $d = $stack->last(2);
- if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function?
- $functionName = $matches[1]; // Get the function name
-// echo 'Closed Function is '.$functionName.'
';
- $d = $stack->pop();
- $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack)
-// if ($argumentCount == 0) {
-// echo 'With no arguments
';
-// } elseif ($argumentCount == 1) {
-// echo 'With 1 argument
';
-// } else {
-// echo 'With '.$argumentCount.' arguments
';
-// }
- $output[] = $d; // Dump the argument count on the output
- $output[] = $stack->pop(); // Pop the function and push onto the output
- if (isset(self::$_controlFunctions[$functionName])) {
-// echo 'Built-in function '.$functionName.'
';
- $expectedArgumentCount = self::$_controlFunctions[$functionName]['argumentCount'];
- $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
- } elseif (isset(self::$_PHPExcelFunctions[$functionName])) {
-// echo 'PHPExcel function '.$functionName.'
';
- $expectedArgumentCount = self::$_PHPExcelFunctions[$functionName]['argumentCount'];
- $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
- } else { // did we somehow push a non-function on the stack? this should never happen
- return $this->_raiseFormulaError("Formula Error: Internal error, non-function on stack");
- }
- // Check the argument count
- $argumentCountError = false;
- if (is_numeric($expectedArgumentCount)) {
- if ($expectedArgumentCount < 0) {
-// echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount).'
';
- if ($argumentCount > abs($expectedArgumentCount)) {
- $argumentCountError = true;
- $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount);
- }
- } else {
-// echo '$expectedArgumentCount is numeric '.$expectedArgumentCount.'
';
- if ($argumentCount != $expectedArgumentCount) {
- $argumentCountError = true;
- $expectedArgumentCountString = $expectedArgumentCount;
- }
- }
- } elseif ($expectedArgumentCount != '*') {
- $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/',$expectedArgumentCount,$argMatch);
-// print_r($argMatch);
-// echo '
';
- switch ($argMatch[2]) {
- case '+' :
- if ($argumentCount < $argMatch[1]) {
- $argumentCountError = true;
- $expectedArgumentCountString = $argMatch[1].' or more ';
- }
- break;
- case '-' :
- if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
- $argumentCountError = true;
- $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3];
- }
- break;
- case ',' :
- if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
- $argumentCountError = true;
- $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3];
- }
- break;
- }
- }
- if ($argumentCountError) {
- return $this->_raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected");
- }
- }
- ++$index;
-
- } elseif ($opCharacter == ',') { // Is this the separator for function arguments?
-// echo 'Element is a Function argument separator
';
- while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
- if ($o2 === NULL) return $this->_raiseFormulaError("Formula Error: Unexpected ,");
- else $output[] = $o2; // pop the argument expression stuff and push onto the output
- }
- // If we've a comma when we're expecting an operand, then what we actually have is a null operand;
- // so push a null onto the stack
- if (($expectingOperand) || (!$expectingOperator)) {
- $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => null);
- }
- // make sure there was a function
- $d = $stack->last(2);
- if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches))
- return $this->_raiseFormulaError("Formula Error: Unexpected ,");
- $d = $stack->pop();
- $stack->push($d['type'],++$d['value'],$d['reference']); // increment the argument count
- $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
- $expectingOperator = false;
- $expectingOperand = true;
- ++$index;
-
- } elseif ($opCharacter == '(' && !$expectingOperator) {
-// echo 'Element is an Opening Bracket
';
- $stack->push('Brace', '(');
- ++$index;
-
- } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number?
- $expectingOperator = true;
- $expectingOperand = false;
- $val = $match[1];
- $length = strlen($val);
-// echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function
';
-
- if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) {
- $val = preg_replace('/\s/','',$val);
-// echo 'Element '.$val.' is a Function
';
- if (isset(self::$_PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$_controlFunctions[strtoupper($matches[1])])) { // it's a function
- $stack->push('Function', strtoupper($val));
- $ax = preg_match('/^\s*(\s*\))/i', substr($formula, $index+$length), $amatch);
- if ($ax) {
- $stack->push('Operand Count for Function '.strtoupper($val).')', 0);
- $expectingOperator = true;
- } else {
- $stack->push('Operand Count for Function '.strtoupper($val).')', 1);
- $expectingOperator = false;
- }
- $stack->push('Brace', '(');
- } else { // it's a var w/ implicit multiplication
- $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => null);
- }
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) {
-// echo 'Element '.$val.' is a Cell reference
';
- // Watch for this case-change when modifying to allow cell references in different worksheets...
- // Should only be applied to the actual cell column, not the worksheet name
-
- // If the last entry on the stack was a : operator, then we have a cell range reference
- $testPrevOp = $stack->last(1);
- if ($testPrevOp['value'] == ':') {
- // If we have a worksheet reference, then we're playing with a 3D reference
- if ($matches[2] == '') {
- // Otherwise, we 'inherit' the worksheet reference from the start cell reference
- // The start of the cell range reference should be the last entry in $output
- $startCellRef = $output[count($output)-1]['value'];
- preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches);
- if ($startMatches[2] > '') {
- $val = $startMatches[2].'!'.$val;
- }
- } else {
- return $this->_raiseFormulaError("3D Range references are not yet supported");
- }
- }
-
- $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val);
-// $expectingOperator = false;
- } else { // it's a variable, constant, string, number or boolean
-// echo 'Element is a Variable, Constant, String, Number or Boolean
';
- // If the last entry on the stack was a : operator, then we may have a row or column range reference
- $testPrevOp = $stack->last(1);
- if ($testPrevOp['value'] == ':') {
- $startRowColRef = $output[count($output)-1]['value'];
- $rangeWS1 = '';
- if (strpos('!',$startRowColRef) !== false) {
- list($rangeWS1,$startRowColRef) = explode('!',$startRowColRef);
- }
- if ($rangeWS1 != '') $rangeWS1 .= '!';
- $rangeWS2 = $rangeWS1;
- if (strpos('!',$val) !== false) {
- list($rangeWS2,$val) = explode('!',$val);
- }
- if ($rangeWS2 != '') $rangeWS2 .= '!';
- if ((is_integer($startRowColRef)) && (ctype_digit($val)) &&
- ($startRowColRef <= 1048576) && ($val <= 1048576)) {
- // Row range
- $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
- $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef;
- $val = $rangeWS2.$endRowColRef.$val;
- } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
- (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) {
- // Column range
- $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
- $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1';
- $val = $rangeWS2.$val.$endRowColRef;
- }
- }
-
- $localeConstant = false;
- if ($opCharacter == '"') {
-// echo 'Element is a String
';
- // UnEscape any quotes within the string
- $val = self::_wrapResult(str_replace('""','"',self::_unwrapResult($val)));
- } elseif (is_numeric($val)) {
-// echo 'Element is a Number
';
- if ((strpos($val,'.') !== false) || (stripos($val,'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
-// echo 'Casting '.$val.' to float
';
- $val = (float) $val;
- } else {
-// echo 'Casting '.$val.' to integer
';
- $val = (integer) $val;
- }
- } elseif (isset(self::$_ExcelConstants[trim(strtoupper($val))])) {
- $excelConstant = trim(strtoupper($val));
-// echo 'Element '.$excelConstant.' is an Excel Constant
';
- $val = self::$_ExcelConstants[$excelConstant];
- } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$_localeBoolean)) !== false) {
-// echo 'Element '.$localeConstant.' is an Excel Constant
';
- $val = self::$_ExcelConstants[$localeConstant];
- }
- $details = array('type' => 'Value', 'value' => $val, 'reference' => null);
- if ($localeConstant) { $details['localeValue'] = $localeConstant; }
- $output[] = $details;
- }
- $index += $length;
-
- } elseif ($opCharacter == '$') { // absolute row or column range
- ++$index;
- } elseif ($opCharacter == ')') { // miscellaneous error checking
- if ($expectingOperand) {
- $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => null);
- $expectingOperand = false;
- $expectingOperator = true;
- } else {
- return $this->_raiseFormulaError("Formula Error: Unexpected ')'");
- }
- } elseif (isset(self::$_operators[$opCharacter]) && !$expectingOperator) {
- return $this->_raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
- } else { // I don't even want to know what you did to get here
- return $this->_raiseFormulaError("Formula Error: An unexpected error occured");
- }
- // Test for end of formula string
- if ($index == strlen($formula)) {
- // Did we end with an operator?.
- // Only valid for the % unary operator
- if ((isset(self::$_operators[$opCharacter])) && ($opCharacter != '%')) {
- return $this->_raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
- } else {
- break;
- }
- }
- // Ignore white space
- while (($formula{$index} == "\n") || ($formula{$index} == "\r")) {
- ++$index;
- }
- if ($formula{$index} == ' ') {
- while ($formula{$index} == ' ') {
- ++$index;
- }
- // If we're expecting an operator, but only have a space between the previous and next operands (and both are
- // Cell References) then we have an INTERSECTION operator
-// echo 'Possible Intersect Operator
';
- if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) &&
- ($output[count($output)-1]['type'] == 'Cell Reference')) {
-// echo 'Element is an Intersect Operator
';
- while($stack->count() > 0 &&
- ($o2 = $stack->last()) &&
- isset(self::$_operators[$o2['value']]) &&
- @($operatorAssociativity[$opCharacter] ? $operatorPrecedence[$opCharacter] < $operatorPrecedence[$o2['value']] : $operatorPrecedence[$opCharacter] <= $operatorPrecedence[$o2['value']])) {
- $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
- }
- $stack->push('Binary Operator','|'); // Put an Intersect Operator on the stack
- $expectingOperator = false;
- }
- }
- }
-
- while (($op = $stack->pop()) !== NULL) { // pop everything off the stack and push onto output
- if ((is_array($op) && $op['value'] == '(') || ($op === '('))
- return $this->_raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
- $output[] = $op;
- }
- return $output;
- } // function _parseFormula()
-
-
- private static function _dataTestReference(&$operandData)
- {
- $operand = $operandData['value'];
- if (($operandData['reference'] === NULL) && (is_array($operand))) {
- $rKeys = array_keys($operand);
- $rowKey = array_shift($rKeys);
- $cKeys = array_keys(array_keys($operand[$rowKey]));
- $colKey = array_shift($cKeys);
- if (ctype_upper($colKey)) {
- $operandData['reference'] = $colKey.$rowKey;
- }
- }
- return $operand;
- }
-
- // evaluate postfix notation
- private function _processTokenStack($tokens, $cellID = null, PHPExcel_Cell $pCell = null) {
- if ($tokens == false) return false;
-
- // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
- // so we store the parent worksheet so that we can re-attach it when necessary
- $pCellParent = ($pCell !== NULL) ? $pCell->getParent() : null;
- $stack = new PHPExcel_Calculation_Token_Stack;
-
- // Loop through each token in turn
- foreach ($tokens as $tokenData) {
-// print_r($tokenData);
-// echo '
';
- $token = $tokenData['value'];
-// echo 'Token is '.$token.'
';
- // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack
- if (isset(self::$_binaryOperators[$token])) {
-// echo 'Token is a binary operator
';
- // We must have two operands, error if we don't
- if (($operand2Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
- if (($operand1Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
-
- $operand1 = self::_dataTestReference($operand1Data);
- $operand2 = self::_dataTestReference($operand2Data);
-
- // Log what we're doing
- if ($token == ':') {
- $this->_writeDebug('Evaluating Range ', $this->_showValue($operand1Data['reference']), ' ', $token, ' ', $this->_showValue($operand2Data['reference']));
- } else {
- $this->_writeDebug('Evaluating ', $this->_showValue($operand1), ' ', $token, ' ', $this->_showValue($operand2));
- }
-
- // Process the operation in the appropriate manner
- switch ($token) {
- // Comparison (Boolean) Operators
- case '>' : // Greater than
- case '<' : // Less than
- case '>=' : // Greater than or Equal to
- case '<=' : // Less than or Equal to
- case '=' : // Equality
- case '<>' : // Inequality
- $this->_executeBinaryComparisonOperation($cellID,$operand1,$operand2,$token,$stack);
- break;
- // Binary Operators
- case ':' : // Range
- $sheet1 = $sheet2 = '';
- if (strpos($operand1Data['reference'],'!') !== false) {
- list($sheet1,$operand1Data['reference']) = explode('!',$operand1Data['reference']);
- } else {
- $sheet1 = ($pCellParent !== NULL) ? $pCellParent->getTitle() : '';
- }
- if (strpos($operand2Data['reference'],'!') !== false) {
- list($sheet2,$operand2Data['reference']) = explode('!',$operand2Data['reference']);
- } else {
- $sheet2 = $sheet1;
- }
- if ($sheet1 == $sheet2) {
- if ($operand1Data['reference'] === NULL) {
- if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
- $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value'];
- } elseif (trim($operand1Data['reference']) == '') {
- $operand1Data['reference'] = $pCell->getCoordinate();
- } else {
- $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow();
- }
- }
- if ($operand2Data['reference'] === NULL) {
- if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
- $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value'];
- } elseif (trim($operand2Data['reference']) == '') {
- $operand2Data['reference'] = $pCell->getCoordinate();
- } else {
- $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow();
- }
- }
-
- $oData = array_merge(explode(':',$operand1Data['reference']),explode(':',$operand2Data['reference']));
- $oCol = $oRow = array();
- foreach($oData as $oDatum) {
- $oCR = PHPExcel_Cell::coordinateFromString($oDatum);
- $oCol[] = PHPExcel_Cell::columnIndexFromString($oCR[0]) - 1;
- $oRow[] = $oCR[1];
- }
- $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
- if ($pCellParent !== NULL) {
- $cellValue = $this->extractCellRange($cellRef, $pCellParent->getParent()->getSheetByName($sheet1), false);
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $stack->push('Cell Reference',$cellValue,$cellRef);
- } else {
- $stack->push('Error',PHPExcel_Calculation_Functions::REF(),null);
- }
-
- break;
- case '+' : // Addition
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'plusEquals',$stack);
- break;
- case '-' : // Subtraction
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'minusEquals',$stack);
- break;
- case '*' : // Multiplication
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayTimesEquals',$stack);
- break;
- case '/' : // Division
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayRightDivide',$stack);
- break;
- case '^' : // Exponential
- $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'power',$stack);
- break;
- case '&' : // Concatenation
- // If either of the operands is a matrix, we need to treat them both as matrices
- // (converting the other operand to a matrix if need be); then perform the required
- // matrix operation
- if (is_bool($operand1)) {
- $operand1 = ($operand1) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
- }
- if (is_bool($operand2)) {
- $operand2 = ($operand2) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
- }
- if ((is_array($operand1)) || (is_array($operand2))) {
- // Ensure that both operands are arrays/matrices
- self::_checkMatrixOperands($operand1,$operand2,2);
- try {
- // Convert operand 1 from a PHP array to a matrix
- $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
- // Perform the required operation against the operand 1 matrix, passing in operand 2
- $matrixResult = $matrix->concat($operand2);
- $result = $matrixResult->getArray();
- } catch (PHPExcel_Exception $ex) {
- $this->_writeDebug('JAMA Matrix Exception: ', $ex->getMessage());
- $result = '#VALUE!';
- }
- } else {
- $result = '"'.str_replace('""','"',self::_unwrapResult($operand1,'"').self::_unwrapResult($operand2,'"')).'"';
- }
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails($result));
- $stack->push('Value',$result);
- break;
- case '|' : // Intersect
- $rowIntersect = array_intersect_key($operand1,$operand2);
- $cellIntersect = $oCol = $oRow = array();
- foreach(array_keys($rowIntersect) as $row) {
- $oRow[] = $row;
- foreach($rowIntersect[$row] as $col => $data) {
- $oCol[] = PHPExcel_Cell::columnIndexFromString($col) - 1;
- $cellIntersect[$row] = array_intersect_key($operand1[$row],$operand2[$row]);
- }
- }
- $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails($cellIntersect));
- $stack->push('Value',$cellIntersect,$cellRef);
- break;
- }
-
- // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
- } elseif (($token === '~') || ($token === '%')) {
-// echo 'Token is a unary operator
';
- if (($arg = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
- $arg = $arg['value'];
- if ($token === '~') {
-// echo 'Token is a negation operator
';
- $this->_writeDebug('Evaluating Negation of ', $this->_showValue($arg));
- $multiplier = -1;
- } else {
-// echo 'Token is a percentile operator
';
- $this->_writeDebug('Evaluating Percentile of ', $this->_showValue($arg));
- $multiplier = 0.01;
- }
- if (is_array($arg)) {
- self::_checkMatrixOperands($arg,$multiplier,2);
- try {
- $matrix1 = new PHPExcel_Shared_JAMA_Matrix($arg);
- $matrixResult = $matrix1->arrayTimesEquals($multiplier);
- $result = $matrixResult->getArray();
- } catch (PHPExcel_Exception $ex) {
- $this->_writeDebug('JAMA Matrix Exception: ', $ex->getMessage());
- $result = '#VALUE!';
- }
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails($result));
- $stack->push('Value',$result);
- } else {
- $this->_executeNumericBinaryOperation($cellID,$multiplier,$arg,'*','arrayTimesEquals',$stack);
- }
-
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
- $cellRef = null;
-// echo 'Element '.$token.' is a Cell reference
';
- if (isset($matches[8])) {
-// echo 'Reference is a Range of cells
';
- if ($pCell === NULL) {
-// We can't access the range, so return a REF error
- $cellValue = PHPExcel_Calculation_Functions::REF();
- } else {
- $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10];
- if ($matches[2] > '') {
- $matches[2] = trim($matches[2],"\"'");
- if ((strpos($matches[2],'[') !== false) || (strpos($matches[2],']') !== false)) {
- // It's a Reference to an external workbook (not currently supported)
- return $this->_raiseFormulaError('Unable to access External Workbook');
- }
- $matches[2] = trim($matches[2],"\"'");
-// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
- $this->_writeDebug('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]);
- if ($pCellParent !== NULL) {
- $cellValue = $this->extractCellRange($cellRef, $pCellParent->getParent()->getSheetByName($matches[2]), false);
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $this->_writeDebug('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
-// $cellRef = $matches[2].'!'.$cellRef;
- } else {
-// echo '$cellRef='.$cellRef.' in current worksheet
';
- $this->_writeDebug('Evaluating Cell Range ', $cellRef, ' in current worksheet');
- if ($pCellParent !== NULL) {
- $cellValue = $this->extractCellRange($cellRef, $pCellParent, false);
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $this->_writeDebug('Evaluation Result for cells ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
- }
- }
- } else {
-// echo 'Reference is a single Cell
';
- if ($pCell === NULL) {
-// We can't access the cell, so return a REF error
- $cellValue = PHPExcel_Calculation_Functions::REF();
- } else {
- $cellRef = $matches[6].$matches[7];
- if ($matches[2] > '') {
- $matches[2] = trim($matches[2],"\"'");
- if ((strpos($matches[2],'[') !== false) || (strpos($matches[2],']') !== false)) {
- // It's a Reference to an external workbook (not currently supported)
- return $this->_raiseFormulaError('Unable to access External Workbook');
- }
-// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
';
- $this->_writeDebug('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]);
- if ($pCellParent !== NULL) {
- if ($pCellParent->getParent()->getSheetByName($matches[2])->cellExists($cellRef)) {
- $cellValue = $this->extractCellRange($cellRef, $pCellParent->getParent()->getSheetByName($matches[2]), false);
- $pCell->attach($pCellParent);
- } else {
- $cellValue = null;
- }
- } else {
- return $this->_raiseFormulaError('Unable to access Cell Reference');
- }
- $this->_writeDebug('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
-// $cellRef = $matches[2].'!'.$cellRef;
- } else {
-// echo '$cellRef='.$cellRef.' in current worksheet
';
- $this->_writeDebug('Evaluating Cell ', $cellRef, ' in current worksheet');
- if ($pCellParent->cellExists($cellRef)) {
- $cellValue = $this->extractCellRange($cellRef, $pCellParent, false);
- $pCell->attach($pCellParent);
- } else {
- $cellValue = null;
- }
- $this->_writeDebug('Evaluation Result for cell ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
- }
- }
- }
- $stack->push('Value',$cellValue,$cellRef);
-
- // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) {
-// echo 'Token is a function
';
- $functionName = $matches[1];
- $argCount = $stack->pop();
- $argCount = $argCount['value'];
- if ($functionName != 'MKMATRIX') {
- $this->_writeDebug('Evaluating Function ', self::_localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's'));
- }
- if ((isset(self::$_PHPExcelFunctions[$functionName])) || (isset(self::$_controlFunctions[$functionName]))) { // function
- if (isset(self::$_PHPExcelFunctions[$functionName])) {
- $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
- $passByReference = isset(self::$_PHPExcelFunctions[$functionName]['passByReference']);
- $passCellReference = isset(self::$_PHPExcelFunctions[$functionName]['passCellReference']);
- } elseif (isset(self::$_controlFunctions[$functionName])) {
- $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
- $passByReference = isset(self::$_controlFunctions[$functionName]['passByReference']);
- $passCellReference = isset(self::$_controlFunctions[$functionName]['passCellReference']);
- }
- // get the arguments for this function
-// echo 'Function '.$functionName.' expects '.$argCount.' arguments
';
- $args = $argArrayVals = array();
- for ($i = 0; $i < $argCount; ++$i) {
- $arg = $stack->pop();
- $a = $argCount - $i - 1;
- if (($passByReference) &&
- (isset(self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) &&
- (self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) {
- if ($arg['reference'] === NULL) {
- $args[] = $cellID;
- if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($cellID); }
- } else {
- $args[] = $arg['reference'];
- if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['reference']); }
- }
- } else {
- $args[] = self::_unwrapResult($arg['value']);
- if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['value']); }
- }
- }
- // Reverse the order of the arguments
- krsort($args);
- if (($passByReference) && ($argCount == 0)) {
- $args[] = $cellID;
- $argArrayVals[] = $this->_showValue($cellID);
- }
-// echo 'Arguments are: ';
-// print_r($args);
-// echo '
';
- if ($functionName != 'MKMATRIX') {
- if ($this->writeDebugLog) {
- krsort($argArrayVals);
- $this->_writeDebug('Evaluating ', self::_localeFunc($functionName), '( ', implode(self::$_localeArgumentSeparator.' ',PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )');
- }
- }
- // Process each argument in turn, building the return value as an array
-// if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) {
-// $operand1 = $args[1];
-// $this->_writeDebug('Argument is a matrix: ', $this->_showValue($operand1));
-// $result = array();
-// $row = 0;
-// foreach($operand1 as $args) {
-// if (is_array($args)) {
-// foreach($args as $arg) {
-// $this->_writeDebug('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($arg), ' )');
-// $r = call_user_func_array($functionCall,$arg);
-// $this->_writeDebug('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
-// $result[$row][] = $r;
-// }
-// ++$row;
-// } else {
-// $this->_writeDebug('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($args), ' )');
-// $r = call_user_func_array($functionCall,$args);
-// $this->_writeDebug('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
-// $result[] = $r;
-// }
-// }
-// } else {
- // Process the argument with the appropriate function call
- if ($passCellReference) {
- $args[] = $pCell;
- }
- if (strpos($functionCall,'::') !== false) {
- $result = call_user_func_array(explode('::',$functionCall),$args);
- } else {
- foreach($args as &$arg) {
- $arg = PHPExcel_Calculation_Functions::flattenSingleValue($arg);
- }
- unset($arg);
- $result = call_user_func_array($functionCall,$args);
- }
-// }
- if ($functionName != 'MKMATRIX') {
- $this->_writeDebug('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result));
- }
- $stack->push('Value',self::_wrapResult($result));
- }
-
- } else {
- // if the token is a number, boolean, string or an Excel error, push it onto the stack
- if (isset(self::$_ExcelConstants[strtoupper($token)])) {
- $excelConstant = strtoupper($token);
-// echo 'Token is a PHPExcel constant: '.$excelConstant.'
';
- $stack->push('Constant Value',self::$_ExcelConstants[$excelConstant]);
- $this->_writeDebug('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$_ExcelConstants[$excelConstant]));
- } elseif ((is_numeric($token)) || ($token === NULL) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) {
-// echo 'Token is a number, boolean, string, null or an Excel error
';
- $stack->push('Value',$token);
- // if the token is a named range, push the named range name onto the stack
- } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) {
-// echo 'Token is a named range
';
- $namedRange = $matches[6];
-// echo 'Named Range is '.$namedRange.'
';
- $this->_writeDebug('Evaluating Named Range ', $namedRange);
- $cellValue = $this->extractNamedRange($namedRange, ((null !== $pCell) ? $pCellParent : null), false);
- $pCell->attach($pCellParent);
- $this->_writeDebug('Evaluation Result for named range ', $namedRange, ' is ', $this->_showTypeDetails($cellValue));
- $stack->push('Named Range',$cellValue,$namedRange);
- } else {
- return $this->_raiseFormulaError("undefined variable '$token'");
- }
- }
- }
- // when we're out of tokens, the stack should have a single element, the final result
- if ($stack->count() != 1) return $this->_raiseFormulaError("internal error");
- $output = $stack->pop();
- $output = $output['value'];
-
-// if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
-// return array_shift(PHPExcel_Calculation_Functions::flattenArray($output));
-// }
- return $output;
- } // function _processTokenStack()
-
-
- private function _validateBinaryOperand($cellID,&$operand,&$stack) {
- // Numbers, matrices and booleans can pass straight through, as they're already valid
- if (is_string($operand)) {
- // We only need special validations for the operand if it is a string
- // Start by stripping off the quotation marks we use to identify true excel string values internally
- if ($operand > '' && $operand{0} == '"') { $operand = self::_unwrapResult($operand); }
- // If the string is a numeric value, we treat it as a numeric, so no further testing
- if (!is_numeric($operand)) {
- // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
- if ($operand > '' && $operand{0} == '#') {
- $stack->push('Value', $operand);
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails($operand));
- return false;
- } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) {
- // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations
- $stack->push('Value', '#VALUE!');
- $this->_writeDebug('Evaluation Result is a ', $this->_showTypeDetails('#VALUE!'));
- return false;
- }
- }
- }
-
- // return a true if the value of the operand is one that we can use in normal binary operations
- return true;
- } // function _validateBinaryOperand()
-
-
- private function _executeBinaryComparisonOperation($cellID,$operand1,$operand2,$operation,&$stack,$recursingArrays=false) {
- // If we're dealing with matrix operations, we want a matrix result
- if ((is_array($operand1)) || (is_array($operand2))) {
- $result = array();
- if ((is_array($operand1)) && (!is_array($operand2))) {
- foreach($operand1 as $x => $operandData) {
- $this->_writeDebug('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2));
- $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2,$operation,$stack);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- } elseif ((!is_array($operand1)) && (is_array($operand2))) {
- foreach($operand2 as $x => $operandData) {
- $this->_writeDebug('Evaluating Comparison ', $this->_showValue($operand1), ' ', $operation, ' ', $this->_showValue($operandData));
- $this->_executeBinaryComparisonOperation($cellID,$operand1,$operandData,$operation,$stack);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- } else {
- if (!$recursingArrays) { self::_checkMatrixOperands($operand1,$operand2,2); }
- foreach($operand1 as $x => $operandData) {
- $this->_writeDebug('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2[$x]));
- $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2[$x],$operation,$stack,true);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- }
- // Log the result details
- $this->_writeDebug('Comparison Evaluation Result is ', $this->_showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Array',$result);
- return true;
- }
-
- // Simple validate the two operands if they are string values
- if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') { $operand1 = self::_unwrapResult($operand1); }
- if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') { $operand2 = self::_unwrapResult($operand2); }
-
- // execute the necessary operation
- switch ($operation) {
- // Greater than
- case '>':
- $result = ($operand1 > $operand2);
- break;
- // Less than
- case '<':
- $result = ($operand1 < $operand2);
- break;
- // Equality
- case '=':
- $result = ($operand1 == $operand2);
- break;
- // Greater than or equal
- case '>=':
- $result = ($operand1 >= $operand2);
- break;
- // Less than or equal
- case '<=':
- $result = ($operand1 <= $operand2);
- break;
- // Inequality
- case '<>':
- $result = ($operand1 != $operand2);
- break;
- }
-
- // Log the result details
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Value',$result);
- return true;
- } // function _executeBinaryComparisonOperation()
-
-
- private function _executeNumericBinaryOperation($cellID,$operand1,$operand2,$operation,$matrixFunction,&$stack) {
- // Validate the two operands
- if (!$this->_validateBinaryOperand($cellID,$operand1,$stack)) return false;
- if (!$this->_validateBinaryOperand($cellID,$operand2,$stack)) return false;
-
- $executeMatrixOperation = false;
- // If either of the operands is a matrix, we need to treat them both as matrices
- // (converting the other operand to a matrix if need be); then perform the required
- // matrix operation
- if ((is_array($operand1)) || (is_array($operand2))) {
- // Ensure that both operands are arrays/matrices
- $executeMatrixOperation = true;
- $mSize = array();
- list($mSize[],$mSize[],$mSize[],$mSize[]) = self::_checkMatrixOperands($operand1,$operand2,2);
-
- // But if they're both single cell matrices, then we can treat them as simple values
- if (array_sum($mSize) == 4) {
- $executeMatrixOperation = false;
- $operand1 = $operand1[0][0];
- $operand2 = $operand2[0][0];
- }
- }
-
- if ($executeMatrixOperation) {
- try {
- // Convert operand 1 from a PHP array to a matrix
- $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
- // Perform the required operation against the operand 1 matrix, passing in operand 2
- $matrixResult = $matrix->$matrixFunction($operand2);
- $result = $matrixResult->getArray();
- } catch (PHPExcel_Exception $ex) {
- $this->_writeDebug('JAMA Matrix Exception: ', $ex->getMessage());
- $result = '#VALUE!';
- }
- } else {
- if ((PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) &&
- ((is_string($operand1) && !is_numeric($operand1)) || (is_string($operand2) && !is_numeric($operand2)))) {
- $result = PHPExcel_Calculation_Functions::VALUE();
- } else {
- // If we're dealing with non-matrix operations, execute the necessary operation
- switch ($operation) {
- // Addition
- case '+':
- $result = $operand1+$operand2;
- break;
- // Subtraction
- case '-':
- $result = $operand1-$operand2;
- break;
- // Multiplication
- case '*':
- $result = $operand1*$operand2;
- break;
- // Division
- case '/':
- if ($operand2 == 0) {
- // Trap for Divide by Zero error
- $stack->push('Value','#DIV/0!');
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails('#DIV/0!'));
- return false;
- } else {
- $result = $operand1/$operand2;
- }
- break;
- // Power
- case '^':
- $result = pow($operand1,$operand2);
- break;
- }
- }
- }
-
- // Log the result details
- $this->_writeDebug('Evaluation Result is ', $this->_showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Value',$result);
- return true;
- } // function _executeNumericBinaryOperation()
-
-
- private function _writeDebug() {
- // Only write the debug log if logging is enabled
- if ($this->writeDebugLog) {
- $message = implode('',func_get_args());
- if ($this->echoDebugLog) {
- echo implode(' -> ',$this->debugLogStack).' -> '.$message,'
';
- }
- $this->debugLog[] = implode(' -> ',$this->debugLogStack).' -> '.$message;
- }
- } // function _writeDebug()
-
-
- // trigger an error, but nicely, if need be
- protected function _raiseFormulaError($errorMessage) {
- $this->formulaError = $errorMessage;
- $this->debugLogStack = array();
- if (!$this->suppressFormulaErrors) throw new PHPExcel_Calculation_Exception($errorMessage);
- trigger_error($errorMessage, E_USER_ERROR);
- } // function _raiseFormulaError()
-
-
- /**
- * Extract range values
- *
- * @param string &$pRange String based range representation
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
- * @throws PHPExcel_Calculation_Exception
- */
- public function extractCellRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog=true) {
- // Return value
- $returnValue = array ();
-
-// echo 'extractCellRange('.$pRange.')
';
- if ($pSheet !== NULL) {
-// echo 'Passed sheet name is '.$pSheet->getTitle().'
';
-// echo 'Range reference is '.$pRange.'
';
- if (strpos ($pRange, '!') !== false) {
-// echo '$pRange reference includes sheet reference
';
- $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
- $pSheet = $pSheet->getParent()->getSheetByName($worksheetReference[0]);
-// echo 'New sheet name is '.$pSheet->getTitle().'
';
- $pRange = $worksheetReference[1];
-// echo 'Adjusted Range reference is '.$pRange.'
';
- }
-
- // Extract range
- $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
- $pRange = $pSheet->getTitle().'!'.$pRange;
- if (!isset($aReferences[1])) {
- // Single cell in range
- list($currentCol,$currentRow) = sscanf($aReferences[0],'%[A-Z]%d');
- if ($pSheet->cellExists($aReferences[0])) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = null;
- }
- } else {
- // Extract cell data for all cells in the range
- foreach ($aReferences as $reference) {
- // Extract range
- list($currentCol,$currentRow) = sscanf($reference,'%[A-Z]%d');
-
- if ($pSheet->cellExists($reference)) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = null;
- }
- }
- }
- }
-
- // Return
- return $returnValue;
- } // function extractCellRange()
-
-
- /**
- * Extract range values
- *
- * @param string &$pRange String based range representation
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
- * @throws PHPExcel_Calculation_Exception
- */
- public function extractNamedRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog=true) {
- // Return value
- $returnValue = array ();
-
-// echo 'extractNamedRange('.$pRange.')
';
- if ($pSheet !== NULL) {
-// echo 'Current sheet name is '.$pSheet->getTitle().'
';
-// echo 'Range reference is '.$pRange.'
';
- if (strpos ($pRange, '!') !== false) {
-// echo '$pRange reference includes sheet reference
';
- $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
- $pSheet = $pSheet->getParent()->getSheetByName($worksheetReference[0]);
-// echo 'New sheet name is '.$pSheet->getTitle().'
';
- $pRange = $worksheetReference[1];
-// echo 'Adjusted Range reference is '.$pRange.'
';
- }
-
- // Named range?
- $namedRange = PHPExcel_NamedRange::resolveRange($pRange, $pSheet);
- if ($namedRange !== NULL) {
- $pSheet = $namedRange->getWorksheet();
-// echo 'Named Range '.$pRange.' (';
- $pRange = $namedRange->getRange();
- $splitRange = PHPExcel_Cell::splitRange($pRange);
- // Convert row and column references
- if (ctype_alpha($splitRange[0][0])) {
- $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
- } elseif(ctype_digit($splitRange[0][0])) {
- $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
- }
-// echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'
';
-
-// if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) {
-// if (!$namedRange->getLocalOnly()) {
-// $pSheet = $namedRange->getWorksheet();
-// } else {
-// return $returnValue;
-// }
-// }
- } else {
- return PHPExcel_Calculation_Functions::REF();
- }
-
- // Extract range
- $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
-// var_dump($aReferences);
- if (!isset($aReferences[1])) {
- // Single cell (or single column or row) in range
- list($currentCol,$currentRow) = PHPExcel_Cell::coordinateFromString($aReferences[0]);
- if ($pSheet->cellExists($aReferences[0])) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = null;
- }
- } else {
- // Extract cell data for all cells in the range
- foreach ($aReferences as $reference) {
- // Extract range
- list($currentCol,$currentRow) = PHPExcel_Cell::coordinateFromString($reference);
-// echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'
';
- if ($pSheet->cellExists($reference)) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
- } else {
- $returnValue[$currentRow][$currentCol] = null;
- }
- }
- }
-// print_r($returnValue);
-// echo '
';
- }
-
- // Return
- return $returnValue;
- } // function extractNamedRange()
-
-
- /**
- * Is a specific function implemented?
- *
- * @param string $pFunction Function Name
- * @return boolean
- */
- public function isImplemented($pFunction = '') {
- $pFunction = strtoupper ($pFunction);
- if (isset(self::$_PHPExcelFunctions[$pFunction])) {
- return (self::$_PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY');
- } else {
- return false;
- }
- } // function isImplemented()
-
-
- /**
- * Get a list of all implemented functions as an array of function objects
- *
- * @return array of PHPExcel_Calculation_Function
- */
- public function listFunctions() {
- // Return value
- $returnValue = array();
- // Loop functions
- foreach(self::$_PHPExcelFunctions as $functionName => $function) {
- if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
- $returnValue[$functionName] = new PHPExcel_Calculation_Function($function['category'],
- $functionName,
- $function['functionCall']
- );
- }
- }
-
- // Return
- return $returnValue;
- } // function listFunctions()
-
-
- /**
- * Get a list of all Excel function names
- *
- * @return array
- */
- public function listAllFunctionNames() {
- return array_keys(self::$_PHPExcelFunctions);
- } // function listAllFunctionNames()
-
- /**
- * Get a list of implemented Excel function names
- *
- * @return array
- */
- public function listFunctionNames() {
- // Return value
- $returnValue = array();
- // Loop functions
- foreach(self::$_PHPExcelFunctions as $functionName => $function) {
- if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
- $returnValue[] = $functionName;
- }
- }
-
- // Return
- return $returnValue;
- } // function listFunctionNames()
-
-} // class PHPExcel_Calculation
-
diff --git a/Classes/PHPExcel/Calculation/Database.php b/Classes/PHPExcel/Calculation/Database.php
index 02f27006e..b8d91cb6e 100644
--- a/Classes/PHPExcel/Calculation/Database.php
+++ b/Classes/PHPExcel/Calculation/Database.php
@@ -1,8 +1,18 @@
$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;
+ }
+
+
+ private static function getFilteredColumn($database, $field, $criteria)
+ {
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::filter($database, $criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach ($database as $row) {
+ $colData[] = $row[$field];
+ }
+
+ return $colData;
+ }
+
+ /**
+ * DAVERAGE
+ *
+ * Averages the values in a column of a list or database that match conditions you specify.
+ *
+ * Excel Function:
+ * DAVERAGE(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DAVERAGE($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::AVERAGE(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DCOUNT
+ *
+ * Counts the cells that contain numbers in a column of a list or database that match conditions
+ * that you specify.
+ *
+ * Excel Function:
+ * DCOUNT(database,[field],criteria)
+ *
+ * Excel Function:
+ * DAVERAGE(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 integer
+ *
+ * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
+ * database that match the criteria.
+ *
+ */
+ public static function DCOUNT($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::COUNT(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DCOUNTA
+ *
+ * Counts the nonblank cells in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DCOUNTA(database,[field],criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 integer
+ *
+ * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
+ * database that match the criteria.
+ *
+ */
+ public static function DCOUNTA($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // reduce the database to a set of rows that match all the criteria
+ $database = self::filter($database, $criteria);
+ // extract an array of values for the requested column
+ $colData = array();
+ foreach ($database as $row) {
+ $colData[] = $row[$field];
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::COUNTA(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DGET
+ *
+ * Extracts a single value from a column of a list or database that matches conditions that you
+ * specify.
+ *
+ * Excel Function:
+ * DGET(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 mixed
+ *
+ */
+ public static function DGET($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ $colData = self::getFilteredColumn($database, $field, $criteria);
+ if (count($colData) > 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ return $colData[0];
+ }
+
+
+ /**
+ * DMAX
+ *
+ * Returns the largest number in a column of a list or database that matches conditions you that
+ * specify.
+ *
+ * Excel Function:
+ * DMAX(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DMAX($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::MAX(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DMIN
+ *
+ * Returns the smallest number in a column of a list or database that matches conditions you that
+ * specify.
+ *
+ * Excel Function:
+ * DMIN(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DMIN($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::MIN(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DPRODUCT
+ *
+ * Multiplies the values in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DPRODUCT(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DPRODUCT($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_MathTrig::PRODUCT(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DSTDEV
+ *
+ * Estimates the standard deviation of a population based on a sample by using the numbers in a
+ * column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DSTDEV(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DSTDEV($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::STDEV(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DSTDEVP
+ *
+ * Calculates the standard deviation of a population based on the entire population by using the
+ * numbers in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DSTDEVP(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DSTDEVP($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::STDEVP(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DSUM
+ *
+ * Adds the numbers in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DSUM(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DSUM($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_MathTrig::SUM(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DVAR
+ *
+ * Estimates the variance of a population based on a sample by using the numbers in a column
+ * of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DVAR(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DVAR($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::VARFunc(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
+
+
+ /**
+ * DVARP
+ *
+ * Calculates the variance of a population based on the entire population by using the numbers
+ * in a column of a list or database that match conditions that you specify.
+ *
+ * Excel Function:
+ * DVARP(database,field,criteria)
+ *
+ * @access public
+ * @category Database Functions
+ * @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 string|integer $field Indicates which column is used in the function. Enter the
+ * column label enclosed between double quotation marks, such as
+ * "Age" or "Yield," or a number (without quotation marks) that
+ * represents the position of the column within the list: 1 for
+ * the first column, 2 for the second column, and so on.
+ * @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 float
+ *
+ */
+ public static function DVARP($database, $field, $criteria)
+ {
+ $field = self::fieldExtract($database, $field);
+ if (is_null($field)) {
+ return null;
+ }
+
+ // Return
+ return PHPExcel_Calculation_Statistical::VARP(
+ self::getFilteredColumn($database, $field, $criteria)
+ );
+ }
}
-
-
-/**
- * PHPExcel_Calculation_Database
- *
- * @category PHPExcel
- * @package PHPExcel_Calculation
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- */
-class PHPExcel_Calculation_Database {
-
-
- /**
- * __fieldExtract
- *
- * Extracts the column ID to use for the data field.
- *
- * @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 $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @return string|NULL
- *
- */
- private static function __fieldExtract($database,$field) {
- $field = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($field));
- $fieldNames = array_map('strtoupper',array_shift($database));
-
- if (is_numeric($field)) {
- $keys = array_keys($fieldNames);
- return $keys[$field-1];
- }
- $key = array_search($field,$fieldNames);
- return ($key) ? $key : NULL;
- }
-
- /**
- * __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;
- }
-
-
- /**
- * DAVERAGE
- *
- * Averages the values in a column of a list or database that match conditions you specify.
- *
- * Excel Function:
- * DAVERAGE(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DAVERAGE($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::AVERAGE($colData);
- } // function DAVERAGE()
-
-
- /**
- * DCOUNT
- *
- * Counts the cells that contain numbers in a column of a list or database that match conditions
- * that you specify.
- *
- * Excel Function:
- * DCOUNT(database,[field],criteria)
- *
- * Excel Function:
- * DAVERAGE(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 integer
- *
- * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
- * database that match the criteria.
- *
- */
- public static function DCOUNT($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::COUNT($colData);
- } // function DCOUNT()
-
-
- /**
- * DCOUNTA
- *
- * Counts the nonblank cells in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DCOUNTA(database,[field],criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 integer
- *
- * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
- * database that match the criteria.
- *
- */
- public static function DCOUNTA($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::COUNTA($colData);
- } // function DCOUNTA()
-
-
- /**
- * DGET
- *
- * Extracts a single value from a column of a list or database that matches conditions that you
- * specify.
- *
- * Excel Function:
- * DGET(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 mixed
- *
- */
- public static function DGET($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- if (count($colData) > 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return $colData[0];
- } // function DGET()
-
-
- /**
- * DMAX
- *
- * Returns the largest number in a column of a list or database that matches conditions you that
- * specify.
- *
- * Excel Function:
- * DMAX(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DMAX($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::MAX($colData);
- } // function DMAX()
-
-
- /**
- * DMIN
- *
- * Returns the smallest number in a column of a list or database that matches conditions you that
- * specify.
- *
- * Excel Function:
- * DMIN(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DMIN($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::MIN($colData);
- } // function DMIN()
-
-
- /**
- * DPRODUCT
- *
- * Multiplies the values in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DPRODUCT(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DPRODUCT($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_MathTrig::PRODUCT($colData);
- } // function DPRODUCT()
-
-
- /**
- * DSTDEV
- *
- * Estimates the standard deviation of a population based on a sample by using the numbers in a
- * column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DSTDEV(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DSTDEV($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::STDEV($colData);
- } // function DSTDEV()
-
-
- /**
- * DSTDEVP
- *
- * Calculates the standard deviation of a population based on the entire population by using the
- * numbers in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DSTDEVP(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DSTDEVP($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::STDEVP($colData);
- } // function DSTDEVP()
-
-
- /**
- * DSUM
- *
- * Adds the numbers in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DSUM(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DSUM($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_MathTrig::SUM($colData);
- } // function DSUM()
-
-
- /**
- * DVAR
- *
- * Estimates the variance of a population based on a sample by using the numbers in a column
- * of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DVAR(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DVAR($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::VARFunc($colData);
- } // function DVAR()
-
-
- /**
- * DVARP
- *
- * Calculates the variance of a population based on the entire population by using the numbers
- * in a column of a list or database that match conditions that you specify.
- *
- * Excel Function:
- * DVARP(database,field,criteria)
- *
- * @access public
- * @category Database Functions
- * @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 string|integer $field Indicates which column is used in the function. Enter the
- * column label enclosed between double quotation marks, such as
- * "Age" or "Yield," or a number (without quotation marks) that
- * represents the position of the column within the list: 1 for
- * the first column, 2 for the second column, and so on.
- * @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 float
- *
- */
- public static function DVARP($database,$field,$criteria) {
- $field = self::__fieldExtract($database,$field);
- if (is_null($field)) {
- return NULL;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::__filter($database,$criteria);
- // extract an array of values for the requested column
- $colData = array();
- foreach($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return PHPExcel_Calculation_Statistical::VARP($colData);
- } // function DVARP()
-
-
-} // class PHPExcel_Calculation_Database
diff --git a/Classes/PHPExcel/Calculation/DateTime.php b/Classes/PHPExcel/Calculation/DateTime.php
index 854f8f842..72f4c7a23 100644
--- a/Classes/PHPExcel/Calculation/DateTime.php
+++ b/Classes/PHPExcel/Calculation/DateTime.php
@@ -1,8 +1,18 @@
format('m');
- $oYear = (int) $PHPDateObject->format('Y');
-
- $adjustmentMonthsString = (string) $adjustmentMonths;
- if ($adjustmentMonths > 0) {
- $adjustmentMonthsString = '+'.$adjustmentMonths;
- }
- if ($adjustmentMonths != 0) {
- $PHPDateObject->modify($adjustmentMonthsString.' months');
- }
- $nMonth = (int) $PHPDateObject->format('m');
- $nYear = (int) $PHPDateObject->format('Y');
-
- $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
- if ($monthDiff != $adjustmentMonths) {
- $adjustDays = (int) $PHPDateObject->format('d');
- $adjustDaysString = '-'.$adjustDays.' days';
- $PHPDateObject->modify($adjustDaysString);
- }
- return $PHPDateObject;
- } // function _adjustDateByMonths()
-
-
- /**
- * DATETIMENOW
- *
- * Returns the current date and time.
- * The NOW function is useful when you need to display the current date and time on a worksheet or
- * calculate a value based on the current date and time, and have that value updated each time you
- * open the worksheet.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * NOW()
- *
- * @access public
- * @category Date/Time Functions
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATETIMENOW() {
- $saveTimeZone = date_default_timezone_get();
- date_default_timezone_set('UTC');
- $retValue = False;
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time());
- break;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- $retValue = (integer) time();
- break;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- $retValue = new DateTime();
- break;
- }
- date_default_timezone_set($saveTimeZone);
-
- return $retValue;
- } // function DATETIMENOW()
-
-
- /**
- * DATENOW
- *
- * Returns the current date.
- * The NOW function is useful when you need to display the current date and time on a worksheet or
- * calculate a value based on the current date and time, and have that value updated each time you
- * open the worksheet.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * TODAY()
- *
- * @access public
- * @category Date/Time Functions
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATENOW() {
- $saveTimeZone = date_default_timezone_get();
- date_default_timezone_set('UTC');
- $retValue = False;
- $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time()));
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- $retValue = (float) $excelDateTime;
- break;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime);
- break;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime);
- break;
- }
- date_default_timezone_set($saveTimeZone);
-
- return $retValue;
- } // function DATENOW()
-
-
- /**
- * DATE
- *
- * The DATE function returns a value that represents a particular date.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * DATE(year,month,day)
- *
- * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function.
- * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
- * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
- *
- * @access public
- * @category Date/Time Functions
- * @param integer $year The value of the year argument can include one to four digits.
- * Excel interprets the year argument according to the configured
- * date system: 1900 or 1904.
- * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
- * value to 1900 to calculate the year. For example, DATE(108,1,2)
- * returns January 2, 2008 (1900+108).
- * If year is between 1900 and 9999 (inclusive), Excel uses that
- * value as the year. For example, DATE(2008,1,2) returns January 2,
- * 2008.
- * If year is less than 0 or is 10000 or greater, Excel returns the
- * #NUM! error value.
- * @param integer $month A positive or negative integer representing the month of the year
- * from 1 to 12 (January to December).
- * If month is greater than 12, month adds that number of months to
- * the first month in the year specified. For example, DATE(2008,14,2)
- * returns the serial number representing February 2, 2009.
- * If month is less than 1, month subtracts the magnitude of that
- * number of months, plus 1, from the first month in the year
- * specified. For example, DATE(2008,-3,2) returns the serial number
- * representing September 2, 2007.
- * @param integer $day A positive or negative integer representing the day of the month
- * from 1 to 31.
- * If day is greater than the number of days in the month specified,
- * day adds that number of days to the first day in the month. For
- * example, DATE(2008,1,35) returns the serial number representing
- * February 4, 2008.
- * If day is less than 1, day subtracts the magnitude that number of
- * days, plus one, from the first day of the month specified. For
- * example, DATE(2008,1,-15) returns the serial number representing
- * December 16, 2007.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATE($year = 0, $month = 1, $day = 1) {
- $year = PHPExcel_Calculation_Functions::flattenSingleValue($year);
- $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
- $day = PHPExcel_Calculation_Functions::flattenSingleValue($day);
-
- if (($month !== NULL) && (!is_numeric($month))) {
+class PHPExcel_Calculation_DateTime
+{
+ /**
+ * Identify if a year is a leap year or not
+ *
+ * @param integer $year The year to test
+ * @return boolean TRUE if the year is a leap year, otherwise FALSE
+ */
+ public static function isLeapYear($year)
+ {
+ return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
+ }
+
+
+ /**
+ * Return the number of days between two dates based on a 360 day calendar
+ *
+ * @param integer $startDay Day of month of the start date
+ * @param integer $startMonth Month of the start date
+ * @param integer $startYear Year of the start date
+ * @param integer $endDay Day of month of the start date
+ * @param integer $endMonth Month of the start date
+ * @param integer $endYear Year of the start date
+ * @param boolean $methodUS Whether to use the US method or the European method of calculation
+ * @return integer Number of days between the start date and the end date
+ */
+ private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS)
+ {
+ if ($startDay == 31) {
+ --$startDay;
+ } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) {
+ $startDay = 30;
+ }
+ if ($endDay == 31) {
+ if ($methodUS && $startDay != 30) {
+ $endDay = 1;
+ if ($endMonth == 12) {
+ ++$endYear;
+ $endMonth = 1;
+ } else {
+ ++$endMonth;
+ }
+ } else {
+ $endDay = 30;
+ }
+ }
+
+ return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
+ }
+
+
+ /**
+ * getDateValue
+ *
+ * @param string $dateValue
+ * @return mixed Excel date/time serial value, or string if error
+ */
+ public static function getDateValue($dateValue)
+ {
+ if (!is_numeric($dateValue)) {
+ if ((is_string($dateValue)) &&
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
+ $dateValue = PHPExcel_Shared_Date::PHPToExcel($dateValue);
+ } else {
+ $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $dateValue = self::DATEVALUE($dateValue);
+ PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType);
+ }
+ }
+ return $dateValue;
+ }
+
+
+ /**
+ * getTimeValue
+ *
+ * @param string $timeValue
+ * @return mixed Excel date/time serial value, or string if error
+ */
+ private static function getTimeValue($timeValue)
+ {
+ $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $timeValue = self::TIMEVALUE($timeValue);
+ PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType);
+ return $timeValue;
+ }
+
+
+ private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0)
+ {
+ // Execute function
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
+ $oMonth = (int) $PHPDateObject->format('m');
+ $oYear = (int) $PHPDateObject->format('Y');
+
+ $adjustmentMonthsString = (string) $adjustmentMonths;
+ if ($adjustmentMonths > 0) {
+ $adjustmentMonthsString = '+'.$adjustmentMonths;
+ }
+ if ($adjustmentMonths != 0) {
+ $PHPDateObject->modify($adjustmentMonthsString.' months');
+ }
+ $nMonth = (int) $PHPDateObject->format('m');
+ $nYear = (int) $PHPDateObject->format('Y');
+
+ $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
+ if ($monthDiff != $adjustmentMonths) {
+ $adjustDays = (int) $PHPDateObject->format('d');
+ $adjustDaysString = '-'.$adjustDays.' days';
+ $PHPDateObject->modify($adjustDaysString);
+ }
+ return $PHPDateObject;
+ }
+
+
+ /**
+ * DATETIMENOW
+ *
+ * Returns the current date and time.
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
+ * calculate a value based on the current date and time, and have that value updated each time you
+ * open the worksheet.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * NOW()
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATETIMENOW()
+ {
+ $saveTimeZone = date_default_timezone_get();
+ date_default_timezone_set('UTC');
+ $retValue = false;
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time());
+ break;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ $retValue = (integer) time();
+ break;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ $retValue = new DateTime();
+ break;
+ }
+ date_default_timezone_set($saveTimeZone);
+
+ return $retValue;
+ }
+
+
+ /**
+ * DATENOW
+ *
+ * Returns the current date.
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
+ * calculate a value based on the current date and time, and have that value updated each time you
+ * open the worksheet.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * TODAY()
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATENOW()
+ {
+ $saveTimeZone = date_default_timezone_get();
+ date_default_timezone_set('UTC');
+ $retValue = false;
+ $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time()));
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ $retValue = (float) $excelDateTime;
+ break;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime);
+ break;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime);
+ break;
+ }
+ date_default_timezone_set($saveTimeZone);
+
+ return $retValue;
+ }
+
+
+ /**
+ * DATE
+ *
+ * The DATE function returns a value that represents a particular date.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * DATE(year,month,day)
+ *
+ * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function.
+ * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
+ * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param integer $year The value of the year argument can include one to four digits.
+ * Excel interprets the year argument according to the configured
+ * date system: 1900 or 1904.
+ * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
+ * value to 1900 to calculate the year. For example, DATE(108,1,2)
+ * returns January 2, 2008 (1900+108).
+ * If year is between 1900 and 9999 (inclusive), Excel uses that
+ * value as the year. For example, DATE(2008,1,2) returns January 2,
+ * 2008.
+ * If year is less than 0 or is 10000 or greater, Excel returns the
+ * #NUM! error value.
+ * @param integer $month A positive or negative integer representing the month of the year
+ * from 1 to 12 (January to December).
+ * If month is greater than 12, month adds that number of months to
+ * the first month in the year specified. For example, DATE(2008,14,2)
+ * returns the serial number representing February 2, 2009.
+ * If month is less than 1, month subtracts the magnitude of that
+ * number of months, plus 1, from the first month in the year
+ * specified. For example, DATE(2008,-3,2) returns the serial number
+ * representing September 2, 2007.
+ * @param integer $day A positive or negative integer representing the day of the month
+ * from 1 to 31.
+ * If day is greater than the number of days in the month specified,
+ * day adds that number of days to the first day in the month. For
+ * example, DATE(2008,1,35) returns the serial number representing
+ * February 4, 2008.
+ * If day is less than 1, day subtracts the magnitude that number of
+ * days, plus one, from the first day of the month specified. For
+ * example, DATE(2008,1,-15) returns the serial number representing
+ * December 16, 2007.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATE($year = 0, $month = 1, $day = 1)
+ {
+ $year = PHPExcel_Calculation_Functions::flattenSingleValue($year);
+ $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
+ $day = PHPExcel_Calculation_Functions::flattenSingleValue($day);
+
+ if (($month !== null) && (!is_numeric($month))) {
$month = PHPExcel_Shared_Date::monthStringToNumber($month);
- }
+ }
- if (($day !== NULL) && (!is_numeric($day))) {
+ if (($day !== null) && (!is_numeric($day))) {
$day = PHPExcel_Shared_Date::dayStringToNumber($day);
- }
-
- $year = ($year !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($year) : 0;
- $month = ($month !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($month) : 0;
- $day = ($day !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($day) : 0;
- if ((!is_numeric($year)) ||
- (!is_numeric($month)) ||
- (!is_numeric($day))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $year = (integer) $year;
- $month = (integer) $month;
- $day = (integer) $day;
-
- $baseYear = PHPExcel_Shared_Date::getExcelCalendar();
- // Validate parameters
- if ($year < ($baseYear-1900)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
- $year += 1900;
- }
-
- if ($month < 1) {
- // Handle year/month adjustment if month < 1
- --$month;
- $year += ceil($month / 12) - 1;
- $month = 13 - abs($month % 12);
- } elseif ($month > 12) {
- // Handle year/month adjustment if month > 12
- $year += floor($month / 12);
- $month = ($month % 12);
- }
-
- // Re-validate the year parameter after adjustments
- if (($year < $baseYear) || ($year >= 10000)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day);
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $excelDateValue;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue);
- }
- } // function DATE()
-
-
- /**
- * TIME
- *
- * The TIME function returns a value that represents a particular time.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * TIME(hour,minute,second)
- *
- * @access public
- * @category Date/Time Functions
- * @param integer $hour A number from 0 (zero) to 32767 representing the hour.
- * Any value greater than 23 will be divided by 24 and the remainder
- * will be treated as the hour value. For example, TIME(27,0,0) =
- * TIME(3,0,0) = .125 or 3:00 AM.
- * @param integer $minute A number from 0 to 32767 representing the minute.
- * Any value greater than 59 will be converted to hours and minutes.
- * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
- * @param integer $second A number from 0 to 32767 representing the second.
- * Any value greater than 59 will be converted to hours, minutes,
- * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
- * or 12:33:20 AM
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function TIME($hour = 0, $minute = 0, $second = 0) {
- $hour = PHPExcel_Calculation_Functions::flattenSingleValue($hour);
- $minute = PHPExcel_Calculation_Functions::flattenSingleValue($minute);
- $second = PHPExcel_Calculation_Functions::flattenSingleValue($second);
-
- if ($hour == '') { $hour = 0; }
- if ($minute == '') { $minute = 0; }
- if ($second == '') { $second = 0; }
-
- if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $hour = (integer) $hour;
- $minute = (integer) $minute;
- $second = (integer) $second;
-
- if ($second < 0) {
- $minute += floor($second / 60);
- $second = 60 - abs($second % 60);
- if ($second == 60) { $second = 0; }
- } elseif ($second >= 60) {
- $minute += floor($second / 60);
- $second = $second % 60;
- }
- if ($minute < 0) {
- $hour += floor($minute / 60);
- $minute = 60 - abs($minute % 60);
- if ($minute == 60) { $minute = 0; }
- } elseif ($minute >= 60) {
- $hour += floor($minute / 60);
- $minute = $minute % 60;
- }
-
- if ($hour > 23) {
- $hour = $hour % 24;
- } elseif ($hour < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- $date = 0;
- $calendar = PHPExcel_Shared_Date::getExcelCalendar();
- if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) {
- $date = 1;
- }
- return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- $dayAdjust = 0;
- if ($hour < 0) {
- $dayAdjust = floor($hour / 24);
- $hour = 24 - abs($hour % 24);
- if ($hour == 24) { $hour = 0; }
- } elseif ($hour >= 24) {
- $dayAdjust = floor($hour / 24);
- $hour = $hour % 24;
- }
- $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
- if ($dayAdjust != 0) {
- $phpDateObject->modify($dayAdjust.' days');
- }
- return $phpDateObject;
- }
- } // function TIME()
-
-
- /**
- * DATEVALUE
- *
- * Returns a value that represents a particular date.
- * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
- * value.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * DATEVALUE(dateValue)
- *
- * @access public
- * @category Date/Time Functions
- * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
- * For example, "1/30/2008" or "30-Jan-2008" are text strings within
- * quotation marks that represent dates. Using the default date
- * system in Excel for Windows, date_text must represent a date from
- * January 1, 1900, to December 31, 9999. Using the default date
- * system in Excel for the Macintosh, date_text must represent a date
- * from January 1, 1904, to December 31, 9999. DATEVALUE returns the
- * #VALUE! error value if date_text is out of this range.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function DATEVALUE($dateValue = 1) {
- $dateValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($dateValue),'"');
- // Strip any ordinals because they're allowed in Excel (English only)
- $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui','$1$3',$dateValue);
- // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
- $dateValue = str_replace(array('/','.','-',' '),array(' ',' ',' ',' '),$dateValue);
-
- $yearFound = false;
- $t1 = explode(' ',$dateValue);
- foreach($t1 as &$t) {
- if ((is_numeric($t)) && ($t > 31)) {
- if ($yearFound) {
- return PHPExcel_Calculation_Functions::VALUE();
- } else {
- if ($t < 100) { $t += 1900; }
- $yearFound = true;
- }
- }
- }
- if ((count($t1) == 1) && (strpos($t,':') != false)) {
- // We've been fed a time value without any date
- return 0.0;
- } elseif (count($t1) == 2) {
- // We only have two parts of the date: either day/month or month/year
- if ($yearFound) {
- array_unshift($t1,1);
- } else {
- array_push($t1,date('Y'));
- }
- }
- unset($t);
- $dateValue = implode(' ',$t1);
-
- $PHPDateArray = date_parse($dateValue);
- if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
- $testVal1 = strtok($dateValue,'- ');
- if ($testVal1 !== False) {
- $testVal2 = strtok('- ');
- if ($testVal2 !== False) {
- $testVal3 = strtok('- ');
- if ($testVal3 === False) {
- $testVal3 = strftime('%Y');
- }
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
- if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
- $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
- if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- }
-
- if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
- // Execute function
- if ($PHPDateArray['year'] == '') { $PHPDateArray['year'] = strftime('%Y'); }
- if ($PHPDateArray['year'] < 1900)
- return PHPExcel_Calculation_Functions::VALUE();
- if ($PHPDateArray['month'] == '') { $PHPDateArray['month'] = strftime('%m'); }
- if ($PHPDateArray['day'] == '') { $PHPDateArray['day'] = strftime('%d'); }
- $excelDateValue = floor(PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']));
-
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $excelDateValue;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function DATEVALUE()
-
-
- /**
- * TIMEVALUE
- *
- * Returns a value that represents a particular time.
- * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
- * value.
- *
- * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
- * format of your regional settings. PHPExcel does not change cell formatting in this way.
- *
- * Excel Function:
- * TIMEVALUE(timeValue)
- *
- * @access public
- * @category Date/Time Functions
- * @param string $timeValue A text string that represents a time in any one of the Microsoft
- * Excel time formats; for example, "6:45 PM" and "18:45" text strings
- * within quotation marks that represent time.
- * Date information in time_text is ignored.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function TIMEVALUE($timeValue) {
- $timeValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($timeValue),'"');
- $timeValue = str_replace(array('/','.'),array('-','-'),$timeValue);
-
- $PHPDateArray = date_parse($timeValue);
- if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']);
- } else {
- $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900,1,1,$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']) - 1;
- }
-
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $excelDateValue;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function TIMEVALUE()
-
-
- /**
- * DATEDIF
- *
- * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
- * or a standard date string
- * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
- * or a standard date string
- * @param string $unit
- * @return integer Interval between the dates
- */
- public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') {
- $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
- $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
- $unit = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($unit));
-
- if (is_string($startDate = self::_getDateValue($startDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($endDate = self::_getDateValue($endDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Validate parameters
- if ($startDate >= $endDate) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $difference = $endDate - $startDate;
-
- $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
- $startDays = $PHPStartDateObject->format('j');
- $startMonths = $PHPStartDateObject->format('n');
- $startYears = $PHPStartDateObject->format('Y');
-
- $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
- $endDays = $PHPEndDateObject->format('j');
- $endMonths = $PHPEndDateObject->format('n');
- $endYears = $PHPEndDateObject->format('Y');
-
- $retVal = PHPExcel_Calculation_Functions::NaN();
- switch ($unit) {
- case 'D':
- $retVal = intval($difference);
- break;
- case 'M':
- $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
- // We're only interested in full months
- if ($endDays < $startDays) {
- --$retVal;
- }
- break;
- case 'Y':
- $retVal = intval($endYears - $startYears);
- // We're only interested in full months
- if ($endMonths < $startMonths) {
- --$retVal;
- } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
- --$retVal;
- }
- break;
- case 'MD':
- if ($endDays < $startDays) {
- $retVal = $endDays;
- $PHPEndDateObject->modify('-'.$endDays.' days');
- $adjustDays = $PHPEndDateObject->format('j');
- if ($adjustDays > $startDays) {
- $retVal += ($adjustDays - $startDays);
- }
- } else {
- $retVal = $endDays - $startDays;
- }
- break;
- case 'YM':
- $retVal = intval($endMonths - $startMonths);
- if ($retVal < 0) $retVal = 12 + $retVal;
- // We're only interested in full months
- if ($endDays < $startDays) {
- --$retVal;
- }
- break;
- case 'YD':
- $retVal = intval($difference);
- if ($endYears > $startYears) {
- while ($endYears > $startYears) {
- $PHPEndDateObject->modify('-1 year');
- $endYears = $PHPEndDateObject->format('Y');
- }
- $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
- if ($retVal < 0) { $retVal += 365; }
- }
- break;
- default:
- $retVal = PHPExcel_Calculation_Functions::NaN();
- }
- return $retVal;
- } // function DATEDIF()
-
-
- /**
- * DAYS360
- *
- * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
- * which is used in some accounting calculations. Use this function to help compute payments if
- * your accounting system is based on twelve 30-day months.
- *
- * Excel Function:
- * DAYS360(startDate,endDate[,method])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param boolean $method US or European Method
- * FALSE or omitted: U.S. (NASD) method. If the starting date is
- * the last day of a month, it becomes equal to the 30th of the
- * same month. If the ending date is the last day of a month and
- * the starting date is earlier than the 30th of a month, the
- * ending date becomes equal to the 1st of the next month;
- * otherwise the ending date becomes equal to the 30th of the
- * same month.
- * TRUE: European method. Starting dates and ending dates that
- * occur on the 31st of a month become equal to the 30th of the
- * same month.
- * @return integer Number of days between start date and end date
- */
- public static function DAYS360($startDate = 0, $endDate = 0, $method = false) {
- $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
- $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
-
- if (is_string($startDate = self::_getDateValue($startDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($endDate = self::_getDateValue($endDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (!is_bool($method)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Execute function
- $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
- $startDay = $PHPStartDateObject->format('j');
- $startMonth = $PHPStartDateObject->format('n');
- $startYear = $PHPStartDateObject->format('Y');
-
- $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
- $endDay = $PHPEndDateObject->format('j');
- $endMonth = $PHPEndDateObject->format('n');
- $endYear = $PHPEndDateObject->format('Y');
-
- return self::_dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
- } // function DAYS360()
-
-
- /**
- * YEARFRAC
- *
- * Calculates the fraction of the year represented by the number of whole days between two dates
- * (the start_date and the end_date).
- * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
- * obligations to assign to a specific term.
- *
- * Excel Function:
- * YEARFRAC(startDate,endDate[,method])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param integer $method Method used for the calculation
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float fraction of the year
- */
- public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) {
- $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
- $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
- $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
-
- if (is_string($startDate = self::_getDateValue($startDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($endDate = self::_getDateValue($endDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
- switch($method) {
- case 0 :
- return self::DAYS360($startDate,$endDate) / 360;
- case 1 :
- $days = self::DATEDIF($startDate,$endDate);
- $startYear = self::YEAR($startDate);
- $endYear = self::YEAR($endDate);
- $years = $endYear - $startYear + 1;
- $leapDays = 0;
- if ($years == 1) {
- if (self::_isLeapYear($endYear)) {
- $startMonth = self::MONTHOFYEAR($startDate);
- $endMonth = self::MONTHOFYEAR($endDate);
- $endDay = self::DAYOFMONTH($endDate);
- if (($startMonth < 3) ||
- (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
- $leapDays += 1;
- }
- }
- } else {
- for($year = $startYear; $year <= $endYear; ++$year) {
- if ($year == $startYear) {
- $startMonth = self::MONTHOFYEAR($startDate);
- $startDay = self::DAYOFMONTH($startDate);
- if ($startMonth < 3) {
- $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
- }
- } elseif($year == $endYear) {
- $endMonth = self::MONTHOFYEAR($endDate);
- $endDay = self::DAYOFMONTH($endDate);
- if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
- $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
- }
- } else {
- $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
- }
- }
- if ($years == 2) {
- if (($leapDays == 0) && (self::_isLeapYear($startYear)) && ($days > 365)) {
- $leapDays = 1;
- } elseif ($days < 366) {
- $years = 1;
- }
- }
- $leapDays /= $years;
- }
- return $days / (365 + $leapDays);
- case 2 :
- return self::DATEDIF($startDate,$endDate) / 360;
- case 3 :
- return self::DATEDIF($startDate,$endDate) / 365;
- case 4 :
- return self::DAYS360($startDate,$endDate,True) / 360;
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function YEARFRAC()
-
-
- /**
- * NETWORKDAYS
- *
- * Returns the number of whole working days between start_date and end_date. Working days
- * exclude weekends and any dates identified in holidays.
- * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
- * worked during a specific term.
- *
- * Excel Function:
- * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
- * timestamp (integer), PHP DateTime object, or a standard date
- * strings that will be excluded from the working calendar, such
- * as state and federal holidays and floating holidays.
- * @return integer Interval between the dates
- */
- public static function NETWORKDAYS($startDate,$endDate) {
- // Retrieve the mandatory start and end date that are referenced in the function definition
- $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
- $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
- // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
- $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
- array_shift($dateArgs);
- array_shift($dateArgs);
-
- // Validate the start and end dates
- if (is_string($startDate = $sDate = self::_getDateValue($startDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $startDate = (float) floor($startDate);
- if (is_string($endDate = $eDate = self::_getDateValue($endDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $endDate = (float) floor($endDate);
-
- if ($sDate > $eDate) {
- $startDate = $eDate;
- $endDate = $sDate;
- }
-
- // Execute function
- $startDoW = 6 - self::DAYOFWEEK($startDate,2);
- if ($startDoW < 0) { $startDoW = 0; }
- $endDoW = self::DAYOFWEEK($endDate,2);
- if ($endDoW >= 6) { $endDoW = 0; }
-
- $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
- $partWeekDays = $endDoW + $startDoW;
- if ($partWeekDays > 5) {
- $partWeekDays -= 5;
- }
-
- // Test any extra holiday parameters
- $holidayCountedArray = array();
- foreach ($dateArgs as $holidayDate) {
- if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
- if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
- --$partWeekDays;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- }
-
- if ($sDate > $eDate) {
- return 0 - ($wholeWeekDays + $partWeekDays);
- }
- return $wholeWeekDays + $partWeekDays;
- } // function NETWORKDAYS()
-
-
- /**
- * WORKDAY
- *
- * Returns the date that is the indicated number of working days before or after a date (the
- * starting date). Working days exclude weekends and any dates identified as holidays.
- * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
- * delivery times, or the number of days of work performed.
- *
- * Excel Function:
- * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
- *
- * @access public
- * @category Date/Time Functions
- * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param integer $endDays The number of nonweekend and nonholiday days before or after
- * startDate. A positive value for days yields a future date; a
- * negative value yields a past date.
- * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
- * timestamp (integer), PHP DateTime object, or a standard date
- * strings that will be excluded from the working calendar, such
- * as state and federal holidays and floating holidays.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function WORKDAY($startDate,$endDays) {
- // Retrieve the mandatory start date and days that are referenced in the function definition
- $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
- $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays);
- // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
- $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
- array_shift($dateArgs);
- array_shift($dateArgs);
-
- if ((is_string($startDate = self::_getDateValue($startDate))) || (!is_numeric($endDays))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $startDate = (float) floor($startDate);
- $endDays = (int) floor($endDays);
- // If endDays is 0, we always return startDate
- if ($endDays == 0) { return $startDate; }
-
- $decrementing = ($endDays < 0) ? True : False;
-
- // Adjust the start date if it falls over a weekend
-
- $startDoW = self::DAYOFWEEK($startDate,3);
- if (self::DAYOFWEEK($startDate,3) >= 5) {
- $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;
- ($decrementing) ? $endDays++ : $endDays--;
- }
-
- // Add endDays
- $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);
-
- // Adjust the calculated end date if it falls over a weekend
- $endDoW = self::DAYOFWEEK($endDate,3);
- if ($endDoW >= 5) {
- $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
- }
-
- // Test any extra holiday parameters
- if (!empty($dateArgs)) {
- $holidayCountedArray = $holidayDates = array();
- foreach ($dateArgs as $holidayDate) {
- if (($holidayDate !== NULL) && (trim($holidayDate) > '')) {
- if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (self::DAYOFWEEK($holidayDate,3) < 5) {
- $holidayDates[] = $holidayDate;
- }
- }
- }
- if ($decrementing) {
- rsort($holidayDates, SORT_NUMERIC);
- } else {
- sort($holidayDates, SORT_NUMERIC);
- }
- foreach ($holidayDates as $holidayDate) {
- if ($decrementing) {
- if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
- if (!in_array($holidayDate,$holidayCountedArray)) {
- --$endDate;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- } else {
- if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
- if (!in_array($holidayDate,$holidayCountedArray)) {
- ++$endDate;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- }
- // Adjust the calculated end date if it falls over a weekend
- $endDoW = self::DAYOFWEEK($endDate,3);
- if ($endDoW >= 5) {
- $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
- }
-
- }
- }
-
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- return (float) $endDate;
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate);
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
- }
- } // function WORKDAY()
-
-
- /**
- * DAYOFMONTH
- *
- * Returns the day of the month, for a specified date. The day is given as an integer
- * ranging from 1 to 31.
- *
- * Excel Function:
- * DAY(dateValue)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @return int Day of the month
- */
- public static function DAYOFMONTH($dateValue = 1) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($dateValue == 0.0) {
- return 0;
- } elseif ($dateValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
-
- return (int) $PHPDateObject->format('j');
- } // function DAYOFMONTH()
-
-
- /**
- * DAYOFWEEK
- *
- * Returns the day of the week for a specified date. The day is given as an integer
- * ranging from 0 to 7 (dependent on the requested style).
- *
- * Excel Function:
- * WEEKDAY(dateValue[,style])
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param int $style A number that determines the type of return value
- * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday).
- * 2 Numbers 1 (Monday) through 7 (Sunday).
- * 3 Numbers 0 (Monday) through 6 (Sunday).
- * @return int Day of the week value
- */
- public static function DAYOFWEEK($dateValue = 1, $style = 1) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
- $style = PHPExcel_Calculation_Functions::flattenSingleValue($style);
-
- if (!is_numeric($style)) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif (($style < 1) || ($style > 3)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $style = floor($style);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
- $DoW = $PHPDateObject->format('w');
-
- $firstDay = 1;
- switch ($style) {
- case 1: ++$DoW;
- break;
- case 2: if ($DoW == 0) { $DoW = 7; }
- break;
- case 3: if ($DoW == 0) { $DoW = 7; }
- $firstDay = 0;
- --$DoW;
- break;
- }
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL) {
- // Test for Excel's 1900 leap year, and introduce the error as required
- if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
- --$DoW;
- if ($DoW < $firstDay) {
- $DoW += 7;
- }
- }
- }
-
- return (int) $DoW;
- } // function DAYOFWEEK()
-
-
- /**
- * WEEKOFYEAR
- *
- * Returns the week of the year for a specified date.
- * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
- * However, there is a European standard that defines the first week as the one with the majority
- * of days (four or more) falling in the new year. This means that for years in which there are
- * three days or less in the first week of January, the WEEKNUM function returns week numbers
- * that are incorrect according to the European standard.
- *
- * Excel Function:
- * WEEKNUM(dateValue[,style])
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param boolean $method Week begins on Sunday or Monday
- * 1 or omitted Week begins on Sunday.
- * 2 Week begins on Monday.
- * @return int Week Number
- */
- public static function WEEKOFYEAR($dateValue = 1, $method = 1) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
- $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
-
- if (!is_numeric($method)) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif (($method < 1) || ($method > 2)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $method = floor($method);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
- $dayOfYear = $PHPDateObject->format('z');
- $dow = $PHPDateObject->format('w');
- $PHPDateObject->modify('-'.$dayOfYear.' days');
- $dow = $PHPDateObject->format('w');
- $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
- $dayOfYear -= $daysInFirstWeek;
- $weekOfYear = ceil($dayOfYear / 7) + 1;
-
- return (int) $weekOfYear;
- } // function WEEKOFYEAR()
-
-
- /**
- * MONTHOFYEAR
- *
- * Returns the month of a date represented by a serial number.
- * The month is given as an integer, ranging from 1 (January) to 12 (December).
- *
- * Excel Function:
- * MONTH(dateValue)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @return int Month of the year
- */
- public static function MONTHOFYEAR($dateValue = 1) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
-
- return (int) $PHPDateObject->format('n');
- } // function MONTHOFYEAR()
-
-
- /**
- * YEAR
- *
- * Returns the year corresponding to a date.
- * The year is returned as an integer in the range 1900-9999.
- *
- * Excel Function:
- * YEAR(dateValue)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @return int Year
- */
- public static function YEAR($dateValue = 1) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Execute function
- $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
-
- return (int) $PHPDateObject->format('Y');
- } // function YEAR()
-
-
- /**
- * HOUROFDAY
- *
- * Returns the hour of a time value.
- * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
- *
- * Excel Function:
- * HOUR(timeValue)
- *
- * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard time string
- * @return int Hour
- */
- public static function HOUROFDAY($timeValue = 0) {
- $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue,'/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- $timeValue = self::_getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue,1);
- } elseif ($timeValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
-
- return (int) gmdate('G',$timeValue);
- } // function HOUROFDAY()
-
-
- /**
- * MINUTEOFHOUR
- *
- * Returns the minutes of a time value.
- * The minute is given as an integer, ranging from 0 to 59.
- *
- * Excel Function:
- * MINUTE(timeValue)
- *
- * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard time string
- * @return int Minute
- */
- public static function MINUTEOFHOUR($timeValue = 0) {
- $timeValue = $timeTester = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue,'/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- $timeValue = self::_getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue,1);
- } elseif ($timeValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
-
- return (int) gmdate('i',$timeValue);
- } // function MINUTEOFHOUR()
-
-
- /**
- * SECONDOFMINUTE
- *
- * Returns the seconds of a time value.
- * The second is given as an integer in the range 0 (zero) to 59.
- *
- * Excel Function:
- * SECOND(timeValue)
- *
- * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard time string
- * @return int Second
- */
- public static function SECONDOFMINUTE($timeValue = 0) {
- $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue,'/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- $timeValue = self::_getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue,1);
- } elseif ($timeValue < 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
-
- return (int) gmdate('s',$timeValue);
- } // function SECONDOFMINUTE()
-
-
- /**
- * EDATE
- *
- * Returns the serial number that represents the date that is the indicated number of months
- * before or after a specified date (the start_date).
- * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
- * as the date of issue.
- *
- * Excel Function:
- * EDATE(dateValue,adjustmentMonths)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param int $adjustmentMonths The number of months before or after start_date.
- * A positive value for months yields a future date;
- * a negative value yields a past date.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function EDATE($dateValue = 1, $adjustmentMonths = 0) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
- $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
-
- if (!is_numeric($adjustmentMonths)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $adjustmentMonths = floor($adjustmentMonths);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Execute function
- $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths);
-
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return $PHPDateObject;
- }
- } // function EDATE()
-
-
- /**
- * EOMONTH
- *
- * Returns the date value for the last day of the month that is the indicated number of months
- * before or after start_date.
- * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
- *
- * Excel Function:
- * EOMONTH(dateValue,adjustmentMonths)
- *
- * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
- * PHP DateTime object, or a standard date string
- * @param int $adjustmentMonths The number of months before or after start_date.
- * A positive value for months yields a future date;
- * a negative value yields a past date.
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) {
- $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
- $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
-
- if (!is_numeric($adjustmentMonths)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $adjustmentMonths = floor($adjustmentMonths);
-
- if (is_string($dateValue = self::_getDateValue($dateValue))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Execute function
- $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths+1);
- $adjustDays = (int) $PHPDateObject->format('d');
- $adjustDaysString = '-'.$adjustDays.' days';
- $PHPDateObject->modify($adjustDaysString);
-
- switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
- case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
- return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
- return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
- case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
- return $PHPDateObject;
- }
- } // function EOMONTH()
-
-} // class PHPExcel_Calculation_DateTime
-
+ }
+
+ $year = ($year !== null) ? PHPExcel_Shared_String::testStringAsNumeric($year) : 0;
+ $month = ($month !== null) ? PHPExcel_Shared_String::testStringAsNumeric($month) : 0;
+ $day = ($day !== null) ? PHPExcel_Shared_String::testStringAsNumeric($day) : 0;
+ if ((!is_numeric($year)) ||
+ (!is_numeric($month)) ||
+ (!is_numeric($day))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $year = (integer) $year;
+ $month = (integer) $month;
+ $day = (integer) $day;
+
+ $baseYear = PHPExcel_Shared_Date::getExcelCalendar();
+ // Validate parameters
+ if ($year < ($baseYear-1900)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
+ $year += 1900;
+ }
+
+ if ($month < 1) {
+ // Handle year/month adjustment if month < 1
+ --$month;
+ $year += ceil($month / 12) - 1;
+ $month = 13 - abs($month % 12);
+ } elseif ($month > 12) {
+ // Handle year/month adjustment if month > 12
+ $year += floor($month / 12);
+ $month = ($month % 12);
+ }
+
+ // Re-validate the year parameter after adjustments
+ if (($year < $baseYear) || ($year >= 10000)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day);
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ return (float) $excelDateValue;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue);
+ }
+ }
+
+
+ /**
+ * TIME
+ *
+ * The TIME function returns a value that represents a particular time.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * TIME(hour,minute,second)
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param integer $hour A number from 0 (zero) to 32767 representing the hour.
+ * Any value greater than 23 will be divided by 24 and the remainder
+ * will be treated as the hour value. For example, TIME(27,0,0) =
+ * TIME(3,0,0) = .125 or 3:00 AM.
+ * @param integer $minute A number from 0 to 32767 representing the minute.
+ * Any value greater than 59 will be converted to hours and minutes.
+ * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
+ * @param integer $second A number from 0 to 32767 representing the second.
+ * Any value greater than 59 will be converted to hours, minutes,
+ * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
+ * or 12:33:20 AM
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function TIME($hour = 0, $minute = 0, $second = 0)
+ {
+ $hour = PHPExcel_Calculation_Functions::flattenSingleValue($hour);
+ $minute = PHPExcel_Calculation_Functions::flattenSingleValue($minute);
+ $second = PHPExcel_Calculation_Functions::flattenSingleValue($second);
+
+ if ($hour == '') {
+ $hour = 0;
+ }
+ if ($minute == '') {
+ $minute = 0;
+ }
+ if ($second == '') {
+ $second = 0;
+ }
+
+ if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $hour = (integer) $hour;
+ $minute = (integer) $minute;
+ $second = (integer) $second;
+
+ if ($second < 0) {
+ $minute += floor($second / 60);
+ $second = 60 - abs($second % 60);
+ if ($second == 60) {
+ $second = 0;
+ }
+ } elseif ($second >= 60) {
+ $minute += floor($second / 60);
+ $second = $second % 60;
+ }
+ if ($minute < 0) {
+ $hour += floor($minute / 60);
+ $minute = 60 - abs($minute % 60);
+ if ($minute == 60) {
+ $minute = 0;
+ }
+ } elseif ($minute >= 60) {
+ $hour += floor($minute / 60);
+ $minute = $minute % 60;
+ }
+
+ if ($hour > 23) {
+ $hour = $hour % 24;
+ } elseif ($hour < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ $date = 0;
+ $calendar = PHPExcel_Shared_Date::getExcelCalendar();
+ if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) {
+ $date = 1;
+ }
+ return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ $dayAdjust = 0;
+ if ($hour < 0) {
+ $dayAdjust = floor($hour / 24);
+ $hour = 24 - abs($hour % 24);
+ if ($hour == 24) {
+ $hour = 0;
+ }
+ } elseif ($hour >= 24) {
+ $dayAdjust = floor($hour / 24);
+ $hour = $hour % 24;
+ }
+ $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
+ if ($dayAdjust != 0) {
+ $phpDateObject->modify($dayAdjust.' days');
+ }
+ return $phpDateObject;
+ }
+ }
+
+
+ /**
+ * DATEVALUE
+ *
+ * Returns a value that represents a particular date.
+ * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
+ * value.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * DATEVALUE(dateValue)
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
+ * For example, "1/30/2008" or "30-Jan-2008" are text strings within
+ * quotation marks that represent dates. Using the default date
+ * system in Excel for Windows, date_text must represent a date from
+ * January 1, 1900, to December 31, 9999. Using the default date
+ * system in Excel for the Macintosh, date_text must represent a date
+ * from January 1, 1904, to December 31, 9999. DATEVALUE returns the
+ * #VALUE! error value if date_text is out of this range.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function DATEVALUE($dateValue = 1)
+ {
+ $dateValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($dateValue), '"');
+ // Strip any ordinals because they're allowed in Excel (English only)
+ $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue);
+ // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
+ $dateValue = str_replace(array('/', '.', '-', ' '), array(' ', ' ', ' ', ' '), $dateValue);
+
+ $yearFound = false;
+ $t1 = explode(' ', $dateValue);
+ foreach ($t1 as &$t) {
+ if ((is_numeric($t)) && ($t > 31)) {
+ if ($yearFound) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } else {
+ if ($t < 100) {
+ $t += 1900;
+ }
+ $yearFound = true;
+ }
+ }
+ }
+ if ((count($t1) == 1) && (strpos($t, ':') != false)) {
+ // We've been fed a time value without any date
+ return 0.0;
+ } elseif (count($t1) == 2) {
+ // We only have two parts of the date: either day/month or month/year
+ if ($yearFound) {
+ array_unshift($t1, 1);
+ } else {
+ array_push($t1, date('Y'));
+ }
+ }
+ unset($t);
+ $dateValue = implode(' ', $t1);
+
+ $PHPDateArray = date_parse($dateValue);
+ if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
+ $testVal1 = strtok($dateValue, '- ');
+ if ($testVal1 !== false) {
+ $testVal2 = strtok('- ');
+ if ($testVal2 !== false) {
+ $testVal3 = strtok('- ');
+ if ($testVal3 === false) {
+ $testVal3 = strftime('%Y');
+ }
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
+ if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
+ $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
+ if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ }
+
+ if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
+ // Execute function
+ if ($PHPDateArray['year'] == '') {
+ $PHPDateArray['year'] = strftime('%Y');
+ }
+ if ($PHPDateArray['year'] < 1900) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if ($PHPDateArray['month'] == '') {
+ $PHPDateArray['month'] = strftime('%m');
+ }
+ if ($PHPDateArray['day'] == '') {
+ $PHPDateArray['day'] = strftime('%d');
+ }
+ $excelDateValue = floor(
+ PHPExcel_Shared_Date::FormattedPHPToExcel(
+ $PHPDateArray['year'],
+ $PHPDateArray['month'],
+ $PHPDateArray['day'],
+ $PHPDateArray['hour'],
+ $PHPDateArray['minute'],
+ $PHPDateArray['second']
+ )
+ );
+
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ return (float) $excelDateValue;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * TIMEVALUE
+ *
+ * Returns a value that represents a particular time.
+ * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
+ * value.
+ *
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
+ *
+ * Excel Function:
+ * TIMEVALUE(timeValue)
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param string $timeValue A text string that represents a time in any one of the Microsoft
+ * Excel time formats; for example, "6:45 PM" and "18:45" text strings
+ * within quotation marks that represent time.
+ * Date information in time_text is ignored.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function TIMEVALUE($timeValue)
+ {
+ $timeValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($timeValue), '"');
+ $timeValue = str_replace(array('/', '.'), array('-', '-'), $timeValue);
+
+ $PHPDateArray = date_parse($timeValue);
+ if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(
+ $PHPDateArray['year'],
+ $PHPDateArray['month'],
+ $PHPDateArray['day'],
+ $PHPDateArray['hour'],
+ $PHPDateArray['minute'],
+ $PHPDateArray['second']
+ );
+ } else {
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1;
+ }
+
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ return (float) $excelDateValue;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * DATEDIF
+ *
+ * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
+ * or a standard date string
+ * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
+ * or a standard date string
+ * @param string $unit
+ * @return integer Interval between the dates
+ */
+ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D')
+ {
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
+ $unit = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($unit));
+
+ if (is_string($startDate = self::getDateValue($startDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($endDate = self::getDateValue($endDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Validate parameters
+ if ($startDate >= $endDate) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $difference = $endDate - $startDate;
+
+ $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
+ $startDays = $PHPStartDateObject->format('j');
+ $startMonths = $PHPStartDateObject->format('n');
+ $startYears = $PHPStartDateObject->format('Y');
+
+ $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
+ $endDays = $PHPEndDateObject->format('j');
+ $endMonths = $PHPEndDateObject->format('n');
+ $endYears = $PHPEndDateObject->format('Y');
+
+ $retVal = PHPExcel_Calculation_Functions::NaN();
+ switch ($unit) {
+ case 'D':
+ $retVal = intval($difference);
+ break;
+ case 'M':
+ $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
+ // We're only interested in full months
+ if ($endDays < $startDays) {
+ --$retVal;
+ }
+ break;
+ case 'Y':
+ $retVal = intval($endYears - $startYears);
+ // We're only interested in full months
+ if ($endMonths < $startMonths) {
+ --$retVal;
+ } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
+ --$retVal;
+ }
+ break;
+ case 'MD':
+ if ($endDays < $startDays) {
+ $retVal = $endDays;
+ $PHPEndDateObject->modify('-'.$endDays.' days');
+ $adjustDays = $PHPEndDateObject->format('j');
+ if ($adjustDays > $startDays) {
+ $retVal += ($adjustDays - $startDays);
+ }
+ } else {
+ $retVal = $endDays - $startDays;
+ }
+ break;
+ case 'YM':
+ $retVal = intval($endMonths - $startMonths);
+ if ($retVal < 0) {
+ $retVal += 12;
+ }
+ // We're only interested in full months
+ if ($endDays < $startDays) {
+ --$retVal;
+ }
+ break;
+ case 'YD':
+ $retVal = intval($difference);
+ if ($endYears > $startYears) {
+ while ($endYears > $startYears) {
+ $PHPEndDateObject->modify('-1 year');
+ $endYears = $PHPEndDateObject->format('Y');
+ }
+ $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
+ if ($retVal < 0) {
+ $retVal += 365;
+ }
+ }
+ break;
+ default:
+ $retVal = PHPExcel_Calculation_Functions::NaN();
+ }
+ return $retVal;
+ }
+
+
+ /**
+ * DAYS360
+ *
+ * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
+ * which is used in some accounting calculations. Use this function to help compute payments if
+ * your accounting system is based on twelve 30-day months.
+ *
+ * Excel Function:
+ * DAYS360(startDate,endDate[,method])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param boolean $method US or European Method
+ * FALSE or omitted: U.S. (NASD) method. If the starting date is
+ * the last day of a month, it becomes equal to the 30th of the
+ * same month. If the ending date is the last day of a month and
+ * the starting date is earlier than the 30th of a month, the
+ * ending date becomes equal to the 1st of the next month;
+ * otherwise the ending date becomes equal to the 30th of the
+ * same month.
+ * TRUE: European method. Starting dates and ending dates that
+ * occur on the 31st of a month become equal to the 30th of the
+ * same month.
+ * @return integer Number of days between start date and end date
+ */
+ public static function DAYS360($startDate = 0, $endDate = 0, $method = false)
+ {
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
+
+ if (is_string($startDate = self::getDateValue($startDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($endDate = self::getDateValue($endDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (!is_bool($method)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Execute function
+ $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
+ $startDay = $PHPStartDateObject->format('j');
+ $startMonth = $PHPStartDateObject->format('n');
+ $startYear = $PHPStartDateObject->format('Y');
+
+ $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
+ $endDay = $PHPEndDateObject->format('j');
+ $endMonth = $PHPEndDateObject->format('n');
+ $endYear = $PHPEndDateObject->format('Y');
+
+ return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
+ }
+
+
+ /**
+ * YEARFRAC
+ *
+ * Calculates the fraction of the year represented by the number of whole days between two dates
+ * (the start_date and the end_date).
+ * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
+ * obligations to assign to a specific term.
+ *
+ * Excel Function:
+ * YEARFRAC(startDate,endDate[,method])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param integer $method Method used for the calculation
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float fraction of the year
+ */
+ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0)
+ {
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
+ $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
+
+ if (is_string($startDate = self::getDateValue($startDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($endDate = self::getDateValue($endDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
+ switch ($method) {
+ case 0:
+ return self::DAYS360($startDate, $endDate) / 360;
+ case 1:
+ $days = self::DATEDIF($startDate, $endDate);
+ $startYear = self::YEAR($startDate);
+ $endYear = self::YEAR($endDate);
+ $years = $endYear - $startYear + 1;
+ $leapDays = 0;
+ if ($years == 1) {
+ if (self::isLeapYear($endYear)) {
+ $startMonth = self::MONTHOFYEAR($startDate);
+ $endMonth = self::MONTHOFYEAR($endDate);
+ $endDay = self::DAYOFMONTH($endDate);
+ if (($startMonth < 3) ||
+ (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
+ $leapDays += 1;
+ }
+ }
+ } else {
+ for ($year = $startYear; $year <= $endYear; ++$year) {
+ if ($year == $startYear) {
+ $startMonth = self::MONTHOFYEAR($startDate);
+ $startDay = self::DAYOFMONTH($startDate);
+ if ($startMonth < 3) {
+ $leapDays += (self::isLeapYear($year)) ? 1 : 0;
+ }
+ } elseif ($year == $endYear) {
+ $endMonth = self::MONTHOFYEAR($endDate);
+ $endDay = self::DAYOFMONTH($endDate);
+ if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
+ $leapDays += (self::isLeapYear($year)) ? 1 : 0;
+ }
+ } else {
+ $leapDays += (self::isLeapYear($year)) ? 1 : 0;
+ }
+ }
+ if ($years == 2) {
+ if (($leapDays == 0) && (self::isLeapYear($startYear)) && ($days > 365)) {
+ $leapDays = 1;
+ } elseif ($days < 366) {
+ $years = 1;
+ }
+ }
+ $leapDays /= $years;
+ }
+ return $days / (365 + $leapDays);
+ case 2:
+ return self::DATEDIF($startDate, $endDate) / 360;
+ case 3:
+ return self::DATEDIF($startDate, $endDate) / 365;
+ case 4:
+ return self::DAYS360($startDate, $endDate, true) / 360;
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * NETWORKDAYS
+ *
+ * Returns the number of whole working days between start_date and end_date. Working days
+ * exclude weekends and any dates identified in holidays.
+ * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
+ * worked during a specific term.
+ *
+ * Excel Function:
+ * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
+ * timestamp (integer), PHP DateTime object, or a standard date
+ * strings that will be excluded from the working calendar, such
+ * as state and federal holidays and floating holidays.
+ * @return integer Interval between the dates
+ */
+ public static function NETWORKDAYS($startDate, $endDate)
+ {
+ // Retrieve the mandatory start and end date that are referenced in the function definition
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
+ // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
+ $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ array_shift($dateArgs);
+ array_shift($dateArgs);
+
+ // Validate the start and end dates
+ if (is_string($startDate = $sDate = self::getDateValue($startDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $startDate = (float) floor($startDate);
+ if (is_string($endDate = $eDate = self::getDateValue($endDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $endDate = (float) floor($endDate);
+
+ if ($sDate > $eDate) {
+ $startDate = $eDate;
+ $endDate = $sDate;
+ }
+
+ // Execute function
+ $startDoW = 6 - self::DAYOFWEEK($startDate, 2);
+ if ($startDoW < 0) {
+ $startDoW = 0;
+ }
+ $endDoW = self::DAYOFWEEK($endDate, 2);
+ if ($endDoW >= 6) {
+ $endDoW = 0;
+ }
+
+ $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
+ $partWeekDays = $endDoW + $startDoW;
+ if ($partWeekDays > 5) {
+ $partWeekDays -= 5;
+ }
+
+ // Test any extra holiday parameters
+ $holidayCountedArray = array();
+ foreach ($dateArgs as $holidayDate) {
+ if (is_string($holidayDate = self::getDateValue($holidayDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
+ if ((self::DAYOFWEEK($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) {
+ --$partWeekDays;
+ $holidayCountedArray[] = $holidayDate;
+ }
+ }
+ }
+
+ if ($sDate > $eDate) {
+ return 0 - ($wholeWeekDays + $partWeekDays);
+ }
+ return $wholeWeekDays + $partWeekDays;
+ }
+
+
+ /**
+ * WORKDAY
+ *
+ * Returns the date that is the indicated number of working days before or after a date (the
+ * starting date). Working days exclude weekends and any dates identified as holidays.
+ * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
+ * delivery times, or the number of days of work performed.
+ *
+ * Excel Function:
+ * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
+ *
+ * @access public
+ * @category Date/Time Functions
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param integer $endDays The number of nonweekend and nonholiday days before or after
+ * startDate. A positive value for days yields a future date; a
+ * negative value yields a past date.
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
+ * timestamp (integer), PHP DateTime object, or a standard date
+ * strings that will be excluded from the working calendar, such
+ * as state and federal holidays and floating holidays.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function WORKDAY($startDate, $endDays)
+ {
+ // Retrieve the mandatory start date and days that are referenced in the function definition
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
+ $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays);
+ // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
+ $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ array_shift($dateArgs);
+ array_shift($dateArgs);
+
+ if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $startDate = (float) floor($startDate);
+ $endDays = (int) floor($endDays);
+ // If endDays is 0, we always return startDate
+ if ($endDays == 0) {
+ return $startDate;
+ }
+
+ $decrementing = ($endDays < 0) ? true : false;
+
+ // Adjust the start date if it falls over a weekend
+
+ $startDoW = self::DAYOFWEEK($startDate, 3);
+ if (self::DAYOFWEEK($startDate, 3) >= 5) {
+ $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;
+ ($decrementing) ? $endDays++ : $endDays--;
+ }
+
+ // Add endDays
+ $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);
+
+ // Adjust the calculated end date if it falls over a weekend
+ $endDoW = self::DAYOFWEEK($endDate, 3);
+ if ($endDoW >= 5) {
+ $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
+ }
+
+ // Test any extra holiday parameters
+ if (!empty($dateArgs)) {
+ $holidayCountedArray = $holidayDates = array();
+ foreach ($dateArgs as $holidayDate) {
+ if (($holidayDate !== null) && (trim($holidayDate) > '')) {
+ if (is_string($holidayDate = self::getDateValue($holidayDate))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (self::DAYOFWEEK($holidayDate, 3) < 5) {
+ $holidayDates[] = $holidayDate;
+ }
+ }
+ }
+ if ($decrementing) {
+ rsort($holidayDates, SORT_NUMERIC);
+ } else {
+ sort($holidayDates, SORT_NUMERIC);
+ }
+ foreach ($holidayDates as $holidayDate) {
+ if ($decrementing) {
+ if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
+ if (!in_array($holidayDate, $holidayCountedArray)) {
+ --$endDate;
+ $holidayCountedArray[] = $holidayDate;
+ }
+ }
+ } else {
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
+ if (!in_array($holidayDate, $holidayCountedArray)) {
+ ++$endDate;
+ $holidayCountedArray[] = $holidayDate;
+ }
+ }
+ }
+ // Adjust the calculated end date if it falls over a weekend
+ $endDoW = self::DAYOFWEEK($endDate, 3);
+ if ($endDoW >= 5) {
+ $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;
+ }
+ }
+ }
+
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ return (float) $endDate;
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate);
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ return PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
+ }
+ }
+
+
+ /**
+ * DAYOFMONTH
+ *
+ * Returns the day of the month, for a specified date. The day is given as an integer
+ * ranging from 1 to 31.
+ *
+ * Excel Function:
+ * DAY(dateValue)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @return int Day of the month
+ */
+ public static function DAYOFMONTH($dateValue = 1)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+
+ if ($dateValue === null) {
+ $dateValue = 1;
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($dateValue == 0.0) {
+ return 0;
+ } elseif ($dateValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
+
+ return (int) $PHPDateObject->format('j');
+ }
+
+
+ /**
+ * DAYOFWEEK
+ *
+ * Returns the day of the week for a specified date. The day is given as an integer
+ * ranging from 0 to 7 (dependent on the requested style).
+ *
+ * Excel Function:
+ * WEEKDAY(dateValue[,style])
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param int $style A number that determines the type of return value
+ * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday).
+ * 2 Numbers 1 (Monday) through 7 (Sunday).
+ * 3 Numbers 0 (Monday) through 6 (Sunday).
+ * @return int Day of the week value
+ */
+ public static function DAYOFWEEK($dateValue = 1, $style = 1)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+ $style = PHPExcel_Calculation_Functions::flattenSingleValue($style);
+
+ if (!is_numeric($style)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif (($style < 1) || ($style > 3)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $style = floor($style);
+
+ if ($dateValue === null) {
+ $dateValue = 1;
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
+ $DoW = $PHPDateObject->format('w');
+
+ $firstDay = 1;
+ switch ($style) {
+ case 1:
+ ++$DoW;
+ break;
+ case 2:
+ if ($DoW == 0) {
+ $DoW = 7;
+ }
+ break;
+ case 3:
+ if ($DoW == 0) {
+ $DoW = 7;
+ }
+ $firstDay = 0;
+ --$DoW;
+ break;
+ }
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL) {
+ // Test for Excel's 1900 leap year, and introduce the error as required
+ if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
+ --$DoW;
+ if ($DoW < $firstDay) {
+ $DoW += 7;
+ }
+ }
+ }
+
+ return (int) $DoW;
+ }
+
+
+ /**
+ * WEEKOFYEAR
+ *
+ * Returns the week of the year for a specified date.
+ * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
+ * However, there is a European standard that defines the first week as the one with the majority
+ * of days (four or more) falling in the new year. This means that for years in which there are
+ * three days or less in the first week of January, the WEEKNUM function returns week numbers
+ * that are incorrect according to the European standard.
+ *
+ * Excel Function:
+ * WEEKNUM(dateValue[,style])
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param boolean $method Week begins on Sunday or Monday
+ * 1 or omitted Week begins on Sunday.
+ * 2 Week begins on Monday.
+ * @return int Week Number
+ */
+ public static function WEEKOFYEAR($dateValue = 1, $method = 1)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+ $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
+
+ if (!is_numeric($method)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif (($method < 1) || ($method > 2)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $method = floor($method);
+
+ if ($dateValue === null) {
+ $dateValue = 1;
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
+ $dayOfYear = $PHPDateObject->format('z');
+ $dow = $PHPDateObject->format('w');
+ $PHPDateObject->modify('-' . $dayOfYear . ' days');
+ $dow = $PHPDateObject->format('w');
+ $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
+ $dayOfYear -= $daysInFirstWeek;
+ $weekOfYear = ceil($dayOfYear / 7) + 1;
+
+ return (int) $weekOfYear;
+ }
+
+
+ /**
+ * MONTHOFYEAR
+ *
+ * Returns the month of a date represented by a serial number.
+ * The month is given as an integer, ranging from 1 (January) to 12 (December).
+ *
+ * Excel Function:
+ * MONTH(dateValue)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @return int Month of the year
+ */
+ public static function MONTHOFYEAR($dateValue = 1)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+
+ if ($dateValue === null) {
+ $dateValue = 1;
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
+
+ return (int) $PHPDateObject->format('n');
+ }
+
+
+ /**
+ * YEAR
+ *
+ * Returns the year corresponding to a date.
+ * The year is returned as an integer in the range 1900-9999.
+ *
+ * Excel Function:
+ * YEAR(dateValue)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @return int Year
+ */
+ public static function YEAR($dateValue = 1)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+
+ if ($dateValue === null) {
+ $dateValue = 1;
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($dateValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Execute function
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
+
+ return (int) $PHPDateObject->format('Y');
+ }
+
+
+ /**
+ * HOUROFDAY
+ *
+ * Returns the hour of a time value.
+ * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
+ *
+ * Excel Function:
+ * HOUR(timeValue)
+ *
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard time string
+ * @return int Hour
+ */
+ public static function HOUROFDAY($timeValue = 0)
+ {
+ $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
+
+ if (!is_numeric($timeValue)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $testVal = strtok($timeValue, '/-: ');
+ if (strlen($testVal) < strlen($timeValue)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ $timeValue = self::getTimeValue($timeValue);
+ if (is_string($timeValue)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ // Execute function
+ if ($timeValue >= 1) {
+ $timeValue = fmod($timeValue, 1);
+ } elseif ($timeValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
+
+ return (int) gmdate('G', $timeValue);
+ }
+
+
+ /**
+ * MINUTEOFHOUR
+ *
+ * Returns the minutes of a time value.
+ * The minute is given as an integer, ranging from 0 to 59.
+ *
+ * Excel Function:
+ * MINUTE(timeValue)
+ *
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard time string
+ * @return int Minute
+ */
+ public static function MINUTEOFHOUR($timeValue = 0)
+ {
+ $timeValue = $timeTester = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
+
+ if (!is_numeric($timeValue)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $testVal = strtok($timeValue, '/-: ');
+ if (strlen($testVal) < strlen($timeValue)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ $timeValue = self::getTimeValue($timeValue);
+ if (is_string($timeValue)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ // Execute function
+ if ($timeValue >= 1) {
+ $timeValue = fmod($timeValue, 1);
+ } elseif ($timeValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
+
+ return (int) gmdate('i', $timeValue);
+ }
+
+
+ /**
+ * SECONDOFMINUTE
+ *
+ * Returns the seconds of a time value.
+ * The second is given as an integer in the range 0 (zero) to 59.
+ *
+ * Excel Function:
+ * SECOND(timeValue)
+ *
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard time string
+ * @return int Second
+ */
+ public static function SECONDOFMINUTE($timeValue = 0)
+ {
+ $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
+
+ if (!is_numeric($timeValue)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $testVal = strtok($timeValue, '/-: ');
+ if (strlen($testVal) < strlen($timeValue)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ $timeValue = self::getTimeValue($timeValue);
+ if (is_string($timeValue)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ // Execute function
+ if ($timeValue >= 1) {
+ $timeValue = fmod($timeValue, 1);
+ } elseif ($timeValue < 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
+
+ return (int) gmdate('s', $timeValue);
+ }
+
+
+ /**
+ * EDATE
+ *
+ * Returns the serial number that represents the date that is the indicated number of months
+ * before or after a specified date (the start_date).
+ * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
+ * as the date of issue.
+ *
+ * Excel Function:
+ * EDATE(dateValue,adjustmentMonths)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param int $adjustmentMonths The number of months before or after start_date.
+ * A positive value for months yields a future date;
+ * a negative value yields a past date.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function EDATE($dateValue = 1, $adjustmentMonths = 0)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+ $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
+
+ if (!is_numeric($adjustmentMonths)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $adjustmentMonths = floor($adjustmentMonths);
+
+ if (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Execute function
+ $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths);
+
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ return $PHPDateObject;
+ }
+ }
+
+
+ /**
+ * EOMONTH
+ *
+ * Returns the date value for the last day of the month that is the indicated number of months
+ * before or after start_date.
+ * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
+ *
+ * Excel Function:
+ * EOMONTH(dateValue,adjustmentMonths)
+ *
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @param int $adjustmentMonths The number of months before or after start_date.
+ * A positive value for months yields a future date;
+ * a negative value yields a past date.
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0)
+ {
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
+ $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
+
+ if (!is_numeric($adjustmentMonths)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $adjustmentMonths = floor($adjustmentMonths);
+
+ if (is_string($dateValue = self::getDateValue($dateValue))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Execute function
+ $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths+1);
+ $adjustDays = (int) $PHPDateObject->format('d');
+ $adjustDaysString = '-' . $adjustDays . ' days';
+ $PHPDateObject->modify($adjustDaysString);
+
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
+ return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
+ return $PHPDateObject;
+ }
+ }
+}
diff --git a/Classes/PHPExcel/Calculation/Engineering.php b/Classes/PHPExcel/Calculation/Engineering.php
index 84dcd388f..75e278474 100644
--- a/Classes/PHPExcel/Calculation/Engineering.php
+++ b/Classes/PHPExcel/Calculation/Engineering.php
@@ -1,8 +1,21 @@
array('Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true),
+ 'sg' => array('Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false),
+ 'lbm' => array('Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false),
+ 'u' => array('Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true),
+ 'ozm' => array('Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false),
+ 'm' => array('Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true),
+ 'mi' => array('Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false),
+ 'Nmi' => array('Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false),
+ 'in' => array('Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false),
+ 'ft' => array('Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false),
+ 'yd' => array('Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false),
+ 'ang' => array('Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true),
+ 'Pica' => array('Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false),
+ 'yr' => array('Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false),
+ 'day' => array('Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false),
+ 'hr' => array('Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false),
+ 'mn' => array('Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false),
+ 'sec' => array('Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true),
+ 'Pa' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true),
+ 'p' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true),
+ 'atm' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true),
+ 'at' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true),
+ 'mmHg' => array('Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true),
+ 'N' => array('Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true),
+ 'dyn' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true),
+ 'dy' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true),
+ 'lbf' => array('Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false),
+ 'J' => array('Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true),
+ 'e' => array('Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true),
+ 'c' => array('Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true),
+ 'cal' => array('Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true),
+ 'eV' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true),
+ 'ev' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true),
+ 'HPh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false),
+ 'hh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false),
+ 'Wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true),
+ 'wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true),
+ 'flb' => array('Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false),
+ 'BTU' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false),
+ 'btu' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false),
+ 'HP' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false),
+ 'h' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false),
+ 'W' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true),
+ 'w' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true),
+ 'T' => array('Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true),
+ 'ga' => array('Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true),
+ 'C' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false),
+ 'cel' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false),
+ 'F' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false),
+ 'fah' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false),
+ 'K' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false),
+ 'kel' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false),
+ 'tsp' => array('Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false),
+ 'tbs' => array('Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false),
+ 'oz' => array('Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false),
+ 'cup' => array('Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false),
+ 'pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false),
+ 'us_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false),
+ 'uk_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false),
+ 'qt' => array('Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false),
+ 'gal' => array('Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false),
+ 'l' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true),
+ 'lt' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true),
+ );
+
+ /**
+ * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
+ *
+ * @var mixed[]
+ */
+ private static $conversionMultipliers = array(
+ 'Y' => array('multiplier' => 1E24, 'name' => 'yotta'),
+ 'Z' => array('multiplier' => 1E21, 'name' => 'zetta'),
+ 'E' => array('multiplier' => 1E18, 'name' => 'exa'),
+ 'P' => array('multiplier' => 1E15, 'name' => 'peta'),
+ 'T' => array('multiplier' => 1E12, 'name' => 'tera'),
+ 'G' => array('multiplier' => 1E9, 'name' => 'giga'),
+ 'M' => array('multiplier' => 1E6, 'name' => 'mega'),
+ 'k' => array('multiplier' => 1E3, 'name' => 'kilo'),
+ 'h' => array('multiplier' => 1E2, 'name' => 'hecto'),
+ 'e' => array('multiplier' => 1E1, 'name' => 'deka'),
+ 'd' => array('multiplier' => 1E-1, 'name' => 'deci'),
+ 'c' => array('multiplier' => 1E-2, 'name' => 'centi'),
+ 'm' => array('multiplier' => 1E-3, 'name' => 'milli'),
+ 'u' => array('multiplier' => 1E-6, 'name' => 'micro'),
+ 'n' => array('multiplier' => 1E-9, 'name' => 'nano'),
+ 'p' => array('multiplier' => 1E-12, 'name' => 'pico'),
+ 'f' => array('multiplier' => 1E-15, 'name' => 'femto'),
+ 'a' => array('multiplier' => 1E-18, 'name' => 'atto'),
+ 'z' => array('multiplier' => 1E-21, 'name' => 'zepto'),
+ 'y' => array('multiplier' => 1E-24, 'name' => 'yocto'),
+ );
+
+ /**
+ * Details of the Units of measure conversion factors, organised by group
+ *
+ * @var mixed[]
+ */
+ private static $unitConversions = array(
+ 'Mass' => array(
+ 'g' => array(
+ 'g' => 1.0,
+ 'sg' => 6.85220500053478E-05,
+ 'lbm' => 2.20462291469134E-03,
+ 'u' => 6.02217000000000E+23,
+ 'ozm' => 3.52739718003627E-02,
+ ),
+ 'sg' => array(
+ 'g' => 1.45938424189287E+04,
+ 'sg' => 1.0,
+ 'lbm' => 3.21739194101647E+01,
+ 'u' => 8.78866000000000E+27,
+ 'ozm' => 5.14782785944229E+02,
+ ),
+ 'lbm' => array(
+ 'g' => 4.5359230974881148E+02,
+ 'sg' => 3.10810749306493E-02,
+ 'lbm' => 1.0,
+ 'u' => 2.73161000000000E+26,
+ 'ozm' => 1.60000023429410E+01,
+ ),
+ 'u' => array(
+ 'g' => 1.66053100460465E-24,
+ 'sg' => 1.13782988532950E-28,
+ 'lbm' => 3.66084470330684E-27,
+ 'u' => 1.0,
+ 'ozm' => 5.85735238300524E-26,
+ ),
+ 'ozm' => array(
+ 'g' => 2.83495152079732E+01,
+ 'sg' => 1.94256689870811E-03,
+ 'lbm' => 6.24999908478882E-02,
+ 'u' => 1.70725600000000E+25,
+ 'ozm' => 1.0,
+ ),
+ ),
+ 'Distance' => array(
+ 'm' => array(
+ 'm' => 1.0,
+ 'mi' => 6.21371192237334E-04,
+ 'Nmi' => 5.39956803455724E-04,
+ 'in' => 3.93700787401575E+01,
+ 'ft' => 3.28083989501312E+00,
+ 'yd' => 1.09361329797891E+00,
+ 'ang' => 1.00000000000000E+10,
+ 'Pica' => 2.83464566929116E+03,
+ ),
+ 'mi' => array(
+ 'm' => 1.60934400000000E+03,
+ 'mi' => 1.0,
+ 'Nmi' => 8.68976241900648E-01,
+ 'in' => 6.33600000000000E+04,
+ 'ft' => 5.28000000000000E+03,
+ 'yd' => 1.76000000000000E+03,
+ 'ang' => 1.60934400000000E+13,
+ 'Pica' => 4.56191999999971E+06,
+ ),
+ 'Nmi' => array(
+ 'm' => 1.85200000000000E+03,
+ 'mi' => 1.15077944802354E+00,
+ 'Nmi' => 1.0,
+ 'in' => 7.29133858267717E+04,
+ 'ft' => 6.07611548556430E+03,
+ 'yd' => 2.02537182785694E+03,
+ 'ang' => 1.85200000000000E+13,
+ 'Pica' => 5.24976377952723E+06,
+ ),
+ 'in' => array(
+ 'm' => 2.54000000000000E-02,
+ 'mi' => 1.57828282828283E-05,
+ 'Nmi' => 1.37149028077754E-05,
+ 'in' => 1.0,
+ 'ft' => 8.33333333333333E-02,
+ 'yd' => 2.77777777686643E-02,
+ 'ang' => 2.54000000000000E+08,
+ 'Pica' => 7.19999999999955E+01,
+ ),
+ 'ft' => array(
+ 'm' => 3.04800000000000E-01,
+ 'mi' => 1.89393939393939E-04,
+ 'Nmi' => 1.64578833693305E-04,
+ 'in' => 1.20000000000000E+01,
+ 'ft' => 1.0,
+ 'yd' => 3.33333333223972E-01,
+ 'ang' => 3.04800000000000E+09,
+ 'Pica' => 8.63999999999946E+02,
+ ),
+ 'yd' => array(
+ 'm' => 9.14400000300000E-01,
+ 'mi' => 5.68181818368230E-04,
+ 'Nmi' => 4.93736501241901E-04,
+ 'in' => 3.60000000118110E+01,
+ 'ft' => 3.00000000000000E+00,
+ 'yd' => 1.0,
+ 'ang' => 9.14400000300000E+09,
+ 'Pica' => 2.59200000085023E+03,
+ ),
+ 'ang' => array(
+ 'm' => 1.00000000000000E-10,
+ 'mi' => 6.21371192237334E-14,
+ 'Nmi' => 5.39956803455724E-14,
+ 'in' => 3.93700787401575E-09,
+ 'ft' => 3.28083989501312E-10,
+ 'yd' => 1.09361329797891E-10,
+ 'ang' => 1.0,
+ 'Pica' => 2.83464566929116E-07,
+ ),
+ 'Pica' => array(
+ 'm' => 3.52777777777800E-04,
+ 'mi' => 2.19205948372629E-07,
+ 'Nmi' => 1.90484761219114E-07,
+ 'in' => 1.38888888888898E-02,
+ 'ft' => 1.15740740740748E-03,
+ 'yd' => 3.85802469009251E-04,
+ 'ang' => 3.52777777777800E+06,
+ 'Pica' => 1.0,
+ ),
+ ),
+ 'Time' => array(
+ 'yr' => array(
+ 'yr' => 1.0,
+ 'day' => 365.25,
+ 'hr' => 8766.0,
+ 'mn' => 525960.0,
+ 'sec' => 31557600.0,
+ ),
+ 'day' => array(
+ 'yr' => 2.73785078713210E-03,
+ 'day' => 1.0,
+ 'hr' => 24.0,
+ 'mn' => 1440.0,
+ 'sec' => 86400.0,
+ ),
+ 'hr' => array(
+ 'yr' => 1.14077116130504E-04,
+ 'day' => 4.16666666666667E-02,
+ 'hr' => 1.0,
+ 'mn' => 60.0,
+ 'sec' => 3600.0,
+ ),
+ 'mn' => array(
+ 'yr' => 1.90128526884174E-06,
+ 'day' => 6.94444444444444E-04,
+ 'hr' => 1.66666666666667E-02,
+ 'mn' => 1.0,
+ 'sec' => 60.0,
+ ),
+ 'sec' => array(
+ 'yr' => 3.16880878140289E-08,
+ 'day' => 1.15740740740741E-05,
+ 'hr' => 2.77777777777778E-04,
+ 'mn' => 1.66666666666667E-02,
+ 'sec' => 1.0,
+ ),
+ ),
+ 'Pressure' => array(
+ 'Pa' => array(
+ 'Pa' => 1.0,
+ 'p' => 1.0,
+ 'atm' => 9.86923299998193E-06,
+ 'at' => 9.86923299998193E-06,
+ 'mmHg' => 7.50061707998627E-03,
+ ),
+ 'p' => array(
+ 'Pa' => 1.0,
+ 'p' => 1.0,
+ 'atm' => 9.86923299998193E-06,
+ 'at' => 9.86923299998193E-06,
+ 'mmHg' => 7.50061707998627E-03,
+ ),
+ 'atm' => array(
+ 'Pa' => 1.01324996583000E+05,
+ 'p' => 1.01324996583000E+05,
+ 'atm' => 1.0,
+ 'at' => 1.0,
+ 'mmHg' => 760.0,
+ ),
+ 'at' => array(
+ 'Pa' => 1.01324996583000E+05,
+ 'p' => 1.01324996583000E+05,
+ 'atm' => 1.0,
+ 'at' => 1.0,
+ 'mmHg' => 760.0,
+ ),
+ 'mmHg' => array(
+ 'Pa' => 1.33322363925000E+02,
+ 'p' => 1.33322363925000E+02,
+ 'atm' => 1.31578947368421E-03,
+ 'at' => 1.31578947368421E-03,
+ 'mmHg' => 1.0,
+ ),
+ ),
+ 'Force' => array(
+ 'N' => array(
+ 'N' => 1.0,
+ 'dyn' => 1.0E+5,
+ 'dy' => 1.0E+5,
+ 'lbf' => 2.24808923655339E-01,
+ ),
+ 'dyn' => array(
+ 'N' => 1.0E-5,
+ 'dyn' => 1.0,
+ 'dy' => 1.0,
+ 'lbf' => 2.24808923655339E-06,
+ ),
+ 'dy' => array(
+ 'N' => 1.0E-5,
+ 'dyn' => 1.0,
+ 'dy' => 1.0,
+ 'lbf' => 2.24808923655339E-06,
+ ),
+ 'lbf' => array(
+ 'N' => 4.448222,
+ 'dyn' => 4.448222E+5,
+ 'dy' => 4.448222E+5,
+ 'lbf' => 1.0,
+ ),
+ ),
+ 'Energy' => array(
+ 'J' => array(
+ 'J' => 1.0,
+ 'e' => 9.99999519343231E+06,
+ 'c' => 2.39006249473467E-01,
+ 'cal' => 2.38846190642017E-01,
+ 'eV' => 6.24145700000000E+18,
+ 'ev' => 6.24145700000000E+18,
+ 'HPh' => 3.72506430801000E-07,
+ 'hh' => 3.72506430801000E-07,
+ 'Wh' => 2.77777916238711E-04,
+ 'wh' => 2.77777916238711E-04,
+ 'flb' => 2.37304222192651E+01,
+ 'BTU' => 9.47815067349015E-04,
+ 'btu' => 9.47815067349015E-04,
+ ),
+ 'e' => array(
+ 'J' => 1.00000048065700E-07,
+ 'e' => 1.0,
+ 'c' => 2.39006364353494E-08,
+ 'cal' => 2.38846305445111E-08,
+ 'eV' => 6.24146000000000E+11,
+ 'ev' => 6.24146000000000E+11,
+ 'HPh' => 3.72506609848824E-14,
+ 'hh' => 3.72506609848824E-14,
+ 'Wh' => 2.77778049754611E-11,
+ 'wh' => 2.77778049754611E-11,
+ 'flb' => 2.37304336254586E-06,
+ 'BTU' => 9.47815522922962E-11,
+ 'btu' => 9.47815522922962E-11,
+ ),
+ 'c' => array(
+ 'J' => 4.18399101363672E+00,
+ 'e' => 4.18398900257312E+07,
+ 'c' => 1.0,
+ 'cal' => 9.99330315287563E-01,
+ 'eV' => 2.61142000000000E+19,
+ 'ev' => 2.61142000000000E+19,
+ 'HPh' => 1.55856355899327E-06,
+ 'hh' => 1.55856355899327E-06,
+ 'Wh' => 1.16222030532950E-03,
+ 'wh' => 1.16222030532950E-03,
+ 'flb' => 9.92878733152102E+01,
+ 'BTU' => 3.96564972437776E-03,
+ 'btu' => 3.96564972437776E-03,
+ ),
+ 'cal' => array(
+ 'J' => 4.18679484613929E+00,
+ 'e' => 4.18679283372801E+07,
+ 'c' => 1.00067013349059E+00,
+ 'cal' => 1.0,
+ 'eV' => 2.61317000000000E+19,
+ 'ev' => 2.61317000000000E+19,
+ 'HPh' => 1.55960800463137E-06,
+ 'hh' => 1.55960800463137E-06,
+ 'Wh' => 1.16299914807955E-03,
+ 'wh' => 1.16299914807955E-03,
+ 'flb' => 9.93544094443283E+01,
+ 'BTU' => 3.96830723907002E-03,
+ 'btu' => 3.96830723907002E-03,
+ ),
+ 'eV' => array(
+ 'J' => 1.60219000146921E-19,
+ 'e' => 1.60218923136574E-12,
+ 'c' => 3.82933423195043E-20,
+ 'cal' => 3.82676978535648E-20,
+ 'eV' => 1.0,
+ 'ev' => 1.0,
+ 'HPh' => 5.96826078912344E-26,
+ 'hh' => 5.96826078912344E-26,
+ 'Wh' => 4.45053000026614E-23,
+ 'wh' => 4.45053000026614E-23,
+ 'flb' => 3.80206452103492E-18,
+ 'BTU' => 1.51857982414846E-22,
+ 'btu' => 1.51857982414846E-22,
+ ),
+ 'ev' => array(
+ 'J' => 1.60219000146921E-19,
+ 'e' => 1.60218923136574E-12,
+ 'c' => 3.82933423195043E-20,
+ 'cal' => 3.82676978535648E-20,
+ 'eV' => 1.0,
+ 'ev' => 1.0,
+ 'HPh' => 5.96826078912344E-26,
+ 'hh' => 5.96826078912344E-26,
+ 'Wh' => 4.45053000026614E-23,
+ 'wh' => 4.45053000026614E-23,
+ 'flb' => 3.80206452103492E-18,
+ 'BTU' => 1.51857982414846E-22,
+ 'btu' => 1.51857982414846E-22,
+ ),
+ 'HPh' => array(
+ 'J' => 2.68451741316170E+06,
+ 'e' => 2.68451612283024E+13,
+ 'c' => 6.41616438565991E+05,
+ 'cal' => 6.41186757845835E+05,
+ 'eV' => 1.67553000000000E+25,
+ 'ev' => 1.67553000000000E+25,
+ 'HPh' => 1.0,
+ 'hh' => 1.0,
+ 'Wh' => 7.45699653134593E+02,
+ 'wh' => 7.45699653134593E+02,
+ 'flb' => 6.37047316692964E+07,
+ 'BTU' => 2.54442605275546E+03,
+ 'btu' => 2.54442605275546E+03,
+ ),
+ 'hh' => array(
+ 'J' => 2.68451741316170E+06,
+ 'e' => 2.68451612283024E+13,
+ 'c' => 6.41616438565991E+05,
+ 'cal' => 6.41186757845835E+05,
+ 'eV' => 1.67553000000000E+25,
+ 'ev' => 1.67553000000000E+25,
+ 'HPh' => 1.0,
+ 'hh' => 1.0,
+ 'Wh' => 7.45699653134593E+02,
+ 'wh' => 7.45699653134593E+02,
+ 'flb' => 6.37047316692964E+07,
+ 'BTU' => 2.54442605275546E+03,
+ 'btu' => 2.54442605275546E+03,
+ ),
+ 'Wh' => array(
+ 'J' => 3.59999820554720E+03,
+ 'e' => 3.59999647518369E+10,
+ 'c' => 8.60422069219046E+02,
+ 'cal' => 8.59845857713046E+02,
+ 'eV' => 2.24692340000000E+22,
+ 'ev' => 2.24692340000000E+22,
+ 'HPh' => 1.34102248243839E-03,
+ 'hh' => 1.34102248243839E-03,
+ 'Wh' => 1.0,
+ 'wh' => 1.0,
+ 'flb' => 8.54294774062316E+04,
+ 'BTU' => 3.41213254164705E+00,
+ 'btu' => 3.41213254164705E+00,
+ ),
+ 'wh' => array(
+ 'J' => 3.59999820554720E+03,
+ 'e' => 3.59999647518369E+10,
+ 'c' => 8.60422069219046E+02,
+ 'cal' => 8.59845857713046E+02,
+ 'eV' => 2.24692340000000E+22,
+ 'ev' => 2.24692340000000E+22,
+ 'HPh' => 1.34102248243839E-03,
+ 'hh' => 1.34102248243839E-03,
+ 'Wh' => 1.0,
+ 'wh' => 1.0,
+ 'flb' => 8.54294774062316E+04,
+ 'BTU' => 3.41213254164705E+00,
+ 'btu' => 3.41213254164705E+00,
+ ),
+ 'flb' => array(
+ 'J' => 4.21400003236424E-02,
+ 'e' => 4.21399800687660E+05,
+ 'c' => 1.00717234301644E-02,
+ 'cal' => 1.00649785509554E-02,
+ 'eV' => 2.63015000000000E+17,
+ 'ev' => 2.63015000000000E+17,
+ 'HPh' => 1.56974211145130E-08,
+ 'hh' => 1.56974211145130E-08,
+ 'Wh' => 1.17055614802000E-05,
+ 'wh' => 1.17055614802000E-05,
+ 'flb' => 1.0,
+ 'BTU' => 3.99409272448406E-05,
+ 'btu' => 3.99409272448406E-05,
+ ),
+ 'BTU' => array(
+ 'J' => 1.05505813786749E+03,
+ 'e' => 1.05505763074665E+10,
+ 'c' => 2.52165488508168E+02,
+ 'cal' => 2.51996617135510E+02,
+ 'eV' => 6.58510000000000E+21,
+ 'ev' => 6.58510000000000E+21,
+ 'HPh' => 3.93015941224568E-04,
+ 'hh' => 3.93015941224568E-04,
+ 'Wh' => 2.93071851047526E-01,
+ 'wh' => 2.93071851047526E-01,
+ 'flb' => 2.50369750774671E+04,
+ 'BTU' => 1.0,
+ 'btu' => 1.0,
+ ),
+ 'btu' => array(
+ 'J' => 1.05505813786749E+03,
+ 'e' => 1.05505763074665E+10,
+ 'c' => 2.52165488508168E+02,
+ 'cal' => 2.51996617135510E+02,
+ 'eV' => 6.58510000000000E+21,
+ 'ev' => 6.58510000000000E+21,
+ 'HPh' => 3.93015941224568E-04,
+ 'hh' => 3.93015941224568E-04,
+ 'Wh' => 2.93071851047526E-01,
+ 'wh' => 2.93071851047526E-01,
+ 'flb' => 2.50369750774671E+04,
+ 'BTU' => 1.0,
+ 'btu' => 1.0,
+ ),
+ ),
+ 'Power' => array(
+ 'HP' => array(
+ 'HP' => 1.0,
+ 'h' => 1.0,
+ 'W' => 7.45701000000000E+02,
+ 'w' => 7.45701000000000E+02,
+ ),
+ 'h' => array(
+ 'HP' => 1.0,
+ 'h' => 1.0,
+ 'W' => 7.45701000000000E+02,
+ 'w' => 7.45701000000000E+02,
+ ),
+ 'W' => array(
+ 'HP' => 1.34102006031908E-03,
+ 'h' => 1.34102006031908E-03,
+ 'W' => 1.0,
+ 'w' => 1.0,
+ ),
+ 'w' => array(
+ 'HP' => 1.34102006031908E-03,
+ 'h' => 1.34102006031908E-03,
+ 'W' => 1.0,
+ 'w' => 1.0,
+ ),
+ ),
+ 'Magnetism' => array(
+ 'T' => array(
+ 'T' => 1.0,
+ 'ga' => 10000.0,
+ ),
+ 'ga' => array(
+ 'T' => 0.0001,
+ 'ga' => 1.0,
+ ),
+ ),
+ 'Liquid' => array(
+ 'tsp' => array(
+ 'tsp' => 1.0,
+ 'tbs' => 3.33333333333333E-01,
+ 'oz' => 1.66666666666667E-01,
+ 'cup' => 2.08333333333333E-02,
+ 'pt' => 1.04166666666667E-02,
+ 'us_pt' => 1.04166666666667E-02,
+ 'uk_pt' => 8.67558516821960E-03,
+ 'qt' => 5.20833333333333E-03,
+ 'gal' => 1.30208333333333E-03,
+ 'l' => 4.92999408400710E-03,
+ 'lt' => 4.92999408400710E-03,
+ ),
+ 'tbs' => array(
+ 'tsp' => 3.00000000000000E+00,
+ 'tbs' => 1.0,
+ 'oz' => 5.00000000000000E-01,
+ 'cup' => 6.25000000000000E-02,
+ 'pt' => 3.12500000000000E-02,
+ 'us_pt' => 3.12500000000000E-02,
+ 'uk_pt' => 2.60267555046588E-02,
+ 'qt' => 1.56250000000000E-02,
+ 'gal' => 3.90625000000000E-03,
+ 'l' => 1.47899822520213E-02,
+ 'lt' => 1.47899822520213E-02,
+ ),
+ 'oz' => array(
+ 'tsp' => 6.00000000000000E+00,
+ 'tbs' => 2.00000000000000E+00,
+ 'oz' => 1.0,
+ 'cup' => 1.25000000000000E-01,
+ 'pt' => 6.25000000000000E-02,
+ 'us_pt' => 6.25000000000000E-02,
+ 'uk_pt' => 5.20535110093176E-02,
+ 'qt' => 3.12500000000000E-02,
+ 'gal' => 7.81250000000000E-03,
+ 'l' => 2.95799645040426E-02,
+ 'lt' => 2.95799645040426E-02,
+ ),
+ 'cup' => array(
+ 'tsp' => 4.80000000000000E+01,
+ 'tbs' => 1.60000000000000E+01,
+ 'oz' => 8.00000000000000E+00,
+ 'cup' => 1.0,
+ 'pt' => 5.00000000000000E-01,
+ 'us_pt' => 5.00000000000000E-01,
+ 'uk_pt' => 4.16428088074541E-01,
+ 'qt' => 2.50000000000000E-01,
+ 'gal' => 6.25000000000000E-02,
+ 'l' => 2.36639716032341E-01,
+ 'lt' => 2.36639716032341E-01,
+ ),
+ 'pt' => array(
+ 'tsp' => 9.60000000000000E+01,
+ 'tbs' => 3.20000000000000E+01,
+ 'oz' => 1.60000000000000E+01,
+ 'cup' => 2.00000000000000E+00,
+ 'pt' => 1.0,
+ 'us_pt' => 1.0,
+ 'uk_pt' => 8.32856176149081E-01,
+ 'qt' => 5.00000000000000E-01,
+ 'gal' => 1.25000000000000E-01,
+ 'l' => 4.73279432064682E-01,
+ 'lt' => 4.73279432064682E-01,
+ ),
+ 'us_pt' => array(
+ 'tsp' => 9.60000000000000E+01,
+ 'tbs' => 3.20000000000000E+01,
+ 'oz' => 1.60000000000000E+01,
+ 'cup' => 2.00000000000000E+00,
+ 'pt' => 1.0,
+ 'us_pt' => 1.0,
+ 'uk_pt' => 8.32856176149081E-01,
+ 'qt' => 5.00000000000000E-01,
+ 'gal' => 1.25000000000000E-01,
+ 'l' => 4.73279432064682E-01,
+ 'lt' => 4.73279432064682E-01,
+ ),
+ 'uk_pt' => array(
+ 'tsp' => 1.15266000000000E+02,
+ 'tbs' => 3.84220000000000E+01,
+ 'oz' => 1.92110000000000E+01,
+ 'cup' => 2.40137500000000E+00,
+ 'pt' => 1.20068750000000E+00,
+ 'us_pt' => 1.20068750000000E+00,
+ 'uk_pt' => 1.0,
+ 'qt' => 6.00343750000000E-01,
+ 'gal' => 1.50085937500000E-01,
+ 'l' => 5.68260698087162E-01,
+ 'lt' => 5.68260698087162E-01,
+ ),
+ 'qt' => array(
+ 'tsp' => 1.92000000000000E+02,
+ 'tbs' => 6.40000000000000E+01,
+ 'oz' => 3.20000000000000E+01,
+ 'cup' => 4.00000000000000E+00,
+ 'pt' => 2.00000000000000E+00,
+ 'us_pt' => 2.00000000000000E+00,
+ 'uk_pt' => 1.66571235229816E+00,
+ 'qt' => 1.0,
+ 'gal' => 2.50000000000000E-01,
+ 'l' => 9.46558864129363E-01,
+ 'lt' => 9.46558864129363E-01,
+ ),
+ 'gal' => array(
+ 'tsp' => 7.68000000000000E+02,
+ 'tbs' => 2.56000000000000E+02,
+ 'oz' => 1.28000000000000E+02,
+ 'cup' => 1.60000000000000E+01,
+ 'pt' => 8.00000000000000E+00,
+ 'us_pt' => 8.00000000000000E+00,
+ 'uk_pt' => 6.66284940919265E+00,
+ 'qt' => 4.00000000000000E+00,
+ 'gal' => 1.0,
+ 'l' => 3.78623545651745E+00,
+ 'lt' => 3.78623545651745E+00,
+ ),
+ 'l' => array(
+ 'tsp' => 2.02840000000000E+02,
+ 'tbs' => 6.76133333333333E+01,
+ 'oz' => 3.38066666666667E+01,
+ 'cup' => 4.22583333333333E+00,
+ 'pt' => 2.11291666666667E+00,
+ 'us_pt' => 2.11291666666667E+00,
+ 'uk_pt' => 1.75975569552166E+00,
+ 'qt' => 1.05645833333333E+00,
+ 'gal' => 2.64114583333333E-01,
+ 'l' => 1.0,
+ 'lt' => 1.0,
+ ),
+ 'lt' => array(
+ 'tsp' => 2.02840000000000E+02,
+ 'tbs' => 6.76133333333333E+01,
+ 'oz' => 3.38066666666667E+01,
+ 'cup' => 4.22583333333333E+00,
+ 'pt' => 2.11291666666667E+00,
+ 'us_pt' => 2.11291666666667E+00,
+ 'uk_pt' => 1.75975569552166E+00,
+ 'qt' => 1.05645833333333E+00,
+ 'gal' => 2.64114583333333E-01,
+ 'l' => 1.0,
+ 'lt' => 1.0,
+ ),
+ ),
+ );
+
+
+ /**
+ * parseComplex
+ *
+ * Parses a complex number into its real and imaginary parts, and an I or J suffix
+ *
+ * @param string $complexNumber The complex number
+ * @return string[] Indexed on "real", "imaginary" and "suffix"
+ */
+ public static function parseComplex($complexNumber)
+ {
+ $workString = (string) $complexNumber;
+
+ $realNumber = $imaginary = 0;
+ // Extract the suffix, if there is one
+ $suffix = substr($workString, -1);
+ if (!is_numeric($suffix)) {
+ $workString = substr($workString, 0, -1);
+ } else {
+ $suffix = '';
+ }
+
+ // Split the input into its Real and Imaginary components
+ $leadingSign = 0;
+ if (strlen($workString) > 0) {
+ $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
+ }
+ $power = '';
+ $realNumber = strtok($workString, '+-');
+ if (strtoupper(substr($realNumber, -1)) == 'E') {
+ $power = strtok('+-');
+ ++$leadingSign;
+ }
+
+ $realNumber = substr($workString, 0, strlen($realNumber)+strlen($power)+$leadingSign);
+
+ if ($suffix != '') {
+ $imaginary = substr($workString, strlen($realNumber));
+
+ if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
+ $imaginary = $realNumber.'1';
+ $realNumber = '0';
+ } elseif ($imaginary == '') {
+ $imaginary = $realNumber;
+ $realNumber = '0';
+ } elseif (($imaginary == '+') || ($imaginary == '-')) {
+ $imaginary .= '1';
+ }
+ }
+
+ return array(
+ 'real' => $realNumber,
+ 'imaginary' => $imaginary,
+ 'suffix' => $suffix
+ );
+ }
+
+
+ /**
+ * Cleans the leading characters in a complex number string
+ *
+ * @param string $complexNumber The complex number to clean
+ * @return string The "cleaned" complex number
+ */
+ private static function cleanComplex($complexNumber)
+ {
+ if ($complexNumber{0} == '+') {
+ $complexNumber = substr($complexNumber, 1);
+ }
+ if ($complexNumber{0} == '0') {
+ $complexNumber = substr($complexNumber, 1);
+ }
+ if ($complexNumber{0} == '.') {
+ $complexNumber = '0'.$complexNumber;
+ }
+ if ($complexNumber{0} == '+') {
+ $complexNumber = substr($complexNumber, 1);
+ }
+ return $complexNumber;
+ }
+
+ /**
+ * Formats a number base string value with leading zeroes
+ *
+ * @param string $xVal The "number" to pad
+ * @param integer $places The length that we want to pad this value
+ * @return string The padded "number"
+ */
+ private static function nbrConversionFormat($xVal, $places)
+ {
+ if (!is_null($places)) {
+ if (strlen($xVal) <= $places) {
+ return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10);
+ } else {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ }
+
+ return substr($xVal, -10);
+ }
+
+ /**
+ * BESSELI
+ *
+ * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated
+ * for purely imaginary arguments
+ *
+ * Excel Function:
+ * BESSELI(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELI returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function.
+ * If ord is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELI returns the #VALUE! error value.
+ * If $ord < 0, BESSELI returns the #NUM! error value.
+ * @return float
+ *
+ */
+ public static function BESSELI($x, $ord)
+ {
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ $ord = floor($ord);
+ if ($ord < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ if (abs($x) <= 30) {
+ $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
+ $ordK = 1;
+ $fSqrX = ($x * $x) / 4;
+ do {
+ $fTerm *= $fSqrX;
+ $fTerm /= ($ordK * ($ordK + $ord));
+ $fResult += $fTerm;
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
+ } else {
+ $f_2_PI = 2 * M_PI;
+
+ $fXAbs = abs($x);
+ $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
+ if (($ord & 1) && ($x < 0)) {
+ $fResult = -$fResult;
+ }
+ }
+ return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * BESSELJ
+ *
+ * Returns the Bessel function
+ *
+ * Excel Function:
+ * BESSELJ(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELJ returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value.
+ * If $ord < 0, BESSELJ returns the #NUM! error value.
+ * @return float
+ *
+ */
+ public static function BESSELJ($x, $ord)
+ {
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ $ord = floor($ord);
+ if ($ord < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $fResult = 0;
+ if (abs($x) <= 30) {
+ $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
+ $ordK = 1;
+ $fSqrX = ($x * $x) / -4;
+ do {
+ $fTerm *= $fSqrX;
+ $fTerm /= ($ordK * ($ordK + $ord));
+ $fResult += $fTerm;
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
+ } else {
+ $f_PI_DIV_2 = M_PI / 2;
+ $f_PI_DIV_4 = M_PI / 4;
+
+ $fXAbs = abs($x);
+ $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
+ if (($ord & 1) && ($x < 0)) {
+ $fResult = -$fResult;
+ }
+ }
+ return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ private static function besselK0($fNum)
+ {
+ if ($fNum <= 2) {
+ $fNum2 = $fNum * 0.5;
+ $y = ($fNum2 * $fNum2);
+ $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
+ (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
+ (0.10750e-3 + $y * 0.74e-5))))));
+ } else {
+ $y = 2 / $fNum;
+ $fRet = exp(-$fNum) / sqrt($fNum) *
+ (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
+ (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
+ }
+ return $fRet;
+ }
+
+
+ private static function besselK1($fNum)
+ {
+ if ($fNum <= 2) {
+ $fNum2 = $fNum * 0.5;
+ $y = ($fNum2 * $fNum2);
+ $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
+ (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
+ (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
+ } else {
+ $y = 2 / $fNum;
+ $fRet = exp(-$fNum) / sqrt($fNum) *
+ (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
+ (0.325614e-2 + $y * (-0.68245e-3)))))));
+ }
+ return $fRet;
+ }
+
+
+ /**
+ * BESSELK
+ *
+ * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated
+ * for purely imaginary arguments.
+ *
+ * Excel Function:
+ * BESSELK(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
+ * If $ord < 0, BESSELK returns the #NUM! error value.
+ * @return float
+ *
+ */
+ public static function BESSELK($x, $ord)
+ {
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ if (($ord < 0) || ($x == 0.0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ switch (floor($ord)) {
+ case 0:
+ return self::besselK0($x);
+ case 1:
+ return self::besselK1($x);
+ default:
+ $fTox = 2 / $x;
+ $fBkm = self::besselK0($x);
+ $fBk = self::besselK1($x);
+ for ($n = 1; $n < $ord; ++$n) {
+ $fBkp = $fBkm + $n * $fTox * $fBk;
+ $fBkm = $fBk;
+ $fBk = $fBkp;
+ }
+ }
+ return (is_nan($fBk)) ? PHPExcel_Calculation_Functions::NaN() : $fBk;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ private static function besselY0($fNum)
+ {
+ if ($fNum < 8.0) {
+ $y = ($fNum * $fNum);
+ $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
+ $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
+ $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
+ } else {
+ $z = 8.0 / $fNum;
+ $y = ($z * $z);
+ $xx = $fNum - 0.785398164;
+ $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
+ $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
+ $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
+ }
+ return $fRet;
+ }
+
+
+ private static function besselY1($fNum)
+ {
+ if ($fNum < 8.0) {
+ $y = ($fNum * $fNum);
+ $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
+ (-0.4237922726e7 + $y * 0.8511937935e4)))));
+ $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
+ (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
+ $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
+ } else {
+ $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
+ }
+ return $fRet;
+ }
+
+
+ /**
+ * BESSELY
+ *
+ * Returns the Bessel function, which is also called the Weber function or the Neumann function.
+ *
+ * Excel Function:
+ * BESSELY(x,ord)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $x The value at which to evaluate the function.
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
+ * If $ord < 0, BESSELK returns the #NUM! error value.
+ *
+ * @return float
+ */
+ public static function BESSELY($x, $ord)
+ {
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
+
+ if ((is_numeric($x)) && (is_numeric($ord))) {
+ if (($ord < 0) || ($x == 0.0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ switch (floor($ord)) {
+ case 0:
+ return self::besselY0($x);
+ case 1:
+ return self::besselY1($x);
+ default:
+ $fTox = 2 / $x;
+ $fBym = self::besselY0($x);
+ $fBy = self::besselY1($x);
+ for ($n = 1; $n < $ord; ++$n) {
+ $fByp = $n * $fTox * $fBy - $fBym;
+ $fBym = $fBy;
+ $fBy = $fByp;
+ }
+ }
+ return (is_nan($fBy)) ? PHPExcel_Calculation_Functions::NaN() : $fBy;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * BINTODEC
+ *
+ * Return a binary value as decimal.
+ *
+ * Excel Function:
+ * BIN2DEC(x)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The binary number (as a string) that you want to convert. The number
+ * cannot contain more than 10 characters (10 bits). The most significant
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
+ * Negative numbers are represented using two's-complement notation.
+ * If number is not a valid binary number, or if number contains more than
+ * 10 characters (10 bits), BIN2DEC returns the #NUM! error value.
+ * @return string
+ */
+ public static function BINTODEC($x)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+
+ if (is_bool($x)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $x = floor($x);
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if (strlen($x) > 10) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif (strlen($x) == 10) {
+ // Two's Complement
+ $x = substr($x, -9);
+ return '-'.(512-bindec($x));
+ }
+ return bindec($x);
+ }
+
+
+ /**
+ * BINTOHEX
+ *
+ * Return a binary value as hex.
+ *
+ * Excel Function:
+ * BIN2HEX(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The binary number (as a string) that you want to convert. The number
+ * cannot contain more than 10 characters (10 bits). The most significant
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
+ * Negative numbers are represented using two's-complement notation.
+ * If number is not a valid binary number, or if number contains more than
+ * 10 characters (10 bits), BIN2HEX returns the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the
+ * minimum number of characters necessary. Places is useful for padding the
+ * return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, BIN2HEX returns the #VALUE! error value.
+ * If places is negative, BIN2HEX returns the #NUM! error value.
+ * @return string
+ */
+ public static function BINTOHEX($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $x = floor($x);
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if (strlen($x) > 10) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif (strlen($x) == 10) {
+ // Two's Complement
+ return str_repeat('F', 8).substr(strtoupper(dechex(bindec(substr($x, -9)))), -2);
+ }
+ $hexVal = (string) strtoupper(dechex(bindec($x)));
+
+ return self::nbrConversionFormat($hexVal, $places);
+ }
+
+
+ /**
+ * BINTOOCT
+ *
+ * Return a binary value as octal.
+ *
+ * Excel Function:
+ * BIN2OCT(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The binary number (as a string) that you want to convert. The number
+ * cannot contain more than 10 characters (10 bits). The most significant
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
+ * Negative numbers are represented using two's-complement notation.
+ * If number is not a valid binary number, or if number contains more than
+ * 10 characters (10 bits), BIN2OCT returns the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the
+ * minimum number of characters necessary. Places is useful for padding the
+ * return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, BIN2OCT returns the #VALUE! error value.
+ * If places is negative, BIN2OCT returns the #NUM! error value.
+ * @return string
+ */
+ public static function BINTOOCT($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $x = floor($x);
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if (strlen($x) > 10) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif (strlen($x) == 10) {
+ // Two's Complement
+ return str_repeat('7', 7).substr(strtoupper(decoct(bindec(substr($x, -9)))), -3);
+ }
+ $octVal = (string) decoct(bindec($x));
+
+ return self::nbrConversionFormat($octVal, $places);
+ }
+
+
+ /**
+ * DECTOBIN
+ *
+ * Return a decimal value as binary.
+ *
+ * Excel Function:
+ * DEC2BIN(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The decimal integer you want to convert. If number is negative,
+ * valid place values are ignored and DEC2BIN returns a 10-character
+ * (10-bit) binary number in which the most significant bit is the sign
+ * bit. The remaining 9 bits are magnitude bits. Negative numbers are
+ * represented using two's-complement notation.
+ * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error
+ * value.
+ * If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
+ * If DEC2BIN requires more than places characters, it returns the #NUM!
+ * error value.
+ * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses
+ * the minimum number of characters necessary. Places is useful for
+ * padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, DEC2BIN returns the #VALUE! error value.
+ * If places is zero or negative, DEC2BIN returns the #NUM! error value.
+ * @return string
+ */
+ public static function DECTOBIN($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) floor($x);
+ $r = decbin($x);
+ if (strlen($r) == 32) {
+ // Two's Complement
+ $r = substr($r, -10);
+ } elseif (strlen($r) > 11) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ return self::nbrConversionFormat($r, $places);
+ }
+
+
+ /**
+ * DECTOHEX
+ *
+ * Return a decimal value as hex.
+ *
+ * Excel Function:
+ * DEC2HEX(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The decimal integer you want to convert. If number is negative,
+ * places is ignored and DEC2HEX returns a 10-character (40-bit)
+ * hexadecimal number in which the most significant bit is the sign
+ * bit. The remaining 39 bits are magnitude bits. Negative numbers
+ * are represented using two's-complement notation.
+ * If number < -549,755,813,888 or if number > 549,755,813,887,
+ * DEC2HEX returns the #NUM! error value.
+ * If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
+ * If DEC2HEX requires more than places characters, it returns the
+ * #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses
+ * the minimum number of characters necessary. Places is useful for
+ * padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, DEC2HEX returns the #VALUE! error value.
+ * If places is zero or negative, DEC2HEX returns the #NUM! error value.
+ * @return string
+ */
+ public static function DECTOHEX($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) floor($x);
+ $r = strtoupper(dechex($x));
+ if (strlen($r) == 8) {
+ // Two's Complement
+ $r = 'FF'.$r;
+ }
+
+ return self::nbrConversionFormat($r, $places);
+ }
+
+
+ /**
+ * DECTOOCT
+ *
+ * Return an decimal value as octal.
+ *
+ * Excel Function:
+ * DEC2OCT(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The decimal integer you want to convert. If number is negative,
+ * places is ignored and DEC2OCT returns a 10-character (30-bit)
+ * octal number in which the most significant bit is the sign bit.
+ * The remaining 29 bits are magnitude bits. Negative numbers are
+ * represented using two's-complement notation.
+ * If number < -536,870,912 or if number > 536,870,911, DEC2OCT
+ * returns the #NUM! error value.
+ * If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
+ * If DEC2OCT requires more than places characters, it returns the
+ * #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses
+ * the minimum number of characters necessary. Places is useful for
+ * padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, DEC2OCT returns the #VALUE! error value.
+ * If places is zero or negative, DEC2OCT returns the #NUM! error value.
+ * @return string
+ */
+ public static function DECTOOCT($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ $x = (int) $x;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) floor($x);
+ $r = decoct($x);
+ if (strlen($r) == 11) {
+ // Two's Complement
+ $r = substr($r, -10);
+ }
+
+ return self::nbrConversionFormat($r, $places);
+ }
+
+
+ /**
+ * HEXTOBIN
+ *
+ * Return a hex value as binary.
+ *
+ * Excel Function:
+ * HEX2BIN(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x the hexadecimal number you want to convert. Number cannot
+ * contain more than 10 characters. The most significant bit of
+ * number is the sign bit (40th bit from the right). The remaining
+ * 9 bits are magnitude bits. Negative numbers are represented
+ * using two's-complement notation.
+ * If number is negative, HEX2BIN ignores places and returns a
+ * 10-character binary number.
+ * If number is negative, it cannot be less than FFFFFFFE00, and
+ * if number is positive, it cannot be greater than 1FF.
+ * If number is not a valid hexadecimal number, HEX2BIN returns
+ * the #NUM! error value.
+ * If HEX2BIN requires more than places characters, it returns
+ * the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted,
+ * HEX2BIN uses the minimum number of characters necessary. Places
+ * is useful for padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, HEX2BIN returns the #VALUE! error value.
+ * If places is negative, HEX2BIN returns the #NUM! error value.
+ * @return string
+ */
+ public static function HEXTOBIN($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $binVal = decbin(hexdec($x));
+
+ return substr(self::nbrConversionFormat($binVal, $places), -10);
+ }
+
+
+ /**
+ * HEXTODEC
+ *
+ * Return a hex value as decimal.
+ *
+ * Excel Function:
+ * HEX2DEC(x)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The hexadecimal number you want to convert. This number cannot
+ * contain more than 10 characters (40 bits). The most significant
+ * bit of number is the sign bit. The remaining 39 bits are magnitude
+ * bits. Negative numbers are represented using two's-complement
+ * notation.
+ * If number is not a valid hexadecimal number, HEX2DEC returns the
+ * #NUM! error value.
+ * @return string
+ */
+ public static function HEXTODEC($x)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+
+ if (is_bool($x)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return hexdec($x);
+ }
+
+
+ /**
+ * HEXTOOCT
+ *
+ * Return a hex value as octal.
+ *
+ * Excel Function:
+ * HEX2OCT(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The hexadecimal number you want to convert. Number cannot
+ * contain more than 10 characters. The most significant bit of
+ * number is the sign bit. The remaining 39 bits are magnitude
+ * bits. Negative numbers are represented using two's-complement
+ * notation.
+ * If number is negative, HEX2OCT ignores places and returns a
+ * 10-character octal number.
+ * If number is negative, it cannot be less than FFE0000000, and
+ * if number is positive, it cannot be greater than 1FFFFFFF.
+ * If number is not a valid hexadecimal number, HEX2OCT returns
+ * the #NUM! error value.
+ * If HEX2OCT requires more than places characters, it returns
+ * the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, HEX2OCT
+ * uses the minimum number of characters necessary. Places is
+ * useful for padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, HEX2OCT returns the #VALUE! error
+ * value.
+ * If places is negative, HEX2OCT returns the #NUM! error value.
+ * @return string
+ */
+ public static function HEXTOOCT($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $octVal = decoct(hexdec($x));
+
+ return self::nbrConversionFormat($octVal, $places);
+ } // function HEXTOOCT()
+
+
+ /**
+ * OCTTOBIN
+ *
+ * Return an octal value as binary.
+ *
+ * Excel Function:
+ * OCT2BIN(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The octal number you want to convert. Number may not
+ * contain more than 10 characters. The most significant
+ * bit of number is the sign bit. The remaining 29 bits
+ * are magnitude bits. Negative numbers are represented
+ * using two's-complement notation.
+ * If number is negative, OCT2BIN ignores places and returns
+ * a 10-character binary number.
+ * If number is negative, it cannot be less than 7777777000,
+ * and if number is positive, it cannot be greater than 777.
+ * If number is not a valid octal number, OCT2BIN returns
+ * the #NUM! error value.
+ * If OCT2BIN requires more than places characters, it
+ * returns the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted,
+ * OCT2BIN uses the minimum number of characters necessary.
+ * Places is useful for padding the return value with
+ * leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, OCT2BIN returns the #VALUE!
+ * error value.
+ * If places is negative, OCT2BIN returns the #NUM! error
+ * value.
+ * @return string
+ */
+ public static function OCTTOBIN($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $r = decbin(octdec($x));
+
+ return self::nbrConversionFormat($r, $places);
+ }
+
+
+ /**
+ * OCTTODEC
+ *
+ * Return an octal value as decimal.
+ *
+ * Excel Function:
+ * OCT2DEC(x)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The octal number you want to convert. Number may not contain
+ * more than 10 octal characters (30 bits). The most significant
+ * bit of number is the sign bit. The remaining 29 bits are
+ * magnitude bits. Negative numbers are represented using
+ * two's-complement notation.
+ * If number is not a valid octal number, OCT2DEC returns the
+ * #NUM! error value.
+ * @return string
+ */
+ public static function OCTTODEC($x)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+
+ if (is_bool($x)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return octdec($x);
+ }
+
+
+ /**
+ * OCTTOHEX
+ *
+ * Return an octal value as hex.
+ *
+ * Excel Function:
+ * OCT2HEX(x[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $x The octal number you want to convert. Number may not contain
+ * more than 10 octal characters (30 bits). The most significant
+ * bit of number is the sign bit. The remaining 29 bits are
+ * magnitude bits. Negative numbers are represented using
+ * two's-complement notation.
+ * If number is negative, OCT2HEX ignores places and returns a
+ * 10-character hexadecimal number.
+ * If number is not a valid octal number, OCT2HEX returns the
+ * #NUM! error value.
+ * If OCT2HEX requires more than places characters, it returns
+ * the #NUM! error value.
+ * @param integer $places The number of characters to use. If places is omitted, OCT2HEX
+ * uses the minimum number of characters necessary. Places is useful
+ * for padding the return value with leading 0s (zeros).
+ * If places is not an integer, it is truncated.
+ * If places is nonnumeric, OCT2HEX returns the #VALUE! error value.
+ * If places is negative, OCT2HEX returns the #NUM! error value.
+ * @return string
+ */
+ public static function OCTTOHEX($x, $places = null)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
+
+ if (is_bool($x)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $x = (string) $x;
+ if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $hexVal = strtoupper(dechex(octdec($x)));
+
+ return self::nbrConversionFormat($hexVal, $places);
+ }
+
+
+ /**
+ * COMPLEX
+ *
+ * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.
+ *
+ * Excel Function:
+ * COMPLEX(realNumber,imaginary[,places])
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param float $realNumber The real coefficient of the complex number.
+ * @param float $imaginary The imaginary coefficient of the complex number.
+ * @param string $suffix The suffix for the imaginary component of the complex number.
+ * If omitted, the suffix is assumed to be "i".
+ * @return string
+ */
+ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i')
+ {
+ $realNumber = (is_null($realNumber)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
+ $imaginary = (is_null($imaginary)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($imaginary);
+ $suffix = (is_null($suffix)) ? 'i' : PHPExcel_Calculation_Functions::flattenSingleValue($suffix);
+
+ if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
+ (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
+ $realNumber = (float) $realNumber;
+ $imaginary = (float) $imaginary;
+
+ if ($suffix == '') {
+ $suffix = 'i';
+ }
+ if ($realNumber == 0.0) {
+ if ($imaginary == 0.0) {
+ return (string) '0';
+ } elseif ($imaginary == 1.0) {
+ return (string) $suffix;
+ } elseif ($imaginary == -1.0) {
+ return (string) '-'.$suffix;
+ }
+ return (string) $imaginary.$suffix;
+ } elseif ($imaginary == 0.0) {
+ return (string) $realNumber;
+ } elseif ($imaginary == 1.0) {
+ return (string) $realNumber.'+'.$suffix;
+ } elseif ($imaginary == -1.0) {
+ return (string) $realNumber.'-'.$suffix;
+ }
+ if ($imaginary > 0) {
+ $imaginary = (string) '+'.$imaginary;
+ }
+ return (string) $realNumber.$imaginary.$suffix;
+ }
+
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * IMAGINARY
+ *
+ * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMAGINARY(complexNumber)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $complexNumber The complex number for which you want the imaginary
+ * coefficient.
+ * @return float
+ */
+ public static function IMAGINARY($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+ return $parsedComplex['imaginary'];
+ }
+
+
+ /**
+ * IMREAL
+ *
+ * Returns the real coefficient of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMREAL(complexNumber)
+ *
+ * @access public
+ * @category Engineering Functions
+ * @param string $complexNumber The complex number for which you want the real coefficient.
+ * @return float
+ */
+ public static function IMREAL($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+ return $parsedComplex['real'];
+ }
+
+
+ /**
+ * IMABS
+ *
+ * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMABS(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the absolute value.
+ * @return float
+ */
+ public static function IMABS($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ return sqrt(
+ ($parsedComplex['real'] * $parsedComplex['real']) +
+ ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])
+ );
+ }
+
+
+ /**
+ * IMARGUMENT
+ *
+ * Returns the argument theta of a complex number, i.e. the angle in radians from the real
+ * axis to the representation of the number in polar coordinates.
+ *
+ * Excel Function:
+ * IMARGUMENT(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the argument theta.
+ * @return float
+ */
+ public static function IMARGUMENT($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if ($parsedComplex['real'] == 0.0) {
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return 0.0;
+ } elseif ($parsedComplex['imaginary'] < 0.0) {
+ return M_PI / -2;
+ } else {
+ return M_PI / 2;
+ }
+ } elseif ($parsedComplex['real'] > 0.0) {
+ return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
+ } elseif ($parsedComplex['imaginary'] < 0.0) {
+ return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
+ } else {
+ return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
+ }
+ }
+
+
+ /**
+ * IMCONJUGATE
+ *
+ * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMCONJUGATE(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the conjugate.
+ * @return string
+ */
+ public static function IMCONJUGATE($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return $parsedComplex['real'];
+ } else {
+ return self::cleanComplex(
+ self::COMPLEX(
+ $parsedComplex['real'],
+ 0 - $parsedComplex['imaginary'],
+ $parsedComplex['suffix']
+ )
+ );
+ }
+ }
+
+
+ /**
+ * IMCOS
+ *
+ * Returns the cosine of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMCOS(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the cosine.
+ * @return string|float
+ */
+ public static function IMCOS($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return cos($parsedComplex['real']);
+ } else {
+ return self::IMCONJUGATE(
+ self::COMPLEX(
+ cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),
+ sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),
+ $parsedComplex['suffix']
+ )
+ );
+ }
+ }
+
+
+ /**
+ * IMSIN
+ *
+ * Returns the sine of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSIN(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the sine.
+ * @return string|float
+ */
+ public static function IMSIN($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if ($parsedComplex['imaginary'] == 0.0) {
+ return sin($parsedComplex['real']);
+ } else {
+ return self::COMPLEX(
+ sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),
+ cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),
+ $parsedComplex['suffix']
+ );
+ }
+ }
+
+
+ /**
+ * IMSQRT
+ *
+ * Returns the square root of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSQRT(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the square root.
+ * @return string
+ */
+ public static function IMSQRT($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ $theta = self::IMARGUMENT($complexNumber);
+ $d1 = cos($theta / 2);
+ $d2 = sin($theta / 2);
+ $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
+
+ if ($parsedComplex['suffix'] == '') {
+ return self::COMPLEX($d1 * $r, $d2 * $r);
+ } else {
+ return self::COMPLEX($d1 * $r, $d2 * $r, $parsedComplex['suffix']);
+ }
+ }
+
+
+ /**
+ * IMLN
+ *
+ * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMLN(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the natural logarithm.
+ * @return string
+ */
+ public static function IMLN($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
+ $t = self::IMARGUMENT($complexNumber);
+
+ if ($parsedComplex['suffix'] == '') {
+ return self::COMPLEX($logR, $t);
+ } else {
+ return self::COMPLEX($logR, $t, $parsedComplex['suffix']);
+ }
+ }
+
+
+ /**
+ * IMLOG10
+ *
+ * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMLOG10(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the common logarithm.
+ * @return string
+ */
+ public static function IMLOG10($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return log10($parsedComplex['real']);
+ }
+
+ return self::IMPRODUCT(log10(EULER), self::IMLN($complexNumber));
+ }
+
+
+ /**
+ * IMLOG2
+ *
+ * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMLOG2(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the base-2 logarithm.
+ * @return string
+ */
+ public static function IMLOG2($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return log($parsedComplex['real'], 2);
+ }
+
+ return self::IMPRODUCT(log(EULER, 2), self::IMLN($complexNumber));
+ }
+
+
+ /**
+ * IMEXP
+ *
+ * Returns the exponential of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMEXP(complexNumber)
+ *
+ * @param string $complexNumber The complex number for which you want the exponential.
+ * @return string
+ */
+ public static function IMEXP($complexNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
+ return '1';
+ }
+
+ $e = exp($parsedComplex['real']);
+ $eX = $e * cos($parsedComplex['imaginary']);
+ $eY = $e * sin($parsedComplex['imaginary']);
+
+ if ($parsedComplex['suffix'] == '') {
+ return self::COMPLEX($eX, $eY);
+ } else {
+ return self::COMPLEX($eX, $eY, $parsedComplex['suffix']);
+ }
+ }
+
+
+ /**
+ * IMPOWER
+ *
+ * Returns a complex number in x + yi or x + yj text format raised to a power.
+ *
+ * Excel Function:
+ * IMPOWER(complexNumber,realNumber)
+ *
+ * @param string $complexNumber The complex number you want to raise to a power.
+ * @param float $realNumber The power to which you want to raise the complex number.
+ * @return string
+ */
+ public static function IMPOWER($complexNumber, $realNumber)
+ {
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
+ $realNumber = PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
+
+ if (!is_numeric($realNumber)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ $parsedComplex = self::parseComplex($complexNumber);
+
+ $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
+ $rPower = pow($r, $realNumber);
+ $theta = self::IMARGUMENT($complexNumber) * $realNumber;
+ if ($theta == 0) {
+ return 1;
+ } elseif ($parsedComplex['imaginary'] == 0.0) {
+ return self::COMPLEX($rPower * cos($theta), $rPower * sin($theta), $parsedComplex['suffix']);
+ } else {
+ return self::COMPLEX($rPower * cos($theta), $rPower * sin($theta), $parsedComplex['suffix']);
+ }
+ }
+
+
+ /**
+ * IMDIV
+ *
+ * Returns the quotient of two complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMDIV(complexDividend,complexDivisor)
+ *
+ * @param string $complexDividend The complex numerator or dividend.
+ * @param string $complexDivisor The complex denominator or divisor.
+ * @return string
+ */
+ public static function IMDIV($complexDividend, $complexDivisor)
+ {
+ $complexDividend = PHPExcel_Calculation_Functions::flattenSingleValue($complexDividend);
+ $complexDivisor = PHPExcel_Calculation_Functions::flattenSingleValue($complexDivisor);
+
+ $parsedComplexDividend = self::parseComplex($complexDividend);
+ $parsedComplexDivisor = self::parseComplex($complexDivisor);
+
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
+ ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
+ $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
+ }
+
+ $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
+ $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
+ $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
+
+ $r = $d1 / $d3;
+ $i = $d2 / $d3;
+
+ if ($i > 0.0) {
+ return self::cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
+ } elseif ($i < 0.0) {
+ return self::cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
+ } else {
+ return $r;
+ }
+ }
+
+
+ /**
+ * IMSUB
+ *
+ * Returns the difference of two complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSUB(complexNumber1,complexNumber2)
+ *
+ * @param string $complexNumber1 The complex number from which to subtract complexNumber2.
+ * @param string $complexNumber2 The complex number to subtract from complexNumber1.
+ * @return string
+ */
+ public static function IMSUB($complexNumber1, $complexNumber2)
+ {
+ $complexNumber1 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber1);
+ $complexNumber2 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber2);
+
+ $parsedComplex1 = self::parseComplex($complexNumber1);
+ $parsedComplex2 = self::parseComplex($complexNumber2);
+
+ if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
+ ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
+ $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
+ }
+
+ $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
+ $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
+
+ return self::COMPLEX($d1, $d2, $parsedComplex1['suffix']);
+ }
+
+
+ /**
+ * IMSUM
+ *
+ * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSUM(complexNumber[,complexNumber[,...]])
+ *
+ * @param string $complexNumber,... Series of complex numbers to add
+ * @return string
+ */
+ public static function IMSUM()
+ {
+ // Return value
+ $returnValue = self::parseComplex('0');
+ $activeSuffix = '';
+
+ // Loop through the arguments
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ foreach ($aArgs as $arg) {
+ $parsedComplex = self::parseComplex($arg);
+
+ if ($activeSuffix == '') {
+ $activeSuffix = $parsedComplex['suffix'];
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ $returnValue['real'] += $parsedComplex['real'];
+ $returnValue['imaginary'] += $parsedComplex['imaginary'];
+ }
+
+ if ($returnValue['imaginary'] == 0.0) {
+ $activeSuffix = '';
+ }
+ return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix);
+ }
+
+
+ /**
+ * IMPRODUCT
+ *
+ * Returns the product of two or more complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMPRODUCT(complexNumber[,complexNumber[,...]])
+ *
+ * @param string $complexNumber,... Series of complex numbers to multiply
+ * @return string
+ */
+ public static function IMPRODUCT()
+ {
+ // Return value
+ $returnValue = self::parseComplex('1');
+ $activeSuffix = '';
+
+ // Loop through the arguments
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ foreach ($aArgs as $arg) {
+ $parsedComplex = self::parseComplex($arg);
+
+ $workValue = $returnValue;
+ if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
+ $activeSuffix = $parsedComplex['suffix'];
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
+ $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
+ }
+
+ if ($returnValue['imaginary'] == 0.0) {
+ $activeSuffix = '';
+ }
+ return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix);
+ }
+
+
+ /**
+ * DELTA
+ *
+ * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
+ * Use this function to filter a set of values. For example, by summing several DELTA
+ * functions you calculate the count of equal pairs. This function is also known as the
+ * Kronecker Delta function.
+ *
+ * Excel Function:
+ * DELTA(a[,b])
+ *
+ * @param float $a The first number.
+ * @param float $b The second number. If omitted, b is assumed to be zero.
+ * @return int
+ */
+ public static function DELTA($a, $b = 0)
+ {
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
+
+ return (int) ($a == $b);
+ }
+
+
+ /**
+ * GESTEP
+ *
+ * Excel Function:
+ * GESTEP(number[,step])
+ *
+ * Returns 1 if number >= step; returns 0 (zero) otherwise
+ * Use this function to filter a set of values. For example, by summing several GESTEP
+ * functions you calculate the count of values that exceed a threshold.
+ *
+ * @param float $number The value to test against step.
+ * @param float $step The threshold value.
+ * If you omit a value for step, GESTEP uses zero.
+ * @return int
+ */
+ public static function GESTEP($number, $step = 0)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $step = PHPExcel_Calculation_Functions::flattenSingleValue($step);
+
+ return (int) ($number >= $step);
+ }
+
+
+ //
+ // Private method to calculate the erf value
+ //
+ private static $twoSqrtPi = 1.128379167095512574;
+
+ public static function erfVal($x)
+ {
+ if (abs($x) > 2.2) {
+ return 1 - self::erfcVal($x);
+ }
+ $sum = $term = $x;
+ $xsqr = ($x * $x);
+ $j = 1;
+ do {
+ $term *= $xsqr / $j;
+ $sum -= $term / (2 * $j + 1);
+ ++$j;
+ $term *= $xsqr / $j;
+ $sum += $term / (2 * $j + 1);
+ ++$j;
+ if ($sum == 0.0) {
+ break;
+ }
+ } while (abs($term / $sum) > PRECISION);
+ return self::$twoSqrtPi * $sum;
+ }
+
+
+ /**
+ * ERF
+ *
+ * Returns the error function integrated between the lower and upper bound arguments.
+ *
+ * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments,
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
+ * improved, so that it can now calculate the function for both positive and negative ranges.
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
+ *
+ * Excel Function:
+ * ERF(lower[,upper])
+ *
+ * @param float $lower lower bound for integrating ERF
+ * @param float $upper upper bound for integrating ERF.
+ * If omitted, ERF integrates between zero and lower_limit
+ * @return float
+ */
+ public static function ERF($lower, $upper = null)
+ {
+ $lower = PHPExcel_Calculation_Functions::flattenSingleValue($lower);
+ $upper = PHPExcel_Calculation_Functions::flattenSingleValue($upper);
+
+ if (is_numeric($lower)) {
+ if (is_null($upper)) {
+ return self::erfVal($lower);
+ }
+ if (is_numeric($upper)) {
+ return self::erfVal($upper) - self::erfVal($lower);
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ //
+ // Private method to calculate the erfc value
+ //
+ private static $oneSqrtPi = 0.564189583547756287;
+
+ private static function erfcVal($x)
+ {
+ if (abs($x) < 2.2) {
+ return 1 - self::erfVal($x);
+ }
+ if ($x < 0) {
+ return 2 - self::ERFC(-$x);
+ }
+ $a = $n = 1;
+ $b = $c = $x;
+ $d = ($x * $x) + 0.5;
+ $q1 = $q2 = $b / $d;
+ $t = 0;
+ do {
+ $t = $a * $n + $b * $x;
+ $a = $b;
+ $b = $t;
+ $t = $c * $n + $d * $x;
+ $c = $d;
+ $d = $t;
+ $n += 0.5;
+ $q1 = $q2;
+ $q2 = $b / $d;
+ } while ((abs($q1 - $q2) / $q2) > PRECISION);
+ return self::$oneSqrtPi * exp(-$x * $x) * $q2;
+ }
+
+
+ /**
+ * ERFC
+ *
+ * Returns the complementary ERF function integrated between x and infinity
+ *
+ * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument,
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
+ * improved, so that it can now calculate the function for both positive and negative x values.
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
+ *
+ * Excel Function:
+ * ERFC(x)
+ *
+ * @param float $x The lower bound for integrating ERFC
+ * @return float
+ */
+ public static function ERFC($x)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+
+ if (is_numeric($x)) {
+ return self::erfcVal($x);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * getConversionGroups
+ * Returns a list of the different conversion groups for UOM conversions
+ *
+ * @return array
+ */
+ public static function getConversionGroups()
+ {
+ $conversionGroups = array();
+ foreach (self::$conversionUnits as $conversionUnit) {
+ $conversionGroups[] = $conversionUnit['Group'];
+ }
+ return array_merge(array_unique($conversionGroups));
+ }
+
+
+ /**
+ * getConversionGroupUnits
+ * Returns an array of units of measure, for a specified conversion group, or for all groups
+ *
+ * @param string $group The group whose units of measure you want to retrieve
+ * @return array
+ */
+ public static function getConversionGroupUnits($group = null)
+ {
+ $conversionGroups = array();
+ foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) {
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
+ $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
+ }
+ }
+ return $conversionGroups;
+ }
+
+
+ /**
+ * getConversionGroupUnitDetails
+ *
+ * @param string $group The group whose units of measure you want to retrieve
+ * @return array
+ */
+ public static function getConversionGroupUnitDetails($group = null)
+ {
+ $conversionGroups = array();
+ foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) {
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
+ $conversionGroups[$conversionGroup['Group']][] = array(
+ 'unit' => $conversionUnit,
+ 'description' => $conversionGroup['Unit Name']
+ );
+ }
+ }
+ return $conversionGroups;
+ }
+
+
+ /**
+ * getConversionMultipliers
+ * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
+ *
+ * @return array of mixed
+ */
+ public static function getConversionMultipliers()
+ {
+ return self::$conversionMultipliers;
+ }
+
+
+ /**
+ * CONVERTUOM
+ *
+ * Converts a number from one measurement system to another.
+ * For example, CONVERT can translate a table of distances in miles to a table of distances
+ * in kilometers.
+ *
+ * Excel Function:
+ * CONVERT(value,fromUOM,toUOM)
+ *
+ * @param float $value The value in fromUOM to convert.
+ * @param string $fromUOM The units for value.
+ * @param string $toUOM The units for the result.
+ *
+ * @return float
+ */
+ public static function CONVERTUOM($value, $fromUOM, $toUOM)
+ {
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
+ $fromUOM = PHPExcel_Calculation_Functions::flattenSingleValue($fromUOM);
+ $toUOM = PHPExcel_Calculation_Functions::flattenSingleValue($toUOM);
+
+ if (!is_numeric($value)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $fromMultiplier = 1.0;
+ if (isset(self::$conversionUnits[$fromUOM])) {
+ $unitGroup1 = self::$conversionUnits[$fromUOM]['Group'];
+ } else {
+ $fromMultiplier = substr($fromUOM, 0, 1);
+ $fromUOM = substr($fromUOM, 1);
+ if (isset(self::$conversionMultipliers[$fromMultiplier])) {
+ $fromMultiplier = self::$conversionMultipliers[$fromMultiplier]['multiplier'];
+ } else {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+ if ((isset(self::$conversionUnits[$fromUOM])) && (self::$conversionUnits[$fromUOM]['AllowPrefix'])) {
+ $unitGroup1 = self::$conversionUnits[$fromUOM]['Group'];
+ } else {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+ }
+ $value *= $fromMultiplier;
+
+ $toMultiplier = 1.0;
+ if (isset(self::$conversionUnits[$toUOM])) {
+ $unitGroup2 = self::$conversionUnits[$toUOM]['Group'];
+ } else {
+ $toMultiplier = substr($toUOM, 0, 1);
+ $toUOM = substr($toUOM, 1);
+ if (isset(self::$conversionMultipliers[$toMultiplier])) {
+ $toMultiplier = self::$conversionMultipliers[$toMultiplier]['multiplier'];
+ } else {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+ if ((isset(self::$conversionUnits[$toUOM])) && (self::$conversionUnits[$toUOM]['AllowPrefix'])) {
+ $unitGroup2 = self::$conversionUnits[$toUOM]['Group'];
+ } else {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+ }
+ if ($unitGroup1 != $unitGroup2) {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+ if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) {
+ // We've already factored $fromMultiplier into the value, so we need
+ // to reverse it again
+ return $value / $fromMultiplier;
+ } elseif ($unitGroup1 == 'Temperature') {
+ if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
+ return $value;
+ } else {
+ $value = (($value - 32) / 1.8);
+ if (($toUOM == 'K') || ($toUOM == 'kel')) {
+ $value += 273.15;
+ }
+ return $value;
+ }
+ } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
+ (($toUOM == 'K') || ($toUOM == 'kel'))) {
+ return $value;
+ } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
+ (($toUOM == 'C') || ($toUOM == 'cel'))) {
+ return $value;
+ }
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
+ if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
+ $value -= 273.15;
+ }
+ return ($value * 1.8) + 32;
+ }
+ if (($toUOM == 'C') || ($toUOM == 'cel')) {
+ return $value - 273.15;
+ }
+ return $value + 273.15;
+ }
+ return ($value * self::$unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
+ }
}
-
-
-/** EULER */
-define('EULER', 2.71828182845904523536);
-
-
-/**
- * PHPExcel_Calculation_Engineering
- *
- * @category PHPExcel
- * @package PHPExcel_Calculation
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- */
-class PHPExcel_Calculation_Engineering {
-
- /**
- * Details of the Units of measure that can be used in CONVERTUOM()
- *
- * @var mixed[]
- */
- private static $_conversionUnits = array( 'g' => array( 'Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => True ),
- 'sg' => array( 'Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => False ),
- 'lbm' => array( 'Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => False ),
- 'u' => array( 'Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => True ),
- 'ozm' => array( 'Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => False ),
- 'm' => array( 'Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => True ),
- 'mi' => array( 'Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => False ),
- 'Nmi' => array( 'Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => False ),
- 'in' => array( 'Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => False ),
- 'ft' => array( 'Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => False ),
- 'yd' => array( 'Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => False ),
- 'ang' => array( 'Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => True ),
- 'Pica' => array( 'Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => False ),
- 'yr' => array( 'Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => False ),
- 'day' => array( 'Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => False ),
- 'hr' => array( 'Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => False ),
- 'mn' => array( 'Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => False ),
- 'sec' => array( 'Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => True ),
- 'Pa' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
- 'p' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
- 'atm' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
- 'at' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
- 'mmHg' => array( 'Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => True ),
- 'N' => array( 'Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => True ),
- 'dyn' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
- 'dy' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
- 'lbf' => array( 'Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => False ),
- 'J' => array( 'Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => True ),
- 'e' => array( 'Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => True ),
- 'c' => array( 'Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => True ),
- 'cal' => array( 'Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => True ),
- 'eV' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
- 'ev' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
- 'HPh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
- 'hh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
- 'Wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
- 'wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
- 'flb' => array( 'Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => False ),
- 'BTU' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
- 'btu' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
- 'HP' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
- 'h' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
- 'W' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
- 'w' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
- 'T' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => True ),
- 'ga' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => True ),
- 'C' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
- 'cel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
- 'F' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
- 'fah' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
- 'K' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
- 'kel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
- 'tsp' => array( 'Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => False ),
- 'tbs' => array( 'Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => False ),
- 'oz' => array( 'Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => False ),
- 'cup' => array( 'Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => False ),
- 'pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
- 'us_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
- 'uk_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => False ),
- 'qt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => False ),
- 'gal' => array( 'Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => False ),
- 'l' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ),
- 'lt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True )
- );
-
- /**
- * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
- *
- * @var mixed[]
- */
- private static $_conversionMultipliers = array( 'Y' => array( 'multiplier' => 1E24, 'name' => 'yotta' ),
- 'Z' => array( 'multiplier' => 1E21, 'name' => 'zetta' ),
- 'E' => array( 'multiplier' => 1E18, 'name' => 'exa' ),
- 'P' => array( 'multiplier' => 1E15, 'name' => 'peta' ),
- 'T' => array( 'multiplier' => 1E12, 'name' => 'tera' ),
- 'G' => array( 'multiplier' => 1E9, 'name' => 'giga' ),
- 'M' => array( 'multiplier' => 1E6, 'name' => 'mega' ),
- 'k' => array( 'multiplier' => 1E3, 'name' => 'kilo' ),
- 'h' => array( 'multiplier' => 1E2, 'name' => 'hecto' ),
- 'e' => array( 'multiplier' => 1E1, 'name' => 'deka' ),
- 'd' => array( 'multiplier' => 1E-1, 'name' => 'deci' ),
- 'c' => array( 'multiplier' => 1E-2, 'name' => 'centi' ),
- 'm' => array( 'multiplier' => 1E-3, 'name' => 'milli' ),
- 'u' => array( 'multiplier' => 1E-6, 'name' => 'micro' ),
- 'n' => array( 'multiplier' => 1E-9, 'name' => 'nano' ),
- 'p' => array( 'multiplier' => 1E-12, 'name' => 'pico' ),
- 'f' => array( 'multiplier' => 1E-15, 'name' => 'femto' ),
- 'a' => array( 'multiplier' => 1E-18, 'name' => 'atto' ),
- 'z' => array( 'multiplier' => 1E-21, 'name' => 'zepto' ),
- 'y' => array( 'multiplier' => 1E-24, 'name' => 'yocto' )
- );
-
- /**
- * Details of the Units of measure conversion factors, organised by group
- *
- * @var mixed[]
- */
- private static $_unitConversions = array( 'Mass' => array( 'g' => array( 'g' => 1.0,
- 'sg' => 6.85220500053478E-05,
- 'lbm' => 2.20462291469134E-03,
- 'u' => 6.02217000000000E+23,
- 'ozm' => 3.52739718003627E-02
- ),
- 'sg' => array( 'g' => 1.45938424189287E+04,
- 'sg' => 1.0,
- 'lbm' => 3.21739194101647E+01,
- 'u' => 8.78866000000000E+27,
- 'ozm' => 5.14782785944229E+02
- ),
- 'lbm' => array( 'g' => 4.5359230974881148E+02,
- 'sg' => 3.10810749306493E-02,
- 'lbm' => 1.0,
- 'u' => 2.73161000000000E+26,
- 'ozm' => 1.60000023429410E+01
- ),
- 'u' => array( 'g' => 1.66053100460465E-24,
- 'sg' => 1.13782988532950E-28,
- 'lbm' => 3.66084470330684E-27,
- 'u' => 1.0,
- 'ozm' => 5.85735238300524E-26
- ),
- 'ozm' => array( 'g' => 2.83495152079732E+01,
- 'sg' => 1.94256689870811E-03,
- 'lbm' => 6.24999908478882E-02,
- 'u' => 1.70725600000000E+25,
- 'ozm' => 1.0
- )
- ),
- 'Distance' => array( 'm' => array( 'm' => 1.0,
- 'mi' => 6.21371192237334E-04,
- 'Nmi' => 5.39956803455724E-04,
- 'in' => 3.93700787401575E+01,
- 'ft' => 3.28083989501312E+00,
- 'yd' => 1.09361329797891E+00,
- 'ang' => 1.00000000000000E+10,
- 'Pica' => 2.83464566929116E+03
- ),
- 'mi' => array( 'm' => 1.60934400000000E+03,
- 'mi' => 1.0,
- 'Nmi' => 8.68976241900648E-01,
- 'in' => 6.33600000000000E+04,
- 'ft' => 5.28000000000000E+03,
- 'yd' => 1.76000000000000E+03,
- 'ang' => 1.60934400000000E+13,
- 'Pica' => 4.56191999999971E+06
- ),
- 'Nmi' => array( 'm' => 1.85200000000000E+03,
- 'mi' => 1.15077944802354E+00,
- 'Nmi' => 1.0,
- 'in' => 7.29133858267717E+04,
- 'ft' => 6.07611548556430E+03,
- 'yd' => 2.02537182785694E+03,
- 'ang' => 1.85200000000000E+13,
- 'Pica' => 5.24976377952723E+06
- ),
- 'in' => array( 'm' => 2.54000000000000E-02,
- 'mi' => 1.57828282828283E-05,
- 'Nmi' => 1.37149028077754E-05,
- 'in' => 1.0,
- 'ft' => 8.33333333333333E-02,
- 'yd' => 2.77777777686643E-02,
- 'ang' => 2.54000000000000E+08,
- 'Pica' => 7.19999999999955E+01
- ),
- 'ft' => array( 'm' => 3.04800000000000E-01,
- 'mi' => 1.89393939393939E-04,
- 'Nmi' => 1.64578833693305E-04,
- 'in' => 1.20000000000000E+01,
- 'ft' => 1.0,
- 'yd' => 3.33333333223972E-01,
- 'ang' => 3.04800000000000E+09,
- 'Pica' => 8.63999999999946E+02
- ),
- 'yd' => array( 'm' => 9.14400000300000E-01,
- 'mi' => 5.68181818368230E-04,
- 'Nmi' => 4.93736501241901E-04,
- 'in' => 3.60000000118110E+01,
- 'ft' => 3.00000000000000E+00,
- 'yd' => 1.0,
- 'ang' => 9.14400000300000E+09,
- 'Pica' => 2.59200000085023E+03
- ),
- 'ang' => array( 'm' => 1.00000000000000E-10,
- 'mi' => 6.21371192237334E-14,
- 'Nmi' => 5.39956803455724E-14,
- 'in' => 3.93700787401575E-09,
- 'ft' => 3.28083989501312E-10,
- 'yd' => 1.09361329797891E-10,
- 'ang' => 1.0,
- 'Pica' => 2.83464566929116E-07
- ),
- 'Pica' => array( 'm' => 3.52777777777800E-04,
- 'mi' => 2.19205948372629E-07,
- 'Nmi' => 1.90484761219114E-07,
- 'in' => 1.38888888888898E-02,
- 'ft' => 1.15740740740748E-03,
- 'yd' => 3.85802469009251E-04,
- 'ang' => 3.52777777777800E+06,
- 'Pica' => 1.0
- )
- ),
- 'Time' => array( 'yr' => array( 'yr' => 1.0,
- 'day' => 365.25,
- 'hr' => 8766.0,
- 'mn' => 525960.0,
- 'sec' => 31557600.0
- ),
- 'day' => array( 'yr' => 2.73785078713210E-03,
- 'day' => 1.0,
- 'hr' => 24.0,
- 'mn' => 1440.0,
- 'sec' => 86400.0
- ),
- 'hr' => array( 'yr' => 1.14077116130504E-04,
- 'day' => 4.16666666666667E-02,
- 'hr' => 1.0,
- 'mn' => 60.0,
- 'sec' => 3600.0
- ),
- 'mn' => array( 'yr' => 1.90128526884174E-06,
- 'day' => 6.94444444444444E-04,
- 'hr' => 1.66666666666667E-02,
- 'mn' => 1.0,
- 'sec' => 60.0
- ),
- 'sec' => array( 'yr' => 3.16880878140289E-08,
- 'day' => 1.15740740740741E-05,
- 'hr' => 2.77777777777778E-04,
- 'mn' => 1.66666666666667E-02,
- 'sec' => 1.0
- )
- ),
- 'Pressure' => array( 'Pa' => array( 'Pa' => 1.0,
- 'p' => 1.0,
- 'atm' => 9.86923299998193E-06,
- 'at' => 9.86923299998193E-06,
- 'mmHg' => 7.50061707998627E-03
- ),
- 'p' => array( 'Pa' => 1.0,
- 'p' => 1.0,
- 'atm' => 9.86923299998193E-06,
- 'at' => 9.86923299998193E-06,
- 'mmHg' => 7.50061707998627E-03
- ),
- 'atm' => array( 'Pa' => 1.01324996583000E+05,
- 'p' => 1.01324996583000E+05,
- 'atm' => 1.0,
- 'at' => 1.0,
- 'mmHg' => 760.0
- ),
- 'at' => array( 'Pa' => 1.01324996583000E+05,
- 'p' => 1.01324996583000E+05,
- 'atm' => 1.0,
- 'at' => 1.0,
- 'mmHg' => 760.0
- ),
- 'mmHg' => array( 'Pa' => 1.33322363925000E+02,
- 'p' => 1.33322363925000E+02,
- 'atm' => 1.31578947368421E-03,
- 'at' => 1.31578947368421E-03,
- 'mmHg' => 1.0
- )
- ),
- 'Force' => array( 'N' => array( 'N' => 1.0,
- 'dyn' => 1.0E+5,
- 'dy' => 1.0E+5,
- 'lbf' => 2.24808923655339E-01
- ),
- 'dyn' => array( 'N' => 1.0E-5,
- 'dyn' => 1.0,
- 'dy' => 1.0,
- 'lbf' => 2.24808923655339E-06
- ),
- 'dy' => array( 'N' => 1.0E-5,
- 'dyn' => 1.0,
- 'dy' => 1.0,
- 'lbf' => 2.24808923655339E-06
- ),
- 'lbf' => array( 'N' => 4.448222,
- 'dyn' => 4.448222E+5,
- 'dy' => 4.448222E+5,
- 'lbf' => 1.0
- )
- ),
- 'Energy' => array( 'J' => array( 'J' => 1.0,
- 'e' => 9.99999519343231E+06,
- 'c' => 2.39006249473467E-01,
- 'cal' => 2.38846190642017E-01,
- 'eV' => 6.24145700000000E+18,
- 'ev' => 6.24145700000000E+18,
- 'HPh' => 3.72506430801000E-07,
- 'hh' => 3.72506430801000E-07,
- 'Wh' => 2.77777916238711E-04,
- 'wh' => 2.77777916238711E-04,
- 'flb' => 2.37304222192651E+01,
- 'BTU' => 9.47815067349015E-04,
- 'btu' => 9.47815067349015E-04
- ),
- 'e' => array( 'J' => 1.00000048065700E-07,
- 'e' => 1.0,
- 'c' => 2.39006364353494E-08,
- 'cal' => 2.38846305445111E-08,
- 'eV' => 6.24146000000000E+11,
- 'ev' => 6.24146000000000E+11,
- 'HPh' => 3.72506609848824E-14,
- 'hh' => 3.72506609848824E-14,
- 'Wh' => 2.77778049754611E-11,
- 'wh' => 2.77778049754611E-11,
- 'flb' => 2.37304336254586E-06,
- 'BTU' => 9.47815522922962E-11,
- 'btu' => 9.47815522922962E-11
- ),
- 'c' => array( 'J' => 4.18399101363672E+00,
- 'e' => 4.18398900257312E+07,
- 'c' => 1.0,
- 'cal' => 9.99330315287563E-01,
- 'eV' => 2.61142000000000E+19,
- 'ev' => 2.61142000000000E+19,
- 'HPh' => 1.55856355899327E-06,
- 'hh' => 1.55856355899327E-06,
- 'Wh' => 1.16222030532950E-03,
- 'wh' => 1.16222030532950E-03,
- 'flb' => 9.92878733152102E+01,
- 'BTU' => 3.96564972437776E-03,
- 'btu' => 3.96564972437776E-03
- ),
- 'cal' => array( 'J' => 4.18679484613929E+00,
- 'e' => 4.18679283372801E+07,
- 'c' => 1.00067013349059E+00,
- 'cal' => 1.0,
- 'eV' => 2.61317000000000E+19,
- 'ev' => 2.61317000000000E+19,
- 'HPh' => 1.55960800463137E-06,
- 'hh' => 1.55960800463137E-06,
- 'Wh' => 1.16299914807955E-03,
- 'wh' => 1.16299914807955E-03,
- 'flb' => 9.93544094443283E+01,
- 'BTU' => 3.96830723907002E-03,
- 'btu' => 3.96830723907002E-03
- ),
- 'eV' => array( 'J' => 1.60219000146921E-19,
- 'e' => 1.60218923136574E-12,
- 'c' => 3.82933423195043E-20,
- 'cal' => 3.82676978535648E-20,
- 'eV' => 1.0,
- 'ev' => 1.0,
- 'HPh' => 5.96826078912344E-26,
- 'hh' => 5.96826078912344E-26,
- 'Wh' => 4.45053000026614E-23,
- 'wh' => 4.45053000026614E-23,
- 'flb' => 3.80206452103492E-18,
- 'BTU' => 1.51857982414846E-22,
- 'btu' => 1.51857982414846E-22
- ),
- 'ev' => array( 'J' => 1.60219000146921E-19,
- 'e' => 1.60218923136574E-12,
- 'c' => 3.82933423195043E-20,
- 'cal' => 3.82676978535648E-20,
- 'eV' => 1.0,
- 'ev' => 1.0,
- 'HPh' => 5.96826078912344E-26,
- 'hh' => 5.96826078912344E-26,
- 'Wh' => 4.45053000026614E-23,
- 'wh' => 4.45053000026614E-23,
- 'flb' => 3.80206452103492E-18,
- 'BTU' => 1.51857982414846E-22,
- 'btu' => 1.51857982414846E-22
- ),
- 'HPh' => array( 'J' => 2.68451741316170E+06,
- 'e' => 2.68451612283024E+13,
- 'c' => 6.41616438565991E+05,
- 'cal' => 6.41186757845835E+05,
- 'eV' => 1.67553000000000E+25,
- 'ev' => 1.67553000000000E+25,
- 'HPh' => 1.0,
- 'hh' => 1.0,
- 'Wh' => 7.45699653134593E+02,
- 'wh' => 7.45699653134593E+02,
- 'flb' => 6.37047316692964E+07,
- 'BTU' => 2.54442605275546E+03,
- 'btu' => 2.54442605275546E+03
- ),
- 'hh' => array( 'J' => 2.68451741316170E+06,
- 'e' => 2.68451612283024E+13,
- 'c' => 6.41616438565991E+05,
- 'cal' => 6.41186757845835E+05,
- 'eV' => 1.67553000000000E+25,
- 'ev' => 1.67553000000000E+25,
- 'HPh' => 1.0,
- 'hh' => 1.0,
- 'Wh' => 7.45699653134593E+02,
- 'wh' => 7.45699653134593E+02,
- 'flb' => 6.37047316692964E+07,
- 'BTU' => 2.54442605275546E+03,
- 'btu' => 2.54442605275546E+03
- ),
- 'Wh' => array( 'J' => 3.59999820554720E+03,
- 'e' => 3.59999647518369E+10,
- 'c' => 8.60422069219046E+02,
- 'cal' => 8.59845857713046E+02,
- 'eV' => 2.24692340000000E+22,
- 'ev' => 2.24692340000000E+22,
- 'HPh' => 1.34102248243839E-03,
- 'hh' => 1.34102248243839E-03,
- 'Wh' => 1.0,
- 'wh' => 1.0,
- 'flb' => 8.54294774062316E+04,
- 'BTU' => 3.41213254164705E+00,
- 'btu' => 3.41213254164705E+00
- ),
- 'wh' => array( 'J' => 3.59999820554720E+03,
- 'e' => 3.59999647518369E+10,
- 'c' => 8.60422069219046E+02,
- 'cal' => 8.59845857713046E+02,
- 'eV' => 2.24692340000000E+22,
- 'ev' => 2.24692340000000E+22,
- 'HPh' => 1.34102248243839E-03,
- 'hh' => 1.34102248243839E-03,
- 'Wh' => 1.0,
- 'wh' => 1.0,
- 'flb' => 8.54294774062316E+04,
- 'BTU' => 3.41213254164705E+00,
- 'btu' => 3.41213254164705E+00
- ),
- 'flb' => array( 'J' => 4.21400003236424E-02,
- 'e' => 4.21399800687660E+05,
- 'c' => 1.00717234301644E-02,
- 'cal' => 1.00649785509554E-02,
- 'eV' => 2.63015000000000E+17,
- 'ev' => 2.63015000000000E+17,
- 'HPh' => 1.56974211145130E-08,
- 'hh' => 1.56974211145130E-08,
- 'Wh' => 1.17055614802000E-05,
- 'wh' => 1.17055614802000E-05,
- 'flb' => 1.0,
- 'BTU' => 3.99409272448406E-05,
- 'btu' => 3.99409272448406E-05
- ),
- 'BTU' => array( 'J' => 1.05505813786749E+03,
- 'e' => 1.05505763074665E+10,
- 'c' => 2.52165488508168E+02,
- 'cal' => 2.51996617135510E+02,
- 'eV' => 6.58510000000000E+21,
- 'ev' => 6.58510000000000E+21,
- 'HPh' => 3.93015941224568E-04,
- 'hh' => 3.93015941224568E-04,
- 'Wh' => 2.93071851047526E-01,
- 'wh' => 2.93071851047526E-01,
- 'flb' => 2.50369750774671E+04,
- 'BTU' => 1.0,
- 'btu' => 1.0,
- ),
- 'btu' => array( 'J' => 1.05505813786749E+03,
- 'e' => 1.05505763074665E+10,
- 'c' => 2.52165488508168E+02,
- 'cal' => 2.51996617135510E+02,
- 'eV' => 6.58510000000000E+21,
- 'ev' => 6.58510000000000E+21,
- 'HPh' => 3.93015941224568E-04,
- 'hh' => 3.93015941224568E-04,
- 'Wh' => 2.93071851047526E-01,
- 'wh' => 2.93071851047526E-01,
- 'flb' => 2.50369750774671E+04,
- 'BTU' => 1.0,
- 'btu' => 1.0,
- )
- ),
- 'Power' => array( 'HP' => array( 'HP' => 1.0,
- 'h' => 1.0,
- 'W' => 7.45701000000000E+02,
- 'w' => 7.45701000000000E+02
- ),
- 'h' => array( 'HP' => 1.0,
- 'h' => 1.0,
- 'W' => 7.45701000000000E+02,
- 'w' => 7.45701000000000E+02
- ),
- 'W' => array( 'HP' => 1.34102006031908E-03,
- 'h' => 1.34102006031908E-03,
- 'W' => 1.0,
- 'w' => 1.0
- ),
- 'w' => array( 'HP' => 1.34102006031908E-03,
- 'h' => 1.34102006031908E-03,
- 'W' => 1.0,
- 'w' => 1.0
- )
- ),
- 'Magnetism' => array( 'T' => array( 'T' => 1.0,
- 'ga' => 10000.0
- ),
- 'ga' => array( 'T' => 0.0001,
- 'ga' => 1.0
- )
- ),
- 'Liquid' => array( 'tsp' => array( 'tsp' => 1.0,
- 'tbs' => 3.33333333333333E-01,
- 'oz' => 1.66666666666667E-01,
- 'cup' => 2.08333333333333E-02,
- 'pt' => 1.04166666666667E-02,
- 'us_pt' => 1.04166666666667E-02,
- 'uk_pt' => 8.67558516821960E-03,
- 'qt' => 5.20833333333333E-03,
- 'gal' => 1.30208333333333E-03,
- 'l' => 4.92999408400710E-03,
- 'lt' => 4.92999408400710E-03
- ),
- 'tbs' => array( 'tsp' => 3.00000000000000E+00,
- 'tbs' => 1.0,
- 'oz' => 5.00000000000000E-01,
- 'cup' => 6.25000000000000E-02,
- 'pt' => 3.12500000000000E-02,
- 'us_pt' => 3.12500000000000E-02,
- 'uk_pt' => 2.60267555046588E-02,
- 'qt' => 1.56250000000000E-02,
- 'gal' => 3.90625000000000E-03,
- 'l' => 1.47899822520213E-02,
- 'lt' => 1.47899822520213E-02
- ),
- 'oz' => array( 'tsp' => 6.00000000000000E+00,
- 'tbs' => 2.00000000000000E+00,
- 'oz' => 1.0,
- 'cup' => 1.25000000000000E-01,
- 'pt' => 6.25000000000000E-02,
- 'us_pt' => 6.25000000000000E-02,
- 'uk_pt' => 5.20535110093176E-02,
- 'qt' => 3.12500000000000E-02,
- 'gal' => 7.81250000000000E-03,
- 'l' => 2.95799645040426E-02,
- 'lt' => 2.95799645040426E-02
- ),
- 'cup' => array( 'tsp' => 4.80000000000000E+01,
- 'tbs' => 1.60000000000000E+01,
- 'oz' => 8.00000000000000E+00,
- 'cup' => 1.0,
- 'pt' => 5.00000000000000E-01,
- 'us_pt' => 5.00000000000000E-01,
- 'uk_pt' => 4.16428088074541E-01,
- 'qt' => 2.50000000000000E-01,
- 'gal' => 6.25000000000000E-02,
- 'l' => 2.36639716032341E-01,
- 'lt' => 2.36639716032341E-01
- ),
- 'pt' => array( 'tsp' => 9.60000000000000E+01,
- 'tbs' => 3.20000000000000E+01,
- 'oz' => 1.60000000000000E+01,
- 'cup' => 2.00000000000000E+00,
- 'pt' => 1.0,
- 'us_pt' => 1.0,
- 'uk_pt' => 8.32856176149081E-01,
- 'qt' => 5.00000000000000E-01,
- 'gal' => 1.25000000000000E-01,
- 'l' => 4.73279432064682E-01,
- 'lt' => 4.73279432064682E-01
- ),
- 'us_pt' => array( 'tsp' => 9.60000000000000E+01,
- 'tbs' => 3.20000000000000E+01,
- 'oz' => 1.60000000000000E+01,
- 'cup' => 2.00000000000000E+00,
- 'pt' => 1.0,
- 'us_pt' => 1.0,
- 'uk_pt' => 8.32856176149081E-01,
- 'qt' => 5.00000000000000E-01,
- 'gal' => 1.25000000000000E-01,
- 'l' => 4.73279432064682E-01,
- 'lt' => 4.73279432064682E-01
- ),
- 'uk_pt' => array( 'tsp' => 1.15266000000000E+02,
- 'tbs' => 3.84220000000000E+01,
- 'oz' => 1.92110000000000E+01,
- 'cup' => 2.40137500000000E+00,
- 'pt' => 1.20068750000000E+00,
- 'us_pt' => 1.20068750000000E+00,
- 'uk_pt' => 1.0,
- 'qt' => 6.00343750000000E-01,
- 'gal' => 1.50085937500000E-01,
- 'l' => 5.68260698087162E-01,
- 'lt' => 5.68260698087162E-01
- ),
- 'qt' => array( 'tsp' => 1.92000000000000E+02,
- 'tbs' => 6.40000000000000E+01,
- 'oz' => 3.20000000000000E+01,
- 'cup' => 4.00000000000000E+00,
- 'pt' => 2.00000000000000E+00,
- 'us_pt' => 2.00000000000000E+00,
- 'uk_pt' => 1.66571235229816E+00,
- 'qt' => 1.0,
- 'gal' => 2.50000000000000E-01,
- 'l' => 9.46558864129363E-01,
- 'lt' => 9.46558864129363E-01
- ),
- 'gal' => array( 'tsp' => 7.68000000000000E+02,
- 'tbs' => 2.56000000000000E+02,
- 'oz' => 1.28000000000000E+02,
- 'cup' => 1.60000000000000E+01,
- 'pt' => 8.00000000000000E+00,
- 'us_pt' => 8.00000000000000E+00,
- 'uk_pt' => 6.66284940919265E+00,
- 'qt' => 4.00000000000000E+00,
- 'gal' => 1.0,
- 'l' => 3.78623545651745E+00,
- 'lt' => 3.78623545651745E+00
- ),
- 'l' => array( 'tsp' => 2.02840000000000E+02,
- 'tbs' => 6.76133333333333E+01,
- 'oz' => 3.38066666666667E+01,
- 'cup' => 4.22583333333333E+00,
- 'pt' => 2.11291666666667E+00,
- 'us_pt' => 2.11291666666667E+00,
- 'uk_pt' => 1.75975569552166E+00,
- 'qt' => 1.05645833333333E+00,
- 'gal' => 2.64114583333333E-01,
- 'l' => 1.0,
- 'lt' => 1.0
- ),
- 'lt' => array( 'tsp' => 2.02840000000000E+02,
- 'tbs' => 6.76133333333333E+01,
- 'oz' => 3.38066666666667E+01,
- 'cup' => 4.22583333333333E+00,
- 'pt' => 2.11291666666667E+00,
- 'us_pt' => 2.11291666666667E+00,
- 'uk_pt' => 1.75975569552166E+00,
- 'qt' => 1.05645833333333E+00,
- 'gal' => 2.64114583333333E-01,
- 'l' => 1.0,
- 'lt' => 1.0
- )
- )
- );
-
-
- /**
- * _parseComplex
- *
- * Parses a complex number into its real and imaginary parts, and an I or J suffix
- *
- * @param string $complexNumber The complex number
- * @return string[] Indexed on "real", "imaginary" and "suffix"
- */
- public static function _parseComplex($complexNumber) {
- $workString = (string) $complexNumber;
-
- $realNumber = $imaginary = 0;
- // Extract the suffix, if there is one
- $suffix = substr($workString,-1);
- if (!is_numeric($suffix)) {
- $workString = substr($workString,0,-1);
- } else {
- $suffix = '';
- }
-
- // Split the input into its Real and Imaginary components
- $leadingSign = 0;
- if (strlen($workString) > 0) {
- $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
- }
- $power = '';
- $realNumber = strtok($workString, '+-');
- if (strtoupper(substr($realNumber,-1)) == 'E') {
- $power = strtok('+-');
- ++$leadingSign;
- }
-
- $realNumber = substr($workString,0,strlen($realNumber)+strlen($power)+$leadingSign);
-
- if ($suffix != '') {
- $imaginary = substr($workString,strlen($realNumber));
-
- if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
- $imaginary = $realNumber.'1';
- $realNumber = '0';
- } else if ($imaginary == '') {
- $imaginary = $realNumber;
- $realNumber = '0';
- } elseif (($imaginary == '+') || ($imaginary == '-')) {
- $imaginary .= '1';
- }
- }
-
- return array( 'real' => $realNumber,
- 'imaginary' => $imaginary,
- 'suffix' => $suffix
- );
- } // function _parseComplex()
-
-
- /**
- * _cleanComplex
- *
- * Cleans the leading characters in a complex number string
- *
- * @param string $complexNumber The complex number to clean
- * @return string The "cleaned" complex number
- */
- private static function _cleanComplex($complexNumber) {
- if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
- if ($complexNumber{0} == '0') $complexNumber = substr($complexNumber,1);
- if ($complexNumber{0} == '.') $complexNumber = '0'.$complexNumber;
- if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
- return $complexNumber;
- }
-
-
- private static function _nbrConversionFormat($xVal,$places) {
- if (!is_null($places)) {
- if (strlen($xVal) <= $places) {
- return substr(str_pad($xVal,$places,'0',STR_PAD_LEFT),-10);
- } else {
- return PHPExcel_Calculation_Functions::NaN();
- }
- }
-
- return substr($xVal,-10);
- } // function _nbrConversionFormat()
-
-
- /**
- * BESSELI
- *
- * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated
- * for purely imaginary arguments
- *
- * Excel Function:
- * BESSELI(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELI returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function.
- * If ord is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELI returns the #VALUE! error value.
- * If $ord < 0, BESSELI returns the #NUM! error value.
- * @return float
- *
- */
- public static function BESSELI($x, $ord) {
- $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- $ord = floor($ord);
- if ($ord < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- if (abs($x) <= 30) {
- $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
- $ordK = 1;
- $fSqrX = ($x * $x) / 4;
- do {
- $fTerm *= $fSqrX;
- $fTerm /= ($ordK * ($ordK + $ord));
- $fResult += $fTerm;
- } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
- } else {
- $f_2_PI = 2 * M_PI;
-
- $fXAbs = abs($x);
- $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
- if (($ord & 1) && ($x < 0)) {
- $fResult = -$fResult;
- }
- }
- return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function BESSELI()
-
-
- /**
- * BESSELJ
- *
- * Returns the Bessel function
- *
- * Excel Function:
- * BESSELJ(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELJ returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value.
- * If $ord < 0, BESSELJ returns the #NUM! error value.
- * @return float
- *
- */
- public static function BESSELJ($x, $ord) {
- $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- $ord = floor($ord);
- if ($ord < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $fResult = 0;
- if (abs($x) <= 30) {
- $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
- $ordK = 1;
- $fSqrX = ($x * $x) / -4;
- do {
- $fTerm *= $fSqrX;
- $fTerm /= ($ordK * ($ordK + $ord));
- $fResult += $fTerm;
- } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
- } else {
- $f_PI_DIV_2 = M_PI / 2;
- $f_PI_DIV_4 = M_PI / 4;
-
- $fXAbs = abs($x);
- $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
- if (($ord & 1) && ($x < 0)) {
- $fResult = -$fResult;
- }
- }
- return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function BESSELJ()
-
-
- private static function _Besselk0($fNum) {
- if ($fNum <= 2) {
- $fNum2 = $fNum * 0.5;
- $y = ($fNum2 * $fNum2);
- $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
- (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
- (0.10750e-3 + $y * 0.74e-5))))));
- } else {
- $y = 2 / $fNum;
- $fRet = exp(-$fNum) / sqrt($fNum) *
- (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
- (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
- }
- return $fRet;
- } // function _Besselk0()
-
-
- private static function _Besselk1($fNum) {
- if ($fNum <= 2) {
- $fNum2 = $fNum * 0.5;
- $y = ($fNum2 * $fNum2);
- $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
- (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
- (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
- } else {
- $y = 2 / $fNum;
- $fRet = exp(-$fNum) / sqrt($fNum) *
- (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
- (0.325614e-2 + $y * (-0.68245e-3)))))));
- }
- return $fRet;
- } // function _Besselk1()
-
-
- /**
- * BESSELK
- *
- * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated
- * for purely imaginary arguments.
- *
- * Excel Function:
- * BESSELK(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELK returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
- * If $ord < 0, BESSELK returns the #NUM! error value.
- * @return float
- *
- */
- public static function BESSELK($x, $ord) {
- $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- if (($ord < 0) || ($x == 0.0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- switch(floor($ord)) {
- case 0 : return self::_Besselk0($x);
- break;
- case 1 : return self::_Besselk1($x);
- break;
- default : $fTox = 2 / $x;
- $fBkm = self::_Besselk0($x);
- $fBk = self::_Besselk1($x);
- for ($n = 1; $n < $ord; ++$n) {
- $fBkp = $fBkm + $n * $fTox * $fBk;
- $fBkm = $fBk;
- $fBk = $fBkp;
- }
- }
- return (is_nan($fBk)) ? PHPExcel_Calculation_Functions::NaN() : $fBk;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function BESSELK()
-
-
- private static function _Bessely0($fNum) {
- if ($fNum < 8.0) {
- $y = ($fNum * $fNum);
- $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
- $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
- $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
- } else {
- $z = 8.0 / $fNum;
- $y = ($z * $z);
- $xx = $fNum - 0.785398164;
- $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
- $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
- $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
- }
- return $fRet;
- } // function _Bessely0()
-
-
- private static function _Bessely1($fNum) {
- if ($fNum < 8.0) {
- $y = ($fNum * $fNum);
- $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
- (-0.4237922726e7 + $y * 0.8511937935e4)))));
- $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
- (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
- $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
- } else {
- $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
- }
- return $fRet;
- } // function _Bessely1()
-
-
- /**
- * BESSELY
- *
- * Returns the Bessel function, which is also called the Weber function or the Neumann function.
- *
- * Excel Function:
- * BESSELY(x,ord)
- *
- * @access public
- * @category Engineering Functions
- * @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELK returns the #VALUE! error value.
- * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
- * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
- * If $ord < 0, BESSELK returns the #NUM! error value.
- *
- * @return float
- */
- public static function BESSELY($x, $ord) {
- $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- if (($ord < 0) || ($x == 0.0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- switch(floor($ord)) {
- case 0 : return self::_Bessely0($x);
- break;
- case 1 : return self::_Bessely1($x);
- break;
- default: $fTox = 2 / $x;
- $fBym = self::_Bessely0($x);
- $fBy = self::_Bessely1($x);
- for ($n = 1; $n < $ord; ++$n) {
- $fByp = $n * $fTox * $fBy - $fBym;
- $fBym = $fBy;
- $fBy = $fByp;
- }
- }
- return (is_nan($fBy)) ? PHPExcel_Calculation_Functions::NaN() : $fBy;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function BESSELY()
-
-
- /**
- * BINTODEC
- *
- * Return a binary value as decimal.
- *
- * Excel Function:
- * BIN2DEC(x)
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The binary number (as a string) that you want to convert. The number
- * cannot contain more than 10 characters (10 bits). The most significant
- * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
- * Negative numbers are represented using two's-complement notation.
- * If number is not a valid binary number, or if number contains more than
- * 10 characters (10 bits), BIN2DEC returns the #NUM! error value.
- * @return string
- */
- public static function BINTODEC($x) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if (strlen($x) > 10) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- $x = substr($x,-9);
- return '-'.(512-bindec($x));
- }
- return bindec($x);
- } // function BINTODEC()
-
-
- /**
- * BINTOHEX
- *
- * Return a binary value as hex.
- *
- * Excel Function:
- * BIN2HEX(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The binary number (as a string) that you want to convert. The number
- * cannot contain more than 10 characters (10 bits). The most significant
- * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
- * Negative numbers are represented using two's-complement notation.
- * If number is not a valid binary number, or if number contains more than
- * 10 characters (10 bits), BIN2HEX returns the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the
- * minimum number of characters necessary. Places is useful for padding the
- * return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, BIN2HEX returns the #VALUE! error value.
- * If places is negative, BIN2HEX returns the #NUM! error value.
- * @return string
- */
- public static function BINTOHEX($x, $places=NULL) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if (strlen($x) > 10) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- return str_repeat('F',8).substr(strtoupper(dechex(bindec(substr($x,-9)))),-2);
- }
- $hexVal = (string) strtoupper(dechex(bindec($x)));
-
- return self::_nbrConversionFormat($hexVal,$places);
- } // function BINTOHEX()
-
-
- /**
- * BINTOOCT
- *
- * Return a binary value as octal.
- *
- * Excel Function:
- * BIN2OCT(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The binary number (as a string) that you want to convert. The number
- * cannot contain more than 10 characters (10 bits). The most significant
- * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
- * Negative numbers are represented using two's-complement notation.
- * If number is not a valid binary number, or if number contains more than
- * 10 characters (10 bits), BIN2OCT returns the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the
- * minimum number of characters necessary. Places is useful for padding the
- * return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, BIN2OCT returns the #VALUE! error value.
- * If places is negative, BIN2OCT returns the #NUM! error value.
- * @return string
- */
- public static function BINTOOCT($x, $places=NULL) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if (strlen($x) > 10) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- return str_repeat('7',7).substr(strtoupper(decoct(bindec(substr($x,-9)))),-3);
- }
- $octVal = (string) decoct(bindec($x));
-
- return self::_nbrConversionFormat($octVal,$places);
- } // function BINTOOCT()
-
-
- /**
- * DECTOBIN
- *
- * Return a decimal value as binary.
- *
- * Excel Function:
- * DEC2BIN(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The decimal integer you want to convert. If number is negative,
- * valid place values are ignored and DEC2BIN returns a 10-character
- * (10-bit) binary number in which the most significant bit is the sign
- * bit. The remaining 9 bits are magnitude bits. Negative numbers are
- * represented using two's-complement notation.
- * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error
- * value.
- * If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
- * If DEC2BIN requires more than places characters, it returns the #NUM!
- * error value.
- * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses
- * the minimum number of characters necessary. Places is useful for
- * padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, DEC2BIN returns the #VALUE! error value.
- * If places is zero or negative, DEC2BIN returns the #NUM! error value.
- * @return string
- */
- public static function DECTOBIN($x, $places=NULL) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = decbin($x);
- if (strlen($r) == 32) {
- // Two's Complement
- $r = substr($r,-10);
- } elseif (strlen($r) > 11) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return self::_nbrConversionFormat($r,$places);
- } // function DECTOBIN()
-
-
- /**
- * DECTOHEX
- *
- * Return a decimal value as hex.
- *
- * Excel Function:
- * DEC2HEX(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The decimal integer you want to convert. If number is negative,
- * places is ignored and DEC2HEX returns a 10-character (40-bit)
- * hexadecimal number in which the most significant bit is the sign
- * bit. The remaining 39 bits are magnitude bits. Negative numbers
- * are represented using two's-complement notation.
- * If number < -549,755,813,888 or if number > 549,755,813,887,
- * DEC2HEX returns the #NUM! error value.
- * If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
- * If DEC2HEX requires more than places characters, it returns the
- * #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses
- * the minimum number of characters necessary. Places is useful for
- * padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, DEC2HEX returns the #VALUE! error value.
- * If places is zero or negative, DEC2HEX returns the #NUM! error value.
- * @return string
- */
- public static function DECTOHEX($x, $places=null) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = strtoupper(dechex($x));
- if (strlen($r) == 8) {
- // Two's Complement
- $r = 'FF'.$r;
- }
-
- return self::_nbrConversionFormat($r,$places);
- } // function DECTOHEX()
-
-
- /**
- * DECTOOCT
- *
- * Return an decimal value as octal.
- *
- * Excel Function:
- * DEC2OCT(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The decimal integer you want to convert. If number is negative,
- * places is ignored and DEC2OCT returns a 10-character (30-bit)
- * octal number in which the most significant bit is the sign bit.
- * The remaining 29 bits are magnitude bits. Negative numbers are
- * represented using two's-complement notation.
- * If number < -536,870,912 or if number > 536,870,911, DEC2OCT
- * returns the #NUM! error value.
- * If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
- * If DEC2OCT requires more than places characters, it returns the
- * #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses
- * the minimum number of characters necessary. Places is useful for
- * padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, DEC2OCT returns the #VALUE! error value.
- * If places is zero or negative, DEC2OCT returns the #NUM! error value.
- * @return string
- */
- public static function DECTOOCT($x, $places=null) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = decoct($x);
- if (strlen($r) == 11) {
- // Two's Complement
- $r = substr($r,-10);
- }
-
- return self::_nbrConversionFormat($r,$places);
- } // function DECTOOCT()
-
-
- /**
- * HEXTOBIN
- *
- * Return a hex value as binary.
- *
- * Excel Function:
- * HEX2BIN(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x the hexadecimal number you want to convert. Number cannot
- * contain more than 10 characters. The most significant bit of
- * number is the sign bit (40th bit from the right). The remaining
- * 9 bits are magnitude bits. Negative numbers are represented
- * using two's-complement notation.
- * If number is negative, HEX2BIN ignores places and returns a
- * 10-character binary number.
- * If number is negative, it cannot be less than FFFFFFFE00, and
- * if number is positive, it cannot be greater than 1FF.
- * If number is not a valid hexadecimal number, HEX2BIN returns
- * the #NUM! error value.
- * If HEX2BIN requires more than places characters, it returns
- * the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted,
- * HEX2BIN uses the minimum number of characters necessary. Places
- * is useful for padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, HEX2BIN returns the #VALUE! error value.
- * If places is negative, HEX2BIN returns the #NUM! error value.
- * @return string
- */
- public static function HEXTOBIN($x, $places=null) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $binVal = decbin(hexdec($x));
-
- return substr(self::_nbrConversionFormat($binVal,$places),-10);
- } // function HEXTOBIN()
-
-
- /**
- * HEXTODEC
- *
- * Return a hex value as decimal.
- *
- * Excel Function:
- * HEX2DEC(x)
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The hexadecimal number you want to convert. This number cannot
- * contain more than 10 characters (40 bits). The most significant
- * bit of number is the sign bit. The remaining 39 bits are magnitude
- * bits. Negative numbers are represented using two's-complement
- * notation.
- * If number is not a valid hexadecimal number, HEX2DEC returns the
- * #NUM! error value.
- * @return string
- */
- public static function HEXTODEC($x) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return hexdec($x);
- } // function HEXTODEC()
-
-
- /**
- * HEXTOOCT
- *
- * Return a hex value as octal.
- *
- * Excel Function:
- * HEX2OCT(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The hexadecimal number you want to convert. Number cannot
- * contain more than 10 characters. The most significant bit of
- * number is the sign bit. The remaining 39 bits are magnitude
- * bits. Negative numbers are represented using two's-complement
- * notation.
- * If number is negative, HEX2OCT ignores places and returns a
- * 10-character octal number.
- * If number is negative, it cannot be less than FFE0000000, and
- * if number is positive, it cannot be greater than 1FFFFFFF.
- * If number is not a valid hexadecimal number, HEX2OCT returns
- * the #NUM! error value.
- * If HEX2OCT requires more than places characters, it returns
- * the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, HEX2OCT
- * uses the minimum number of characters necessary. Places is
- * useful for padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, HEX2OCT returns the #VALUE! error
- * value.
- * If places is negative, HEX2OCT returns the #NUM! error value.
- * @return string
- */
- public static function HEXTOOCT($x, $places=null) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $octVal = decoct(hexdec($x));
-
- return self::_nbrConversionFormat($octVal,$places);
- } // function HEXTOOCT()
-
-
- /**
- * OCTTOBIN
- *
- * Return an octal value as binary.
- *
- * Excel Function:
- * OCT2BIN(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The octal number you want to convert. Number may not
- * contain more than 10 characters. The most significant
- * bit of number is the sign bit. The remaining 29 bits
- * are magnitude bits. Negative numbers are represented
- * using two's-complement notation.
- * If number is negative, OCT2BIN ignores places and returns
- * a 10-character binary number.
- * If number is negative, it cannot be less than 7777777000,
- * and if number is positive, it cannot be greater than 777.
- * If number is not a valid octal number, OCT2BIN returns
- * the #NUM! error value.
- * If OCT2BIN requires more than places characters, it
- * returns the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted,
- * OCT2BIN uses the minimum number of characters necessary.
- * Places is useful for padding the return value with
- * leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, OCT2BIN returns the #VALUE!
- * error value.
- * If places is negative, OCT2BIN returns the #NUM! error
- * value.
- * @return string
- */
- public static function OCTTOBIN($x, $places=null) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $r = decbin(octdec($x));
-
- return self::_nbrConversionFormat($r,$places);
- } // function OCTTOBIN()
-
-
- /**
- * OCTTODEC
- *
- * Return an octal value as decimal.
- *
- * Excel Function:
- * OCT2DEC(x)
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The octal number you want to convert. Number may not contain
- * more than 10 octal characters (30 bits). The most significant
- * bit of number is the sign bit. The remaining 29 bits are
- * magnitude bits. Negative numbers are represented using
- * two's-complement notation.
- * If number is not a valid octal number, OCT2DEC returns the
- * #NUM! error value.
- * @return string
- */
- public static function OCTTODEC($x) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return octdec($x);
- } // function OCTTODEC()
-
-
- /**
- * OCTTOHEX
- *
- * Return an octal value as hex.
- *
- * Excel Function:
- * OCT2HEX(x[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param string $x The octal number you want to convert. Number may not contain
- * more than 10 octal characters (30 bits). The most significant
- * bit of number is the sign bit. The remaining 29 bits are
- * magnitude bits. Negative numbers are represented using
- * two's-complement notation.
- * If number is negative, OCT2HEX ignores places and returns a
- * 10-character hexadecimal number.
- * If number is not a valid octal number, OCT2HEX returns the
- * #NUM! error value.
- * If OCT2HEX requires more than places characters, it returns
- * the #NUM! error value.
- * @param integer $places The number of characters to use. If places is omitted, OCT2HEX
- * uses the minimum number of characters necessary. Places is useful
- * for padding the return value with leading 0s (zeros).
- * If places is not an integer, it is truncated.
- * If places is nonnumeric, OCT2HEX returns the #VALUE! error value.
- * If places is negative, OCT2HEX returns the #NUM! error value.
- * @return string
- */
- public static function OCTTOHEX($x, $places=null) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $hexVal = strtoupper(dechex(octdec($x)));
-
- return self::_nbrConversionFormat($hexVal,$places);
- } // function OCTTOHEX()
-
-
- /**
- * COMPLEX
- *
- * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.
- *
- * Excel Function:
- * COMPLEX(realNumber,imaginary[,places])
- *
- * @access public
- * @category Engineering Functions
- * @param float $realNumber The real coefficient of the complex number.
- * @param float $imaginary The imaginary coefficient of the complex number.
- * @param string $suffix The suffix for the imaginary component of the complex number.
- * If omitted, the suffix is assumed to be "i".
- * @return string
- */
- public static function COMPLEX($realNumber=0.0, $imaginary=0.0, $suffix='i') {
- $realNumber = (is_null($realNumber)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
- $imaginary = (is_null($imaginary)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($imaginary);
- $suffix = (is_null($suffix)) ? 'i' : PHPExcel_Calculation_Functions::flattenSingleValue($suffix);
-
- if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
- (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
- $realNumber = (float) $realNumber;
- $imaginary = (float) $imaginary;
-
- if ($suffix == '') $suffix = 'i';
- if ($realNumber == 0.0) {
- if ($imaginary == 0.0) {
- return (string) '0';
- } elseif ($imaginary == 1.0) {
- return (string) $suffix;
- } elseif ($imaginary == -1.0) {
- return (string) '-'.$suffix;
- }
- return (string) $imaginary.$suffix;
- } elseif ($imaginary == 0.0) {
- return (string) $realNumber;
- } elseif ($imaginary == 1.0) {
- return (string) $realNumber.'+'.$suffix;
- } elseif ($imaginary == -1.0) {
- return (string) $realNumber.'-'.$suffix;
- }
- if ($imaginary > 0) { $imaginary = (string) '+'.$imaginary; }
- return (string) $realNumber.$imaginary.$suffix;
- }
-
- return PHPExcel_Calculation_Functions::VALUE();
- } // function COMPLEX()
-
-
- /**
- * IMAGINARY
- *
- * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMAGINARY(complexNumber)
- *
- * @access public
- * @category Engineering Functions
- * @param string $complexNumber The complex number for which you want the imaginary
- * coefficient.
- * @return float
- */
- public static function IMAGINARY($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
- return $parsedComplex['imaginary'];
- } // function IMAGINARY()
-
-
- /**
- * IMREAL
- *
- * Returns the real coefficient of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMREAL(complexNumber)
- *
- * @access public
- * @category Engineering Functions
- * @param string $complexNumber The complex number for which you want the real coefficient.
- * @return float
- */
- public static function IMREAL($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
- return $parsedComplex['real'];
- } // function IMREAL()
-
-
- /**
- * IMABS
- *
- * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMABS(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the absolute value.
- * @return float
- */
- public static function IMABS($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- return sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
- } // function IMABS()
-
-
- /**
- * IMARGUMENT
- *
- * Returns the argument theta of a complex number, i.e. the angle in radians from the real
- * axis to the representation of the number in polar coordinates.
- *
- * Excel Function:
- * IMARGUMENT(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the argument theta.
- * @return float
- */
- public static function IMARGUMENT($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['real'] == 0.0) {
- if ($parsedComplex['imaginary'] == 0.0) {
- return 0.0;
- } elseif($parsedComplex['imaginary'] < 0.0) {
- return M_PI / -2;
- } else {
- return M_PI / 2;
- }
- } elseif ($parsedComplex['real'] > 0.0) {
- return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
- } elseif ($parsedComplex['imaginary'] < 0.0) {
- return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
- } else {
- return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
- }
- } // function IMARGUMENT()
-
-
- /**
- * IMCONJUGATE
- *
- * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMCONJUGATE(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the conjugate.
- * @return string
- */
- public static function IMCONJUGATE($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['imaginary'] == 0.0) {
- return $parsedComplex['real'];
- } else {
- return self::_cleanComplex( self::COMPLEX( $parsedComplex['real'],
- 0 - $parsedComplex['imaginary'],
- $parsedComplex['suffix']
- )
- );
- }
- } // function IMCONJUGATE()
-
-
- /**
- * IMCOS
- *
- * Returns the cosine of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMCOS(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the cosine.
- * @return string|float
- */
- public static function IMCOS($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['imaginary'] == 0.0) {
- return cos($parsedComplex['real']);
- } else {
- return self::IMCONJUGATE(self::COMPLEX(cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']));
- }
- } // function IMCOS()
-
-
- /**
- * IMSIN
- *
- * Returns the sine of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSIN(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the sine.
- * @return string|float
- */
- public static function IMSIN($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if ($parsedComplex['imaginary'] == 0.0) {
- return sin($parsedComplex['real']);
- } else {
- return self::COMPLEX(sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']);
- }
- } // function IMSIN()
-
-
- /**
- * IMSQRT
- *
- * Returns the square root of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSQRT(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the square root.
- * @return string
- */
- public static function IMSQRT($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- $theta = self::IMARGUMENT($complexNumber);
- $d1 = cos($theta / 2);
- $d2 = sin($theta / 2);
- $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
-
- if ($parsedComplex['suffix'] == '') {
- return self::COMPLEX($d1 * $r,$d2 * $r);
- } else {
- return self::COMPLEX($d1 * $r,$d2 * $r,$parsedComplex['suffix']);
- }
- } // function IMSQRT()
-
-
- /**
- * IMLN
- *
- * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMLN(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the natural logarithm.
- * @return string
- */
- public static function IMLN($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
- $t = self::IMARGUMENT($complexNumber);
-
- if ($parsedComplex['suffix'] == '') {
- return self::COMPLEX($logR,$t);
- } else {
- return self::COMPLEX($logR,$t,$parsedComplex['suffix']);
- }
- } // function IMLN()
-
-
- /**
- * IMLOG10
- *
- * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMLOG10(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the common logarithm.
- * @return string
- */
- public static function IMLOG10($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return log10($parsedComplex['real']);
- }
-
- return self::IMPRODUCT(log10(EULER),self::IMLN($complexNumber));
- } // function IMLOG10()
-
-
- /**
- * IMLOG2
- *
- * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMLOG2(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the base-2 logarithm.
- * @return string
- */
- public static function IMLOG2($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return log($parsedComplex['real'],2);
- }
-
- return self::IMPRODUCT(log(EULER,2),self::IMLN($complexNumber));
- } // function IMLOG2()
-
-
- /**
- * IMEXP
- *
- * Returns the exponential of a complex number in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMEXP(complexNumber)
- *
- * @param string $complexNumber The complex number for which you want the exponential.
- * @return string
- */
- public static function IMEXP($complexNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
- return '1';
- }
-
- $e = exp($parsedComplex['real']);
- $eX = $e * cos($parsedComplex['imaginary']);
- $eY = $e * sin($parsedComplex['imaginary']);
-
- if ($parsedComplex['suffix'] == '') {
- return self::COMPLEX($eX,$eY);
- } else {
- return self::COMPLEX($eX,$eY,$parsedComplex['suffix']);
- }
- } // function IMEXP()
-
-
- /**
- * IMPOWER
- *
- * Returns a complex number in x + yi or x + yj text format raised to a power.
- *
- * Excel Function:
- * IMPOWER(complexNumber,realNumber)
- *
- * @param string $complexNumber The complex number you want to raise to a power.
- * @param float $realNumber The power to which you want to raise the complex number.
- * @return string
- */
- public static function IMPOWER($complexNumber,$realNumber) {
- $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
- $realNumber = PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
-
- if (!is_numeric($realNumber)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- $parsedComplex = self::_parseComplex($complexNumber);
-
- $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
- $rPower = pow($r,$realNumber);
- $theta = self::IMARGUMENT($complexNumber) * $realNumber;
- if ($theta == 0) {
- return 1;
- } elseif ($parsedComplex['imaginary'] == 0.0) {
- return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
- } else {
- return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
- }
- } // function IMPOWER()
-
-
- /**
- * IMDIV
- *
- * Returns the quotient of two complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMDIV(complexDividend,complexDivisor)
- *
- * @param string $complexDividend The complex numerator or dividend.
- * @param string $complexDivisor The complex denominator or divisor.
- * @return string
- */
- public static function IMDIV($complexDividend,$complexDivisor) {
- $complexDividend = PHPExcel_Calculation_Functions::flattenSingleValue($complexDividend);
- $complexDivisor = PHPExcel_Calculation_Functions::flattenSingleValue($complexDivisor);
-
- $parsedComplexDividend = self::_parseComplex($complexDividend);
- $parsedComplexDivisor = self::_parseComplex($complexDivisor);
-
- if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
- ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
- $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
- }
-
- $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
- $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
- $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
-
- $r = $d1/$d3;
- $i = $d2/$d3;
-
- if ($i > 0.0) {
- return self::_cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
- } elseif ($i < 0.0) {
- return self::_cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
- } else {
- return $r;
- }
- } // function IMDIV()
-
-
- /**
- * IMSUB
- *
- * Returns the difference of two complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSUB(complexNumber1,complexNumber2)
- *
- * @param string $complexNumber1 The complex number from which to subtract complexNumber2.
- * @param string $complexNumber2 The complex number to subtract from complexNumber1.
- * @return string
- */
- public static function IMSUB($complexNumber1,$complexNumber2) {
- $complexNumber1 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber1);
- $complexNumber2 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber2);
-
- $parsedComplex1 = self::_parseComplex($complexNumber1);
- $parsedComplex2 = self::_parseComplex($complexNumber2);
-
- if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
- ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
- $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
- }
-
- $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
- $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
-
- return self::COMPLEX($d1,$d2,$parsedComplex1['suffix']);
- } // function IMSUB()
-
-
- /**
- * IMSUM
- *
- * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMSUM(complexNumber[,complexNumber[,...]])
- *
- * @param string $complexNumber,... Series of complex numbers to add
- * @return string
- */
- public static function IMSUM() {
- // Return value
- $returnValue = self::_parseComplex('0');
- $activeSuffix = '';
-
- // Loop through the arguments
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
- foreach ($aArgs as $arg) {
- $parsedComplex = self::_parseComplex($arg);
-
- if ($activeSuffix == '') {
- $activeSuffix = $parsedComplex['suffix'];
- } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- $returnValue['real'] += $parsedComplex['real'];
- $returnValue['imaginary'] += $parsedComplex['imaginary'];
- }
-
- if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
- return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
- } // function IMSUM()
-
-
- /**
- * IMPRODUCT
- *
- * Returns the product of two or more complex numbers in x + yi or x + yj text format.
- *
- * Excel Function:
- * IMPRODUCT(complexNumber[,complexNumber[,...]])
- *
- * @param string $complexNumber,... Series of complex numbers to multiply
- * @return string
- */
- public static function IMPRODUCT() {
- // Return value
- $returnValue = self::_parseComplex('1');
- $activeSuffix = '';
-
- // Loop through the arguments
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
- foreach ($aArgs as $arg) {
- $parsedComplex = self::_parseComplex($arg);
-
- $workValue = $returnValue;
- if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
- $activeSuffix = $parsedComplex['suffix'];
- } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
- $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
- }
-
- if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
- return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
- } // function IMPRODUCT()
-
-
- /**
- * DELTA
- *
- * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
- * Use this function to filter a set of values. For example, by summing several DELTA
- * functions you calculate the count of equal pairs. This function is also known as the
- * Kronecker Delta function.
- *
- * Excel Function:
- * DELTA(a[,b])
- *
- * @param float $a The first number.
- * @param float $b The second number. If omitted, b is assumed to be zero.
- * @return int
- */
- public static function DELTA($a, $b=0) {
- $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
- $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
-
- return (int) ($a == $b);
- } // function DELTA()
-
-
- /**
- * GESTEP
- *
- * Excel Function:
- * GESTEP(number[,step])
- *
- * Returns 1 if number >= step; returns 0 (zero) otherwise
- * Use this function to filter a set of values. For example, by summing several GESTEP
- * functions you calculate the count of values that exceed a threshold.
- *
- * @param float $number The value to test against step.
- * @param float $step The threshold value.
- * If you omit a value for step, GESTEP uses zero.
- * @return int
- */
- public static function GESTEP($number, $step=0) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $step = PHPExcel_Calculation_Functions::flattenSingleValue($step);
-
- return (int) ($number >= $step);
- } // function GESTEP()
-
-
- //
- // Private method to calculate the erf value
- //
- private static $_two_sqrtpi = 1.128379167095512574;
-
- public static function _erfVal($x) {
- if (abs($x) > 2.2) {
- return 1 - self::_erfcVal($x);
- }
- $sum = $term = $x;
- $xsqr = ($x * $x);
- $j = 1;
- do {
- $term *= $xsqr / $j;
- $sum -= $term / (2 * $j + 1);
- ++$j;
- $term *= $xsqr / $j;
- $sum += $term / (2 * $j + 1);
- ++$j;
- if ($sum == 0.0) {
- break;
- }
- } while (abs($term / $sum) > PRECISION);
- return self::$_two_sqrtpi * $sum;
- } // function _erfVal()
-
-
- /**
- * ERF
- *
- * Returns the error function integrated between the lower and upper bound arguments.
- *
- * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments,
- * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
- * improved, so that it can now calculate the function for both positive and negative ranges.
- * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
- *
- * Excel Function:
- * ERF(lower[,upper])
- *
- * @param float $lower lower bound for integrating ERF
- * @param float $upper upper bound for integrating ERF.
- * If omitted, ERF integrates between zero and lower_limit
- * @return float
- */
- public static function ERF($lower, $upper = NULL) {
- $lower = PHPExcel_Calculation_Functions::flattenSingleValue($lower);
- $upper = PHPExcel_Calculation_Functions::flattenSingleValue($upper);
-
- if (is_numeric($lower)) {
- if (is_null($upper)) {
- return self::_erfVal($lower);
- }
- if (is_numeric($upper)) {
- return self::_erfVal($upper) - self::_erfVal($lower);
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ERF()
-
-
- //
- // Private method to calculate the erfc value
- //
- private static $_one_sqrtpi = 0.564189583547756287;
-
- private static function _erfcVal($x) {
- if (abs($x) < 2.2) {
- return 1 - self::_erfVal($x);
- }
- if ($x < 0) {
- return 2 - self::ERFC(-$x);
- }
- $a = $n = 1;
- $b = $c = $x;
- $d = ($x * $x) + 0.5;
- $q1 = $q2 = $b / $d;
- $t = 0;
- do {
- $t = $a * $n + $b * $x;
- $a = $b;
- $b = $t;
- $t = $c * $n + $d * $x;
- $c = $d;
- $d = $t;
- $n += 0.5;
- $q1 = $q2;
- $q2 = $b / $d;
- } while ((abs($q1 - $q2) / $q2) > PRECISION);
- return self::$_one_sqrtpi * exp(-$x * $x) * $q2;
- } // function _erfcVal()
-
-
- /**
- * ERFC
- *
- * Returns the complementary ERF function integrated between x and infinity
- *
- * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument,
- * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
- * improved, so that it can now calculate the function for both positive and negative x values.
- * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
- *
- * Excel Function:
- * ERFC(x)
- *
- * @param float $x The lower bound for integrating ERFC
- * @return float
- */
- public static function ERFC($x) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
-
- if (is_numeric($x)) {
- return self::_erfcVal($x);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ERFC()
-
-
- /**
- * getConversionGroups
- * Returns a list of the different conversion groups for UOM conversions
- *
- * @return array
- */
- public static function getConversionGroups() {
- $conversionGroups = array();
- foreach(self::$_conversionUnits as $conversionUnit) {
- $conversionGroups[] = $conversionUnit['Group'];
- }
- return array_merge(array_unique($conversionGroups));
- } // function getConversionGroups()
-
-
- /**
- * getConversionGroupUnits
- * Returns an array of units of measure, for a specified conversion group, or for all groups
- *
- * @param string $group The group whose units of measure you want to retrieve
- *
- * @return array
- */
- public static function getConversionGroupUnits($group = NULL) {
- $conversionGroups = array();
- foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
- if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
- $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
- }
- }
- return $conversionGroups;
- } // function getConversionGroupUnits()
-
-
- /**
- * getConversionGroupUnitDetails
- *
- * @return array
- */
- public static function getConversionGroupUnitDetails($group = NULL) {
- $conversionGroups = array();
- foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
- if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
- $conversionGroups[$conversionGroup['Group']][] = array( 'unit' => $conversionUnit,
- 'description' => $conversionGroup['Unit Name']
- );
- }
- }
- return $conversionGroups;
- } // function getConversionGroupUnitDetails()
-
-
- /**
- * getConversionMultipliers
- * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
- *
- * @return array of mixed
- */
- public static function getConversionMultipliers() {
- return self::$_conversionMultipliers;
- } // function getConversionGroups()
-
-
- /**
- * CONVERTUOM
- *
- * Converts a number from one measurement system to another.
- * For example, CONVERT can translate a table of distances in miles to a table of distances
- * in kilometers.
- *
- * Excel Function:
- * CONVERT(value,fromUOM,toUOM)
- *
- * @param float $value The value in fromUOM to convert.
- * @param string $fromUOM The units for value.
- * @param string $toUOM The units for the result.
- *
- * @return float
- */
- public static function CONVERTUOM($value, $fromUOM, $toUOM) {
- $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
- $fromUOM = PHPExcel_Calculation_Functions::flattenSingleValue($fromUOM);
- $toUOM = PHPExcel_Calculation_Functions::flattenSingleValue($toUOM);
-
- if (!is_numeric($value)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $fromMultiplier = 1.0;
- if (isset(self::$_conversionUnits[$fromUOM])) {
- $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
- } else {
- $fromMultiplier = substr($fromUOM,0,1);
- $fromUOM = substr($fromUOM,1);
- if (isset(self::$_conversionMultipliers[$fromMultiplier])) {
- $fromMultiplier = self::$_conversionMultipliers[$fromMultiplier]['multiplier'];
- } else {
- return PHPExcel_Calculation_Functions::NA();
- }
- if ((isset(self::$_conversionUnits[$fromUOM])) && (self::$_conversionUnits[$fromUOM]['AllowPrefix'])) {
- $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
- } else {
- return PHPExcel_Calculation_Functions::NA();
- }
- }
- $value *= $fromMultiplier;
-
- $toMultiplier = 1.0;
- if (isset(self::$_conversionUnits[$toUOM])) {
- $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
- } else {
- $toMultiplier = substr($toUOM,0,1);
- $toUOM = substr($toUOM,1);
- if (isset(self::$_conversionMultipliers[$toMultiplier])) {
- $toMultiplier = self::$_conversionMultipliers[$toMultiplier]['multiplier'];
- } else {
- return PHPExcel_Calculation_Functions::NA();
- }
- if ((isset(self::$_conversionUnits[$toUOM])) && (self::$_conversionUnits[$toUOM]['AllowPrefix'])) {
- $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
- } else {
- return PHPExcel_Calculation_Functions::NA();
- }
- }
- if ($unitGroup1 != $unitGroup2) {
- return PHPExcel_Calculation_Functions::NA();
- }
-
- if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) {
- // We've already factored $fromMultiplier into the value, so we need
- // to reverse it again
- return $value / $fromMultiplier;
- } elseif ($unitGroup1 == 'Temperature') {
- if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
- if (($toUOM == 'F') || ($toUOM == 'fah')) {
- return $value;
- } else {
- $value = (($value - 32) / 1.8);
- if (($toUOM == 'K') || ($toUOM == 'kel')) {
- $value += 273.15;
- }
- return $value;
- }
- } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
- (($toUOM == 'K') || ($toUOM == 'kel'))) {
- return $value;
- } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
- (($toUOM == 'C') || ($toUOM == 'cel'))) {
- return $value;
- }
- if (($toUOM == 'F') || ($toUOM == 'fah')) {
- if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
- $value -= 273.15;
- }
- return ($value * 1.8) + 32;
- }
- if (($toUOM == 'C') || ($toUOM == 'cel')) {
- return $value - 273.15;
- }
- return $value + 273.15;
- }
- return ($value * self::$_unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
- } // function CONVERTUOM()
-
-} // class PHPExcel_Calculation_Engineering
diff --git a/Classes/PHPExcel/Calculation/Exception.php b/Classes/PHPExcel/Calculation/Exception.php
index 9be7e1b65..52d73fc4f 100644
--- a/Classes/PHPExcel/Calculation/Exception.php
+++ b/Classes/PHPExcel/Calculation/Exception.php
@@ -1,8 +1,9 @@
line = $line;
- $e->file = $file;
- throw $e;
- }
+class PHPExcel_Calculation_Exception extends PHPExcel_Exception
+{
+ /**
+ * Error handler callback
+ *
+ * @param mixed $code
+ * @param mixed $string
+ * @param mixed $file
+ * @param mixed $line
+ * @param mixed $context
+ */
+ public static function errorHandlerCallback($code, $string, $file, $line, $context)
+ {
+ $e = new self($string, $code);
+ $e->line = $line;
+ $e->file = $file;
+ throw $e;
+ }
}
diff --git a/Classes/PHPExcel/Calculation/ExceptionHandler.php b/Classes/PHPExcel/Calculation/ExceptionHandler.php
index 68c122410..4cb0a6880 100644
--- a/Classes/PHPExcel/Calculation/ExceptionHandler.php
+++ b/Classes/PHPExcel/Calculation/ExceptionHandler.php
@@ -1,8 +1,9 @@
format('d') == $testDate->format('t'));
- } // function _lastDayOfMonth()
-
-
- /**
- * _firstDayOfMonth
- *
- * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month
- *
- * @param DateTime $testDate The date for testing
- * @return boolean
- */
- private static function _firstDayOfMonth($testDate)
- {
- return ($testDate->format('d') == 1);
- } // function _firstDayOfMonth()
-
-
- private static function _coupFirstPeriodDate($settlement, $maturity, $frequency, $next)
- {
- $months = 12 / $frequency;
-
- $result = PHPExcel_Shared_Date::ExcelToPHPObject($maturity);
- $eom = self::_lastDayOfMonth($result);
-
- while ($settlement < PHPExcel_Shared_Date::PHPToExcel($result)) {
- $result->modify('-'.$months.' months');
- }
- if ($next) {
- $result->modify('+'.$months.' months');
- }
-
- if ($eom) {
- $result->modify('-1 day');
- }
-
- return PHPExcel_Shared_Date::PHPToExcel($result);
- } // function _coupFirstPeriodDate()
-
-
- private static function _validFrequency($frequency)
- {
- if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
- return true;
- }
- if ((PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) &&
- (($frequency == 6) || ($frequency == 12))) {
- return true;
- }
- return false;
- } // function _validFrequency()
-
-
- /**
- * _daysPerYear
- *
- * Returns the number of days in a specified year, as defined by the "basis" value
- *
- * @param integer $year The year against which we're testing
- * @param integer $basis The type of day count:
- * 0 or omitted US (NASD) 360
- * 1 Actual (365 or 366 in a leap year)
- * 2 360
- * 3 365
- * 4 European 360
- * @return integer
- */
- private static function _daysPerYear($year, $basis=0)
- {
- switch ($basis) {
- case 0 :
- case 2 :
- case 4 :
- $daysPerYear = 360;
- break;
- case 3 :
- $daysPerYear = 365;
- break;
- case 1 :
- $daysPerYear = (PHPExcel_Calculation_DateTime::_isLeapYear($year)) ? 366 : 365;
- break;
- default :
- return PHPExcel_Calculation_Functions::NaN();
- }
- return $daysPerYear;
- } // function _daysPerYear()
-
-
- private static function _interestAndPrincipal($rate=0, $per=0, $nper=0, $pv=0, $fv=0, $type=0)
- {
- $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
- $capital = $pv;
- for ($i = 1; $i<= $per; ++$i) {
- $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
- $principal = $pmt - $interest;
- $capital += $principal;
- }
- return array($interest, $principal);
- } // function _interestAndPrincipal()
-
-
- /**
- * ACCRINT
- *
- * Returns the accrued interest for a security that pays periodic interest.
- *
- * Excel Function:
- * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed $issue The security's issue date.
- * @param mixed $firstinterest The security's first interest date.
- * @param mixed $settlement The security's settlement date.
- * The security settlement date is the date after the issue date
- * when the security is traded to the buyer.
- * @param float $rate The security's annual coupon rate.
- * @param float $par The security's par value.
- * If you omit par, ACCRINT uses $1,000.
- * @param integer $frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer $basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par=1000, $frequency=1, $basis=0)
- {
- $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
- $firstinterest = PHPExcel_Calculation_Functions::flattenSingleValue($firstinterest);
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
- $frequency = (is_null($frequency)) ? 1 : PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($rate)) && (is_numeric($par))) {
- $rate = (float) $rate;
- $par = (float) $par;
- if (($rate <= 0) || ($par <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
-
- return $par * $rate * $daysBetweenIssueAndSettlement;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ACCRINT()
-
-
- /**
- * ACCRINTM
- *
- * Returns the accrued interest for a security that pays interest at maturity.
- *
- * Excel Function:
- * ACCRINTM(issue,settlement,rate[,par[,basis]])
- *
- * @access public
- * @category Financial Functions
- * @param mixed issue The security's issue date.
- * @param mixed settlement The security's settlement (or maturity) date.
- * @param float rate The security's annual coupon rate.
- * @param float par The security's par value.
- * If you omit par, ACCRINT uses $1,000.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function ACCRINTM($issue, $settlement, $rate, $par=1000, $basis=0) {
- $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
- $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($rate)) && (is_numeric($par))) {
- $rate = (float) $rate;
- $par = (float) $par;
- if (($rate <= 0) || ($par <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- return $par * $rate * $daysBetweenIssueAndSettlement;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ACCRINTM()
-
-
- /**
- * AMORDEGRC
- *
- * Returns the depreciation for each accounting period.
- * This function is provided for the French accounting system. If an asset is purchased in
- * the middle of the accounting period, the prorated depreciation is taken into account.
- * The function is similar to AMORLINC, except that a depreciation coefficient is applied in
- * the calculation depending on the life of the assets.
- * This function will return the depreciation until the last period of the life of the assets
- * or until the cumulated value of depreciation is greater than the cost of the assets minus
- * the salvage value.
- *
- * Excel Function:
- * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param float cost The cost of the asset.
- * @param mixed purchased Date of the purchase of the asset.
- * @param mixed firstPeriod Date of the end of the first period.
- * @param mixed salvage The salvage value at the end of the life of the asset.
- * @param float period The period.
- * @param float rate Rate of depreciation.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
- $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
- $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
- $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
- $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
- $period = floor(PHPExcel_Calculation_Functions::flattenSingleValue($period));
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // The depreciation coefficients are:
- // Life of assets (1/rate) Depreciation coefficient
- // Less than 3 years 1
- // Between 3 and 4 years 1.5
- // Between 5 and 6 years 2
- // More than 6 years 2.5
- $fUsePer = 1.0 / $rate;
- if ($fUsePer < 3.0) {
- $amortiseCoeff = 1.0;
- } elseif ($fUsePer < 5.0) {
- $amortiseCoeff = 1.5;
- } elseif ($fUsePer <= 6.0) {
- $amortiseCoeff = 2.0;
- } else {
- $amortiseCoeff = 2.5;
- }
-
- $rate *= $amortiseCoeff;
- $fNRate = round(PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost,0);
- $cost -= $fNRate;
- $fRest = $cost - $salvage;
-
- for ($n = 0; $n < $period; ++$n) {
- $fNRate = round($rate * $cost,0);
- $fRest -= $fNRate;
-
- if ($fRest < 0.0) {
- switch ($period - $n) {
- case 0 :
- case 1 : return round($cost * 0.5, 0);
- break;
- default : return 0.0;
- break;
- }
- }
- $cost -= $fNRate;
- }
- return $fNRate;
- } // function AMORDEGRC()
-
-
- /**
- * AMORLINC
- *
- * Returns the depreciation for each accounting period.
- * This function is provided for the French accounting system. If an asset is purchased in
- * the middle of the accounting period, the prorated depreciation is taken into account.
- *
- * Excel Function:
- * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param float cost The cost of the asset.
- * @param mixed purchased Date of the purchase of the asset.
- * @param mixed firstPeriod Date of the end of the first period.
- * @param mixed salvage The salvage value at the end of the life of the asset.
- * @param float period The period.
- * @param float rate Rate of depreciation.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
- $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
- $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
- $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
- $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
- $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- $fOneRate = $cost * $rate;
- $fCostDelta = $cost - $salvage;
- // Note, quirky variation for leap years on the YEARFRAC for this function
- $purchasedYear = PHPExcel_Calculation_DateTime::YEAR($purchased);
- $yearFrac = PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
-
- if (($basis == 1) && ($yearFrac < 1) && (PHPExcel_Calculation_DateTime::_isLeapYear($purchasedYear))) {
- $yearFrac *= 365 / 366;
- }
-
- $f0Rate = $yearFrac * $rate * $cost;
- $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
-
- if ($period == 0) {
- return $f0Rate;
- } elseif ($period <= $nNumOfFullPeriods) {
- return $fOneRate;
- } elseif ($period == ($nNumOfFullPeriods + 1)) {
+class PHPExcel_Calculation_Financial
+{
+ /**
+ * isLastDayOfMonth
+ *
+ * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month
+ *
+ * @param DateTime $testDate The date for testing
+ * @return boolean
+ */
+ private static function isLastDayOfMonth($testDate)
+ {
+ return ($testDate->format('d') == $testDate->format('t'));
+ }
+
+
+ /**
+ * isFirstDayOfMonth
+ *
+ * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month
+ *
+ * @param DateTime $testDate The date for testing
+ * @return boolean
+ */
+ private static function isFirstDayOfMonth($testDate)
+ {
+ return ($testDate->format('d') == 1);
+ }
+
+
+ private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next)
+ {
+ $months = 12 / $frequency;
+
+ $result = PHPExcel_Shared_Date::ExcelToPHPObject($maturity);
+ $eom = self::isLastDayOfMonth($result);
+
+ while ($settlement < PHPExcel_Shared_Date::PHPToExcel($result)) {
+ $result->modify('-'.$months.' months');
+ }
+ if ($next) {
+ $result->modify('+'.$months.' months');
+ }
+
+ if ($eom) {
+ $result->modify('-1 day');
+ }
+
+ return PHPExcel_Shared_Date::PHPToExcel($result);
+ }
+
+
+ private static function isValidFrequency($frequency)
+ {
+ if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
+ return true;
+ }
+ if ((PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) &&
+ (($frequency == 6) || ($frequency == 12))) {
+ return true;
+ }
+ return false;
+ }
+
+
+ /**
+ * daysPerYear
+ *
+ * Returns the number of days in a specified year, as defined by the "basis" value
+ *
+ * @param integer $year The year against which we're testing
+ * @param integer $basis The type of day count:
+ * 0 or omitted US (NASD) 360
+ * 1 Actual (365 or 366 in a leap year)
+ * 2 360
+ * 3 365
+ * 4 European 360
+ * @return integer
+ */
+ private static function daysPerYear($year, $basis = 0)
+ {
+ switch ($basis) {
+ case 0:
+ case 2:
+ case 4:
+ $daysPerYear = 360;
+ break;
+ case 3:
+ $daysPerYear = 365;
+ break;
+ case 1:
+ $daysPerYear = (PHPExcel_Calculation_DateTime::isLeapYear($year)) ? 366 : 365;
+ break;
+ default:
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return $daysPerYear;
+ }
+
+
+ private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0)
+ {
+ $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
+ $capital = $pv;
+ for ($i = 1; $i<= $per; ++$i) {
+ $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
+ $principal = $pmt - $interest;
+ $capital += $principal;
+ }
+ return array($interest, $principal);
+ }
+
+
+ /**
+ * ACCRINT
+ *
+ * Returns the accrued interest for a security that pays periodic interest.
+ *
+ * Excel Function:
+ * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed $issue The security's issue date.
+ * @param mixed $firstinterest The security's first interest date.
+ * @param mixed $settlement The security's settlement date.
+ * The security settlement date is the date after the issue date
+ * when the security is traded to the buyer.
+ * @param float $rate The security's annual coupon rate.
+ * @param float $par The security's par value.
+ * If you omit par, ACCRINT uses $1,000.
+ * @param integer $frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer $basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par = 1000, $frequency = 1, $basis = 0)
+ {
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
+ $firstinterest = PHPExcel_Calculation_Functions::flattenSingleValue($firstinterest);
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
+ $frequency = (is_null($frequency)) ? 1 : PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($rate)) && (is_numeric($par))) {
+ $rate = (float) $rate;
+ $par = (float) $par;
+ if (($rate <= 0) || ($par <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+
+ return $par * $rate * $daysBetweenIssueAndSettlement;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * ACCRINTM
+ *
+ * Returns the accrued interest for a security that pays interest at maturity.
+ *
+ * Excel Function:
+ * ACCRINTM(issue,settlement,rate[,par[,basis]])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed issue The security's issue date.
+ * @param mixed settlement The security's settlement (or maturity) date.
+ * @param float rate The security's annual coupon rate.
+ * @param float par The security's par value.
+ * If you omit par, ACCRINT uses $1,000.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis = 0)
+ {
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
+ $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($rate)) && (is_numeric($par))) {
+ $rate = (float) $rate;
+ $par = (float) $par;
+ if (($rate <= 0) || ($par <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ return $par * $rate * $daysBetweenIssueAndSettlement;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * AMORDEGRC
+ *
+ * Returns the depreciation for each accounting period.
+ * This function is provided for the French accounting system. If an asset is purchased in
+ * the middle of the accounting period, the prorated depreciation is taken into account.
+ * The function is similar to AMORLINC, except that a depreciation coefficient is applied in
+ * the calculation depending on the life of the assets.
+ * This function will return the depreciation until the last period of the life of the assets
+ * or until the cumulated value of depreciation is greater than the cost of the assets minus
+ * the salvage value.
+ *
+ * Excel Function:
+ * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost The cost of the asset.
+ * @param mixed purchased Date of the purchase of the asset.
+ * @param mixed firstPeriod Date of the end of the first period.
+ * @param mixed salvage The salvage value at the end of the life of the asset.
+ * @param float period The period.
+ * @param float rate Rate of depreciation.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0)
+ {
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
+ $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
+ $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
+ $period = floor(PHPExcel_Calculation_Functions::flattenSingleValue($period));
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // The depreciation coefficients are:
+ // Life of assets (1/rate) Depreciation coefficient
+ // Less than 3 years 1
+ // Between 3 and 4 years 1.5
+ // Between 5 and 6 years 2
+ // More than 6 years 2.5
+ $fUsePer = 1.0 / $rate;
+ if ($fUsePer < 3.0) {
+ $amortiseCoeff = 1.0;
+ } elseif ($fUsePer < 5.0) {
+ $amortiseCoeff = 1.5;
+ } elseif ($fUsePer <= 6.0) {
+ $amortiseCoeff = 2.0;
+ } else {
+ $amortiseCoeff = 2.5;
+ }
+
+ $rate *= $amortiseCoeff;
+ $fNRate = round(PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost, 0);
+ $cost -= $fNRate;
+ $fRest = $cost - $salvage;
+
+ for ($n = 0; $n < $period; ++$n) {
+ $fNRate = round($rate * $cost, 0);
+ $fRest -= $fNRate;
+
+ if ($fRest < 0.0) {
+ switch ($period - $n) {
+ case 0:
+ case 1:
+ return round($cost * 0.5, 0);
+ default:
+ return 0.0;
+ }
+ }
+ $cost -= $fNRate;
+ }
+ return $fNRate;
+ }
+
+
+ /**
+ * AMORLINC
+ *
+ * Returns the depreciation for each accounting period.
+ * This function is provided for the French accounting system. If an asset is purchased in
+ * the middle of the accounting period, the prorated depreciation is taken into account.
+ *
+ * Excel Function:
+ * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost The cost of the asset.
+ * @param mixed purchased Date of the purchase of the asset.
+ * @param mixed firstPeriod Date of the end of the first period.
+ * @param mixed salvage The salvage value at the end of the life of the asset.
+ * @param float period The period.
+ * @param float rate Rate of depreciation.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0)
+ {
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
+ $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
+ $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ $fOneRate = $cost * $rate;
+ $fCostDelta = $cost - $salvage;
+ // Note, quirky variation for leap years on the YEARFRAC for this function
+ $purchasedYear = PHPExcel_Calculation_DateTime::YEAR($purchased);
+ $yearFrac = PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
+
+ if (($basis == 1) && ($yearFrac < 1) && (PHPExcel_Calculation_DateTime::isLeapYear($purchasedYear))) {
+ $yearFrac *= 365 / 366;
+ }
+
+ $f0Rate = $yearFrac * $rate * $cost;
+ $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
+
+ if ($period == 0) {
+ return $f0Rate;
+ } elseif ($period <= $nNumOfFullPeriods) {
+ return $fOneRate;
+ } elseif ($period == ($nNumOfFullPeriods + 1)) {
return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate);
- } else {
- return 0.0;
- }
- } // function AMORLINC()
-
-
- /**
- * COUPDAYBS
- *
- * Returns the number of days from the beginning of the coupon period to the settlement date.
- *
- * Excel Function:
- * COUPDAYBS(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function COUPDAYBS($settlement, $maturity, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
- $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
-
- return PHPExcel_Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
- } // function COUPDAYBS()
-
-
- /**
- * COUPDAYS
- *
- * Returns the number of days in the coupon period that contains the settlement date.
- *
- * Excel Function:
- * COUPDAYS(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function COUPDAYS($settlement, $maturity, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- switch ($basis) {
- case 3: // Actual/365
- return 365 / $frequency;
- case 1: // Actual/actual
- if ($frequency == 1) {
- $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($maturity),$basis);
- return ($daysPerYear / $frequency);
- } else {
- $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
- $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
- return ($next - $prev);
- }
- default: // US (NASD) 30/360, Actual/360 or European 30/360
- return 360 / $frequency;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function COUPDAYS()
-
-
- /**
- * COUPDAYSNC
- *
- * Returns the number of days from the settlement date to the next coupon date.
- *
- * Excel Function:
- * COUPDAYSNC(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
- $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
-
- return PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
- } // function COUPDAYSNC()
-
-
- /**
- * COUPNCD
- *
- * Returns the next coupon date after the settlement date.
- *
- * Excel Function:
- * COUPNCD(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function COUPNCD($settlement, $maturity, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
- } // function COUPNCD()
-
-
- /**
- * COUPNUM
- *
- * Returns the number of coupons payable between the settlement date and maturity date,
- * rounded up to the nearest whole coupon.
- *
- * Excel Function:
- * COUPNUM(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return integer
- */
- public static function COUPNUM($settlement, $maturity, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $settlement = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365;
-
- switch ($frequency) {
- case 1: // annual payments
- return ceil($daysBetweenSettlementAndMaturity / 360);
- case 2: // half-yearly
- return ceil($daysBetweenSettlementAndMaturity / 180);
- case 4: // quarterly
- return ceil($daysBetweenSettlementAndMaturity / 90);
- case 6: // bimonthly
- return ceil($daysBetweenSettlementAndMaturity / 60);
- case 12: // monthly
- return ceil($daysBetweenSettlementAndMaturity / 30);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function COUPNUM()
-
-
- /**
- * COUPPCD
- *
- * Returns the previous coupon date before the settlement date.
- *
- * Excel Function:
- * COUPPCD(settlement,maturity,frequency[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed frequency the number of coupon payments per year.
- * Valid frequency values are:
- * 1 Annual
- * 2 Semi-Annual
- * 4 Quarterly
- * If working in Gnumeric Mode, the following frequency options are
- * also available
- * 6 Bimonthly
- * 12 Monthly
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
- * depending on the value of the ReturnDateType flag
- */
- public static function COUPPCD($settlement, $maturity, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
- } // function COUPPCD()
-
-
- /**
- * CUMIPMT
- *
- * Returns the cumulative interest paid on a loan between the start and end periods.
- *
- * Excel Function:
- * CUMIPMT(rate,nper,pv,start,end[,type])
- *
- * @access public
- * @category Financial Functions
- * @param float $rate The Interest rate
- * @param integer $nper The total number of payment periods
- * @param float $pv Present Value
- * @param integer $start The first period in the calculation.
- * Payment periods are numbered beginning with 1.
- * @param integer $end The last period in the calculation.
- * @param integer $type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @return float
- */
- public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
- $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
- $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ($start < 1 || $start > $end) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Calculate
- $interest = 0;
- for ($per = $start; $per <= $end; ++$per) {
- $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
- }
-
- return $interest;
- } // function CUMIPMT()
-
-
- /**
- * CUMPRINC
- *
- * Returns the cumulative principal paid on a loan between the start and end periods.
- *
- * Excel Function:
- * CUMPRINC(rate,nper,pv,start,end[,type])
- *
- * @access public
- * @category Financial Functions
- * @param float $rate The Interest rate
- * @param integer $nper The total number of payment periods
- * @param float $pv Present Value
- * @param integer $start The first period in the calculation.
- * Payment periods are numbered beginning with 1.
- * @param integer $end The last period in the calculation.
- * @param integer $type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @return float
- */
- public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
- $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
- $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ($start < 1 || $start > $end) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Calculate
- $principal = 0;
- for ($per = $start; $per <= $end; ++$per) {
- $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
- }
-
- return $principal;
- } // function CUMPRINC()
-
-
- /**
- * DB
- *
- * Returns the depreciation of an asset for a specified period using the
- * fixed-declining balance method.
- * This form of depreciation is used if you want to get a higher depreciation value
- * at the beginning of the depreciation (as opposed to linear depreciation). The
- * depreciation value is reduced with every depreciation period by the depreciation
- * already deducted from the initial cost.
- *
- * Excel Function:
- * DB(cost,salvage,life,period[,month])
- *
- * @access public
- * @category Financial Functions
- * @param float cost Initial cost of the asset.
- * @param float salvage Value at the end of the depreciation.
- * (Sometimes called the salvage value of the asset)
- * @param integer life Number of periods over which the asset is depreciated.
- * (Sometimes called the useful life of the asset)
- * @param integer period The period for which you want to calculate the
- * depreciation. Period must use the same units as life.
- * @param integer month Number of months in the first year. If month is omitted,
- * it defaults to 12.
- * @return float
- */
- public static function DB($cost, $salvage, $life, $period, $month=12) {
- $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
- $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
- $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
- $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
- $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
-
- // Validate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
- $cost = (float) $cost;
- $salvage = (float) $salvage;
- $life = (int) $life;
- $period = (int) $period;
- $month = (int) $month;
- if ($cost == 0) {
- return 0.0;
- } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- // Set Fixed Depreciation Rate
- $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
- $fixedDepreciationRate = round($fixedDepreciationRate, 3);
-
- // Loop through each period calculating the depreciation
- $previousDepreciation = 0;
- for ($per = 1; $per <= $period; ++$per) {
- if ($per == 1) {
- $depreciation = $cost * $fixedDepreciationRate * $month / 12;
- } elseif ($per == ($life + 1)) {
- $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
- } else {
- $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
- }
- $previousDepreciation += $depreciation;
- }
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $depreciation = round($depreciation,2);
- }
- return $depreciation;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function DB()
-
-
- /**
- * DDB
- *
- * Returns the depreciation of an asset for a specified period using the
- * double-declining balance method or some other method you specify.
- *
- * Excel Function:
- * DDB(cost,salvage,life,period[,factor])
- *
- * @access public
- * @category Financial Functions
- * @param float cost Initial cost of the asset.
- * @param float salvage Value at the end of the depreciation.
- * (Sometimes called the salvage value of the asset)
- * @param integer life Number of periods over which the asset is depreciated.
- * (Sometimes called the useful life of the asset)
- * @param integer period The period for which you want to calculate the
- * depreciation. Period must use the same units as life.
- * @param float factor The rate at which the balance declines.
- * If factor is omitted, it is assumed to be 2 (the
- * double-declining balance method).
- * @return float
- */
- public static function DDB($cost, $salvage, $life, $period, $factor=2.0) {
- $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
- $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
- $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
- $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
- $factor = PHPExcel_Calculation_Functions::flattenSingleValue($factor);
-
- // Validate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
- $cost = (float) $cost;
- $salvage = (float) $salvage;
- $life = (int) $life;
- $period = (int) $period;
- $factor = (float) $factor;
- if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- // Set Fixed Depreciation Rate
- $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
- $fixedDepreciationRate = round($fixedDepreciationRate, 3);
-
- // Loop through each period calculating the depreciation
- $previousDepreciation = 0;
- for ($per = 1; $per <= $period; ++$per) {
- $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) );
- $previousDepreciation += $depreciation;
- }
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- $depreciation = round($depreciation,2);
- }
- return $depreciation;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function DDB()
-
-
- /**
- * DISC
- *
- * Returns the discount rate for a security.
- *
- * Excel Function:
- * DISC(settlement,maturity,price,redemption[,basis])
- *
- * @access public
- * @category Financial Functions
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue
- * date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param integer price The security's price per $100 face value.
- * @param integer redemption The security's redemption value per $100 face value.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function DISC($settlement, $maturity, $price, $redemption, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
- $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
- $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- $price = (float) $price;
- $redemption = (float) $redemption;
- $basis = (int) $basis;
- if (($price <= 0) || ($redemption <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function DISC()
-
-
- /**
- * DOLLARDE
- *
- * Converts a dollar price expressed as an integer part and a fraction
- * part into a dollar price expressed as a decimal number.
- * Fractional dollar numbers are sometimes used for security prices.
- *
- * Excel Function:
- * DOLLARDE(fractional_dollar,fraction)
- *
- * @access public
- * @category Financial Functions
- * @param float $fractional_dollar Fractional Dollar
- * @param integer $fraction Fraction
- * @return float
- */
- public static function DOLLARDE($fractional_dollar = Null, $fraction = 0) {
- $fractional_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($fractional_dollar);
- $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
-
- // Validate parameters
- if (is_null($fractional_dollar) || $fraction < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ($fraction == 0) {
- return PHPExcel_Calculation_Functions::DIV0();
- }
-
- $dollars = floor($fractional_dollar);
- $cents = fmod($fractional_dollar,1);
- $cents /= $fraction;
- $cents *= pow(10,ceil(log10($fraction)));
- return $dollars + $cents;
- } // function DOLLARDE()
-
-
- /**
- * DOLLARFR
- *
- * Converts a dollar price expressed as a decimal number into a dollar price
- * expressed as a fraction.
- * Fractional dollar numbers are sometimes used for security prices.
- *
- * Excel Function:
- * DOLLARFR(decimal_dollar,fraction)
- *
- * @access public
- * @category Financial Functions
- * @param float $decimal_dollar Decimal Dollar
- * @param integer $fraction Fraction
- * @return float
- */
- public static function DOLLARFR($decimal_dollar = Null, $fraction = 0) {
- $decimal_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($decimal_dollar);
- $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
-
- // Validate parameters
- if (is_null($decimal_dollar) || $fraction < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ($fraction == 0) {
- return PHPExcel_Calculation_Functions::DIV0();
- }
-
- $dollars = floor($decimal_dollar);
- $cents = fmod($decimal_dollar,1);
- $cents *= $fraction;
- $cents *= pow(10,-ceil(log10($fraction)));
- return $dollars + $cents;
- } // function DOLLARFR()
-
-
- /**
- * EFFECT
- *
- * Returns the effective interest rate given the nominal rate and the number of
- * compounding payments per year.
- *
- * Excel Function:
- * EFFECT(nominal_rate,npery)
- *
- * @access public
- * @category Financial Functions
- * @param float $nominal_rate Nominal interest rate
- * @param integer $npery Number of compounding payments per year
- * @return float
- */
- public static function EFFECT($nominal_rate = 0, $npery = 0) {
- $nominal_rate = PHPExcel_Calculation_Functions::flattenSingleValue($nominal_rate);
- $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
-
- // Validate parameters
- if ($nominal_rate <= 0 || $npery < 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return pow((1 + $nominal_rate / $npery), $npery) - 1;
- } // function EFFECT()
-
-
- /**
- * FV
- *
- * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
- *
- * Excel Function:
- * FV(rate,nper,pmt[,pv[,type]])
- *
- * @access public
- * @category Financial Functions
- * @param float $rate The interest rate per period
- * @param int $nper Total number of payment periods in an annuity
- * @param float $pmt The payment made each period: it cannot change over the
- * life of the annuity. Typically, pmt contains principal
- * and interest but no other fees or taxes.
- * @param float $pv Present Value, or the lump-sum amount that a series of
- * future payments is worth right now.
- * @param integer $type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @return float
- */
- public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
- } else {
- return -$pv - $pmt * $nper;
- }
- } // function FV()
-
-
- /**
- * FVSCHEDULE
- *
- */
- public static function FVSCHEDULE($principal, $schedule) {
- $principal = PHPExcel_Calculation_Functions::flattenSingleValue($principal);
- $schedule = PHPExcel_Calculation_Functions::flattenArray($schedule);
-
- foreach($schedule as $n) {
- $principal *= 1 + $n;
- }
-
- return $principal;
- } // function FVSCHEDULE()
-
-
- /**
- * INTRATE
- *
- * Returns the interest rate for a fully invested security.
- *
- * Excel Function:
- * INTRATE(settlement,maturity,investment,redemption[,basis])
- *
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param integer investment The amount invested in the security.
- * @param integer redemption The amount to be received at maturity.
- * @param integer basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $investment = PHPExcel_Calculation_Functions::flattenSingleValue($investment);
- $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
- $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- $investment = (float) $investment;
- $redemption = (float) $redemption;
- $basis = (int) $basis;
- if (($investment <= 0) || ($redemption <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function INTRATE()
-
-
- /**
- * IPMT
- *
- * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $per Period for which we want to find the interest
- * @param int $nper Number of periods
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
- $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
- $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ($per <= 0 || $per > $nper) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Calculate
- $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
- return $interestAndPrincipal[0];
- } // function IPMT()
-
-
- public static function IRR($values, $guess = 0.1) {
- if (!is_array($values)) return PHPExcel_Calculation_Functions::VALUE();
- $values = PHPExcel_Calculation_Functions::flattenArray($values);
- $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
-
- // create an initial range, with a root somewhere between 0 and guess
- $x1 = 0.0;
- $x2 = $guess;
- $f1 = self::NPV($x1, $values);
- $f2 = self::NPV($x2, $values);
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- if (($f1 * $f2) < 0.0) break;
- if (abs($f1) < abs($f2)) {
- $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
- } else {
- $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
- }
- }
- if (($f1 * $f2) > 0.0) return PHPExcel_Calculation_Functions::VALUE();
-
- $f = self::NPV($x1, $values);
- if ($f < 0.0) {
- $rtb = $x1;
- $dx = $x2 - $x1;
- } else {
- $rtb = $x2;
- $dx = $x1 - $x2;
- }
-
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- $dx *= 0.5;
- $x_mid = $rtb + $dx;
- $f_mid = self::NPV($x_mid, $values);
- if ($f_mid <= 0.0) $rtb = $x_mid;
- if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function IRR()
-
-
- /**
- * ISPMT
- *
- * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
- *
- * Excel Function:
- * =ISPMT(interest_rate, period, number_payments, PV)
- *
- * interest_rate is the interest rate for the investment
- *
- * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
- *
- * number_payments is the number of payments for the annuity
- *
- * PV is the loan amount or present value of the payments
- */
- public static function ISPMT() {
- // Return value
- $returnValue = 0;
-
- // Get the parameters
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
- $interestRate = array_shift($aArgs);
- $period = array_shift($aArgs);
- $numberPeriods = array_shift($aArgs);
- $principleRemaining = array_shift($aArgs);
-
- // Calculate
- $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
- for($i=0; $i <= $period; ++$i) {
- $returnValue = $interestRate * $principleRemaining * -1;
- $principleRemaining -= $principlePayment;
- // principle needs to be 0 after the last payment, don't let floating point screw it up
- if($i == $numberPeriods) {
- $returnValue = 0;
- }
- }
- return($returnValue);
- } // function ISPMT()
-
-
- public static function MIRR($values, $finance_rate, $reinvestment_rate) {
- if (!is_array($values)) return PHPExcel_Calculation_Functions::VALUE();
- $values = PHPExcel_Calculation_Functions::flattenArray($values);
- $finance_rate = PHPExcel_Calculation_Functions::flattenSingleValue($finance_rate);
- $reinvestment_rate = PHPExcel_Calculation_Functions::flattenSingleValue($reinvestment_rate);
- $n = count($values);
-
- $rr = 1.0 + $reinvestment_rate;
- $fr = 1.0 + $finance_rate;
-
- $npv_pos = $npv_neg = 0.0;
- foreach($values as $i => $v) {
- if ($v >= 0) {
- $npv_pos += $v / pow($rr, $i);
- } else {
- $npv_neg += $v / pow($fr, $i);
- }
- }
-
- if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- $mirr = pow((-$npv_pos * pow($rr, $n))
- / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
-
- return (is_finite($mirr) ? $mirr : PHPExcel_Calculation_Functions::VALUE());
- } // function MIRR()
-
-
- /**
- * NOMINAL
- *
- * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
- *
- * @param float $effect_rate Effective interest rate
- * @param int $npery Number of compounding payments per year
- * @return float
- */
- public static function NOMINAL($effect_rate = 0, $npery = 0) {
- $effect_rate = PHPExcel_Calculation_Functions::flattenSingleValue($effect_rate);
- $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
-
- // Validate parameters
- if ($effect_rate <= 0 || $npery < 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Calculate
- return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
- } // function NOMINAL()
-
-
- /**
- * NPER
- *
- * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $pmt Periodic payment (annuity)
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
- $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- if ($pmt == 0 && $pv == 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
- } else {
- if ($pmt == 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return (-$pv -$fv) / $pmt;
- }
- } // function NPER()
-
-
- /**
- * NPV
- *
- * Returns the Net Present Value of a cash flow series given a discount rate.
- *
- * @param float Discount interest rate
- * @param array Cash flow series
- * @return float
- */
- public static function NPV() {
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
-
- // Calculate
- $rate = array_shift($aArgs);
- for ($i = 1; $i <= count($aArgs); ++$i) {
- // Is it a numeric value?
- if (is_numeric($aArgs[$i - 1])) {
- $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
- }
- }
-
- // Return
- return $returnValue;
- } // function NPV()
-
-
- /**
- * PMT
- *
- * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $nper Number of periods
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
- $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
- } else {
- return (-$pv - $fv) / $nper;
- }
- } // function PMT()
-
-
- /**
- * PPMT
- *
- * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
- *
- * @param float $rate Interest rate per period
- * @param int $per Period for which we want to find the interest
- * @param int $nper Number of periods
- * @param float $pv Present Value
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
- $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
- $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- if ($per <= 0 || $per > $nper) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Calculate
- $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
- return $interestAndPrincipal[1];
- } // function PPMT()
-
-
- public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $rate = (float) PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $yield = (float) PHPExcel_Calculation_Functions::flattenSingleValue($yield);
- $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
- $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
- $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (($settlement > $maturity) ||
- (!self::_validFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
- $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
- $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
- $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis);
-
- $baseYF = 1.0 + ($yield / $frequency);
- $rfp = 100 * ($rate / $frequency);
- $de = $dsc / $e;
-
- $result = $redemption / pow($baseYF, (--$n + $de));
- for($k = 0; $k <= $n; ++$k) {
- $result += $rfp / (pow($baseYF, ($k + $de)));
- }
- $result -= $rfp * ($a / $e);
-
- return $result;
- } // function PRICE()
-
-
- /**
- * PRICEDISC
- *
- * Returns the price per $100 face value of a discounted security.
- *
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param int discount The security's discount rate.
- * @param int redemption The security's redemption value per $100 face value.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
- $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
- $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- if (($discount <= 0) || ($redemption <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function PRICEDISC()
-
-
- /**
- * PRICEMAT
- *
- * Returns the price per $100 face value of a security that pays interest at maturity.
- *
- * @param mixed settlement The security's settlement date.
- * The security's settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed issue The security's issue date.
- * @param int rate The security's interest rate at date of issue.
- * @param int yield The security's annual yield.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $yield = PHPExcel_Calculation_Functions::flattenSingleValue($yield);
- $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($rate) && is_numeric($yield)) {
- if (($rate <= 0) || ($yield <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- $daysBetweenIssueAndSettlement *= $daysPerYear;
- $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
- if (!is_numeric($daysBetweenIssueAndMaturity)) {
- // return date error
- return $daysBetweenIssueAndMaturity;
- }
- $daysBetweenIssueAndMaturity *= $daysPerYear;
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
- (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
- (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function PRICEMAT()
-
-
- /**
- * PV
- *
- * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
- *
- * @param float $rate Interest rate per period
- * @param int $nper Number of periods
- * @param float $pmt Periodic payment (annuity)
- * @param float $fv Future Value
- * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
- * @return float
- */
- public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
- $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
- $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- // Calculate
- if (!is_null($rate) && $rate != 0) {
- return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
- } else {
- return -$fv - $pmt * $nper;
- }
- } // function PV()
-
-
- /**
- * RATE
- *
- * Returns the interest rate per period of an annuity.
- * RATE is calculated by iteration and can have zero or more solutions.
- * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations,
- * RATE returns the #NUM! error value.
- *
- * Excel Function:
- * RATE(nper,pmt,pv[,fv[,type[,guess]]])
- *
- * @access public
- * @category Financial Functions
- * @param float nper The total number of payment periods in an annuity.
- * @param float pmt The payment made each period and cannot change over the life
- * of the annuity.
- * Typically, pmt includes principal and interest but no other
- * fees or taxes.
- * @param float pv The present value - the total amount that a series of future
- * payments is worth now.
- * @param float fv The future value, or a cash balance you want to attain after
- * the last payment is made. If fv is omitted, it is assumed
- * to be 0 (the future value of a loan, for example, is 0).
- * @param integer type A number 0 or 1 and indicates when payments are due:
- * 0 or omitted At the end of the period.
- * 1 At the beginning of the period.
- * @param float guess Your guess for what the rate will be.
- * If you omit guess, it is assumed to be 10 percent.
- * @return float
- **/
- public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) {
- $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
- $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
- $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
- $fv = (is_null($fv)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($fv);
- $type = (is_null($type)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
- $guess = (is_null($guess)) ? 0.1 : PHPExcel_Calculation_Functions::flattenSingleValue($guess);
-
- $rate = $guess;
- if (abs($rate) < FINANCIAL_PRECISION) {
- $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
- } else {
- $f = exp($nper * log(1 + $rate));
- $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
- }
- $y0 = $pv + $pmt * $nper + $fv;
- $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
-
- // find root by secant method
- $i = $x0 = 0.0;
- $x1 = $rate;
- while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
- $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
- $x0 = $x1;
- $x1 = $rate;
- if (($nper * abs($pmt)) > ($pv - $fv))
- $x1 = abs($x1);
-
- if (abs($rate) < FINANCIAL_PRECISION) {
- $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
- } else {
- $f = exp($nper * log(1 + $rate));
- $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
- }
-
- $y0 = $y1;
- $y1 = $y;
- ++$i;
- }
- return $rate;
- } // function RATE()
-
-
- /**
- * RECEIVED
- *
- * Returns the price per $100 face value of a discounted security.
- *
- * @param mixed settlement The security's settlement date.
- * The security settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param int investment The amount invested in the security.
- * @param int discount The security's discount rate.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $investment = (float) PHPExcel_Calculation_Functions::flattenSingleValue($investment);
- $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
- $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
- if (($investment <= 0) || ($discount <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function RECEIVED()
-
-
- /**
- * SLN
- *
- * Returns the straight-line depreciation of an asset for one period
- *
- * @param cost Initial cost of the asset
- * @param salvage Value at the end of the depreciation
- * @param life Number of periods over which the asset is depreciated
- * @return float
- */
- public static function SLN($cost, $salvage, $life) {
- $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
- $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
- $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
-
- // Calculate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
- if ($life < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return ($cost - $salvage) / $life;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function SLN()
-
-
- /**
- * SYD
- *
- * Returns the sum-of-years' digits depreciation of an asset for a specified period.
- *
- * @param cost Initial cost of the asset
- * @param salvage Value at the end of the depreciation
- * @param life Number of periods over which the asset is depreciated
- * @param period Period
- * @return float
- */
- public static function SYD($cost, $salvage, $life, $period) {
- $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
- $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
- $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
- $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
-
- // Calculate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
- if (($life < 1) || ($period > $life)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function SYD()
-
-
- /**
- * TBILLEQ
- *
- * Returns the bond-equivalent yield for a Treasury bill.
- *
- * @param mixed settlement The Treasury bill's settlement date.
- * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
- * @param mixed maturity The Treasury bill's maturity date.
- * The maturity date is the date when the Treasury bill expires.
- * @param int discount The Treasury bill's discount rate.
- * @return float
- */
- public static function TBILLEQ($settlement, $maturity, $discount) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
-
- // Use TBILLPRICE for validation
- $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
- if (is_string($testValue)) {
- return $testValue;
- }
-
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
- } else {
- $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement));
- }
-
- return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
- } // function TBILLEQ()
-
-
- /**
- * TBILLPRICE
- *
- * Returns the yield for a Treasury bill.
- *
- * @param mixed settlement The Treasury bill's settlement date.
- * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
- * @param mixed maturity The Treasury bill's maturity date.
- * The maturity date is the date when the Treasury bill expires.
- * @param int discount The Treasury bill's discount rate.
- * @return float
- */
- public static function TBILLPRICE($settlement, $maturity, $discount) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
-
- if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // Validate
- if (is_numeric($discount)) {
- if ($discount <= 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- } else {
- $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement));
- }
-
- if ($daysBetweenSettlementAndMaturity > 360) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
- if ($price <= 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return $price;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function TBILLPRICE()
-
-
- /**
- * TBILLYIELD
- *
- * Returns the yield for a Treasury bill.
- *
- * @param mixed settlement The Treasury bill's settlement date.
- * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
- * @param mixed maturity The Treasury bill's maturity date.
- * The maturity date is the date when the Treasury bill expires.
- * @param int price The Treasury bill's price per $100 face value.
- * @return float
- */
- public static function TBILLYIELD($settlement, $maturity, $price) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
-
- // Validate
- if (is_numeric($price)) {
- if ($price <= 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- } else {
- $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement));
- }
-
- if ($daysBetweenSettlementAndMaturity > 360) {
- return PHPExcel_Calculation_Functions::NaN();
- }
-
- return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function TBILLYIELD()
-
-
- public static function XIRR($values, $dates, $guess = 0.1) {
- if ((!is_array($values)) && (!is_array($dates))) return PHPExcel_Calculation_Functions::VALUE();
- $values = PHPExcel_Calculation_Functions::flattenArray($values);
- $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
- $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
- if (count($values) != count($dates)) return PHPExcel_Calculation_Functions::NaN();
-
- // create an initial range, with a root somewhere between 0 and guess
- $x1 = 0.0;
- $x2 = $guess;
- $f1 = self::XNPV($x1, $values, $dates);
- $f2 = self::XNPV($x2, $values, $dates);
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- if (($f1 * $f2) < 0.0) break;
- if (abs($f1) < abs($f2)) {
- $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
- } else {
- $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
- }
- }
- if (($f1 * $f2) > 0.0) return PHPExcel_Calculation_Functions::VALUE();
-
- $f = self::XNPV($x1, $values, $dates);
- if ($f < 0.0) {
- $rtb = $x1;
- $dx = $x2 - $x1;
- } else {
- $rtb = $x2;
- $dx = $x1 - $x2;
- }
-
- for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
- $dx *= 0.5;
- $x_mid = $rtb + $dx;
- $f_mid = self::XNPV($x_mid, $values, $dates);
- if ($f_mid <= 0.0) $rtb = $x_mid;
- if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
-
- /**
- * XNPV
- *
- * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
- * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
- *
- * Excel Function:
- * =XNPV(rate,values,dates)
- *
- * @param float $rate The discount rate to apply to the cash flows.
- * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. The series of values must contain at least one positive value and one negative value.
- * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order.
- * @return float
- */
- public static function XNPV($rate, $values, $dates) {
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- if (!is_numeric($rate)) return PHPExcel_Calculation_Functions::VALUE();
- if ((!is_array($values)) || (!is_array($dates))) return PHPExcel_Calculation_Functions::VALUE();
- $values = PHPExcel_Calculation_Functions::flattenArray($values);
- $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
- $valCount = count($values);
- if ($valCount != count($dates)) return PHPExcel_Calculation_Functions::NaN();
- if ((min($values) > 0) || (max($values) < 0)) return PHPExcel_Calculation_Functions::VALUE();
-
- $xnpv = 0.0;
- for ($i = 0; $i < $valCount; ++$i) {
- if (!is_numeric($values[$i])) return PHPExcel_Calculation_Functions::VALUE();
- $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0],$dates[$i],'d') / 365);
- }
- return (is_finite($xnpv)) ? $xnpv : PHPExcel_Calculation_Functions::VALUE();
- } // function XNPV()
-
-
- /**
- * YIELDDISC
- *
- * Returns the annual yield of a security that pays interest at maturity.
- *
- * @param mixed settlement The security's settlement date.
- * The security's settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param int price The security's price per $100 face value.
- * @param int redemption The security's redemption value per $100 face value.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
- $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
- $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($price) && is_numeric($redemption)) {
- if (($price <= 0) || ($redemption <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity,$basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function YIELDDISC()
-
-
- /**
- * YIELDMAT
- *
- * Returns the annual yield of a security that pays interest at maturity.
- *
- * @param mixed settlement The security's settlement date.
- * The security's settlement date is the date after the issue date when the security is traded to the buyer.
- * @param mixed maturity The security's maturity date.
- * The maturity date is the date when the security expires.
- * @param mixed issue The security's issue date.
- * @param int rate The security's interest rate at date of issue.
- * @param int price The security's price per $100 face value.
- * @param int basis The type of day count to use.
- * 0 or omitted US (NASD) 30/360
- * 1 Actual/actual
- * 2 Actual/360
- * 3 Actual/365
- * 4 European 30/360
- * @return float
- */
- public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis=0) {
- $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
- $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
- $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
- $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
- $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
- $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($rate) && is_numeric($price)) {
- if (($rate <= 0) || ($price <= 0)) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- $daysBetweenIssueAndSettlement *= $daysPerYear;
- $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
- if (!is_numeric($daysBetweenIssueAndMaturity)) {
- // return date error
- return $daysBetweenIssueAndMaturity;
- }
- $daysBetweenIssueAndMaturity *= $daysPerYear;
- $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
- (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
- ($daysPerYear / $daysBetweenSettlementAndMaturity);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function YIELDMAT()
-
-} // class PHPExcel_Calculation_Financial
+ } else {
+ return 0.0;
+ }
+ }
+
+
+ /**
+ * COUPDAYBS
+ *
+ * Returns the number of days from the beginning of the coupon period to the settlement date.
+ *
+ * Excel Function:
+ * COUPDAYBS(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
+ $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
+
+ return PHPExcel_Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
+ }
+
+
+ /**
+ * COUPDAYS
+ *
+ * Returns the number of days in the coupon period that contains the settlement date.
+ *
+ * Excel Function:
+ * COUPDAYS(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ switch ($basis) {
+ case 3:
+ // Actual/365
+ return 365 / $frequency;
+ case 1:
+ // Actual/actual
+ if ($frequency == 1) {
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($maturity), $basis);
+ return ($daysPerYear / $frequency);
+ }
+ $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
+ $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
+ return ($next - $prev);
+ default:
+ // US (NASD) 30/360, Actual/360 or European 30/360
+ return 360 / $frequency;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * COUPDAYSNC
+ *
+ * Returns the number of days from the settlement date to the next coupon date.
+ *
+ * Excel Function:
+ * COUPDAYSNC(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
+ $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
+
+ return PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
+ }
+
+
+ /**
+ * COUPNCD
+ *
+ * Returns the next coupon date after the settlement date.
+ *
+ * Excel Function:
+ * COUPNCD(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
+ }
+
+
+ /**
+ * COUPNUM
+ *
+ * Returns the number of coupons payable between the settlement date and maturity date,
+ * rounded up to the nearest whole coupon.
+ *
+ * Excel Function:
+ * COUPNUM(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return integer
+ */
+ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $settlement = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365;
+
+ switch ($frequency) {
+ case 1: // annual payments
+ return ceil($daysBetweenSettlementAndMaturity / 360);
+ case 2: // half-yearly
+ return ceil($daysBetweenSettlementAndMaturity / 180);
+ case 4: // quarterly
+ return ceil($daysBetweenSettlementAndMaturity / 90);
+ case 6: // bimonthly
+ return ceil($daysBetweenSettlementAndMaturity / 60);
+ case 12: // monthly
+ return ceil($daysBetweenSettlementAndMaturity / 30);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * COUPPCD
+ *
+ * Returns the previous coupon date before the settlement date.
+ *
+ * Excel Function:
+ * COUPPCD(settlement,maturity,frequency[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed frequency the number of coupon payments per year.
+ * Valid frequency values are:
+ * 1 Annual
+ * 2 Semi-Annual
+ * 4 Quarterly
+ * If working in Gnumeric Mode, the following frequency options are
+ * also available
+ * 6 Bimonthly
+ * 12 Monthly
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
+ * depending on the value of the ReturnDateType flag
+ */
+ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
+ }
+
+
+ /**
+ * CUMIPMT
+ *
+ * Returns the cumulative interest paid on a loan between the start and end periods.
+ *
+ * Excel Function:
+ * CUMIPMT(rate,nper,pv,start,end[,type])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $rate The Interest rate
+ * @param integer $nper The total number of payment periods
+ * @param float $pv Present Value
+ * @param integer $start The first period in the calculation.
+ * Payment periods are numbered beginning with 1.
+ * @param integer $end The last period in the calculation.
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @return float
+ */
+ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
+ $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ($start < 1 || $start > $end) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $interest = 0;
+ for ($per = $start; $per <= $end; ++$per) {
+ $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
+ }
+
+ return $interest;
+ }
+
+
+ /**
+ * CUMPRINC
+ *
+ * Returns the cumulative principal paid on a loan between the start and end periods.
+ *
+ * Excel Function:
+ * CUMPRINC(rate,nper,pv,start,end[,type])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $rate The Interest rate
+ * @param integer $nper The total number of payment periods
+ * @param float $pv Present Value
+ * @param integer $start The first period in the calculation.
+ * Payment periods are numbered beginning with 1.
+ * @param integer $end The last period in the calculation.
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @return float
+ */
+ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
+ $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ($start < 1 || $start > $end) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $principal = 0;
+ for ($per = $start; $per <= $end; ++$per) {
+ $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
+ }
+
+ return $principal;
+ }
+
+
+ /**
+ * DB
+ *
+ * Returns the depreciation of an asset for a specified period using the
+ * fixed-declining balance method.
+ * This form of depreciation is used if you want to get a higher depreciation value
+ * at the beginning of the depreciation (as opposed to linear depreciation). The
+ * depreciation value is reduced with every depreciation period by the depreciation
+ * already deducted from the initial cost.
+ *
+ * Excel Function:
+ * DB(cost,salvage,life,period[,month])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost Initial cost of the asset.
+ * @param float salvage Value at the end of the depreciation.
+ * (Sometimes called the salvage value of the asset)
+ * @param integer life Number of periods over which the asset is depreciated.
+ * (Sometimes called the useful life of the asset)
+ * @param integer period The period for which you want to calculate the
+ * depreciation. Period must use the same units as life.
+ * @param integer month Number of months in the first year. If month is omitted,
+ * it defaults to 12.
+ * @return float
+ */
+ public static function DB($cost, $salvage, $life, $period, $month = 12)
+ {
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
+ $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
+
+ // Validate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
+ $cost = (float) $cost;
+ $salvage = (float) $salvage;
+ $life = (int) $life;
+ $period = (int) $period;
+ $month = (int) $month;
+ if ($cost == 0) {
+ return 0.0;
+ } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ // Set Fixed Depreciation Rate
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
+
+ // Loop through each period calculating the depreciation
+ $previousDepreciation = 0;
+ for ($per = 1; $per <= $period; ++$per) {
+ if ($per == 1) {
+ $depreciation = $cost * $fixedDepreciationRate * $month / 12;
+ } elseif ($per == ($life + 1)) {
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
+ } else {
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
+ }
+ $previousDepreciation += $depreciation;
+ }
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $depreciation = round($depreciation, 2);
+ }
+ return $depreciation;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * DDB
+ *
+ * Returns the depreciation of an asset for a specified period using the
+ * double-declining balance method or some other method you specify.
+ *
+ * Excel Function:
+ * DDB(cost,salvage,life,period[,factor])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float cost Initial cost of the asset.
+ * @param float salvage Value at the end of the depreciation.
+ * (Sometimes called the salvage value of the asset)
+ * @param integer life Number of periods over which the asset is depreciated.
+ * (Sometimes called the useful life of the asset)
+ * @param integer period The period for which you want to calculate the
+ * depreciation. Period must use the same units as life.
+ * @param float factor The rate at which the balance declines.
+ * If factor is omitted, it is assumed to be 2 (the
+ * double-declining balance method).
+ * @return float
+ */
+ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0)
+ {
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
+ $factor = PHPExcel_Calculation_Functions::flattenSingleValue($factor);
+
+ // Validate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
+ $cost = (float) $cost;
+ $salvage = (float) $salvage;
+ $life = (int) $life;
+ $period = (int) $period;
+ $factor = (float) $factor;
+ if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ // Set Fixed Depreciation Rate
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
+
+ // Loop through each period calculating the depreciation
+ $previousDepreciation = 0;
+ for ($per = 1; $per <= $period; ++$per) {
+ $depreciation = min(($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation));
+ $previousDepreciation += $depreciation;
+ }
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ $depreciation = round($depreciation, 2);
+ }
+ return $depreciation;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * DISC
+ *
+ * Returns the discount rate for a security.
+ *
+ * Excel Function:
+ * DISC(settlement,maturity,price,redemption[,basis])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue
+ * date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param integer price The security's price per $100 face value.
+ * @param integer redemption The security's redemption value per $100 face value.
+ * @param integer basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
+ $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
+ $price = (float) $price;
+ $redemption = (float) $redemption;
+ $basis = (int) $basis;
+ if (($price <= 0) || ($redemption <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * DOLLARDE
+ *
+ * Converts a dollar price expressed as an integer part and a fraction
+ * part into a dollar price expressed as a decimal number.
+ * Fractional dollar numbers are sometimes used for security prices.
+ *
+ * Excel Function:
+ * DOLLARDE(fractional_dollar,fraction)
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $fractional_dollar Fractional Dollar
+ * @param integer $fraction Fraction
+ * @return float
+ */
+ public static function DOLLARDE($fractional_dollar = null, $fraction = 0)
+ {
+ $fractional_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($fractional_dollar);
+ $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
+
+ // Validate parameters
+ if (is_null($fractional_dollar) || $fraction < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ($fraction == 0) {
+ return PHPExcel_Calculation_Functions::DIV0();
+ }
+
+ $dollars = floor($fractional_dollar);
+ $cents = fmod($fractional_dollar, 1);
+ $cents /= $fraction;
+ $cents *= pow(10, ceil(log10($fraction)));
+ return $dollars + $cents;
+ }
+
+
+ /**
+ * DOLLARFR
+ *
+ * Converts a dollar price expressed as a decimal number into a dollar price
+ * expressed as a fraction.
+ * Fractional dollar numbers are sometimes used for security prices.
+ *
+ * Excel Function:
+ * DOLLARFR(decimal_dollar,fraction)
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $decimal_dollar Decimal Dollar
+ * @param integer $fraction Fraction
+ * @return float
+ */
+ public static function DOLLARFR($decimal_dollar = null, $fraction = 0)
+ {
+ $decimal_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($decimal_dollar);
+ $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
+
+ // Validate parameters
+ if (is_null($decimal_dollar) || $fraction < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ($fraction == 0) {
+ return PHPExcel_Calculation_Functions::DIV0();
+ }
+
+ $dollars = floor($decimal_dollar);
+ $cents = fmod($decimal_dollar, 1);
+ $cents *= $fraction;
+ $cents *= pow(10, -ceil(log10($fraction)));
+ return $dollars + $cents;
+ }
+
+
+ /**
+ * EFFECT
+ *
+ * Returns the effective interest rate given the nominal rate and the number of
+ * compounding payments per year.
+ *
+ * Excel Function:
+ * EFFECT(nominal_rate,npery)
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $nominal_rate Nominal interest rate
+ * @param integer $npery Number of compounding payments per year
+ * @return float
+ */
+ public static function EFFECT($nominal_rate = 0, $npery = 0)
+ {
+ $nominal_rate = PHPExcel_Calculation_Functions::flattenSingleValue($nominal_rate);
+ $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
+
+ // Validate parameters
+ if ($nominal_rate <= 0 || $npery < 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ return pow((1 + $nominal_rate / $npery), $npery) - 1;
+ }
+
+
+ /**
+ * FV
+ *
+ * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
+ *
+ * Excel Function:
+ * FV(rate,nper,pmt[,pv[,type]])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float $rate The interest rate per period
+ * @param int $nper Total number of payment periods in an annuity
+ * @param float $pmt The payment made each period: it cannot change over the
+ * life of the annuity. Typically, pmt contains principal
+ * and interest but no other fees or taxes.
+ * @param float $pv Present Value, or the lump-sum amount that a series of
+ * future payments is worth right now.
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @return float
+ */
+ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
+ }
+ return -$pv - $pmt * $nper;
+ }
+
+
+ /**
+ * FVSCHEDULE
+ *
+ * Returns the future value of an initial principal after applying a series of compound interest rates.
+ * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate.
+ *
+ * Excel Function:
+ * FVSCHEDULE(principal,schedule)
+ *
+ * @param float $principal The present value.
+ * @param float[] $schedule An array of interest rates to apply.
+ * @return float
+ */
+ public static function FVSCHEDULE($principal, $schedule)
+ {
+ $principal = PHPExcel_Calculation_Functions::flattenSingleValue($principal);
+ $schedule = PHPExcel_Calculation_Functions::flattenArray($schedule);
+
+ foreach ($schedule as $rate) {
+ $principal *= 1 + $rate;
+ }
+
+ return $principal;
+ }
+
+
+ /**
+ * INTRATE
+ *
+ * Returns the interest rate for a fully invested security.
+ *
+ * Excel Function:
+ * INTRATE(settlement,maturity,investment,redemption[,basis])
+ *
+ * @param mixed $settlement The security's settlement date.
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed $maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param integer $investment The amount invested in the security.
+ * @param integer $redemption The amount to be received at maturity.
+ * @param integer $basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $investment = PHPExcel_Calculation_Functions::flattenSingleValue($investment);
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
+ $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
+ $investment = (float) $investment;
+ $redemption = (float) $redemption;
+ $basis = (int) $basis;
+ if (($investment <= 0) || ($redemption <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * IPMT
+ *
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
+ *
+ * Excel Function:
+ * IPMT(rate,per,nper,pv[,fv][,type])
+ *
+ * @param float $rate Interest rate per period
+ * @param int $per Period for which we want to find the interest
+ * @param int $nper Number of periods
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ($per <= 0 || $per > $nper) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
+ return $interestAndPrincipal[0];
+ }
+
+ /**
+ * IRR
+ *
+ * Returns the internal rate of return for a series of cash flows represented by the numbers in values.
+ * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur
+ * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received
+ * for an investment consisting of payments (negative values) and income (positive values) that occur at regular
+ * periods.
+ *
+ * Excel Function:
+ * IRR(values[,guess])
+ *
+ * @param float[] $values An array or a reference to cells that contain numbers for which you want
+ * to calculate the internal rate of return.
+ * Values must contain at least one positive value and one negative value to
+ * calculate the internal rate of return.
+ * @param float $guess A number that you guess is close to the result of IRR
+ * @return float
+ */
+ public static function IRR($values, $guess = 0.1)
+ {
+ if (!is_array($values)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
+ $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
+
+ // create an initial range, with a root somewhere between 0 and guess
+ $x1 = 0.0;
+ $x2 = $guess;
+ $f1 = self::NPV($x1, $values);
+ $f2 = self::NPV($x2, $values);
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ if (($f1 * $f2) < 0.0) {
+ break;
+ }
+ if (abs($f1) < abs($f2)) {
+ $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
+ } else {
+ $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
+ }
+ }
+ if (($f1 * $f2) > 0.0) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ $f = self::NPV($x1, $values);
+ if ($f < 0.0) {
+ $rtb = $x1;
+ $dx = $x2 - $x1;
+ } else {
+ $rtb = $x2;
+ $dx = $x1 - $x2;
+ }
+
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ $dx *= 0.5;
+ $x_mid = $rtb + $dx;
+ $f_mid = self::NPV($x_mid, $values);
+ if ($f_mid <= 0.0) {
+ $rtb = $x_mid;
+ }
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) {
+ return $x_mid;
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * ISPMT
+ *
+ * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
+ *
+ * Excel Function:
+ * =ISPMT(interest_rate, period, number_payments, PV)
+ *
+ * interest_rate is the interest rate for the investment
+ *
+ * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
+ *
+ * number_payments is the number of payments for the annuity
+ *
+ * PV is the loan amount or present value of the payments
+ */
+ public static function ISPMT()
+ {
+ // Return value
+ $returnValue = 0;
+
+ // Get the parameters
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ $interestRate = array_shift($aArgs);
+ $period = array_shift($aArgs);
+ $numberPeriods = array_shift($aArgs);
+ $principleRemaining = array_shift($aArgs);
+
+ // Calculate
+ $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
+ for ($i=0; $i <= $period; ++$i) {
+ $returnValue = $interestRate * $principleRemaining * -1;
+ $principleRemaining -= $principlePayment;
+ // principle needs to be 0 after the last payment, don't let floating point screw it up
+ if ($i == $numberPeriods) {
+ $returnValue = 0;
+ }
+ }
+ return($returnValue);
+ }
+
+
+ /**
+ * MIRR
+ *
+ * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both
+ * the cost of the investment and the interest received on reinvestment of cash.
+ *
+ * Excel Function:
+ * MIRR(values,finance_rate, reinvestment_rate)
+ *
+ * @param float[] $values An array or a reference to cells that contain a series of payments and
+ * income occurring at regular intervals.
+ * Payments are negative value, income is positive values.
+ * @param float $finance_rate The interest rate you pay on the money used in the cash flows
+ * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them
+ * @return float
+ */
+ public static function MIRR($values, $finance_rate, $reinvestment_rate)
+ {
+ if (!is_array($values)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
+ $finance_rate = PHPExcel_Calculation_Functions::flattenSingleValue($finance_rate);
+ $reinvestment_rate = PHPExcel_Calculation_Functions::flattenSingleValue($reinvestment_rate);
+ $n = count($values);
+
+ $rr = 1.0 + $reinvestment_rate;
+ $fr = 1.0 + $finance_rate;
+
+ $npv_pos = $npv_neg = 0.0;
+ foreach ($values as $i => $v) {
+ if ($v >= 0) {
+ $npv_pos += $v / pow($rr, $i);
+ } else {
+ $npv_neg += $v / pow($fr, $i);
+ }
+ }
+
+ if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ $mirr = pow((-$npv_pos * pow($rr, $n))
+ / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
+
+ return (is_finite($mirr) ? $mirr : PHPExcel_Calculation_Functions::VALUE());
+ }
+
+
+ /**
+ * NOMINAL
+ *
+ * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
+ *
+ * @param float $effect_rate Effective interest rate
+ * @param int $npery Number of compounding payments per year
+ * @return float
+ */
+ public static function NOMINAL($effect_rate = 0, $npery = 0)
+ {
+ $effect_rate = PHPExcel_Calculation_Functions::flattenSingleValue($effect_rate);
+ $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
+
+ // Validate parameters
+ if ($effect_rate <= 0 || $npery < 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
+ }
+
+
+ /**
+ * NPER
+ *
+ * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
+ *
+ * @param float $rate Interest rate per period
+ * @param int $pmt Periodic payment (annuity)
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ if ($pmt == 0 && $pv == 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
+ }
+ if ($pmt == 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return (-$pv -$fv) / $pmt;
+ }
+
+ /**
+ * NPV
+ *
+ * Returns the Net Present Value of a cash flow series given a discount rate.
+ *
+ * @return float
+ */
+ public static function NPV()
+ {
+ // Return value
+ $returnValue = 0;
+
+ // Loop through arguments
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+
+ // Calculate
+ $rate = array_shift($aArgs);
+ for ($i = 1; $i <= count($aArgs); ++$i) {
+ // Is it a numeric value?
+ if (is_numeric($aArgs[$i - 1])) {
+ $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
+ }
+ }
+
+ // Return
+ return $returnValue;
+ }
+
+ /**
+ * PMT
+ *
+ * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
+ *
+ * @param float $rate Interest rate per period
+ * @param int $nper Number of periods
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
+ }
+ return (-$pv - $fv) / $nper;
+ }
+
+
+ /**
+ * PPMT
+ *
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
+ *
+ * @param float $rate Interest rate per period
+ * @param int $per Period for which we want to find the interest
+ * @param int $nper Number of periods
+ * @param float $pv Present Value
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ($per <= 0 || $per > $nper) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Calculate
+ $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
+ return $interestAndPrincipal[1];
+ }
+
+
+ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $rate = (float) PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $yield = (float) PHPExcel_Calculation_Functions::flattenSingleValue($yield);
+ $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (($settlement > $maturity) ||
+ (!self::isValidFrequency($frequency)) ||
+ (($basis < 0) || ($basis > 4))) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
+ $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
+ $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
+ $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis);
+
+ $baseYF = 1.0 + ($yield / $frequency);
+ $rfp = 100 * ($rate / $frequency);
+ $de = $dsc / $e;
+
+ $result = $redemption / pow($baseYF, (--$n + $de));
+ for ($k = 0; $k <= $n; ++$k) {
+ $result += $rfp / (pow($baseYF, ($k + $de)));
+ }
+ $result -= $rfp * ($a / $e);
+
+ return $result;
+ }
+
+
+ /**
+ * PRICEDISC
+ *
+ * Returns the price per $100 face value of a discounted security.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param int discount The security's discount rate.
+ * @param int redemption The security's redemption value per $100 face value.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
+ $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
+ if (($discount <= 0) || ($redemption <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * PRICEMAT
+ *
+ * Returns the price per $100 face value of a security that pays interest at maturity.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed issue The security's issue date.
+ * @param int rate The security's interest rate at date of issue.
+ * @param int yield The security's annual yield.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $yield = PHPExcel_Calculation_Functions::flattenSingleValue($yield);
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if (is_numeric($rate) && is_numeric($yield)) {
+ if (($rate <= 0) || ($yield <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
+ $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
+ // return date error
+ return $daysBetweenIssueAndMaturity;
+ }
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
+
+ return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
+ (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
+ (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * PV
+ *
+ * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
+ *
+ * @param float $rate Interest rate per period
+ * @param int $nper Number of periods
+ * @param float $pmt Periodic payment (annuity)
+ * @param float $fv Future Value
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
+ * @return float
+ */
+ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
+
+ // Validate parameters
+ if ($type != 0 && $type != 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // Calculate
+ if (!is_null($rate) && $rate != 0) {
+ return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
+ }
+ return -$fv - $pmt * $nper;
+ }
+
+
+ /**
+ * RATE
+ *
+ * Returns the interest rate per period of an annuity.
+ * RATE is calculated by iteration and can have zero or more solutions.
+ * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations,
+ * RATE returns the #NUM! error value.
+ *
+ * Excel Function:
+ * RATE(nper,pmt,pv[,fv[,type[,guess]]])
+ *
+ * @access public
+ * @category Financial Functions
+ * @param float nper The total number of payment periods in an annuity.
+ * @param float pmt The payment made each period and cannot change over the life
+ * of the annuity.
+ * Typically, pmt includes principal and interest but no other
+ * fees or taxes.
+ * @param float pv The present value - the total amount that a series of future
+ * payments is worth now.
+ * @param float fv The future value, or a cash balance you want to attain after
+ * the last payment is made. If fv is omitted, it is assumed
+ * to be 0 (the future value of a loan, for example, is 0).
+ * @param integer type A number 0 or 1 and indicates when payments are due:
+ * 0 or omitted At the end of the period.
+ * 1 At the beginning of the period.
+ * @param float guess Your guess for what the rate will be.
+ * If you omit guess, it is assumed to be 10 percent.
+ * @return float
+ **/
+ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1)
+ {
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
+ $fv = (is_null($fv)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($fv);
+ $type = (is_null($type)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
+ $guess = (is_null($guess)) ? 0.1 : PHPExcel_Calculation_Functions::flattenSingleValue($guess);
+
+ $rate = $guess;
+ if (abs($rate) < FINANCIAL_PRECISION) {
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
+ } else {
+ $f = exp($nper * log(1 + $rate));
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
+ }
+ $y0 = $pv + $pmt * $nper + $fv;
+ $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
+
+ // find root by secant method
+ $i = $x0 = 0.0;
+ $x1 = $rate;
+ while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
+ $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
+ $x0 = $x1;
+ $x1 = $rate;
+ if (($nper * abs($pmt)) > ($pv - $fv)) {
+ $x1 = abs($x1);
+ }
+ if (abs($rate) < FINANCIAL_PRECISION) {
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
+ } else {
+ $f = exp($nper * log(1 + $rate));
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
+ }
+
+ $y0 = $y1;
+ $y1 = $y;
+ ++$i;
+ }
+ return $rate;
+ }
+
+
+ /**
+ * RECEIVED
+ *
+ * Returns the price per $100 face value of a discounted security.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param int investment The amount invested in the security.
+ * @param int discount The security's discount rate.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $investment = (float) PHPExcel_Calculation_Functions::flattenSingleValue($investment);
+ $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
+ if (($investment <= 0) || ($discount <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SLN
+ *
+ * Returns the straight-line depreciation of an asset for one period
+ *
+ * @param cost Initial cost of the asset
+ * @param salvage Value at the end of the depreciation
+ * @param life Number of periods over which the asset is depreciated
+ * @return float
+ */
+ public static function SLN($cost, $salvage, $life)
+ {
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
+
+ // Calculate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
+ if ($life < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return ($cost - $salvage) / $life;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SYD
+ *
+ * Returns the sum-of-years' digits depreciation of an asset for a specified period.
+ *
+ * @param cost Initial cost of the asset
+ * @param salvage Value at the end of the depreciation
+ * @param life Number of periods over which the asset is depreciated
+ * @param period Period
+ * @return float
+ */
+ public static function SYD($cost, $salvage, $life, $period)
+ {
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
+
+ // Calculate
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
+ if (($life < 1) || ($period > $life)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * TBILLEQ
+ *
+ * Returns the bond-equivalent yield for a Treasury bill.
+ *
+ * @param mixed settlement The Treasury bill's settlement date.
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
+ * @param mixed maturity The Treasury bill's maturity date.
+ * The maturity date is the date when the Treasury bill expires.
+ * @param int discount The Treasury bill's discount rate.
+ * @return float
+ */
+ public static function TBILLEQ($settlement, $maturity, $discount)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
+
+ // Use TBILLPRICE for validation
+ $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
+ if (is_string($testValue)) {
+ return $testValue;
+ }
+
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ ++$maturity;
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
+ } else {
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement));
+ }
+
+ return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
+ }
+
+
+ /**
+ * TBILLPRICE
+ *
+ * Returns the yield for a Treasury bill.
+ *
+ * @param mixed settlement The Treasury bill's settlement date.
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
+ * @param mixed maturity The Treasury bill's maturity date.
+ * The maturity date is the date when the Treasury bill expires.
+ * @param int discount The Treasury bill's discount rate.
+ * @return float
+ */
+ public static function TBILLPRICE($settlement, $maturity, $discount)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
+
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // Validate
+ if (is_numeric($discount)) {
+ if ($discount <= 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ ++$maturity;
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ } else {
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement));
+ }
+
+ if ($daysBetweenSettlementAndMaturity > 360) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
+ if ($price <= 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return $price;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * TBILLYIELD
+ *
+ * Returns the yield for a Treasury bill.
+ *
+ * @param mixed settlement The Treasury bill's settlement date.
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
+ * @param mixed maturity The Treasury bill's maturity date.
+ * The maturity date is the date when the Treasury bill expires.
+ * @param int price The Treasury bill's price per $100 face value.
+ * @return float
+ */
+ public static function TBILLYIELD($settlement, $maturity, $price)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
+
+ // Validate
+ if (is_numeric($price)) {
+ if ($price <= 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
+ ++$maturity;
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ } else {
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement));
+ }
+
+ if ($daysBetweenSettlementAndMaturity > 360) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ public static function XIRR($values, $dates, $guess = 0.1)
+ {
+ if ((!is_array($values)) && (!is_array($dates))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
+ $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
+ $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
+ if (count($values) != count($dates)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+
+ // create an initial range, with a root somewhere between 0 and guess
+ $x1 = 0.0;
+ $x2 = $guess;
+ $f1 = self::XNPV($x1, $values, $dates);
+ $f2 = self::XNPV($x2, $values, $dates);
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ if (($f1 * $f2) < 0.0) {
+ break;
+ } elseif (abs($f1) < abs($f2)) {
+ $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
+ } else {
+ $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
+ }
+ }
+ if (($f1 * $f2) > 0.0) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ $f = self::XNPV($x1, $values, $dates);
+ if ($f < 0.0) {
+ $rtb = $x1;
+ $dx = $x2 - $x1;
+ } else {
+ $rtb = $x2;
+ $dx = $x1 - $x2;
+ }
+
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
+ $dx *= 0.5;
+ $x_mid = $rtb + $dx;
+ $f_mid = self::XNPV($x_mid, $values, $dates);
+ if ($f_mid <= 0.0) {
+ $rtb = $x_mid;
+ }
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) {
+ return $x_mid;
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * XNPV
+ *
+ * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
+ * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
+ *
+ * Excel Function:
+ * =XNPV(rate,values,dates)
+ *
+ * @param float $rate The discount rate to apply to the cash flows.
+ * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates.
+ * The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment.
+ * If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year.
+ * The series of values must contain at least one positive value and one negative value.
+ * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments.
+ * The first payment date indicates the beginning of the schedule of payments.
+ * All other dates must be later than this date, but they may occur in any order.
+ * @return float
+ */
+ public static function XNPV($rate, $values, $dates)
+ {
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ if (!is_numeric($rate)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if ((!is_array($values)) || (!is_array($dates))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
+ $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
+ $valCount = count($values);
+ if ($valCount != count($dates)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ if ((min($values) > 0) || (max($values) < 0)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ $xnpv = 0.0;
+ for ($i = 0; $i < $valCount; ++$i) {
+ if (!is_numeric($values[$i])) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0], $dates[$i], 'd') / 365);
+ }
+ return (is_finite($xnpv)) ? $xnpv : PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * YIELDDISC
+ *
+ * Returns the annual yield of a security that pays interest at maturity.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param int price The security's price per $100 face value.
+ * @param int redemption The security's redemption value per $100 face value.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if (is_numeric($price) && is_numeric($redemption)) {
+ if (($price <= 0) || ($redemption <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
+
+ return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * YIELDMAT
+ *
+ * Returns the annual yield of a security that pays interest at maturity.
+ *
+ * @param mixed settlement The security's settlement date.
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
+ * @param mixed maturity The security's maturity date.
+ * The maturity date is the date when the security expires.
+ * @param mixed issue The security's issue date.
+ * @param int rate The security's interest rate at date of issue.
+ * @param int price The security's price per $100 face value.
+ * @param int basis The type of day count to use.
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
+ * @return float
+ */
+ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0)
+ {
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
+
+ // Validate
+ if (is_numeric($rate) && is_numeric($price)) {
+ if (($rate <= 0) || ($price <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
+ $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
+ // return date error
+ return $daysBetweenIssueAndMaturity;
+ }
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
+
+ return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
+ (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
+ ($daysPerYear / $daysBetweenSettlementAndMaturity);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+}
diff --git a/Classes/PHPExcel/Calculation/FormulaParser.php b/Classes/PHPExcel/Calculation/FormulaParser.php
index 72b7c6e02..893f19e94 100644
--- a/Classes/PHPExcel/Calculation/FormulaParser.php
+++ b/Classes/PHPExcel/Calculation/FormulaParser.php
@@ -1,8 +1,32 @@
<";
+ const OPERATORS_POSTFIX = "%";
- http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
- http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
-*/
+ /**
+ * Formula
+ *
+ * @var string
+ */
+ private $formula;
-/**
- * PHPExcel_Calculation_FormulaParser
- *
- * @category PHPExcel
- * @package PHPExcel_Calculation
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- */
-class PHPExcel_Calculation_FormulaParser {
- /* Character constants */
- const QUOTE_DOUBLE = '"';
- const QUOTE_SINGLE = '\'';
- const BRACKET_CLOSE = ']';
- const BRACKET_OPEN = '[';
- const BRACE_OPEN = '{';
- const BRACE_CLOSE = '}';
- const PAREN_OPEN = '(';
- const PAREN_CLOSE = ')';
- const SEMICOLON = ';';
- const WHITESPACE = ' ';
- const COMMA = ',';
- const ERROR_START = '#';
-
- const OPERATORS_SN = "+-";
- const OPERATORS_INFIX = "+-*/^&=><";
- const OPERATORS_POSTFIX = "%";
-
- /**
- * Formula
- *
- * @var string
- */
- private $_formula;
-
- /**
- * Tokens
- *
- * @var PHPExcel_Calculation_FormulaToken[]
- */
- private $_tokens = array();
+ /**
+ * Tokens
+ *
+ * @var PHPExcel_Calculation_FormulaToken[]
+ */
+ private $tokens = array();
/**
* Create a new PHPExcel_Calculation_FormulaParser
*
- * @param string $pFormula Formula to parse
- * @throws PHPExcel_Calculation_Exception
+ * @param string $pFormula Formula to parse
+ * @throws PHPExcel_Calculation_Exception
*/
public function __construct($pFormula = '')
{
- // Check parameters
- if (is_null($pFormula)) {
- throw new PHPExcel_Calculation_Exception("Invalid parameter passed: formula");
- }
-
- // Initialise values
- $this->_formula = trim($pFormula);
- // Parse!
- $this->_parseToTokens();
+ // Check parameters
+ if (is_null($pFormula)) {
+ throw new PHPExcel_Calculation_Exception("Invalid parameter passed: formula");
+ }
+
+ // Initialise values
+ $this->formula = trim($pFormula);
+ // Parse!
+ $this->parseToTokens();
}
/**
@@ -113,23 +108,25 @@ public function __construct($pFormula = '')
*
* @return string
*/
- public function getFormula() {
- return $this->_formula;
+ public function getFormula()
+ {
+ return $this->formula;
}
/**
* Get Token
*
- * @param int $pId Token id
- * @return string
+ * @param int $pId Token id
+ * @return string
* @throws PHPExcel_Calculation_Exception
*/
- public function getToken($pId = 0) {
- if (isset($this->_tokens[$pId])) {
- return $this->_tokens[$pId];
- } else {
- throw new PHPExcel_Calculation_Exception("Token with id $pId does not exist.");
- }
+ public function getToken($pId = 0)
+ {
+ if (isset($this->tokens[$pId])) {
+ return $this->tokens[$pId];
+ } else {
+ throw new PHPExcel_Calculation_Exception("Token with id $pId does not exist.");
+ }
}
/**
@@ -137,8 +134,9 @@ public function getToken($pId = 0) {
*
* @return string
*/
- public function getTokenCount() {
- return count($this->_tokens);
+ public function getTokenCount()
+ {
+ return count($this->tokens);
}
/**
@@ -146,469 +144,479 @@ public function getTokenCount() {
*
* @return PHPExcel_Calculation_FormulaToken[]
*/
- public function getTokens() {
- return $this->_tokens;
+ public function getTokens()
+ {
+ return $this->tokens;
}
/**
* Parse to tokens
*/
- private function _parseToTokens() {
- // No attempt is made to verify formulas; assumes formulas are derived from Excel, where
- // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions.
-
- // Check if the formula has a valid starting =
- $formulaLength = strlen($this->_formula);
- if ($formulaLength < 2 || $this->_formula{0} != '=') return;
-
- // Helper variables
- $tokens1 = $tokens2 = $stack = array();
- $inString = $inPath = $inRange = $inError = false;
- $token = $previousToken = $nextToken = null;
-
- $index = 1;
- $value = '';
-
- $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A");
- $COMPARATORS_MULTI = array(">=", "<=", "<>");
-
- while ($index < $formulaLength) {
- // state-dependent character evaluation (order is important)
-
- // double-quoted strings
- // embeds are doubled
- // end marks token
- if ($inString) {
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
- if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE)) {
- $value .= PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE;
- ++$index;
- } else {
- $inString = false;
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT);
- $value = "";
- }
- } else {
- $value .= $this->_formula{$index};
- }
- ++$index;
- continue;
- }
-
- // single-quoted strings (links)
- // embeds are double
- // end does not mark a token
- if ($inPath) {
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
- if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE)) {
- $value .= PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE;
- ++$index;
- } else {
- $inPath = false;
- }
- } else {
- $value .= $this->_formula{$index};
- }
- ++$index;
- continue;
- }
-
- // bracked strings (R1C1 range index or linked workbook name)
- // no embeds (changed to "()" by Excel)
- // end does not mark a token
- if ($inRange) {
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_CLOSE) {
- $inRange = false;
- }
- $value .= $this->_formula{$index};
- ++$index;
- continue;
- }
-
- // error values
- // end marks a token, determined from absolute list of values
- if ($inError) {
- $value .= $this->_formula{$index};
- ++$index;
- if (in_array($value, $ERRORS)) {
- $inError = false;
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR);
- $value = "";
- }
- continue;
- }
-
- // scientific notation check
- if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_SN, $this->_formula{$index}) !== false) {
- if (strlen($value) > 1) {
- if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->_formula{$index}) != 0) {
- $value .= $this->_formula{$index};
- ++$index;
- continue;
- }
- }
- }
-
- // independent character evaluation (order not important)
-
- // establish state-dependent character evaluations
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
- if (strlen($value > 0)) { // unexpected
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
- $inString = true;
- ++$index;
- continue;
- }
-
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
- if (strlen($value) > 0) { // unexpected
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
- $inPath = true;
- ++$index;
- continue;
- }
-
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_OPEN) {
- $inRange = true;
- $value .= PHPExcel_Calculation_FormulaParser::BRACKET_OPEN;
- ++$index;
- continue;
- }
-
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::ERROR_START) {
- if (strlen($value) > 0) { // unexpected
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
- $inError = true;
- $value .= PHPExcel_Calculation_FormulaParser::ERROR_START;
- ++$index;
- continue;
- }
-
- // mark start and end of arrays and array rows
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_OPEN) {
- if (strlen($value) > 0) { // unexpected
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
- $value = "";
- }
-
- $tmp = new PHPExcel_Calculation_FormulaToken("ARRAY", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
-
- $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
-
- ++$index;
- continue;
- }
-
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::SEMICOLON) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
-
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
-
- $tmp = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
- $tokens1[] = $tmp;
-
- $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
-
- ++$index;
- continue;
- }
-
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_CLOSE) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
-
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
-
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
-
- ++$index;
- continue;
- }
-
- // trim white-space
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE);
- ++$index;
- while (($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) {
- ++$index;
- }
- continue;
- }
-
- // multi-character comparators
- if (($index + 2) <= $formulaLength) {
- if (in_array(substr($this->_formula, $index, 2), $COMPARATORS_MULTI)) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new PHPExcel_Calculation_FormulaToken(substr($this->_formula, $index, 2), PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
- $index += 2;
- continue;
- }
- }
-
- // standard infix operators
- if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_INFIX, $this->_formula{$index}) !== false) {
- if (strlen($value) > 0) {
- $tokens1[] =new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->_formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX);
- ++$index;
- continue;
- }
-
- // standard postfix operators (only one)
- if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_POSTFIX, $this->_formula{$index}) !== false) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->_formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
- ++$index;
- continue;
- }
-
- // start subexpression or function
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_OPEN) {
- if (strlen($value) > 0) {
- $tmp = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
- $value = "";
- } else {
- $tmp = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
- $tokens1[] = $tmp;
- $stack[] = clone $tmp;
- }
- ++$index;
- continue;
- }
-
- // function, subexpression, or array parameters, or operand unions
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::COMMA) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
-
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $stack[] = $tmp;
-
- if ($tmp->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_UNION);
- } else {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
- }
- ++$index;
- continue;
- }
-
- // stop subexpression
- if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_CLOSE) {
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- $value = "";
- }
-
- $tmp = array_pop($stack);
- $tmp->setValue("");
- $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
- $tokens1[] = $tmp;
-
- ++$index;
- continue;
- }
-
- // token accumulation
- $value .= $this->_formula{$index};
- ++$index;
- }
-
- // dump remaining accumulation
- if (strlen($value) > 0) {
- $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
- }
-
- // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections
- $tokenCount = count($tokens1);
- for ($i = 0; $i < $tokenCount; ++$i) {
- $token = $tokens1[$i];
- if (isset($tokens1[$i - 1])) {
- $previousToken = $tokens1[$i - 1];
- } else {
- $previousToken = null;
- }
- if (isset($tokens1[$i + 1])) {
- $nextToken = $tokens1[$i + 1];
- } else {
- $nextToken = null;
- }
-
- if (is_null($token)) {
- continue;
- }
-
- if ($token->getTokenType() != PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) {
- $tokens2[] = $token;
- continue;
- }
-
- if (is_null($previousToken)) {
- continue;
- }
-
- if (! (
- (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) ) {
- continue;
- }
-
- if (is_null($nextToken)) {
- continue;
- }
-
- if (! (
- (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
- (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
- ($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) ) {
- continue;
- }
-
- $tokens2[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION);
- }
-
- // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
- // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
- $this->_tokens = array();
-
- $tokenCount = count($tokens2);
- for ($i = 0; $i < $tokenCount; ++$i) {
- $token = $tokens2[$i];
- if (isset($tokens2[$i - 1])) {
- $previousToken = $tokens2[$i - 1];
- } else {
- $previousToken = null;
- }
- if (isset($tokens2[$i + 1])) {
- $nextToken = $tokens2[$i + 1];
- } else {
- $nextToken = null;
- }
-
- if (is_null($token)) {
- continue;
- }
-
- if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") {
- if ($i == 0) {
- $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
- } else if (
- (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
- ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
- } else {
- $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
- }
-
- $this->_tokens[] = $token;
- continue;
- }
-
- if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") {
- if ($i == 0) {
- continue;
- } else if (
- (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
- ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
- ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
- ) {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
- } else {
- continue;
- }
-
- $this->_tokens[] = $token;
- continue;
- }
-
- if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
- if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
- } else if ($token->getValue() == "&") {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
- } else {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
- }
-
- $this->_tokens[] = $token;
- continue;
- }
-
- if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
- if (!is_numeric($token->getValue())) {
- if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
- } else {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE);
- }
- } else {
- $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER);
- }
-
- $this->_tokens[] = $token;
- continue;
- }
-
- if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
- if (strlen($token->getValue() > 0)) {
- if (substr($token->getValue(), 0, 1) == "@") {
- $token->setValue(substr($token->getValue(), 1));
- }
- }
- }
-
- $this->_tokens[] = $token;
- }
+ private function parseToTokens()
+ {
+ // No attempt is made to verify formulas; assumes formulas are derived from Excel, where
+ // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions.
+
+ // Check if the formula has a valid starting =
+ $formulaLength = strlen($this->formula);
+ if ($formulaLength < 2 || $this->formula{0} != '=') {
+ return;
+ }
+
+ // Helper variables
+ $tokens1 = $tokens2 = $stack = array();
+ $inString = $inPath = $inRange = $inError = false;
+ $token = $previousToken = $nextToken = null;
+
+ $index = 1;
+ $value = '';
+
+ $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A");
+ $COMPARATORS_MULTI = array(">=", "<=", "<>");
+
+ while ($index < $formulaLength) {
+ // state-dependent character evaluation (order is important)
+
+ // double-quoted strings
+ // embeds are doubled
+ // end marks token
+ if ($inString) {
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
+ if ((($index + 2) <= $formulaLength) && ($this->formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE)) {
+ $value .= PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE;
+ ++$index;
+ } else {
+ $inString = false;
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT);
+ $value = "";
+ }
+ } else {
+ $value .= $this->formula{$index};
+ }
+ ++$index;
+ continue;
+ }
+
+ // single-quoted strings (links)
+ // embeds are double
+ // end does not mark a token
+ if ($inPath) {
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
+ if ((($index + 2) <= $formulaLength) && ($this->formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE)) {
+ $value .= PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE;
+ ++$index;
+ } else {
+ $inPath = false;
+ }
+ } else {
+ $value .= $this->formula{$index};
+ }
+ ++$index;
+ continue;
+ }
+
+ // bracked strings (R1C1 range index or linked workbook name)
+ // no embeds (changed to "()" by Excel)
+ // end does not mark a token
+ if ($inRange) {
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_CLOSE) {
+ $inRange = false;
+ }
+ $value .= $this->formula{$index};
+ ++$index;
+ continue;
+ }
+
+ // error values
+ // end marks a token, determined from absolute list of values
+ if ($inError) {
+ $value .= $this->formula{$index};
+ ++$index;
+ if (in_array($value, $ERRORS)) {
+ $inError = false;
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR);
+ $value = "";
+ }
+ continue;
+ }
+
+ // scientific notation check
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_SN, $this->formula{$index}) !== false) {
+ if (strlen($value) > 1) {
+ if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->formula{$index}) != 0) {
+ $value .= $this->formula{$index};
+ ++$index;
+ continue;
+ }
+ }
+ }
+
+ // independent character evaluation (order not important)
+
+ // establish state-dependent character evaluations
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
+ if (strlen($value > 0)) {
+ // unexpected
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+ $inString = true;
+ ++$index;
+ continue;
+ }
+
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
+ if (strlen($value) > 0) {
+ // unexpected
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+ $inPath = true;
+ ++$index;
+ continue;
+ }
+
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_OPEN) {
+ $inRange = true;
+ $value .= PHPExcel_Calculation_FormulaParser::BRACKET_OPEN;
+ ++$index;
+ continue;
+ }
+
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::ERROR_START) {
+ if (strlen($value) > 0) {
+ // unexpected
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+ $inError = true;
+ $value .= PHPExcel_Calculation_FormulaParser::ERROR_START;
+ ++$index;
+ continue;
+ }
+
+ // mark start and end of arrays and array rows
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_OPEN) {
+ if (strlen($value) > 0) {
+ // unexpected
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
+ $value = "";
+ }
+
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAY", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+
+ ++$index;
+ continue;
+ }
+
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::SEMICOLON) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
+
+ $tmp = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
+ $tokens1[] = $tmp;
+
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+
+ ++$index;
+ continue;
+ }
+
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_CLOSE) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
+
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
+
+ ++$index;
+ continue;
+ }
+
+ // trim white-space
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE);
+ ++$index;
+ while (($this->formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) {
+ ++$index;
+ }
+ continue;
+ }
+
+ // multi-character comparators
+ if (($index + 2) <= $formulaLength) {
+ if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(substr($this->formula, $index, 2), PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
+ $index += 2;
+ continue;
+ }
+ }
+
+ // standard infix operators
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_INFIX, $this->formula{$index}) !== false) {
+ if (strlen($value) > 0) {
+ $tokens1[] =new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX);
+ ++$index;
+ continue;
+ }
+
+ // standard postfix operators (only one)
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_POSTFIX, $this->formula{$index}) !== false) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
+ ++$index;
+ continue;
+ }
+
+ // start subexpression or function
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_OPEN) {
+ if (strlen($value) > 0) {
+ $tmp = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+ $value = "";
+ } else {
+ $tmp = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
+ $tokens1[] = $tmp;
+ $stack[] = clone $tmp;
+ }
+ ++$index;
+ continue;
+ }
+
+ // function, subexpression, or array parameters, or operand unions
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::COMMA) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $stack[] = $tmp;
+
+ if ($tmp->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_UNION);
+ } else {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
+ }
+ ++$index;
+ continue;
+ }
+
+ // stop subexpression
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_CLOSE) {
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ $value = "";
+ }
+
+ $tmp = array_pop($stack);
+ $tmp->setValue("");
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
+ $tokens1[] = $tmp;
+
+ ++$index;
+ continue;
+ }
+
+ // token accumulation
+ $value .= $this->formula{$index};
+ ++$index;
+ }
+
+ // dump remaining accumulation
+ if (strlen($value) > 0) {
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
+ }
+
+ // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections
+ $tokenCount = count($tokens1);
+ for ($i = 0; $i < $tokenCount; ++$i) {
+ $token = $tokens1[$i];
+ if (isset($tokens1[$i - 1])) {
+ $previousToken = $tokens1[$i - 1];
+ } else {
+ $previousToken = null;
+ }
+ if (isset($tokens1[$i + 1])) {
+ $nextToken = $tokens1[$i + 1];
+ } else {
+ $nextToken = null;
+ }
+
+ if (is_null($token)) {
+ continue;
+ }
+
+ if ($token->getTokenType() != PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) {
+ $tokens2[] = $token;
+ continue;
+ }
+
+ if (is_null($previousToken)) {
+ continue;
+ }
+
+ if (! (
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
+ ) ) {
+ continue;
+ }
+
+ if (is_null($nextToken)) {
+ continue;
+ }
+
+ if (! (
+ (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
+ (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
+ ($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
+ ) ) {
+ continue;
+ }
+
+ $tokens2[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION);
+ }
+
+ // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
+ // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
+ $this->tokens = array();
+
+ $tokenCount = count($tokens2);
+ for ($i = 0; $i < $tokenCount; ++$i) {
+ $token = $tokens2[$i];
+ if (isset($tokens2[$i - 1])) {
+ $previousToken = $tokens2[$i - 1];
+ } else {
+ $previousToken = null;
+ }
+ if (isset($tokens2[$i + 1])) {
+ $nextToken = $tokens2[$i + 1];
+ } else {
+ $nextToken = null;
+ }
+
+ if (is_null($token)) {
+ continue;
+ }
+
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") {
+ if ($i == 0) {
+ $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
+ } elseif ((($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) &&
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) &&
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)) {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
+ } else {
+ $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
+ }
+
+ $this->tokens[] = $token;
+ continue;
+ }
+
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") {
+ if ($i == 0) {
+ continue;
+ } elseif ((($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) &&
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) &&
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)) {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
+ } else {
+ continue;
+ }
+
+ $this->tokens[] = $token;
+ continue;
+ }
+
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX &&
+ $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
+ if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
+ } elseif ($token->getValue() == "&") {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
+ } else {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
+ }
+
+ $this->tokens[] = $token;
+ continue;
+ }
+
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND &&
+ $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
+ if (!is_numeric($token->getValue())) {
+ if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
+ } else {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE);
+ }
+ } else {
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER);
+ }
+
+ $this->tokens[] = $token;
+ continue;
+ }
+
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
+ if (strlen($token->getValue() > 0)) {
+ if (substr($token->getValue(), 0, 1) == "@") {
+ $token->setValue(substr($token->getValue(), 1));
+ }
+ }
+ }
+
+ $this->tokens[] = $token;
+ }
}
}
diff --git a/Classes/PHPExcel/Calculation/FormulaToken.php b/Classes/PHPExcel/Calculation/FormulaToken.php
index a5acbd1bd..41c6e3d5d 100644
--- a/Classes/PHPExcel/Calculation/FormulaToken.php
+++ b/Classes/PHPExcel/Calculation/FormulaToken.php
@@ -1,8 +1,32 @@
_value = $pValue;
- $this->_tokenType = $pTokenType;
- $this->_tokenSubType = $pTokenSubType;
+ // Initialise values
+ $this->value = $pValue;
+ $this->tokenType = $pTokenType;
+ $this->tokenSubType = $pTokenSubType;
}
/**
@@ -125,17 +119,19 @@ public function __construct($pValue, $pTokenType = PHPExcel_Calculation_FormulaT
*
* @return string
*/
- public function getValue() {
- return $this->_value;
+ public function getValue()
+ {
+ return $this->value;
}
/**
* Set Value
*
- * @param string $value
+ * @param string $value
*/
- public function setValue($value) {
- $this->_value = $value;
+ public function setValue($value)
+ {
+ $this->value = $value;
}
/**
@@ -143,17 +139,19 @@ public function setValue($value) {
*
* @return string
*/
- public function getTokenType() {
- return $this->_tokenType;
+ public function getTokenType()
+ {
+ return $this->tokenType;
}
/**
* Set Token Type
*
- * @param string $value
+ * @param string $value
*/
- public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN) {
- $this->_tokenType = $value;
+ public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN)
+ {
+ $this->tokenType = $value;
}
/**
@@ -161,16 +159,18 @@ public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_T
*
* @return string
*/
- public function getTokenSubType() {
- return $this->_tokenSubType;
+ public function getTokenSubType()
+ {
+ return $this->tokenSubType;
}
/**
* Set Token SubType
*
- * @param string $value
+ * @param string $value
*/
- public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
- $this->_tokenSubType = $value;
+ public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING)
+ {
+ $this->tokenSubType = $value;
}
}
diff --git a/Classes/PHPExcel/Calculation/Function.php b/Classes/PHPExcel/Calculation/Function.php
index 3ca09904d..d58cef253 100644
--- a/Classes/PHPExcel/Calculation/Function.php
+++ b/Classes/PHPExcel/Calculation/Function.php
@@ -1,8 +1,9 @@
_category = $pCategory;
- $this->_excelName = $pExcelName;
- $this->_phpExcelName = $pPHPExcelName;
- } else {
- throw new PHPExcel_Calculation_Exception("Invalid parameters passed.");
- }
+ if (($pCategory !== null) && ($pExcelName !== null) && ($pPHPExcelName !== null)) {
+ // Initialise values
+ $this->category = $pCategory;
+ $this->excelName = $pExcelName;
+ $this->phpExcelName = $pPHPExcelName;
+ } else {
+ throw new PHPExcel_Calculation_Exception("Invalid parameters passed.");
+ }
}
/**
@@ -93,22 +86,24 @@ public function __construct($pCategory = NULL, $pExcelName = NULL, $pPHPExcelNam
*
* @return string
*/
- public function getCategory() {
- return $this->_category;
+ public function getCategory()
+ {
+ return $this->category;
}
/**
* Set Category (represented by CATEGORY_*)
*
- * @param string $value
- * @throws PHPExcel_Calculation_Exception
+ * @param string $value
+ * @throws PHPExcel_Calculation_Exception
*/
- public function setCategory($value = null) {
- if (!is_null($value)) {
- $this->_category = $value;
- } else {
- throw new PHPExcel_Calculation_Exception("Invalid parameter passed.");
- }
+ public function setCategory($value = null)
+ {
+ if (!is_null($value)) {
+ $this->category = $value;
+ } else {
+ throw new PHPExcel_Calculation_Exception("Invalid parameter passed.");
+ }
}
/**
@@ -116,17 +111,19 @@ public function setCategory($value = null) {
*
* @return string
*/
- public function getExcelName() {
- return $this->_excelName;
+ public function getExcelName()
+ {
+ return $this->excelName;
}
/**
* Set Excel name
*
- * @param string $value
+ * @param string $value
*/
- public function setExcelName($value) {
- $this->_excelName = $value;
+ public function setExcelName($value)
+ {
+ $this->excelName = $value;
}
/**
@@ -134,16 +131,18 @@ public function setExcelName($value) {
*
* @return string
*/
- public function getPHPExcelName() {
- return $this->_phpExcelName;
+ public function getPHPExcelName()
+ {
+ return $this->phpExcelName;
}
/**
* Set PHPExcel name
*
- * @param string $value
+ * @param string $value
*/
- public function setPHPExcelName($value) {
- $this->_phpExcelName = $value;
+ public function setPHPExcelName($value)
+ {
+ $this->phpExcelName = $value;
}
}
diff --git a/Classes/PHPExcel/Calculation/Functions.php b/Classes/PHPExcel/Calculation/Functions.php
index f06dd6ef2..5a1e5ee5a 100644
--- a/Classes/PHPExcel/Calculation/Functions.php
+++ b/Classes/PHPExcel/Calculation/Functions.php
@@ -1,38 +1,12 @@
'#NULL!',
- 'divisionbyzero' => '#DIV/0!',
- 'value' => '#VALUE!',
- 'reference' => '#REF!',
- 'name' => '#NAME?',
- 'num' => '#NUM!',
- 'na' => '#N/A',
- 'gettingdata' => '#GETTING_DATA'
- );
-
-
- /**
- * Set the Compatibility Mode
- *
- * @access public
- * @category Function Configuration
- * @param string $compatibilityMode Compatibility Mode
- * Permitted values are:
- * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
- * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
- * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
- * @return boolean (Success or Failure)
- */
- public static function setCompatibilityMode($compatibilityMode) {
- if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
- ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
- ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
- self::$compatibilityMode = $compatibilityMode;
- return True;
- }
- return False;
- } // function setCompatibilityMode()
-
-
- /**
- * Return the current Compatibility Mode
- *
- * @access public
- * @category Function Configuration
- * @return string Compatibility Mode
- * Possible Return values are:
- * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
- * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
- * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
- */
- public static function getCompatibilityMode() {
- return self::$compatibilityMode;
- } // function getCompatibilityMode()
-
-
- /**
- * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
- *
- * @access public
- * @category Function Configuration
- * @param string $returnDateType Return Date Format
- * Permitted values are:
- * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
- * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
- * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
- * @return boolean Success or failure
- */
- public static function setReturnDateType($returnDateType) {
- if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
- ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
- ($returnDateType == self::RETURNDATE_EXCEL)) {
- self::$ReturnDateType = $returnDateType;
- return True;
- }
- return False;
- } // function setReturnDateType()
-
-
- /**
- * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
- *
- * @access public
- * @category Function Configuration
- * @return string Return Date Format
- * Possible Return values are:
- * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
- * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
- * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
- */
- public static function getReturnDateType() {
- return self::$ReturnDateType;
- } // function getReturnDateType()
-
-
- /**
- * DUMMY
- *
- * @access public
- * @category Error Returns
- * @return string #Not Yet Implemented
- */
- public static function DUMMY() {
- return '#Not Yet Implemented';
- } // function DUMMY()
-
-
- /**
- * DIV0
- *
- * @access public
- * @category Error Returns
- * @return string #Not Yet Implemented
- */
- public static function DIV0() {
- return self::$_errorCodes['divisionbyzero'];
- } // function DIV0()
-
-
- /**
- * NA
- *
- * Excel Function:
- * =NA()
- *
- * Returns the error value #N/A
- * #N/A is the error value that means "no value is available."
- *
- * @access public
- * @category Logical Functions
- * @return string #N/A!
- */
- public static function NA() {
- return self::$_errorCodes['na'];
- } // function NA()
-
-
- /**
- * NaN
- *
- * Returns the error value #NUM!
- *
- * @access public
- * @category Error Returns
- * @return string #NUM!
- */
- public static function NaN() {
- return self::$_errorCodes['num'];
- } // function NaN()
-
-
- /**
- * NAME
- *
- * Returns the error value #NAME?
- *
- * @access public
- * @category Error Returns
- * @return string #NAME?
- */
- public static function NAME() {
- return self::$_errorCodes['name'];
- } // function NAME()
-
-
- /**
- * REF
- *
- * Returns the error value #REF!
- *
- * @access public
- * @category Error Returns
- * @return string #REF!
- */
- public static function REF() {
- return self::$_errorCodes['reference'];
- } // function REF()
-
-
- /**
- * NULL
- *
- * Returns the error value #NULL!
- *
- * @access public
- * @category Error Returns
- * @return string #REF!
- */
- public static function NULL() {
- return self::$_errorCodes['null'];
- } // function NULL()
-
-
- /**
- * VALUE
- *
- * Returns the error value #VALUE!
- *
- * @access public
- * @category Error Returns
- * @return string #VALUE!
- */
- public static function VALUE() {
- return self::$_errorCodes['value'];
- } // function VALUE()
-
-
- public static function isMatrixValue($idx) {
- return ((substr_count($idx,'.') <= 1) || (preg_match('/\.[A-Z]/',$idx) > 0));
- }
-
-
- public static function isValue($idx) {
- return (substr_count($idx,'.') == 0);
- }
-
-
- public static function isCellValue($idx) {
- return (substr_count($idx,'.') > 1);
- }
-
-
- 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;
- }
- } // function _ifCondition()
-
-
- /**
- * ERROR_TYPE
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function ERROR_TYPE($value = '') {
- $value = self::flattenSingleValue($value);
-
- $i = 1;
- foreach(self::$_errorCodes as $errorCode) {
- if ($value === $errorCode) {
- return $i;
- }
- ++$i;
- }
- return self::NA();
- } // function ERROR_TYPE()
-
-
- /**
- * IS_BLANK
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_BLANK($value = NULL) {
- if (!is_null($value)) {
- $value = self::flattenSingleValue($value);
- }
-
- return is_null($value);
- } // function IS_BLANK()
-
-
- /**
- * IS_ERR
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_ERR($value = '') {
- $value = self::flattenSingleValue($value);
-
- return self::IS_ERROR($value) && (!self::IS_NA($value));
- } // function IS_ERR()
-
-
- /**
- * IS_ERROR
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_ERROR($value = '') {
- $value = self::flattenSingleValue($value);
-
- if (!is_string($value))
- return false;
- return in_array($value, array_values(self::$_errorCodes));
- } // function IS_ERROR()
-
-
- /**
- * IS_NA
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_NA($value = '') {
- $value = self::flattenSingleValue($value);
-
- return ($value === self::NA());
- } // function IS_NA()
-
-
- /**
- * IS_EVEN
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_EVEN($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- if ($value === NULL)
- return self::NAME();
- if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
- return self::VALUE();
- return ($value % 2 == 0);
- } // function IS_EVEN()
-
-
- /**
- * IS_ODD
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_ODD($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- if ($value === NULL)
- return self::NAME();
- if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
- return self::VALUE();
- return (abs($value) % 2 == 1);
- } // function IS_ODD()
-
-
- /**
- * IS_NUMBER
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_NUMBER($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- if (is_string($value)) {
- return False;
- }
- return is_numeric($value);
- } // function IS_NUMBER()
-
-
- /**
- * IS_LOGICAL
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_LOGICAL($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- return is_bool($value);
- } // function IS_LOGICAL()
-
-
- /**
- * IS_TEXT
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_TEXT($value = NULL) {
- $value = self::flattenSingleValue($value);
-
- return (is_string($value) && !self::IS_ERROR($value));
- } // function IS_TEXT()
-
-
- /**
- * IS_NONTEXT
- *
- * @param mixed $value Value to check
- * @return boolean
- */
- public static function IS_NONTEXT($value = NULL) {
- return !self::IS_TEXT($value);
- } // function IS_NONTEXT()
-
-
- /**
- * VERSION
- *
- * @return string Version information
- */
- public static function VERSION() {
- return 'PHPExcel ##VERSION##, ##DATE##';
- } // function VERSION()
-
-
- /**
- * N
- *
- * Returns a value converted to a number
- *
- * @param value The value you want converted
- * @return number N converts values listed in the following table
- * If value is or refers to N returns
- * A number That number
- * A date The serial number of that date
- * TRUE 1
- * FALSE 0
- * An error value The error value
- * Anything else 0
- */
- public static function N($value = NULL) {
- while (is_array($value)) {
- $value = array_shift($value);
- }
-
- switch (gettype($value)) {
- case 'double' :
- case 'float' :
- case 'integer' :
- return $value;
- break;
- case 'boolean' :
- return (integer) $value;
- break;
- case 'string' :
- // Errors
- if ((strlen($value) > 0) && ($value{0} == '#')) {
- return $value;
- }
- break;
- }
- return 0;
- } // function N()
-
-
- /**
- * TYPE
- *
- * Returns a number that identifies the type of a value
- *
- * @param value The value you want tested
- * @return number N converts values listed in the following table
- * If value is or refers to N returns
- * A number 1
- * Text 2
- * Logical Value 4
- * An error value 16
- * Array or Matrix 64
- */
- public static function TYPE($value = NULL) {
- $value = self::flattenArrayIndexed($value);
- if (is_array($value) && (count($value) > 1)) {
- $a = array_keys($value);
- $a = array_pop($a);
- // Range of cells is an error
- if (self::isCellValue($a)) {
- return 16;
- // Test for Matrix
- } elseif (self::isMatrixValue($a)) {
- return 64;
- }
- } elseif(empty($value)) {
- // Empty Cell
- return 1;
- }
- $value = self::flattenSingleValue($value);
-
- if (($value === NULL) || (is_float($value)) || (is_int($value))) {
- return 1;
- } elseif(is_bool($value)) {
- return 4;
- } elseif(is_array($value)) {
- return 64;
- break;
- } elseif(is_string($value)) {
- // Errors
- if ((strlen($value) > 0) && ($value{0} == '#')) {
- return 16;
- }
- return 2;
- }
- return 0;
- } // function TYPE()
-
-
- /**
- * Convert a multi-dimensional array to a simple 1-dimensional array
- *
- * @param array $array Array to be flattened
- * @return array Flattened array
- */
- public static function flattenArray($array) {
- if (!is_array($array)) {
- return (array) $array;
- }
-
- $arrayValues = array();
- foreach ($array as $value) {
- if (is_array($value)) {
- foreach ($value as $val) {
- if (is_array($val)) {
- foreach ($val as $v) {
- $arrayValues[] = $v;
- }
- } else {
- $arrayValues[] = $val;
- }
- }
- } else {
- $arrayValues[] = $value;
- }
- }
-
- return $arrayValues;
- } // function flattenArray()
-
-
- /**
- * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
- *
- * @param array $array Array to be flattened
- * @return array Flattened array
- */
- public static function flattenArrayIndexed($array) {
- if (!is_array($array)) {
- return (array) $array;
- }
-
- $arrayValues = array();
- foreach ($array as $k1 => $value) {
- if (is_array($value)) {
- foreach ($value as $k2 => $val) {
- if (is_array($val)) {
- foreach ($val as $k3 => $v) {
- $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
- }
- } else {
- $arrayValues[$k1.'.'.$k2] = $val;
- }
- }
- } else {
- $arrayValues[$k1] = $value;
- }
- }
-
- return $arrayValues;
- } // function flattenArrayIndexed()
-
-
- /**
- * Convert an array to a single scalar value by extracting the first element
- *
- * @param mixed $value Array or scalar value
- * @return mixed
- */
- public static function flattenSingleValue($value = '') {
- while (is_array($value)) {
- $value = array_pop($value);
- }
-
- return $value;
- } // function flattenSingleValue()
-
-} // class PHPExcel_Calculation_Functions
+class PHPExcel_Calculation_Functions
+{
+
+ /** constants */
+ const COMPATIBILITY_EXCEL = 'Excel';
+ const COMPATIBILITY_GNUMERIC = 'Gnumeric';
+ const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
+
+ const RETURNDATE_PHP_NUMERIC = 'P';
+ const RETURNDATE_PHP_OBJECT = 'O';
+ const RETURNDATE_EXCEL = 'E';
+
+
+ /**
+ * Compatibility mode to use for error checking and responses
+ *
+ * @access private
+ * @var string
+ */
+ protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
+
+ /**
+ * Data Type to use when returning date values
+ *
+ * @access private
+ * @var string
+ */
+ protected static $returnDateType = self::RETURNDATE_EXCEL;
+
+ /**
+ * List of error codes
+ *
+ * @access private
+ * @var array
+ */
+ protected static $errorCodes = array(
+ 'null' => '#NULL!',
+ 'divisionbyzero' => '#DIV/0!',
+ 'value' => '#VALUE!',
+ 'reference' => '#REF!',
+ 'name' => '#NAME?',
+ 'num' => '#NUM!',
+ 'na' => '#N/A',
+ 'gettingdata' => '#GETTING_DATA'
+ );
+
+
+ /**
+ * Set the Compatibility Mode
+ *
+ * @access public
+ * @category Function Configuration
+ * @param string $compatibilityMode Compatibility Mode
+ * Permitted values are:
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
+ * @return boolean (Success or Failure)
+ */
+ public static function setCompatibilityMode($compatibilityMode)
+ {
+ if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
+ ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
+ ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
+ self::$compatibilityMode = $compatibilityMode;
+ return true;
+ }
+ return false;
+ }
+
+
+ /**
+ * Return the current Compatibility Mode
+ *
+ * @access public
+ * @category Function Configuration
+ * @return string Compatibility Mode
+ * Possible Return values are:
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
+ */
+ public static function getCompatibilityMode()
+ {
+ return self::$compatibilityMode;
+ }
+
+
+ /**
+ * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
+ *
+ * @access public
+ * @category Function Configuration
+ * @param string $returnDateType Return Date Format
+ * Permitted values are:
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
+ * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
+ * @return boolean Success or failure
+ */
+ public static function setReturnDateType($returnDateType)
+ {
+ if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
+ ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
+ ($returnDateType == self::RETURNDATE_EXCEL)) {
+ self::$returnDateType = $returnDateType;
+ return true;
+ }
+ return false;
+ }
+
+
+ /**
+ * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
+ *
+ * @access public
+ * @category Function Configuration
+ * @return string Return Date Format
+ * Possible Return values are:
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
+ * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
+ */
+ public static function getReturnDateType()
+ {
+ return self::$returnDateType;
+ }
+
+
+ /**
+ * DUMMY
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #Not Yet Implemented
+ */
+ public static function DUMMY()
+ {
+ return '#Not Yet Implemented';
+ }
+
+
+ /**
+ * DIV0
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #Not Yet Implemented
+ */
+ public static function DIV0()
+ {
+ return self::$errorCodes['divisionbyzero'];
+ }
+
+
+ /**
+ * NA
+ *
+ * Excel Function:
+ * =NA()
+ *
+ * Returns the error value #N/A
+ * #N/A is the error value that means "no value is available."
+ *
+ * @access public
+ * @category Logical Functions
+ * @return string #N/A!
+ */
+ public static function NA()
+ {
+ return self::$errorCodes['na'];
+ }
+
+
+ /**
+ * NaN
+ *
+ * Returns the error value #NUM!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #NUM!
+ */
+ public static function NaN()
+ {
+ return self::$errorCodes['num'];
+ }
+
+
+ /**
+ * NAME
+ *
+ * Returns the error value #NAME?
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #NAME?
+ */
+ public static function NAME()
+ {
+ return self::$errorCodes['name'];
+ }
+
+
+ /**
+ * REF
+ *
+ * Returns the error value #REF!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #REF!
+ */
+ public static function REF()
+ {
+ return self::$errorCodes['reference'];
+ }
+
+
+ /**
+ * NULL
+ *
+ * Returns the error value #NULL!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #NULL!
+ */
+ public static function NULL()
+ {
+ return self::$errorCodes['null'];
+ }
+
+
+ /**
+ * VALUE
+ *
+ * Returns the error value #VALUE!
+ *
+ * @access public
+ * @category Error Returns
+ * @return string #VALUE!
+ */
+ public static function VALUE()
+ {
+ return self::$errorCodes['value'];
+ }
+
+
+ public static function isMatrixValue($idx)
+ {
+ return ((substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0));
+ }
+
+
+ public static function isValue($idx)
+ {
+ return (substr_count($idx, '.') == 0);
+ }
+
+
+ public static function isCellValue($idx)
+ {
+ return (substr_count($idx, '.') > 1);
+ }
+
+
+ public static function ifCondition($condition)
+ {
+ $condition = PHPExcel_Calculation_Functions::flattenSingleValue($condition);
+ if (!isset($condition{0})) {
+ $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 = str_replace('"', '""', $operand);
+ $operand = PHPExcel_Calculation::wrapResult(strtoupper($operand));
+ }
+
+ return $operator.$operand;
+ }
+ }
+
+ /**
+ * ERROR_TYPE
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function ERROR_TYPE($value = '')
+ {
+ $value = self::flattenSingleValue($value);
+
+ $i = 1;
+ foreach (self::$errorCodes as $errorCode) {
+ if ($value === $errorCode) {
+ return $i;
+ }
+ ++$i;
+ }
+ return self::NA();
+ }
+
+
+ /**
+ * IS_BLANK
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_BLANK($value = null)
+ {
+ if (!is_null($value)) {
+ $value = self::flattenSingleValue($value);
+ }
+
+ return is_null($value);
+ }
+
+
+ /**
+ * IS_ERR
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_ERR($value = '')
+ {
+ $value = self::flattenSingleValue($value);
+
+ return self::IS_ERROR($value) && (!self::IS_NA($value));
+ }
+
+
+ /**
+ * IS_ERROR
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_ERROR($value = '')
+ {
+ $value = self::flattenSingleValue($value);
+
+ if (!is_string($value)) {
+ return false;
+ }
+ return in_array($value, array_values(self::$errorCodes));
+ }
+
+
+ /**
+ * IS_NA
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_NA($value = '')
+ {
+ $value = self::flattenSingleValue($value);
+
+ return ($value === self::NA());
+ }
+
+
+ /**
+ * IS_EVEN
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_EVEN($value = null)
+ {
+ $value = self::flattenSingleValue($value);
+
+ if ($value === null) {
+ return self::NAME();
+ } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
+ return self::VALUE();
+ }
+
+ return ($value % 2 == 0);
+ }
+
+
+ /**
+ * IS_ODD
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_ODD($value = null)
+ {
+ $value = self::flattenSingleValue($value);
+
+ if ($value === null) {
+ return self::NAME();
+ } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
+ return self::VALUE();
+ }
+
+ return (abs($value) % 2 == 1);
+ }
+
+
+ /**
+ * IS_NUMBER
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_NUMBER($value = null)
+ {
+ $value = self::flattenSingleValue($value);
+
+ if (is_string($value)) {
+ return false;
+ }
+ return is_numeric($value);
+ }
+
+
+ /**
+ * IS_LOGICAL
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_LOGICAL($value = null)
+ {
+ $value = self::flattenSingleValue($value);
+
+ return is_bool($value);
+ }
+
+
+ /**
+ * IS_TEXT
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_TEXT($value = null)
+ {
+ $value = self::flattenSingleValue($value);
+
+ return (is_string($value) && !self::IS_ERROR($value));
+ }
+
+
+ /**
+ * IS_NONTEXT
+ *
+ * @param mixed $value Value to check
+ * @return boolean
+ */
+ public static function IS_NONTEXT($value = null)
+ {
+ return !self::IS_TEXT($value);
+ }
+
+
+ /**
+ * VERSION
+ *
+ * @return string Version information
+ */
+ public static function VERSION()
+ {
+ return 'PHPExcel ##VERSION##, ##DATE##';
+ }
+
+
+ /**
+ * N
+ *
+ * Returns a value converted to a number
+ *
+ * @param value The value you want converted
+ * @return number N converts values listed in the following table
+ * If value is or refers to N returns
+ * A number That number
+ * A date The serial number of that date
+ * TRUE 1
+ * FALSE 0
+ * An error value The error value
+ * Anything else 0
+ */
+ public static function N($value = null)
+ {
+ while (is_array($value)) {
+ $value = array_shift($value);
+ }
+
+ switch (gettype($value)) {
+ case 'double':
+ case 'float':
+ case 'integer':
+ return $value;
+ case 'boolean':
+ return (integer) $value;
+ case 'string':
+ // Errors
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
+ return $value;
+ }
+ break;
+ }
+ return 0;
+ }
+
+
+ /**
+ * TYPE
+ *
+ * Returns a number that identifies the type of a value
+ *
+ * @param value The value you want tested
+ * @return number N converts values listed in the following table
+ * If value is or refers to N returns
+ * A number 1
+ * Text 2
+ * Logical Value 4
+ * An error value 16
+ * Array or Matrix 64
+ */
+ public static function TYPE($value = null)
+ {
+ $value = self::flattenArrayIndexed($value);
+ if (is_array($value) && (count($value) > 1)) {
+ end($value);
+ $a = key($value);
+ // Range of cells is an error
+ if (self::isCellValue($a)) {
+ return 16;
+ // Test for Matrix
+ } elseif (self::isMatrixValue($a)) {
+ return 64;
+ }
+ } elseif (empty($value)) {
+ // Empty Cell
+ return 1;
+ }
+ $value = self::flattenSingleValue($value);
+
+ if (($value === null) || (is_float($value)) || (is_int($value))) {
+ return 1;
+ } elseif (is_bool($value)) {
+ return 4;
+ } elseif (is_array($value)) {
+ return 64;
+ } elseif (is_string($value)) {
+ // Errors
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
+ return 16;
+ }
+ return 2;
+ }
+ return 0;
+ }
+
+
+ /**
+ * Convert a multi-dimensional array to a simple 1-dimensional array
+ *
+ * @param array $array Array to be flattened
+ * @return array Flattened array
+ */
+ public static function flattenArray($array)
+ {
+ if (!is_array($array)) {
+ return (array) $array;
+ }
+
+ $arrayValues = array();
+ foreach ($array as $value) {
+ if (is_array($value)) {
+ foreach ($value as $val) {
+ if (is_array($val)) {
+ foreach ($val as $v) {
+ $arrayValues[] = $v;
+ }
+ } else {
+ $arrayValues[] = $val;
+ }
+ }
+ } else {
+ $arrayValues[] = $value;
+ }
+ }
+
+ return $arrayValues;
+ }
+
+
+ /**
+ * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
+ *
+ * @param array $array Array to be flattened
+ * @return array Flattened array
+ */
+ public static function flattenArrayIndexed($array)
+ {
+ if (!is_array($array)) {
+ return (array) $array;
+ }
+
+ $arrayValues = array();
+ foreach ($array as $k1 => $value) {
+ if (is_array($value)) {
+ foreach ($value as $k2 => $val) {
+ if (is_array($val)) {
+ foreach ($val as $k3 => $v) {
+ $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
+ }
+ } else {
+ $arrayValues[$k1.'.'.$k2] = $val;
+ }
+ }
+ } else {
+ $arrayValues[$k1] = $value;
+ }
+ }
+
+ return $arrayValues;
+ }
+
+
+ /**
+ * Convert an array to a single scalar value by extracting the first element
+ *
+ * @param mixed $value Array or scalar value
+ * @return mixed
+ */
+ public static function flattenSingleValue($value = '')
+ {
+ while (is_array($value)) {
+ $value = array_pop($value);
+ }
+
+ return $value;
+ }
+}
//
-// There are a few mathematical functions that aren't available on all versions of PHP for all platforms
-// These functions aren't available in Windows implementations of PHP prior to version 5.3.0
-// So we test if they do exist for this version of PHP/operating platform; and if not we create them
+// There are a few mathematical functions that aren't available on all versions of PHP for all platforms
+// These functions aren't available in Windows implementations of PHP prior to version 5.3.0
+// So we test if they do exist for this version of PHP/operating platform; and if not we create them
//
if (!function_exists('acosh')) {
- function acosh($x) {
- return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
- } // function acosh()
+ function acosh($x)
+ {
+ return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
+ } // function acosh()
}
if (!function_exists('asinh')) {
- function asinh($x) {
- return log($x + sqrt(1 + $x * $x));
- } // function asinh()
+ function asinh($x)
+ {
+ return log($x + sqrt(1 + $x * $x));
+ } // function asinh()
}
if (!function_exists('atanh')) {
- function atanh($x) {
- return (log(1 + $x) - log(1 - $x)) / 2;
- } // function atanh()
-}
-
-if (!function_exists('money_format')) {
- function money_format($format, $number) {
- $regex = array( '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?(?:#([0-9]+))?',
- '(?:\.([0-9]+))?([in%])/'
- );
- $regex = implode('', $regex);
- if (setlocale(LC_MONETARY, null) == '') {
- setlocale(LC_MONETARY, '');
- }
- $locale = localeconv();
- $number = floatval($number);
- if (!preg_match($regex, $format, $fmatch)) {
- trigger_error("No format specified or invalid format", E_USER_WARNING);
- return $number;
- }
- $flags = array( 'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
- 'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
- 'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
- 'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
- 'isleft' => preg_match('/\-/', $fmatch[1]) > 0
- );
- $width = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
- $left = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
- $right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
- $conversion = $fmatch[5];
- $positive = true;
- if ($number < 0) {
- $positive = false;
- $number *= -1;
- }
- $letter = $positive ? 'p' : 'n';
- $prefix = $suffix = $cprefix = $csuffix = $signal = '';
- if (!$positive) {
- $signal = $locale['negative_sign'];
- switch (true) {
- case $locale['n_sign_posn'] == 0 || $flags['usesignal'] == '(':
- $prefix = '(';
- $suffix = ')';
- break;
- case $locale['n_sign_posn'] == 1:
- $prefix = $signal;
- break;
- case $locale['n_sign_posn'] == 2:
- $suffix = $signal;
- break;
- case $locale['n_sign_posn'] == 3:
- $cprefix = $signal;
- break;
- case $locale['n_sign_posn'] == 4:
- $csuffix = $signal;
- break;
- }
- }
- if (!$flags['nosimbol']) {
- $currency = $cprefix;
- $currency .= ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']);
- $currency .= $csuffix;
- $currency = iconv('ISO-8859-1','UTF-8',$currency);
- } else {
- $currency = '';
- }
- $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
-
- if (!isset($locale['mon_decimal_point']) || empty($locale['mon_decimal_point'])) {
- $locale['mon_decimal_point'] = (!isset($locale['decimal_point']) || empty($locale['decimal_point'])) ?
- $locale['decimal_point'] :
- '.';
- }
-
- $number = number_format($number, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep'] );
- $number = explode($locale['mon_decimal_point'], $number);
-
- $n = strlen($prefix) + strlen($currency);
- if ($left > 0 && $left > $n) {
- if ($flags['isleft']) {
- $number[0] .= str_repeat($flags['fillchar'], $left - $n);
- } else {
- $number[0] = str_repeat($flags['fillchar'], $left - $n) . $number[0];
- }
- }
- $number = implode($locale['mon_decimal_point'], $number);
- if ($locale["{$letter}_cs_precedes"]) {
- $number = $prefix . $currency . $space . $number . $suffix;
- } else {
- $number = $prefix . $number . $space . $currency . $suffix;
- }
- if ($width > 0) {
- $number = str_pad($number, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
- }
- $format = str_replace($fmatch[0], $number, $format);
- return $format;
- } // function money_format()
+ function atanh($x)
+ {
+ return (log(1 + $x) - log(1 - $x)) / 2;
+ } // function atanh()
}
//
-// Strangely, PHP doesn't have a mb_str_replace multibyte function
-// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
+// Strangely, PHP doesn't have a mb_str_replace multibyte function
+// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
//
if ((!function_exists('mb_str_replace')) &&
- (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
- function mb_str_replace($search, $replace, $subject) {
- if(is_array($subject)) {
- $ret = array();
- foreach($subject as $key => $val) {
- $ret[$key] = mb_str_replace($search, $replace, $val);
- }
- return $ret;
- }
-
- foreach((array) $search as $key => $s) {
- if($s == '') {
- continue;
- }
- $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
- $pos = mb_strpos($subject, $s, 0, 'UTF-8');
- while($pos !== false) {
- $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
- $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
- }
- }
- return $subject;
- }
+ (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
+ function mb_str_replace($search, $replace, $subject)
+ {
+ if (is_array($subject)) {
+ $ret = array();
+ foreach ($subject as $key => $val) {
+ $ret[$key] = mb_str_replace($search, $replace, $val);
+ }
+ return $ret;
+ }
+
+ foreach ((array) $search as $key => $s) {
+ if ($s == '' && $s !== 0) {
+ continue;
+ }
+ $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
+ $pos = mb_strpos($subject, $s, 0, 'UTF-8');
+ while ($pos !== false) {
+ $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
+ $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
+ }
+ }
+ return $subject;
+ }
}
diff --git a/Classes/PHPExcel/Calculation/Logical.php b/Classes/PHPExcel/Calculation/Logical.php
index 5d6a31c8d..dd65f0104 100644
--- a/Classes/PHPExcel/Calculation/Logical.php
+++ b/Classes/PHPExcel/Calculation/Logical.php
@@ -1,8 +1,18 @@
$arg) {
- // Is it a boolean value?
- if (is_bool($arg)) {
- $returnValue = $returnValue && $arg;
- } elseif ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue = $returnValue && ($arg != 0);
- } elseif (is_string($arg)) {
- $arg = strtoupper($arg);
- if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
- $arg = TRUE;
- } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
- $arg = FALSE;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $returnValue = $returnValue && ($arg != 0);
- }
- }
+ // Loop through the arguments
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ $argCount = -1;
+ foreach ($aArgs as $argCount => $arg) {
+ // Is it a boolean value?
+ if (is_bool($arg)) {
+ $returnValue = $returnValue && $arg;
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue = $returnValue && ($arg != 0);
+ } elseif (is_string($arg)) {
+ $arg = strtoupper($arg);
+ if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
+ $arg = true;
+ } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
+ $arg = false;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $returnValue = $returnValue && ($arg != 0);
+ }
+ }
- // Return
- if ($argCount < 0) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- return $returnValue;
- } // function LOGICAL_AND()
+ // Return
+ if ($argCount < 0) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ return $returnValue;
+ }
- /**
- * LOGICAL_OR
- *
- * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
- *
- * Excel Function:
- * =OR(logical1[,logical2[, ...]])
- *
- * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
- * or references that contain logical values.
- *
- * 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 $arg,... Data values
- * @return boolean The logical OR of the arguments.
- */
- public static function LOGICAL_OR() {
- // Return value
- $returnValue = FALSE;
+ /**
+ * LOGICAL_OR
+ *
+ * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
+ *
+ * Excel Function:
+ * =OR(logical1[,logical2[, ...]])
+ *
+ * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
+ * or references that contain logical values.
+ *
+ * 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 $arg,... Data values
+ * @return boolean The logical OR of the arguments.
+ */
+ public static function LOGICAL_OR()
+ {
+ // Return value
+ $returnValue = false;
- // Loop through the arguments
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
- $argCount = -1;
- foreach ($aArgs as $argCount => $arg) {
- // Is it a boolean value?
- if (is_bool($arg)) {
- $returnValue = $returnValue || $arg;
- } elseif ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue = $returnValue || ($arg != 0);
- } elseif (is_string($arg)) {
- $arg = strtoupper($arg);
- if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
- $arg = TRUE;
- } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
- $arg = FALSE;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $returnValue = $returnValue || ($arg != 0);
- }
- }
+ // Loop through the arguments
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+ $argCount = -1;
+ foreach ($aArgs as $argCount => $arg) {
+ // Is it a boolean value?
+ if (is_bool($arg)) {
+ $returnValue = $returnValue || $arg;
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue = $returnValue || ($arg != 0);
+ } elseif (is_string($arg)) {
+ $arg = strtoupper($arg);
+ if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
+ $arg = true;
+ } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
+ $arg = false;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $returnValue = $returnValue || ($arg != 0);
+ }
+ }
- // Return
- if ($argCount < 0) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- return $returnValue;
- } // function LOGICAL_OR()
+ // Return
+ if ($argCount < 0) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ return $returnValue;
+ }
- /**
- * 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();
- }
- }
+ /**
+ * 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;
- } // function NOT()
+ return !$logical;
+ }
- /**
- * STATEMENT_IF
- *
- * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
- *
- * Excel Function:
- * =IF(condition[,returnIfTrue[,returnIfFalse]])
- *
- * Condition is any value or expression that can be evaluated to TRUE or FALSE.
- * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
- * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
- * This argument can use any comparison calculation operator.
- * ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
- * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
- * then the IF function returns the text "Within budget"
- * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
- * the logical value TRUE for this argument.
- * ReturnIfTrue can be another formula.
- * ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
- * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
- * then the IF function returns the text "Over budget".
- * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
- * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
- * ReturnIfFalse can be another formula.
- *
- * @access public
- * @category Logical Functions
- * @param mixed $condition Condition to evaluate
- * @param mixed $returnIfTrue Value to return when condition is true
- * @param mixed $returnIfFalse Optional value to return when condition is false
- * @return mixed The value of returnIfTrue or returnIfFalse determined by condition
- */
- public static function STATEMENT_IF($condition = TRUE, $returnIfTrue = 0, $returnIfFalse = FALSE) {
- $condition = (is_null($condition)) ? TRUE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($condition);
- $returnIfTrue = (is_null($returnIfTrue)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfTrue);
- $returnIfFalse = (is_null($returnIfFalse)) ? FALSE : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfFalse);
+ /**
+ * STATEMENT_IF
+ *
+ * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
+ *
+ * Excel Function:
+ * =IF(condition[,returnIfTrue[,returnIfFalse]])
+ *
+ * Condition is any value or expression that can be evaluated to TRUE or FALSE.
+ * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
+ * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
+ * This argument can use any comparison calculation operator.
+ * ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
+ * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
+ * then the IF function returns the text "Within budget"
+ * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
+ * the logical value TRUE for this argument.
+ * ReturnIfTrue can be another formula.
+ * ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
+ * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
+ * then the IF function returns the text "Over budget".
+ * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
+ * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
+ * ReturnIfFalse can be another formula.
+ *
+ * @access public
+ * @category Logical Functions
+ * @param mixed $condition Condition to evaluate
+ * @param mixed $returnIfTrue Value to return when condition is true
+ * @param mixed $returnIfFalse Optional value to return when condition is false
+ * @return mixed The value of returnIfTrue or returnIfFalse determined by condition
+ */
+ public static function STATEMENT_IF($condition = true, $returnIfTrue = 0, $returnIfFalse = false)
+ {
+ $condition = (is_null($condition)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($condition);
+ $returnIfTrue = (is_null($returnIfTrue)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfTrue);
+ $returnIfFalse = (is_null($returnIfFalse)) ? false : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfFalse);
- return ($condition) ? $returnIfTrue : $returnIfFalse;
- } // function STATEMENT_IF()
+ return ($condition) ? $returnIfTrue : $returnIfFalse;
+ }
- /**
- * IFERROR
- *
- * Excel Function:
- * =IFERROR(testValue,errorpart)
- *
- * @access public
- * @category Logical Functions
- * @param mixed $testValue Value to check, is also the value returned when no error
- * @param mixed $errorpart Value to return when testValue is an error condition
- * @return mixed The value of errorpart or testValue determined by error condition
- */
- public static function IFERROR($testValue = '', $errorpart = '') {
- $testValue = (is_null($testValue)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($testValue);
- $errorpart = (is_null($errorpart)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($errorpart);
+ /**
+ * IFERROR
+ *
+ * Excel Function:
+ * =IFERROR(testValue,errorpart)
+ *
+ * @access public
+ * @category Logical Functions
+ * @param mixed $testValue Value to check, is also the value returned when no error
+ * @param mixed $errorpart Value to return when testValue is an error condition
+ * @return mixed The value of errorpart or testValue determined by error condition
+ */
+ public static function IFERROR($testValue = '', $errorpart = '')
+ {
+ $testValue = (is_null($testValue)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($testValue);
+ $errorpart = (is_null($errorpart)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($errorpart);
- return self::STATEMENT_IF(PHPExcel_Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue);
- } // function IFERROR()
-
-} // class PHPExcel_Calculation_Logical
+ return self::STATEMENT_IF(PHPExcel_Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue);
+ }
+}
diff --git a/Classes/PHPExcel/Calculation/LookupRef.php b/Classes/PHPExcel/Calculation/LookupRef.php
index ba89a1147..1fe77902f 100644
--- a/Classes/PHPExcel/Calculation/LookupRef.php
+++ b/Classes/PHPExcel/Calculation/LookupRef.php
@@ -1,8 +1,18 @@
'') {
+ if (strpos($sheetText, ' ') !== false) {
+ $sheetText = "'".$sheetText."'";
+ }
+ $sheetText .='!';
+ }
+ if ((!is_bool($referenceStyle)) || $referenceStyle) {
+ $rowRelative = $columnRelative = '$';
+ $column = PHPExcel_Cell::stringFromColumnIndex($column-1);
+ if (($relativity == 2) || ($relativity == 4)) {
+ $columnRelative = '';
+ }
+ if (($relativity == 3) || ($relativity == 4)) {
+ $rowRelative = '';
+ }
+ return $sheetText.$columnRelative.$column.$rowRelative.$row;
+ } else {
+ if (($relativity == 2) || ($relativity == 4)) {
+ $column = '['.$column.']';
+ }
+ if (($relativity == 3) || ($relativity == 4)) {
+ $row = '['.$row.']';
+ }
+ return $sheetText.'R'.$row.'C'.$column;
+ }
+ }
+
+
+ /**
+ * COLUMN
+ *
+ * Returns the column number of the given cell reference
+ * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
+ * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
+ *
+ * Excel Function:
+ * =COLUMN([cellAddress])
+ *
+ * @param cellAddress A reference to a range of cells for which you want the column numbers
+ * @return integer or array of integer
+ */
+ public static function COLUMN($cellAddress = null)
+ {
+ if (is_null($cellAddress) || trim($cellAddress) === '') {
+ return 0;
+ }
+
+ if (is_array($cellAddress)) {
+ foreach ($cellAddress as $columnKey => $value) {
+ $columnKey = preg_replace('/[^a-z]/i', '', $columnKey);
+ return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
+ }
+ } else {
+ if (strpos($cellAddress, '!') !== false) {
+ list($sheet, $cellAddress) = explode('!', $cellAddress);
+ }
+ if (strpos($cellAddress, ':') !== false) {
+ list($startAddress, $endAddress) = explode(':', $cellAddress);
+ $startAddress = preg_replace('/[^a-z]/i', '', $startAddress);
+ $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
+ $returnValue = array();
+ do {
+ $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
+ } while ($startAddress++ != $endAddress);
+ return $returnValue;
+ } else {
+ $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress);
+ return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
+ }
+ }
+ }
+
+
+ /**
+ * COLUMNS
+ *
+ * Returns the number of columns in an array or reference.
+ *
+ * Excel Function:
+ * =COLUMNS(cellAddress)
+ *
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
+ * @return integer The number of columns in cellAddress
+ */
+ public static function COLUMNS($cellAddress = null)
+ {
+ if (is_null($cellAddress) || $cellAddress === '') {
+ return 1;
+ } elseif (!is_array($cellAddress)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ reset($cellAddress);
+ $isMatrix = (is_numeric(key($cellAddress)));
+ list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
+
+ if ($isMatrix) {
+ return $rows;
+ } else {
+ return $columns;
+ }
+ }
+
+
+ /**
+ * ROW
+ *
+ * Returns the row number of the given cell reference
+ * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
+ * reference of the cell in which the ROW function appears; otherwise this function returns 0.
+ *
+ * Excel Function:
+ * =ROW([cellAddress])
+ *
+ * @param cellAddress A reference to a range of cells for which you want the row numbers
+ * @return integer or array of integer
+ */
+ public static function ROW($cellAddress = null)
+ {
+ if (is_null($cellAddress) || trim($cellAddress) === '') {
+ return 0;
+ }
+
+ if (is_array($cellAddress)) {
+ foreach ($cellAddress as $columnKey => $rowValue) {
+ foreach ($rowValue as $rowKey => $cellValue) {
+ return (integer) preg_replace('/[^0-9]/i', '', $rowKey);
+ }
+ }
+ } else {
+ if (strpos($cellAddress, '!') !== false) {
+ list($sheet, $cellAddress) = explode('!', $cellAddress);
+ }
+ if (strpos($cellAddress, ':') !== false) {
+ list($startAddress, $endAddress) = explode(':', $cellAddress);
+ $startAddress = preg_replace('/[^0-9]/', '', $startAddress);
+ $endAddress = preg_replace('/[^0-9]/', '', $endAddress);
+ $returnValue = array();
+ do {
+ $returnValue[][] = (integer) $startAddress;
+ } while ($startAddress++ != $endAddress);
+ return $returnValue;
+ } else {
+ list($cellAddress) = explode(':', $cellAddress);
+ return (integer) preg_replace('/[^0-9]/', '', $cellAddress);
+ }
+ }
+ }
+
+
+ /**
+ * ROWS
+ *
+ * Returns the number of rows in an array or reference.
+ *
+ * Excel Function:
+ * =ROWS(cellAddress)
+ *
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
+ * @return integer The number of rows in cellAddress
+ */
+ public static function ROWS($cellAddress = null)
+ {
+ if (is_null($cellAddress) || $cellAddress === '') {
+ return 1;
+ } elseif (!is_array($cellAddress)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ reset($cellAddress);
+ $isMatrix = (is_numeric(key($cellAddress)));
+ list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
+
+ if ($isMatrix) {
+ return $columns;
+ } else {
+ return $rows;
+ }
+ }
+
+
+ /**
+ * HYPERLINK
+ *
+ * Excel Function:
+ * =HYPERLINK(linkURL,displayName)
+ *
+ * @access public
+ * @category Logical Functions
+ * @param string $linkURL Value to check, is also the value returned when no error
+ * @param string $displayName Value to return when testValue is an error condition
+ * @param PHPExcel_Cell $pCell The cell to set the hyperlink in
+ * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
+ */
+ public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null)
+ {
+ $args = func_get_args();
+ $pCell = array_pop($args);
+
+ $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL);
+ $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName);
+
+ if ((!is_object($pCell)) || (trim($linkURL) == '')) {
+ return PHPExcel_Calculation_Functions::REF();
+ }
+
+ if ((is_object($displayName)) || trim($displayName) == '') {
+ $displayName = $linkURL;
+ }
+
+ $pCell->getHyperlink()->setUrl($linkURL);
+ $pCell->getHyperlink()->setTooltip($displayName);
+
+ return $displayName;
+ }
+
+
+ /**
+ * INDIRECT
+ *
+ * Returns the reference specified by a text string.
+ * References are immediately evaluated to display their contents.
+ *
+ * Excel Function:
+ * =INDIRECT(cellAddress)
+ *
+ * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
+ *
+ * @param cellAddress $cellAddress The cell address of the current cell (containing this formula)
+ * @param PHPExcel_Cell $pCell The current cell (containing this formula)
+ * @return mixed The cells referenced by cellAddress
+ *
+ * @todo Support for the optional a1 parameter introduced in Excel 2010
+ *
+ */
+ public static function INDIRECT($cellAddress = null, PHPExcel_Cell $pCell = null)
+ {
+ $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress);
+ if (is_null($cellAddress) || $cellAddress === '') {
+ return PHPExcel_Calculation_Functions::REF();
+ }
+
+ $cellAddress1 = $cellAddress;
+ $cellAddress2 = null;
+ if (strpos($cellAddress, ':') !== false) {
+ list($cellAddress1, $cellAddress2) = explode(':', $cellAddress);
+ }
+
+ if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
+ ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
+ if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
+ return PHPExcel_Calculation_Functions::REF();
+ }
+
+ if (strpos($cellAddress, '!') !== false) {
+ list($sheetName, $cellAddress) = explode('!', $cellAddress);
+ $sheetName = trim($sheetName, "'");
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
+ } else {
+ $pSheet = $pCell->getWorksheet();
+ }
+
+ return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false);
+ }
+
+ if (strpos($cellAddress, '!') !== false) {
+ list($sheetName, $cellAddress) = explode('!', $cellAddress);
+ $sheetName = trim($sheetName, "'");
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
+ } else {
+ $pSheet = $pCell->getWorksheet();
+ }
+
+ return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
+ }
+
+
+ /**
+ * 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.
+ *
+ * Excel Function:
+ * =OFFSET(cellAddress, rows, cols, [height], [width])
+ *
+ * @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);
+ $sheetName = trim($sheetName, "'");
+ }
+ 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->getWorksheet()->getParent()->getSheetByName($sheetName);
+ } else {
+ $pSheet = $pCell->getWorksheet();
+ }
+
+ return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
+ }
+
+
+ /**
+ * CHOOSE
+ *
+ * Uses lookup_value to return a value from the list of value arguments.
+ * Use CHOOSE to select one of up to 254 values based on the lookup_value.
+ *
+ * Excel Function:
+ * =CHOOSE(index_num, value1, [value2], ...)
+ *
+ * @param index_num Specifies which value argument is selected.
+ * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
+ * between 1 and 254.
+ * @param value1... Value1 is required, subsequent values are optional.
+ * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
+ * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
+ * text.
+ * @return mixed The selected value
+ */
+ public static function CHOOSE()
+ {
+ $chooseArgs = func_get_args();
+ $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs));
+ $entryCount = count($chooseArgs) - 1;
+
+ if (is_array($chosenEntry)) {
+ $chosenEntry = array_shift($chosenEntry);
+ }
+ if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
+ --$chosenEntry;
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $chosenEntry = floor($chosenEntry);
+ if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (is_array($chooseArgs[$chosenEntry])) {
+ return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
+ } else {
+ return $chooseArgs[$chosenEntry];
+ }
+ }
+
+
+ /**
+ * MATCH
+ *
+ * The MATCH function searches for a specified item in a range of cells
+ *
+ * Excel Function:
+ * =MATCH(lookup_value, lookup_array, [match_type])
+ *
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_array The range of cells being searched
+ * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
+ * @return integer The relative position of the found item
+ */
+ public static function MATCH($lookup_value, $lookup_array, $match_type = 1)
+ {
+ $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array);
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
+ $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type);
+ // MATCH is not case sensitive
+ $lookup_value = strtolower($lookup_value);
+
+ // lookup_value type has to be number, text, or logical values
+ if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+ // match_type is 0, 1 or -1
+ if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+ // lookup_array should not be empty
+ $lookupArraySize = count($lookup_array);
+ if ($lookupArraySize <= 0) {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+ // lookup_array should contain only number, text, or logical values, or empty (null) cells
+ foreach ($lookup_array as $i => $lookupArrayValue) {
+ // check the type of the value
+ if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
+ (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+ // convert strings to lowercase for case-insensitive testing
+ if (is_string($lookupArrayValue)) {
+ $lookup_array[$i] = strtolower($lookupArrayValue);
+ }
+ if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
+ $lookup_array = array_slice($lookup_array, 0, $i-1);
+ }
+ }
+
+ // if match_type is 1 or -1, the list has to be ordered
+ if ($match_type == 1) {
+ asort($lookup_array);
+ $keySet = array_keys($lookup_array);
+ } elseif ($match_type == -1) {
+ arsort($lookup_array);
+ $keySet = array_keys($lookup_array);
+ }
+
+ // **
+ // find the match
+ // **
+ foreach ($lookup_array as $i => $lookupArrayValue) {
+ if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
+ // exact match
+ return ++$i;
+ } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
+ $i = array_search($i, $keySet);
+ // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
+ if ($i < 1) {
+ // 1st cell was already smaller than the lookup_value
+ break;
+ } else {
+ // the previous cell was the match
+ return $keySet[$i-1]+1;
+ }
+ } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
+ $i = array_search($i, $keySet);
+ // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
+ if ($i < 1) {
+ // 1st cell was already bigger than the lookup_value
+ break;
+ } else {
+ // the previous cell was the match
+ return $keySet[$i-1]+1;
+ }
+ }
+ }
+
+ // unsuccessful in finding a match, return #N/A error value
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+
+ /**
+ * INDEX
+ *
+ * Uses an index to choose a value from a reference or array
+ *
+ * Excel Function:
+ * =INDEX(range_array, row_num, [column_num])
+ *
+ * @param range_array A range of cells or an array constant
+ * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
+ * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
+ * @return mixed the value of a specified cell or array of cells
+ */
+ public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0)
+ {
+ if (($rowNum < 0) || ($columnNum < 0)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ if (!is_array($arrayValues)) {
+ return PHPExcel_Calculation_Functions::REF();
+ }
+
+ $rowKeys = array_keys($arrayValues);
+ $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
+
+ if ($columnNum > count($columnKeys)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($columnNum == 0) {
+ if ($rowNum == 0) {
+ return $arrayValues;
+ }
+ $rowNum = $rowKeys[--$rowNum];
+ $returnArray = array();
+ foreach ($arrayValues as $arrayColumn) {
+ if (is_array($arrayColumn)) {
+ if (isset($arrayColumn[$rowNum])) {
+ $returnArray[] = $arrayColumn[$rowNum];
+ } else {
+ return $arrayValues[$rowNum];
+ }
+ } else {
+ return $arrayValues[$rowNum];
+ }
+ }
+ return $returnArray;
+ }
+ $columnNum = $columnKeys[--$columnNum];
+ if ($rowNum > count($rowKeys)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($rowNum == 0) {
+ return $arrayValues[$columnNum];
+ }
+ $rowNum = $rowKeys[--$rowNum];
+
+ return $arrayValues[$rowNum][$columnNum];
+ }
+
+
+ /**
+ * TRANSPOSE
+ *
+ * @param array $matrixData A matrix of values
+ * @return array
+ *
+ * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
+ */
+ public static function TRANSPOSE($matrixData)
+ {
+ $returnMatrix = array();
+ if (!is_array($matrixData)) {
+ $matrixData = array(array($matrixData));
+ }
+
+ $column = 0;
+ foreach ($matrixData as $matrixRow) {
+ $row = 0;
+ foreach ($matrixRow as $matrixCell) {
+ $returnMatrix[$row][$column] = $matrixCell;
+ ++$row;
+ }
+ ++$column;
+ }
+ return $returnMatrix;
+ }
+
+
+ private static function vlookupSort($a, $b)
+ {
+ reset($a);
+ $firstColumn = key($a);
+ if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) {
+ return 0;
+ }
+ return ($aLower < $bLower) ? -1 : 1;
+ }
+
+
+ /**
+ * VLOOKUP
+ * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_array The range of cells being searched
+ * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
+ * @return mixed The value of the found cell
+ */
+ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
+ {
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
+ $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
+ $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
+
+ // index_number must be greater than or equal to 1
+ if ($index_number < 1) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // index_number must be less than or equal to the number of columns in lookup_array
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
+ return PHPExcel_Calculation_Functions::REF();
+ } else {
+ $f = array_keys($lookup_array);
+ $firstRow = array_pop($f);
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
+ return PHPExcel_Calculation_Functions::REF();
+ } else {
+ $columnKeys = array_keys($lookup_array[$firstRow]);
+ $returnColumn = $columnKeys[--$index_number];
+ $firstColumn = array_shift($columnKeys);
+ }
+ }
+
+ if (!$not_exact_match) {
+ uasort($lookup_array, array('self', 'vlookupSort'));
+ }
+
+ $rowNumber = $rowValue = false;
+ foreach ($lookup_array as $rowKey => $rowData) {
+ if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
+ (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) {
+ break;
+ }
+ $rowNumber = $rowKey;
+ $rowValue = $rowData[$firstColumn];
+ }
+
+ if ($rowNumber !== false) {
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
+ // if an exact match is required, we have what we need to return an appropriate response
+ return PHPExcel_Calculation_Functions::NA();
+ } else {
+ // otherwise return the appropriate value
+ return $lookup_array[$rowNumber][$returnColumn];
+ }
+ }
+
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+
+ /**
+ * HLOOKUP
+ * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number.
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_array The range of cells being searched
+ * @param index_number The row number in table_array from which the matching value must be returned. The first row is 1.
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
+ * @return mixed The value of the found cell
+ */
+ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
+ {
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
+ $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
+ $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
+
+ // index_number must be greater than or equal to 1
+ if ($index_number < 1) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ // index_number must be less than or equal to the number of columns in lookup_array
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
+ return PHPExcel_Calculation_Functions::REF();
+ } else {
+ $f = array_keys($lookup_array);
+ $firstRow = array_pop($f);
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
+ return PHPExcel_Calculation_Functions::REF();
+ } else {
+ $columnKeys = array_keys($lookup_array[$firstRow]);
+ $firstkey = $f[0] - 1;
+ $returnColumn = $firstkey + $index_number;
+ $firstColumn = array_shift($f);
+ }
+ }
+
+ if (!$not_exact_match) {
+ $firstRowH = asort($lookup_array[$firstColumn]);
+ }
+
+ $rowNumber = $rowValue = false;
+ foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) {
+ if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) ||
+ (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) {
+ break;
+ }
+ $rowNumber = $rowKey;
+ $rowValue = $rowData;
+ }
+
+ if ($rowNumber !== false) {
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
+ // if an exact match is required, we have what we need to return an appropriate response
+ return PHPExcel_Calculation_Functions::NA();
+ } else {
+ // otherwise return the appropriate value
+ return $lookup_array[$returnColumn][$rowNumber];
+ }
+ }
+
+ return PHPExcel_Calculation_Functions::NA();
+ }
+
+
+ /**
+ * LOOKUP
+ * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
+ * @param lookup_value The value that you want to match in lookup_array
+ * @param lookup_vector The range of cells being searched
+ * @param result_vector The column from which the matching value must be returned
+ * @return mixed The value of the found cell
+ */
+ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null)
+ {
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
+
+ if (!is_array($lookup_vector)) {
+ return PHPExcel_Calculation_Functions::NA();
+ }
+ $lookupRows = count($lookup_vector);
+ $l = array_keys($lookup_vector);
+ $l = array_shift($l);
+ $lookupColumns = count($lookup_vector[$l]);
+ if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
+ $lookup_vector = self::TRANSPOSE($lookup_vector);
+ $lookupRows = count($lookup_vector);
+ $l = array_keys($lookup_vector);
+ $lookupColumns = count($lookup_vector[array_shift($l)]);
+ }
+
+ if (is_null($result_vector)) {
+ $result_vector = $lookup_vector;
+ }
+ $resultRows = count($result_vector);
+ $l = array_keys($result_vector);
+ $l = array_shift($l);
+ $resultColumns = count($result_vector[$l]);
+ if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
+ $result_vector = self::TRANSPOSE($result_vector);
+ $resultRows = count($result_vector);
+ $r = array_keys($result_vector);
+ $resultColumns = count($result_vector[array_shift($r)]);
+ }
+
+ if ($lookupRows == 2) {
+ $result_vector = array_pop($lookup_vector);
+ $lookup_vector = array_shift($lookup_vector);
+ }
+ if ($lookupColumns != 2) {
+ foreach ($lookup_vector as &$value) {
+ if (is_array($value)) {
+ $k = array_keys($value);
+ $key1 = $key2 = array_shift($k);
+ $key2++;
+ $dataValue1 = $value[$key1];
+ } else {
+ $key1 = 0;
+ $key2 = 1;
+ $dataValue1 = $value;
+ }
+ $dataValue2 = array_shift($result_vector);
+ if (is_array($dataValue2)) {
+ $dataValue2 = array_shift($dataValue2);
+ }
+ $value = array($key1 => $dataValue1, $key2 => $dataValue2);
+ }
+ unset($value);
+ }
+
+ return self::VLOOKUP($lookup_value, $lookup_vector, 2);
+ }
}
-
-
-/**
- * PHPExcel_Calculation_LookupRef
- *
- * @category PHPExcel
- * @package PHPExcel_Calculation
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- */
-class PHPExcel_Calculation_LookupRef {
-
-
- /**
- * CELL_ADDRESS
- *
- * Creates a cell address as text, given specified row and column numbers.
- *
- * Excel Function:
- * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
- *
- * @param row Row number to use in the cell reference
- * @param column Column number to use in the cell reference
- * @param relativity Flag indicating the type of reference to return
- * 1 or omitted Absolute
- * 2 Absolute row; relative column
- * 3 Relative row; absolute column
- * 4 Relative
- * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
- * TRUE or omitted CELL_ADDRESS returns an A1-style reference
- * FALSE CELL_ADDRESS returns an R1C1-style reference
- * @param sheetText Optional Name of worksheet to use
- * @return string
- */
- public static function CELL_ADDRESS($row, $column, $relativity=1, $referenceStyle=True, $sheetText='') {
- $row = PHPExcel_Calculation_Functions::flattenSingleValue($row);
- $column = PHPExcel_Calculation_Functions::flattenSingleValue($column);
- $relativity = PHPExcel_Calculation_Functions::flattenSingleValue($relativity);
- $sheetText = PHPExcel_Calculation_Functions::flattenSingleValue($sheetText);
-
- if (($row < 1) || ($column < 1)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if ($sheetText > '') {
- if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; }
- $sheetText .='!';
- }
- if ((!is_bool($referenceStyle)) || $referenceStyle) {
- $rowRelative = $columnRelative = '$';
- $column = PHPExcel_Cell::stringFromColumnIndex($column-1);
- if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; }
- if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; }
- return $sheetText.$columnRelative.$column.$rowRelative.$row;
- } else {
- if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; }
- if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; }
- return $sheetText.'R'.$row.'C'.$column;
- }
- } // function CELL_ADDRESS()
-
-
- /**
- * COLUMN
- *
- * Returns the column number of the given cell reference
- * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
- * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
- * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
- *
- * Excel Function:
- * =COLUMN([cellAddress])
- *
- * @param cellAddress A reference to a range of cells for which you want the column numbers
- * @return integer or array of integer
- */
- public static function COLUMN($cellAddress=Null) {
- if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
-
- if (is_array($cellAddress)) {
- foreach($cellAddress as $columnKey => $value) {
- $columnKey = preg_replace('/[^a-z]/i','',$columnKey);
- return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
- }
- } else {
- if (strpos($cellAddress,'!') !== false) {
- list($sheet,$cellAddress) = explode('!',$cellAddress);
- }
- if (strpos($cellAddress,':') !== false) {
- list($startAddress,$endAddress) = explode(':',$cellAddress);
- $startAddress = preg_replace('/[^a-z]/i','',$startAddress);
- $endAddress = preg_replace('/[^a-z]/i','',$endAddress);
- $returnValue = array();
- do {
- $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
- } while ($startAddress++ != $endAddress);
- return $returnValue;
- } else {
- $cellAddress = preg_replace('/[^a-z]/i','',$cellAddress);
- return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
- }
- }
- } // function COLUMN()
-
-
- /**
- * COLUMNS
- *
- * Returns the number of columns in an array or reference.
- *
- * Excel Function:
- * =COLUMNS(cellAddress)
- *
- * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
- * @return integer The number of columns in cellAddress
- */
- public static function COLUMNS($cellAddress=Null) {
- if (is_null($cellAddress) || $cellAddress === '') {
- return 1;
- } elseif (!is_array($cellAddress)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- $x = array_keys($cellAddress);
- $x = array_shift($x);
- $isMatrix = (is_numeric($x));
- list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
-
- if ($isMatrix) {
- return $rows;
- } else {
- return $columns;
- }
- } // function COLUMNS()
-
-
- /**
- * ROW
- *
- * Returns the row number of the given cell reference
- * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
- * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
- * reference of the cell in which the ROW function appears; otherwise this function returns 0.
- *
- * Excel Function:
- * =ROW([cellAddress])
- *
- * @param cellAddress A reference to a range of cells for which you want the row numbers
- * @return integer or array of integer
- */
- public static function ROW($cellAddress=Null) {
- if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
-
- if (is_array($cellAddress)) {
- foreach($cellAddress as $columnKey => $rowValue) {
- foreach($rowValue as $rowKey => $cellValue) {
- return (integer) preg_replace('/[^0-9]/i','',$rowKey);
- }
- }
- } else {
- if (strpos($cellAddress,'!') !== false) {
- list($sheet,$cellAddress) = explode('!',$cellAddress);
- }
- if (strpos($cellAddress,':') !== false) {
- list($startAddress,$endAddress) = explode(':',$cellAddress);
- $startAddress = preg_replace('/[^0-9]/','',$startAddress);
- $endAddress = preg_replace('/[^0-9]/','',$endAddress);
- $returnValue = array();
- do {
- $returnValue[][] = (integer) $startAddress;
- } while ($startAddress++ != $endAddress);
- return $returnValue;
- } else {
- list($cellAddress) = explode(':',$cellAddress);
- return (integer) preg_replace('/[^0-9]/','',$cellAddress);
- }
- }
- } // function ROW()
-
-
- /**
- * ROWS
- *
- * Returns the number of rows in an array or reference.
- *
- * Excel Function:
- * =ROWS(cellAddress)
- *
- * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
- * @return integer The number of rows in cellAddress
- */
- public static function ROWS($cellAddress=Null) {
- if (is_null($cellAddress) || $cellAddress === '') {
- return 1;
- } elseif (!is_array($cellAddress)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- $i = array_keys($cellAddress);
- $isMatrix = (is_numeric(array_shift($i)));
- list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
-
- if ($isMatrix) {
- return $columns;
- } else {
- return $rows;
- }
- } // function ROWS()
-
-
- /**
- * HYPERLINK
- *
- * Excel Function:
- * =HYPERLINK(linkURL,displayName)
- *
- * @access public
- * @category Logical Functions
- * @param string $linkURL Value to check, is also the value returned when no error
- * @param string $displayName Value to return when testValue is an error condition
- * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
- */
- public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null) {
- $args = func_get_args();
- $pCell = array_pop($args);
-
- $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL);
- $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName);
-
- if ((!is_object($pCell)) || (trim($linkURL) == '')) {
- return PHPExcel_Calculation_Functions::REF();
- }
-
- if ((is_object($displayName)) || trim($displayName) == '') {
- $displayName = $linkURL;
- }
-
- $pCell->getHyperlink()->setUrl($linkURL);
-
- return $displayName;
- } // function HYPERLINK()
-
-
- /**
- * INDIRECT
- *
- * Returns the reference specified by a text string.
- * References are immediately evaluated to display their contents.
- *
- * Excel Function:
- * =INDIRECT(cellAddress)
- *
- * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
- *
- * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
- * @return mixed The cells referenced by cellAddress
- *
- * @todo Support for the optional a1 parameter introduced in Excel 2010
- *
- */
- public static function INDIRECT($cellAddress=Null, PHPExcel_Cell $pCell = null) {
- $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress);
- if (is_null($cellAddress) || $cellAddress === '') {
- return PHPExcel_Calculation_Functions::REF();
- }
-
- $cellAddress1 = $cellAddress;
- $cellAddress2 = NULL;
- if (strpos($cellAddress,':') !== false) {
- list($cellAddress1,$cellAddress2) = explode(':',$cellAddress);
- }
-
- if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
- ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
-
- if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
- return PHPExcel_Calculation_Functions::REF();
- }
-
- if (strpos($cellAddress,'!') !== false) {
- list($sheetName,$cellAddress) = explode('!',$cellAddress);
- $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getParent();
- }
-
- return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, False);
- }
-
- if (strpos($cellAddress,'!') !== false) {
- list($sheetName,$cellAddress) = explode('!',$cellAddress);
- $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getParent();
- }
-
- return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
- } // function INDIRECT()
-
-
- /**
- * 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.
- *
- * Excel Function:
- * =OFFSET(cellAddress, rows, cols, [height], [width])
- *
- * @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);
- } // function OFFSET()
-
-
- /**
- * CHOOSE
- *
- * Uses lookup_value to return a value from the list of value arguments.
- * Use CHOOSE to select one of up to 254 values based on the lookup_value.
- *
- * Excel Function:
- * =CHOOSE(index_num, value1, [value2], ...)
- *
- * @param index_num Specifies which value argument is selected.
- * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
- * between 1 and 254.
- * @param value1... Value1 is required, subsequent values are optional.
- * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
- * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
- * text.
- * @return mixed The selected value
- */
- public static function CHOOSE() {
- $chooseArgs = func_get_args();
- $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs));
- $entryCount = count($chooseArgs) - 1;
-
- if(is_array($chosenEntry)) {
- $chosenEntry = array_shift($chosenEntry);
- }
- if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
- --$chosenEntry;
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $chosenEntry = floor($chosenEntry);
- if (($chosenEntry <= 0) || ($chosenEntry > $entryCount)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (is_array($chooseArgs[$chosenEntry])) {
- return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
- } else {
- return $chooseArgs[$chosenEntry];
- }
- } // function CHOOSE()
-
-
- /**
- * MATCH
- *
- * The MATCH function searches for a specified item in a range of cells
- *
- * Excel Function:
- * =MATCH(lookup_value, lookup_array, [match_type])
- *
- * @param lookup_value The value that you want to match in lookup_array
- * @param lookup_array The range of cells being searched
- * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
- * @return integer The relative position of the found item
- */
- public static function MATCH($lookup_value, $lookup_array, $match_type=1) {
- $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array);
- $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
- $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type);
- // MATCH is not case sensitive
- $lookup_value = strtolower($lookup_value);
-
- // lookup_value type has to be number, text, or logical values
- if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
- return PHPExcel_Calculation_Functions::NA();
- }
-
- // match_type is 0, 1 or -1
- if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
- return PHPExcel_Calculation_Functions::NA();
- }
-
- // lookup_array should not be empty
- $lookupArraySize = count($lookup_array);
- if ($lookupArraySize <= 0) {
- return PHPExcel_Calculation_Functions::NA();
- }
-
- // lookup_array should contain only number, text, or logical values, or empty (null) cells
- foreach($lookup_array as $i => $lookupArrayValue) {
- // check the type of the value
- if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
- (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
- return PHPExcel_Calculation_Functions::NA();
- }
- // convert strings to lowercase for case-insensitive testing
- if (is_string($lookupArrayValue)) {
- $lookup_array[$i] = strtolower($lookupArrayValue);
- }
- if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
- $lookup_array = array_slice($lookup_array,0,$i-1);
- }
- }
-
- // if match_type is 1 or -1, the list has to be ordered
- if ($match_type == 1) {
- asort($lookup_array);
- $keySet = array_keys($lookup_array);
- } elseif($match_type == -1) {
- arsort($lookup_array);
- $keySet = array_keys($lookup_array);
- }
-
- // **
- // find the match
- // **
- // loop on the cells
-// var_dump($lookup_array);
-// echo '
';
- foreach($lookup_array as $i => $lookupArrayValue) {
- if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
- // exact match
- return ++$i;
- } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
-// echo '$i = '.$i.' => ';
-// var_dump($lookupArrayValue);
-// echo '
';
-// echo 'Keyset = ';
-// var_dump($keySet);
-// echo '
';
- $i = array_search($i,$keySet);
-// echo '$i='.$i.'
';
- // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
- if ($i < 1){
- // 1st cell was allready smaller than the lookup_value
- break;
- } else {
- // the previous cell was the match
- return $keySet[$i-1]+1;
- }
- } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
-// echo '$i = '.$i.' => ';
-// var_dump($lookupArrayValue);
-// echo '
';
-// echo 'Keyset = ';
-// var_dump($keySet);
-// echo '
';
- $i = array_search($i,$keySet);
-// echo '$i='.$i.'
';
- // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
- if ($i < 1){
- // 1st cell was allready bigger than the lookup_value
- break;
- } else {
- // the previous cell was the match
- return $keySet[$i-1]+1;
- }
- }
- }
-
- // unsuccessful in finding a match, return #N/A error value
- return PHPExcel_Calculation_Functions::NA();
- } // function MATCH()
-
-
- /**
- * INDEX
- *
- * Uses an index to choose a value from a reference or array
- *
- * Excel Function:
- * =INDEX(range_array, row_num, [column_num])
- *
- * @param range_array A range of cells or an array constant
- * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
- * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
- * @return mixed the value of a specified cell or array of cells
- */
- public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) {
-
- if (($rowNum < 0) || ($columnNum < 0)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- if (!is_array($arrayValues)) {
- return PHPExcel_Calculation_Functions::REF();
- }
-
- $rowKeys = array_keys($arrayValues);
- $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
-
- if ($columnNum > count($columnKeys)) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($columnNum == 0) {
- if ($rowNum == 0) {
- return $arrayValues;
- }
- $rowNum = $rowKeys[--$rowNum];
- $returnArray = array();
- foreach($arrayValues as $arrayColumn) {
- if (is_array($arrayColumn)) {
- if (isset($arrayColumn[$rowNum])) {
- $returnArray[] = $arrayColumn[$rowNum];
- } else {
- return $arrayValues[$rowNum];
- }
- } else {
- return $arrayValues[$rowNum];
- }
- }
- return $returnArray;
- }
- $columnNum = $columnKeys[--$columnNum];
- if ($rowNum > count($rowKeys)) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($rowNum == 0) {
- return $arrayValues[$columnNum];
- }
- $rowNum = $rowKeys[--$rowNum];
-
- return $arrayValues[$rowNum][$columnNum];
- } // function INDEX()
-
-
- /**
- * TRANSPOSE
- *
- * @param array $matrixData A matrix of values
- * @return array
- *
- * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
- */
- public static function TRANSPOSE($matrixData) {
- $returnMatrix = array();
- if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); }
-
- $column = 0;
- foreach($matrixData as $matrixRow) {
- $row = 0;
- foreach($matrixRow as $matrixCell) {
- $returnMatrix[$row][$column] = $matrixCell;
- ++$row;
- }
- ++$column;
- }
- return $returnMatrix;
- } // function TRANSPOSE()
-
-
- private static function _vlookupSort($a,$b) {
- $f = array_keys($a);
- $firstColumn = array_shift($f);
- if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) {
- return 0;
- }
- return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1;
- } // function _vlookupSort()
-
-
- /**
- * VLOOKUP
- * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
- * @param lookup_value The value that you want to match in lookup_array
- * @param lookup_array The range of cells being searched
- * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
- * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
- * @return mixed The value of the found cell
- */
- public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
- $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
- $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
- $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
-
- // index_number must be greater than or equal to 1
- if ($index_number < 1) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- // index_number must be less than or equal to the number of columns in lookup_array
- if ((!is_array($lookup_array)) || (empty($lookup_array))) {
- return PHPExcel_Calculation_Functions::REF();
- } else {
- $f = array_keys($lookup_array);
- $firstRow = array_pop($f);
- if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
- return PHPExcel_Calculation_Functions::REF();
- } else {
- $columnKeys = array_keys($lookup_array[$firstRow]);
- $returnColumn = $columnKeys[--$index_number];
- $firstColumn = array_shift($columnKeys);
- }
- }
-
- if (!$not_exact_match) {
- uasort($lookup_array,array('self','_vlookupSort'));
- }
-
- $rowNumber = $rowValue = False;
- foreach($lookup_array as $rowKey => $rowData) {
- if (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)) {
- break;
- }
- $rowNumber = $rowKey;
- $rowValue = $rowData[$firstColumn];
- }
-
- if ($rowNumber !== false) {
- if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
- // if an exact match is required, we have what we need to return an appropriate response
- return PHPExcel_Calculation_Functions::NA();
- } else {
- // otherwise return the appropriate value
- return $lookup_array[$rowNumber][$returnColumn];
- }
- }
-
- return PHPExcel_Calculation_Functions::NA();
- } // function VLOOKUP()
-
-
- /**
- * LOOKUP
- * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
- * @param lookup_value The value that you want to match in lookup_array
- * @param lookup_vector The range of cells being searched
- * @param result_vector The column from which the matching value must be returned
- * @return mixed The value of the found cell
- */
- public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) {
- $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
-
- if (!is_array($lookup_vector)) {
- return PHPExcel_Calculation_Functions::NA();
- }
- $lookupRows = count($lookup_vector);
- $l = array_keys($lookup_vector);
- $l = array_shift($l);
- $lookupColumns = count($lookup_vector[$l]);
- if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
- $lookup_vector = self::TRANSPOSE($lookup_vector);
- $lookupRows = count($lookup_vector);
- $l = array_keys($lookup_vector);
- $lookupColumns = count($lookup_vector[array_shift($l)]);
- }
-
- if (is_null($result_vector)) {
- $result_vector = $lookup_vector;
- }
- $resultRows = count($result_vector);
- $l = array_keys($result_vector);
- $l = array_shift($l);
- $resultColumns = count($result_vector[$l]);
- if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
- $result_vector = self::TRANSPOSE($result_vector);
- $resultRows = count($result_vector);
- $r = array_keys($result_vector);
- $resultColumns = count($result_vector[array_shift($r)]);
- }
-
- if ($lookupRows == 2) {
- $result_vector = array_pop($lookup_vector);
- $lookup_vector = array_shift($lookup_vector);
- }
- if ($lookupColumns != 2) {
- foreach($lookup_vector as &$value) {
- if (is_array($value)) {
- $k = array_keys($value);
- $key1 = $key2 = array_shift($k);
- $key2++;
- $dataValue1 = $value[$key1];
- } else {
- $key1 = 0;
- $key2 = 1;
- $dataValue1 = $value;
- }
- $dataValue2 = array_shift($result_vector);
- if (is_array($dataValue2)) {
- $dataValue2 = array_shift($dataValue2);
- }
- $value = array($key1 => $dataValue1, $key2 => $dataValue2);
- }
- unset($value);
- }
-
- return self::VLOOKUP($lookup_value,$lookup_vector,2);
- } // function LOOKUP()
-
-} // class PHPExcel_Calculation_LookupRef
diff --git a/Classes/PHPExcel/Calculation/MathTrig.php b/Classes/PHPExcel/Calculation/MathTrig.php
index 2da748afd..894ba9cf0 100644
--- a/Classes/PHPExcel/Calculation/MathTrig.php
+++ b/Classes/PHPExcel/Calculation/MathTrig.php
@@ -1,8 +1,18 @@
1; --$i) {
- if (($value % $i) == 0) {
- $factorArray = array_merge($factorArray,self::_factors($value / $i));
- $factorArray = array_merge($factorArray,self::_factors($i));
- if ($i <= sqrt($value)) {
- break;
- }
- }
- }
- if (!empty($factorArray)) {
- rsort($factorArray);
- return $factorArray;
- } else {
- return array((integer) $value);
- }
- } // function _factors()
-
-
- private static function _romanCut($num, $n) {
- return ($num - ($num % $n ) ) / $n;
- } // function _romanCut()
-
-
- /**
- * ATAN2
- *
- * This function calculates the arc tangent of the two variables x and y. It is similar to
- * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
- * to determine the quadrant of the result.
- * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
- * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
- * -pi and pi, excluding -pi.
- *
- * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
- * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
- *
- * Excel Function:
- * ATAN2(xCoordinate,yCoordinate)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $xCoordinate The x-coordinate of the point.
- * @param float $yCoordinate The y-coordinate of the point.
- * @return float The inverse tangent of the specified x- and y-coordinates.
- */
- public static function ATAN2($xCoordinate = NULL, $yCoordinate = NULL) {
- $xCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($xCoordinate);
- $yCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($yCoordinate);
-
- $xCoordinate = ($xCoordinate !== NULL) ? $xCoordinate : 0.0;
- $yCoordinate = ($yCoordinate !== NULL) ? $yCoordinate : 0.0;
-
- if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
- ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
- $xCoordinate = (float) $xCoordinate;
- $yCoordinate = (float) $yCoordinate;
-
- if (($xCoordinate == 0) && ($yCoordinate == 0)) {
- return PHPExcel_Calculation_Functions::DIV0();
- }
-
- return atan2($yCoordinate, $xCoordinate);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ATAN2()
-
-
- /**
- * CEILING
- *
- * Returns number rounded up, away from zero, to the nearest multiple of significance.
- * For example, if you want to avoid using pennies in your prices and your product is
- * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the
- * nearest nickel.
- *
- * Excel Function:
- * CEILING(number[,significance])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number The number you want to round.
- * @param float $significance The multiple to which you want to round.
- * @return float Rounded Number
+class PHPExcel_Calculation_MathTrig
+{
+ //
+ // Private method to return an array of the factors of the input value
+ //
+ private static function factors($value)
+ {
+ $startVal = floor(sqrt($value));
+
+ $factorArray = array();
+ for ($i = $startVal; $i > 1; --$i) {
+ if (($value % $i) == 0) {
+ $factorArray = array_merge($factorArray, self::factors($value / $i));
+ $factorArray = array_merge($factorArray, self::factors($i));
+ if ($i <= sqrt($value)) {
+ break;
+ }
+ }
+ }
+ if (!empty($factorArray)) {
+ rsort($factorArray);
+ return $factorArray;
+ } else {
+ return array((integer) $value);
+ }
+ }
+
+
+ private static function romanCut($num, $n)
+ {
+ return ($num - ($num % $n ) ) / $n;
+ }
+
+
+ /**
+ * ATAN2
+ *
+ * This function calculates the arc tangent of the two variables x and y. It is similar to
+ * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
+ * to determine the quadrant of the result.
+ * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
+ * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
+ * -pi and pi, excluding -pi.
+ *
+ * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
+ * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
+ *
+ * Excel Function:
+ * ATAN2(xCoordinate,yCoordinate)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $xCoordinate The x-coordinate of the point.
+ * @param float $yCoordinate The y-coordinate of the point.
+ * @return float The inverse tangent of the specified x- and y-coordinates.
+ */
+ public static function ATAN2($xCoordinate = null, $yCoordinate = null)
+ {
+ $xCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($xCoordinate);
+ $yCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($yCoordinate);
+
+ $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0;
+ $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0;
+
+ if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
+ ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
+ $xCoordinate = (float) $xCoordinate;
+ $yCoordinate = (float) $yCoordinate;
+
+ if (($xCoordinate == 0) && ($yCoordinate == 0)) {
+ return PHPExcel_Calculation_Functions::DIV0();
+ }
+
+ return atan2($yCoordinate, $xCoordinate);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * CEILING
+ *
+ * Returns number rounded up, away from zero, to the nearest multiple of significance.
+ * For example, if you want to avoid using pennies in your prices and your product is
+ * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the
+ * nearest nickel.
+ *
+ * Excel Function:
+ * CEILING(number[,significance])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number The number you want to round.
+ * @param float $significance The multiple to which you want to round.
+ * @return float Rounded Number
+ */
+ public static function CEILING($number, $significance = null)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
+
+ if ((is_null($significance)) &&
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
+ $significance = $number / abs($number);
+ }
+
+ if ((is_numeric($number)) && (is_numeric($significance))) {
+ if (($number == 0.0 ) || ($significance == 0.0)) {
+ return 0.0;
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
+ return ceil($number / $significance) * $significance;
+ } else {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * COMBIN
+ *
+ * Returns the number of combinations for a given number of items. Use COMBIN to
+ * determine the total possible number of groups for a given number of items.
+ *
+ * Excel Function:
+ * COMBIN(numObjs,numInSet)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param int $numObjs Number of different objects
+ * @param int $numInSet Number of objects in each combination
+ * @return int Number of combinations
+ */
+ public static function COMBIN($numObjs, $numInSet)
+ {
+ $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs);
+ $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet);
+
+ if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
+ if ($numObjs < $numInSet) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif ($numInSet < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * EVEN
+ *
+ * Returns number rounded up to the nearest even integer.
+ * You can use this function for processing items that come in twos. For example,
+ * a packing crate accepts rows of one or two items. The crate is full when
+ * the number of items, rounded up to the nearest two, matches the crate's
+ * capacity.
+ *
+ * Excel Function:
+ * EVEN(number)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number Number to round
+ * @return int Rounded Number
+ */
+ public static function EVEN($number)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+
+ if (is_null($number)) {
+ return 0;
+ } elseif (is_bool($number)) {
+ $number = (int) $number;
+ }
+
+ if (is_numeric($number)) {
+ $significance = 2 * self::SIGN($number);
+ return (int) self::CEILING($number, $significance);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * FACT
+ *
+ * Returns the factorial of a number.
+ * The factorial of a number is equal to 1*2*3*...* number.
+ *
+ * Excel Function:
+ * FACT(factVal)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $factVal Factorial Value
+ * @return int Factorial
+ */
+ public static function FACT($factVal)
+ {
+ $factVal = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
+
+ if (is_numeric($factVal)) {
+ if ($factVal < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $factLoop = floor($factVal);
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
+ if ($factVal > $factLoop) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ }
+
+ $factorial = 1;
+ while ($factLoop > 1) {
+ $factorial *= $factLoop--;
+ }
+ return $factorial ;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * FACTDOUBLE
+ *
+ * Returns the double factorial of a number.
+ *
+ * Excel Function:
+ * FACTDOUBLE(factVal)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $factVal Factorial Value
+ * @return int Double Factorial
+ */
+ public static function FACTDOUBLE($factVal)
+ {
+ $factLoop = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
+
+ if (is_numeric($factLoop)) {
+ $factLoop = floor($factLoop);
+ if ($factVal < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $factorial = 1;
+ while ($factLoop > 1) {
+ $factorial *= $factLoop--;
+ --$factLoop;
+ }
+ return $factorial ;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * FLOOR
+ *
+ * Rounds number down, toward zero, to the nearest multiple of significance.
+ *
+ * Excel Function:
+ * FLOOR(number[,significance])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number Number to round
+ * @param float $significance Significance
+ * @return float Rounded Number
+ */
+ public static function FLOOR($number, $significance = null)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
+
+ if ((is_null($significance)) &&
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
+ $significance = $number/abs($number);
+ }
+
+ if ((is_numeric($number)) && (is_numeric($significance))) {
+ if ($significance == 0.0) {
+ return PHPExcel_Calculation_Functions::DIV0();
+ } elseif ($number == 0.0) {
+ return 0.0;
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
+ return floor($number / $significance) * $significance;
+ } else {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ }
+
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * GCD
+ *
+ * Returns the greatest common divisor of a series of numbers.
+ * The greatest common divisor is the largest integer that divides both
+ * number1 and number2 without a remainder.
+ *
+ * Excel Function:
+ * GCD(number1[,number2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return integer Greatest Common Divisor
+ */
+ public static function GCD()
+ {
+ $returnValue = 1;
+ $allValuesFactors = array();
+ // Loop through arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
+ if (!is_numeric($value)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ } elseif ($value == 0) {
+ continue;
+ } elseif ($value < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $myFactors = self::factors($value);
+ $myCountedFactors = array_count_values($myFactors);
+ $allValuesFactors[] = $myCountedFactors;
+ }
+ $allValuesCount = count($allValuesFactors);
+ if ($allValuesCount == 0) {
+ return 0;
+ }
+
+ $mergedArray = $allValuesFactors[0];
+ for ($i=1; $i < $allValuesCount; ++$i) {
+ $mergedArray = array_intersect_key($mergedArray, $allValuesFactors[$i]);
+ }
+ $mergedArrayValues = count($mergedArray);
+ if ($mergedArrayValues == 0) {
+ return $returnValue;
+ } elseif ($mergedArrayValues > 1) {
+ foreach ($mergedArray as $mergedKey => $mergedValue) {
+ foreach ($allValuesFactors as $highestPowerTest) {
+ foreach ($highestPowerTest as $testKey => $testValue) {
+ if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
+ $mergedArray[$mergedKey] = $testValue;
+ $mergedValue = $testValue;
+ }
+ }
+ }
+ }
+
+ $returnValue = 1;
+ foreach ($mergedArray as $key => $value) {
+ $returnValue *= pow($key, $value);
+ }
+ return $returnValue;
+ } else {
+ $keys = array_keys($mergedArray);
+ $key = $keys[0];
+ $value = $mergedArray[$key];
+ foreach ($allValuesFactors as $testValue) {
+ foreach ($testValue as $mergedKey => $mergedValue) {
+ if (($mergedKey == $key) && ($mergedValue < $value)) {
+ $value = $mergedValue;
+ }
+ }
+ }
+ return pow($key, $value);
+ }
+ }
+
+
+ /**
+ * INT
+ *
+ * Casts a floating point value to an integer
+ *
+ * Excel Function:
+ * INT(number)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number Number to cast to an integer
+ * @return integer Integer value
+ */
+ public static function INT($number)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+
+ if (is_null($number)) {
+ return 0;
+ } elseif (is_bool($number)) {
+ return (int) $number;
+ }
+ if (is_numeric($number)) {
+ return (int) floor($number);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * LCM
+ *
+ * Returns the lowest common multiplier of a series of numbers
+ * The least common multiple is the smallest positive integer that is a multiple
+ * of all integer arguments number1, number2, and so on. Use LCM to add fractions
+ * with different denominators.
+ *
+ * Excel Function:
+ * LCM(number1[,number2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return int Lowest Common Multiplier
+ */
+ public static function LCM()
+ {
+ $returnValue = 1;
+ $allPoweredFactors = array();
+ // Loop through arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
+ if (!is_numeric($value)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if ($value == 0) {
+ return 0;
+ } elseif ($value < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $myFactors = self::factors(floor($value));
+ $myCountedFactors = array_count_values($myFactors);
+ $myPoweredFactors = array();
+ foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) {
+ $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower);
+ }
+ foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
+ if (array_key_exists($myPoweredValue, $allPoweredFactors)) {
+ if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
+ }
+ } else {
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
+ }
+ }
+ }
+ foreach ($allPoweredFactors as $allPoweredFactor) {
+ $returnValue *= (integer) $allPoweredFactor;
+ }
+ return $returnValue;
+ }
+
+
+ /**
+ * LOG_BASE
+ *
+ * Returns the logarithm of a number to a specified base. The default base is 10.
+ *
+ * Excel Function:
+ * LOG(number[,base])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param float $number The positive real number for which you want the logarithm
+ * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
+ * @return float
+ */
+ public static function LOG_BASE($number = null, $base = 10)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $base = (is_null($base)) ? 10 : (float) PHPExcel_Calculation_Functions::flattenSingleValue($base);
+
+ if ((!is_numeric($base)) || (!is_numeric($number))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ if (($base <= 0) || ($number <= 0)) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return log($number, $base);
+ }
+
+
+ /**
+ * MDETERM
+ *
+ * Returns the matrix determinant of an array.
+ *
+ * Excel Function:
+ * MDETERM(array)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param array $matrixValues A matrix of values
+ * @return float
+ */
+ public static function MDETERM($matrixValues)
+ {
+ $matrixData = array();
+ if (!is_array($matrixValues)) {
+ $matrixValues = array(array($matrixValues));
+ }
+
+ $row = $maxColumn = 0;
+ foreach ($matrixValues as $matrixRow) {
+ if (!is_array($matrixRow)) {
+ $matrixRow = array($matrixRow);
+ }
+ $column = 0;
+ foreach ($matrixRow as $matrixCell) {
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $matrixData[$column][$row] = $matrixCell;
+ ++$column;
+ }
+ if ($column > $maxColumn) {
+ $maxColumn = $column;
+ }
+ ++$row;
+ }
+ if ($row != $maxColumn) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ try {
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
+ return $matrix->det();
+ } catch (PHPExcel_Exception $ex) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+
+
+ /**
+ * MINVERSE
+ *
+ * Returns the inverse matrix for the matrix stored in an array.
+ *
+ * Excel Function:
+ * MINVERSE(array)
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param array $matrixValues A matrix of values
+ * @return array
+ */
+ public static function MINVERSE($matrixValues)
+ {
+ $matrixData = array();
+ if (!is_array($matrixValues)) {
+ $matrixValues = array(array($matrixValues));
+ }
+
+ $row = $maxColumn = 0;
+ foreach ($matrixValues as $matrixRow) {
+ if (!is_array($matrixRow)) {
+ $matrixRow = array($matrixRow);
+ }
+ $column = 0;
+ foreach ($matrixRow as $matrixCell) {
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $matrixData[$column][$row] = $matrixCell;
+ ++$column;
+ }
+ if ($column > $maxColumn) {
+ $maxColumn = $column;
+ }
+ ++$row;
+ }
+ if ($row != $maxColumn) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ try {
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
+ return $matrix->inverse()->getArray();
+ } catch (PHPExcel_Exception $ex) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+
+
+ /**
+ * MMULT
+ *
+ * @param array $matrixData1 A matrix of values
+ * @param array $matrixData2 A matrix of values
+ * @return array
+ */
+ public static function MMULT($matrixData1, $matrixData2)
+ {
+ $matrixAData = $matrixBData = array();
+ if (!is_array($matrixData1)) {
+ $matrixData1 = array(array($matrixData1));
+ }
+ if (!is_array($matrixData2)) {
+ $matrixData2 = array(array($matrixData2));
+ }
+
+ try {
+ $rowA = 0;
+ foreach ($matrixData1 as $matrixRow) {
+ if (!is_array($matrixRow)) {
+ $matrixRow = array($matrixRow);
+ }
+ $columnA = 0;
+ foreach ($matrixRow as $matrixCell) {
+ if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $matrixAData[$rowA][$columnA] = $matrixCell;
+ ++$columnA;
+ }
+ ++$rowA;
+ }
+ $matrixA = new PHPExcel_Shared_JAMA_Matrix($matrixAData);
+ $rowB = 0;
+ foreach ($matrixData2 as $matrixRow) {
+ if (!is_array($matrixRow)) {
+ $matrixRow = array($matrixRow);
+ }
+ $columnB = 0;
+ foreach ($matrixRow as $matrixCell) {
+ if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $matrixBData[$rowB][$columnB] = $matrixCell;
+ ++$columnB;
+ }
+ ++$rowB;
+ }
+ $matrixB = new PHPExcel_Shared_JAMA_Matrix($matrixBData);
+
+ if ($columnA != $rowB) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ return $matrixA->times($matrixB)->getArray();
+ } catch (PHPExcel_Exception $ex) {
+ var_dump($ex->getMessage());
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+
+
+ /**
+ * MOD
+ *
+ * @param int $a Dividend
+ * @param int $b Divisor
+ * @return int Remainder
+ */
+ public static function MOD($a = 1, $b = 1)
+ {
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
+
+ if ($b == 0.0) {
+ return PHPExcel_Calculation_Functions::DIV0();
+ } elseif (($a < 0.0) && ($b > 0.0)) {
+ return $b - fmod(abs($a), $b);
+ } elseif (($a > 0.0) && ($b < 0.0)) {
+ return $b + fmod($a, abs($b));
+ }
+
+ return fmod($a, $b);
+ }
+
+
+ /**
+ * MROUND
+ *
+ * Rounds a number to the nearest multiple of a specified value
+ *
+ * @param float $number Number to round
+ * @param int $multiple Multiple to which you want to round $number
+ * @return float Rounded Number
+ */
+ public static function MROUND($number, $multiple)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $multiple = PHPExcel_Calculation_Functions::flattenSingleValue($multiple);
+
+ if ((is_numeric($number)) && (is_numeric($multiple))) {
+ if ($multiple == 0) {
+ return 0;
+ }
+ if ((self::SIGN($number)) == (self::SIGN($multiple))) {
+ $multiplier = 1 / $multiple;
+ return round($number * $multiplier) / $multiplier;
+ }
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * MULTINOMIAL
+ *
+ * Returns the ratio of the factorial of a sum of values to the product of factorials.
+ *
+ * @param array of mixed Data Series
+ * @return float
+ */
+ public static function MULTINOMIAL()
+ {
+ $summer = 0;
+ $divisor = 1;
+ // Loop through arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if (is_numeric($arg)) {
+ if ($arg < 1) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ $summer += floor($arg);
+ $divisor *= self::FACT($arg);
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+
+ // Return
+ if ($summer > 0) {
+ $summer = self::FACT($summer);
+ return $summer / $divisor;
+ }
+ return 0;
+ }
+
+
+ /**
+ * ODD
+ *
+ * Returns number rounded up to the nearest odd integer.
+ *
+ * @param float $number Number to round
+ * @return int Rounded Number
+ */
+ public static function ODD($number)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+
+ if (is_null($number)) {
+ return 1;
+ } elseif (is_bool($number)) {
+ return 1;
+ } elseif (is_numeric($number)) {
+ $significance = self::SIGN($number);
+ if ($significance == 0) {
+ return 1;
+ }
+
+ $result = self::CEILING($number, $significance);
+ if ($result == self::EVEN($result)) {
+ $result += $significance;
+ }
+
+ return (int) $result;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * POWER
+ *
+ * Computes x raised to the power y.
+ *
+ * @param float $x
+ * @param float $y
+ * @return float
+ */
+ public static function POWER($x = 0, $y = 2)
+ {
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
+ $y = PHPExcel_Calculation_Functions::flattenSingleValue($y);
+
+ // Validate parameters
+ if ($x == 0.0 && $y == 0.0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ } elseif ($x == 0.0 && $y < 0.0) {
+ return PHPExcel_Calculation_Functions::DIV0();
+ }
+
+ // Return
+ $result = pow($x, $y);
+ return (!is_nan($result) && !is_infinite($result)) ? $result : PHPExcel_Calculation_Functions::NaN();
+ }
+
+
+ /**
+ * PRODUCT
+ *
+ * PRODUCT returns the product of all the values and cells referenced in the argument list.
+ *
+ * Excel Function:
+ * PRODUCT(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function PRODUCT()
+ {
+ // Return value
+ $returnValue = null;
+
+ // Loop through arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ if (is_null($returnValue)) {
+ $returnValue = $arg;
+ } else {
+ $returnValue *= $arg;
+ }
+ }
+ }
+
+ // Return
+ if (is_null($returnValue)) {
+ return 0;
+ }
+ return $returnValue;
+ }
+
+
+ /**
+ * QUOTIENT
+ *
+ * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
+ * and denominator is the divisor.
+ *
+ * Excel Function:
+ * QUOTIENT(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function QUOTIENT()
+ {
+ // Return value
+ $returnValue = null;
+
+ // Loop through arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ if (is_null($returnValue)) {
+ $returnValue = ($arg == 0) ? 0 : $arg;
+ } else {
+ if (($returnValue == 0) || ($arg == 0)) {
+ $returnValue = 0;
+ } else {
+ $returnValue /= $arg;
+ }
+ }
+ }
+ }
+
+ // Return
+ return intval($returnValue);
+ }
+
+
+ /**
+ * RAND
+ *
+ * @param int $min Minimal value
+ * @param int $max Maximal value
+ * @return int Random number
+ */
+ public static function RAND($min = 0, $max = 0)
+ {
+ $min = PHPExcel_Calculation_Functions::flattenSingleValue($min);
+ $max = PHPExcel_Calculation_Functions::flattenSingleValue($max);
+
+ if ($min == 0 && $max == 0) {
+ return (mt_rand(0, 10000000)) / 10000000;
+ } else {
+ return mt_rand($min, $max);
+ }
+ }
+
+
+ public static function ROMAN($aValue, $style = 0)
+ {
+ $aValue = PHPExcel_Calculation_Functions::flattenSingleValue($aValue);
+ $style = (is_null($style)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($style);
+ if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $aValue = (integer) $aValue;
+ if ($aValue == 0) {
+ return '';
+ }
+
+ $mill = array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
+ $cent = array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
+ $tens = array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
+ $ones = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
+
+ $roman = '';
+ while ($aValue > 5999) {
+ $roman .= 'M';
+ $aValue -= 1000;
+ }
+ $m = self::romanCut($aValue, 1000);
+ $aValue %= 1000;
+ $c = self::romanCut($aValue, 100);
+ $aValue %= 100;
+ $t = self::romanCut($aValue, 10);
+ $aValue %= 10;
+
+ return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
+ }
+
+
+ /**
+ * ROUNDUP
+ *
+ * Rounds a number up to a specified number of decimal places
+ *
+ * @param float $number Number to round
+ * @param int $digits Number of digits to which you want to round $number
+ * @return float Rounded Number
+ */
+ public static function ROUNDUP($number, $digits)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
+
+ if ((is_numeric($number)) && (is_numeric($digits))) {
+ $significance = pow(10, (int) $digits);
+ if ($number < 0.0) {
+ return floor($number * $significance) / $significance;
+ } else {
+ return ceil($number * $significance) / $significance;
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * ROUNDDOWN
+ *
+ * Rounds a number down to a specified number of decimal places
+ *
+ * @param float $number Number to round
+ * @param int $digits Number of digits to which you want to round $number
+ * @return float Rounded Number
+ */
+ public static function ROUNDDOWN($number, $digits)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
+
+ if ((is_numeric($number)) && (is_numeric($digits))) {
+ $significance = pow(10, (int) $digits);
+ if ($number < 0.0) {
+ return ceil($number * $significance) / $significance;
+ } else {
+ return floor($number * $significance) / $significance;
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SERIESSUM
+ *
+ * Returns the sum of a power series
+ *
+ * @param float $x Input value to the power series
+ * @param float $n Initial power to which you want to raise $x
+ * @param float $m Step by which to increase $n for each term in the series
+ * @param array of mixed Data Series
+ * @return float
+ */
+ public static function SERIESSUM()
+ {
+ $returnValue = 0;
+
+ // Loop through arguments
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+
+ $x = array_shift($aArgs);
+ $n = array_shift($aArgs);
+ $m = array_shift($aArgs);
+
+ if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
+ // Calculate
+ $i = 0;
+ foreach ($aArgs as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue += $arg * pow($x, $n + ($m * $i++));
+ } else {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ }
+ return $returnValue;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SIGN
+ *
+ * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
+ * if the number is 0, and -1 if the number is negative.
+ *
+ * @param float $number Number to round
+ * @return int sign value
+ */
+ public static function SIGN($number)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+
+ if (is_bool($number)) {
+ return (int) $number;
+ }
+ if (is_numeric($number)) {
+ if ($number == 0.0) {
+ return 0;
+ }
+ return $number / abs($number);
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SQRTPI
+ *
+ * Returns the square root of (number * pi).
+ *
+ * @param float $number Number
+ * @return float Square Root of Number * Pi
+ */
+ public static function SQRTPI($number)
+ {
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
+
+ if (is_numeric($number)) {
+ if ($number < 0) {
+ return PHPExcel_Calculation_Functions::NaN();
+ }
+ return sqrt($number * M_PI) ;
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SUBTOTAL
+ *
+ * Returns a subtotal in a list or database.
+ *
+ * @param int the number 1 to 11 that specifies which function to
+ * use in calculating subtotals within a list.
+ * @param array of mixed Data Series
+ * @return float
+ */
+ public static function SUBTOTAL()
+ {
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
+
+ // Calculate
+ $subtotal = array_shift($aArgs);
+
+ if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
+ switch ($subtotal) {
+ case 1:
+ return PHPExcel_Calculation_Statistical::AVERAGE($aArgs);
+ case 2:
+ return PHPExcel_Calculation_Statistical::COUNT($aArgs);
+ case 3:
+ return PHPExcel_Calculation_Statistical::COUNTA($aArgs);
+ case 4:
+ return PHPExcel_Calculation_Statistical::MAX($aArgs);
+ case 5:
+ return PHPExcel_Calculation_Statistical::MIN($aArgs);
+ case 6:
+ return self::PRODUCT($aArgs);
+ case 7:
+ return PHPExcel_Calculation_Statistical::STDEV($aArgs);
+ case 8:
+ return PHPExcel_Calculation_Statistical::STDEVP($aArgs);
+ case 9:
+ return self::SUM($aArgs);
+ case 10:
+ return PHPExcel_Calculation_Statistical::VARFunc($aArgs);
+ case 11:
+ return PHPExcel_Calculation_Statistical::VARP($aArgs);
+ }
+ }
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+
+ /**
+ * SUM
+ *
+ * SUM computes the sum of all the values and cells referenced in the argument list.
+ *
+ * Excel Function:
+ * SUM(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function SUM()
+ {
+ $returnValue = 0;
+
+ // Loop through the arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue += $arg;
+ }
+ }
+
+ return $returnValue;
+ }
+
+
+ /**
+ * 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())
+ {
+ $returnValue = 0;
+
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
+ if (empty($sumArgs)) {
+ $sumArgs = $aArgs;
+ }
+ $condition = PHPExcel_Calculation_Functions::ifCondition($condition);
+ // Loop through arguments
+ foreach ($aArgs as $key => $arg) {
+ if (!is_numeric($arg)) {
+ $arg = str_replace('"', '""', $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 $returnValue;
+ }
+
+
+ /**
+ * SUMIFS
+ *
+ * Counts the number of cells that contain numbers within the list of arguments
+ *
+ * Excel Function:
+ * SUMIFS(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 CEILING($number, $significance = NULL) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
-
- if ((is_null($significance)) &&
- (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
- $significance = $number/abs($number);
- }
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if ($significance == 0.0) {
- return 0.0;
- } elseif (self::SIGN($number) == self::SIGN($significance)) {
- return ceil($number / $significance) * $significance;
- } else {
- return PHPExcel_Calculation_Functions::NaN();
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function CEILING()
-
-
- /**
- * COMBIN
- *
- * Returns the number of combinations for a given number of items. Use COMBIN to
- * determine the total possible number of groups for a given number of items.
- *
- * Excel Function:
- * COMBIN(numObjs,numInSet)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param int $numObjs Number of different objects
- * @param int $numInSet Number of objects in each combination
- * @return int Number of combinations
- */
- public static function COMBIN($numObjs, $numInSet) {
- $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs);
- $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet);
-
- if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
- if ($numObjs < $numInSet) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif ($numInSet < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function COMBIN()
-
-
- /**
- * EVEN
- *
- * Returns number rounded up to the nearest even integer.
- * You can use this function for processing items that come in twos. For example,
- * a packing crate accepts rows of one or two items. The crate is full when
- * the number of items, rounded up to the nearest two, matches the crate's
- * capacity.
- *
- * Excel Function:
- * EVEN(number)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number Number to round
- * @return int Rounded Number
- */
- public static function EVEN($number) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
-
- if (is_null($number)) {
- return 0;
- } elseif (is_bool($number)) {
- $number = (int) $number;
- }
-
- if (is_numeric($number)) {
- $significance = 2 * self::SIGN($number);
- return (int) self::CEILING($number,$significance);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function EVEN()
-
-
- /**
- * FACT
- *
- * Returns the factorial of a number.
- * The factorial of a number is equal to 1*2*3*...* number.
- *
- * Excel Function:
- * FACT(factVal)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $factVal Factorial Value
- * @return int Factorial
- */
- public static function FACT($factVal) {
- $factVal = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
-
- if (is_numeric($factVal)) {
- if ($factVal < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $factLoop = floor($factVal);
- if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
- if ($factVal > $factLoop) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- }
-
- $factorial = 1;
- while ($factLoop > 1) {
- $factorial *= $factLoop--;
- }
- return $factorial ;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function FACT()
-
-
- /**
- * FACTDOUBLE
- *
- * Returns the double factorial of a number.
- *
- * Excel Function:
- * FACTDOUBLE(factVal)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $factVal Factorial Value
- * @return int Double Factorial
- */
- public static function FACTDOUBLE($factVal) {
- $factLoop = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
-
- if (is_numeric($factLoop)) {
- $factLoop = floor($factLoop);
- if ($factVal < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $factorial = 1;
- while ($factLoop > 1) {
- $factorial *= $factLoop--;
- --$factLoop;
- }
- return $factorial ;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function FACTDOUBLE()
-
-
- /**
- * FLOOR
- *
- * Rounds number down, toward zero, to the nearest multiple of significance.
- *
- * Excel Function:
- * FLOOR(number[,significance])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number Number to round
- * @param float $significance Significance
- * @return float Rounded Number
- */
- public static function FLOOR($number, $significance = NULL) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
-
- if ((is_null($significance)) && (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
- $significance = $number/abs($number);
- }
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if ((float) $significance == 0.0) {
- return PHPExcel_Calculation_Functions::DIV0();
- }
- if (self::SIGN($number) == self::SIGN($significance)) {
- return floor($number / $significance) * $significance;
- } else {
- return PHPExcel_Calculation_Functions::NaN();
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function FLOOR()
-
-
- /**
- * GCD
- *
- * Returns the greatest common divisor of a series of numbers.
- * The greatest common divisor is the largest integer that divides both
- * number1 and number2 without a remainder.
- *
- * Excel Function:
- * GCD(number1[,number2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return integer Greatest Common Divisor
- */
- public static function GCD() {
- $returnValue = 1;
- $allValuesFactors = array();
- // Loop through arguments
- foreach(PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
- if (!is_numeric($value)) {
- return PHPExcel_Calculation_Functions::VALUE();
- } elseif ($value == 0) {
- continue;
- } elseif($value < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $myFactors = self::_factors($value);
- $myCountedFactors = array_count_values($myFactors);
- $allValuesFactors[] = $myCountedFactors;
- }
- $allValuesCount = count($allValuesFactors);
- if ($allValuesCount == 0) {
- return 0;
- }
-
- $mergedArray = $allValuesFactors[0];
- for ($i=1;$i < $allValuesCount; ++$i) {
- $mergedArray = array_intersect_key($mergedArray,$allValuesFactors[$i]);
- }
- $mergedArrayValues = count($mergedArray);
- if ($mergedArrayValues == 0) {
- return $returnValue;
- } elseif ($mergedArrayValues > 1) {
- foreach($mergedArray as $mergedKey => $mergedValue) {
- foreach($allValuesFactors as $highestPowerTest) {
- foreach($highestPowerTest as $testKey => $testValue) {
- if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
- $mergedArray[$mergedKey] = $testValue;
- $mergedValue = $testValue;
- }
- }
- }
- }
-
- $returnValue = 1;
- foreach($mergedArray as $key => $value) {
- $returnValue *= pow($key,$value);
- }
- return $returnValue;
- } else {
- $keys = array_keys($mergedArray);
- $key = $keys[0];
- $value = $mergedArray[$key];
- foreach($allValuesFactors as $testValue) {
- foreach($testValue as $mergedKey => $mergedValue) {
- if (($mergedKey == $key) && ($mergedValue < $value)) {
- $value = $mergedValue;
- }
- }
- }
- return pow($key,$value);
- }
- } // function GCD()
-
-
- /**
- * INT
- *
- * Casts a floating point value to an integer
- *
- * Excel Function:
- * INT(number)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $number Number to cast to an integer
- * @return integer Integer value
- */
- public static function INT($number) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
-
- if (is_null($number)) {
- return 0;
- } elseif (is_bool($number)) {
- return (int) $number;
- }
- if (is_numeric($number)) {
- return (int) floor($number);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function INT()
-
-
- /**
- * LCM
- *
- * Returns the lowest common multiplier of a series of numbers
- * The least common multiple is the smallest positive integer that is a multiple
- * of all integer arguments number1, number2, and so on. Use LCM to add fractions
- * with different denominators.
- *
- * Excel Function:
- * LCM(number1[,number2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return int Lowest Common Multiplier
- */
- public static function LCM() {
- $returnValue = 1;
- $allPoweredFactors = array();
- // Loop through arguments
- foreach(PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
- if (!is_numeric($value)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- if ($value == 0) {
- return 0;
- } elseif ($value < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $myFactors = self::_factors(floor($value));
- $myCountedFactors = array_count_values($myFactors);
- $myPoweredFactors = array();
- foreach($myCountedFactors as $myCountedFactor => $myCountedPower) {
- $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor,$myCountedPower);
- }
- foreach($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
- if (array_key_exists($myPoweredValue,$allPoweredFactors)) {
- if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
- $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
- }
- } else {
- $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
- }
- }
- }
- foreach($allPoweredFactors as $allPoweredFactor) {
- $returnValue *= (integer) $allPoweredFactor;
- }
- return $returnValue;
- } // function LCM()
-
-
- /**
- * LOG_BASE
- *
- * Returns the logarithm of a number to a specified base. The default base is 10.
- *
- * Excel Function:
- * LOG(number[,base])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param float $value The positive real number for which you want the logarithm
- * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
- * @return float
- */
- public static function LOG_BASE($number = NULL, $base = 10) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $base = (is_null($base)) ? 10 : (float) PHPExcel_Calculation_Functions::flattenSingleValue($base);
-
- if ((!is_numeric($base)) || (!is_numeric($number)))
- return PHPExcel_Calculation_Functions::VALUE();
- if (($base <= 0) || ($number <= 0))
- return PHPExcel_Calculation_Functions::NaN();
- return log($number, $base);
- } // function LOG_BASE()
-
-
- /**
- * MDETERM
- *
- * Returns the matrix determinant of an array.
- *
- * Excel Function:
- * MDETERM(array)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param array $matrixValues A matrix of values
- * @return float
- */
- public static function MDETERM($matrixValues) {
- $matrixData = array();
- if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
-
- $row = $maxColumn = 0;
- foreach($matrixValues as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $column = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $matrixData[$column][$row] = $matrixCell;
- ++$column;
- }
- if ($column > $maxColumn) { $maxColumn = $column; }
- ++$row;
- }
- if ($row != $maxColumn) { return PHPExcel_Calculation_Functions::VALUE(); }
-
- try {
- $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
- return $matrix->det();
- } catch (PHPExcel_Exception $ex) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- } // function MDETERM()
-
-
- /**
- * MINVERSE
- *
- * Returns the inverse matrix for the matrix stored in an array.
- *
- * Excel Function:
- * MINVERSE(array)
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param array $matrixValues A matrix of values
- * @return array
- */
- public static function MINVERSE($matrixValues) {
- $matrixData = array();
- if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
-
- $row = $maxColumn = 0;
- foreach($matrixValues as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $column = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $matrixData[$column][$row] = $matrixCell;
- ++$column;
- }
- if ($column > $maxColumn) { $maxColumn = $column; }
- ++$row;
- }
- if ($row != $maxColumn) { return PHPExcel_Calculation_Functions::VALUE(); }
-
- try {
- $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
- return $matrix->inverse()->getArray();
- } catch (PHPExcel_Exception $ex) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- } // function MINVERSE()
-
-
- /**
- * MMULT
- *
- * @param array $matrixData1 A matrix of values
- * @param array $matrixData2 A matrix of values
- * @return array
- */
- public static function MMULT($matrixData1,$matrixData2) {
- $matrixAData = $matrixBData = array();
- if (!is_array($matrixData1)) { $matrixData1 = array(array($matrixData1)); }
- if (!is_array($matrixData2)) { $matrixData2 = array(array($matrixData2)); }
-
- $rowA = 0;
- foreach($matrixData1 as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $columnA = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $matrixAData[$rowA][$columnA] = $matrixCell;
- ++$columnA;
- }
- ++$rowA;
- }
- try {
- $matrixA = new PHPExcel_Shared_JAMA_Matrix($matrixAData);
- $rowB = 0;
- foreach($matrixData2 as $matrixRow) {
- if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
- $columnB = 0;
- foreach($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $matrixBData[$rowB][$columnB] = $matrixCell;
- ++$columnB;
- }
- ++$rowB;
- }
- $matrixB = new PHPExcel_Shared_JAMA_Matrix($matrixBData);
-
- if (($rowA != $columnB) || ($rowB != $columnA)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- return $matrixA->times($matrixB)->getArray();
- } catch (PHPExcel_Exception $ex) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- } // function MMULT()
-
-
- /**
- * MOD
- *
- * @param int $a Dividend
- * @param int $b Divisor
- * @return int Remainder
- */
- public static function MOD($a = 1, $b = 1) {
- $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
- $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
-
- if ($b == 0.0) {
- return PHPExcel_Calculation_Functions::DIV0();
- } elseif (($a < 0.0) && ($b > 0.0)) {
- return $b - fmod(abs($a),$b);
- } elseif (($a > 0.0) && ($b < 0.0)) {
- return $b + fmod($a,abs($b));
- }
-
- return fmod($a,$b);
- } // function MOD()
-
-
- /**
- * MROUND
- *
- * Rounds a number to the nearest multiple of a specified value
- *
- * @param float $number Number to round
- * @param int $multiple Multiple to which you want to round $number
- * @return float Rounded Number
- */
- public static function MROUND($number,$multiple) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $multiple = PHPExcel_Calculation_Functions::flattenSingleValue($multiple);
-
- if ((is_numeric($number)) && (is_numeric($multiple))) {
- if ($multiple == 0) {
- return 0;
- }
- if ((self::SIGN($number)) == (self::SIGN($multiple))) {
- $multiplier = 1 / $multiple;
- return round($number * $multiplier) / $multiplier;
- }
- return PHPExcel_Calculation_Functions::NaN();
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function MROUND()
-
-
- /**
- * MULTINOMIAL
- *
- * Returns the ratio of the factorial of a sum of values to the product of factorials.
- *
- * @param array of mixed Data Series
- * @return float
- */
- public static function MULTINOMIAL() {
- $summer = 0;
- $divisor = 1;
- // Loop through arguments
- foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if (is_numeric($arg)) {
- if ($arg < 1) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- $summer += floor($arg);
- $divisor *= self::FACT($arg);
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
-
- // Return
- if ($summer > 0) {
- $summer = self::FACT($summer);
- return $summer / $divisor;
- }
- return 0;
- } // function MULTINOMIAL()
-
-
- /**
- * ODD
- *
- * Returns number rounded up to the nearest odd integer.
- *
- * @param float $number Number to round
- * @return int Rounded Number
- */
- public static function ODD($number) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
-
- if (is_null($number)) {
- return 1;
- } elseif (is_bool($number)) {
- $number = (int) $number;
- }
-
- if (is_numeric($number)) {
- $significance = self::SIGN($number);
- if ($significance == 0) {
- return 1;
- }
-
- $result = self::CEILING($number,$significance);
- if ($result == self::EVEN($result)) {
- $result += $significance;
- }
-
- return (int) $result;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ODD()
-
-
- /**
- * POWER
- *
- * Computes x raised to the power y.
- *
- * @param float $x
- * @param float $y
- * @return float
- */
- public static function POWER($x = 0, $y = 2) {
- $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
- $y = PHPExcel_Calculation_Functions::flattenSingleValue($y);
-
- // Validate parameters
- if ($x == 0.0 && $y == 0.0) {
- return PHPExcel_Calculation_Functions::NaN();
- } elseif ($x == 0.0 && $y < 0.0) {
- return PHPExcel_Calculation_Functions::DIV0();
- }
-
- // Return
- $result = pow($x, $y);
- return (!is_nan($result) && !is_infinite($result)) ? $result : PHPExcel_Calculation_Functions::NaN();
- } // function POWER()
-
-
- /**
- * PRODUCT
- *
- * PRODUCT returns the product of all the values and cells referenced in the argument list.
- *
- * Excel Function:
- * PRODUCT(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function PRODUCT() {
- // Return value
- $returnValue = null;
-
- // Loop through arguments
- foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if (is_null($returnValue)) {
- $returnValue = $arg;
- } else {
- $returnValue *= $arg;
- }
- }
- }
-
- // Return
- if (is_null($returnValue)) {
- return 0;
- }
- return $returnValue;
- } // function PRODUCT()
-
-
- /**
- * QUOTIENT
- *
- * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
- * and denominator is the divisor.
- *
- * Excel Function:
- * QUOTIENT(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function QUOTIENT() {
- // Return value
- $returnValue = null;
-
- // Loop through arguments
- foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if (is_null($returnValue)) {
- $returnValue = ($arg == 0) ? 0 : $arg;
- } else {
- if (($returnValue == 0) || ($arg == 0)) {
- $returnValue = 0;
- } else {
- $returnValue /= $arg;
- }
- }
- }
- }
-
- // Return
- return intval($returnValue);
- } // function QUOTIENT()
-
-
- /**
- * RAND
- *
- * @param int $min Minimal value
- * @param int $max Maximal value
- * @return int Random number
- */
- public static function RAND($min = 0, $max = 0) {
- $min = PHPExcel_Calculation_Functions::flattenSingleValue($min);
- $max = PHPExcel_Calculation_Functions::flattenSingleValue($max);
-
- if ($min == 0 && $max == 0) {
- return (rand(0,10000000)) / 10000000;
- } else {
- return rand($min, $max);
- }
- } // function RAND()
-
-
- public static function ROMAN($aValue, $style=0) {
- $aValue = PHPExcel_Calculation_Functions::flattenSingleValue($aValue);
- $style = (is_null($style)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($style);
- if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- $aValue = (integer) $aValue;
- if ($aValue == 0) {
- return '';
- }
-
- $mill = Array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
- $cent = Array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
- $tens = Array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
- $ones = Array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
-
- $roman = '';
- while ($aValue > 5999) {
- $roman .= 'M';
- $aValue -= 1000;
- }
- $m = self::_romanCut($aValue, 1000); $aValue %= 1000;
- $c = self::_romanCut($aValue, 100); $aValue %= 100;
- $t = self::_romanCut($aValue, 10); $aValue %= 10;
-
- return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
- } // function ROMAN()
-
-
- /**
- * ROUNDUP
- *
- * Rounds a number up to a specified number of decimal places
- *
- * @param float $number Number to round
- * @param int $digits Number of digits to which you want to round $number
- * @return float Rounded Number
- */
- public static function ROUNDUP($number,$digits) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
-
- if ((is_numeric($number)) && (is_numeric($digits))) {
- $significance = pow(10,(int) $digits);
- if ($number < 0.0) {
- return floor($number * $significance) / $significance;
- } else {
- return ceil($number * $significance) / $significance;
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ROUNDUP()
-
-
- /**
- * ROUNDDOWN
- *
- * Rounds a number down to a specified number of decimal places
- *
- * @param float $number Number to round
- * @param int $digits Number of digits to which you want to round $number
- * @return float Rounded Number
- */
- public static function ROUNDDOWN($number,$digits) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
- $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
-
- if ((is_numeric($number)) && (is_numeric($digits))) {
- $significance = pow(10,(int) $digits);
- if ($number < 0.0) {
- return ceil($number * $significance) / $significance;
- } else {
- return floor($number * $significance) / $significance;
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function ROUNDDOWN()
-
-
- /**
- * SERIESSUM
- *
- * Returns the sum of a power series
- *
- * @param float $x Input value to the power series
- * @param float $n Initial power to which you want to raise $x
- * @param float $m Step by which to increase $n for each term in the series
- * @param array of mixed Data Series
- * @return float
- */
- public static function SERIESSUM() {
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
-
- $x = array_shift($aArgs);
- $n = array_shift($aArgs);
- $m = array_shift($aArgs);
-
- if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
- // Calculate
- $i = 0;
- foreach($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += $arg * pow($x,$n + ($m * $i++));
- } else {
- return PHPExcel_Calculation_Functions::VALUE();
- }
- }
- // Return
- return $returnValue;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function SERIESSUM()
-
-
- /**
- * SIGN
- *
- * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
- * if the number is 0, and -1 if the number is negative.
- *
- * @param float $number Number to round
- * @return int sign value
- */
- public static function SIGN($number) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
-
- if (is_bool($number))
- return (int) $number;
- if (is_numeric($number)) {
- if ($number == 0.0) {
- return 0;
- }
- return $number / abs($number);
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function SIGN()
-
-
- /**
- * SQRTPI
- *
- * Returns the square root of (number * pi).
- *
- * @param float $number Number
- * @return float Square Root of Number * Pi
- */
- public static function SQRTPI($number) {
- $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
-
- if (is_numeric($number)) {
- if ($number < 0) {
- return PHPExcel_Calculation_Functions::NaN();
- }
- return sqrt($number * M_PI) ;
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function SQRTPI()
-
-
- /**
- * SUBTOTAL
- *
- * Returns a subtotal in a list or database.
- *
- * @param int the number 1 to 11 that specifies which function to
- * use in calculating subtotals within a list.
- * @param array of mixed Data Series
- * @return float
- */
- public static function SUBTOTAL() {
- $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
-
- // Calculate
- $subtotal = array_shift($aArgs);
-
- if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
- switch($subtotal) {
- case 1 :
- return PHPExcel_Calculation_Statistical::AVERAGE($aArgs);
- break;
- case 2 :
- return PHPExcel_Calculation_Statistical::COUNT($aArgs);
- break;
- case 3 :
- return PHPExcel_Calculation_Statistical::COUNTA($aArgs);
- break;
- case 4 :
- return PHPExcel_Calculation_Statistical::MAX($aArgs);
- break;
- case 5 :
- return PHPExcel_Calculation_Statistical::MIN($aArgs);
- break;
- case 6 :
- return self::PRODUCT($aArgs);
- break;
- case 7 :
- return PHPExcel_Calculation_Statistical::STDEV($aArgs);
- break;
- case 8 :
- return PHPExcel_Calculation_Statistical::STDEVP($aArgs);
- break;
- case 9 :
- return self::SUM($aArgs);
- break;
- case 10 :
- return PHPExcel_Calculation_Statistical::VARFunc($aArgs);
- break;
- case 11 :
- return PHPExcel_Calculation_Statistical::VARP($aArgs);
- break;
- }
- }
- return PHPExcel_Calculation_Functions::VALUE();
- } // function SUBTOTAL()
-
-
- /**
- * SUM
- *
- * SUM computes the sum of all the values and cells referenced in the argument list.
- *
- * Excel Function:
- * SUM(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function SUM() {
- // Return value
- $returnValue = 0;
-
- // Loop through the arguments
- foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += $arg;
- }
- }
-
- // Return
- return $returnValue;
- } // function SUM()
-
-
- /**
- * 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 = PHPExcel_Calculation_Functions::flattenArray($aArgs);
- $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
- if (empty($sumArgs)) {
- $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)) {
- // Is it a value within our criteria
- $returnValue += $sumArgs[$key];
- }
- }
-
- // Return
- return $returnValue;
- } // function SUMIF()
-
-
- /**
- * SUMPRODUCT
- *
- * Excel Function:
- * SUMPRODUCT(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function SUMPRODUCT() {
+ public static function SUMIFS() {
$arrayList = func_get_args();
- $wrkArray = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
- $wrkCellCount = count($wrkArray);
-
- for ($i=0; $i< $wrkCellCount; ++$i) {
- if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
- $wrkArray[$i] = 0;
- }
- }
-
- foreach($arrayList as $matrixData) {
- $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData);
- $count = count($array2);
- if ($wrkCellCount != $count) {
- return PHPExcel_Calculation_Functions::VALUE();
- }
-
- foreach ($array2 as $i => $val) {
- if ((!is_numeric($val)) || (is_string($val))) {
- $val = 0;
- }
- $wrkArray[$i] *= $val;
- }
- }
-
- return array_sum($wrkArray);
- } // function SUMPRODUCT()
-
-
- /**
- * SUMSQ
- *
- * SUMSQ returns the sum of the squares of the arguments
- *
- * Excel Function:
- * SUMSQ(value1[,value2[, ...]])
- *
- * @access public
- * @category Mathematical and Trigonometric Functions
- * @param mixed $arg,... Data values
- * @return float
- */
- public static function SUMSQ() {
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += ($arg * $arg);
- }
- }
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
+
+ while (count($arrayList) > 0) {
+ $aArgsArray[] = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
+ $conditions[] = PHPExcel_Calculation_Functions::ifCondition(array_shift($arrayList));
+ }
+
+ // Loop through each set of arguments and conditions
+ foreach ($conditions as $index => $condition) {
+ $aArgs = $aArgsArray[$index];
+ $wildcard = false;
+ if ((strpos($condition, '*') !== false) || (strpos($condition, '?') !== false)) {
+ // * and ? are wildcard characters.
+ // Use ~* and ~? for literal star and question mark
+ // Code logic doesn't yet handle escaping
+ $condition = trim(ltrim($condition, '=<>'), '"');
+ $wildcard = true;
+ }
+ // Loop through arguments
+ foreach ($aArgs as $key => $arg) {
+ if ($wildcard) {
+ if (!fnmatch($condition, $arg, FNM_CASEFOLD)) {
+ // Is it a value within our criteria
+ $sumArgs[$key] = 0.0;
+ }
+ } else {
+ 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
+ $sumArgs[$key] = 0.0;
+ }
+ }
+ }
+ }
// Return
- return $returnValue;
- } // function SUMSQ()
-
-
- /**
- * SUMX2MY2
- *
- * @param mixed $value Value to check
- * @return float
- */
- public static function SUMX2MY2($matrixData1,$matrixData2) {
- $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
- $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
- $count1 = count($array1);
- $count2 = count($array2);
- if ($count1 < $count2) {
- $count = $count1;
- } else {
- $count = $count2;
- }
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
- $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
- }
- }
-
- return $result;
- } // function SUMX2MY2()
-
-
- /**
- * SUMX2PY2
- *
- * @param mixed $value Value to check
- * @return float
- */
- public static function SUMX2PY2($matrixData1,$matrixData2) {
- $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
- $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
- $count1 = count($array1);
- $count2 = count($array2);
- if ($count1 < $count2) {
- $count = $count1;
- } else {
- $count = $count2;
- }
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
- $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
- }
- }
-
- return $result;
- } // function SUMX2PY2()
-
-
- /**
- * SUMXMY2
- *
- * @param mixed $value Value to check
- * @return float
- */
- public static function SUMXMY2($matrixData1,$matrixData2) {
- $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
- $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
- $count1 = count($array1);
- $count2 = count($array2);
- if ($count1 < $count2) {
- $count = $count1;
- } else {
- $count = $count2;
- }
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
- $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
- }
- }
-
- return $result;
- } // function SUMXMY2()
-
-
- /**
- * TRUNC
- *
- * Truncates value to the number of fractional digits by number_digits.
- *
- * @param float $value
- * @param int $digits
- * @return float Truncated value
- */
- public static function TRUNC($value = 0, $digits = 0) {
- $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
- $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
-
- // Validate parameters
- if ((!is_numeric($value)) || (!is_numeric($digits)))
- return PHPExcel_Calculation_Functions::VALUE();
- $digits = floor($digits);
-
- // Truncate
- $adjust = pow(10, $digits);
-
- if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust),'0') < $adjust/10))
- return $value;
-
- return (intval($value * $adjust)) / $adjust;
- } // function TRUNC()
-
-} // class PHPExcel_Calculation_MathTrig
+ return array_sum($sumArgs);
+ }
+
+
+ /**
+ * SUMPRODUCT
+ *
+ * Excel Function:
+ * SUMPRODUCT(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function SUMPRODUCT()
+ {
+ $arrayList = func_get_args();
+
+ $wrkArray = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
+ $wrkCellCount = count($wrkArray);
+
+ for ($i=0; $i< $wrkCellCount; ++$i) {
+ if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
+ $wrkArray[$i] = 0;
+ }
+ }
+
+ foreach ($arrayList as $matrixData) {
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData);
+ $count = count($array2);
+ if ($wrkCellCount != $count) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+
+ foreach ($array2 as $i => $val) {
+ if ((!is_numeric($val)) || (is_string($val))) {
+ $val = 0;
+ }
+ $wrkArray[$i] *= $val;
+ }
+ }
+
+ return array_sum($wrkArray);
+ }
+
+
+ /**
+ * SUMSQ
+ *
+ * SUMSQ returns the sum of the squares of the arguments
+ *
+ * Excel Function:
+ * SUMSQ(value1[,value2[, ...]])
+ *
+ * @access public
+ * @category Mathematical and Trigonometric Functions
+ * @param mixed $arg,... Data values
+ * @return float
+ */
+ public static function SUMSQ()
+ {
+ $returnValue = 0;
+
+ // Loop through arguments
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
+ // Is it a numeric value?
+ if ((is_numeric($arg)) && (!is_string($arg))) {
+ $returnValue += ($arg * $arg);
+ }
+ }
+
+ return $returnValue;
+ }
+
+
+ /**
+ * SUMX2MY2
+ *
+ * @param mixed[] $matrixData1 Matrix #1
+ * @param mixed[] $matrixData2 Matrix #2
+ * @return float
+ */
+ public static function SUMX2MY2($matrixData1, $matrixData2)
+ {
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
+ $count = min(count($array1), count($array2));
+
+ $result = 0;
+ for ($i = 0; $i < $count; ++$i) {
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
+ $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
+ }
+ }
+
+ return $result;
+ }
+
+
+ /**
+ * SUMX2PY2
+ *
+ * @param mixed[] $matrixData1 Matrix #1
+ * @param mixed[] $matrixData2 Matrix #2
+ * @return float
+ */
+ public static function SUMX2PY2($matrixData1, $matrixData2)
+ {
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
+ $count = min(count($array1), count($array2));
+
+ $result = 0;
+ for ($i = 0; $i < $count; ++$i) {
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
+ $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
+ }
+ }
+
+ return $result;
+ }
+
+
+ /**
+ * SUMXMY2
+ *
+ * @param mixed[] $matrixData1 Matrix #1
+ * @param mixed[] $matrixData2 Matrix #2
+ * @return float
+ */
+ public static function SUMXMY2($matrixData1, $matrixData2)
+ {
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
+ $count = min(count($array1), count($array2));
+
+ $result = 0;
+ for ($i = 0; $i < $count; ++$i) {
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
+ $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
+ }
+ }
+
+ return $result;
+ }
+
+
+ /**
+ * TRUNC
+ *
+ * Truncates value to the number of fractional digits by number_digits.
+ *
+ * @param float $value
+ * @param int $digits
+ * @return float Truncated value
+ */
+ public static function TRUNC($value = 0, $digits = 0)
+ {
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
+
+ // Validate parameters
+ if ((!is_numeric($value)) || (!is_numeric($digits))) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ $digits = floor($digits);
+
+ // Truncate
+ $adjust = pow(10, $digits);
+
+ if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust), '0') < $adjust/10)) {
+ return $value;
+ }
+
+ return (intval($value * $adjust)) / $adjust;
+ }
+}
diff --git a/Classes/PHPExcel/Calculation/Statistical.php b/Classes/PHPExcel/Calculation/Statistical.php
index 05dae7be4..1a33610fc 100644
--- a/Classes/PHPExcel/Calculation/Statistical.php
+++ b/Classes/PHPExcel/Calculation/Statistical.php
@@ -1,38 +1,12 @@
$value) {
- if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
- unset($array1[$key]);
- unset($array2[$key]);
- }
- }
- foreach($array2 as $key => $value) {
- if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
- unset($array1[$key]);
- unset($array2[$key]);
- }
- }
- $array1 = array_merge($array1);
- $array2 = array_merge($array2);
-
- return True;
- } // function _checkTrendArrays()
-
-
- /**
- * Beta function.
- *
- * @author Jaco van Kooten
- *
- * @param p require p>0
- * @param q require q>0
- * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
- */
- private static function _beta($p, $q) {
- if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) {
- return 0.0;
- } else {
- return exp(self::_logBeta($p, $q));
- }
- } // function _beta()
-
-
- /**
- * Incomplete beta function
- *
- * @author Jaco van Kooten
- * @author Paul Meagher
- *
- * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992).
- * @param x require 0<=x<=1
- * @param p require p>0
- * @param q require q>0
- * @return 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow
- */
- private static function _incompleteBeta($x, $p, $q) {
- if ($x <= 0.0) {
- return 0.0;
- } elseif ($x >= 1.0) {
- return 1.0;
- } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
- return 0.0;
- }
- $beta_gam = exp((0 - self::_logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x));
- if ($x < ($p + 1.0) / ($p + $q + 2.0)) {
- return $beta_gam * self::_betaFraction($x, $p, $q) / $p;
- } else {
- return 1.0 - ($beta_gam * self::_betaFraction(1 - $x, $q, $p) / $q);
- }
- } // function _incompleteBeta()
-
-
- // Function cache for _logBeta function
- private static $_logBetaCache_p = 0.0;
- private static $_logBetaCache_q = 0.0;
- private static $_logBetaCache_result = 0.0;
-
- /**
- * The natural logarithm of the beta function.
- *
- * @param p require p>0
- * @param q require q>0
- * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
- * @author Jaco van Kooten
- */
- private static function _logBeta($p, $q) {
- if ($p != self::$_logBetaCache_p || $q != self::$_logBetaCache_q) {
- self::$_logBetaCache_p = $p;
- self::$_logBetaCache_q = $q;
- if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
- self::$_logBetaCache_result = 0.0;
- } else {
- self::$_logBetaCache_result = self::_logGamma($p) + self::_logGamma($q) - self::_logGamma($p + $q);
- }
- }
- return self::$_logBetaCache_result;
- } // function _logBeta()
-
-
- /**
- * Evaluates of continued fraction part of incomplete beta function.
- * Based on an idea from Numerical Recipes (W.H. Press et al, 1992).
- * @author Jaco van Kooten
- */
- private static function _betaFraction($x, $p, $q) {
- $c = 1.0;
- $sum_pq = $p + $q;
- $p_plus = $p + 1.0;
- $p_minus = $p - 1.0;
- $h = 1.0 - $sum_pq * $x / $p_plus;
- if (abs($h) < XMININ) {
- $h = XMININ;
- }
- $h = 1.0 / $h;
- $frac = $h;
- $m = 1;
- $delta = 0.0;
- while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION ) {
- $m2 = 2 * $m;
- // even index for d
- $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2));
- $h = 1.0 + $d * $h;
- if (abs($h) < XMININ) {
- $h = XMININ;
- }
- $h = 1.0 / $h;
- $c = 1.0 + $d / $c;
- if (abs($c) < XMININ) {
- $c = XMININ;
- }
- $frac *= $h * $c;
- // odd index for d
- $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2));
- $h = 1.0 + $d * $h;
- if (abs($h) < XMININ) {
- $h = XMININ;
- }
- $h = 1.0 / $h;
- $c = 1.0 + $d / $c;
- if (abs($c) < XMININ) {
- $c = XMININ;
- }
- $delta = $h * $c;
- $frac *= $delta;
- ++$m;
- }
- return $frac;
- } // function _betaFraction()
-
-
- /**
- * logGamma function
- *
- * @version 1.1
- * @author Jaco van Kooten
- *
- * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
- *
- * The natural logarithm of the gamma function.
- * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
- * Applied Mathematics Division
- * Argonne National Laboratory
- * Argonne, IL 60439
- *
- * References: - *
- * From the original documentation: - *
- *- * This routine calculates the LOG(GAMMA) function for a positive real argument X. - * Computation is based on an algorithm outlined in references 1 and 2. - * The program uses rational functions that theoretically approximate LOG(GAMMA) - * to at least 18 significant decimal digits. The approximation for X > 12 is from - * reference 3, while approximations for X < 12.0 are similar to those in reference - * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, - * the compiler, the intrinsic functions, and proper selection of the - * machine-dependent constants. - *
- *
- * Error returns:
- * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
- * The computation is believed to be free of underflow and overflow.
- *
+ * References: + *
+ * From the original documentation: + *
+ *+ * This routine calculates the LOG(GAMMA) function for a positive real argument X. + * Computation is based on an algorithm outlined in references 1 and 2. + * The program uses rational functions that theoretically approximate LOG(GAMMA) + * to at least 18 significant decimal digits. The approximation for X > 12 is from + * reference 3, while approximations for X < 12.0 are similar to those in reference + * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, + * the compiler, the intrinsic functions, and proper selection of the + * machine-dependent constants. + *
+ *
+ * Error returns:
+ * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
+ * The computation is believed to be free of underflow and overflow.
+ *
'; -// print_r($sharedFormulas); -// echo ''; - if (!isset($sharedFormulas[(string)$c->f['si']])) { -// echo 'SETTING NEW SHARED FORMULA
'; -// print_r($sharedFormulas); -// echo ''; - } else { -// echo 'GETTING SHARED FORMULA
'; -// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); -// echo '
'; +// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); +// echo '
'; -// print_r($namespacesMeta); -// echo '
'; -// print_r($namespacesContent); -// echo '
'; +// print_r($namespacesMeta); +// echo '
'; +// print_r($namespacesContent); +// echo '
= -1; --$k) { - if ($k == -1) { - break; - } - if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) { - $e[$k] = 0.0; - break; - } - } - if ($k == $p - 2) { - $kase = 4; - } else { - for ($ks = $p - 1; $ks >= $k; --$ks) { - if ($ks == $k) { - break; - } - $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.); - if (abs($this->s[$ks]) <= $eps * $t) { - $this->s[$ks] = 0.0; - break; - } - } - if ($ks == $k) { - $kase = 3; - } else if ($ks == $p-1) { - $kase = 1; - } else { - $kase = 2; - $k = $ks; - } - } - ++$k; - - // Perform the task indicated by kase. - switch ($kase) { - // Deflate negligible s(p). - case 1: - $f = $e[$p-2]; - $e[$p-2] = 0.0; - for ($j = $p - 2; $j >= $k; --$j) { - $t = hypo($this->s[$j],$f); - $cs = $this->s[$j] / $t; - $sn = $f / $t; - $this->s[$j] = $t; - if ($j != $k) { - $f = -$sn * $e[$j-1]; - $e[$j-1] = $cs * $e[$j-1]; - } - if ($wantv) { - for ($i = 0; $i < $this->n; ++$i) { - $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1]; - $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1]; - $this->V[$i][$j] = $t; - } - } - } - break; - // Split at negligible s(k). - case 2: - $f = $e[$k-1]; - $e[$k-1] = 0.0; - for ($j = $k; $j < $p; ++$j) { - $t = hypo($this->s[$j], $f); - $cs = $this->s[$j] / $t; - $sn = $f / $t; - $this->s[$j] = $t; - $f = -$sn * $e[$j]; - $e[$j] = $cs * $e[$j]; - if ($wantu) { - for ($i = 0; $i < $this->m; ++$i) { - $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1]; - $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1]; - $this->U[$i][$j] = $t; - } - } - } - break; - // Perform one qr step. - case 3: - // Calculate the shift. - $scale = max(max(max(max( - abs($this->s[$p-1]),abs($this->s[$p-2])),abs($e[$p-2])), - abs($this->s[$k])), abs($e[$k])); - $sp = $this->s[$p-1] / $scale; - $spm1 = $this->s[$p-2] / $scale; - $epm1 = $e[$p-2] / $scale; - $sk = $this->s[$k] / $scale; - $ek = $e[$k] / $scale; - $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0; - $c = ($sp * $epm1) * ($sp * $epm1); - $shift = 0.0; - if (($b != 0.0) || ($c != 0.0)) { - $shift = sqrt($b * $b + $c); - if ($b < 0.0) { - $shift = -$shift; - } - $shift = $c / ($b + $shift); - } - $f = ($sk + $sp) * ($sk - $sp) + $shift; - $g = $sk * $ek; - // Chase zeros. - for ($j = $k; $j < $p-1; ++$j) { - $t = hypo($f,$g); - $cs = $f/$t; - $sn = $g/$t; - if ($j != $k) { - $e[$j-1] = $t; - } - $f = $cs * $this->s[$j] + $sn * $e[$j]; - $e[$j] = $cs * $e[$j] - $sn * $this->s[$j]; - $g = $sn * $this->s[$j+1]; - $this->s[$j+1] = $cs * $this->s[$j+1]; - if ($wantv) { - for ($i = 0; $i < $this->n; ++$i) { - $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1]; - $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1]; - $this->V[$i][$j] = $t; - } - } - $t = hypo($f,$g); - $cs = $f/$t; - $sn = $g/$t; - $this->s[$j] = $t; - $f = $cs * $e[$j] + $sn * $this->s[$j+1]; - $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1]; - $g = $sn * $e[$j+1]; - $e[$j+1] = $cs * $e[$j+1]; - if ($wantu && ($j < $this->m - 1)) { - for ($i = 0; $i < $this->m; ++$i) { - $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1]; - $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1]; - $this->U[$i][$j] = $t; - } - } - } - $e[$p-2] = $f; - $iter = $iter + 1; - break; - // Convergence. - case 4: - // Make the singular values positive. - if ($this->s[$k] <= 0.0) { - $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0); - if ($wantv) { - for ($i = 0; $i <= $pp; ++$i) { - $this->V[$i][$k] = -$this->V[$i][$k]; - } - } - } - // Order the singular values. - while ($k < $pp) { - if ($this->s[$k] >= $this->s[$k+1]) { - break; - } - $t = $this->s[$k]; - $this->s[$k] = $this->s[$k+1]; - $this->s[$k+1] = $t; - if ($wantv AND ($k < $this->n - 1)) { - for ($i = 0; $i < $this->n; ++$i) { - $t = $this->V[$i][$k+1]; - $this->V[$i][$k+1] = $this->V[$i][$k]; - $this->V[$i][$k] = $t; - } - } - if ($wantu AND ($k < $this->m-1)) { - for ($i = 0; $i < $this->m; ++$i) { - $t = $this->U[$i][$k+1]; - $this->U[$i][$k+1] = $this->U[$i][$k]; - $this->U[$i][$k] = $t; - } - } - ++$k; - } - $iter = 0; - --$p; - break; - } // end switch - } // end while - - } // end constructor - - - /** - * Return the left singular vectors - * - * @access public - * @return U - */ - public function getU() { - return new Matrix($this->U, $this->m, min($this->m + 1, $this->n)); - } - - - /** - * Return the right singular vectors - * - * @access public - * @return V - */ - public function getV() { - return new Matrix($this->V); - } - - - /** - * Return the one-dimensional array of singular values - * - * @access public - * @return diagonal of S. - */ - public function getSingularValues() { - return $this->s; - } - - - /** - * Return the diagonal matrix of singular values - * - * @access public - * @return S - */ - public function getS() { - for ($i = 0; $i < $this->n; ++$i) { - for ($j = 0; $j < $this->n; ++$j) { - $S[$i][$j] = 0.0; - } - $S[$i][$i] = $this->s[$i]; - } - return new Matrix($S); - } - - - /** - * Two norm - * - * @access public - * @return max(S) - */ - public function norm2() { - return $this->s[0]; - } - - - /** - * Two norm condition number - * - * @access public - * @return max(S)/min(S) - */ - public function cond() { - return $this->s[0] / $this->s[min($this->m, $this->n) - 1]; - } - - - /** - * Effective numerical matrix rank - * - * @access public - * @return Number of nonnegligible singular values. - */ - public function rank() { - $eps = pow(2.0, -52.0); - $tol = max($this->m, $this->n) * $this->s[0] * $eps; - $r = 0; - for ($i = 0; $i < count($this->s); ++$i) { - if ($this->s[$i] > $tol) { - ++$r; - } - } - return $r; - } - -} // class SingularValueDecomposition +class SingularValueDecomposition +{ + /** + * Internal storage of U. + * @var array + */ + private $U = array(); + + /** + * Internal storage of V. + * @var array + */ + private $V = array(); + + /** + * Internal storage of singular values. + * @var array + */ + private $s = array(); + + /** + * Row dimension. + * @var int + */ + private $m; + + /** + * Column dimension. + * @var int + */ + private $n; + + /** + * Construct the singular value decomposition + * + * Derived from LINPACK code. + * + * @param $A Rectangular matrix + * @return Structure to access U, S and V. + */ + public function __construct($Arg) + { + // Initialize. + $A = $Arg->getArrayCopy(); + $this->m = $Arg->getRowDimension(); + $this->n = $Arg->getColumnDimension(); + $nu = min($this->m, $this->n); + $e = array(); + $work = array(); + $wantu = true; + $wantv = true; + $nct = min($this->m - 1, $this->n); + $nrt = max(0, min($this->n - 2, $this->m)); + + // Reduce A to bidiagonal form, storing the diagonal elements + // in s and the super-diagonal elements in e. + for ($k = 0; $k < max($nct, $nrt); ++$k) { + if ($k < $nct) { + // Compute the transformation for the k-th column and + // place the k-th diagonal in s[$k]. + // Compute 2-norm of k-th column without under/overflow. + $this->s[$k] = 0; + for ($i = $k; $i < $this->m; ++$i) { + $this->s[$k] = hypo($this->s[$k], $A[$i][$k]); + } + if ($this->s[$k] != 0.0) { + if ($A[$k][$k] < 0.0) { + $this->s[$k] = -$this->s[$k]; + } + for ($i = $k; $i < $this->m; ++$i) { + $A[$i][$k] /= $this->s[$k]; + } + $A[$k][$k] += 1.0; + } + $this->s[$k] = -$this->s[$k]; + } + + for ($j = $k + 1; $j < $this->n; ++$j) { + if (($k < $nct) & ($this->s[$k] != 0.0)) { + // Apply the transformation. + $t = 0; + for ($i = $k; $i < $this->m; ++$i) { + $t += $A[$i][$k] * $A[$i][$j]; + } + $t = -$t / $A[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $A[$i][$j] += $t * $A[$i][$k]; + } + // Place the k-th row of A into e for the + // subsequent calculation of the row transformation. + $e[$j] = $A[$k][$j]; + } + } + + if ($wantu and ($k < $nct)) { + // Place the transformation in U for subsequent back + // multiplication. + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$k] = $A[$i][$k]; + } + } + + if ($k < $nrt) { + // Compute the k-th row transformation and place the + // k-th super-diagonal in e[$k]. + // Compute 2-norm without under/overflow. + $e[$k] = 0; + for ($i = $k + 1; $i < $this->n; ++$i) { + $e[$k] = hypo($e[$k], $e[$i]); + } + if ($e[$k] != 0.0) { + if ($e[$k+1] < 0.0) { + $e[$k] = -$e[$k]; + } + for ($i = $k + 1; $i < $this->n; ++$i) { + $e[$i] /= $e[$k]; + } + $e[$k+1] += 1.0; + } + $e[$k] = -$e[$k]; + if (($k+1 < $this->m) and ($e[$k] != 0.0)) { + // Apply the transformation. + for ($i = $k+1; $i < $this->m; ++$i) { + $work[$i] = 0.0; + } + for ($j = $k+1; $j < $this->n; ++$j) { + for ($i = $k+1; $i < $this->m; ++$i) { + $work[$i] += $e[$j] * $A[$i][$j]; + } + } + for ($j = $k + 1; $j < $this->n; ++$j) { + $t = -$e[$j] / $e[$k+1]; + for ($i = $k + 1; $i < $this->m; ++$i) { + $A[$i][$j] += $t * $work[$i]; + } + } + } + if ($wantv) { + // Place the transformation in V for subsequent + // back multiplication. + for ($i = $k + 1; $i < $this->n; ++$i) { + $this->V[$i][$k] = $e[$i]; + } + } + } + } + + // Set up the final bidiagonal matrix or order p. + $p = min($this->n, $this->m + 1); + if ($nct < $this->n) { + $this->s[$nct] = $A[$nct][$nct]; + } + if ($this->m < $p) { + $this->s[$p-1] = 0.0; + } + if ($nrt + 1 < $p) { + $e[$nrt] = $A[$nrt][$p-1]; + } + $e[$p-1] = 0.0; + // If required, generate U. + if ($wantu) { + for ($j = $nct; $j < $nu; ++$j) { + for ($i = 0; $i < $this->m; ++$i) { + $this->U[$i][$j] = 0.0; + } + $this->U[$j][$j] = 1.0; + } + for ($k = $nct - 1; $k >= 0; --$k) { + if ($this->s[$k] != 0.0) { + for ($j = $k + 1; $j < $nu; ++$j) { + $t = 0; + for ($i = $k; $i < $this->m; ++$i) { + $t += $this->U[$i][$k] * $this->U[$i][$j]; + } + $t = -$t / $this->U[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$j] += $t * $this->U[$i][$k]; + } + } + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$k] = -$this->U[$i][$k]; + } + $this->U[$k][$k] = 1.0 + $this->U[$k][$k]; + for ($i = 0; $i < $k - 1; ++$i) { + $this->U[$i][$k] = 0.0; + } + } else { + for ($i = 0; $i < $this->m; ++$i) { + $this->U[$i][$k] = 0.0; + } + $this->U[$k][$k] = 1.0; + } + } + } + + // If required, generate V. + if ($wantv) { + for ($k = $this->n - 1; $k >= 0; --$k) { + if (($k < $nrt) and ($e[$k] != 0.0)) { + for ($j = $k + 1; $j < $nu; ++$j) { + $t = 0; + for ($i = $k + 1; $i < $this->n; ++$i) { + $t += $this->V[$i][$k]* $this->V[$i][$j]; + } + $t = -$t / $this->V[$k+1][$k]; + for ($i = $k + 1; $i < $this->n; ++$i) { + $this->V[$i][$j] += $t * $this->V[$i][$k]; + } + } + } + for ($i = 0; $i < $this->n; ++$i) { + $this->V[$i][$k] = 0.0; + } + $this->V[$k][$k] = 1.0; + } + } + + // Main iteration loop for the singular values. + $pp = $p - 1; + $iter = 0; + $eps = pow(2.0, -52.0); + + while ($p > 0) { + // Here is where a test for too many iterations would go. + // This section of the program inspects for negligible + // elements in the s and e arrays. On completion the + // variables kase and k are set as follows: + // kase = 1 if s(p) and e[k-1] are negligible and k
= -1; --$k) {
+ if ($k == -1) {
+ break;
+ }
+ if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) {
+ $e[$k] = 0.0;
+ break;
+ }
+ }
+ if ($k == $p - 2) {
+ $kase = 4;
+ } else {
+ for ($ks = $p - 1; $ks >= $k; --$ks) {
+ if ($ks == $k) {
+ break;
+ }
+ $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.);
+ if (abs($this->s[$ks]) <= $eps * $t) {
+ $this->s[$ks] = 0.0;
+ break;
+ }
+ }
+ if ($ks == $k) {
+ $kase = 3;
+ } elseif ($ks == $p-1) {
+ $kase = 1;
+ } else {
+ $kase = 2;
+ $k = $ks;
+ }
+ }
+ ++$k;
+
+ // Perform the task indicated by kase.
+ switch ($kase) {
+ // Deflate negligible s(p).
+ case 1:
+ $f = $e[$p-2];
+ $e[$p-2] = 0.0;
+ for ($j = $p - 2; $j >= $k; --$j) {
+ $t = hypo($this->s[$j], $f);
+ $cs = $this->s[$j] / $t;
+ $sn = $f / $t;
+ $this->s[$j] = $t;
+ if ($j != $k) {
+ $f = -$sn * $e[$j-1];
+ $e[$j-1] = $cs * $e[$j-1];
+ }
+ if ($wantv) {
+ for ($i = 0; $i < $this->n; ++$i) {
+ $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1];
+ $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1];
+ $this->V[$i][$j] = $t;
+ }
+ }
+ }
+ break;
+ // Split at negligible s(k).
+ case 2:
+ $f = $e[$k-1];
+ $e[$k-1] = 0.0;
+ for ($j = $k; $j < $p; ++$j) {
+ $t = hypo($this->s[$j], $f);
+ $cs = $this->s[$j] / $t;
+ $sn = $f / $t;
+ $this->s[$j] = $t;
+ $f = -$sn * $e[$j];
+ $e[$j] = $cs * $e[$j];
+ if ($wantu) {
+ for ($i = 0; $i < $this->m; ++$i) {
+ $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1];
+ $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1];
+ $this->U[$i][$j] = $t;
+ }
+ }
+ }
+ break;
+ // Perform one qr step.
+ case 3:
+ // Calculate the shift.
+ $scale = max(max(max(max(abs($this->s[$p-1]), abs($this->s[$p-2])), abs($e[$p-2])), abs($this->s[$k])), abs($e[$k]));
+ $sp = $this->s[$p-1] / $scale;
+ $spm1 = $this->s[$p-2] / $scale;
+ $epm1 = $e[$p-2] / $scale;
+ $sk = $this->s[$k] / $scale;
+ $ek = $e[$k] / $scale;
+ $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0;
+ $c = ($sp * $epm1) * ($sp * $epm1);
+ $shift = 0.0;
+ if (($b != 0.0) || ($c != 0.0)) {
+ $shift = sqrt($b * $b + $c);
+ if ($b < 0.0) {
+ $shift = -$shift;
+ }
+ $shift = $c / ($b + $shift);
+ }
+ $f = ($sk + $sp) * ($sk - $sp) + $shift;
+ $g = $sk * $ek;
+ // Chase zeros.
+ for ($j = $k; $j < $p-1; ++$j) {
+ $t = hypo($f, $g);
+ $cs = $f/$t;
+ $sn = $g/$t;
+ if ($j != $k) {
+ $e[$j-1] = $t;
+ }
+ $f = $cs * $this->s[$j] + $sn * $e[$j];
+ $e[$j] = $cs * $e[$j] - $sn * $this->s[$j];
+ $g = $sn * $this->s[$j+1];
+ $this->s[$j+1] = $cs * $this->s[$j+1];
+ if ($wantv) {
+ for ($i = 0; $i < $this->n; ++$i) {
+ $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1];
+ $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1];
+ $this->V[$i][$j] = $t;
+ }
+ }
+ $t = hypo($f, $g);
+ $cs = $f/$t;
+ $sn = $g/$t;
+ $this->s[$j] = $t;
+ $f = $cs * $e[$j] + $sn * $this->s[$j+1];
+ $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1];
+ $g = $sn * $e[$j+1];
+ $e[$j+1] = $cs * $e[$j+1];
+ if ($wantu && ($j < $this->m - 1)) {
+ for ($i = 0; $i < $this->m; ++$i) {
+ $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1];
+ $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1];
+ $this->U[$i][$j] = $t;
+ }
+ }
+ }
+ $e[$p-2] = $f;
+ $iter = $iter + 1;
+ break;
+ // Convergence.
+ case 4:
+ // Make the singular values positive.
+ if ($this->s[$k] <= 0.0) {
+ $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0);
+ if ($wantv) {
+ for ($i = 0; $i <= $pp; ++$i) {
+ $this->V[$i][$k] = -$this->V[$i][$k];
+ }
+ }
+ }
+ // Order the singular values.
+ while ($k < $pp) {
+ if ($this->s[$k] >= $this->s[$k+1]) {
+ break;
+ }
+ $t = $this->s[$k];
+ $this->s[$k] = $this->s[$k+1];
+ $this->s[$k+1] = $t;
+ if ($wantv and ($k < $this->n - 1)) {
+ for ($i = 0; $i < $this->n; ++$i) {
+ $t = $this->V[$i][$k+1];
+ $this->V[$i][$k+1] = $this->V[$i][$k];
+ $this->V[$i][$k] = $t;
+ }
+ }
+ if ($wantu and ($k < $this->m-1)) {
+ for ($i = 0; $i < $this->m; ++$i) {
+ $t = $this->U[$i][$k+1];
+ $this->U[$i][$k+1] = $this->U[$i][$k];
+ $this->U[$i][$k] = $t;
+ }
+ }
+ ++$k;
+ }
+ $iter = 0;
+ --$p;
+ break;
+ } // end switch
+ } // end while
+
+ } // end constructor
+
+
+ /**
+ * Return the left singular vectors
+ *
+ * @access public
+ * @return U
+ */
+ public function getU()
+ {
+ return new Matrix($this->U, $this->m, min($this->m + 1, $this->n));
+ }
+
+
+ /**
+ * Return the right singular vectors
+ *
+ * @access public
+ * @return V
+ */
+ public function getV()
+ {
+ return new Matrix($this->V);
+ }
+
+
+ /**
+ * Return the one-dimensional array of singular values
+ *
+ * @access public
+ * @return diagonal of S.
+ */
+ public function getSingularValues()
+ {
+ return $this->s;
+ }
+
+
+ /**
+ * Return the diagonal matrix of singular values
+ *
+ * @access public
+ * @return S
+ */
+ public function getS()
+ {
+ for ($i = 0; $i < $this->n; ++$i) {
+ for ($j = 0; $j < $this->n; ++$j) {
+ $S[$i][$j] = 0.0;
+ }
+ $S[$i][$i] = $this->s[$i];
+ }
+ return new Matrix($S);
+ }
+
+
+ /**
+ * Two norm
+ *
+ * @access public
+ * @return max(S)
+ */
+ public function norm2()
+ {
+ return $this->s[0];
+ }
+
+
+ /**
+ * Two norm condition number
+ *
+ * @access public
+ * @return max(S)/min(S)
+ */
+ public function cond()
+ {
+ return $this->s[0] / $this->s[min($this->m, $this->n) - 1];
+ }
+
+
+ /**
+ * Effective numerical matrix rank
+ *
+ * @access public
+ * @return Number of nonnegligible singular values.
+ */
+ public function rank()
+ {
+ $eps = pow(2.0, -52.0);
+ $tol = max($this->m, $this->n) * $this->s[0] * $eps;
+ $r = 0;
+ for ($i = 0; $i < count($this->s); ++$i) {
+ if ($this->s[$i] > $tol) {
+ ++$r;
+ }
+ }
+ return $r;
+ }
+}
diff --git a/Classes/PHPExcel/Shared/JAMA/utils/Error.php b/Classes/PHPExcel/Shared/JAMA/utils/Error.php
index e73252b3d..71b8c994a 100644
--- a/Classes/PHPExcel/Shared/JAMA/utils/Error.php
+++ b/Classes/PHPExcel/Shared/JAMA/utils/Error.php
@@ -1,10 +1,10 @@
abs($b)) {
- $r = $b / $a;
- $r = abs($a) * sqrt(1 + $r * $r);
- } elseif ($b != 0) {
- $r = $a / $b;
- $r = abs($b) * sqrt(1 + $r * $r);
- } else {
- $r = 0.0;
- }
- return $r;
-} // function hypo()
+function hypo($a, $b)
+{
+ if (abs($a) > abs($b)) {
+ $r = $b / $a;
+ $r = abs($a) * sqrt(1 + $r * $r);
+ } elseif ($b != 0) {
+ $r = $a / $b;
+ $r = abs($b) * sqrt(1 + $r * $r);
+ } else {
+ $r = 0.0;
+ }
+ return $r;
+} // function hypo()
/**
- * Mike Bommarito's version.
- * Compute n-dimensional hyotheneuse.
+ * Mike Bommarito's version.
+ * Compute n-dimensional hyotheneuse.
*
function hypot() {
- $s = 0;
- foreach (func_get_args() as $d) {
- if (is_numeric($d)) {
- $s += pow($d, 2);
- } else {
- throw new PHPExcel_Calculation_Exception(JAMAError(ArgumentTypeException));
- }
- }
- return sqrt($s);
+ $s = 0;
+ foreach (func_get_args() as $d) {
+ if (is_numeric($d)) {
+ $s += pow($d, 2);
+ } else {
+ throw new PHPExcel_Calculation_Exception(JAMAError(ARGUMENT_TYPE_EXCEPTION));
+ }
+ }
+ return sqrt($s);
}
*/
diff --git a/Classes/PHPExcel/Shared/OLE.php b/Classes/PHPExcel/Shared/OLE.php
index 9796282a8..42a3c529f 100644
--- a/Classes/PHPExcel/Shared/OLE.php
+++ b/Classes/PHPExcel/Shared/OLE.php
@@ -37,495 +37,490 @@
*/
class PHPExcel_Shared_OLE
{
- const OLE_PPS_TYPE_ROOT = 5;
- const OLE_PPS_TYPE_DIR = 1;
- const OLE_PPS_TYPE_FILE = 2;
- const OLE_DATA_SIZE_SMALL = 0x1000;
- const OLE_LONG_INT_SIZE = 4;
- const OLE_PPS_SIZE = 0x80;
-
- /**
- * The file handle for reading an OLE container
- * @var resource
- */
- public $_file_handle;
-
- /**
- * Array of PPS's found on the OLE container
- * @var array
- */
- public $_list = array();
-
- /**
- * Root directory of OLE container
- * @var OLE_PPS_Root
- */
- public $root;
-
- /**
- * Big Block Allocation Table
- * @var array (blockId => nextBlockId)
- */
- public $bbat;
-
- /**
- * Short Block Allocation Table
- * @var array (blockId => nextBlockId)
- */
- public $sbat;
-
- /**
- * Size of big blocks. This is usually 512.
- * @var int number of octets per block.
- */
- public $bigBlockSize;
-
- /**
- * Size of small blocks. This is usually 64.
- * @var int number of octets per block
- */
- public $smallBlockSize;
-
- /**
- * Reads an OLE container from the contents of the file given.
- *
- * @acces public
- * @param string $file
- * @return mixed true on success, PEAR_Error on failure
- */
- public function read($file)
- {
- $fh = fopen($file, "r");
- if (!$fh) {
- throw new PHPExcel_Reader_Exception("Can't open file $file");
- }
- $this->_file_handle = $fh;
-
- $signature = fread($fh, 8);
- if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
- throw new PHPExcel_Reader_Exception("File doesn't seem to be an OLE container.");
- }
- fseek($fh, 28);
- if (fread($fh, 2) != "\xFE\xFF") {
- // This shouldn't be a problem in practice
- throw new PHPExcel_Reader_Exception("Only Little-Endian encoding is supported.");
- }
- // Size of blocks and short blocks in bytes
- $this->bigBlockSize = pow(2, self::_readInt2($fh));
- $this->smallBlockSize = pow(2, self::_readInt2($fh));
-
- // Skip UID, revision number and version number
- fseek($fh, 44);
- // Number of blocks in Big Block Allocation Table
- $bbatBlockCount = self::_readInt4($fh);
-
- // Root chain 1st block
- $directoryFirstBlockId = self::_readInt4($fh);
-
- // Skip unused bytes
- fseek($fh, 56);
- // Streams shorter than this are stored using small blocks
- $this->bigBlockThreshold = self::_readInt4($fh);
- // Block id of first sector in Short Block Allocation Table
- $sbatFirstBlockId = self::_readInt4($fh);
- // Number of blocks in Short Block Allocation Table
- $sbbatBlockCount = self::_readInt4($fh);
- // Block id of first sector in Master Block Allocation Table
- $mbatFirstBlockId = self::_readInt4($fh);
- // Number of blocks in Master Block Allocation Table
- $mbbatBlockCount = self::_readInt4($fh);
- $this->bbat = array();
-
- // Remaining 4 * 109 bytes of current block is beginning of Master
- // Block Allocation Table
- $mbatBlocks = array();
- for ($i = 0; $i < 109; ++$i) {
- $mbatBlocks[] = self::_readInt4($fh);
- }
-
- // Read rest of Master Block Allocation Table (if any is left)
- $pos = $this->_getBlockOffset($mbatFirstBlockId);
- for ($i = 0; $i < $mbbatBlockCount; ++$i) {
- fseek($fh, $pos);
- for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
- $mbatBlocks[] = self::_readInt4($fh);
- }
- // Last block id in each block points to next block
- $pos = $this->_getBlockOffset(self::_readInt4($fh));
- }
-
- // Read Big Block Allocation Table according to chain specified by
- // $mbatBlocks
- for ($i = 0; $i < $bbatBlockCount; ++$i) {
- $pos = $this->_getBlockOffset($mbatBlocks[$i]);
- fseek($fh, $pos);
- for ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) {
- $this->bbat[] = self::_readInt4($fh);
- }
- }
-
- // Read short block allocation table (SBAT)
- $this->sbat = array();
- $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
- $sbatFh = $this->getStream($sbatFirstBlockId);
- for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
- $this->sbat[$blockId] = self::_readInt4($sbatFh);
- }
- fclose($sbatFh);
-
- $this->_readPpsWks($directoryFirstBlockId);
-
- return true;
- }
-
- /**
- * @param int block id
- * @param int byte offset from beginning of file
- * @access public
- */
- public function _getBlockOffset($blockId)
- {
- return 512 + $blockId * $this->bigBlockSize;
- }
-
- /**
- * Returns a stream for use with fread() etc. External callers should
- * use PHPExcel_Shared_OLE_PPS_File::getStream().
- * @param int|PPS block id or PPS
- * @return resource read-only stream
- */
- public function getStream($blockIdOrPps)
- {
- static $isRegistered = false;
- if (!$isRegistered) {
- stream_wrapper_register('ole-chainedblockstream',
- 'PHPExcel_Shared_OLE_ChainedBlockStream');
- $isRegistered = true;
- }
-
- // Store current instance in global array, so that it can be accessed
- // in OLE_ChainedBlockStream::stream_open().
- // Object is removed from self::$instances in OLE_Stream::close().
- $GLOBALS['_OLE_INSTANCES'][] = $this;
- $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES']));
-
- $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
- if ($blockIdOrPps instanceof PHPExcel_Shared_OLE_PPS) {
- $path .= '&blockId=' . $blockIdOrPps->_StartBlock;
- $path .= '&size=' . $blockIdOrPps->Size;
- } else {
- $path .= '&blockId=' . $blockIdOrPps;
- }
- return fopen($path, 'r');
- }
-
- /**
- * Reads a signed char.
- * @param resource file handle
- * @return int
- * @access public
- */
- private static function _readInt1($fh)
- {
- list(, $tmp) = unpack("c", fread($fh, 1));
- return $tmp;
- }
-
- /**
- * Reads an unsigned short (2 octets).
- * @param resource file handle
- * @return int
- * @access public
- */
- private static function _readInt2($fh)
- {
- list(, $tmp) = unpack("v", fread($fh, 2));
- return $tmp;
- }
-
- /**
- * Reads an unsigned long (4 octets).
- * @param resource file handle
- * @return int
- * @access public
- */
- private static function _readInt4($fh)
- {
- list(, $tmp) = unpack("V", fread($fh, 4));
- return $tmp;
- }
-
- /**
- * Gets information about all PPS's on the OLE container from the PPS WK's
- * creates an OLE_PPS object for each one.
- *
- * @access public
- * @param integer the block id of the first block
- * @return mixed true on success, PEAR_Error on failure
- */
- public function _readPpsWks($blockId)
- {
- $fh = $this->getStream($blockId);
- for ($pos = 0; ; $pos += 128) {
- fseek($fh, $pos, SEEK_SET);
- $nameUtf16 = fread($fh, 64);
- $nameLength = self::_readInt2($fh);
- $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
- // Simple conversion from UTF-16LE to ISO-8859-1
- $name = str_replace("\x00", "", $nameUtf16);
- $type = self::_readInt1($fh);
- switch ($type) {
- case self::OLE_PPS_TYPE_ROOT:
- $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array());
- $this->root = $pps;
- break;
- case self::OLE_PPS_TYPE_DIR:
- $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null,
- null, null, null, null, array());
- break;
- case self::OLE_PPS_TYPE_FILE:
- $pps = new PHPExcel_Shared_OLE_PPS_File($name);
- break;
- default:
- continue;
- }
- fseek($fh, 1, SEEK_CUR);
- $pps->Type = $type;
- $pps->Name = $name;
- $pps->PrevPps = self::_readInt4($fh);
- $pps->NextPps = self::_readInt4($fh);
- $pps->DirPps = self::_readInt4($fh);
- fseek($fh, 20, SEEK_CUR);
- $pps->Time1st = self::OLE2LocalDate(fread($fh, 8));
- $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8));
- $pps->_StartBlock = self::_readInt4($fh);
- $pps->Size = self::_readInt4($fh);
- $pps->No = count($this->_list);
- $this->_list[] = $pps;
-
- // check if the PPS tree (starting from root) is complete
- if (isset($this->root) &&
- $this->_ppsTreeComplete($this->root->No)) {
-
- break;
- }
- }
- fclose($fh);
-
- // Initialize $pps->children on directories
- foreach ($this->_list as $pps) {
- if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
- $nos = array($pps->DirPps);
- $pps->children = array();
- while ($nos) {
- $no = array_pop($nos);
- if ($no != -1) {
- $childPps = $this->_list[$no];
- $nos[] = $childPps->PrevPps;
- $nos[] = $childPps->NextPps;
- $pps->children[] = $childPps;
- }
- }
- }
- }
-
- return true;
- }
-
- /**
- * It checks whether the PPS tree is complete (all PPS's read)
- * starting with the given PPS (not necessarily root)
- *
- * @access public
- * @param integer $index The index of the PPS from which we are checking
- * @return boolean Whether the PPS tree for the given PPS is complete
- */
- public function _ppsTreeComplete($index)
- {
- return isset($this->_list[$index]) &&
- ($pps = $this->_list[$index]) &&
- ($pps->PrevPps == -1 ||
- $this->_ppsTreeComplete($pps->PrevPps)) &&
- ($pps->NextPps == -1 ||
- $this->_ppsTreeComplete($pps->NextPps)) &&
- ($pps->DirPps == -1 ||
- $this->_ppsTreeComplete($pps->DirPps));
- }
-
- /**
- * Checks whether a PPS is a File PPS or not.
- * If there is no PPS for the index given, it will return false.
- *
- * @access public
- * @param integer $index The index for the PPS
- * @return bool true if it's a File PPS, false otherwise
- */
- public function isFile($index)
- {
- if (isset($this->_list[$index])) {
- return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE);
- }
- return false;
- }
-
- /**
- * Checks whether a PPS is a Root PPS or not.
- * If there is no PPS for the index given, it will return false.
- *
- * @access public
- * @param integer $index The index for the PPS.
- * @return bool true if it's a Root PPS, false otherwise
- */
- public function isRoot($index)
- {
- if (isset($this->_list[$index])) {
- return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT);
- }
- return false;
- }
-
- /**
- * Gives the total number of PPS's found in the OLE container.
- *
- * @access public
- * @return integer The total number of PPS's found in the OLE container
- */
- public function ppsTotal()
- {
- return count($this->_list);
- }
-
- /**
- * Gets data from a PPS
- * If there is no PPS for the index given, it will return an empty string.
- *
- * @access public
- * @param integer $index The index for the PPS
- * @param integer $position The position from which to start reading
- * (relative to the PPS)
- * @param integer $length The amount of bytes to read (at most)
- * @return string The binary string containing the data requested
- * @see OLE_PPS_File::getStream()
- */
- public function getData($index, $position, $length)
- {
- // if position is not valid return empty string
- if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
- return '';
- }
- $fh = $this->getStream($this->_list[$index]);
- $data = stream_get_contents($fh, $length, $position);
- fclose($fh);
- return $data;
- }
-
- /**
- * Gets the data length from a PPS
- * If there is no PPS for the index given, it will return 0.
- *
- * @access public
- * @param integer $index The index for the PPS
- * @return integer The amount of bytes in data the PPS has
- */
- public function getDataLength($index)
- {
- if (isset($this->_list[$index])) {
- return $this->_list[$index]->Size;
- }
- return 0;
- }
-
- /**
- * Utility function to transform ASCII text to Unicode
- *
- * @access public
- * @static
- * @param string $ascii The ASCII string to transform
- * @return string The string in Unicode
- */
- public static function Asc2Ucs($ascii)
- {
- $rawname = '';
- for ($i = 0; $i < strlen($ascii); ++$i) {
- $rawname .= $ascii{$i} . "\x00";
- }
- return $rawname;
- }
-
- /**
- * Utility function
- * Returns a string for the OLE container with the date given
- *
- * @access public
- * @static
- * @param integer $date A timestamp
- * @return string The string for the OLE container
- */
- public static function LocalDate2OLE($date = null)
- {
- if (!isset($date)) {
- return "\x00\x00\x00\x00\x00\x00\x00\x00";
- }
-
- // factor used for separating numbers into 4 bytes parts
- $factor = pow(2, 32);
-
- // days from 1-1-1601 until the beggining of UNIX era
- $days = 134774;
- // calculate seconds
- $big_date = $days*24*3600 + gmmktime(date("H",$date),date("i",$date),date("s",$date),
- date("m",$date),date("d",$date),date("Y",$date));
- // multiply just to make MS happy
- $big_date *= 10000000;
-
- $high_part = floor($big_date / $factor);
- // lower 4 bytes
- $low_part = floor((($big_date / $factor) - $high_part) * $factor);
-
- // Make HEX string
- $res = '';
-
- for ($i = 0; $i < 4; ++$i) {
- $hex = $low_part % 0x100;
- $res .= pack('c', $hex);
- $low_part /= 0x100;
- }
- for ($i = 0; $i < 4; ++$i) {
- $hex = $high_part % 0x100;
- $res .= pack('c', $hex);
- $high_part /= 0x100;
- }
- return $res;
- }
-
- /**
- * Returns a timestamp from an OLE container's date
- *
- * @access public
- * @static
- * @param integer $string A binary string with the encoded date
- * @return string The timestamp corresponding to the string
- */
- public static function OLE2LocalDate($string)
- {
- if (strlen($string) != 8) {
- return new PEAR_Error("Expecting 8 byte string");
- }
-
- // factor used for separating numbers into 4 bytes parts
- $factor = pow(2,32);
- list(, $high_part) = unpack('V', substr($string, 4, 4));
- list(, $low_part) = unpack('V', substr($string, 0, 4));
-
- $big_date = ($high_part * $factor) + $low_part;
- // translate to seconds
- $big_date /= 10000000;
-
- // days from 1-1-1601 until the beggining of UNIX era
- $days = 134774;
-
- // translate to seconds from beggining of UNIX era
- $big_date -= $days * 24 * 3600;
- return floor($big_date);
- }
+ const OLE_PPS_TYPE_ROOT = 5;
+ const OLE_PPS_TYPE_DIR = 1;
+ const OLE_PPS_TYPE_FILE = 2;
+ const OLE_DATA_SIZE_SMALL = 0x1000;
+ const OLE_LONG_INT_SIZE = 4;
+ const OLE_PPS_SIZE = 0x80;
+
+ /**
+ * The file handle for reading an OLE container
+ * @var resource
+ */
+ public $_file_handle;
+
+ /**
+ * Array of PPS's found on the OLE container
+ * @var array
+ */
+ public $_list = array();
+
+ /**
+ * Root directory of OLE container
+ * @var OLE_PPS_Root
+ */
+ public $root;
+
+ /**
+ * Big Block Allocation Table
+ * @var array (blockId => nextBlockId)
+ */
+ public $bbat;
+
+ /**
+ * Short Block Allocation Table
+ * @var array (blockId => nextBlockId)
+ */
+ public $sbat;
+
+ /**
+ * Size of big blocks. This is usually 512.
+ * @var int number of octets per block.
+ */
+ public $bigBlockSize;
+
+ /**
+ * Size of small blocks. This is usually 64.
+ * @var int number of octets per block
+ */
+ public $smallBlockSize;
+
+ /**
+ * Reads an OLE container from the contents of the file given.
+ *
+ * @acces public
+ * @param string $file
+ * @return mixed true on success, PEAR_Error on failure
+ */
+ public function read($file)
+ {
+ $fh = fopen($file, "r");
+ if (!$fh) {
+ throw new PHPExcel_Reader_Exception("Can't open file $file");
+ }
+ $this->_file_handle = $fh;
+
+ $signature = fread($fh, 8);
+ if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
+ throw new PHPExcel_Reader_Exception("File doesn't seem to be an OLE container.");
+ }
+ fseek($fh, 28);
+ if (fread($fh, 2) != "\xFE\xFF") {
+ // This shouldn't be a problem in practice
+ throw new PHPExcel_Reader_Exception("Only Little-Endian encoding is supported.");
+ }
+ // Size of blocks and short blocks in bytes
+ $this->bigBlockSize = pow(2, self::_readInt2($fh));
+ $this->smallBlockSize = pow(2, self::_readInt2($fh));
+
+ // Skip UID, revision number and version number
+ fseek($fh, 44);
+ // Number of blocks in Big Block Allocation Table
+ $bbatBlockCount = self::_readInt4($fh);
+
+ // Root chain 1st block
+ $directoryFirstBlockId = self::_readInt4($fh);
+
+ // Skip unused bytes
+ fseek($fh, 56);
+ // Streams shorter than this are stored using small blocks
+ $this->bigBlockThreshold = self::_readInt4($fh);
+ // Block id of first sector in Short Block Allocation Table
+ $sbatFirstBlockId = self::_readInt4($fh);
+ // Number of blocks in Short Block Allocation Table
+ $sbbatBlockCount = self::_readInt4($fh);
+ // Block id of first sector in Master Block Allocation Table
+ $mbatFirstBlockId = self::_readInt4($fh);
+ // Number of blocks in Master Block Allocation Table
+ $mbbatBlockCount = self::_readInt4($fh);
+ $this->bbat = array();
+
+ // Remaining 4 * 109 bytes of current block is beginning of Master
+ // Block Allocation Table
+ $mbatBlocks = array();
+ for ($i = 0; $i < 109; ++$i) {
+ $mbatBlocks[] = self::_readInt4($fh);
+ }
+
+ // Read rest of Master Block Allocation Table (if any is left)
+ $pos = $this->_getBlockOffset($mbatFirstBlockId);
+ for ($i = 0; $i < $mbbatBlockCount; ++$i) {
+ fseek($fh, $pos);
+ for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
+ $mbatBlocks[] = self::_readInt4($fh);
+ }
+ // Last block id in each block points to next block
+ $pos = $this->_getBlockOffset(self::_readInt4($fh));
+ }
+
+ // Read Big Block Allocation Table according to chain specified by
+ // $mbatBlocks
+ for ($i = 0; $i < $bbatBlockCount; ++$i) {
+ $pos = $this->_getBlockOffset($mbatBlocks[$i]);
+ fseek($fh, $pos);
+ for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) {
+ $this->bbat[] = self::_readInt4($fh);
+ }
+ }
+
+ // Read short block allocation table (SBAT)
+ $this->sbat = array();
+ $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
+ $sbatFh = $this->getStream($sbatFirstBlockId);
+ for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
+ $this->sbat[$blockId] = self::_readInt4($sbatFh);
+ }
+ fclose($sbatFh);
+
+ $this->_readPpsWks($directoryFirstBlockId);
+
+ return true;
+ }
+
+ /**
+ * @param int block id
+ * @param int byte offset from beginning of file
+ * @access public
+ */
+ public function _getBlockOffset($blockId)
+ {
+ return 512 + $blockId * $this->bigBlockSize;
+ }
+
+ /**
+ * Returns a stream for use with fread() etc. External callers should
+ * use PHPExcel_Shared_OLE_PPS_File::getStream().
+ * @param int|PPS block id or PPS
+ * @return resource read-only stream
+ */
+ public function getStream($blockIdOrPps)
+ {
+ static $isRegistered = false;
+ if (!$isRegistered) {
+ stream_wrapper_register('ole-chainedblockstream', 'PHPExcel_Shared_OLE_ChainedBlockStream');
+ $isRegistered = true;
+ }
+
+ // Store current instance in global array, so that it can be accessed
+ // in OLE_ChainedBlockStream::stream_open().
+ // Object is removed from self::$instances in OLE_Stream::close().
+ $GLOBALS['_OLE_INSTANCES'][] = $this;
+ $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES']));
+
+ $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
+ if ($blockIdOrPps instanceof PHPExcel_Shared_OLE_PPS) {
+ $path .= '&blockId=' . $blockIdOrPps->_StartBlock;
+ $path .= '&size=' . $blockIdOrPps->Size;
+ } else {
+ $path .= '&blockId=' . $blockIdOrPps;
+ }
+ return fopen($path, 'r');
+ }
+
+ /**
+ * Reads a signed char.
+ * @param resource file handle
+ * @return int
+ * @access public
+ */
+ private static function _readInt1($fh)
+ {
+ list(, $tmp) = unpack("c", fread($fh, 1));
+ return $tmp;
+ }
+
+ /**
+ * Reads an unsigned short (2 octets).
+ * @param resource file handle
+ * @return int
+ * @access public
+ */
+ private static function _readInt2($fh)
+ {
+ list(, $tmp) = unpack("v", fread($fh, 2));
+ return $tmp;
+ }
+
+ /**
+ * Reads an unsigned long (4 octets).
+ * @param resource file handle
+ * @return int
+ * @access public
+ */
+ private static function _readInt4($fh)
+ {
+ list(, $tmp) = unpack("V", fread($fh, 4));
+ return $tmp;
+ }
+
+ /**
+ * Gets information about all PPS's on the OLE container from the PPS WK's
+ * creates an OLE_PPS object for each one.
+ *
+ * @access public
+ * @param integer the block id of the first block
+ * @return mixed true on success, PEAR_Error on failure
+ */
+ public function _readPpsWks($blockId)
+ {
+ $fh = $this->getStream($blockId);
+ for ($pos = 0;; $pos += 128) {
+ fseek($fh, $pos, SEEK_SET);
+ $nameUtf16 = fread($fh, 64);
+ $nameLength = self::_readInt2($fh);
+ $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
+ // Simple conversion from UTF-16LE to ISO-8859-1
+ $name = str_replace("\x00", "", $nameUtf16);
+ $type = self::_readInt1($fh);
+ switch ($type) {
+ case self::OLE_PPS_TYPE_ROOT:
+ $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array());
+ $this->root = $pps;
+ break;
+ case self::OLE_PPS_TYPE_DIR:
+ $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null, null, null, null, null, array());
+ break;
+ case self::OLE_PPS_TYPE_FILE:
+ $pps = new PHPExcel_Shared_OLE_PPS_File($name);
+ break;
+ default:
+ continue;
+ }
+ fseek($fh, 1, SEEK_CUR);
+ $pps->Type = $type;
+ $pps->Name = $name;
+ $pps->PrevPps = self::_readInt4($fh);
+ $pps->NextPps = self::_readInt4($fh);
+ $pps->DirPps = self::_readInt4($fh);
+ fseek($fh, 20, SEEK_CUR);
+ $pps->Time1st = self::OLE2LocalDate(fread($fh, 8));
+ $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8));
+ $pps->_StartBlock = self::_readInt4($fh);
+ $pps->Size = self::_readInt4($fh);
+ $pps->No = count($this->_list);
+ $this->_list[] = $pps;
+
+ // check if the PPS tree (starting from root) is complete
+ if (isset($this->root) && $this->_ppsTreeComplete($this->root->No)) {
+ break;
+ }
+ }
+ fclose($fh);
+
+ // Initialize $pps->children on directories
+ foreach ($this->_list as $pps) {
+ if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
+ $nos = array($pps->DirPps);
+ $pps->children = array();
+ while ($nos) {
+ $no = array_pop($nos);
+ if ($no != -1) {
+ $childPps = $this->_list[$no];
+ $nos[] = $childPps->PrevPps;
+ $nos[] = $childPps->NextPps;
+ $pps->children[] = $childPps;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * It checks whether the PPS tree is complete (all PPS's read)
+ * starting with the given PPS (not necessarily root)
+ *
+ * @access public
+ * @param integer $index The index of the PPS from which we are checking
+ * @return boolean Whether the PPS tree for the given PPS is complete
+ */
+ public function _ppsTreeComplete($index)
+ {
+ return isset($this->_list[$index]) &&
+ ($pps = $this->_list[$index]) &&
+ ($pps->PrevPps == -1 ||
+ $this->_ppsTreeComplete($pps->PrevPps)) &&
+ ($pps->NextPps == -1 ||
+ $this->_ppsTreeComplete($pps->NextPps)) &&
+ ($pps->DirPps == -1 ||
+ $this->_ppsTreeComplete($pps->DirPps));
+ }
+
+ /**
+ * Checks whether a PPS is a File PPS or not.
+ * If there is no PPS for the index given, it will return false.
+ *
+ * @access public
+ * @param integer $index The index for the PPS
+ * @return bool true if it's a File PPS, false otherwise
+ */
+ public function isFile($index)
+ {
+ if (isset($this->_list[$index])) {
+ return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE);
+ }
+ return false;
+ }
+
+ /**
+ * Checks whether a PPS is a Root PPS or not.
+ * If there is no PPS for the index given, it will return false.
+ *
+ * @access public
+ * @param integer $index The index for the PPS.
+ * @return bool true if it's a Root PPS, false otherwise
+ */
+ public function isRoot($index)
+ {
+ if (isset($this->_list[$index])) {
+ return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT);
+ }
+ return false;
+ }
+
+ /**
+ * Gives the total number of PPS's found in the OLE container.
+ *
+ * @access public
+ * @return integer The total number of PPS's found in the OLE container
+ */
+ public function ppsTotal()
+ {
+ return count($this->_list);
+ }
+
+ /**
+ * Gets data from a PPS
+ * If there is no PPS for the index given, it will return an empty string.
+ *
+ * @access public
+ * @param integer $index The index for the PPS
+ * @param integer $position The position from which to start reading
+ * (relative to the PPS)
+ * @param integer $length The amount of bytes to read (at most)
+ * @return string The binary string containing the data requested
+ * @see OLE_PPS_File::getStream()
+ */
+ public function getData($index, $position, $length)
+ {
+ // if position is not valid return empty string
+ if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
+ return '';
+ }
+ $fh = $this->getStream($this->_list[$index]);
+ $data = stream_get_contents($fh, $length, $position);
+ fclose($fh);
+ return $data;
+ }
+
+ /**
+ * Gets the data length from a PPS
+ * If there is no PPS for the index given, it will return 0.
+ *
+ * @access public
+ * @param integer $index The index for the PPS
+ * @return integer The amount of bytes in data the PPS has
+ */
+ public function getDataLength($index)
+ {
+ if (isset($this->_list[$index])) {
+ return $this->_list[$index]->Size;
+ }
+ return 0;
+ }
+
+ /**
+ * Utility function to transform ASCII text to Unicode
+ *
+ * @access public
+ * @static
+ * @param string $ascii The ASCII string to transform
+ * @return string The string in Unicode
+ */
+ public static function Asc2Ucs($ascii)
+ {
+ $rawname = '';
+ for ($i = 0; $i < strlen($ascii); ++$i) {
+ $rawname .= $ascii{$i} . "\x00";
+ }
+ return $rawname;
+ }
+
+ /**
+ * Utility function
+ * Returns a string for the OLE container with the date given
+ *
+ * @access public
+ * @static
+ * @param integer $date A timestamp
+ * @return string The string for the OLE container
+ */
+ public static function LocalDate2OLE($date = null)
+ {
+ if (!isset($date)) {
+ return "\x00\x00\x00\x00\x00\x00\x00\x00";
+ }
+
+ // factor used for separating numbers into 4 bytes parts
+ $factor = pow(2, 32);
+
+ // days from 1-1-1601 until the beggining of UNIX era
+ $days = 134774;
+ // calculate seconds
+ $big_date = $days*24*3600 + gmmktime(date("H", $date), date("i", $date), date("s", $date), date("m", $date), date("d", $date), date("Y", $date));
+ // multiply just to make MS happy
+ $big_date *= 10000000;
+
+ $high_part = floor($big_date / $factor);
+ // lower 4 bytes
+ $low_part = floor((($big_date / $factor) - $high_part) * $factor);
+
+ // Make HEX string
+ $res = '';
+
+ for ($i = 0; $i < 4; ++$i) {
+ $hex = $low_part % 0x100;
+ $res .= pack('c', $hex);
+ $low_part /= 0x100;
+ }
+ for ($i = 0; $i < 4; ++$i) {
+ $hex = $high_part % 0x100;
+ $res .= pack('c', $hex);
+ $high_part /= 0x100;
+ }
+ return $res;
+ }
+
+ /**
+ * Returns a timestamp from an OLE container's date
+ *
+ * @access public
+ * @static
+ * @param integer $string A binary string with the encoded date
+ * @return string The timestamp corresponding to the string
+ */
+ public static function OLE2LocalDate($string)
+ {
+ if (strlen($string) != 8) {
+ return new PEAR_Error("Expecting 8 byte string");
+ }
+
+ // factor used for separating numbers into 4 bytes parts
+ $factor = pow(2, 32);
+ list(, $high_part) = unpack('V', substr($string, 4, 4));
+ list(, $low_part) = unpack('V', substr($string, 0, 4));
+
+ $big_date = ($high_part * $factor) + $low_part;
+ // translate to seconds
+ $big_date /= 10000000;
+
+ // days from 1-1-1601 until the beggining of UNIX era
+ $days = 134774;
+
+ // translate to seconds from beggining of UNIX era
+ $big_date -= $days * 24 * 3600;
+ return floor($big_date);
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php b/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php
index 77b8ff8a2..84d2cc50b 100644
--- a/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php
+++ b/Classes/PHPExcel/Shared/OLE/ChainedBlockStream.php
@@ -1,8 +1,9 @@
params);
- if (!isset($this->params['oleInstanceId'],
- $this->params['blockId'],
- $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) {
-
- if ($options & STREAM_REPORT_ERRORS) {
- trigger_error('OLE stream not found', E_USER_WARNING);
- }
- return false;
- }
- $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']];
-
- $blockId = $this->params['blockId'];
- $this->data = '';
- if (isset($this->params['size']) &&
- $this->params['size'] < $this->ole->bigBlockThreshold &&
- $blockId != $this->ole->root->_StartBlock) {
-
- // Block id refers to small blocks
- $rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock);
- while ($blockId != -2) {
- $pos = $rootPos + $blockId * $this->ole->bigBlockSize;
- $blockId = $this->ole->sbat[$blockId];
- fseek($this->ole->_file_handle, $pos);
- $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
- }
- } else {
- // Block id refers to big blocks
- while ($blockId != -2) {
- $pos = $this->ole->_getBlockOffset($blockId);
- fseek($this->ole->_file_handle, $pos);
- $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
- $blockId = $this->ole->bbat[$blockId];
- }
- }
- if (isset($this->params['size'])) {
- $this->data = substr($this->data, 0, $this->params['size']);
- }
-
- if ($options & STREAM_USE_PATH) {
- $openedPath = $path;
- }
-
- return true;
- }
-
- /**
- * Implements support for fclose().
- *
- */
- public function stream_close()
- {
- $this->ole = null;
- unset($GLOBALS['_OLE_INSTANCES']);
- }
-
- /**
- * Implements support for fread(), fgets() etc.
- *
- * @param int $count maximum number of bytes to read
- * @return string
- */
- public function stream_read($count)
- {
- if ($this->stream_eof()) {
- return false;
- }
- $s = substr($this->data, $this->pos, $count);
- $this->pos += $count;
- return $s;
- }
-
- /**
- * Implements support for feof().
- *
- * @return bool TRUE if the file pointer is at EOF; otherwise FALSE
- */
- public function stream_eof()
- {
- $eof = $this->pos >= strlen($this->data);
- // Workaround for bug in PHP 5.0.x: http://bugs.php.net/27508
- if (version_compare(PHP_VERSION, '5.0', '>=') &&
- version_compare(PHP_VERSION, '5.1', '<')) {
-
- $eof = !$eof;
- }
- return $eof;
- }
-
- /**
- * Returns the position of the file pointer, i.e. its offset into the file
- * stream. Implements support for ftell().
- *
- * @return int
- */
- public function stream_tell()
- {
- return $this->pos;
- }
-
- /**
- * Implements support for fseek().
- *
- * @param int $offset byte offset
- * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END
- * @return bool
- */
- public function stream_seek($offset, $whence)
- {
- if ($whence == SEEK_SET && $offset >= 0) {
- $this->pos = $offset;
- } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) {
- $this->pos += $offset;
- } elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) {
- $this->pos = strlen($this->data) + $offset;
- } else {
- return false;
- }
- return true;
- }
-
- /**
- * Implements support for fstat(). Currently the only supported field is
- * "size".
- * @return array
- */
- public function stream_stat()
- {
- return array(
- 'size' => strlen($this->data),
- );
- }
-
- // Methods used by stream_wrapper_register() that are not implemented:
- // bool stream_flush ( void )
- // int stream_write ( string data )
- // bool rename ( string path_from, string path_to )
- // bool mkdir ( string path, int mode, int options )
- // bool rmdir ( string path, int options )
- // bool dir_opendir ( string path, int options )
- // array url_stat ( string path, int flags )
- // string dir_readdir ( void )
- // bool dir_rewinddir ( void )
- // bool dir_closedir ( void )
+ /**
+ * The OLE container of the file that is being read.
+ * @var OLE
+ */
+ public $ole;
+
+ /**
+ * Parameters specified by fopen().
+ * @var array
+ */
+ public $params;
+
+ /**
+ * The binary data of the file.
+ * @var string
+ */
+ public $data;
+
+ /**
+ * The file pointer.
+ * @var int byte offset
+ */
+ public $pos;
+
+ /**
+ * Implements support for fopen().
+ * For creating streams using this wrapper, use OLE_PPS_File::getStream().
+ *
+ * @param string $path resource name including scheme, e.g.
+ * ole-chainedblockstream://oleInstanceId=1
+ * @param string $mode only "r" is supported
+ * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH
+ * @param string &$openedPath absolute path of the opened stream (out parameter)
+ * @return bool true on success
+ */
+ public function stream_open($path, $mode, $options, &$openedPath)
+ {
+ if ($mode != 'r') {
+ if ($options & STREAM_REPORT_ERRORS) {
+ trigger_error('Only reading is supported', E_USER_WARNING);
+ }
+ return false;
+ }
+
+ // 25 is length of "ole-chainedblockstream://"
+ parse_str(substr($path, 25), $this->params);
+ if (!isset($this->params['oleInstanceId'], $this->params['blockId'], $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) {
+ if ($options & STREAM_REPORT_ERRORS) {
+ trigger_error('OLE stream not found', E_USER_WARNING);
+ }
+ return false;
+ }
+ $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']];
+
+ $blockId = $this->params['blockId'];
+ $this->data = '';
+ if (isset($this->params['size']) && $this->params['size'] < $this->ole->bigBlockThreshold && $blockId != $this->ole->root->_StartBlock) {
+ // Block id refers to small blocks
+ $rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock);
+ while ($blockId != -2) {
+ $pos = $rootPos + $blockId * $this->ole->bigBlockSize;
+ $blockId = $this->ole->sbat[$blockId];
+ fseek($this->ole->_file_handle, $pos);
+ $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
+ }
+ } else {
+ // Block id refers to big blocks
+ while ($blockId != -2) {
+ $pos = $this->ole->_getBlockOffset($blockId);
+ fseek($this->ole->_file_handle, $pos);
+ $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
+ $blockId = $this->ole->bbat[$blockId];
+ }
+ }
+ if (isset($this->params['size'])) {
+ $this->data = substr($this->data, 0, $this->params['size']);
+ }
+
+ if ($options & STREAM_USE_PATH) {
+ $openedPath = $path;
+ }
+
+ return true;
+ }
+
+ /**
+ * Implements support for fclose().
+ *
+ */
+ public function stream_close()
+ {
+ $this->ole = null;
+ unset($GLOBALS['_OLE_INSTANCES']);
+ }
+
+ /**
+ * Implements support for fread(), fgets() etc.
+ *
+ * @param int $count maximum number of bytes to read
+ * @return string
+ */
+ public function stream_read($count)
+ {
+ if ($this->stream_eof()) {
+ return false;
+ }
+ $s = substr($this->data, $this->pos, $count);
+ $this->pos += $count;
+ return $s;
+ }
+
+ /**
+ * Implements support for feof().
+ *
+ * @return bool TRUE if the file pointer is at EOF; otherwise FALSE
+ */
+ public function stream_eof()
+ {
+ return $this->pos >= strlen($this->data);
+ }
+
+ /**
+ * Returns the position of the file pointer, i.e. its offset into the file
+ * stream. Implements support for ftell().
+ *
+ * @return int
+ */
+ public function stream_tell()
+ {
+ return $this->pos;
+ }
+
+ /**
+ * Implements support for fseek().
+ *
+ * @param int $offset byte offset
+ * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END
+ * @return bool
+ */
+ public function stream_seek($offset, $whence)
+ {
+ if ($whence == SEEK_SET && $offset >= 0) {
+ $this->pos = $offset;
+ } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) {
+ $this->pos += $offset;
+ } elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) {
+ $this->pos = strlen($this->data) + $offset;
+ } else {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Implements support for fstat(). Currently the only supported field is
+ * "size".
+ * @return array
+ */
+ public function stream_stat()
+ {
+ return array(
+ 'size' => strlen($this->data),
+ );
+ }
+
+ // Methods used by stream_wrapper_register() that are not implemented:
+ // bool stream_flush ( void )
+ // int stream_write ( string data )
+ // bool rename ( string path_from, string path_to )
+ // bool mkdir ( string path, int mode, int options )
+ // bool rmdir ( string path, int options )
+ // bool dir_opendir ( string path, int options )
+ // array url_stat ( string path, int flags )
+ // string dir_readdir ( void )
+ // bool dir_rewinddir ( void )
+ // bool dir_closedir ( void )
}
diff --git a/Classes/PHPExcel/Shared/OLE/PPS.php b/Classes/PHPExcel/Shared/OLE/PPS.php
index 4db0ae4e2..608a892aa 100644
--- a/Classes/PHPExcel/Shared/OLE/PPS.php
+++ b/Classes/PHPExcel/Shared/OLE/PPS.php
@@ -29,202 +29,202 @@
*/
class PHPExcel_Shared_OLE_PPS
{
- /**
- * The PPS index
- * @var integer
- */
- public $No;
-
- /**
- * The PPS name (in Unicode)
- * @var string
- */
- public $Name;
-
- /**
- * The PPS type. Dir, Root or File
- * @var integer
- */
- public $Type;
-
- /**
- * The index of the previous PPS
- * @var integer
- */
- public $PrevPps;
-
- /**
- * The index of the next PPS
- * @var integer
- */
- public $NextPps;
-
- /**
- * The index of it's first child if this is a Dir or Root PPS
- * @var integer
- */
- public $DirPps;
-
- /**
- * A timestamp
- * @var integer
- */
- public $Time1st;
-
- /**
- * A timestamp
- * @var integer
- */
- public $Time2nd;
-
- /**
- * Starting block (small or big) for this PPS's data inside the container
- * @var integer
- */
- public $_StartBlock;
-
- /**
- * The size of the PPS's data (in bytes)
- * @var integer
- */
- public $Size;
-
- /**
- * The PPS's data (only used if it's not using a temporary file)
- * @var string
- */
- public $_data;
-
- /**
- * Array of child PPS's (only used by Root and Dir PPS's)
- * @var array
- */
- public $children = array();
-
- /**
- * Pointer to OLE container
- * @var OLE
- */
- public $ole;
-
- /**
- * The constructor
- *
- * @access public
- * @param integer $No The PPS index
- * @param string $name The PPS name
- * @param integer $type The PPS type. Dir, Root or File
- * @param integer $prev The index of the previous PPS
- * @param integer $next The index of the next PPS
- * @param integer $dir The index of it's first child if this is a Dir or Root PPS
- * @param integer $time_1st A timestamp
- * @param integer $time_2nd A timestamp
- * @param string $data The (usually binary) source data of the PPS
- * @param array $children Array containing children PPS for this PPS
- */
- public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children)
- {
- $this->No = $No;
- $this->Name = $name;
- $this->Type = $type;
- $this->PrevPps = $prev;
- $this->NextPps = $next;
- $this->DirPps = $dir;
- $this->Time1st = $time_1st;
- $this->Time2nd = $time_2nd;
- $this->_data = $data;
- $this->children = $children;
- if ($data != '') {
- $this->Size = strlen($data);
- } else {
- $this->Size = 0;
- }
- }
-
- /**
- * Returns the amount of data saved for this PPS
- *
- * @access public
- * @return integer The amount of data (in bytes)
- */
- public function _DataLen()
- {
- if (!isset($this->_data)) {
- return 0;
- }
- //if (isset($this->_PPS_FILE)) {
- // fseek($this->_PPS_FILE, 0);
- // $stats = fstat($this->_PPS_FILE);
- // return $stats[7];
- //} else {
- return strlen($this->_data);
- //}
- }
-
- /**
- * Returns a string with the PPS's WK (What is a WK?)
- *
- * @access public
- * @return string The binary string
- */
- public function _getPpsWk()
- {
- $ret = str_pad($this->Name,64,"\x00");
-
- $ret .= pack("v", strlen($this->Name) + 2) // 66
- . pack("c", $this->Type) // 67
- . pack("c", 0x00) //UK // 68
- . pack("V", $this->PrevPps) //Prev // 72
- . pack("V", $this->NextPps) //Next // 76
- . pack("V", $this->DirPps) //Dir // 80
- . "\x00\x09\x02\x00" // 84
- . "\x00\x00\x00\x00" // 88
- . "\xc0\x00\x00\x00" // 92
- . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root
- . "\x00\x00\x00\x00" // 100
- . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time1st) // 108
- . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time2nd) // 116
- . pack("V", isset($this->_StartBlock)?
- $this->_StartBlock:0) // 120
- . pack("V", $this->Size) // 124
- . pack("V", 0); // 128
- return $ret;
- }
-
- /**
- * Updates index and pointers to previous, next and children PPS's for this
- * PPS. I don't think it'll work with Dir PPS's.
- *
- * @access public
- * @param array &$raList Reference to the array of PPS's for the whole OLE
- * container
- * @return integer The index for this PPS
- */
- public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0)
- {
- if ( !is_array($to_save) || (empty($to_save)) ) {
- return 0xFFFFFFFF;
- } elseif( count($to_save) == 1 ) {
- $cnt = count($raList);
- // If the first entry, it's the root... Don't clone it!
- $raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0];
- $raList[$cnt]->No = $cnt;
- $raList[$cnt]->PrevPps = 0xFFFFFFFF;
- $raList[$cnt]->NextPps = 0xFFFFFFFF;
- $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
- } else {
- $iPos = floor(count($to_save) / 2);
- $aPrev = array_slice($to_save, 0, $iPos);
- $aNext = array_slice($to_save, $iPos + 1);
- $cnt = count($raList);
- // If the first entry, it's the root... Don't clone it!
- $raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos];
- $raList[$cnt]->No = $cnt;
- $raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++);
- $raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++);
- $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
-
- }
- return $cnt;
- }
+ /**
+ * The PPS index
+ * @var integer
+ */
+ public $No;
+
+ /**
+ * The PPS name (in Unicode)
+ * @var string
+ */
+ public $Name;
+
+ /**
+ * The PPS type. Dir, Root or File
+ * @var integer
+ */
+ public $Type;
+
+ /**
+ * The index of the previous PPS
+ * @var integer
+ */
+ public $PrevPps;
+
+ /**
+ * The index of the next PPS
+ * @var integer
+ */
+ public $NextPps;
+
+ /**
+ * The index of it's first child if this is a Dir or Root PPS
+ * @var integer
+ */
+ public $DirPps;
+
+ /**
+ * A timestamp
+ * @var integer
+ */
+ public $Time1st;
+
+ /**
+ * A timestamp
+ * @var integer
+ */
+ public $Time2nd;
+
+ /**
+ * Starting block (small or big) for this PPS's data inside the container
+ * @var integer
+ */
+ public $_StartBlock;
+
+ /**
+ * The size of the PPS's data (in bytes)
+ * @var integer
+ */
+ public $Size;
+
+ /**
+ * The PPS's data (only used if it's not using a temporary file)
+ * @var string
+ */
+ public $_data;
+
+ /**
+ * Array of child PPS's (only used by Root and Dir PPS's)
+ * @var array
+ */
+ public $children = array();
+
+ /**
+ * Pointer to OLE container
+ * @var OLE
+ */
+ public $ole;
+
+ /**
+ * The constructor
+ *
+ * @access public
+ * @param integer $No The PPS index
+ * @param string $name The PPS name
+ * @param integer $type The PPS type. Dir, Root or File
+ * @param integer $prev The index of the previous PPS
+ * @param integer $next The index of the next PPS
+ * @param integer $dir The index of it's first child if this is a Dir or Root PPS
+ * @param integer $time_1st A timestamp
+ * @param integer $time_2nd A timestamp
+ * @param string $data The (usually binary) source data of the PPS
+ * @param array $children Array containing children PPS for this PPS
+ */
+ public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children)
+ {
+ $this->No = $No;
+ $this->Name = $name;
+ $this->Type = $type;
+ $this->PrevPps = $prev;
+ $this->NextPps = $next;
+ $this->DirPps = $dir;
+ $this->Time1st = $time_1st;
+ $this->Time2nd = $time_2nd;
+ $this->_data = $data;
+ $this->children = $children;
+ if ($data != '') {
+ $this->Size = strlen($data);
+ } else {
+ $this->Size = 0;
+ }
+ }
+
+ /**
+ * Returns the amount of data saved for this PPS
+ *
+ * @access public
+ * @return integer The amount of data (in bytes)
+ */
+ public function _DataLen()
+ {
+ if (!isset($this->_data)) {
+ return 0;
+ }
+ //if (isset($this->_PPS_FILE)) {
+ // fseek($this->_PPS_FILE, 0);
+ // $stats = fstat($this->_PPS_FILE);
+ // return $stats[7];
+ //} else {
+ return strlen($this->_data);
+ //}
+ }
+
+ /**
+ * Returns a string with the PPS's WK (What is a WK?)
+ *
+ * @access public
+ * @return string The binary string
+ */
+ public function _getPpsWk()
+ {
+ $ret = str_pad($this->Name, 64, "\x00");
+
+ $ret .= pack("v", strlen($this->Name) + 2) // 66
+ . pack("c", $this->Type) // 67
+ . pack("c", 0x00) //UK // 68
+ . pack("V", $this->PrevPps) //Prev // 72
+ . pack("V", $this->NextPps) //Next // 76
+ . pack("V", $this->DirPps) //Dir // 80
+ . "\x00\x09\x02\x00" // 84
+ . "\x00\x00\x00\x00" // 88
+ . "\xc0\x00\x00\x00" // 92
+ . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root
+ . "\x00\x00\x00\x00" // 100
+ . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time1st) // 108
+ . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time2nd) // 116
+ . pack("V", isset($this->_StartBlock)?
+ $this->_StartBlock:0) // 120
+ . pack("V", $this->Size) // 124
+ . pack("V", 0); // 128
+ return $ret;
+ }
+
+ /**
+ * Updates index and pointers to previous, next and children PPS's for this
+ * PPS. I don't think it'll work with Dir PPS's.
+ *
+ * @access public
+ * @param array &$raList Reference to the array of PPS's for the whole OLE
+ * container
+ * @return integer The index for this PPS
+ */
+ public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0)
+ {
+ if (!is_array($to_save) || (empty($to_save))) {
+ return 0xFFFFFFFF;
+ } elseif (count($to_save) == 1) {
+ $cnt = count($raList);
+ // If the first entry, it's the root... Don't clone it!
+ $raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0];
+ $raList[$cnt]->No = $cnt;
+ $raList[$cnt]->PrevPps = 0xFFFFFFFF;
+ $raList[$cnt]->NextPps = 0xFFFFFFFF;
+ $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
+ } else {
+ $iPos = floor(count($to_save) / 2);
+ $aPrev = array_slice($to_save, 0, $iPos);
+ $aNext = array_slice($to_save, $iPos + 1);
+ $cnt = count($raList);
+ // If the first entry, it's the root... Don't clone it!
+ $raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos];
+ $raList[$cnt]->No = $cnt;
+ $raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++);
+ $raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++);
+ $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
+
+ }
+ return $cnt;
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLE/PPS/File.php b/Classes/PHPExcel/Shared/OLE/PPS/File.php
index f061f568c..1ca337cba 100644
--- a/Classes/PHPExcel/Shared/OLE/PPS/File.php
+++ b/Classes/PHPExcel/Shared/OLE/PPS/File.php
@@ -28,57 +28,47 @@
* @package PHPExcel_Shared_OLE
*/
class PHPExcel_Shared_OLE_PPS_File extends PHPExcel_Shared_OLE_PPS
- {
- /**
- * The constructor
- *
- * @access public
- * @param string $name The name of the file (in Unicode)
- * @see OLE::Asc2Ucs()
- */
- public function __construct($name)
- {
- parent::__construct(
- null,
- $name,
- PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE,
- null,
- null,
- null,
- null,
- null,
- '',
- array());
- }
+{
+ /**
+ * The constructor
+ *
+ * @access public
+ * @param string $name The name of the file (in Unicode)
+ * @see OLE::Asc2Ucs()
+ */
+ public function __construct($name)
+ {
+ parent::__construct(null, $name, PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', array());
+ }
- /**
- * Initialization method. Has to be called right after OLE_PPS_File().
- *
- * @access public
- * @return mixed true on success
- */
- public function init()
- {
- return true;
- }
+ /**
+ * Initialization method. Has to be called right after OLE_PPS_File().
+ *
+ * @access public
+ * @return mixed true on success
+ */
+ public function init()
+ {
+ return true;
+ }
- /**
- * Append data to PPS
- *
- * @access public
- * @param string $data The data to append
- */
- public function append($data)
- {
- $this->_data .= $data;
- }
+ /**
+ * Append data to PPS
+ *
+ * @access public
+ * @param string $data The data to append
+ */
+ public function append($data)
+ {
+ $this->_data .= $data;
+ }
- /**
- * Returns a stream for reading this file using fread() etc.
- * @return resource a read-only stream
- */
- public function getStream()
- {
- $this->ole->getStream($this);
- }
+ /**
+ * Returns a stream for reading this file using fread() etc.
+ * @return resource a read-only stream
+ */
+ public function getStream()
+ {
+ $this->ole->getStream($this);
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLE/PPS/Root.php b/Classes/PHPExcel/Shared/OLE/PPS/Root.php
index eb929d205..5d4052f06 100644
--- a/Classes/PHPExcel/Shared/OLE/PPS/Root.php
+++ b/Classes/PHPExcel/Shared/OLE/PPS/Root.php
@@ -28,440 +28,435 @@
* @package PHPExcel_Shared_OLE
*/
class PHPExcel_Shared_OLE_PPS_Root extends PHPExcel_Shared_OLE_PPS
- {
+{
- /**
- * Directory for temporary files
- * @var string
- */
- protected $_tmp_dir = NULL;
+ /**
+ * Directory for temporary files
+ * @var string
+ */
+ protected $tempDirectory = null;
- /**
- * @param integer $time_1st A timestamp
- * @param integer $time_2nd A timestamp
- */
- public function __construct($time_1st, $time_2nd, $raChild)
- {
- $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir();
+ /**
+ * @param integer $time_1st A timestamp
+ * @param integer $time_2nd A timestamp
+ */
+ public function __construct($time_1st, $time_2nd, $raChild)
+ {
+ $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir();
- parent::__construct(
- null,
- PHPExcel_Shared_OLE::Asc2Ucs('Root Entry'),
- PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT,
- null,
- null,
- null,
- $time_1st,
- $time_2nd,
- null,
- $raChild);
- }
+ parent::__construct(null, PHPExcel_Shared_OLE::Asc2Ucs('Root Entry'), PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT, null, null, null, $time_1st, $time_2nd, null, $raChild);
+ }
- /**
- * Method for saving the whole OLE container (including files).
- * In fact, if called with an empty argument (or '-'), it saves to a
- * temporary file and then outputs it's contents to stdout.
- * If a resource pointer to a stream created by fopen() is passed
- * it will be used, but you have to close such stream by yourself.
- *
- * @param string|resource $filename The name of the file or stream where to save the OLE container.
- * @access public
- * @return mixed true on success
- */
- public function save($filename)
- {
- // Initial Setting for saving
- $this->_BIG_BLOCK_SIZE = pow(2,
- ((isset($this->_BIG_BLOCK_SIZE))? self::_adjust2($this->_BIG_BLOCK_SIZE) : 9));
- $this->_SMALL_BLOCK_SIZE= pow(2,
- ((isset($this->_SMALL_BLOCK_SIZE))? self::_adjust2($this->_SMALL_BLOCK_SIZE): 6));
+ /**
+ * Method for saving the whole OLE container (including files).
+ * In fact, if called with an empty argument (or '-'), it saves to a
+ * temporary file and then outputs it's contents to stdout.
+ * If a resource pointer to a stream created by fopen() is passed
+ * it will be used, but you have to close such stream by yourself.
+ *
+ * @param string|resource $filename The name of the file or stream where to save the OLE container.
+ * @access public
+ * @return mixed true on success
+ */
+ public function save($filename)
+ {
+ // Initial Setting for saving
+ $this->_BIG_BLOCK_SIZE = pow(
+ 2,
+ (isset($this->_BIG_BLOCK_SIZE))? self::adjust2($this->_BIG_BLOCK_SIZE) : 9
+ );
+ $this->_SMALL_BLOCK_SIZE= pow(
+ 2,
+ (isset($this->_SMALL_BLOCK_SIZE))? self::adjust2($this->_SMALL_BLOCK_SIZE) : 6
+ );
- if (is_resource($filename)) {
- $this->_FILEH_ = $filename;
- } else if ($filename == '-' || $filename == '') {
- if ($this->_tmp_dir === NULL)
- $this->_tmp_dir = PHPExcel_Shared_File::sys_get_temp_dir();
- $this->_tmp_filename = tempnam($this->_tmp_dir, "OLE_PPS_Root");
- $this->_FILEH_ = fopen($this->_tmp_filename,"w+b");
- if ($this->_FILEH_ == false) {
- throw new PHPExcel_Writer_Exception("Can't create temporary file.");
- }
- } else {
- $this->_FILEH_ = fopen($filename, "wb");
- }
- if ($this->_FILEH_ == false) {
- throw new PHPExcel_Writer_Exception("Can't open $filename. It may be in use or protected.");
- }
- // Make an array of PPS's (for Save)
- $aList = array();
- PHPExcel_Shared_OLE_PPS::_savePpsSetPnt($aList, array($this));
- // calculate values for header
- list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo);
- // Save Header
- $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt);
+ if (is_resource($filename)) {
+ $this->_FILEH_ = $filename;
+ } elseif ($filename == '-' || $filename == '') {
+ if ($this->tempDirectory === null) {
+ $this->tempDirectory = PHPExcel_Shared_File::sys_get_temp_dir();
+ }
+ $this->_tmp_filename = tempnam($this->tempDirectory, "OLE_PPS_Root");
+ $this->_FILEH_ = fopen($this->_tmp_filename, "w+b");
+ if ($this->_FILEH_ == false) {
+ throw new PHPExcel_Writer_Exception("Can't create temporary file.");
+ }
+ } else {
+ $this->_FILEH_ = fopen($filename, "wb");
+ }
+ if ($this->_FILEH_ == false) {
+ throw new PHPExcel_Writer_Exception("Can't open $filename. It may be in use or protected.");
+ }
+ // Make an array of PPS's (for Save)
+ $aList = array();
+ PHPExcel_Shared_OLE_PPS::_savePpsSetPnt($aList, array($this));
+ // calculate values for header
+ list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo);
+ // Save Header
+ $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt);
- // Make Small Data string (write SBD)
- $this->_data = $this->_makeSmallData($aList);
+ // Make Small Data string (write SBD)
+ $this->_data = $this->_makeSmallData($aList);
- // Write BB
- $this->_saveBigData($iSBDcnt, $aList);
- // Write PPS
- $this->_savePps($aList);
- // Write Big Block Depot and BDList and Adding Header informations
- $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt);
+ // Write BB
+ $this->_saveBigData($iSBDcnt, $aList);
+ // Write PPS
+ $this->_savePps($aList);
+ // Write Big Block Depot and BDList and Adding Header informations
+ $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt);
- if (!is_resource($filename)) {
- fclose($this->_FILEH_);
- }
+ if (!is_resource($filename)) {
+ fclose($this->_FILEH_);
+ }
- return true;
- }
+ return true;
+ }
- /**
- * Calculate some numbers
- *
- * @access public
- * @param array $raList Reference to an array of PPS's
- * @return array The array of numbers
- */
- public function _calcSize(&$raList)
- {
- // Calculate Basic Setting
- list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0);
- $iSmallLen = 0;
- $iSBcnt = 0;
- $iCount = count($raList);
- for ($i = 0; $i < $iCount; ++$i) {
- if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) {
- $raList[$i]->Size = $raList[$i]->_DataLen();
- if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) {
- $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
- + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
- } else {
- $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
- (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
- }
- }
- }
- $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE;
- $iSlCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE);
- $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0);
- $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) +
- (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0));
- $iCnt = count($raList);
- $iBdCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE;
- $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0));
+ /**
+ * Calculate some numbers
+ *
+ * @access public
+ * @param array $raList Reference to an array of PPS's
+ * @return array The array of numbers
+ */
+ public function _calcSize(&$raList)
+ {
+ // Calculate Basic Setting
+ list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0);
+ $iSmallLen = 0;
+ $iSBcnt = 0;
+ $iCount = count($raList);
+ for ($i = 0; $i < $iCount; ++$i) {
+ if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) {
+ $raList[$i]->Size = $raList[$i]->_DataLen();
+ if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) {
+ $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
+ + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
+ } else {
+ $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
+ (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
+ }
+ }
+ }
+ $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE;
+ $iSlCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE);
+ $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0);
+ $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) +
+ (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0));
+ $iCnt = count($raList);
+ $iBdCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE;
+ $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0));
- return array($iSBDcnt, $iBBcnt, $iPPScnt);
- }
+ return array($iSBDcnt, $iBBcnt, $iPPScnt);
+ }
- /**
- * Helper function for caculating a magic value for block sizes
- *
- * @access public
- * @param integer $i2 The argument
- * @see save()
- * @return integer
- */
- private static function _adjust2($i2)
- {
- $iWk = log($i2)/log(2);
- return ($iWk > floor($iWk))? floor($iWk)+1:$iWk;
- }
+ /**
+ * Helper function for caculating a magic value for block sizes
+ *
+ * @access public
+ * @param integer $i2 The argument
+ * @see save()
+ * @return integer
+ */
+ private static function adjust2($i2)
+ {
+ $iWk = log($i2)/log(2);
+ return ($iWk > floor($iWk))? floor($iWk)+1:$iWk;
+ }
- /**
- * Save OLE header
- *
- * @access public
- * @param integer $iSBDcnt
- * @param integer $iBBcnt
- * @param integer $iPPScnt
- */
- public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt)
- {
- $FILE = $this->_FILEH_;
+ /**
+ * Save OLE header
+ *
+ * @access public
+ * @param integer $iSBDcnt
+ * @param integer $iBBcnt
+ * @param integer $iPPScnt
+ */
+ public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt)
+ {
+ $FILE = $this->_FILEH_;
- // Calculate Basic Setting
- $iBlCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
- $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
+ // Calculate Basic Setting
+ $iBlCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
+ $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
- $iBdExL = 0;
- $iAll = $iBBcnt + $iPPScnt + $iSBDcnt;
- $iAllW = $iAll;
- $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
- $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
+ $iBdExL = 0;
+ $iAll = $iBBcnt + $iPPScnt + $iSBDcnt;
+ $iAllW = $iAll;
+ $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
+ $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
- // Calculate BD count
- if ($iBdCnt > $i1stBdL) {
- while (1) {
- ++$iBdExL;
- ++$iAllW;
- $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
- $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
- if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) {
- break;
- }
- }
- }
+ // Calculate BD count
+ if ($iBdCnt > $i1stBdL) {
+ while (1) {
+ ++$iBdExL;
+ ++$iAllW;
+ $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);
+ $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);
+ if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) {
+ break;
+ }
+ }
+ }
- // Save Header
- fwrite($FILE,
- "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . pack("v", 0x3b)
- . pack("v", 0x03)
- . pack("v", -2)
- . pack("v", 9)
- . pack("v", 6)
- . pack("v", 0)
- . "\x00\x00\x00\x00"
- . "\x00\x00\x00\x00"
- . pack("V", $iBdCnt)
- . pack("V", $iBBcnt+$iSBDcnt) //ROOT START
- . pack("V", 0)
- . pack("V", 0x1000)
- . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot
- . pack("V", $iSBDcnt)
- );
- // Extra BDList Start, Count
- if ($iBdCnt < $i1stBdL) {
- fwrite($FILE,
- pack("V", -2) // Extra BDList Start
- . pack("V", 0) // Extra BDList Count
- );
- } else {
- fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL));
- }
+ // Save Header
+ fwrite(
+ $FILE,
+ "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . pack("v", 0x3b)
+ . pack("v", 0x03)
+ . pack("v", -2)
+ . pack("v", 9)
+ . pack("v", 6)
+ . pack("v", 0)
+ . "\x00\x00\x00\x00"
+ . "\x00\x00\x00\x00"
+ . pack("V", $iBdCnt)
+ . pack("V", $iBBcnt+$iSBDcnt) //ROOT START
+ . pack("V", 0)
+ . pack("V", 0x1000)
+ . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot
+ . pack("V", $iSBDcnt)
+ );
+ // Extra BDList Start, Count
+ if ($iBdCnt < $i1stBdL) {
+ fwrite(
+ $FILE,
+ pack("V", -2) // Extra BDList Start
+ . pack("V", 0)// Extra BDList Count
+ );
+ } else {
+ fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL));
+ }
- // BDList
- for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) {
- fwrite($FILE, pack("V", $iAll+$i));
- }
- if ($i < $i1stBdL) {
- $jB = $i1stBdL - $i;
- for ($j = 0; $j < $jB; ++$j) {
- fwrite($FILE, (pack("V", -1)));
- }
- }
- }
+ // BDList
+ for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) {
+ fwrite($FILE, pack("V", $iAll+$i));
+ }
+ if ($i < $i1stBdL) {
+ $jB = $i1stBdL - $i;
+ for ($j = 0; $j < $jB; ++$j) {
+ fwrite($FILE, (pack("V", -1)));
+ }
+ }
+ }
- /**
- * Saving big data (PPS's with data bigger than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL)
- *
- * @access public
- * @param integer $iStBlk
- * @param array &$raList Reference to array of PPS's
- */
- public function _saveBigData($iStBlk, &$raList)
- {
- $FILE = $this->_FILEH_;
+ /**
+ * Saving big data (PPS's with data bigger than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL)
+ *
+ * @access public
+ * @param integer $iStBlk
+ * @param array &$raList Reference to array of PPS's
+ */
+ public function _saveBigData($iStBlk, &$raList)
+ {
+ $FILE = $this->_FILEH_;
- // cycle through PPS's
- $iCount = count($raList);
- for ($i = 0; $i < $iCount; ++$i) {
- if ($raList[$i]->Type != PHPExcel_Shared_OLE::OLE_PPS_TYPE_DIR) {
- $raList[$i]->Size = $raList[$i]->_DataLen();
- if (($raList[$i]->Size >= PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) ||
- (($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data)))
- {
- // Write Data
- //if (isset($raList[$i]->_PPS_FILE)) {
- // $iLen = 0;
- // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
- // while($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
- // $iLen += strlen($sBuff);
- // fwrite($FILE, $sBuff);
- // }
- //} else {
- fwrite($FILE, $raList[$i]->_data);
- //}
+ // cycle through PPS's
+ $iCount = count($raList);
+ for ($i = 0; $i < $iCount; ++$i) {
+ if ($raList[$i]->Type != PHPExcel_Shared_OLE::OLE_PPS_TYPE_DIR) {
+ $raList[$i]->Size = $raList[$i]->_DataLen();
+ if (($raList[$i]->Size >= PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) || (($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data))) {
+ // Write Data
+ //if (isset($raList[$i]->_PPS_FILE)) {
+ // $iLen = 0;
+ // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
+ // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
+ // $iLen += strlen($sBuff);
+ // fwrite($FILE, $sBuff);
+ // }
+ //} else {
+ fwrite($FILE, $raList[$i]->_data);
+ //}
- if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) {
- fwrite($FILE, str_repeat("\x00", $this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)));
- }
- // Set For PPS
- $raList[$i]->_StartBlock = $iStBlk;
- $iStBlk +=
- (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
- (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
- }
- // Close file for each PPS, and unlink it
- //if (isset($raList[$i]->_PPS_FILE)) {
- // fclose($raList[$i]->_PPS_FILE);
- // $raList[$i]->_PPS_FILE = null;
- // unlink($raList[$i]->_tmp_filename);
- //}
- }
- }
- }
+ if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) {
+ fwrite($FILE, str_repeat("\x00", $this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)));
+ }
+ // Set For PPS
+ $raList[$i]->_StartBlock = $iStBlk;
+ $iStBlk +=
+ (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
+ (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
+ }
+ // Close file for each PPS, and unlink it
+ //if (isset($raList[$i]->_PPS_FILE)) {
+ // fclose($raList[$i]->_PPS_FILE);
+ // $raList[$i]->_PPS_FILE = null;
+ // unlink($raList[$i]->_tmp_filename);
+ //}
+ }
+ }
+ }
- /**
- * get small data (PPS's with data smaller than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL)
- *
- * @access public
- * @param array &$raList Reference to array of PPS's
- */
- public function _makeSmallData(&$raList)
- {
- $sRes = '';
- $FILE = $this->_FILEH_;
- $iSmBlk = 0;
+ /**
+ * get small data (PPS's with data smaller than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL)
+ *
+ * @access public
+ * @param array &$raList Reference to array of PPS's
+ */
+ public function _makeSmallData(&$raList)
+ {
+ $sRes = '';
+ $FILE = $this->_FILEH_;
+ $iSmBlk = 0;
- $iCount = count($raList);
- for ($i = 0; $i < $iCount; ++$i) {
- // Make SBD, small data string
- if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) {
- if ($raList[$i]->Size <= 0) {
- continue;
- }
- if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) {
- $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
- + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
- // Add to SBD
- $jB = $iSmbCnt - 1;
- for ($j = 0; $j < $jB; ++$j) {
- fwrite($FILE, pack("V", $j+$iSmBlk+1));
- }
- fwrite($FILE, pack("V", -2));
+ $iCount = count($raList);
+ for ($i = 0; $i < $iCount; ++$i) {
+ // Make SBD, small data string
+ if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) {
+ if ($raList[$i]->Size <= 0) {
+ continue;
+ }
+ if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) {
+ $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
+ + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
+ // Add to SBD
+ $jB = $iSmbCnt - 1;
+ for ($j = 0; $j < $jB; ++$j) {
+ fwrite($FILE, pack("V", $j+$iSmBlk+1));
+ }
+ fwrite($FILE, pack("V", -2));
- //// Add to Data String(this will be written for RootEntry)
- //if ($raList[$i]->_PPS_FILE) {
- // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
- // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
- // $sRes .= $sBuff;
- // }
- //} else {
- $sRes .= $raList[$i]->_data;
- //}
- if ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) {
- $sRes .= str_repeat("\x00",$this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE));
- }
- // Set for PPS
- $raList[$i]->_StartBlock = $iSmBlk;
- $iSmBlk += $iSmbCnt;
- }
- }
- }
- $iSbCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE);
- if ($iSmBlk % $iSbCnt) {
- $iB = $iSbCnt - ($iSmBlk % $iSbCnt);
- for ($i = 0; $i < $iB; ++$i) {
- fwrite($FILE, pack("V", -1));
- }
- }
- return $sRes;
- }
+ //// Add to Data String(this will be written for RootEntry)
+ //if ($raList[$i]->_PPS_FILE) {
+ // fseek($raList[$i]->_PPS_FILE, 0); // To The Top
+ // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) {
+ // $sRes .= $sBuff;
+ // }
+ //} else {
+ $sRes .= $raList[$i]->_data;
+ //}
+ if ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) {
+ $sRes .= str_repeat("\x00", $this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE));
+ }
+ // Set for PPS
+ $raList[$i]->_StartBlock = $iSmBlk;
+ $iSmBlk += $iSmbCnt;
+ }
+ }
+ }
+ $iSbCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE);
+ if ($iSmBlk % $iSbCnt) {
+ $iB = $iSbCnt - ($iSmBlk % $iSbCnt);
+ for ($i = 0; $i < $iB; ++$i) {
+ fwrite($FILE, pack("V", -1));
+ }
+ }
+ return $sRes;
+ }
- /**
- * Saves all the PPS's WKs
- *
- * @access public
- * @param array $raList Reference to an array with all PPS's
- */
- public function _savePps(&$raList)
- {
- // Save each PPS WK
- $iC = count($raList);
- for ($i = 0; $i < $iC; ++$i) {
- fwrite($this->_FILEH_, $raList[$i]->_getPpsWk());
- }
- // Adjust for Block
- $iCnt = count($raList);
- $iBCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE;
- if ($iCnt % $iBCnt) {
- fwrite($this->_FILEH_, str_repeat("\x00",($iBCnt - ($iCnt % $iBCnt)) * PHPExcel_Shared_OLE::OLE_PPS_SIZE));
- }
- }
+ /**
+ * Saves all the PPS's WKs
+ *
+ * @access public
+ * @param array $raList Reference to an array with all PPS's
+ */
+ public function _savePps(&$raList)
+ {
+ // Save each PPS WK
+ $iC = count($raList);
+ for ($i = 0; $i < $iC; ++$i) {
+ fwrite($this->_FILEH_, $raList[$i]->_getPpsWk());
+ }
+ // Adjust for Block
+ $iCnt = count($raList);
+ $iBCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE;
+ if ($iCnt % $iBCnt) {
+ fwrite($this->_FILEH_, str_repeat("\x00", ($iBCnt - ($iCnt % $iBCnt)) * PHPExcel_Shared_OLE::OLE_PPS_SIZE));
+ }
+ }
- /**
- * Saving Big Block Depot
- *
- * @access public
- * @param integer $iSbdSize
- * @param integer $iBsize
- * @param integer $iPpsCnt
- */
- public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt)
- {
- $FILE = $this->_FILEH_;
- // Calculate Basic Setting
- $iBbCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
- $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
+ /**
+ * Saving Big Block Depot
+ *
+ * @access public
+ * @param integer $iSbdSize
+ * @param integer $iBsize
+ * @param integer $iPpsCnt
+ */
+ public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt)
+ {
+ $FILE = $this->_FILEH_;
+ // Calculate Basic Setting
+ $iBbCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
+ $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;
- $iBdExL = 0;
- $iAll = $iBsize + $iPpsCnt + $iSbdSize;
- $iAllW = $iAll;
- $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
- $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
- // Calculate BD count
- if ($iBdCnt >$i1stBdL) {
- while (1) {
- ++$iBdExL;
- ++$iAllW;
- $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
- $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
- if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) {
- break;
- }
- }
- }
+ $iBdExL = 0;
+ $iAll = $iBsize + $iPpsCnt + $iSbdSize;
+ $iAllW = $iAll;
+ $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
+ $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
+ // Calculate BD count
+ if ($iBdCnt >$i1stBdL) {
+ while (1) {
+ ++$iBdExL;
+ ++$iAllW;
+ $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0);
+ $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0);
+ if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) {
+ break;
+ }
+ }
+ }
- // Making BD
- // Set for SBD
- if ($iSbdSize > 0) {
- for ($i = 0; $i < ($iSbdSize - 1); ++$i) {
- fwrite($FILE, pack("V", $i+1));
- }
- fwrite($FILE, pack("V", -2));
- }
- // Set for B
- for ($i = 0; $i < ($iBsize - 1); ++$i) {
- fwrite($FILE, pack("V", $i+$iSbdSize+1));
- }
- fwrite($FILE, pack("V", -2));
+ // Making BD
+ // Set for SBD
+ if ($iSbdSize > 0) {
+ for ($i = 0; $i < ($iSbdSize - 1); ++$i) {
+ fwrite($FILE, pack("V", $i+1));
+ }
+ fwrite($FILE, pack("V", -2));
+ }
+ // Set for B
+ for ($i = 0; $i < ($iBsize - 1); ++$i) {
+ fwrite($FILE, pack("V", $i+$iSbdSize+1));
+ }
+ fwrite($FILE, pack("V", -2));
- // Set for PPS
- for ($i = 0; $i < ($iPpsCnt - 1); ++$i) {
- fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1));
- }
- fwrite($FILE, pack("V", -2));
- // Set for BBD itself ( 0xFFFFFFFD : BBD)
- for ($i = 0; $i < $iBdCnt; ++$i) {
- fwrite($FILE, pack("V", 0xFFFFFFFD));
- }
- // Set for ExtraBDList
- for ($i = 0; $i < $iBdExL; ++$i) {
- fwrite($FILE, pack("V", 0xFFFFFFFC));
- }
- // Adjust for Block
- if (($iAllW + $iBdCnt) % $iBbCnt) {
- $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt));
- for ($i = 0; $i < $iBlock; ++$i) {
- fwrite($FILE, pack("V", -1));
- }
- }
- // Extra BDList
- if ($iBdCnt > $i1stBdL) {
- $iN=0;
- $iNb=0;
- for ($i = $i1stBdL;$i < $iBdCnt; $i++, ++$iN) {
- if ($iN >= ($iBbCnt - 1)) {
- $iN = 0;
- ++$iNb;
- fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb));
- }
- fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i));
- }
- if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) {
- $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1));
- for ($i = 0; $i < $iB; ++$i) {
- fwrite($FILE, pack("V", -1));
- }
- }
- fwrite($FILE, pack("V", -2));
- }
- }
+ // Set for PPS
+ for ($i = 0; $i < ($iPpsCnt - 1); ++$i) {
+ fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1));
+ }
+ fwrite($FILE, pack("V", -2));
+ // Set for BBD itself ( 0xFFFFFFFD : BBD)
+ for ($i = 0; $i < $iBdCnt; ++$i) {
+ fwrite($FILE, pack("V", 0xFFFFFFFD));
+ }
+ // Set for ExtraBDList
+ for ($i = 0; $i < $iBdExL; ++$i) {
+ fwrite($FILE, pack("V", 0xFFFFFFFC));
+ }
+ // Adjust for Block
+ if (($iAllW + $iBdCnt) % $iBbCnt) {
+ $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt));
+ for ($i = 0; $i < $iBlock; ++$i) {
+ fwrite($FILE, pack("V", -1));
+ }
+ }
+ // Extra BDList
+ if ($iBdCnt > $i1stBdL) {
+ $iN=0;
+ $iNb=0;
+ for ($i = $i1stBdL; $i < $iBdCnt; $i++, ++$iN) {
+ if ($iN >= ($iBbCnt - 1)) {
+ $iN = 0;
+ ++$iNb;
+ fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb));
+ }
+ fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i));
+ }
+ if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) {
+ $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1));
+ for ($i = 0; $i < $iB; ++$i) {
+ fwrite($FILE, pack("V", -1));
+ }
+ }
+ fwrite($FILE, pack("V", -2));
+ }
+ }
}
diff --git a/Classes/PHPExcel/Shared/OLERead.php b/Classes/PHPExcel/Shared/OLERead.php
index 5319370db..6b15d9700 100644
--- a/Classes/PHPExcel/Shared/OLERead.php
+++ b/Classes/PHPExcel/Shared/OLERead.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,294 +20,299 @@
*
* @category PHPExcel
* @package PHPExcel_Shared
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
defined('IDENTIFIER_OLE') ||
define('IDENTIFIER_OLE', pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1));
-class PHPExcel_Shared_OLERead {
- private $data = '';
+class PHPExcel_Shared_OLERead
+{
+ private $data = '';
- // OLE identifier
- const IDENTIFIER_OLE = IDENTIFIER_OLE;
+ // OLE identifier
+ const IDENTIFIER_OLE = IDENTIFIER_OLE;
- // Size of a sector = 512 bytes
- const BIG_BLOCK_SIZE = 0x200;
+ // Size of a sector = 512 bytes
+ const BIG_BLOCK_SIZE = 0x200;
- // Size of a short sector = 64 bytes
- const SMALL_BLOCK_SIZE = 0x40;
+ // Size of a short sector = 64 bytes
+ const SMALL_BLOCK_SIZE = 0x40;
- // Size of a directory entry always = 128 bytes
- const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
+ // Size of a directory entry always = 128 bytes
+ const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
- // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams
- const SMALL_BLOCK_THRESHOLD = 0x1000;
+ // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams
+ const SMALL_BLOCK_THRESHOLD = 0x1000;
- // header offsets
- const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c;
- const ROOT_START_BLOCK_POS = 0x30;
- const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c;
- const EXTENSION_BLOCK_POS = 0x44;
- const NUM_EXTENSION_BLOCK_POS = 0x48;
- const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c;
+ // header offsets
+ const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c;
+ const ROOT_START_BLOCK_POS = 0x30;
+ const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c;
+ const EXTENSION_BLOCK_POS = 0x44;
+ const NUM_EXTENSION_BLOCK_POS = 0x48;
+ const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c;
- // property storage offsets (directory offsets)
- const SIZE_OF_NAME_POS = 0x40;
- const TYPE_POS = 0x42;
- const START_BLOCK_POS = 0x74;
- const SIZE_POS = 0x78;
+ // property storage offsets (directory offsets)
+ const SIZE_OF_NAME_POS = 0x40;
+ const TYPE_POS = 0x42;
+ const START_BLOCK_POS = 0x74;
+ const SIZE_POS = 0x78;
- public $wrkbook = null;
- public $summaryInformation = null;
- public $documentSummaryInformation = null;
+ public $wrkbook = null;
+ public $summaryInformation = null;
+ public $documentSummaryInformation = null;
- /**
- * Read the file
- *
- * @param $sFileName string Filename
- * @throws PHPExcel_Reader_Exception
- */
- public function read($sFileName)
- {
- // Check if file exists and is readable
- if(!is_readable($sFileName)) {
- throw new PHPExcel_Reader_Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable.");
- }
+ /**
+ * Read the file
+ *
+ * @param $sFileName string Filename
+ * @throws PHPExcel_Reader_Exception
+ */
+ public function read($sFileName)
+ {
+ // Check if file exists and is readable
+ if (!is_readable($sFileName)) {
+ throw new PHPExcel_Reader_Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable.");
+ }
- // Get the file data
- $this->data = file_get_contents($sFileName);
+ // Get the file identifier
+ // Don't bother reading the whole file until we know it's a valid OLE file
+ $this->data = file_get_contents($sFileName, false, null, 0, 8);
- // Check OLE identifier
- if (substr($this->data, 0, 8) != self::IDENTIFIER_OLE) {
- throw new PHPExcel_Reader_Exception('The filename ' . $sFileName . ' is not recognised as an OLE file');
- }
+ // Check OLE identifier
+ if ($this->data != self::IDENTIFIER_OLE) {
+ throw new PHPExcel_Reader_Exception('The filename ' . $sFileName . ' is not recognised as an OLE file');
+ }
- // Total number of sectors used for the SAT
- $this->numBigBlockDepotBlocks = self::_GetInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
+ // Get the file data
+ $this->data = file_get_contents($sFileName);
- // SecID of the first sector of the directory stream
- $this->rootStartBlock = self::_GetInt4d($this->data, self::ROOT_START_BLOCK_POS);
+ // Total number of sectors used for the SAT
+ $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
- // SecID of the first sector of the SSAT (or -2 if not extant)
- $this->sbdStartBlock = self::_GetInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS);
+ // SecID of the first sector of the directory stream
+ $this->rootStartBlock = self::getInt4d($this->data, self::ROOT_START_BLOCK_POS);
- // SecID of the first sector of the MSAT (or -2 if no additional sectors are used)
- $this->extensionBlock = self::_GetInt4d($this->data, self::EXTENSION_BLOCK_POS);
+ // SecID of the first sector of the SSAT (or -2 if not extant)
+ $this->sbdStartBlock = self::getInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS);
- // Total number of sectors used by MSAT
- $this->numExtensionBlocks = self::_GetInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS);
+ // SecID of the first sector of the MSAT (or -2 if no additional sectors are used)
+ $this->extensionBlock = self::getInt4d($this->data, self::EXTENSION_BLOCK_POS);
- $bigBlockDepotBlocks = array();
- $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
+ // Total number of sectors used by MSAT
+ $this->numExtensionBlocks = self::getInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS);
- $bbdBlocks = $this->numBigBlockDepotBlocks;
+ $bigBlockDepotBlocks = array();
+ $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
- if ($this->numExtensionBlocks != 0) {
- $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4;
- }
+ $bbdBlocks = $this->numBigBlockDepotBlocks;
- for ($i = 0; $i < $bbdBlocks; ++$i) {
- $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos);
- $pos += 4;
- }
-
- for ($j = 0; $j < $this->numExtensionBlocks; ++$j) {
- $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE;
- $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
-
- for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) {
- $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos);
- $pos += 4;
- }
-
- $bbdBlocks += $blocksToRead;
- if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
- $this->extensionBlock = self::_GetInt4d($this->data, $pos);
- }
- }
-
- $pos = 0;
- $this->bigBlockChain = '';
- $bbs = self::BIG_BLOCK_SIZE / 4;
- for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) {
- $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE;
-
- $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs);
- $pos += 4*$bbs;
- }
-
- $pos = 0;
- $sbdBlock = $this->sbdStartBlock;
- $this->smallBlockChain = '';
- while ($sbdBlock != -2) {
- $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE;
-
- $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs);
- $pos += 4*$bbs;
-
- $sbdBlock = self::_GetInt4d($this->bigBlockChain, $sbdBlock*4);
- }
-
- // read the directory stream
- $block = $this->rootStartBlock;
- $this->entry = $this->_readData($block);
-
- $this->_readPropertySets();
- }
-
- /**
- * Extract binary stream data
- *
- * @return string
- */
- public function getStream($stream)
- {
- if ($stream === NULL) {
- return null;
- }
-
- $streamData = '';
-
- if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) {
- $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']);
-
- $block = $this->props[$stream]['startBlock'];
-
- while ($block != -2) {
- $pos = $block * self::SMALL_BLOCK_SIZE;
- $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
-
- $block = self::_GetInt4d($this->smallBlockChain, $block*4);
- }
-
- return $streamData;
- } else {
- $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE;
- if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) {
- ++$numBlocks;
- }
-
- if ($numBlocks == 0) return '';
-
- $block = $this->props[$stream]['startBlock'];
-
- while ($block != -2) {
- $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
- $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
- $block = self::_GetInt4d($this->bigBlockChain, $block*4);
- }
-
- return $streamData;
- }
- }
-
- /**
- * Read a standard stream (by joining sectors using information from SAT)
- *
- * @param int $bl Sector ID where the stream starts
- * @return string Data for standard stream
- */
- private function _readData($bl)
- {
- $block = $bl;
- $data = '';
-
- while ($block != -2) {
- $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
- $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
- $block = self::_GetInt4d($this->bigBlockChain, $block*4);
- }
- return $data;
- }
-
- /**
- * Read entries in the directory stream.
- */
- private function _readPropertySets() {
- $offset = 0;
-
- // loop through entires, each entry is 128 bytes
- $entryLen = strlen($this->entry);
- while ($offset < $entryLen) {
- // entry data (128 bytes)
- $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
-
- // size in bytes of name
- $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8);
-
- // type of entry
- $type = ord($d[self::TYPE_POS]);
-
- // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook)
- // sectorID of first sector of the short-stream container stream, if this entry is root entry
- $startBlock = self::_GetInt4d($d, self::START_BLOCK_POS);
-
- $size = self::_GetInt4d($d, self::SIZE_POS);
-
- $name = str_replace("\x00", "", substr($d,0,$nameSize));
-
-
- $this->props[] = array (
- 'name' => $name,
- 'type' => $type,
- 'startBlock' => $startBlock,
- 'size' => $size);
-
- // tmp helper to simplify checks
- $upName = strtoupper($name);
-
- // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook)
- if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) {
- $this->wrkbook = count($this->props) - 1;
- }
- else if ( $upName === 'ROOT ENTRY' || $upName === 'R') {
- // Root entry
- $this->rootentry = count($this->props) - 1;
- }
-
- // Summary information
- if ($name == chr(5) . 'SummaryInformation') {
-// echo 'Summary Information
+
+This block contains an italicized word;
+while this block uses an underline.
+
+
+I want to eat
+
+ 100°C is a hot temperature
+
+
';
- $this->summaryInformation = count($this->props) - 1;
- }
-
- // Additional Document Summary information
- if ($name == chr(5) . 'DocumentSummaryInformation') {
-// echo 'Document Summary Information
';
- $this->documentSummaryInformation = count($this->props) - 1;
- }
-
- $offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
- }
-
- }
-
- /**
- * Read 4 bytes of data at specified position
- *
- * @param string $data
- * @param int $pos
- * @return int
- */
- private static function _GetInt4d($data, $pos)
- {
- // FIX: represent numbers correctly on 64-bit system
- // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
- // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
- $_or_24 = ord($data[$pos + 3]);
- if ($_or_24 >= 128) {
- // negative number
- $_ord_24 = -abs((256 - $_or_24) << 24);
- } else {
- $_ord_24 = ($_or_24 & 127) << 24;
- }
- return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24;
- }
+ if ($this->numExtensionBlocks != 0) {
+ $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4;
+ }
+ for ($i = 0; $i < $bbdBlocks; ++$i) {
+ $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos);
+ $pos += 4;
+ }
+
+ for ($j = 0; $j < $this->numExtensionBlocks; ++$j) {
+ $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE;
+ $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
+
+ for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) {
+ $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos);
+ $pos += 4;
+ }
+
+ $bbdBlocks += $blocksToRead;
+ if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
+ $this->extensionBlock = self::getInt4d($this->data, $pos);
+ }
+ }
+
+ $pos = 0;
+ $this->bigBlockChain = '';
+ $bbs = self::BIG_BLOCK_SIZE / 4;
+ for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) {
+ $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE;
+
+ $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs);
+ $pos += 4*$bbs;
+ }
+
+ $pos = 0;
+ $sbdBlock = $this->sbdStartBlock;
+ $this->smallBlockChain = '';
+ while ($sbdBlock != -2) {
+ $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE;
+
+ $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs);
+ $pos += 4*$bbs;
+
+ $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock*4);
+ }
+
+ // read the directory stream
+ $block = $this->rootStartBlock;
+ $this->entry = $this->_readData($block);
+
+ $this->readPropertySets();
+ }
+
+ /**
+ * Extract binary stream data
+ *
+ * @return string
+ */
+ public function getStream($stream)
+ {
+ if ($stream === null) {
+ return null;
+ }
+
+ $streamData = '';
+
+ if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) {
+ $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']);
+
+ $block = $this->props[$stream]['startBlock'];
+
+ while ($block != -2) {
+ $pos = $block * self::SMALL_BLOCK_SIZE;
+ $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
+
+ $block = self::getInt4d($this->smallBlockChain, $block*4);
+ }
+
+ return $streamData;
+ } else {
+ $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE;
+ if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) {
+ ++$numBlocks;
+ }
+
+ if ($numBlocks == 0) {
+ return '';
+ }
+
+ $block = $this->props[$stream]['startBlock'];
+
+ while ($block != -2) {
+ $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
+ $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
+ $block = self::getInt4d($this->bigBlockChain, $block*4);
+ }
+
+ return $streamData;
+ }
+ }
+
+ /**
+ * Read a standard stream (by joining sectors using information from SAT)
+ *
+ * @param int $bl Sector ID where the stream starts
+ * @return string Data for standard stream
+ */
+ private function _readData($bl)
+ {
+ $block = $bl;
+ $data = '';
+
+ while ($block != -2) {
+ $pos = ($block + 1) * self::BIG_BLOCK_SIZE;
+ $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
+ $block = self::getInt4d($this->bigBlockChain, $block*4);
+ }
+ return $data;
+ }
+
+ /**
+ * Read entries in the directory stream.
+ */
+ private function readPropertySets()
+ {
+ $offset = 0;
+
+ // loop through entires, each entry is 128 bytes
+ $entryLen = strlen($this->entry);
+ while ($offset < $entryLen) {
+ // entry data (128 bytes)
+ $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
+
+ // size in bytes of name
+ $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8);
+
+ // type of entry
+ $type = ord($d[self::TYPE_POS]);
+
+ // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook)
+ // sectorID of first sector of the short-stream container stream, if this entry is root entry
+ $startBlock = self::getInt4d($d, self::START_BLOCK_POS);
+
+ $size = self::getInt4d($d, self::SIZE_POS);
+
+ $name = str_replace("\x00", "", substr($d, 0, $nameSize));
+
+ $this->props[] = array(
+ 'name' => $name,
+ 'type' => $type,
+ 'startBlock' => $startBlock,
+ 'size' => $size
+ );
+
+ // tmp helper to simplify checks
+ $upName = strtoupper($name);
+
+ // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook)
+ if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) {
+ $this->wrkbook = count($this->props) - 1;
+ } elseif ($upName === 'ROOT ENTRY' || $upName === 'R') {
+ // Root entry
+ $this->rootentry = count($this->props) - 1;
+ }
+
+ // Summary information
+ if ($name == chr(5) . 'SummaryInformation') {
+// echo 'Summary Information
';
+ $this->summaryInformation = count($this->props) - 1;
+ }
+
+ // Additional Document Summary information
+ if ($name == chr(5) . 'DocumentSummaryInformation') {
+// echo 'Document Summary Information
';
+ $this->documentSummaryInformation = count($this->props) - 1;
+ }
+
+ $offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
+ }
+ }
+
+ /**
+ * Read 4 bytes of data at specified position
+ *
+ * @param string $data
+ * @param int $pos
+ * @return int
+ */
+ private static function getInt4d($data, $pos)
+ {
+ // FIX: represent numbers correctly on 64-bit system
+ // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
+ // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
+ $_or_24 = ord($data[$pos + 3]);
+ if ($_or_24 >= 128) {
+ // negative number
+ $_ord_24 = -abs((256 - $_or_24) << 24);
+ } else {
+ $_ord_24 = ($_or_24 & 127) << 24;
+ }
+ return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24;
+ }
}
diff --git a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php
index 4bf05a523..a5a9b0a8b 100644
--- a/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php
+++ b/Classes/PHPExcel/Shared/PCLZip/pclzip.lib.php
@@ -1,5694 +1,5173 @@
-zipname = $p_zipname;
- $this->zip_fd = 0;
- $this->magic_quotes_status = -1;
-
- // ----- Return
- return;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // create($p_filelist, $p_add_dir="", $p_remove_dir="")
- // create($p_filelist, $p_option, $p_option_value, ...)
- // Description :
- // This method supports two different synopsis. The first one is historical.
- // This method creates a Zip Archive. The Zip file is created in the
- // filesystem. The files and directories indicated in $p_filelist
- // are added in the archive. See the parameters description for the
- // supported format of $p_filelist.
- // When a directory is in the list, the directory and its content is added
- // in the archive.
- // In this synopsis, the function takes an optional variable list of
- // options. See bellow the supported options.
- // Parameters :
- // $p_filelist : An array containing file or directory names, or
- // a string containing one filename or one directory name, or
- // a string containing a list of filenames and/or directory
- // names separated by spaces.
- // $p_add_dir : A path to add before the real path of the archived file,
- // in order to have it memorized in the archive.
- // $p_remove_dir : A path to remove from the real path of the file to archive,
- // in order to have a shorter path memorized in the archive.
- // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
- // is removed first, before $p_add_dir is added.
- // Options :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_OPT_COMMENT :
- // PCLZIP_CB_PRE_ADD :
- // PCLZIP_CB_POST_ADD :
- // Return Values :
- // 0 on failure,
- // The list of the added files, with a status of the add action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function create($p_filelist)
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Set default values
- $v_options = array();
- $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Look for arguments
- if ($v_size > 1) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Remove from the options list the first argument
- array_shift($v_arg_list);
- $v_size--;
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_ADD => 'optional',
- PCLZIP_CB_POST_ADD => 'optional',
- PCLZIP_OPT_NO_COMPRESSION => 'optional',
- PCLZIP_OPT_COMMENT => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- //, PCLZIP_OPT_CRYPT => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Invalid number / type of arguments");
- return 0;
- }
- }
- }
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Init
- $v_string_list = array();
- $v_att_list = array();
- $v_filedescr_list = array();
- $p_result_list = array();
-
- // ----- Look if the $p_filelist is really an array
- if (is_array($p_filelist)) {
-
- // ----- Look if the first element is also an array
- // This will mean that this is a file description entry
- if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
- $v_att_list = $p_filelist;
- }
-
- // ----- The list is a list of string names
- else {
- $v_string_list = $p_filelist;
- }
- }
-
- // ----- Look if the $p_filelist is a string
- else if (is_string($p_filelist)) {
- // ----- Create a list from the string
- $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
- }
-
- // ----- Invalid variable type for $p_filelist
- else {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
- return 0;
- }
-
- // ----- Reformat the string list
- if (sizeof($v_string_list) != 0) {
- foreach ($v_string_list as $v_string) {
- if ($v_string != '') {
- $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
- }
- else {
- }
- }
- }
-
- // ----- For each file in the list check the attributes
- $v_supported_attributes
- = array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
- ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
- ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
- ,PCLZIP_ATT_FILE_MTIME => 'optional'
- ,PCLZIP_ATT_FILE_CONTENT => 'optional'
- ,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
- foreach ($v_att_list as $v_entry) {
- $v_result = $this->privFileDescrParseAtt($v_entry,
- $v_filedescr_list[],
- $v_options,
- $v_supported_attributes);
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Expand the filelist (expand directories)
- $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Call the create fct
- $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Return
- return $p_result_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // add($p_filelist, $p_add_dir="", $p_remove_dir="")
- // add($p_filelist, $p_option, $p_option_value, ...)
- // Description :
- // This method supports two synopsis. The first one is historical.
- // This methods add the list of files in an existing archive.
- // If a file with the same name already exists, it is added at the end of the
- // archive, the first one is still present.
- // If the archive does not exist, it is created.
- // Parameters :
- // $p_filelist : An array containing file or directory names, or
- // a string containing one filename or one directory name, or
- // a string containing a list of filenames and/or directory
- // names separated by spaces.
- // $p_add_dir : A path to add before the real path of the archived file,
- // in order to have it memorized in the archive.
- // $p_remove_dir : A path to remove from the real path of the file to archive,
- // in order to have a shorter path memorized in the archive.
- // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
- // is removed first, before $p_add_dir is added.
- // Options :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_OPT_COMMENT :
- // PCLZIP_OPT_ADD_COMMENT :
- // PCLZIP_OPT_PREPEND_COMMENT :
- // PCLZIP_CB_PRE_ADD :
- // PCLZIP_CB_POST_ADD :
- // Return Values :
- // 0 on failure,
- // The list of the added files, with a status of the add action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function add($p_filelist)
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Set default values
- $v_options = array();
- $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Look for arguments
- if ($v_size > 1) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Remove form the options list the first argument
- array_shift($v_arg_list);
- $v_size--;
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_ADD => 'optional',
- PCLZIP_CB_POST_ADD => 'optional',
- PCLZIP_OPT_NO_COMPRESSION => 'optional',
- PCLZIP_OPT_COMMENT => 'optional',
- PCLZIP_OPT_ADD_COMMENT => 'optional',
- PCLZIP_OPT_PREPEND_COMMENT => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- //, PCLZIP_OPT_CRYPT => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
-
- // ----- Return
- return 0;
- }
- }
- }
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Init
- $v_string_list = array();
- $v_att_list = array();
- $v_filedescr_list = array();
- $p_result_list = array();
-
- // ----- Look if the $p_filelist is really an array
- if (is_array($p_filelist)) {
-
- // ----- Look if the first element is also an array
- // This will mean that this is a file description entry
- if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
- $v_att_list = $p_filelist;
- }
-
- // ----- The list is a list of string names
- else {
- $v_string_list = $p_filelist;
- }
- }
-
- // ----- Look if the $p_filelist is a string
- else if (is_string($p_filelist)) {
- // ----- Create a list from the string
- $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
- }
-
- // ----- Invalid variable type for $p_filelist
- else {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
- return 0;
- }
-
- // ----- Reformat the string list
- if (sizeof($v_string_list) != 0) {
- foreach ($v_string_list as $v_string) {
- $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
- }
- }
-
- // ----- For each file in the list check the attributes
- $v_supported_attributes
- = array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
- ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
- ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
- ,PCLZIP_ATT_FILE_MTIME => 'optional'
- ,PCLZIP_ATT_FILE_CONTENT => 'optional'
- ,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
- foreach ($v_att_list as $v_entry) {
- $v_result = $this->privFileDescrParseAtt($v_entry,
- $v_filedescr_list[],
- $v_options,
- $v_supported_attributes);
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Expand the filelist (expand directories)
- $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Call the create fct
- $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Return
- return $p_result_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : listContent()
- // Description :
- // This public method, gives the list of the files and directories, with their
- // properties.
- // The properties of each entries in the list are (used also in other functions) :
- // filename : Name of the file. For a create or add action it is the filename
- // given by the user. For an extract function it is the filename
- // of the extracted file.
- // stored_filename : Name of the file / directory stored in the archive.
- // size : Size of the stored file.
- // compressed_size : Size of the file's data compressed in the archive
- // (without the headers overhead)
- // mtime : Last known modification date of the file (UNIX timestamp)
- // comment : Comment associated with the file
- // folder : true | false
- // index : index of the file in the archive
- // status : status of the action (depending of the action) :
- // Values are :
- // ok : OK !
- // filtered : the file / dir is not extracted (filtered by user)
- // already_a_directory : the file can not be extracted because a
- // directory with the same name already exists
- // write_protected : the file can not be extracted because a file
- // with the same name already exists and is
- // write protected
- // newer_exist : the file was not extracted because a newer file exists
- // path_creation_fail : the file is not extracted because the folder
- // does not exist and can not be created
- // write_error : the file was not extracted because there was a
- // error while writing the file
- // read_error : the file was not extracted because there was a error
- // while reading the file
- // invalid_header : the file was not extracted because of an archive
- // format error (bad file header)
- // Note that each time a method can continue operating when there
- // is an action error on a file, the error is only logged in the file status.
- // Return Values :
- // 0 on an unrecoverable failure,
- // The list of the files in the archive.
- // --------------------------------------------------------------------------------
- function listContent()
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Call the extracting fct
- $p_list = array();
- if (($v_result = $this->privList($p_list)) != 1)
- {
- unset($p_list);
- return(0);
- }
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // extract($p_path="./", $p_remove_path="")
- // extract([$p_option, $p_option_value, ...])
- // Description :
- // This method supports two synopsis. The first one is historical.
- // This method extract all the files / directories from the archive to the
- // folder indicated in $p_path.
- // If you want to ignore the 'root' part of path of the memorized files
- // you can indicate this in the optional $p_remove_path parameter.
- // By default, if a newer file with the same name already exists, the
- // file is not extracted.
- //
- // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
- // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
- // at the end of the path value of PCLZIP_OPT_PATH.
- // Parameters :
- // $p_path : Path where the files and directories are to be extracted
- // $p_remove_path : First part ('root' part) of the memorized path
- // (if any similar) to remove while extracting.
- // Options :
- // PCLZIP_OPT_PATH :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_CB_PRE_EXTRACT :
- // PCLZIP_CB_POST_EXTRACT :
- // Return Values :
- // 0 or a negative value on failure,
- // The list of the extracted files, with a status of the action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function extract()
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Set default values
- $v_options = array();
-// $v_path = "./";
- $v_path = '';
- $v_remove_path = "";
- $v_remove_all_path = false;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Default values for option
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
-
- // ----- Look for arguments
- if ($v_size > 0) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_PATH => 'optional',
- PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_EXTRACT => 'optional',
- PCLZIP_CB_POST_EXTRACT => 'optional',
- PCLZIP_OPT_SET_CHMOD => 'optional',
- PCLZIP_OPT_BY_NAME => 'optional',
- PCLZIP_OPT_BY_EREG => 'optional',
- PCLZIP_OPT_BY_PREG => 'optional',
- PCLZIP_OPT_BY_INDEX => 'optional',
- PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
- PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
- PCLZIP_OPT_REPLACE_NEWER => 'optional'
- ,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
- ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Set the arguments
- if (isset($v_options[PCLZIP_OPT_PATH])) {
- $v_path = $v_options[PCLZIP_OPT_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
- $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
- $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
- // ----- Check for '/' in last path char
- if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
- $v_path .= '/';
- }
- $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_path = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_remove_path = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
-
- // ----- Return
- return 0;
- }
- }
- }
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Trace
-
- // ----- Call the extracting fct
- $p_list = array();
- $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
- $v_remove_all_path, $v_options);
- if ($v_result < 1) {
- unset($p_list);
- return(0);
- }
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
-
- // --------------------------------------------------------------------------------
- // Function :
- // extractByIndex($p_index, $p_path="./", $p_remove_path="")
- // extractByIndex($p_index, [$p_option, $p_option_value, ...])
- // Description :
- // This method supports two synopsis. The first one is historical.
- // This method is doing a partial extract of the archive.
- // The extracted files or folders are identified by their index in the
- // archive (from 0 to n).
- // Note that if the index identify a folder, only the folder entry is
- // extracted, not all the files included in the archive.
- // Parameters :
- // $p_index : A single index (integer) or a string of indexes of files to
- // extract. The form of the string is "0,4-6,8-12" with only numbers
- // and '-' for range or ',' to separate ranges. No spaces or ';'
- // are allowed.
- // $p_path : Path where the files and directories are to be extracted
- // $p_remove_path : First part ('root' part) of the memorized path
- // (if any similar) to remove while extracting.
- // Options :
- // PCLZIP_OPT_PATH :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
- // not as files.
- // The resulting content is in a new field 'content' in the file
- // structure.
- // This option must be used alone (any other options are ignored).
- // PCLZIP_CB_PRE_EXTRACT :
- // PCLZIP_CB_POST_EXTRACT :
- // Return Values :
- // 0 on failure,
- // The list of the extracted files, with a status of the action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- //function extractByIndex($p_index, options...)
- function extractByIndex($p_index)
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Set default values
- $v_options = array();
-// $v_path = "./";
- $v_path = '';
- $v_remove_path = "";
- $v_remove_all_path = false;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Default values for option
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
-
- // ----- Look for arguments
- if ($v_size > 1) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Remove form the options list the first argument
- array_shift($v_arg_list);
- $v_size--;
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_PATH => 'optional',
- PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_EXTRACT => 'optional',
- PCLZIP_CB_POST_EXTRACT => 'optional',
- PCLZIP_OPT_SET_CHMOD => 'optional',
- PCLZIP_OPT_REPLACE_NEWER => 'optional'
- ,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
- ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Set the arguments
- if (isset($v_options[PCLZIP_OPT_PATH])) {
- $v_path = $v_options[PCLZIP_OPT_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
- $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
- $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
- // ----- Check for '/' in last path char
- if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
- $v_path .= '/';
- }
- $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
- }
- if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
- }
- else {
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_path = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_remove_path = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
-
- // ----- Return
- return 0;
- }
- }
- }
-
- // ----- Trace
-
- // ----- Trick
- // Here I want to reuse extractByRule(), so I need to parse the $p_index
- // with privParseOptions()
- $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index);
- $v_options_trick = array();
- $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick,
- array (PCLZIP_OPT_BY_INDEX => 'optional' ));
- if ($v_result != 1) {
- return 0;
- }
- $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Call the extracting fct
- if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
- return(0);
- }
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // delete([$p_option, $p_option_value, ...])
- // Description :
- // This method removes files from the archive.
- // If no parameters are given, then all the archive is emptied.
- // Parameters :
- // None or optional arguments.
- // Options :
- // PCLZIP_OPT_BY_INDEX :
- // PCLZIP_OPT_BY_NAME :
- // PCLZIP_OPT_BY_EREG :
- // PCLZIP_OPT_BY_PREG :
- // Return Values :
- // 0 on failure,
- // The list of the files which are still present in the archive.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function delete()
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Set default values
- $v_options = array();
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Look for arguments
- if ($v_size > 0) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_BY_NAME => 'optional',
- PCLZIP_OPT_BY_EREG => 'optional',
- PCLZIP_OPT_BY_PREG => 'optional',
- PCLZIP_OPT_BY_INDEX => 'optional' ));
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Call the delete fct
- $v_list = array();
- if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
- $this->privSwapBackMagicQuotes();
- unset($v_list);
- return(0);
- }
-
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : deleteByIndex()
- // Description :
- // ***** Deprecated *****
- // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
- // --------------------------------------------------------------------------------
- function deleteByIndex($p_index)
- {
-
- $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : properties()
- // Description :
- // This method gives the properties of the archive.
- // The properties are :
- // nb : Number of files in the archive
- // comment : Comment associated with the archive file
- // status : not_exist, ok
- // Parameters :
- // None
- // Return Values :
- // 0 on failure,
- // An array with the archive properties.
- // --------------------------------------------------------------------------------
- function properties()
- {
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- $this->privSwapBackMagicQuotes();
- return(0);
- }
-
- // ----- Default properties
- $v_prop = array();
- $v_prop['comment'] = '';
- $v_prop['nb'] = 0;
- $v_prop['status'] = 'not_exist';
-
- // ----- Look if file exists
- if (@is_file($this->zipname))
- {
- // ----- Open the zip file
- if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
- {
- $this->privSwapBackMagicQuotes();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
-
- // ----- Return
- return 0;
- }
-
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- $this->privSwapBackMagicQuotes();
- return 0;
- }
-
- // ----- Close the zip file
- $this->privCloseFd();
-
- // ----- Set the user attributes
- $v_prop['comment'] = $v_central_dir['comment'];
- $v_prop['nb'] = $v_central_dir['entries'];
- $v_prop['status'] = 'ok';
- }
-
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_prop;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : duplicate()
- // Description :
- // This method creates an archive by copying the content of an other one. If
- // the archive already exist, it is replaced by the new one without any warning.
- // Parameters :
- // $p_archive : The filename of a valid archive, or
- // a valid PclZip object.
- // Return Values :
- // 1 on success.
- // 0 or a negative value on error (error code).
- // --------------------------------------------------------------------------------
- function duplicate($p_archive)
- {
- $v_result = 1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Look if the $p_archive is a PclZip object
- if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip'))
- {
-
- // ----- Duplicate the archive
- $v_result = $this->privDuplicate($p_archive->zipname);
- }
-
- // ----- Look if the $p_archive is a string (so a filename)
- else if (is_string($p_archive))
- {
-
- // ----- Check that $p_archive is a valid zip file
- // TBC : Should also check the archive format
- if (!is_file($p_archive)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
- $v_result = PCLZIP_ERR_MISSING_FILE;
- }
- else {
- // ----- Duplicate the archive
- $v_result = $this->privDuplicate($p_archive);
- }
- }
-
- // ----- Invalid variable
- else
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
- $v_result = PCLZIP_ERR_INVALID_PARAMETER;
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : merge()
- // Description :
- // This method merge the $p_archive_to_add archive at the end of the current
- // one ($this).
- // If the archive ($this) does not exist, the merge becomes a duplicate.
- // If the $p_archive_to_add archive does not exist, the merge is a success.
- // Parameters :
- // $p_archive_to_add : It can be directly the filename of a valid zip archive,
- // or a PclZip object archive.
- // Return Values :
- // 1 on success,
- // 0 or negative values on error (see below).
- // --------------------------------------------------------------------------------
- function merge($p_archive_to_add)
- {
- $v_result = 1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Look if the $p_archive_to_add is a PclZip object
- if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip'))
- {
-
- // ----- Merge the archive
- $v_result = $this->privMerge($p_archive_to_add);
- }
-
- // ----- Look if the $p_archive_to_add is a string (so a filename)
- else if (is_string($p_archive_to_add))
- {
-
- // ----- Create a temporary archive
- $v_object_archive = new PclZip($p_archive_to_add);
-
- // ----- Merge the archive
- $v_result = $this->privMerge($v_object_archive);
- }
-
- // ----- Invalid variable
- else
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
- $v_result = PCLZIP_ERR_INVALID_PARAMETER;
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
-
-
- // --------------------------------------------------------------------------------
- // Function : errorCode()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function errorCode()
- {
- if (PCLZIP_ERROR_EXTERNAL == 1) {
- return(PclErrorCode());
- }
- else {
- return($this->error_code);
- }
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : errorName()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function errorName($p_with_code=false)
- {
- $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
- PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
- PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
- PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
- PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
- PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
- PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
- PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
- PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
- PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
- PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
- PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
- PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
- PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
- PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
- PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
- PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
- PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
- PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION'
- ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE'
- ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION'
- );
-
- if (isset($v_name[$this->error_code])) {
- $v_value = $v_name[$this->error_code];
- }
- else {
- $v_value = 'NoName';
- }
-
- if ($p_with_code) {
- return($v_value.' ('.$this->error_code.')');
- }
- else {
- return($v_value);
- }
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : errorInfo()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function errorInfo($p_full=false)
- {
- if (PCLZIP_ERROR_EXTERNAL == 1) {
- return(PclErrorString());
- }
- else {
- if ($p_full) {
- return($this->errorName(true)." : ".$this->error_string);
- }
- else {
- return($this->error_string." [code ".$this->error_code."]");
- }
- }
- }
- // --------------------------------------------------------------------------------
-
-
-// --------------------------------------------------------------------------------
-// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
-// ***** *****
-// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
-// --------------------------------------------------------------------------------
-
-
-
- // --------------------------------------------------------------------------------
- // Function : privCheckFormat()
- // Description :
- // This method check that the archive exists and is a valid zip archive.
- // Several level of check exists. (futur)
- // Parameters :
- // $p_level : Level of check. Default 0.
- // 0 : Check the first bytes (magic codes) (default value))
- // 1 : 0 + Check the central directory (futur)
- // 2 : 1 + Check each file header (futur)
- // Return Values :
- // true on success,
- // false on error, the error code is set.
- // --------------------------------------------------------------------------------
- function privCheckFormat($p_level=0)
- {
- $v_result = true;
-
- // ----- Reset the file system cache
- clearstatcache();
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Look if the file exits
- if (!is_file($this->zipname)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
- return(false);
- }
-
- // ----- Check that the file is readeable
- if (!is_readable($this->zipname)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
- return(false);
- }
-
- // ----- Check the magic code
- // TBC
-
- // ----- Check the central header
- // TBC
-
- // ----- Check each file header
- // TBC
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privParseOptions()
- // Description :
- // This internal methods reads the variable list of arguments ($p_options_list,
- // $p_size) and generate an array with the options and values ($v_result_list).
- // $v_requested_options contains the options that can be present and those that
- // must be present.
- // $v_requested_options is an array, with the option value as key, and 'optional',
- // or 'mandatory' as value.
- // Parameters :
- // See above.
- // Return Values :
- // 1 on success.
- // 0 on failure.
- // --------------------------------------------------------------------------------
- function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
- {
- $v_result=1;
-
- // ----- Read the options
- $i=0;
- while ($i<$p_size) {
-
- // ----- Check if the option is supported
- if (!isset($v_requested_options[$p_options_list[$i]])) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Look for next option
- switch ($p_options_list[$i]) {
- // ----- Look for options that request a path value
- case PCLZIP_OPT_PATH :
- case PCLZIP_OPT_REMOVE_PATH :
- case PCLZIP_OPT_ADD_PATH :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
- $i++;
- break;
-
- case PCLZIP_OPT_TEMP_FILE_THRESHOLD :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
- return PclZip::errorCode();
- }
-
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
- return PclZip::errorCode();
- }
-
- // ----- Check the value
- $v_value = $p_options_list[$i+1];
- if ((!is_integer($v_value)) || ($v_value<0)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'");
- return PclZip::errorCode();
- }
-
- // ----- Get the value (and convert it in bytes)
- $v_result_list[$p_options_list[$i]] = $v_value*1048576;
- $i++;
- break;
-
- case PCLZIP_OPT_TEMP_FILE_ON :
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
- return PclZip::errorCode();
- }
-
- $v_result_list[$p_options_list[$i]] = true;
- break;
-
- case PCLZIP_OPT_TEMP_FILE_OFF :
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'");
- return PclZip::errorCode();
- }
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
- return PclZip::errorCode();
- }
-
- $v_result_list[$p_options_list[$i]] = true;
- break;
-
- case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if ( is_string($p_options_list[$i+1])
- && ($p_options_list[$i+1] != '')) {
- $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
- $i++;
- }
- else {
- }
- break;
-
- // ----- Look for options that request an array of string for value
- case PCLZIP_OPT_BY_NAME :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if (is_string($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
- }
- else if (is_array($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
- $i++;
- break;
-
- // ----- Look for options that request an EREG or PREG expression
- case PCLZIP_OPT_BY_EREG :
- // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG
- // to PCLZIP_OPT_BY_PREG
- $p_options_list[$i] = PCLZIP_OPT_BY_PREG;
- case PCLZIP_OPT_BY_PREG :
- //case PCLZIP_OPT_CRYPT :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if (is_string($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
- $i++;
- break;
-
- // ----- Look for options that takes a string
- case PCLZIP_OPT_COMMENT :
- case PCLZIP_OPT_ADD_COMMENT :
- case PCLZIP_OPT_PREPEND_COMMENT :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
- "Missing parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if (is_string($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
- "Wrong parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
- $i++;
- break;
-
- // ----- Look for options that request an array of index
- case PCLZIP_OPT_BY_INDEX :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- $v_work_list = array();
- if (is_string($p_options_list[$i+1])) {
-
- // ----- Remove spaces
- $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
-
- // ----- Parse items
- $v_work_list = explode(",", $p_options_list[$i+1]);
- }
- else if (is_integer($p_options_list[$i+1])) {
- $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
- }
- else if (is_array($p_options_list[$i+1])) {
- $v_work_list = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Reduce the index list
- // each index item in the list must be a couple with a start and
- // an end value : [0,3], [5-5], [8-10], ...
- // ----- Check the format of each item
- $v_sort_flag=false;
- $v_sort_value=0;
- for ($j=0; $j
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray(
- * array(
- * 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
- * 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
- * 'rotation' => 0,
- * 'wrap' => TRUE
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Alignment
- */
- public function applyFromArray($pStyles = NULL) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())
- ->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (isset($pStyles['horizontal'])) {
- $this->setHorizontal($pStyles['horizontal']);
- }
- if (isset($pStyles['vertical'])) {
- $this->setVertical($pStyles['vertical']);
- }
- if (isset($pStyles['rotation'])) {
- $this->setTextRotation($pStyles['rotation']);
- }
- if (isset($pStyles['wrap'])) {
- $this->setWrapText($pStyles['wrap']);
- }
- if (isset($pStyles['shrinkToFit'])) {
- $this->setShrinkToFit($pStyles['shrinkToFit']);
- }
- if (isset($pStyles['indent'])) {
- $this->setIndent($pStyles['indent']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
-
- /**
- * Get Horizontal
- *
- * @return string
- */
- public function getHorizontal() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHorizontal();
- }
- return $this->_horizontal;
- }
-
- /**
- * Set Horizontal
- *
- * @param string $pValue
- * @return PHPExcel_Style_Alignment
- */
- public function setHorizontal($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) {
- if ($pValue == '') {
- $pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL;
- }
-
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('horizontal' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- }
- else {
- $this->_horizontal = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Vertical
- *
- * @return string
- */
- public function getVertical() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getVertical();
- }
- return $this->_vertical;
- }
-
- /**
- * Set Vertical
- *
- * @param string $pValue
- * @return PHPExcel_Style_Alignment
- */
- public function setVertical($pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM) {
- if ($pValue == '') {
- $pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM;
- }
-
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('vertical' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_vertical = $pValue;
- }
- return $this;
- }
-
- /**
- * Get TextRotation
- *
- * @return int
- */
- public function getTextRotation() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getTextRotation();
- }
- return $this->_textRotation;
- }
-
- /**
- * Set TextRotation
- *
- * @param int $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Alignment
- */
- public function setTextRotation($pValue = 0) {
- // Excel2007 value 255 => PHPExcel value -165
- if ($pValue == 255) {
- $pValue = -165;
- }
-
- // Set rotation
- if ( ($pValue >= -90 && $pValue <= 90) || $pValue == -165 ) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('rotation' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_textRotation = $pValue;
- }
- } else {
- throw new PHPExcel_Exception("Text rotation should be a value between -90 and 90.");
- }
-
- return $this;
- }
-
- /**
- * Get Wrap Text
- *
- * @return boolean
- */
- public function getWrapText() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getWrapText();
- }
- return $this->_wrapText;
- }
-
- /**
- * Set Wrap Text
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Alignment
- */
- public function setWrapText($pValue = FALSE) {
- if ($pValue == '') {
- $pValue = FALSE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('wrap' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_wrapText = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Shrink to fit
- *
- * @return boolean
- */
- public function getShrinkToFit() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getShrinkToFit();
- }
- return $this->_shrinkToFit;
- }
-
- /**
- * Set Shrink to fit
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Alignment
- */
- public function setShrinkToFit($pValue = FALSE) {
- if ($pValue == '') {
- $pValue = FALSE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_shrinkToFit = $pValue;
- }
- return $this;
- }
-
- /**
- * Get indent
- *
- * @return int
- */
- public function getIndent() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getIndent();
- }
- return $this->_indent;
- }
-
- /**
- * Set indent
- *
- * @param int $pValue
- * @return PHPExcel_Style_Alignment
- */
- public function setIndent($pValue = 0) {
- if ($pValue > 0) {
- if ($this->getHorizontal() != self::HORIZONTAL_GENERAL &&
- $this->getHorizontal() != self::HORIZONTAL_LEFT &&
- $this->getHorizontal() != self::HORIZONTAL_RIGHT) {
- $pValue = 0; // indent not supported
- }
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('indent' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_indent = $pValue;
- }
- return $this;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_horizontal
- . $this->_vertical
- . $this->_textRotation
- . ($this->_wrapText ? 't' : 'f')
- . ($this->_shrinkToFit ? 't' : 'f')
- . $this->_indent
- . __CLASS__
- );
- }
-
+ /* Horizontal alignment styles */
+ const HORIZONTAL_GENERAL = 'general';
+ const HORIZONTAL_LEFT = 'left';
+ const HORIZONTAL_RIGHT = 'right';
+ const HORIZONTAL_CENTER = 'center';
+ const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous';
+ const HORIZONTAL_JUSTIFY = 'justify';
+ const HORIZONTAL_FILL = 'fill';
+ const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only
+
+ /* Vertical alignment styles */
+ const VERTICAL_BOTTOM = 'bottom';
+ const VERTICAL_TOP = 'top';
+ const VERTICAL_CENTER = 'center';
+ const VERTICAL_JUSTIFY = 'justify';
+ const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only
+
+ /* Read order */
+ const READORDER_CONTEXT = 0;
+ const READORDER_LTR = 1;
+ const READORDER_RTL = 2;
+
+ /**
+ * Horizontal alignment
+ *
+ * @var string
+ */
+ protected $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL;
+
+ /**
+ * Vertical alignment
+ *
+ * @var string
+ */
+ protected $vertical = PHPExcel_Style_Alignment::VERTICAL_BOTTOM;
+
+ /**
+ * Text rotation
+ *
+ * @var integer
+ */
+ protected $textRotation = 0;
+
+ /**
+ * Wrap text
+ *
+ * @var boolean
+ */
+ protected $wrapText = false;
+
+ /**
+ * Shrink to fit
+ *
+ * @var boolean
+ */
+ protected $shrinkToFit = false;
+
+ /**
+ * Indent - only possible with horizontal alignment left and right
+ *
+ * @var integer
+ */
+ protected $indent = 0;
+
+ /**
+ * Read order
+ *
+ * @var integer
+ */
+ protected $readorder = 0;
+
+ /**
+ * Create a new PHPExcel_Style_Alignment
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
+
+ if ($isConditional) {
+ $this->horizontal = null;
+ $this->vertical = null;
+ $this->textRotation = null;
+ }
+ }
+
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Alignment
+ */
+ public function getSharedComponent()
+ {
+ return $this->parent->getSharedComponent()->getAlignment();
+ }
+
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('alignment' => $array);
+ }
+
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray(
+ * array(
+ * 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
+ * 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
+ * 'rotation' => 0,
+ * 'wrap' => TRUE
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Alignment
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())
+ ->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (isset($pStyles['horizontal'])) {
+ $this->setHorizontal($pStyles['horizontal']);
+ }
+ if (isset($pStyles['vertical'])) {
+ $this->setVertical($pStyles['vertical']);
+ }
+ if (isset($pStyles['rotation'])) {
+ $this->setTextRotation($pStyles['rotation']);
+ }
+ if (isset($pStyles['wrap'])) {
+ $this->setWrapText($pStyles['wrap']);
+ }
+ if (isset($pStyles['shrinkToFit'])) {
+ $this->setShrinkToFit($pStyles['shrinkToFit']);
+ }
+ if (isset($pStyles['indent'])) {
+ $this->setIndent($pStyles['indent']);
+ }
+ if (isset($pStyles['readorder'])) {
+ $this->setReadorder($pStyles['readorder']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
+
+ /**
+ * Get Horizontal
+ *
+ * @return string
+ */
+ public function getHorizontal()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHorizontal();
+ }
+ return $this->horizontal;
+ }
+
+ /**
+ * Set Horizontal
+ *
+ * @param string $pValue
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setHorizontal($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL)
+ {
+ if ($pValue == '') {
+ $pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL;
+ }
+
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('horizontal' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->horizontal = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Vertical
+ *
+ * @return string
+ */
+ public function getVertical()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getVertical();
+ }
+ return $this->vertical;
+ }
+
+ /**
+ * Set Vertical
+ *
+ * @param string $pValue
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setVertical($pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM)
+ {
+ if ($pValue == '') {
+ $pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM;
+ }
+
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('vertical' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->vertical = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get TextRotation
+ *
+ * @return int
+ */
+ public function getTextRotation()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getTextRotation();
+ }
+ return $this->textRotation;
+ }
+
+ /**
+ * Set TextRotation
+ *
+ * @param int $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setTextRotation($pValue = 0)
+ {
+ // Excel2007 value 255 => PHPExcel value -165
+ if ($pValue == 255) {
+ $pValue = -165;
+ }
+
+ // Set rotation
+ if (($pValue >= -90 && $pValue <= 90) || $pValue == -165) {
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('rotation' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->textRotation = $pValue;
+ }
+ } else {
+ throw new PHPExcel_Exception("Text rotation should be a value between -90 and 90.");
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get Wrap Text
+ *
+ * @return boolean
+ */
+ public function getWrapText()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getWrapText();
+ }
+ return $this->wrapText;
+ }
+
+ /**
+ * Set Wrap Text
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setWrapText($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('wrap' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->wrapText = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Shrink to fit
+ *
+ * @return boolean
+ */
+ public function getShrinkToFit()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getShrinkToFit();
+ }
+ return $this->shrinkToFit;
+ }
+
+ /**
+ * Set Shrink to fit
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setShrinkToFit($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->shrinkToFit = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get indent
+ *
+ * @return int
+ */
+ public function getIndent()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getIndent();
+ }
+ return $this->indent;
+ }
+
+ /**
+ * Set indent
+ *
+ * @param int $pValue
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setIndent($pValue = 0)
+ {
+ if ($pValue > 0) {
+ if ($this->getHorizontal() != self::HORIZONTAL_GENERAL &&
+ $this->getHorizontal() != self::HORIZONTAL_LEFT &&
+ $this->getHorizontal() != self::HORIZONTAL_RIGHT) {
+ $pValue = 0; // indent not supported
+ }
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('indent' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->indent = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get read order
+ *
+ * @return integer
+ */
+ public function getReadorder()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getReadorder();
+ }
+ return $this->readorder;
+ }
+
+ /**
+ * Set read order
+ *
+ * @param int $pValue
+ * @return PHPExcel_Style_Alignment
+ */
+ public function setReadorder($pValue = 0)
+ {
+ if ($pValue < 0 || $pValue > 2) {
+ $pValue = 0;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('readorder' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->readorder = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->horizontal .
+ $this->vertical .
+ $this->textRotation .
+ ($this->wrapText ? 't' : 'f') .
+ ($this->shrinkToFit ? 't' : 'f') .
+ $this->indent .
+ $this->readorder .
+ __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Border.php b/Classes/PHPExcel/Style/Border.php
index b0e5a9e7b..55efc501e 100644
--- a/Classes/PHPExcel/Style/Border.php
+++ b/Classes/PHPExcel/Style/Border.php
@@ -1,8 +1,9 @@
_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor);
+ /**
+ * Parent property name
+ *
+ * @var string
+ */
+ protected $parentPropertyName;
- // bind parent if we are a supervisor
- if ($isSupervisor) {
- $this->_color->bindParent($this, '_color');
- }
- }
+ /**
+ * Create a new PHPExcel_Style_Border
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- /**
- * Bind parent. Only used for supervisor
- *
- * @param PHPExcel_Style_Borders $parent
- * @param string $parentPropertyName
- * @return PHPExcel_Style_Border
- */
- public function bindParent($parent, $parentPropertyName=NULL)
- {
- $this->_parent = $parent;
- $this->_parentPropertyName = $parentPropertyName;
- return $this;
- }
+ // Initialise values
+ $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor);
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_Border
- * @throws PHPExcel_Exception
- */
- public function getSharedComponent()
- {
- switch ($this->_parentPropertyName) {
- case '_allBorders':
- case '_horizontal':
- case '_inside':
- case '_outline':
- case '_vertical':
- throw new PHPExcel_Exception('Cannot get shared component for a pseudo-border.');
- break;
- case '_bottom':
- return $this->_parent->getSharedComponent()->getBottom(); break;
- case '_diagonal':
- return $this->_parent->getSharedComponent()->getDiagonal(); break;
- case '_left':
- return $this->_parent->getSharedComponent()->getLeft(); break;
- case '_right':
- return $this->_parent->getSharedComponent()->getRight(); break;
- case '_top':
- return $this->_parent->getSharedComponent()->getTop(); break;
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->color->bindParent($this, 'color');
+ }
+ }
- }
- }
+ /**
+ * Bind parent. Only used for supervisor
+ *
+ * @param PHPExcel_Style_Borders $parent
+ * @param string $parentPropertyName
+ * @return PHPExcel_Style_Border
+ */
+ public function bindParent($parent, $parentPropertyName = null)
+ {
+ $this->parent = $parent;
+ $this->parentPropertyName = $parentPropertyName;
+ return $this;
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- switch ($this->_parentPropertyName) {
- case '_allBorders':
- $key = 'allborders'; break;
- case '_bottom':
- $key = 'bottom'; break;
- case '_diagonal':
- $key = 'diagonal'; break;
- case '_horizontal':
- $key = 'horizontal'; break;
- case '_inside':
- $key = 'inside'; break;
- case '_left':
- $key = 'left'; break;
- case '_outline':
- $key = 'outline'; break;
- case '_right':
- $key = 'right'; break;
- case '_top':
- $key = 'top'; break;
- case '_vertical':
- $key = 'vertical'; break;
- }
- return $this->_parent->getStyleArray(array($key => $array));
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Border
+ * @throws PHPExcel_Exception
+ */
+ public function getSharedComponent()
+ {
+ switch ($this->parentPropertyName) {
+ case 'allBorders':
+ case 'horizontal':
+ case 'inside':
+ case 'outline':
+ case 'vertical':
+ throw new PHPExcel_Exception('Cannot get shared component for a pseudo-border.');
+ break;
+ case 'bottom':
+ return $this->parent->getSharedComponent()->getBottom();
+ case 'diagonal':
+ return $this->parent->getSharedComponent()->getDiagonal();
+ case 'left':
+ return $this->parent->getSharedComponent()->getLeft();
+ case 'right':
+ return $this->parent->getSharedComponent()->getRight();
+ case 'top':
+ return $this->parent->getSharedComponent()->getTop();
+ }
+ }
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray(
- * array(
- * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Border
- */
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (isset($pStyles['style'])) {
- $this->setBorderStyle($pStyles['style']);
- }
- if (isset($pStyles['color'])) {
- $this->getColor()->applyFromArray($pStyles['color']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ switch ($this->parentPropertyName) {
+ case 'allBorders':
+ case 'bottom':
+ case 'diagonal':
+ case 'horizontal':
+ case 'inside':
+ case 'left':
+ case 'outline':
+ case 'right':
+ case 'top':
+ case 'vertical':
+ $key = strtolower('vertical');
+ break;
+ }
+ return $this->parent->getStyleArray(array($key => $array));
+ }
- /**
- * Get Border style
- *
- * @return string
- */
- public function getBorderStyle() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getBorderStyle();
- }
- return $this->_borderStyle;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray(
+ * array(
+ * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Border
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (isset($pStyles['style'])) {
+ $this->setBorderStyle($pStyles['style']);
+ }
+ if (isset($pStyles['color'])) {
+ $this->getColor()->applyFromArray($pStyles['color']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Set Border style
- *
- * @param string|boolean $pValue
- * When passing a boolean, FALSE equates PHPExcel_Style_Border::BORDER_NONE
- * and TRUE to PHPExcel_Style_Border::BORDER_MEDIUM
- * @return PHPExcel_Style_Border
- */
- public function setBorderStyle($pValue = PHPExcel_Style_Border::BORDER_NONE) {
+ /**
+ * Get Border style
+ *
+ * @return string
+ */
+ public function getBorderStyle()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getBorderStyle();
+ }
+ return $this->borderStyle;
+ }
- if (empty($pValue)) {
- $pValue = PHPExcel_Style_Border::BORDER_NONE;
- } elseif(is_bool($pValue) && $pValue) {
- $pValue = PHPExcel_Style_Border::BORDER_MEDIUM;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('style' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_borderStyle = $pValue;
- }
- return $this;
- }
+ /**
+ * Set Border style
+ *
+ * @param string|boolean $pValue
+ * When passing a boolean, FALSE equates PHPExcel_Style_Border::BORDER_NONE
+ * and TRUE to PHPExcel_Style_Border::BORDER_MEDIUM
+ * @return PHPExcel_Style_Border
+ */
+ public function setBorderStyle($pValue = PHPExcel_Style_Border::BORDER_NONE)
+ {
- /**
- * Get Border Color
- *
- * @return PHPExcel_Style_Color
- */
- public function getColor() {
- return $this->_color;
- }
+ if (empty($pValue)) {
+ $pValue = PHPExcel_Style_Border::BORDER_NONE;
+ } elseif (is_bool($pValue) && $pValue) {
+ $pValue = PHPExcel_Style_Border::BORDER_MEDIUM;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('style' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->borderStyle = $pValue;
+ }
+ return $this;
+ }
- /**
- * Set Border Color
- *
- * @param PHPExcel_Style_Color $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Border
- */
- public function setColor(PHPExcel_Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Get Border Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getColor()
+ {
+ return $this->color;
+ }
- if ($this->_isSupervisor) {
- $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_color = $color;
- }
- return $this;
- }
+ /**
+ * Set Border Color
+ *
+ * @param PHPExcel_Style_Color $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Border
+ */
+ public function setColor(PHPExcel_Style_Color $pValue = null)
+ {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_borderStyle
- . $this->_color->getHashCode()
- . __CLASS__
- );
- }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->color = $color;
+ }
+ return $this;
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->borderStyle .
+ $this->color->getHashCode() .
+ __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Borders.php b/Classes/PHPExcel/Style/Borders.php
index 9c79ed8d7..27c40a48e 100644
--- a/Classes/PHPExcel/Style/Borders.php
+++ b/Classes/PHPExcel/Style/Borders.php
@@ -1,8 +1,9 @@
_left = new PHPExcel_Style_Border($isSupervisor, $isConditional);
- $this->_right = new PHPExcel_Style_Border($isSupervisor, $isConditional);
- $this->_top = new PHPExcel_Style_Border($isSupervisor, $isConditional);
- $this->_bottom = new PHPExcel_Style_Border($isSupervisor, $isConditional);
- $this->_diagonal = new PHPExcel_Style_Border($isSupervisor, $isConditional);
- $this->_diagonalDirection = PHPExcel_Style_Borders::DIAGONAL_NONE;
-
- // Specially for supervisor
- if ($isSupervisor) {
- // Initialize pseudo-borders
- $this->_allBorders = new PHPExcel_Style_Border(TRUE);
- $this->_outline = new PHPExcel_Style_Border(TRUE);
- $this->_inside = new PHPExcel_Style_Border(TRUE);
- $this->_vertical = new PHPExcel_Style_Border(TRUE);
- $this->_horizontal = new PHPExcel_Style_Border(TRUE);
-
- // bind parent if we are a supervisor
- $this->_left->bindParent($this, '_left');
- $this->_right->bindParent($this, '_right');
- $this->_top->bindParent($this, '_top');
- $this->_bottom->bindParent($this, '_bottom');
- $this->_diagonal->bindParent($this, '_diagonal');
- $this->_allBorders->bindParent($this, '_allBorders');
- $this->_outline->bindParent($this, '_outline');
- $this->_inside->bindParent($this, '_inside');
- $this->_vertical->bindParent($this, '_vertical');
- $this->_horizontal->bindParent($this, '_horizontal');
- }
+ // Supervisor?
+ parent::__construct($isSupervisor);
+
+ // Initialise values
+ $this->left = new PHPExcel_Style_Border($isSupervisor, $isConditional);
+ $this->right = new PHPExcel_Style_Border($isSupervisor, $isConditional);
+ $this->top = new PHPExcel_Style_Border($isSupervisor, $isConditional);
+ $this->bottom = new PHPExcel_Style_Border($isSupervisor, $isConditional);
+ $this->diagonal = new PHPExcel_Style_Border($isSupervisor, $isConditional);
+ $this->diagonalDirection = PHPExcel_Style_Borders::DIAGONAL_NONE;
+
+ // Specially for supervisor
+ if ($isSupervisor) {
+ // Initialize pseudo-borders
+ $this->allBorders = new PHPExcel_Style_Border(true);
+ $this->outline = new PHPExcel_Style_Border(true);
+ $this->inside = new PHPExcel_Style_Border(true);
+ $this->vertical = new PHPExcel_Style_Border(true);
+ $this->horizontal = new PHPExcel_Style_Border(true);
+
+ // bind parent if we are a supervisor
+ $this->left->bindParent($this, 'left');
+ $this->right->bindParent($this, 'right');
+ $this->top->bindParent($this, 'top');
+ $this->bottom->bindParent($this, 'bottom');
+ $this->diagonal->bindParent($this, 'diagonal');
+ $this->allBorders->bindParent($this, 'allBorders');
+ $this->outline->bindParent($this, 'outline');
+ $this->inside->bindParent($this, 'inside');
+ $this->vertical->bindParent($this, 'vertical');
+ $this->horizontal->bindParent($this, 'horizontal');
+ }
}
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_Borders
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getBorders();
- }
-
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('borders' => $array);
- }
-
- /**
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Borders
+ */
+ public function getSharedComponent()
+ {
+ return $this->parent->getSharedComponent()->getBorders();
+ }
+
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('borders' => $array);
+ }
+
+ /**
* Apply styles from array
*
*
* $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
- * array(
- * 'bottom' => array(
- * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * ),
- * 'top' => array(
- * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * )
+ * array(
+ * 'bottom' => array(
+ * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * ),
+ * 'top' => array(
+ * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * )
* );
*
*
* $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
- * array(
- * 'allborders' => array(
- * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * )
+ * array(
+ * 'allborders' => array(
+ * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * )
* );
*
*
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
* @return PHPExcel_Style_Borders
*/
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('left', $pStyles)) {
- $this->getLeft()->applyFromArray($pStyles['left']);
- }
- if (array_key_exists('right', $pStyles)) {
- $this->getRight()->applyFromArray($pStyles['right']);
- }
- if (array_key_exists('top', $pStyles)) {
- $this->getTop()->applyFromArray($pStyles['top']);
- }
- if (array_key_exists('bottom', $pStyles)) {
- $this->getBottom()->applyFromArray($pStyles['bottom']);
- }
- if (array_key_exists('diagonal', $pStyles)) {
- $this->getDiagonal()->applyFromArray($pStyles['diagonal']);
- }
- if (array_key_exists('diagonaldirection', $pStyles)) {
- $this->setDiagonalDirection($pStyles['diagonaldirection']);
- }
- if (array_key_exists('allborders', $pStyles)) {
- $this->getLeft()->applyFromArray($pStyles['allborders']);
- $this->getRight()->applyFromArray($pStyles['allborders']);
- $this->getTop()->applyFromArray($pStyles['allborders']);
- $this->getBottom()->applyFromArray($pStyles['allborders']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('left', $pStyles)) {
+ $this->getLeft()->applyFromArray($pStyles['left']);
+ }
+ if (array_key_exists('right', $pStyles)) {
+ $this->getRight()->applyFromArray($pStyles['right']);
+ }
+ if (array_key_exists('top', $pStyles)) {
+ $this->getTop()->applyFromArray($pStyles['top']);
+ }
+ if (array_key_exists('bottom', $pStyles)) {
+ $this->getBottom()->applyFromArray($pStyles['bottom']);
+ }
+ if (array_key_exists('diagonal', $pStyles)) {
+ $this->getDiagonal()->applyFromArray($pStyles['diagonal']);
+ }
+ if (array_key_exists('diagonaldirection', $pStyles)) {
+ $this->setDiagonalDirection($pStyles['diagonaldirection']);
+ }
+ if (array_key_exists('allborders', $pStyles)) {
+ $this->getLeft()->applyFromArray($pStyles['allborders']);
+ $this->getRight()->applyFromArray($pStyles['allborders']);
+ $this->getTop()->applyFromArray($pStyles['allborders']);
+ $this->getBottom()->applyFromArray($pStyles['allborders']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
/**
* Get Left
*
* @return PHPExcel_Style_Border
*/
- public function getLeft() {
- return $this->_left;
+ public function getLeft()
+ {
+ return $this->left;
}
/**
@@ -274,8 +268,9 @@ public function getLeft() {
*
* @return PHPExcel_Style_Border
*/
- public function getRight() {
- return $this->_right;
+ public function getRight()
+ {
+ return $this->right;
}
/**
@@ -283,8 +278,9 @@ public function getRight() {
*
* @return PHPExcel_Style_Border
*/
- public function getTop() {
- return $this->_top;
+ public function getTop()
+ {
+ return $this->top;
}
/**
@@ -292,8 +288,9 @@ public function getTop() {
*
* @return PHPExcel_Style_Border
*/
- public function getBottom() {
- return $this->_bottom;
+ public function getBottom()
+ {
+ return $this->bottom;
}
/**
@@ -301,8 +298,9 @@ public function getBottom() {
*
* @return PHPExcel_Style_Border
*/
- public function getDiagonal() {
- return $this->_diagonal;
+ public function getDiagonal()
+ {
+ return $this->diagonal;
}
/**
@@ -311,11 +309,12 @@ public function getDiagonal() {
* @return PHPExcel_Style_Border
* @throws PHPExcel_Exception
*/
- public function getAllBorders() {
- if (!$this->_isSupervisor) {
- throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_allBorders;
+ public function getAllBorders()
+ {
+ if (!$this->isSupervisor) {
+ throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->allBorders;
}
/**
@@ -324,11 +323,12 @@ public function getAllBorders() {
* @return boolean
* @throws PHPExcel_Exception
*/
- public function getOutline() {
- if (!$this->_isSupervisor) {
- throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_outline;
+ public function getOutline()
+ {
+ if (!$this->isSupervisor) {
+ throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->outline;
}
/**
@@ -337,11 +337,12 @@ public function getOutline() {
* @return boolean
* @throws PHPExcel_Exception
*/
- public function getInside() {
- if (!$this->_isSupervisor) {
- throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_inside;
+ public function getInside()
+ {
+ if (!$this->isSupervisor) {
+ throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->inside;
}
/**
@@ -350,11 +351,12 @@ public function getInside() {
* @return PHPExcel_Style_Border
* @throws PHPExcel_Exception
*/
- public function getVertical() {
- if (!$this->_isSupervisor) {
- throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_vertical;
+ public function getVertical()
+ {
+ if (!$this->isSupervisor) {
+ throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->vertical;
}
/**
@@ -363,11 +365,12 @@ public function getVertical() {
* @return PHPExcel_Style_Border
* @throws PHPExcel_Exception
*/
- public function getHorizontal() {
- if (!$this->_isSupervisor) {
- throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
- }
- return $this->_horizontal;
+ public function getHorizontal()
+ {
+ if (!$this->isSupervisor) {
+ throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.');
+ }
+ return $this->horizontal;
}
/**
@@ -375,11 +378,12 @@ public function getHorizontal() {
*
* @return int
*/
- public function getDiagonalDirection() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getDiagonalDirection();
- }
- return $this->_diagonalDirection;
+ public function getDiagonalDirection()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getDiagonalDirection();
+ }
+ return $this->diagonalDirection;
}
/**
@@ -388,37 +392,38 @@ public function getDiagonalDirection() {
* @param int $pValue
* @return PHPExcel_Style_Borders
*/
- public function setDiagonalDirection($pValue = PHPExcel_Style_Borders::DIAGONAL_NONE) {
+ public function setDiagonalDirection($pValue = PHPExcel_Style_Borders::DIAGONAL_NONE)
+ {
if ($pValue == '') {
- $pValue = PHPExcel_Style_Borders::DIAGONAL_NONE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_diagonalDirection = $pValue;
- }
- return $this;
+ $pValue = PHPExcel_Style_Borders::DIAGONAL_NONE;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->diagonalDirection = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashcode();
- }
- return md5(
- $this->getLeft()->getHashCode()
- . $this->getRight()->getHashCode()
- . $this->getTop()->getHashCode()
- . $this->getBottom()->getHashCode()
- . $this->getDiagonal()->getHashCode()
- . $this->getDiagonalDirection()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashcode();
+ }
+ return md5(
+ $this->getLeft()->getHashCode() .
+ $this->getRight()->getHashCode() .
+ $this->getTop()->getHashCode() .
+ $this->getBottom()->getHashCode() .
+ $this->getDiagonal()->getHashCode() .
+ $this->getDiagonalDirection() .
+ __CLASS__
+ );
}
-
}
diff --git a/Classes/PHPExcel/Style/Color.php b/Classes/PHPExcel/Style/Color.php
index d1aaeb0b7..9c7790f00 100644
--- a/Classes/PHPExcel/Style/Color.php
+++ b/Classes/PHPExcel/Style/Color.php
@@ -1,8 +1,9 @@
_argb = $pARGB;
- }
- }
+ /**
+ * Create a new PHPExcel_Style_Color
+ *
+ * @param string $pARGB ARGB value for the colour
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($pARGB = PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- /**
- * Bind parent. Only used for supervisor
- *
- * @param mixed $parent
- * @param string $parentPropertyName
- * @return PHPExcel_Style_Color
- */
- public function bindParent($parent, $parentPropertyName=NULL)
- {
- $this->_parent = $parent;
- $this->_parentPropertyName = $parentPropertyName;
- return $this;
- }
+ // Initialise values
+ if (!$isConditional) {
+ $this->argb = $pARGB;
+ }
+ }
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_Color
- */
- public function getSharedComponent()
- {
- switch ($this->_parentPropertyName) {
- case '_endColor':
- return $this->_parent->getSharedComponent()->getEndColor(); break;
- case '_color':
- return $this->_parent->getSharedComponent()->getColor(); break;
- case '_startColor':
- return $this->_parent->getSharedComponent()->getStartColor(); break;
- }
- }
+ /**
+ * Bind parent. Only used for supervisor
+ *
+ * @param mixed $parent
+ * @param string $parentPropertyName
+ * @return PHPExcel_Style_Color
+ */
+ public function bindParent($parent, $parentPropertyName = null)
+ {
+ $this->parent = $parent;
+ $this->parentPropertyName = $parentPropertyName;
+ return $this;
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- switch ($this->_parentPropertyName) {
- case '_endColor':
- $key = 'endcolor';
- break;
- case '_color':
- $key = 'color';
- break;
- case '_startColor':
- $key = 'startcolor';
- break;
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getSharedComponent()
+ {
+ switch ($this->parentPropertyName) {
+ case 'endColor':
+ return $this->parent->getSharedComponent()->getEndColor();
+ case 'color':
+ return $this->parent->getSharedComponent()->getColor();
+ case 'startColor':
+ return $this->parent->getSharedComponent()->getStartColor();
+ }
+ }
- }
- return $this->_parent->getStyleArray(array($key => $array));
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ switch ($this->parentPropertyName) {
+ case 'endColor':
+ $key = 'endcolor';
+ break;
+ case 'color':
+ $key = 'color';
+ break;
+ case 'startColor':
+ $key = 'startcolor';
+ break;
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray( array('rgb' => '808080') );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Color
- */
- public function applyFromArray($pStyles = NULL) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('rgb', $pStyles)) {
- $this->setRGB($pStyles['rgb']);
- }
- if (array_key_exists('argb', $pStyles)) {
- $this->setARGB($pStyles['argb']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
+ }
+ return $this->parent->getStyleArray(array($key => $array));
+ }
- /**
- * Get ARGB
- *
- * @return string
- */
- public function getARGB() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getARGB();
- }
- return $this->_argb;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray( array('rgb' => '808080') );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Color
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('rgb', $pStyles)) {
+ $this->setRGB($pStyles['rgb']);
+ }
+ if (array_key_exists('argb', $pStyles)) {
+ $this->setARGB($pStyles['argb']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Set ARGB
- *
- * @param string $pValue
- * @return PHPExcel_Style_Color
- */
- public function setARGB($pValue = PHPExcel_Style_Color::COLOR_BLACK) {
- if ($pValue == '') {
- $pValue = PHPExcel_Style_Color::COLOR_BLACK;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('argb' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_argb = $pValue;
- }
- return $this;
- }
+ /**
+ * Get ARGB
+ *
+ * @return string
+ */
+ public function getARGB()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getARGB();
+ }
+ return $this->argb;
+ }
- /**
- * Get RGB
- *
- * @return string
- */
- public function getRGB() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getRGB();
- }
- return substr($this->_argb, 2);
- }
+ /**
+ * Set ARGB
+ *
+ * @param string $pValue
+ * @return PHPExcel_Style_Color
+ */
+ public function setARGB($pValue = PHPExcel_Style_Color::COLOR_BLACK)
+ {
+ if ($pValue == '') {
+ $pValue = PHPExcel_Style_Color::COLOR_BLACK;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('argb' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->argb = $pValue;
+ }
+ return $this;
+ }
- /**
- * Set RGB
- *
- * @param string $pValue RGB value
- * @return PHPExcel_Style_Color
- */
- public function setRGB($pValue = '000000') {
- if ($pValue == '') {
- $pValue = '000000';
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_argb = 'FF' . $pValue;
- }
- return $this;
- }
+ /**
+ * Get RGB
+ *
+ * @return string
+ */
+ public function getRGB()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getRGB();
+ }
+ return substr($this->argb, 2);
+ }
- /**
- * Get a specified colour component of an RGB value
- *
- * @private
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param int $offset Position within the RGB value to extract
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The extracted colour component
- */
- private static function _getColourComponent($RGB,$offset,$hex=TRUE) {
- $colour = substr($RGB, $offset, 2);
- if (!$hex)
- $colour = hexdec($colour);
- return $colour;
- }
+ /**
+ * Set RGB
+ *
+ * @param string $pValue RGB value
+ * @return PHPExcel_Style_Color
+ */
+ public function setRGB($pValue = '000000')
+ {
+ if ($pValue == '') {
+ $pValue = '000000';
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->argb = 'FF' . $pValue;
+ }
+ return $this;
+ }
- /**
- * Get the red colour component of an RGB value
- *
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The red colour component
- */
- public static function getRed($RGB,$hex=TRUE) {
- return self::_getColourComponent($RGB, strlen($RGB) - 6, $hex);
- }
+ /**
+ * Get a specified colour component of an RGB value
+ *
+ * @private
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param int $offset Position within the RGB value to extract
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The extracted colour component
+ */
+ private static function getColourComponent($RGB, $offset, $hex = true)
+ {
+ $colour = substr($RGB, $offset, 2);
+ if (!$hex) {
+ $colour = hexdec($colour);
+ }
+ return $colour;
+ }
- /**
- * Get the green colour component of an RGB value
- *
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The green colour component
- */
- public static function getGreen($RGB,$hex=TRUE) {
- return self::_getColourComponent($RGB, strlen($RGB) - 4, $hex);
- }
+ /**
+ * Get the red colour component of an RGB value
+ *
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The red colour component
+ */
+ public static function getRed($RGB, $hex = true)
+ {
+ return self::getColourComponent($RGB, strlen($RGB) - 6, $hex);
+ }
- /**
- * Get the blue colour component of an RGB value
- *
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
- * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
- * decimal value
- * @return string The blue colour component
- */
- public static function getBlue($RGB,$hex=TRUE) {
- return self::_getColourComponent($RGB, strlen($RGB) - 2, $hex);
- }
+ /**
+ * Get the green colour component of an RGB value
+ *
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The green colour component
+ */
+ public static function getGreen($RGB, $hex = true)
+ {
+ return self::getColourComponent($RGB, strlen($RGB) - 4, $hex);
+ }
- /**
- * Adjust the brightness of a color
- *
- * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
- * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
- * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
- */
- public static function changeBrightness($hex, $adjustPercentage) {
- $rgba = (strlen($hex) == 8);
+ /**
+ * Get the blue colour component of an RGB value
+ *
+ * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param boolean $hex Flag indicating whether the component should be returned as a hex or a
+ * decimal value
+ * @return string The blue colour component
+ */
+ public static function getBlue($RGB, $hex = true)
+ {
+ return self::getColourComponent($RGB, strlen($RGB) - 2, $hex);
+ }
- $red = self::getRed($hex, FALSE);
- $green = self::getGreen($hex, FALSE);
- $blue = self::getBlue($hex, FALSE);
- if ($adjustPercentage > 0) {
- $red += (255 - $red) * $adjustPercentage;
- $green += (255 - $green) * $adjustPercentage;
- $blue += (255 - $blue) * $adjustPercentage;
- } else {
- $red += $red * $adjustPercentage;
- $green += $green * $adjustPercentage;
- $blue += $blue * $adjustPercentage;
- }
+ /**
+ * Adjust the brightness of a color
+ *
+ * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
+ * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
+ * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
+ */
+ public static function changeBrightness($hex, $adjustPercentage)
+ {
+ $rgba = (strlen($hex) == 8);
- if ($red < 0) $red = 0;
- elseif ($red > 255) $red = 255;
- if ($green < 0) $green = 0;
- elseif ($green > 255) $green = 255;
- if ($blue < 0) $blue = 0;
- elseif ($blue > 255) $blue = 255;
+ $red = self::getRed($hex, false);
+ $green = self::getGreen($hex, false);
+ $blue = self::getBlue($hex, false);
+ if ($adjustPercentage > 0) {
+ $red += (255 - $red) * $adjustPercentage;
+ $green += (255 - $green) * $adjustPercentage;
+ $blue += (255 - $blue) * $adjustPercentage;
+ } else {
+ $red += $red * $adjustPercentage;
+ $green += $green * $adjustPercentage;
+ $blue += $blue * $adjustPercentage;
+ }
- $rgb = strtoupper( str_pad(dechex($red), 2, '0', 0) .
- str_pad(dechex($green), 2, '0', 0) .
- str_pad(dechex($blue), 2, '0', 0)
- );
- return (($rgba) ? 'FF' : '') . $rgb;
- }
+ if ($red < 0) {
+ $red = 0;
+ } elseif ($red > 255) {
+ $red = 255;
+ }
+ if ($green < 0) {
+ $green = 0;
+ } elseif ($green > 255) {
+ $green = 255;
+ }
+ if ($blue < 0) {
+ $blue = 0;
+ } elseif ($blue > 255) {
+ $blue = 255;
+ }
- /**
- * Get indexed color
- *
- * @param int $pIndex Index entry point into the colour array
- * @param boolean $background Flag to indicate whether default background or foreground colour
- * should be returned if the indexed colour doesn't exist
- * @return PHPExcel_Style_Color
- */
- public static function indexedColor($pIndex, $background=FALSE) {
- // Clean parameter
- $pIndex = intval($pIndex);
+ $rgb = strtoupper(
+ str_pad(dechex($red), 2, '0', 0) .
+ str_pad(dechex($green), 2, '0', 0) .
+ str_pad(dechex($blue), 2, '0', 0)
+ );
+ return (($rgba) ? 'FF' : '') . $rgb;
+ }
- // Indexed colors
- if (is_null(self::$_indexedColors)) {
- self::$_indexedColors = array(
- 1 => 'FF000000', // System Colour #1 - Black
- 2 => 'FFFFFFFF', // System Colour #2 - White
- 3 => 'FFFF0000', // System Colour #3 - Red
- 4 => 'FF00FF00', // System Colour #4 - Green
- 5 => 'FF0000FF', // System Colour #5 - Blue
- 6 => 'FFFFFF00', // System Colour #6 - Yellow
- 7 => 'FFFF00FF', // System Colour #7- Magenta
- 8 => 'FF00FFFF', // System Colour #8- Cyan
- 9 => 'FF800000', // Standard Colour #9
- 10 => 'FF008000', // Standard Colour #10
- 11 => 'FF000080', // Standard Colour #11
- 12 => 'FF808000', // Standard Colour #12
- 13 => 'FF800080', // Standard Colour #13
- 14 => 'FF008080', // Standard Colour #14
- 15 => 'FFC0C0C0', // Standard Colour #15
- 16 => 'FF808080', // Standard Colour #16
- 17 => 'FF9999FF', // Chart Fill Colour #17
- 18 => 'FF993366', // Chart Fill Colour #18
- 19 => 'FFFFFFCC', // Chart Fill Colour #19
- 20 => 'FFCCFFFF', // Chart Fill Colour #20
- 21 => 'FF660066', // Chart Fill Colour #21
- 22 => 'FFFF8080', // Chart Fill Colour #22
- 23 => 'FF0066CC', // Chart Fill Colour #23
- 24 => 'FFCCCCFF', // Chart Fill Colour #24
- 25 => 'FF000080', // Chart Line Colour #25
- 26 => 'FFFF00FF', // Chart Line Colour #26
- 27 => 'FFFFFF00', // Chart Line Colour #27
- 28 => 'FF00FFFF', // Chart Line Colour #28
- 29 => 'FF800080', // Chart Line Colour #29
- 30 => 'FF800000', // Chart Line Colour #30
- 31 => 'FF008080', // Chart Line Colour #31
- 32 => 'FF0000FF', // Chart Line Colour #32
- 33 => 'FF00CCFF', // Standard Colour #33
- 34 => 'FFCCFFFF', // Standard Colour #34
- 35 => 'FFCCFFCC', // Standard Colour #35
- 36 => 'FFFFFF99', // Standard Colour #36
- 37 => 'FF99CCFF', // Standard Colour #37
- 38 => 'FFFF99CC', // Standard Colour #38
- 39 => 'FFCC99FF', // Standard Colour #39
- 40 => 'FFFFCC99', // Standard Colour #40
- 41 => 'FF3366FF', // Standard Colour #41
- 42 => 'FF33CCCC', // Standard Colour #42
- 43 => 'FF99CC00', // Standard Colour #43
- 44 => 'FFFFCC00', // Standard Colour #44
- 45 => 'FFFF9900', // Standard Colour #45
- 46 => 'FFFF6600', // Standard Colour #46
- 47 => 'FF666699', // Standard Colour #47
- 48 => 'FF969696', // Standard Colour #48
- 49 => 'FF003366', // Standard Colour #49
- 50 => 'FF339966', // Standard Colour #50
- 51 => 'FF003300', // Standard Colour #51
- 52 => 'FF333300', // Standard Colour #52
- 53 => 'FF993300', // Standard Colour #53
- 54 => 'FF993366', // Standard Colour #54
- 55 => 'FF333399', // Standard Colour #55
- 56 => 'FF333333' // Standard Colour #56
- );
- }
+ /**
+ * Get indexed color
+ *
+ * @param int $pIndex Index entry point into the colour array
+ * @param boolean $background Flag to indicate whether default background or foreground colour
+ * should be returned if the indexed colour doesn't exist
+ * @return PHPExcel_Style_Color
+ */
+ public static function indexedColor($pIndex, $background = false)
+ {
+ // Clean parameter
+ $pIndex = intval($pIndex);
- if (array_key_exists($pIndex, self::$_indexedColors)) {
- return new PHPExcel_Style_Color(self::$_indexedColors[$pIndex]);
- }
+ // Indexed colors
+ if (is_null(self::$indexedColors)) {
+ self::$indexedColors = array(
+ 1 => 'FF000000', // System Colour #1 - Black
+ 2 => 'FFFFFFFF', // System Colour #2 - White
+ 3 => 'FFFF0000', // System Colour #3 - Red
+ 4 => 'FF00FF00', // System Colour #4 - Green
+ 5 => 'FF0000FF', // System Colour #5 - Blue
+ 6 => 'FFFFFF00', // System Colour #6 - Yellow
+ 7 => 'FFFF00FF', // System Colour #7- Magenta
+ 8 => 'FF00FFFF', // System Colour #8- Cyan
+ 9 => 'FF800000', // Standard Colour #9
+ 10 => 'FF008000', // Standard Colour #10
+ 11 => 'FF000080', // Standard Colour #11
+ 12 => 'FF808000', // Standard Colour #12
+ 13 => 'FF800080', // Standard Colour #13
+ 14 => 'FF008080', // Standard Colour #14
+ 15 => 'FFC0C0C0', // Standard Colour #15
+ 16 => 'FF808080', // Standard Colour #16
+ 17 => 'FF9999FF', // Chart Fill Colour #17
+ 18 => 'FF993366', // Chart Fill Colour #18
+ 19 => 'FFFFFFCC', // Chart Fill Colour #19
+ 20 => 'FFCCFFFF', // Chart Fill Colour #20
+ 21 => 'FF660066', // Chart Fill Colour #21
+ 22 => 'FFFF8080', // Chart Fill Colour #22
+ 23 => 'FF0066CC', // Chart Fill Colour #23
+ 24 => 'FFCCCCFF', // Chart Fill Colour #24
+ 25 => 'FF000080', // Chart Line Colour #25
+ 26 => 'FFFF00FF', // Chart Line Colour #26
+ 27 => 'FFFFFF00', // Chart Line Colour #27
+ 28 => 'FF00FFFF', // Chart Line Colour #28
+ 29 => 'FF800080', // Chart Line Colour #29
+ 30 => 'FF800000', // Chart Line Colour #30
+ 31 => 'FF008080', // Chart Line Colour #31
+ 32 => 'FF0000FF', // Chart Line Colour #32
+ 33 => 'FF00CCFF', // Standard Colour #33
+ 34 => 'FFCCFFFF', // Standard Colour #34
+ 35 => 'FFCCFFCC', // Standard Colour #35
+ 36 => 'FFFFFF99', // Standard Colour #36
+ 37 => 'FF99CCFF', // Standard Colour #37
+ 38 => 'FFFF99CC', // Standard Colour #38
+ 39 => 'FFCC99FF', // Standard Colour #39
+ 40 => 'FFFFCC99', // Standard Colour #40
+ 41 => 'FF3366FF', // Standard Colour #41
+ 42 => 'FF33CCCC', // Standard Colour #42
+ 43 => 'FF99CC00', // Standard Colour #43
+ 44 => 'FFFFCC00', // Standard Colour #44
+ 45 => 'FFFF9900', // Standard Colour #45
+ 46 => 'FFFF6600', // Standard Colour #46
+ 47 => 'FF666699', // Standard Colour #47
+ 48 => 'FF969696', // Standard Colour #48
+ 49 => 'FF003366', // Standard Colour #49
+ 50 => 'FF339966', // Standard Colour #50
+ 51 => 'FF003300', // Standard Colour #51
+ 52 => 'FF333300', // Standard Colour #52
+ 53 => 'FF993300', // Standard Colour #53
+ 54 => 'FF993366', // Standard Colour #54
+ 55 => 'FF333399', // Standard Colour #55
+ 56 => 'FF333333' // Standard Colour #56
+ );
+ }
- if ($background) {
- return new PHPExcel_Style_Color('FFFFFFFF');
- }
- return new PHPExcel_Style_Color('FF000000');
- }
+ if (array_key_exists($pIndex, self::$indexedColors)) {
+ return new PHPExcel_Style_Color(self::$indexedColors[$pIndex]);
+ }
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_argb
- . __CLASS__
- );
- }
+ if ($background) {
+ return new PHPExcel_Style_Color(self::COLOR_WHITE);
+ }
+ return new PHPExcel_Style_Color(self::COLOR_BLACK);
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->argb .
+ __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Conditional.php b/Classes/PHPExcel/Style/Conditional.php
index 9573f5b78..331362b42 100644
--- a/Classes/PHPExcel/Style/Conditional.php
+++ b/Classes/PHPExcel/Style/Conditional.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,8 +20,8 @@
*
* @category PHPExcel
* @package PHPExcel_Style
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,76 +31,76 @@
*
* @category PHPExcel
* @package PHPExcel_Style
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Style_Conditional implements PHPExcel_IComparable
{
- /* Condition types */
- const CONDITION_NONE = 'none';
- const CONDITION_CELLIS = 'cellIs';
- const CONDITION_CONTAINSTEXT = 'containsText';
- const CONDITION_EXPRESSION = 'expression';
+ /* Condition types */
+ const CONDITION_NONE = 'none';
+ const CONDITION_CELLIS = 'cellIs';
+ const CONDITION_CONTAINSTEXT = 'containsText';
+ const CONDITION_EXPRESSION = 'expression';
- /* Operator types */
- const OPERATOR_NONE = '';
- const OPERATOR_BEGINSWITH = 'beginsWith';
- const OPERATOR_ENDSWITH = 'endsWith';
- const OPERATOR_EQUAL = 'equal';
- const OPERATOR_GREATERTHAN = 'greaterThan';
- const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
- const OPERATOR_LESSTHAN = 'lessThan';
- const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
- const OPERATOR_NOTEQUAL = 'notEqual';
- const OPERATOR_CONTAINSTEXT = 'containsText';
- const OPERATOR_NOTCONTAINS = 'notContains';
- const OPERATOR_BETWEEN = 'between';
+ /* Operator types */
+ const OPERATOR_NONE = '';
+ const OPERATOR_BEGINSWITH = 'beginsWith';
+ const OPERATOR_ENDSWITH = 'endsWith';
+ const OPERATOR_EQUAL = 'equal';
+ const OPERATOR_GREATERTHAN = 'greaterThan';
+ const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
+ const OPERATOR_LESSTHAN = 'lessThan';
+ const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
+ const OPERATOR_NOTEQUAL = 'notEqual';
+ const OPERATOR_CONTAINSTEXT = 'containsText';
+ const OPERATOR_NOTCONTAINS = 'notContains';
+ const OPERATOR_BETWEEN = 'between';
- /**
- * Condition type
- *
- * @var int
- */
- private $_conditionType;
+ /**
+ * Condition type
+ *
+ * @var int
+ */
+ private $conditionType;
- /**
- * Operator type
- *
- * @var int
- */
- private $_operatorType;
+ /**
+ * Operator type
+ *
+ * @var int
+ */
+ private $operatorType;
- /**
- * Text
- *
- * @var string
- */
- private $_text;
+ /**
+ * Text
+ *
+ * @var string
+ */
+ private $text;
- /**
- * Condition
- *
- * @var string[]
- */
- private $_condition = array();
+ /**
+ * Condition
+ *
+ * @var string[]
+ */
+ private $condition = array();
- /**
- * Style
- *
- * @var PHPExcel_Style
- */
- private $_style;
+ /**
+ * Style
+ *
+ * @var PHPExcel_Style
+ */
+ private $style;
/**
* Create a new PHPExcel_Style_Conditional
*/
public function __construct()
{
- // Initialise values
- $this->_conditionType = PHPExcel_Style_Conditional::CONDITION_NONE;
- $this->_operatorType = PHPExcel_Style_Conditional::OPERATOR_NONE;
- $this->_text = null;
- $this->_condition = array();
- $this->_style = new PHPExcel_Style(FALSE, TRUE);
+ // Initialise values
+ $this->conditionType = PHPExcel_Style_Conditional::CONDITION_NONE;
+ $this->operatorType = PHPExcel_Style_Conditional::OPERATOR_NONE;
+ $this->text = null;
+ $this->condition = array();
+ $this->style = new PHPExcel_Style(false, true);
}
/**
@@ -108,19 +108,21 @@ public function __construct()
*
* @return string
*/
- public function getConditionType() {
- return $this->_conditionType;
+ public function getConditionType()
+ {
+ return $this->conditionType;
}
/**
* Set Condition type
*
- * @param string $pValue PHPExcel_Style_Conditional condition type
+ * @param string $pValue PHPExcel_Style_Conditional condition type
* @return PHPExcel_Style_Conditional
*/
- public function setConditionType($pValue = PHPExcel_Style_Conditional::CONDITION_NONE) {
- $this->_conditionType = $pValue;
- return $this;
+ public function setConditionType($pValue = PHPExcel_Style_Conditional::CONDITION_NONE)
+ {
+ $this->conditionType = $pValue;
+ return $this;
}
/**
@@ -128,19 +130,21 @@ public function setConditionType($pValue = PHPExcel_Style_Conditional::CONDITION
*
* @return string
*/
- public function getOperatorType() {
- return $this->_operatorType;
+ public function getOperatorType()
+ {
+ return $this->operatorType;
}
/**
* Set Operator type
*
- * @param string $pValue PHPExcel_Style_Conditional operator type
+ * @param string $pValue PHPExcel_Style_Conditional operator type
* @return PHPExcel_Style_Conditional
*/
- public function setOperatorType($pValue = PHPExcel_Style_Conditional::OPERATOR_NONE) {
- $this->_operatorType = $pValue;
- return $this;
+ public function setOperatorType($pValue = PHPExcel_Style_Conditional::OPERATOR_NONE)
+ {
+ $this->operatorType = $pValue;
+ return $this;
}
/**
@@ -148,8 +152,9 @@ public function setOperatorType($pValue = PHPExcel_Style_Conditional::OPERATOR_N
*
* @return string
*/
- public function getText() {
- return $this->_text;
+ public function getText()
+ {
+ return $this->text;
}
/**
@@ -158,9 +163,10 @@ public function getText() {
* @param string $value
* @return PHPExcel_Style_Conditional
*/
- public function setText($value = null) {
- $this->_text = $value;
- return $this;
+ public function setText($value = null)
+ {
+ $this->text = $value;
+ return $this;
}
/**
@@ -169,26 +175,29 @@ public function setText($value = null) {
* @deprecated Deprecated, use getConditions instead
* @return string
*/
- public function getCondition() {
- if (isset($this->_condition[0])) {
- return $this->_condition[0];
- }
+ public function getCondition()
+ {
+ if (isset($this->condition[0])) {
+ return $this->condition[0];
+ }
- return '';
+ return '';
}
/**
* Set Condition
*
* @deprecated Deprecated, use setConditions instead
- * @param string $pValue Condition
+ * @param string $pValue Condition
* @return PHPExcel_Style_Conditional
*/
- public function setCondition($pValue = '') {
- if (!is_array($pValue))
- $pValue = array($pValue);
+ public function setCondition($pValue = '')
+ {
+ if (!is_array($pValue)) {
+ $pValue = array($pValue);
+ }
- return $this->setConditions($pValue);
+ return $this->setConditions($pValue);
}
/**
@@ -196,33 +205,36 @@ public function setCondition($pValue = '') {
*
* @return string[]
*/
- public function getConditions() {
- return $this->_condition;
+ public function getConditions()
+ {
+ return $this->condition;
}
/**
* Set Conditions
*
- * @param string[] $pValue Condition
+ * @param string[] $pValue Condition
* @return PHPExcel_Style_Conditional
*/
- public function setConditions($pValue) {
- if (!is_array($pValue))
- $pValue = array($pValue);
-
- $this->_condition = $pValue;
- return $this;
+ public function setConditions($pValue)
+ {
+ if (!is_array($pValue)) {
+ $pValue = array($pValue);
+ }
+ $this->condition = $pValue;
+ return $this;
}
/**
* Add Condition
*
- * @param string $pValue Condition
+ * @param string $pValue Condition
* @return PHPExcel_Style_Conditional
*/
- public function addCondition($pValue = '') {
- $this->_condition[] = $pValue;
- return $this;
+ public function addCondition($pValue = '')
+ {
+ $this->condition[] = $pValue;
+ return $this;
}
/**
@@ -230,48 +242,52 @@ public function addCondition($pValue = '') {
*
* @return PHPExcel_Style
*/
- public function getStyle() {
- return $this->_style;
+ public function getStyle()
+ {
+ return $this->style;
}
/**
* Set Style
*
- * @param PHPExcel_Style $pValue
- * @throws PHPExcel_Exception
+ * @param PHPExcel_Style $pValue
+ * @throws PHPExcel_Exception
* @return PHPExcel_Style_Conditional
*/
- public function setStyle(PHPExcel_Style $pValue = null) {
- $this->_style = $pValue;
- return $this;
+ public function setStyle(PHPExcel_Style $pValue = null)
+ {
+ $this->style = $pValue;
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_conditionType
- . $this->_operatorType
- . implode(';', $this->_condition)
- . $this->_style->getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ return md5(
+ $this->conditionType .
+ $this->operatorType .
+ implode(';', $this->condition) .
+ $this->style->getHashCode() .
+ __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Style/Fill.php b/Classes/PHPExcel/Style/Fill.php
index f76b0e9e8..26343ff5a 100644
--- a/Classes/PHPExcel/Style/Fill.php
+++ b/Classes/PHPExcel/Style/Fill.php
@@ -1,8 +1,9 @@
_fillType = NULL;
- }
- $this->_startColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_WHITE, $isSupervisor, $isConditional);
- $this->_endColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
+ /**
+ * Create a new PHPExcel_Style_Fill
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
- // bind parent if we are a supervisor
- if ($isSupervisor) {
- $this->_startColor->bindParent($this, '_startColor');
- $this->_endColor->bindParent($this, '_endColor');
- }
- }
+ // Initialise values
+ if ($isConditional) {
+ $this->fillType = null;
+ }
+ $this->startColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_WHITE, $isSupervisor, $isConditional);
+ $this->endColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_Fill
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getFill();
- }
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->startColor->bindParent($this, 'startColor');
+ $this->endColor->bindParent($this, 'endColor');
+ }
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('fill' => $array);
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Fill
+ */
+ public function getSharedComponent()
+ {
+ return $this->parent->getSharedComponent()->getFill();
+ }
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray(
- * array(
- * 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
- * 'rotation' => 0,
- * 'startcolor' => array(
- * 'rgb' => '000000'
- * ),
- * 'endcolor' => array(
- * 'argb' => 'FFFFFFFF'
- * )
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Fill
- */
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('type', $pStyles)) {
- $this->setFillType($pStyles['type']);
- }
- if (array_key_exists('rotation', $pStyles)) {
- $this->setRotation($pStyles['rotation']);
- }
- if (array_key_exists('startcolor', $pStyles)) {
- $this->getStartColor()->applyFromArray($pStyles['startcolor']);
- }
- if (array_key_exists('endcolor', $pStyles)) {
- $this->getEndColor()->applyFromArray($pStyles['endcolor']);
- }
- if (array_key_exists('color', $pStyles)) {
- $this->getStartColor()->applyFromArray($pStyles['color']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('fill' => $array);
+ }
- /**
- * Get Fill Type
- *
- * @return string
- */
- public function getFillType() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getFillType();
- }
- return $this->_fillType;
- }
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray(
+ * array(
+ * 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
+ * 'rotation' => 0,
+ * 'startcolor' => array(
+ * 'rgb' => '000000'
+ * ),
+ * 'endcolor' => array(
+ * 'argb' => 'FFFFFFFF'
+ * )
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Fill
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('type', $pStyles)) {
+ $this->setFillType($pStyles['type']);
+ }
+ if (array_key_exists('rotation', $pStyles)) {
+ $this->setRotation($pStyles['rotation']);
+ }
+ if (array_key_exists('startcolor', $pStyles)) {
+ $this->getStartColor()->applyFromArray($pStyles['startcolor']);
+ }
+ if (array_key_exists('endcolor', $pStyles)) {
+ $this->getEndColor()->applyFromArray($pStyles['endcolor']);
+ }
+ if (array_key_exists('color', $pStyles)) {
+ $this->getStartColor()->applyFromArray($pStyles['color']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
- /**
- * Set Fill Type
- *
- * @param string $pValue PHPExcel_Style_Fill fill type
- * @return PHPExcel_Style_Fill
- */
- public function setFillType($pValue = PHPExcel_Style_Fill::FILL_NONE) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('type' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_fillType = $pValue;
- }
- return $this;
- }
+ /**
+ * Get Fill Type
+ *
+ * @return string
+ */
+ public function getFillType()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getFillType();
+ }
+ return $this->fillType;
+ }
- /**
- * Get Rotation
- *
- * @return double
- */
- public function getRotation() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getRotation();
- }
- return $this->_rotation;
- }
+ /**
+ * Set Fill Type
+ *
+ * @param string $pValue PHPExcel_Style_Fill fill type
+ * @return PHPExcel_Style_Fill
+ */
+ public function setFillType($pValue = PHPExcel_Style_Fill::FILL_NONE)
+ {
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('type' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->fillType = $pValue;
+ }
+ return $this;
+ }
- /**
- * Set Rotation
- *
- * @param double $pValue
- * @return PHPExcel_Style_Fill
- */
- public function setRotation($pValue = 0) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('rotation' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_rotation = $pValue;
- }
- return $this;
- }
+ /**
+ * Get Rotation
+ *
+ * @return double
+ */
+ public function getRotation()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getRotation();
+ }
+ return $this->rotation;
+ }
- /**
- * Get Start Color
- *
- * @return PHPExcel_Style_Color
- */
- public function getStartColor() {
- return $this->_startColor;
- }
+ /**
+ * Set Rotation
+ *
+ * @param double $pValue
+ * @return PHPExcel_Style_Fill
+ */
+ public function setRotation($pValue = 0)
+ {
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('rotation' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->rotation = $pValue;
+ }
+ return $this;
+ }
- /**
- * Set Start Color
- *
- * @param PHPExcel_Style_Color $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Fill
- */
- public function setStartColor(PHPExcel_Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Get Start Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getStartColor()
+ {
+ return $this->startColor;
+ }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_startColor = $color;
- }
- return $this;
- }
+ /**
+ * Set Start Color
+ *
+ * @param PHPExcel_Style_Color $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Fill
+ */
+ public function setStartColor(PHPExcel_Style_Color $pValue = null)
+ {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- /**
- * Get End Color
- *
- * @return PHPExcel_Style_Color
- */
- public function getEndColor() {
- return $this->_endColor;
- }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->startColor = $color;
+ }
+ return $this;
+ }
- /**
- * Set End Color
- *
- * @param PHPExcel_Style_Color $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Fill
- */
- public function setEndColor(PHPExcel_Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ /**
+ * Get End Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getEndColor()
+ {
+ return $this->endColor;
+ }
- if ($this->_isSupervisor) {
- $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_endColor = $color;
- }
- return $this;
- }
+ /**
+ * Set End Color
+ *
+ * @param PHPExcel_Style_Color $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Fill
+ */
+ public function setEndColor(PHPExcel_Style_Color $pValue = null)
+ {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->getFillType()
- . $this->getRotation()
- . $this->getStartColor()->getHashCode()
- . $this->getEndColor()->getHashCode()
- . __CLASS__
- );
- }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->endColor = $color;
+ }
+ return $this;
+ }
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->getFillType() .
+ $this->getRotation() .
+ $this->getStartColor()->getHashCode() .
+ $this->getEndColor()->getHashCode() .
+ __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/Font.php b/Classes/PHPExcel/Style/Font.php
index a9f01fbc6..9566e1dfa 100644
--- a/Classes/PHPExcel/Style/Font.php
+++ b/Classes/PHPExcel/Style/Font.php
@@ -1,8 +1,9 @@
_name = NULL;
- $this->_size = NULL;
- $this->_bold = NULL;
- $this->_italic = NULL;
- $this->_superScript = NULL;
- $this->_subScript = NULL;
- $this->_underline = NULL;
- $this->_strikethrough = NULL;
- $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
- } else {
- $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor);
- }
- // bind parent if we are a supervisor
- if ($isSupervisor) {
- $this->_color->bindParent($this, '_color');
- }
- }
-
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_Font
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getFont();
- }
-
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('font' => $array);
- }
-
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray(
- * array(
- * 'name' => 'Arial',
- * 'bold' => TRUE,
- * 'italic' => FALSE,
- * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE,
- * 'strike' => FALSE,
- * 'color' => array(
- * 'rgb' => '808080'
- * )
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Font
- */
- public function applyFromArray($pStyles = null) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('name', $pStyles)) {
- $this->setName($pStyles['name']);
- }
- if (array_key_exists('bold', $pStyles)) {
- $this->setBold($pStyles['bold']);
- }
- if (array_key_exists('italic', $pStyles)) {
- $this->setItalic($pStyles['italic']);
- }
- if (array_key_exists('superScript', $pStyles)) {
- $this->setSuperScript($pStyles['superScript']);
- }
- if (array_key_exists('subScript', $pStyles)) {
- $this->setSubScript($pStyles['subScript']);
- }
- if (array_key_exists('underline', $pStyles)) {
- $this->setUnderline($pStyles['underline']);
- }
- if (array_key_exists('strike', $pStyles)) {
- $this->setStrikethrough($pStyles['strike']);
- }
- if (array_key_exists('color', $pStyles)) {
- $this->getColor()->applyFromArray($pStyles['color']);
- }
- if (array_key_exists('size', $pStyles)) {
- $this->setSize($pStyles['size']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
-
- /**
- * Get Name
- *
- * @return string
- */
- public function getName() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getName();
- }
- return $this->_name;
- }
-
- /**
- * Set Name
- *
- * @param string $pValue
- * @return PHPExcel_Style_Font
- */
- public function setName($pValue = 'Calibri') {
- if ($pValue == '') {
- $pValue = 'Calibri';
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('name' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_name = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Size
- *
- * @return double
- */
- public function getSize() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getSize();
- }
- return $this->_size;
- }
-
- /**
- * Set Size
- *
- * @param double $pValue
- * @return PHPExcel_Style_Font
- */
- public function setSize($pValue = 10) {
- if ($pValue == '') {
- $pValue = 10;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('size' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_size = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Bold
- *
- * @return boolean
- */
- public function getBold() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getBold();
- }
- return $this->_bold;
- }
-
- /**
- * Set Bold
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Font
- */
- public function setBold($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('bold' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_bold = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Italic
- *
- * @return boolean
- */
- public function getItalic() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getItalic();
- }
- return $this->_italic;
- }
-
- /**
- * Set Italic
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Font
- */
- public function setItalic($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('italic' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_italic = $pValue;
- }
- return $this;
- }
-
- /**
- * Get SuperScript
- *
- * @return boolean
- */
- public function getSuperScript() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getSuperScript();
- }
- return $this->_superScript;
- }
-
- /**
- * Set SuperScript
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Font
- */
- public function setSuperScript($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('superScript' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_superScript = $pValue;
- $this->_subScript = !$pValue;
- }
- return $this;
- }
-
- /**
- * Get SubScript
- *
- * @return boolean
- */
- public function getSubScript() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getSubScript();
- }
- return $this->_subScript;
- }
-
- /**
- * Set SubScript
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Font
- */
- public function setSubScript($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('subScript' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_subScript = $pValue;
- $this->_superScript = !$pValue;
- }
- return $this;
- }
-
- /**
- * Get Underline
- *
- * @return string
- */
- public function getUnderline() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getUnderline();
- }
- return $this->_underline;
- }
-
- /**
- * Set Underline
- *
- * @param string|boolean $pValue PHPExcel_Style_Font underline type
- * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
- * false equates to UNDERLINE_NONE
- * @return PHPExcel_Style_Font
- */
- public function setUnderline($pValue = self::UNDERLINE_NONE) {
- if (is_bool($pValue)) {
- $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
- } elseif ($pValue == '') {
- $pValue = self::UNDERLINE_NONE;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('underline' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_underline = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Strikethrough
- *
- * @return boolean
- */
- public function getStrikethrough() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getStrikethrough();
- }
- return $this->_strikethrough;
- }
-
- /**
- * Set Strikethrough
- *
- * @param boolean $pValue
- * @return PHPExcel_Style_Font
- */
- public function setStrikethrough($pValue = false) {
- if ($pValue == '') {
- $pValue = false;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('strike' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_strikethrough = $pValue;
- }
- return $this;
- }
-
- /**
- * Get Color
- *
- * @return PHPExcel_Style_Color
- */
- public function getColor() {
- return $this->_color;
- }
-
- /**
- * Set Color
- *
- * @param PHPExcel_Style_Color $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_Font
- */
- public function setColor(PHPExcel_Style_Color $pValue = null) {
- // make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
-
- if ($this->_isSupervisor) {
- $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_color = $color;
- }
- return $this;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_name
- . $this->_size
- . ($this->_bold ? 't' : 'f')
- . ($this->_italic ? 't' : 'f')
- . ($this->_superScript ? 't' : 'f')
- . ($this->_subScript ? 't' : 'f')
- . $this->_underline
- . ($this->_strikethrough ? 't' : 'f')
- . $this->_color->getHashCode()
- . __CLASS__
- );
- }
-
+ /* Underline types */
+ const UNDERLINE_NONE = 'none';
+ const UNDERLINE_DOUBLE = 'double';
+ const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting';
+ const UNDERLINE_SINGLE = 'single';
+ const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting';
+
+ /**
+ * Font Name
+ *
+ * @var string
+ */
+ protected $name = 'Calibri';
+
+ /**
+ * Font Size
+ *
+ * @var float
+ */
+ protected $size = 11;
+
+ /**
+ * Bold
+ *
+ * @var boolean
+ */
+ protected $bold = false;
+
+ /**
+ * Italic
+ *
+ * @var boolean
+ */
+ protected $italic = false;
+
+ /**
+ * Superscript
+ *
+ * @var boolean
+ */
+ protected $superScript = false;
+
+ /**
+ * Subscript
+ *
+ * @var boolean
+ */
+ protected $subScript = false;
+
+ /**
+ * Underline
+ *
+ * @var string
+ */
+ protected $underline = self::UNDERLINE_NONE;
+
+ /**
+ * Strikethrough
+ *
+ * @var boolean
+ */
+ protected $strikethrough = false;
+
+ /**
+ * Foreground color
+ *
+ * @var PHPExcel_Style_Color
+ */
+ protected $color;
+
+ /**
+ * Create a new PHPExcel_Style_Font
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
+
+ // Initialise values
+ if ($isConditional) {
+ $this->name = null;
+ $this->size = null;
+ $this->bold = null;
+ $this->italic = null;
+ $this->superScript = null;
+ $this->subScript = null;
+ $this->underline = null;
+ $this->strikethrough = null;
+ $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional);
+ } else {
+ $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor);
+ }
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->color->bindParent($this, 'color');
+ }
+ }
+
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Font
+ */
+ public function getSharedComponent()
+ {
+ return $this->parent->getSharedComponent()->getFont();
+ }
+
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('font' => $array);
+ }
+
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray(
+ * array(
+ * 'name' => 'Arial',
+ * 'bold' => TRUE,
+ * 'italic' => FALSE,
+ * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE,
+ * 'strike' => FALSE,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Font
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('name', $pStyles)) {
+ $this->setName($pStyles['name']);
+ }
+ if (array_key_exists('bold', $pStyles)) {
+ $this->setBold($pStyles['bold']);
+ }
+ if (array_key_exists('italic', $pStyles)) {
+ $this->setItalic($pStyles['italic']);
+ }
+ if (array_key_exists('superScript', $pStyles)) {
+ $this->setSuperScript($pStyles['superScript']);
+ }
+ if (array_key_exists('subScript', $pStyles)) {
+ $this->setSubScript($pStyles['subScript']);
+ }
+ if (array_key_exists('underline', $pStyles)) {
+ $this->setUnderline($pStyles['underline']);
+ }
+ if (array_key_exists('strike', $pStyles)) {
+ $this->setStrikethrough($pStyles['strike']);
+ }
+ if (array_key_exists('color', $pStyles)) {
+ $this->getColor()->applyFromArray($pStyles['color']);
+ }
+ if (array_key_exists('size', $pStyles)) {
+ $this->setSize($pStyles['size']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
+
+ /**
+ * Get Name
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getName();
+ }
+ return $this->name;
+ }
+
+ /**
+ * Set Name
+ *
+ * @param string $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setName($pValue = 'Calibri')
+ {
+ if ($pValue == '') {
+ $pValue = 'Calibri';
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('name' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->name = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Size
+ *
+ * @return double
+ */
+ public function getSize()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getSize();
+ }
+ return $this->size;
+ }
+
+ /**
+ * Set Size
+ *
+ * @param double $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setSize($pValue = 10)
+ {
+ if ($pValue == '') {
+ $pValue = 10;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('size' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->size = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Bold
+ *
+ * @return boolean
+ */
+ public function getBold()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getBold();
+ }
+ return $this->bold;
+ }
+
+ /**
+ * Set Bold
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setBold($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('bold' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->bold = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Italic
+ *
+ * @return boolean
+ */
+ public function getItalic()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getItalic();
+ }
+ return $this->italic;
+ }
+
+ /**
+ * Set Italic
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setItalic($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('italic' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->italic = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get SuperScript
+ *
+ * @return boolean
+ */
+ public function getSuperScript()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getSuperScript();
+ }
+ return $this->superScript;
+ }
+
+ /**
+ * Set SuperScript
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setSuperScript($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('superScript' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->superScript = $pValue;
+ $this->subScript = !$pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get SubScript
+ *
+ * @return boolean
+ */
+ public function getSubScript()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getSubScript();
+ }
+ return $this->subScript;
+ }
+
+ /**
+ * Set SubScript
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setSubScript($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('subScript' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->subScript = $pValue;
+ $this->superScript = !$pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Underline
+ *
+ * @return string
+ */
+ public function getUnderline()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getUnderline();
+ }
+ return $this->underline;
+ }
+
+ /**
+ * Set Underline
+ *
+ * @param string|boolean $pValue PHPExcel_Style_Font underline type
+ * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
+ * false equates to UNDERLINE_NONE
+ * @return PHPExcel_Style_Font
+ */
+ public function setUnderline($pValue = self::UNDERLINE_NONE)
+ {
+ if (is_bool($pValue)) {
+ $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
+ } elseif ($pValue == '') {
+ $pValue = self::UNDERLINE_NONE;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('underline' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->underline = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Strikethrough
+ *
+ * @return boolean
+ */
+ public function getStrikethrough()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getStrikethrough();
+ }
+ return $this->strikethrough;
+ }
+
+ /**
+ * Set Strikethrough
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Style_Font
+ */
+ public function setStrikethrough($pValue = false)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('strike' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->strikethrough = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getColor()
+ {
+ return $this->color;
+ }
+
+ /**
+ * Set Color
+ *
+ * @param PHPExcel_Style_Color $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Font
+ */
+ public function setColor(PHPExcel_Style_Color $pValue = null)
+ {
+ // make sure parameter is a real color and not a supervisor
+ $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+
+ if ($this->isSupervisor) {
+ $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->color = $color;
+ }
+ return $this;
+ }
+
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->name .
+ $this->size .
+ ($this->bold ? 't' : 'f') .
+ ($this->italic ? 't' : 'f') .
+ ($this->superScript ? 't' : 'f') .
+ ($this->subScript ? 't' : 'f') .
+ $this->underline .
+ ($this->strikethrough ? 't' : 'f') .
+ $this->color->getHashCode() .
+ __CLASS__
+ );
+ }
}
diff --git a/Classes/PHPExcel/Style/NumberFormat.php b/Classes/PHPExcel/Style/NumberFormat.php
index ed6ace90c..1b72cda92 100644
--- a/Classes/PHPExcel/Style/NumberFormat.php
+++ b/Classes/PHPExcel/Style/NumberFormat.php
@@ -1,8 +1,9 @@
_formatCode = NULL;
- }
- }
-
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_NumberFormat
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getNumberFormat();
- }
-
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('numberformat' => $array);
- }
-
- /**
- * Apply styles from array
- *
- *
- * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
- * array(
- * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
- * )
- * );
- *
- *
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
- * @return PHPExcel_Style_NumberFormat
- */
- public function applyFromArray($pStyles = null)
- {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (array_key_exists('code', $pStyles)) {
- $this->setFormatCode($pStyles['code']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
-
- /**
- * Get Format Code
- *
- * @return string
- */
- public function getFormatCode()
- {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getFormatCode();
- }
- if ($this->_builtInFormatCode !== false)
- {
- return self::builtInFormatCode($this->_builtInFormatCode);
- }
- return $this->_formatCode;
- }
-
- /**
- * Set Format Code
- *
- * @param string $pValue
- * @return PHPExcel_Style_NumberFormat
- */
- public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL)
- {
- if ($pValue == '') {
- $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
- }
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('code' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_formatCode = $pValue;
- $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue);
- }
- return $this;
- }
-
- /**
- * Get Built-In Format Code
- *
- * @return int
- */
- public function getBuiltInFormatCode()
- {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getBuiltInFormatCode();
- }
- return $this->_builtInFormatCode;
- }
-
- /**
- * Set Built-In Format Code
- *
- * @param int $pValue
- * @return PHPExcel_Style_NumberFormat
- */
- public function setBuiltInFormatCode($pValue = 0)
- {
-
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_builtInFormatCode = $pValue;
- $this->_formatCode = self::builtInFormatCode($pValue);
- }
- return $this;
- }
-
- /**
- * Fill built-in format codes
- */
- private static function fillBuiltInFormatCodes()
- {
- // Built-in format codes
- if (is_null(self::$_builtInFormats)) {
- self::$_builtInFormats = array();
-
- // General
- self::$_builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
- self::$_builtInFormats[1] = '0';
- self::$_builtInFormats[2] = '0.00';
- self::$_builtInFormats[3] = '#,##0';
- self::$_builtInFormats[4] = '#,##0.00';
-
- self::$_builtInFormats[9] = '0%';
- self::$_builtInFormats[10] = '0.00%';
- self::$_builtInFormats[11] = '0.00E+00';
- self::$_builtInFormats[12] = '# ?/?';
- self::$_builtInFormats[13] = '# ??/??';
- self::$_builtInFormats[14] = 'mm-dd-yy';
- self::$_builtInFormats[15] = 'd-mmm-yy';
- self::$_builtInFormats[16] = 'd-mmm';
- self::$_builtInFormats[17] = 'mmm-yy';
- self::$_builtInFormats[18] = 'h:mm AM/PM';
- self::$_builtInFormats[19] = 'h:mm:ss AM/PM';
- self::$_builtInFormats[20] = 'h:mm';
- self::$_builtInFormats[21] = 'h:mm:ss';
- self::$_builtInFormats[22] = 'm/d/yy h:mm';
-
- self::$_builtInFormats[37] = '#,##0 ;(#,##0)';
- self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)';
- self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)';
- self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)';
-
- self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
- self::$_builtInFormats[45] = 'mm:ss';
- self::$_builtInFormats[46] = '[h]:mm:ss';
- self::$_builtInFormats[47] = 'mmss.0';
- self::$_builtInFormats[48] = '##0.0E+0';
- self::$_builtInFormats[49] = '@';
-
- // CHT
- self::$_builtInFormats[27] = '[$-404]e/m/d';
- self::$_builtInFormats[30] = 'm/d/yy';
- self::$_builtInFormats[36] = '[$-404]e/m/d';
- self::$_builtInFormats[50] = '[$-404]e/m/d';
- self::$_builtInFormats[57] = '[$-404]e/m/d';
-
- // THA
- self::$_builtInFormats[59] = 't0';
- self::$_builtInFormats[60] = 't0.00';
- self::$_builtInFormats[61] = 't#,##0';
- self::$_builtInFormats[62] = 't#,##0.00';
- self::$_builtInFormats[67] = 't0%';
- self::$_builtInFormats[68] = 't0.00%';
- self::$_builtInFormats[69] = 't# ?/?';
- self::$_builtInFormats[70] = 't# ??/??';
-
- // Flip array (for faster lookups)
- self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats);
- }
- }
-
- /**
- * Get built-in format code
- *
- * @param int $pIndex
- * @return string
- */
- public static function builtInFormatCode($pIndex)
- {
- // Clean parameter
- $pIndex = intval($pIndex);
-
- // Ensure built-in format codes are available
- self::fillBuiltInFormatCodes();
-
- // Lookup format code
- if (isset(self::$_builtInFormats[$pIndex])) {
- return self::$_builtInFormats[$pIndex];
- }
-
- return '';
- }
-
- /**
- * Get built-in format code index
- *
- * @param string $formatCode
- * @return int|boolean
- */
- public static function builtInFormatCodeIndex($formatCode)
- {
- // Ensure built-in format codes are available
- self::fillBuiltInFormatCodes();
-
- // Lookup format code
- if (isset(self::$_flippedBuiltInFormats[$formatCode])) {
- return self::$_flippedBuiltInFormats[$formatCode];
- }
-
- return false;
- }
-
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode()
- {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_formatCode
- . $this->_builtInFormatCode
- . __CLASS__
- );
- }
-
- /**
- * Search/replace values to convert Excel date/time format masks to PHP format masks
- *
- * @var array
- */
- private static $_dateFormatReplacements = array(
- // first remove escapes related to non-format characters
- '\\' => '',
- // 12-hour suffix
- 'am/pm' => 'A',
- // 4-digit year
- 'e' => 'Y',
- 'yyyy' => 'Y',
- // 2-digit year
- 'yy' => 'y',
- // first letter of month - no php equivalent
- 'mmmmm' => 'M',
- // full month name
- 'mmmm' => 'F',
- // short month name
- 'mmm' => 'M',
- // mm is minutes if time, but can also be month w/leading zero
- // so we try to identify times be the inclusion of a : separator in the mask
- // It isn't perfect, but the best way I know how
- ':mm' => ':i',
- 'mm:' => 'i:',
- // month leading zero
- 'mm' => 'm',
- // month no leading zero
- 'm' => 'n',
- // full day of week name
- 'dddd' => 'l',
- // short day of week name
- 'ddd' => 'D',
- // days leading zero
- 'dd' => 'd',
- // days no leading zero
- 'd' => 'j',
- // seconds
- 'ss' => 's',
- // fractional seconds - no php equivalent
- '.s' => ''
- );
- /**
- * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
- *
- * @var array
- */
- private static $_dateFormatReplacements24 = array(
- 'hh' => 'H',
- 'h' => 'G'
- );
- /**
- * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
- *
- * @var array
- */
- private static $_dateFormatReplacements12 = array(
- 'hh' => 'h',
- 'h' => 'g'
- );
-
- /**
- * Convert a value in a pre-defined format to a PHP string
- *
- * @param mixed $value Value to format
- * @param string $format Format code
- * @param array $callBack Callback function for additional formatting of string
- * @return string Formatted string
- */
- public static function toFormattedString($value = '', $format = '', $callBack = null)
- {
- // For now we do not treat strings although section 4 of a format code affects strings
- if (!is_numeric($value)) return $value;
-
- // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
- // it seems to round numbers to a total of 10 digits.
- if (($format === PHPExcel_Style_NumberFormat::FORMAT_GENERAL) || ($format === PHPExcel_Style_NumberFormat::FORMAT_TEXT)) {
- return $value;
- }
-
- // Get the sections, there can be up to four sections
- $sections = explode(';', $format);
-
- // Fetch the relevant section depending on whether number is positive, negative, or zero?
- // Text not supported yet.
- // Here is how the sections apply to various values in Excel:
- // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
- // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
- // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
- // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
- switch (count($sections)) {
- case 1:
- $format = $sections[0];
- break;
-
- case 2:
- $format = ($value >= 0) ? $sections[0] : $sections[1];
- $value = abs($value); // Use the absolute value
- break;
-
- case 3:
- $format = ($value > 0) ?
- $sections[0] : ( ($value < 0) ?
- $sections[1] : $sections[2]);
- $value = abs($value); // Use the absolute value
- break;
-
- case 4:
- $format = ($value > 0) ?
- $sections[0] : ( ($value < 0) ?
- $sections[1] : $sections[2]);
- $value = abs($value); // Use the absolute value
- break;
-
- default:
- // something is wrong, just use first section
- $format = $sections[0];
- break;
- }
-
- // Save format with color information for later use below
- $formatColor = $format;
-
- // Strip color information
- $color_regex = '/^\\[[a-zA-Z]+\\]/';
- $format = preg_replace($color_regex, '', $format);
-
- // Let's begin inspecting the format and converting the value to a formatted string
- if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $format)) { // datetime format
- // dvc: convert Excel formats to PHP date formats
-
- // strip off first part containing e.g. [$-F800] or [$USD-409]
- // general syntax: [$
';
- if ($value != (int)$value) {
- $sign = ($value < 0) ? '-' : '';
-
- $integerPart = floor(abs($value));
- $decimalPart = trim(fmod(abs($value),1),'0.');
- $decimalLength = strlen($decimalPart);
- $decimalDivisor = pow(10,$decimalLength);
-
- $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart,$decimalDivisor);
-
- $adjustedDecimalPart = $decimalPart/$GCD;
- $adjustedDecimalDivisor = $decimalDivisor/$GCD;
-
- if ((strpos($format,'0') !== false) || (strpos($format,'#') !== false) || (substr($format,0,3) == '? ?')) {
- if ($integerPart == 0) { $integerPart = ''; }
- $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
- } else {
- $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
- $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
- }
- }
-
- } else {
- // Handle the number itself
-
- // scale number
- $value = $value / $scale;
-
- // Strip #
- $format = preg_replace('/\\#/', '', $format);
-
- $n = "/\[[^\]]+\]/";
- $m = preg_replace($n, '', $format);
- $number_regex = "/(0+)(\.?)(0*)/";
- if (preg_match($number_regex, $m, $matches)) {
- $left = $matches[1];
- $dec = $matches[2];
- $right = $matches[3];
-
- // minimun width of formatted number (including dot)
- $minWidth = strlen($left) + strlen($dec) + strlen($right);
-
- if ($useThousands) {
- $value = number_format(
- $value
- , strlen($right)
- , PHPExcel_Shared_String::getDecimalSeparator()
- , PHPExcel_Shared_String::getThousandsSeparator()
- );
- } else {
- $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
- $value = sprintf($sprintf_pattern, $value);
- }
-
- $value = preg_replace($number_regex, $value, $format);
- }
- }
- if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
- // Currency or Accounting
- $currencyFormat = $m[0];
- $currencyCode = $m[1];
- list($currencyCode) = explode('-',$currencyCode);
- if ($currencyCode == '') {
- $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
- }
- $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value);
- }
- }
- }
-
- // Additional formatting provided by callback function
- if ($callBack !== null) {
- list($writerInstance, $function) = $callBack;
- $value = $writerInstance->$function($value, $formatColor);
- }
-
- return $value;
- }
-
+ /* Pre-defined formats */
+ const FORMAT_GENERAL = 'General';
+
+ const FORMAT_TEXT = '@';
+
+ const FORMAT_NUMBER = '0';
+ const FORMAT_NUMBER_00 = '0.00';
+ const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
+ const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
+
+ const FORMAT_PERCENTAGE = '0%';
+ const FORMAT_PERCENTAGE_00 = '0.00%';
+
+ const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
+ const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
+ const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
+ const FORMAT_DATE_DMYSLASH = 'd/m/y';
+ const FORMAT_DATE_DMYMINUS = 'd-m-y';
+ const FORMAT_DATE_DMMINUS = 'd-m';
+ const FORMAT_DATE_MYMINUS = 'm-y';
+ const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
+ const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
+ const FORMAT_DATE_XLSX16 = 'd-mmm';
+ const FORMAT_DATE_XLSX17 = 'mmm-yy';
+ const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
+ const FORMAT_DATE_DATETIME = 'd/m/y h:mm';
+ const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
+ const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
+ const FORMAT_DATE_TIME3 = 'h:mm';
+ const FORMAT_DATE_TIME4 = 'h:mm:ss';
+ const FORMAT_DATE_TIME5 = 'mm:ss';
+ const FORMAT_DATE_TIME6 = 'h:mm:ss';
+ const FORMAT_DATE_TIME7 = 'i:s.S';
+ const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
+ const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
+
+ const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
+ const FORMAT_CURRENCY_USD = '$#,##0_-';
+ const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-';
+
+ /**
+ * Excel built-in number formats
+ *
+ * @var array
+ */
+ protected static $builtInFormats;
+
+ /**
+ * Excel built-in number formats (flipped, for faster lookups)
+ *
+ * @var array
+ */
+ protected static $flippedBuiltInFormats;
+
+ /**
+ * Format Code
+ *
+ * @var string
+ */
+ protected $formatCode = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
+
+ /**
+ * Built-in format Code
+ *
+ * @var string
+ */
+ protected $builtInFormatCode = 0;
+
+ /**
+ * Create a new PHPExcel_Style_NumberFormat
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ * @param boolean $isConditional Flag indicating if this is a conditional style or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false, $isConditional = false)
+ {
+ // Supervisor?
+ parent::__construct($isSupervisor);
+
+ if ($isConditional) {
+ $this->formatCode = null;
+ $this->builtInFormatCode = false;
+ }
+ }
+
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_NumberFormat
+ */
+ public function getSharedComponent()
+ {
+ return $this->parent->getSharedComponent()->getNumberFormat();
+ }
+
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('numberformat' => $array);
+ }
+
+ /**
+ * Apply styles from array
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
+ * array(
+ * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_NumberFormat
+ */
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (array_key_exists('code', $pStyles)) {
+ $this->setFormatCode($pStyles['code']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
+
+ /**
+ * Get Format Code
+ *
+ * @return string
+ */
+ public function getFormatCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getFormatCode();
+ }
+ if ($this->builtInFormatCode !== false) {
+ return self::builtInFormatCode($this->builtInFormatCode);
+ }
+ return $this->formatCode;
+ }
+
+ /**
+ * Set Format Code
+ *
+ * @param string $pValue
+ * @return PHPExcel_Style_NumberFormat
+ */
+ public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL)
+ {
+ if ($pValue == '') {
+ $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
+ }
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('code' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->formatCode = $pValue;
+ $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue);
+ }
+ return $this;
+ }
+
+ /**
+ * Get Built-In Format Code
+ *
+ * @return int
+ */
+ public function getBuiltInFormatCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getBuiltInFormatCode();
+ }
+ return $this->builtInFormatCode;
+ }
+
+ /**
+ * Set Built-In Format Code
+ *
+ * @param int $pValue
+ * @return PHPExcel_Style_NumberFormat
+ */
+ public function setBuiltInFormatCode($pValue = 0)
+ {
+
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->builtInFormatCode = $pValue;
+ $this->formatCode = self::builtInFormatCode($pValue);
+ }
+ return $this;
+ }
+
+ /**
+ * Fill built-in format codes
+ */
+ private static function fillBuiltInFormatCodes()
+ {
+ // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance]
+ // 18.8.30. numFmt (Number Format)
+ //
+ // The ECMA standard defines built-in format IDs
+ // 14: "mm-dd-yy"
+ // 22: "m/d/yy h:mm"
+ // 37: "#,##0 ;(#,##0)"
+ // 38: "#,##0 ;[Red](#,##0)"
+ // 39: "#,##0.00;(#,##0.00)"
+ // 40: "#,##0.00;[Red](#,##0.00)"
+ // 47: "mmss.0"
+ // KOR fmt 55: "yyyy-mm-dd"
+ // Excel defines built-in format IDs
+ // 14: "m/d/yyyy"
+ // 22: "m/d/yyyy h:mm"
+ // 37: "#,##0_);(#,##0)"
+ // 38: "#,##0_);[Red](#,##0)"
+ // 39: "#,##0.00_);(#,##0.00)"
+ // 40: "#,##0.00_);[Red](#,##0.00)"
+ // 47: "mm:ss.0"
+ // KOR fmt 55: "yyyy/mm/dd"
+
+ // Built-in format codes
+ if (is_null(self::$builtInFormats)) {
+ self::$builtInFormats = array();
+
+ // General
+ self::$builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
+ self::$builtInFormats[1] = '0';
+ self::$builtInFormats[2] = '0.00';
+ self::$builtInFormats[3] = '#,##0';
+ self::$builtInFormats[4] = '#,##0.00';
+
+ self::$builtInFormats[9] = '0%';
+ self::$builtInFormats[10] = '0.00%';
+ self::$builtInFormats[11] = '0.00E+00';
+ self::$builtInFormats[12] = '# ?/?';
+ self::$builtInFormats[13] = '# ??/??';
+ self::$builtInFormats[14] = 'm/d/yyyy'; // Despite ECMA 'mm-dd-yy';
+ self::$builtInFormats[15] = 'd-mmm-yy';
+ self::$builtInFormats[16] = 'd-mmm';
+ self::$builtInFormats[17] = 'mmm-yy';
+ self::$builtInFormats[18] = 'h:mm AM/PM';
+ self::$builtInFormats[19] = 'h:mm:ss AM/PM';
+ self::$builtInFormats[20] = 'h:mm';
+ self::$builtInFormats[21] = 'h:mm:ss';
+ self::$builtInFormats[22] = 'm/d/yyyy h:mm'; // Despite ECMA 'm/d/yy h:mm';
+
+ self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)';
+ self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)';
+ self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)';
+ self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)';
+
+ self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
+ self::$builtInFormats[45] = 'mm:ss';
+ self::$builtInFormats[46] = '[h]:mm:ss';
+ self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0';
+ self::$builtInFormats[48] = '##0.0E+0';
+ self::$builtInFormats[49] = '@';
+
+ // CHT
+ self::$builtInFormats[27] = '[$-404]e/m/d';
+ self::$builtInFormats[30] = 'm/d/yy';
+ self::$builtInFormats[36] = '[$-404]e/m/d';
+ self::$builtInFormats[50] = '[$-404]e/m/d';
+ self::$builtInFormats[57] = '[$-404]e/m/d';
+
+ // THA
+ self::$builtInFormats[59] = 't0';
+ self::$builtInFormats[60] = 't0.00';
+ self::$builtInFormats[61] = 't#,##0';
+ self::$builtInFormats[62] = 't#,##0.00';
+ self::$builtInFormats[67] = 't0%';
+ self::$builtInFormats[68] = 't0.00%';
+ self::$builtInFormats[69] = 't# ?/?';
+ self::$builtInFormats[70] = 't# ??/??';
+
+ // Flip array (for faster lookups)
+ self::$flippedBuiltInFormats = array_flip(self::$builtInFormats);
+ }
+ }
+
+ /**
+ * Get built-in format code
+ *
+ * @param int $pIndex
+ * @return string
+ */
+ public static function builtInFormatCode($pIndex)
+ {
+ // Clean parameter
+ $pIndex = intval($pIndex);
+
+ // Ensure built-in format codes are available
+ self::fillBuiltInFormatCodes();
+ // Lookup format code
+ if (isset(self::$builtInFormats[$pIndex])) {
+ return self::$builtInFormats[$pIndex];
+ }
+
+ return '';
+ }
+
+ /**
+ * Get built-in format code index
+ *
+ * @param string $formatCode
+ * @return int|boolean
+ */
+ public static function builtInFormatCodeIndex($formatCode)
+ {
+ // Ensure built-in format codes are available
+ self::fillBuiltInFormatCodes();
+
+ // Lookup format code
+ if (isset(self::$flippedBuiltInFormats[$formatCode])) {
+ return self::$flippedBuiltInFormats[$formatCode];
+ }
+
+ return false;
+ }
+
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->formatCode .
+ $this->builtInFormatCode .
+ __CLASS__
+ );
+ }
+
+ /**
+ * Search/replace values to convert Excel date/time format masks to PHP format masks
+ *
+ * @var array
+ */
+ private static $dateFormatReplacements = array(
+ // first remove escapes related to non-format characters
+ '\\' => '',
+ // 12-hour suffix
+ 'am/pm' => 'A',
+ // 4-digit year
+ 'e' => 'Y',
+ 'yyyy' => 'Y',
+ // 2-digit year
+ 'yy' => 'y',
+ // first letter of month - no php equivalent
+ 'mmmmm' => 'M',
+ // full month name
+ 'mmmm' => 'F',
+ // short month name
+ 'mmm' => 'M',
+ // mm is minutes if time, but can also be month w/leading zero
+ // so we try to identify times be the inclusion of a : separator in the mask
+ // It isn't perfect, but the best way I know how
+ ':mm' => ':i',
+ 'mm:' => 'i:',
+ // month leading zero
+ 'mm' => 'm',
+ // month no leading zero
+ 'm' => 'n',
+ // full day of week name
+ 'dddd' => 'l',
+ // short day of week name
+ 'ddd' => 'D',
+ // days leading zero
+ 'dd' => 'd',
+ // days no leading zero
+ 'd' => 'j',
+ // seconds
+ 'ss' => 's',
+ // fractional seconds - no php equivalent
+ '.s' => ''
+ );
+ /**
+ * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
+ *
+ * @var array
+ */
+ private static $dateFormatReplacements24 = array(
+ 'hh' => 'H',
+ 'h' => 'G'
+ );
+ /**
+ * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
+ *
+ * @var array
+ */
+ private static $dateFormatReplacements12 = array(
+ 'hh' => 'h',
+ 'h' => 'g'
+ );
+
+ private static function setLowercaseCallback($matches) {
+ return mb_strtolower($matches[0]);
+ }
+
+ private static function escapeQuotesCallback($matches) {
+ return '\\' . implode('\\', str_split($matches[1]));
+ }
+
+ private static function formatAsDate(&$value, &$format)
+ {
+ // strip off first part containing e.g. [$-F800] or [$USD-409]
+ // general syntax: [$
';
+ if ($value != (int)$value) {
+ self::formatAsFraction($value, $format);
+ }
+
+ } else {
+ // Handle the number itself
+
+ // scale number
+ $value = $value / $scale;
+
+ // Strip #
+ $format = preg_replace('/\\#/', '0', $format);
+
+ $n = "/\[[^\]]+\]/";
+ $m = preg_replace($n, '', $format);
+ $number_regex = "/(0+)(\.?)(0*)/";
+ if (preg_match($number_regex, $m, $matches)) {
+ $left = $matches[1];
+ $dec = $matches[2];
+ $right = $matches[3];
+
+ // minimun width of formatted number (including dot)
+ $minWidth = strlen($left) + strlen($dec) + strlen($right);
+ if ($useThousands) {
+ $value = number_format(
+ $value,
+ strlen($right),
+ PHPExcel_Shared_String::getDecimalSeparator(),
+ PHPExcel_Shared_String::getThousandsSeparator()
+ );
+ $value = preg_replace($number_regex, $value, $format);
+ } else {
+ if (preg_match('/[0#]E[+-]0/i', $format)) {
+ // Scientific format
+ $value = sprintf('%5.2E', $value);
+ } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
+ $value = self::complexNumberFormatMask($value, $format);
+ } else {
+ $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
+ $value = sprintf($sprintf_pattern, $value);
+ $value = preg_replace($number_regex, $value, $format);
+ }
+ }
+ }
+ }
+ if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
+ // Currency or Accounting
+ $currencyFormat = $m[0];
+ $currencyCode = $m[1];
+ list($currencyCode) = explode('-', $currencyCode);
+ if ($currencyCode == '') {
+ $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
+ }
+ $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value);
+ }
+ }
+ }
+
+ // Escape any escaped slashes to a single slash
+ $format = preg_replace("/\\\\/u", '\\', $format);
+
+ // Additional formatting provided by callback function
+ if ($callBack !== null) {
+ list($writerInstance, $function) = $callBack;
+ $value = $writerInstance->$function($value, $formatColor);
+ }
+
+ return $value;
+ }
}
diff --git a/Classes/PHPExcel/Style/Protection.php b/Classes/PHPExcel/Style/Protection.php
index 67e0bdd2f..d5568f655 100644
--- a/Classes/PHPExcel/Style/Protection.php
+++ b/Classes/PHPExcel/Style/Protection.php
@@ -1,8 +1,9 @@
_locked = self::PROTECTION_INHERIT;
- $this->_hidden = self::PROTECTION_INHERIT;
- }
+ // Initialise values
+ if (!$isConditional) {
+ $this->locked = self::PROTECTION_INHERIT;
+ $this->hidden = self::PROTECTION_INHERIT;
+ }
}
- /**
- * Get the shared style component for the currently active cell in currently active sheet.
- * Only used for style supervisor
- *
- * @return PHPExcel_Style_Protection
- */
- public function getSharedComponent()
- {
- return $this->_parent->getSharedComponent()->getProtection();
- }
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor
+ *
+ * @return PHPExcel_Style_Protection
+ */
+ public function getSharedComponent()
+ {
+ return $this->parent->getSharedComponent()->getProtection();
+ }
- /**
- * Build style array from subcomponents
- *
- * @param array $array
- * @return array
- */
- public function getStyleArray($array)
- {
- return array('protection' => $array);
- }
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('protection' => $array);
+ }
/**
* Apply styles from array
*
*
* $objPHPExcel->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray(
- * array(
- * 'locked' => TRUE,
- * 'hidden' => FALSE
- * )
+ * array(
+ * 'locked' => TRUE,
+ * 'hidden' => FALSE
+ * )
* );
*
*
- * @param array $pStyles Array containing style information
- * @throws PHPExcel_Exception
+ * @param array $pStyles Array containing style information
+ * @throws PHPExcel_Exception
* @return PHPExcel_Style_Protection
*/
- public function applyFromArray($pStyles = NULL) {
- if (is_array($pStyles)) {
- if ($this->_isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
- } else {
- if (isset($pStyles['locked'])) {
- $this->setLocked($pStyles['locked']);
- }
- if (isset($pStyles['hidden'])) {
- $this->setHidden($pStyles['hidden']);
- }
- }
- } else {
- throw new PHPExcel_Exception("Invalid style array passed.");
- }
- return $this;
- }
+ public function applyFromArray($pStyles = null)
+ {
+ if (is_array($pStyles)) {
+ if ($this->isSupervisor) {
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ } else {
+ if (isset($pStyles['locked'])) {
+ $this->setLocked($pStyles['locked']);
+ }
+ if (isset($pStyles['hidden'])) {
+ $this->setHidden($pStyles['hidden']);
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
/**
* Get locked
*
* @return string
*/
- public function getLocked() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getLocked();
- }
- return $this->_locked;
+ public function getLocked()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getLocked();
+ }
+ return $this->locked;
}
/**
@@ -150,14 +144,15 @@ public function getLocked() {
* @param string $pValue
* @return PHPExcel_Style_Protection
*/
- public function setLocked($pValue = self::PROTECTION_INHERIT) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('locked' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_locked = $pValue;
- }
- return $this;
+ public function setLocked($pValue = self::PROTECTION_INHERIT)
+ {
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('locked' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->locked = $pValue;
+ }
+ return $this;
}
/**
@@ -165,11 +160,12 @@ public function setLocked($pValue = self::PROTECTION_INHERIT) {
*
* @return string
*/
- public function getHidden() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHidden();
- }
- return $this->_hidden;
+ public function getHidden()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHidden();
+ }
+ return $this->hidden;
}
/**
@@ -178,30 +174,31 @@ public function getHidden() {
* @param string $pValue
* @return PHPExcel_Style_Protection
*/
- public function setHidden($pValue = self::PROTECTION_INHERIT) {
- if ($this->_isSupervisor) {
- $styleArray = $this->getStyleArray(array('hidden' => $pValue));
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
- } else {
- $this->_hidden = $pValue;
- }
- return $this;
+ public function setHidden($pValue = self::PROTECTION_INHERIT)
+ {
+ if ($this->isSupervisor) {
+ $styleArray = $this->getStyleArray(array('hidden' => $pValue));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->hidden = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- if ($this->_isSupervisor) {
- return $this->getSharedComponent()->getHashCode();
- }
- return md5(
- $this->_locked
- . $this->_hidden
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->getHashCode();
+ }
+ return md5(
+ $this->locked .
+ $this->hidden .
+ __CLASS__
+ );
}
-
}
diff --git a/Classes/PHPExcel/Style/Supervisor.php b/Classes/PHPExcel/Style/Supervisor.php
index e91f22521..a90e1c6a9 100644
--- a/Classes/PHPExcel/Style/Supervisor.php
+++ b/Classes/PHPExcel/Style/Supervisor.php
@@ -1,8 +1,9 @@
_isSupervisor = $isSupervisor;
- }
+ /**
+ * Create a new PHPExcel_Style_Alignment
+ *
+ * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
+ * Leave this value at default unless you understand exactly what
+ * its ramifications are
+ */
+ public function __construct($isSupervisor = false)
+ {
+ // Supervisor?
+ $this->isSupervisor = $isSupervisor;
+ }
- /**
- * Bind parent. Only used for supervisor
- *
- * @param PHPExcel $parent
- * @return PHPExcel_Style_Supervisor
- */
- public function bindParent($parent, $parentPropertyName=NULL)
- {
- $this->_parent = $parent;
- return $this;
- }
+ /**
+ * Bind parent. Only used for supervisor
+ *
+ * @param PHPExcel $parent
+ * @return PHPExcel_Style_Supervisor
+ */
+ public function bindParent($parent, $parentPropertyName = null)
+ {
+ $this->parent = $parent;
+ return $this;
+ }
- /**
- * Is this a supervisor or a cell style component?
- *
- * @return boolean
- */
- public function getIsSupervisor()
- {
- return $this->_isSupervisor;
- }
+ /**
+ * Is this a supervisor or a cell style component?
+ *
+ * @return boolean
+ */
+ public function getIsSupervisor()
+ {
+ return $this->isSupervisor;
+ }
- /**
- * Get the currently active sheet. Only used for supervisor
- *
- * @return PHPExcel_Worksheet
- */
- public function getActiveSheet()
- {
- return $this->_parent->getActiveSheet();
- }
+ /**
+ * Get the currently active sheet. Only used for supervisor
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function getActiveSheet()
+ {
+ return $this->parent->getActiveSheet();
+ }
- /**
- * Get the currently active cell coordinate in currently active sheet.
- * Only used for supervisor
- *
- * @return string E.g. 'A1'
- */
- public function getSelectedCells()
- {
- return $this->getActiveSheet()->getSelectedCells();
- }
+ /**
+ * Get the currently active cell coordinate in currently active sheet.
+ * Only used for supervisor
+ *
+ * @return string E.g. 'A1'
+ */
+ public function getSelectedCells()
+ {
+ return $this->getActiveSheet()->getSelectedCells();
+ }
- /**
- * Get the currently active cell coordinate in currently active sheet.
- * Only used for supervisor
- *
- * @return string E.g. 'A1'
- */
- public function getActiveCell()
- {
- return $this->getActiveSheet()->getActiveCell();
- }
+ /**
+ * Get the currently active cell coordinate in currently active sheet.
+ * Only used for supervisor
+ *
+ * @return string E.g. 'A1'
+ */
+ public function getActiveCell()
+ {
+ return $this->getActiveSheet()->getActiveCell();
+ }
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if ((is_object($value)) && ($key != '_parent')) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if ((is_object($value)) && ($key != 'parent')) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet.php b/Classes/PHPExcel/Worksheet.php
index 738d1674d..483aa0021 100644
--- a/Classes/PHPExcel/Worksheet.php
+++ b/Classes/PHPExcel/Worksheet.php
@@ -1,8 +1,9 @@
_parent = $pParent;
- $this->setTitle($pTitle, FALSE);
+ $this->parent = $pParent;
+ $this->setTitle($pTitle, false);
+ // setTitle can change $pTitle
+ $this->setCodeName($this->getTitle());
$this->setSheetState(PHPExcel_Worksheet::SHEETSTATE_VISIBLE);
- $this->_cellCollection = PHPExcel_CachedObjectStorageFactory::getInstance($this);
-
+ $this->cellCollection = PHPExcel_CachedObjectStorageFactory::getInstance($this);
// Set page setup
- $this->_pageSetup = new PHPExcel_Worksheet_PageSetup();
-
+ $this->pageSetup = new PHPExcel_Worksheet_PageSetup();
// Set page margins
- $this->_pageMargins = new PHPExcel_Worksheet_PageMargins();
-
+ $this->pageMargins = new PHPExcel_Worksheet_PageMargins();
// Set page header/footer
- $this->_headerFooter = new PHPExcel_Worksheet_HeaderFooter();
-
+ $this->headerFooter = new PHPExcel_Worksheet_HeaderFooter();
// Set sheet view
- $this->_sheetView = new PHPExcel_Worksheet_SheetView();
-
+ $this->sheetView = new PHPExcel_Worksheet_SheetView();
// Drawing collection
- $this->_drawingCollection = new ArrayObject();
-
+ $this->drawingCollection = new ArrayObject();
// Chart collection
- $this->_chartCollection = new ArrayObject();
-
+ $this->chartCollection = new ArrayObject();
// Protection
- $this->_protection = new PHPExcel_Worksheet_Protection();
-
+ $this->protection = new PHPExcel_Worksheet_Protection();
// Default row dimension
- $this->_defaultRowDimension = new PHPExcel_Worksheet_RowDimension(null);
-
+ $this->defaultRowDimension = new PHPExcel_Worksheet_RowDimension(null);
// Default column dimension
- $this->_defaultColumnDimension = new PHPExcel_Worksheet_ColumnDimension(null);
-
- $this->_autoFilter = new PHPExcel_Worksheet_AutoFilter(null, $this);
+ $this->defaultColumnDimension = new PHPExcel_Worksheet_ColumnDimension(null);
+ $this->autoFilter = new PHPExcel_Worksheet_AutoFilter(null, $this);
}
@@ -378,23 +369,24 @@ public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet')
*/
public function disconnectCells()
{
- if ( $this->_cellCollection != null ){
- $this->_cellCollection->unsetWorksheetCells();
- $this->_cellCollection = null;
- }
+ if ($this->cellCollection !== null) {
+ $this->cellCollection->unsetWorksheetCells();
+ $this->cellCollection = null;
+ }
// detach ourself from the workbook, so that it can then delete this worksheet successfully
- $this->_parent = null;
+ $this->parent = null;
}
/**
* Code to execute when this worksheet is unset()
*
*/
- function __destruct() {
- if ($this->_cellCollection !== null) {
- $this->disconnectCells();
- }
- }
+ public function __destruct()
+ {
+ PHPExcel_Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
+
+ $this->disconnectCells();
+ }
/**
* Return the cache controller for the cell collection
@@ -403,8 +395,8 @@ function __destruct() {
*/
public function getCellCacheController()
{
- return $this->_cellCollection;
- } // function getCellCacheController()
+ return $this->cellCollection;
+ }
/**
@@ -414,20 +406,48 @@ public function getCellCacheController()
*/
public static function getInvalidCharacters()
{
- return self::$_invalidCharacters;
+ return self::$invalidCharacters;
}
/**
+ * Check sheet code name for valid Excel syntax
+ *
+ * @param string $pValue The string to check
+ * @return string The valid string
+ * @throws Exception
+ */
+ private static function checkSheetCodeName($pValue)
+ {
+ $CharCount = PHPExcel_Shared_String::CountCharacters($pValue);
+ if ($CharCount == 0) {
+ throw new PHPExcel_Exception('Sheet code name cannot be empty.');
+ }
+ // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'"
+ if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) ||
+ (PHPExcel_Shared_String::Substring($pValue, -1, 1)=='\'') ||
+ (PHPExcel_Shared_String::Substring($pValue, 0, 1)=='\'')) {
+ throw new PHPExcel_Exception('Invalid character found in sheet code name');
+ }
+
+ // Maximum 31 characters allowed for sheet title
+ if ($CharCount > 31) {
+ throw new PHPExcel_Exception('Maximum 31 characters allowed in sheet code name.');
+ }
+
+ return $pValue;
+ }
+
+ /**
* Check sheet title for valid Excel syntax
*
* @param string $pValue The string to check
* @return string The valid string
* @throws PHPExcel_Exception
*/
- private static function _checkSheetTitle($pValue)
+ private static function checkSheetTitle($pValue)
{
// Some of the printable ASCII characters are invalid: * : / \ ? [ ]
- if (str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) {
+ if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) {
throw new PHPExcel_Exception('Invalid character found in sheet title');
}
@@ -451,8 +471,8 @@ public function getCellCollection($pSorted = true)
// Re-order cell collection
return $this->sortCellCollection();
}
- if ($this->_cellCollection !== null) {
- return $this->_cellCollection->getCellList();
+ if ($this->cellCollection !== null) {
+ return $this->cellCollection->getCellList();
}
return array();
}
@@ -464,8 +484,8 @@ public function getCellCollection($pSorted = true)
*/
public function sortCellCollection()
{
- if ($this->_cellCollection !== null) {
- return $this->_cellCollection->getSortedCellList();
+ if ($this->cellCollection !== null) {
+ return $this->cellCollection->getSortedCellList();
}
return array();
}
@@ -477,7 +497,7 @@ public function sortCellCollection()
*/
public function getRowDimensions()
{
- return $this->_rowDimensions;
+ return $this->rowDimensions;
}
/**
@@ -487,7 +507,7 @@ public function getRowDimensions()
*/
public function getDefaultRowDimension()
{
- return $this->_defaultRowDimension;
+ return $this->defaultRowDimension;
}
/**
@@ -497,7 +517,7 @@ public function getDefaultRowDimension()
*/
public function getColumnDimensions()
{
- return $this->_columnDimensions;
+ return $this->columnDimensions;
}
/**
@@ -507,7 +527,7 @@ public function getColumnDimensions()
*/
public function getDefaultColumnDimension()
{
- return $this->_defaultColumnDimension;
+ return $this->defaultColumnDimension;
}
/**
@@ -517,7 +537,7 @@ public function getDefaultColumnDimension()
*/
public function getDrawingCollection()
{
- return $this->_drawingCollection;
+ return $this->drawingCollection;
}
/**
@@ -527,7 +547,7 @@ public function getDrawingCollection()
*/
public function getChartCollection()
{
- return $this->_chartCollection;
+ return $this->chartCollection;
}
/**
@@ -541,10 +561,10 @@ public function addChart(PHPExcel_Chart $pChart = null, $iChartIndex = null)
{
$pChart->setWorksheet($this);
if (is_null($iChartIndex)) {
- $this->_chartCollection[] = $pChart;
+ $this->chartCollection[] = $pChart;
} else {
// Insert the chart at the requested index
- array_splice($this->_chartCollection, $iChartIndex, 0, array($pChart));
+ array_splice($this->chartCollection, $iChartIndex, 0, array($pChart));
}
return $pChart;
@@ -557,7 +577,7 @@ public function addChart(PHPExcel_Chart $pChart = null, $iChartIndex = null)
*/
public function getChartCount()
{
- return count($this->_chartCollection);
+ return count($this->chartCollection);
}
/**
@@ -569,18 +589,18 @@ public function getChartCount()
*/
public function getChartByIndex($index = null)
{
- $chartCount = count($this->_chartCollection);
+ $chartCount = count($this->chartCollection);
if ($chartCount == 0) {
return false;
}
if (is_null($index)) {
$index = --$chartCount;
}
- if (!isset($this->_chartCollection[$index])) {
+ if (!isset($this->chartCollection[$index])) {
return false;
}
- return $this->_chartCollection[$index];
+ return $this->chartCollection[$index];
}
/**
@@ -592,7 +612,7 @@ public function getChartByIndex($index = null)
public function getChartNames()
{
$chartNames = array();
- foreach($this->_chartCollection as $chart) {
+ foreach ($this->chartCollection as $chart) {
$chartNames[] = $chart->getName();
}
return $chartNames;
@@ -607,13 +627,13 @@ public function getChartNames()
*/
public function getChartByName($chartName = '')
{
- $chartCount = count($this->_chartCollection);
+ $chartCount = count($this->chartCollection);
if ($chartCount == 0) {
return false;
}
- foreach($this->_chartCollection as $index => $chart) {
+ foreach ($this->chartCollection as $index => $chart) {
if ($chart->getName() == $chartName) {
- return $this->_chartCollection[$index];
+ return $this->chartCollection[$index];
}
}
return false;
@@ -633,7 +653,7 @@ public function refreshColumnDimensions()
$newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
}
- $this->_columnDimensions = $newColumnDimensions;
+ $this->columnDimensions = $newColumnDimensions;
return $this;
}
@@ -652,7 +672,7 @@ public function refreshRowDimensions()
$newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
}
- $this->_rowDimensions = $newRowDimensions;
+ $this->rowDimensions = $newRowDimensions;
return $this;
}
@@ -697,7 +717,6 @@ public function calculateColumnWidths($calculateMergeCells = false)
// There is only something to do if there are some auto-size columns
if (!empty($autoSizes)) {
-
// build list of cells references that participate in a merge
$isMergeCell = array();
foreach ($this->getMergeCells() as $cells) {
@@ -708,18 +727,19 @@ public function calculateColumnWidths($calculateMergeCells = false)
// loop through all cells in the worksheet
foreach ($this->getCellCollection(false) as $cellID) {
- $cell = $this->getCell($cellID);
- if (isset($autoSizes[$cell->getColumn()])) {
+ $cell = $this->getCell($cellID, false);
+ if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
// Determine width if cell does not participate in a merge
- if (!isset($isMergeCell[$cell->getCoordinate()])) {
+ if (!isset($isMergeCell[$this->cellCollection->getCurrentAddress()])) {
// Calculated value
- $cellValue = $cell->getCalculatedValue();
-
// To formatted string
- $cellValue = PHPExcel_Style_NumberFormat::toFormattedString($cellValue, $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode());
+ $cellValue = PHPExcel_Style_NumberFormat::toFormattedString(
+ $cell->getCalculatedValue(),
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
+ );
- $autoSizes[$cell->getColumn()] = max(
- (float)$autoSizes[$cell->getColumn()],
+ $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
+ (float) $autoSizes[$this->cellCollection->getCurrentColumn()],
(float)PHPExcel_Shared_Font::calculateColumnWidth(
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
$cellValue,
@@ -733,7 +753,9 @@ public function calculateColumnWidths($calculateMergeCells = false)
// adjust column widths
foreach ($autoSizes as $columnIndex => $width) {
- if ($width == -1) $width = $this->getDefaultColumnDimension()->getWidth();
+ if ($width == -1) {
+ $width = $this->getDefaultColumnDimension()->getWidth();
+ }
$this->getColumnDimension($columnIndex)->setWidth($width);
}
}
@@ -748,7 +770,7 @@ public function calculateColumnWidths($calculateMergeCells = false)
*/
public function getParent()
{
- return $this->_parent;
+ return $this->parent;
}
/**
@@ -759,15 +781,17 @@ public function getParent()
*/
public function rebindParent(PHPExcel $parent)
{
- $namedRanges = $this->_parent->getNamedRanges();
- foreach ($namedRanges as $namedRange) {
- $parent->addNamedRange($namedRange);
- }
+ if ($this->parent !== null) {
+ $namedRanges = $this->parent->getNamedRanges();
+ foreach ($namedRanges as $namedRange) {
+ $parent->addNamedRange($namedRange);
+ }
- $this->_parent->removeSheetByIndex(
- $this->_parent->getIndex($this)
- );
- $this->_parent = $parent;
+ $this->parent->removeSheetByIndex(
+ $this->parent->getIndex($this)
+ );
+ }
+ $this->parent = $parent;
return $this;
}
@@ -779,7 +803,7 @@ public function rebindParent(PHPExcel $parent)
*/
public function getTitle()
{
- return $this->_title;
+ return $this->title;
}
/**
@@ -787,11 +811,10 @@ public function getTitle()
*
* @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.
+ * 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)
@@ -802,47 +825,50 @@ public function setTitle($pValue = 'Worksheet', $updateFormulaCellReferences = t
}
// Syntax check
- self::_checkSheetTitle($pValue);
+ self::checkSheetTitle($pValue);
// Old title
$oldTitle = $this->getTitle();
- if ($this->getParent()) {
+ if ($this->parent) {
// Is there already such sheet name?
- if ($this->getParent()->sheetNameExists($pValue)) {
+ 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);
+ $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 29);
}
$i = 1;
- while ($this->getParent()->sheetNameExists($pValue . ' ' . $i)) {
+ 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);
+ $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);
+ $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 27);
}
}
}
$altTitle = $pValue . ' ' . $i;
- return $this->setTitle($altTitle,$updateFormulaCellReferences);
+ return $this->setTitle($altTitle, $updateFormulaCellReferences);
}
}
// Set title
- $this->_title = $pValue;
- $this->_dirty = true;
+ $this->title = $pValue;
+ $this->dirty = true;
- if ($this->getParent()) {
+ if ($this->parent && $this->parent->getCalculationEngine()) {
// New title
$newTitle = $this->getTitle();
- if ($updateFormulaCellReferences)
- PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->getParent(), $oldTitle, $newTitle);
+ $this->parent->getCalculationEngine()
+ ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
+ if ($updateFormulaCellReferences) {
+ PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle);
+ }
}
return $this;
@@ -855,7 +881,7 @@ public function setTitle($pValue = 'Worksheet', $updateFormulaCellReferences = t
*/
public function getSheetState()
{
- return $this->_sheetState;
+ return $this->sheetState;
}
/**
@@ -866,7 +892,7 @@ public function getSheetState()
*/
public function setSheetState($value = PHPExcel_Worksheet::SHEETSTATE_VISIBLE)
{
- $this->_sheetState = $value;
+ $this->sheetState = $value;
return $this;
}
@@ -877,7 +903,7 @@ public function setSheetState($value = PHPExcel_Worksheet::SHEETSTATE_VISIBLE)
*/
public function getPageSetup()
{
- return $this->_pageSetup;
+ return $this->pageSetup;
}
/**
@@ -888,7 +914,7 @@ public function getPageSetup()
*/
public function setPageSetup(PHPExcel_Worksheet_PageSetup $pValue)
{
- $this->_pageSetup = $pValue;
+ $this->pageSetup = $pValue;
return $this;
}
@@ -899,7 +925,7 @@ public function setPageSetup(PHPExcel_Worksheet_PageSetup $pValue)
*/
public function getPageMargins()
{
- return $this->_pageMargins;
+ return $this->pageMargins;
}
/**
@@ -910,7 +936,7 @@ public function getPageMargins()
*/
public function setPageMargins(PHPExcel_Worksheet_PageMargins $pValue)
{
- $this->_pageMargins = $pValue;
+ $this->pageMargins = $pValue;
return $this;
}
@@ -921,7 +947,7 @@ public function setPageMargins(PHPExcel_Worksheet_PageMargins $pValue)
*/
public function getHeaderFooter()
{
- return $this->_headerFooter;
+ return $this->headerFooter;
}
/**
@@ -932,7 +958,7 @@ public function getHeaderFooter()
*/
public function setHeaderFooter(PHPExcel_Worksheet_HeaderFooter $pValue)
{
- $this->_headerFooter = $pValue;
+ $this->headerFooter = $pValue;
return $this;
}
@@ -943,7 +969,7 @@ public function setHeaderFooter(PHPExcel_Worksheet_HeaderFooter $pValue)
*/
public function getSheetView()
{
- return $this->_sheetView;
+ return $this->sheetView;
}
/**
@@ -954,7 +980,7 @@ public function getSheetView()
*/
public function setSheetView(PHPExcel_Worksheet_SheetView $pValue)
{
- $this->_sheetView = $pValue;
+ $this->sheetView = $pValue;
return $this;
}
@@ -965,7 +991,7 @@ public function setSheetView(PHPExcel_Worksheet_SheetView $pValue)
*/
public function getProtection()
{
- return $this->_protection;
+ return $this->protection;
}
/**
@@ -976,8 +1002,8 @@ public function getProtection()
*/
public function setProtection(PHPExcel_Worksheet_Protection $pValue)
{
- $this->_protection = $pValue;
- $this->_dirty = true;
+ $this->protection = $pValue;
+ $this->dirty = true;
return $this;
}
@@ -985,41 +1011,55 @@ public function setProtection(PHPExcel_Worksheet_Protection $pValue)
/**
* Get highest worksheet column
*
+ * @param string $row Return the data highest column for the specified row,
+ * or the highest column of any row if no row number is passed
* @return string Highest column name
*/
- public function getHighestColumn()
+ public function getHighestColumn($row = null)
{
- return $this->_cachedHighestColumn;
+ if ($row == null) {
+ return $this->cachedHighestColumn;
+ }
+ return $this->getHighestDataColumn($row);
}
/**
* Get highest worksheet column that contains data
*
+ * @param string $row Return the highest data column for the specified row,
+ * or the highest data column of any row if no row number is passed
* @return string Highest column name that contains data
*/
- public function getHighestDataColumn()
+ public function getHighestDataColumn($row = null)
{
- return $this->_cellCollection->getHighestColumn();
+ return $this->cellCollection->getHighestColumn($row);
}
/**
* Get highest worksheet row
*
+ * @param string $column Return the highest data row for the specified column,
+ * or the highest row of any column if no column letter is passed
* @return int Highest row number
*/
- public function getHighestRow()
+ public function getHighestRow($column = null)
{
- return $this->_cachedHighestRow;
+ if ($column == null) {
+ return $this->cachedHighestRow;
+ }
+ return $this->getHighestDataRow($column);
}
/**
* Get highest worksheet row that contains data
*
+ * @param string $column Return the highest data row for the specified column,
+ * or the highest data row of any column if no column letter is passed
* @return string Highest row number that contains data
*/
- public function getHighestDataRow()
+ public function getHighestDataRow($column = null)
{
- return $this->_cellCollection->getHighestRow();
+ return $this->cellCollection->getHighestRow($column);
}
/**
@@ -1029,7 +1069,7 @@ public function getHighestDataRow()
*/
public function getHighestRowAndColumn()
{
- return $this->_cellCollection->getHighestRowAndColumn();
+ return $this->cellCollection->getHighestRowAndColumn();
}
/**
@@ -1042,7 +1082,7 @@ public function getHighestRowAndColumn()
*/
public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell = false)
{
- $cell = $this->getCell($pCoordinate)->setValue($pValue);
+ $cell = $this->getCell(strtoupper($pCoordinate))->setValue($pValue);
return ($returnCell) ? $cell : $this;
}
@@ -1057,7 +1097,7 @@ public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell =
*/
public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $returnCell = false)
{
- $cell = $this->getCell(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow)->setValue($pValue);
+ $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValue($pValue);
return ($returnCell) ? $cell : $this;
}
@@ -1073,7 +1113,7 @@ public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = nu
public function setCellValueExplicit($pCoordinate = 'A1', $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false)
{
// Set value
- $cell = $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
+ $cell = $this->getCell(strtoupper($pCoordinate))->setValueExplicit($pValue, $pDataType);
return ($returnCell) ? $cell : $this;
}
@@ -1089,7 +1129,7 @@ public function setCellValueExplicit($pCoordinate = 'A1', $pValue = null, $pData
*/
public function setCellValueExplicitByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false)
{
- $cell = $this->getCell(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow)->setValueExplicit($pValue, $pDataType);
+ $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValueExplicit($pValue, $pDataType);
return ($returnCell) ? $cell : $this;
}
@@ -1097,20 +1137,22 @@ public function setCellValueExplicitByColumnAndRow($pColumn = 0, $pRow = 1, $pVa
* Get cell at a specific coordinate
*
* @param string $pCoordinate Coordinate of the cell
+ * @param boolean $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
+ * already exist, or a null should be returned instead
* @throws PHPExcel_Exception
- * @return PHPExcel_Cell Cell that was found
+ * @return null|PHPExcel_Cell Cell that was found/created or null
*/
- public function getCell($pCoordinate = 'A1')
+ public function getCell($pCoordinate = 'A1', $createIfNotExists = true)
{
// Check cell collection
- if ($this->_cellCollection->isDataSet($pCoordinate)) {
- return $this->_cellCollection->getCacheData($pCoordinate);
+ if ($this->cellCollection->isDataSet(strtoupper($pCoordinate))) {
+ return $this->cellCollection->getCacheData($pCoordinate);
}
// Worksheet reference?
if (strpos($pCoordinate, '!') !== false) {
$worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true);
- return $this->getParent()->getSheetByName($worksheetReference[0])->getCell($worksheetReference[1]);
+ return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists);
}
// Named range?
@@ -1119,79 +1161,84 @@ public function getCell($pCoordinate = 'A1')
$namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this);
if ($namedRange !== null) {
$pCoordinate = $namedRange->getRange();
- return $namedRange->getWorksheet()->getCell($pCoordinate);
+ return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists);
}
}
// Uppercase coordinate
$pCoordinate = strtoupper($pCoordinate);
- if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
+ if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) {
throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.');
- } elseif (strpos($pCoordinate,'$') !== false) {
+ } elseif (strpos($pCoordinate, '$') !== false) {
throw new PHPExcel_Exception('Cell coordinate must not be absolute.');
- } else {
- // Create new cell object
-
- // Coordinates
- $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate);
-
- $cell = $this->_cellCollection->addCacheData($pCoordinate,new PHPExcel_Cell($pCoordinate, null, PHPExcel_Cell_DataType::TYPE_NULL, $this));
- $this->_cellCollectionIsSorted = false;
-
- if (PHPExcel_Cell::columnIndexFromString($this->_cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($aCoordinates[0]))
- $this->_cachedHighestColumn = $aCoordinates[0];
-
- $this->_cachedHighestRow = max($this->_cachedHighestRow,$aCoordinates[1]);
-
- // Cell needs appropriate xfIndex
- $rowDimensions = $this->getRowDimensions();
- $columnDimensions = $this->getColumnDimensions();
-
- if ( isset($rowDimensions[$aCoordinates[1]]) && $rowDimensions[$aCoordinates[1]]->getXfIndex() !== null ) {
- // then there is a row dimension with explicit style, assign it to the cell
- $cell->setXfIndex($rowDimensions[$aCoordinates[1]]->getXfIndex());
- } else if ( isset($columnDimensions[$aCoordinates[0]]) ) {
- // then there is a column dimension, assign it to the cell
- $cell->setXfIndex($columnDimensions[$aCoordinates[0]]->getXfIndex());
- } else {
- // set to default index
- $cell->setXfIndex(0);
- }
-
- return $cell;
}
+
+ // Create new cell object, if required
+ return $createIfNotExists ? $this->createNewCell($pCoordinate) : null;
}
/**
* Get cell at a specific coordinate by using numeric cell coordinates
*
- * @param string $pColumn Numeric column coordinate of the cell
+ * @param string $pColumn Numeric column coordinate of the cell (starting from 0)
* @param string $pRow Numeric row coordinate of the cell
- * @return PHPExcel_Cell Cell that was found
+ * @param boolean $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
+ * already exist, or a null should be returned instead
+ * @return null|PHPExcel_Cell Cell that was found/created or null
*/
- public function getCellByColumnAndRow($pColumn = 0, $pRow = 1)
+ public function getCellByColumnAndRow($pColumn = 0, $pRow = 1, $createIfNotExists = true)
{
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($pColumn);
$coordinate = $columnLetter . $pRow;
- if (!$this->_cellCollection->isDataSet($coordinate)) {
- $cell = $this->_cellCollection->addCacheData($coordinate, new PHPExcel_Cell($coordinate, null, PHPExcel_Cell_DataType::TYPE_NULL, $this));
- $this->_cellCollectionIsSorted = false;
+ if ($this->cellCollection->isDataSet($coordinate)) {
+ return $this->cellCollection->getCacheData($coordinate);
+ }
- if (PHPExcel_Cell::columnIndexFromString($this->_cachedHighestColumn) < $pColumn)
- $this->_cachedHighestColumn = $columnLetter;
+ // Create new cell object, if required
+ return $createIfNotExists ? $this->createNewCell($coordinate) : null;
+ }
- $this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow);
+ /**
+ * Create a new cell at the specified coordinate
+ *
+ * @param string $pCoordinate Coordinate of the cell
+ * @return PHPExcel_Cell Cell that was created
+ */
+ private function createNewCell($pCoordinate)
+ {
+ $cell = $this->cellCollection->addCacheData(
+ $pCoordinate,
+ new PHPExcel_Cell(null, PHPExcel_Cell_DataType::TYPE_NULL, $this)
+ );
+ $this->cellCollectionIsSorted = false;
- return $cell;
+ // Coordinates
+ $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate);
+ if (PHPExcel_Cell::columnIndexFromString($this->cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($aCoordinates[0])) {
+ $this->cachedHighestColumn = $aCoordinates[0];
}
+ $this->cachedHighestRow = max($this->cachedHighestRow, $aCoordinates[1]);
- return $this->_cellCollection->getCacheData($coordinate);
+ // Cell needs appropriate xfIndex from dimensions records
+ // but don't create dimension records if they don't already exist
+ $rowDimension = $this->getRowDimension($aCoordinates[1], false);
+ $columnDimension = $this->getColumnDimension($aCoordinates[0], false);
+
+ if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
+ // then there is a row dimension with explicit style, assign it to the cell
+ $cell->setXfIndex($rowDimension->getXfIndex());
+ } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) {
+ // then there is a column dimension, assign it to the cell
+ $cell->setXfIndex($columnDimension->getXfIndex());
+ }
+
+ return $cell;
}
/**
- * Cell at a specific coordinate exists?
+ * Does the cell at a specific coordinate exist?
*
* @param string $pCoordinate Coordinate of the cell
* @throws PHPExcel_Exception
@@ -1199,10 +1246,10 @@ public function getCellByColumnAndRow($pColumn = 0, $pRow = 1)
*/
public function cellExists($pCoordinate = 'A1')
{
- // Worksheet reference?
+ // Worksheet reference?
if (strpos($pCoordinate, '!') !== false) {
$worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true);
- return $this->getParent()->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]);
+ return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1]));
}
// Named range?
@@ -1218,23 +1265,24 @@ public function cellExists($pCoordinate = 'A1')
throw new PHPExcel_Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());
}
}
+ } else {
+ return false;
}
- else { return false; }
}
// Uppercase coordinate
$pCoordinate = strtoupper($pCoordinate);
- if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
+ if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) {
throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.');
- } elseif (strpos($pCoordinate,'$') !== false) {
+ } elseif (strpos($pCoordinate, '$') !== false) {
throw new PHPExcel_Exception('Cell coordinate must not be absolute.');
} else {
// Coordinates
$aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate);
// Cell exists?
- return $this->_cellCollection->isDataSet($pCoordinate);
+ return $this->cellCollection->isDataSet($pCoordinate);
}
}
@@ -1256,18 +1304,21 @@ public function cellExistsByColumnAndRow($pColumn = 0, $pRow = 1)
* @param int $pRow Numeric index of the row
* @return PHPExcel_Worksheet_RowDimension
*/
- public function getRowDimension($pRow = 1)
+ public function getRowDimension($pRow = 1, $create = true)
{
// Found
$found = null;
// Get row dimension
- if (!isset($this->_rowDimensions[$pRow])) {
- $this->_rowDimensions[$pRow] = new PHPExcel_Worksheet_RowDimension($pRow);
+ if (!isset($this->rowDimensions[$pRow])) {
+ if (!$create) {
+ return null;
+ }
+ $this->rowDimensions[$pRow] = new PHPExcel_Worksheet_RowDimension($pRow);
- $this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow);
+ $this->cachedHighestRow = max($this->cachedHighestRow, $pRow);
}
- return $this->_rowDimensions[$pRow];
+ return $this->rowDimensions[$pRow];
}
/**
@@ -1276,19 +1327,23 @@ public function getRowDimension($pRow = 1)
* @param string $pColumn String index of the column
* @return PHPExcel_Worksheet_ColumnDimension
*/
- public function getColumnDimension($pColumn = 'A')
+ public function getColumnDimension($pColumn = 'A', $create = true)
{
// Uppercase coordinate
$pColumn = strtoupper($pColumn);
// Fetch dimensions
- if (!isset($this->_columnDimensions[$pColumn])) {
- $this->_columnDimensions[$pColumn] = new PHPExcel_Worksheet_ColumnDimension($pColumn);
+ if (!isset($this->columnDimensions[$pColumn])) {
+ if (!$create) {
+ return null;
+ }
+ $this->columnDimensions[$pColumn] = new PHPExcel_Worksheet_ColumnDimension($pColumn);
- if (PHPExcel_Cell::columnIndexFromString($this->_cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($pColumn))
- $this->_cachedHighestColumn = $pColumn;
+ if (PHPExcel_Cell::columnIndexFromString($this->cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($pColumn)) {
+ $this->cachedHighestColumn = $pColumn;
+ }
}
- return $this->_columnDimensions[$pColumn];
+ return $this->columnDimensions[$pColumn];
}
/**
@@ -1309,7 +1364,7 @@ public function getColumnDimensionByColumn($pColumn = 0)
*/
public function getStyles()
{
- return $this->_styles;
+ return $this->styles;
}
/**
@@ -1321,7 +1376,7 @@ public function getStyles()
*/
public function getDefaultStyle()
{
- return $this->_parent->getDefaultStyle();
+ return $this->parent->getDefaultStyle();
}
/**
@@ -1334,7 +1389,7 @@ public function getDefaultStyle()
*/
public function setDefaultStyle(PHPExcel_Style $pValue)
{
- $this->_parent->getDefaultStyle()->applyFromArray(array(
+ $this->parent->getDefaultStyle()->applyFromArray(array(
'font' => array(
'name' => $pValue->getFont()->getName(),
'size' => $pValue->getFont()->getSize(),
@@ -1346,19 +1401,19 @@ public function setDefaultStyle(PHPExcel_Style $pValue)
/**
* Get style for cell
*
- * @param string $pCellCoordinate Cell coordinate to get style for
+ * @param string $pCellCoordinate Cell coordinate (or range) to get style for
* @return PHPExcel_Style
* @throws PHPExcel_Exception
*/
public function getStyle($pCellCoordinate = 'A1')
{
// set this sheet as active
- $this->_parent->setActiveSheetIndex($this->_parent->getIndex($this));
+ $this->parent->setActiveSheetIndex($this->parent->getIndex($this));
// set cell coordinate as active
- $this->setSelectedCells($pCellCoordinate);
+ $this->setSelectedCells(strtoupper($pCellCoordinate));
- return $this->_parent->getCellXfSupervisor();
+ return $this->parent->getCellXfSupervisor();
}
/**
@@ -1369,10 +1424,11 @@ public function getStyle($pCellCoordinate = 'A1')
*/
public function getConditionalStyles($pCoordinate = 'A1')
{
- if (!isset($this->_conditionalStylesCollection[$pCoordinate])) {
- $this->_conditionalStylesCollection[$pCoordinate] = array();
+ $pCoordinate = strtoupper($pCoordinate);
+ if (!isset($this->conditionalStylesCollection[$pCoordinate])) {
+ $this->conditionalStylesCollection[$pCoordinate] = array();
}
- return $this->_conditionalStylesCollection[$pCoordinate];
+ return $this->conditionalStylesCollection[$pCoordinate];
}
/**
@@ -1383,7 +1439,7 @@ public function getConditionalStyles($pCoordinate = 'A1')
*/
public function conditionalStylesExists($pCoordinate = 'A1')
{
- if (isset($this->_conditionalStylesCollection[$pCoordinate])) {
+ if (isset($this->conditionalStylesCollection[strtoupper($pCoordinate)])) {
return true;
}
return false;
@@ -1397,7 +1453,7 @@ public function conditionalStylesExists($pCoordinate = 'A1')
*/
public function removeConditionalStyles($pCoordinate = 'A1')
{
- unset($this->_conditionalStylesCollection[$pCoordinate]);
+ unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
return $this;
}
@@ -1408,7 +1464,7 @@ public function removeConditionalStyles($pCoordinate = 'A1')
*/
public function getConditionalStylesCollection()
{
- return $this->_conditionalStylesCollection;
+ return $this->conditionalStylesCollection;
}
/**
@@ -1420,7 +1476,7 @@ public function getConditionalStylesCollection()
*/
public function setConditionalStyles($pCoordinate = 'A1', $pValue)
{
- $this->_conditionalStylesCollection[$pCoordinate] = $pValue;
+ $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue;
return $this;
}
@@ -1429,10 +1485,17 @@ public function setConditionalStyles($pCoordinate = 'A1', $pValue)
*
* @param int $pColumn Numeric column coordinate of the cell
* @param int $pRow Numeric row coordinate of the cell
+ * @param int pColumn2 Numeric column coordinate of the range cell
+ * @param int pRow2 Numeric row coordinate of the range cell
* @return PHPExcel_Style
*/
- public function getStyleByColumnAndRow($pColumn = 0, $pRow = 1)
+ public function getStyleByColumnAndRow($pColumn = 0, $pRow = 1, $pColumn2 = null, $pRow2 = null)
{
+ if (!is_null($pColumn2) && !is_null($pRow2)) {
+ $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2;
+ return $this->getStyle($cellRange);
+ }
+
return $this->getStyle(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow);
}
@@ -1469,36 +1532,18 @@ public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '')
$style = $pCellStyle->getIsSupervisor() ? $pCellStyle->getSharedComponent() : $pCellStyle;
// Add the style to the workbook if necessary
- $workbook = $this->_parent;
- if ($this->_parent->cellXfExists($pCellStyle)) {
- // there is already this cell Xf in our collection
- $xfIndex = $pCellStyle->getIndex();
+ $workbook = $this->parent;
+ if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
+ // there is already such cell Xf in our collection
+ $xfIndex = $existingStyle->getIndex();
} else {
// we don't have such a cell Xf, need to add
$workbook->addCellXf($pCellStyle);
$xfIndex = $pCellStyle->getIndex();
}
- // Uppercase coordinate
- $pRange = strtoupper($pRange);
-
- // Is it a cell range or a single cell?
- $rangeA = '';
- $rangeB = '';
- if (strpos($pRange, ':') === false) {
- $rangeA = $pRange;
- $rangeB = $pRange;
- } else {
- list($rangeA, $rangeB) = explode(':', $pRange);
- }
-
// Calculate range outer borders
- $rangeStart = PHPExcel_Cell::coordinateFromString($rangeA);
- $rangeEnd = PHPExcel_Cell::coordinateFromString($rangeB);
-
- // Translate column into index
- $rangeStart[0] = PHPExcel_Cell::columnIndexFromString($rangeStart[0]) - 1;
- $rangeEnd[0] = PHPExcel_Cell::columnIndexFromString($rangeEnd[0]) - 1;
+ list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange . ':' . $pRange);
// Make sure we can loop upwards on rows and columns
if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
@@ -1510,7 +1555,7 @@ public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '')
// Loop through cells and apply styles
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
- $this->getCell(PHPExcel_Cell::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
+ $this->getCell(PHPExcel_Cell::stringFromColumnIndex($col - 1) . $row)->setXfIndex($xfIndex);
}
}
@@ -1522,39 +1567,21 @@ public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '')
*
* Please note that this will overwrite existing cell styles for cells in range!
*
- * @param [PHPExcel_Style_Conditional] $pCellStyle Cell style to duplicate
+ * @param array of PHPExcel_Style_Conditional $pCellStyle Cell style to duplicate
* @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
public function duplicateConditionalStyle(array $pCellStyle = null, $pRange = '')
{
- foreach($pCellStyle as $cellStyle) {
+ foreach ($pCellStyle as $cellStyle) {
if (!($cellStyle instanceof PHPExcel_Style_Conditional)) {
throw new PHPExcel_Exception('Style is not a conditional style');
}
}
- // Uppercase coordinate
- $pRange = strtoupper($pRange);
-
- // Is it a cell range or a single cell?
- $rangeA = '';
- $rangeB = '';
- if (strpos($pRange, ':') === false) {
- $rangeA = $pRange;
- $rangeB = $pRange;
- } else {
- list($rangeA, $rangeB) = explode(':', $pRange);
- }
-
// Calculate range outer borders
- $rangeStart = PHPExcel_Cell::coordinateFromString($rangeA);
- $rangeEnd = PHPExcel_Cell::coordinateFromString($rangeB);
-
- // Translate column into index
- $rangeStart[0] = PHPExcel_Cell::columnIndexFromString($rangeStart[0]) - 1;
- $rangeEnd[0] = PHPExcel_Cell::columnIndexFromString($rangeEnd[0]) - 1;
+ list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange . ':' . $pRange);
// Make sure we can loop upwards on rows and columns
if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
@@ -1566,7 +1593,7 @@ public function duplicateConditionalStyle(array $pCellStyle = null, $pRange = ''
// Loop through cells and apply styles
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
- $this->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($col) . $row, $pCellStyle);
+ $this->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($col - 1) . $row, $pCellStyle);
}
}
@@ -1607,7 +1634,13 @@ public function setBreak($pCell = 'A1', $pBreak = PHPExcel_Worksheet::BREAK_NONE
$pCell = strtoupper($pCell);
if ($pCell != '') {
- $this->_breaks[$pCell] = $pBreak;
+ if ($pBreak == PHPExcel_Worksheet::BREAK_NONE) {
+ if (isset($this->breaks[$pCell])) {
+ unset($this->breaks[$pCell]);
+ }
+ } else {
+ $this->breaks[$pCell] = $pBreak;
+ }
} else {
throw new PHPExcel_Exception('No cell coordinate specified.');
}
@@ -1635,7 +1668,7 @@ public function setBreakByColumnAndRow($pColumn = 0, $pRow = 1, $pBreak = PHPExc
*/
public function getBreaks()
{
- return $this->_breaks;
+ return $this->breaks;
}
/**
@@ -1650,8 +1683,8 @@ public function mergeCells($pRange = 'A1:A1')
// Uppercase coordinate
$pRange = strtoupper($pRange);
- if (strpos($pRange,':') !== false) {
- $this->_mergeCells[$pRange] = $pRange;
+ if (strpos($pRange, ':') !== false) {
+ $this->mergeCells[$pRange] = $pRange;
// make sure cells are created
@@ -1664,12 +1697,13 @@ public function mergeCells($pRange = 'A1:A1')
$this->getCell($upperLeft)->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL);
}
- // create or blank out the rest of the cells in the range
+ // Blank out the rest of the cells in the range (if they exist)
$count = count($aReferences);
for ($i = 1; $i < $count; $i++) {
- $this->getCell($aReferences[$i])->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL);
+ if ($this->cellExists($aReferences[$i])) {
+ $this->getCell($aReferences[$i])->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL);
+ }
}
-
} else {
throw new PHPExcel_Exception('Merge must be set on a range of cells.');
}
@@ -1705,9 +1739,9 @@ public function unmergeCells($pRange = 'A1:A1')
// Uppercase coordinate
$pRange = strtoupper($pRange);
- if (strpos($pRange,':') !== false) {
- if (isset($this->_mergeCells[$pRange])) {
- unset($this->_mergeCells[$pRange]);
+ if (strpos($pRange, ':') !== false) {
+ if (isset($this->mergeCells[$pRange])) {
+ unset($this->mergeCells[$pRange]);
} else {
throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as merged.');
}
@@ -1741,7 +1775,7 @@ public function unmergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2
*/
public function getMergeCells()
{
- return $this->_mergeCells;
+ return $this->mergeCells;
}
/**
@@ -1752,8 +1786,7 @@ public function getMergeCells()
*/
public function setMergeCells($pValue = array())
{
- $this->_mergeCells = $pValue;
-
+ $this->mergeCells = $pValue;
return $this;
}
@@ -1774,7 +1807,7 @@ public function protectCells($pRange = 'A1', $pPassword = '', $pAlreadyHashed =
if (!$pAlreadyHashed) {
$pPassword = PHPExcel_Shared_PasswordHasher::hashPassword($pPassword);
}
- $this->_protectedCells[$pRange] = $pPassword;
+ $this->protectedCells[$pRange] = $pPassword;
return $this;
}
@@ -1809,8 +1842,8 @@ public function unprotectCells($pRange = 'A1')
// Uppercase coordinate
$pRange = strtoupper($pRange);
- if (isset($this->_protectedCells[$pRange])) {
- unset($this->_protectedCells[$pRange]);
+ if (isset($this->protectedCells[$pRange])) {
+ unset($this->protectedCells[$pRange]);
} else {
throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as protected.');
}
@@ -1842,7 +1875,7 @@ public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn
*/
public function getProtectedCells()
{
- return $this->_protectedCells;
+ return $this->protectedCells;
}
/**
@@ -1852,23 +1885,24 @@ public function getProtectedCells()
*/
public function getAutoFilter()
{
- return $this->_autoFilter;
+ return $this->autoFilter;
}
/**
* Set AutoFilter
*
- * @param PHPExcel_Worksheet_AutoFilter|string $pValue
+ * @param PHPExcel_Worksheet_AutoFilter|string $pValue
* A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
public function setAutoFilter($pValue)
{
+ $pRange = strtoupper($pValue);
if (is_string($pValue)) {
- $this->_autoFilter->setRange($pValue);
- } elseif(is_object($pValue) && ($pValue instanceof PHPExcel_Worksheet_AutoFilter)) {
- $this->_autoFilter = $pValue;
+ $this->autoFilter->setRange($pValue);
+ } elseif (is_object($pValue) && ($pValue instanceof PHPExcel_Worksheet_AutoFilter)) {
+ $this->autoFilter = $pValue;
}
return $this;
}
@@ -1876,10 +1910,10 @@ public function setAutoFilter($pValue)
/**
* Set Autofilter Range by using numeric cell coordinates
*
- * @param int $pColumn1 Numeric column coordinate of the first cell
- * @param int $pRow1 Numeric row coordinate of the first cell
- * @param int $pColumn2 Numeric column coordinate of the second cell
- * @param int $pRow2 Numeric row coordinate of the second cell
+ * @param integer $pColumn1 Numeric column coordinate of the first cell
+ * @param integer $pRow1 Numeric row coordinate of the first cell
+ * @param integer $pColumn2 Numeric column coordinate of the second cell
+ * @param integer $pRow2 Numeric row coordinate of the second cell
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
@@ -1899,7 +1933,7 @@ public function setAutoFilterByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2
*/
public function removeAutoFilter()
{
- $this->_autoFilter->setRange(null);
+ $this->autoFilter->setRange(null);
return $this;
}
@@ -1910,7 +1944,7 @@ public function removeAutoFilter()
*/
public function getFreezePane()
{
- return $this->_freezePane;
+ return $this->freezePane;
}
/**
@@ -1929,9 +1963,8 @@ public function freezePane($pCell = '')
{
// Uppercase coordinate
$pCell = strtoupper($pCell);
-
- if (strpos($pCell,':') === false && strpos($pCell,',') === false) {
- $this->_freezePane = $pCell;
+ if (strpos($pCell, ':') === false && strpos($pCell, ',') === false) {
+ $this->freezePane = $pCell;
} else {
throw new PHPExcel_Exception('Freeze pane can not be set on a range of cells.');
}
@@ -1969,7 +2002,8 @@ public function unfreezePane()
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function insertNewRowBefore($pBefore = 1, $pNumRows = 1) {
+ public function insertNewRowBefore($pBefore = 1, $pNumRows = 1)
+ {
if ($pBefore >= 1) {
$objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
@@ -1987,7 +2021,8 @@ public function insertNewRowBefore($pBefore = 1, $pNumRows = 1) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1) {
+ public function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1)
+ {
if (!is_numeric($pBefore)) {
$objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
@@ -2005,7 +2040,8 @@ public function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1) {
+ public function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1)
+ {
if ($pBefore >= 0) {
return $this->insertNewColumnBefore(PHPExcel_Cell::stringFromColumnIndex($pBefore), $pNumCols);
} else {
@@ -2021,10 +2057,16 @@ public function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function removeRow($pRow = 1, $pNumRows = 1) {
+ public function removeRow($pRow = 1, $pNumRows = 1)
+ {
if ($pRow >= 1) {
+ $highestRow = $this->getHighestDataRow();
$objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this);
+ for ($r = 0; $r < $pNumRows; ++$r) {
+ $this->getCellCacheController()->removeRow($highestRow);
+ --$highestRow;
+ }
} else {
throw new PHPExcel_Exception("Rows to be deleted should at least start from row 1.");
}
@@ -2034,16 +2076,22 @@ public function removeRow($pRow = 1, $pNumRows = 1) {
/**
* Remove a column, updating all possible related data
*
- * @param int $pColumn Remove starting with this one
- * @param int $pNumCols Number of columns to remove
+ * @param string $pColumn Remove starting with this one
+ * @param int $pNumCols Number of columns to remove
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function removeColumn($pColumn = 'A', $pNumCols = 1) {
+ public function removeColumn($pColumn = 'A', $pNumCols = 1)
+ {
if (!is_numeric($pColumn)) {
+ $highestColumn = $this->getHighestDataColumn();
$pColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($pColumn) - 1 + $pNumCols);
$objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this);
+ for ($c = 0; $c < $pNumCols; ++$c) {
+ $this->getCellCacheController()->removeColumn($highestColumn);
+ $highestColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($highestColumn) - 2);
+ }
} else {
throw new PHPExcel_Exception("Column references should not be numeric.");
}
@@ -2058,7 +2106,8 @@ public function removeColumn($pColumn = 'A', $pNumCols = 1) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function removeColumnByIndex($pColumn = 0, $pNumCols = 1) {
+ public function removeColumnByIndex($pColumn = 0, $pNumCols = 1)
+ {
if ($pColumn >= 0) {
return $this->removeColumn(PHPExcel_Cell::stringFromColumnIndex($pColumn), $pNumCols);
} else {
@@ -2071,8 +2120,9 @@ public function removeColumnByIndex($pColumn = 0, $pNumCols = 1) {
*
* @return boolean
*/
- public function getShowGridlines() {
- return $this->_showGridlines;
+ public function getShowGridlines()
+ {
+ return $this->showGridlines;
}
/**
@@ -2081,8 +2131,9 @@ public function getShowGridlines() {
* @param boolean $pValue Show gridlines (true/false)
* @return PHPExcel_Worksheet
*/
- public function setShowGridlines($pValue = false) {
- $this->_showGridlines = $pValue;
+ public function setShowGridlines($pValue = false)
+ {
+ $this->showGridlines = $pValue;
return $this;
}
@@ -2091,8 +2142,9 @@ public function setShowGridlines($pValue = false) {
*
* @return boolean
*/
- public function getPrintGridlines() {
- return $this->_printGridlines;
+ public function getPrintGridlines()
+ {
+ return $this->printGridlines;
}
/**
@@ -2101,8 +2153,9 @@ public function getPrintGridlines() {
* @param boolean $pValue Print gridlines (true/false)
* @return PHPExcel_Worksheet
*/
- public function setPrintGridlines($pValue = false) {
- $this->_printGridlines = $pValue;
+ public function setPrintGridlines($pValue = false)
+ {
+ $this->printGridlines = $pValue;
return $this;
}
@@ -2111,8 +2164,9 @@ public function setPrintGridlines($pValue = false) {
*
* @return boolean
*/
- public function getShowRowColHeaders() {
- return $this->_showRowColHeaders;
+ public function getShowRowColHeaders()
+ {
+ return $this->showRowColHeaders;
}
/**
@@ -2121,8 +2175,9 @@ public function getShowRowColHeaders() {
* @param boolean $pValue Show row and column headers (true/false)
* @return PHPExcel_Worksheet
*/
- public function setShowRowColHeaders($pValue = false) {
- $this->_showRowColHeaders = $pValue;
+ public function setShowRowColHeaders($pValue = false)
+ {
+ $this->showRowColHeaders = $pValue;
return $this;
}
@@ -2131,8 +2186,9 @@ public function setShowRowColHeaders($pValue = false) {
*
* @return boolean
*/
- public function getShowSummaryBelow() {
- return $this->_showSummaryBelow;
+ public function getShowSummaryBelow()
+ {
+ return $this->showSummaryBelow;
}
/**
@@ -2141,8 +2197,9 @@ public function getShowSummaryBelow() {
* @param boolean $pValue Show summary below (true/false)
* @return PHPExcel_Worksheet
*/
- public function setShowSummaryBelow($pValue = true) {
- $this->_showSummaryBelow = $pValue;
+ public function setShowSummaryBelow($pValue = true)
+ {
+ $this->showSummaryBelow = $pValue;
return $this;
}
@@ -2151,8 +2208,9 @@ public function setShowSummaryBelow($pValue = true) {
*
* @return boolean
*/
- public function getShowSummaryRight() {
- return $this->_showSummaryRight;
+ public function getShowSummaryRight()
+ {
+ return $this->showSummaryRight;
}
/**
@@ -2161,8 +2219,9 @@ public function getShowSummaryRight() {
* @param boolean $pValue Show summary right (true/false)
* @return PHPExcel_Worksheet
*/
- public function setShowSummaryRight($pValue = true) {
- $this->_showSummaryRight = $pValue;
+ public function setShowSummaryRight($pValue = true)
+ {
+ $this->showSummaryRight = $pValue;
return $this;
}
@@ -2173,18 +2232,18 @@ public function setShowSummaryRight($pValue = true) {
*/
public function getComments()
{
- return $this->_comments;
+ return $this->comments;
}
/**
* Set comments array for the entire sheet.
*
- * @param [PHPExcel_Comment] $pValue
+ * @param array of PHPExcel_Comment
* @return PHPExcel_Worksheet
*/
public function setComments($pValue = array())
{
- $this->_comments = $pValue;
+ $this->comments = $pValue;
return $this;
}
@@ -2201,20 +2260,20 @@ public function getComment($pCellCoordinate = 'A1')
// Uppercase coordinate
$pCellCoordinate = strtoupper($pCellCoordinate);
- if (strpos($pCellCoordinate,':') !== false || strpos($pCellCoordinate,',') !== false) {
+ if (strpos($pCellCoordinate, ':') !== false || strpos($pCellCoordinate, ',') !== false) {
throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells.');
- } else if (strpos($pCellCoordinate,'$') !== false) {
+ } elseif (strpos($pCellCoordinate, '$') !== false) {
throw new PHPExcel_Exception('Cell coordinate string must not be absolute.');
- } else if ($pCellCoordinate == '') {
+ } elseif ($pCellCoordinate == '') {
throw new PHPExcel_Exception('Cell coordinate can not be zero-length string.');
} else {
// Check if we already have a comment for this cell.
// If not, create a new comment.
- if (isset($this->_comments[$pCellCoordinate])) {
- return $this->_comments[$pCellCoordinate];
+ if (isset($this->comments[$pCellCoordinate])) {
+ return $this->comments[$pCellCoordinate];
} else {
$newComment = new PHPExcel_Comment();
- $this->_comments[$pCellCoordinate] = $newComment;
+ $this->comments[$pCellCoordinate] = $newComment;
return $newComment;
}
}
@@ -2250,7 +2309,7 @@ public function getSelectedCell()
*/
public function getActiveCell()
{
- return $this->_activeCell;
+ return $this->activeCell;
}
/**
@@ -2260,7 +2319,7 @@ public function getActiveCell()
*/
public function getSelectedCells()
{
- return $this->_selectedCells;
+ return $this->selectedCells;
}
/**
@@ -2298,13 +2357,13 @@ public function setSelectedCells($pCoordinate = 'A1')
// Convert '1:3' to 'A1:XFD3'
$pCoordinate = preg_replace('/^([0-9]+):([0-9]+)$/', 'A${1}:XFD${2}', $pCoordinate);
- if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
+ if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) {
list($first, ) = PHPExcel_Cell::splitRange($pCoordinate);
- $this->_activeCell = $first[0];
+ $this->activeCell = $first[0];
} else {
- $this->_activeCell = $pCoordinate;
+ $this->activeCell = $pCoordinate;
}
- $this->_selectedCells = $pCoordinate;
+ $this->selectedCells = $pCoordinate;
return $this;
}
@@ -2326,8 +2385,9 @@ public function setSelectedCellByColumnAndRow($pColumn = 0, $pRow = 1)
*
* @return boolean
*/
- public function getRightToLeft() {
- return $this->_rightToLeft;
+ public function getRightToLeft()
+ {
+ return $this->rightToLeft;
}
/**
@@ -2336,8 +2396,9 @@ public function getRightToLeft() {
* @param boolean $value Right-to-left true/false
* @return PHPExcel_Worksheet
*/
- public function setRightToLeft($value = false) {
- $this->_rightToLeft = $value;
+ public function setRightToLeft($value = false)
+ {
+ $this->rightToLeft = $value;
return $this;
}
@@ -2351,7 +2412,8 @@ public function setRightToLeft($value = false) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet
*/
- public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) {
+ public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
+ {
if (is_array($source)) {
// Convert a 1-D array to 2-D (for ease of looping)
if (!is_array(end($source))) {
@@ -2364,7 +2426,7 @@ public function fromArray($source = null, $nullValue = null, $startCell = 'A1',
// Loop through $source
foreach ($source as $rowData) {
$currentColumn = $startColumn;
- foreach($rowData as $cellValue) {
+ foreach ($rowData as $cellValue) {
if ($strictNullComparison) {
if ($cellValue !== $nullValue) {
// Set cell value
@@ -2397,9 +2459,7 @@ public function fromArray($source = null, $nullValue = null, $startCell = 'A1',
* True - Return rows and columns indexed by their actual row and column IDs
* @return array
*/
- public function rangeToArray(
- $pRange = 'A1', $nullValue = null, $calculateFormulas = true,
- $formatData = true, $returnCellRef = false)
+ public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
// Returnvalue
$returnValue = array();
@@ -2420,10 +2480,10 @@ public function rangeToArray(
for ($col = $minCol; $col != $maxCol; ++$col) {
$cRef = ($returnCellRef) ? $col : ++$c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
- // so we test and retrieve directly against _cellCollection
- if ($this->_cellCollection->isDataSet($col.$row)) {
+ // so we test and retrieve directly against cellCollection
+ if ($this->cellCollection->isDataSet($col.$row)) {
// Cell exists
- $cell = $this->_cellCollection->getCacheData($col.$row);
+ $cell = $this->cellCollection->getCacheData($col.$row);
if ($cell->getValue() !== null) {
if ($cell->getValue() instanceof PHPExcel_RichText) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
@@ -2436,13 +2496,14 @@ public function rangeToArray(
}
if ($formatData) {
- $style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
+ $style = $this->parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString(
- $returnValue[$rRef][$cRef], $style->getNumberFormat()->getFormatCode()
+ $returnValue[$rRef][$cRef],
+ ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
}
} else {
- // Cell holds a null
+ // Cell holds a NULL
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
@@ -2469,20 +2530,14 @@ public function rangeToArray(
* @return array
* @throws PHPExcel_Exception
*/
- public function namedRangeToArray(
- $pNamedRange = '', $nullValue = null, $calculateFormulas = true,
- $formatData = true, $returnCellRef = false
- )
+ public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
$namedRange = PHPExcel_NamedRange::resolveRange($pNamedRange, $this);
if ($namedRange !== null) {
$pWorkSheet = $namedRange->getWorksheet();
$pCellRange = $namedRange->getRange();
- return $pWorkSheet->rangeToArray(
- $pCellRange,
- $nullValue, $calculateFormulas, $formatData, $returnCellRef
- );
+ return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
throw new PHPExcel_Exception('Named Range '.$pNamedRange.' does not exist.');
@@ -2508,21 +2563,33 @@ public function toArray($nullValue = null, $calculateFormulas = true, $formatDat
$maxCol = $this->getHighestColumn();
$maxRow = $this->getHighestRow();
// Return
- return $this->rangeToArray(
- 'A1:'.$maxCol.$maxRow,
- $nullValue, $calculateFormulas, $formatData, $returnCellRef
- );
+ return $this->rangeToArray('A1:'.$maxCol.$maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
/**
* Get row iterator
*
- * @param integer $startRow The row number at which to start iterating
+ * @param integer $startRow The row number at which to start iterating
+ * @param integer $endRow The row number at which to stop iterating
+ *
* @return PHPExcel_Worksheet_RowIterator
*/
- public function getRowIterator($startRow = 1)
+ public function getRowIterator($startRow = 1, $endRow = null)
+ {
+ return new PHPExcel_Worksheet_RowIterator($this, $startRow, $endRow);
+ }
+
+ /**
+ * Get column iterator
+ *
+ * @param string $startColumn The column address at which to start iterating
+ * @param string $endColumn The column address at which to stop iterating
+ *
+ * @return PHPExcel_Worksheet_ColumnIterator
+ */
+ public function getColumnIterator($startColumn = 'A', $endColumn = null)
{
- return new PHPExcel_Worksheet_RowIterator($this,$startRow);
+ return new PHPExcel_Worksheet_ColumnIterator($this, $startColumn, $endColumn);
}
/**
@@ -2533,7 +2600,7 @@ public function getRowIterator($startRow = 1)
public function garbageCollect()
{
// Flush cache
- $this->_cellCollection->getCacheData('A1');
+ $this->cellCollection->getCacheData('A1');
// Build a reference table from images
// $imageCoordinates = array();
// $iterator = $this->getDrawingCollection()->getIterator();
@@ -2544,27 +2611,27 @@ public function garbageCollect()
// }
//
// Lookup highest column and highest row if cells are cleaned
- $colRow = $this->_cellCollection->getHighestRowAndColumn();
+ $colRow = $this->cellCollection->getHighestRowAndColumn();
$highestRow = $colRow['row'];
$highestColumn = PHPExcel_Cell::columnIndexFromString($colRow['column']);
// Loop through column dimensions
- foreach ($this->_columnDimensions as $dimension) {
- $highestColumn = max($highestColumn,PHPExcel_Cell::columnIndexFromString($dimension->getColumnIndex()));
+ foreach ($this->columnDimensions as $dimension) {
+ $highestColumn = max($highestColumn, PHPExcel_Cell::columnIndexFromString($dimension->getColumnIndex()));
}
// Loop through row dimensions
- foreach ($this->_rowDimensions as $dimension) {
- $highestRow = max($highestRow,$dimension->getRowIndex());
+ foreach ($this->rowDimensions as $dimension) {
+ $highestRow = max($highestRow, $dimension->getRowIndex());
}
// Cache values
if ($highestColumn < 0) {
- $this->_cachedHighestColumn = 'A';
+ $this->cachedHighestColumn = 'A';
} else {
- $this->_cachedHighestColumn = PHPExcel_Cell::stringFromColumnIndex(--$highestColumn);
+ $this->cachedHighestColumn = PHPExcel_Cell::stringFromColumnIndex(--$highestColumn);
}
- $this->_cachedHighestRow = $highestRow;
+ $this->cachedHighestRow = $highestRow;
// Return
return $this;
@@ -2577,15 +2644,11 @@ public function garbageCollect()
*/
public function getHashCode()
{
- if ($this->_dirty) {
- $this->_hash = md5( $this->_title .
- $this->_autoFilter .
- ($this->_protection->isProtectionEnabled() ? 't' : 'f') .
- __CLASS__
- );
- $this->_dirty = false;
+ if ($this->dirty) {
+ $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__);
+ $this->dirty = false;
}
- return $this->_hash;
+ return $this->hash;
}
/**
@@ -2606,9 +2669,7 @@ public static function extractSheetTitle($pRange, $returnRange = false)
}
if ($returnRange) {
- return array( trim(substr($pRange, 0, $sep),"'"),
- substr($pRange, $sep + 1)
- );
+ return array(trim(substr($pRange, 0, $sep), "'"), substr($pRange, $sep + 1));
}
return substr($pRange, $sep + 1);
@@ -2622,13 +2683,13 @@ public static function extractSheetTitle($pRange, $returnRange = false)
public function getHyperlink($pCellCoordinate = 'A1')
{
// return hyperlink if we already have one
- if (isset($this->_hyperlinkCollection[$pCellCoordinate])) {
- return $this->_hyperlinkCollection[$pCellCoordinate];
+ if (isset($this->hyperlinkCollection[$pCellCoordinate])) {
+ return $this->hyperlinkCollection[$pCellCoordinate];
}
// else create hyperlink
- $this->_hyperlinkCollection[$pCellCoordinate] = new PHPExcel_Cell_Hyperlink();
- return $this->_hyperlinkCollection[$pCellCoordinate];
+ $this->hyperlinkCollection[$pCellCoordinate] = new PHPExcel_Cell_Hyperlink();
+ return $this->hyperlinkCollection[$pCellCoordinate];
}
/**
@@ -2641,9 +2702,9 @@ public function getHyperlink($pCellCoordinate = 'A1')
public function setHyperlink($pCellCoordinate = 'A1', PHPExcel_Cell_Hyperlink $pHyperlink = null)
{
if ($pHyperlink === null) {
- unset($this->_hyperlinkCollection[$pCellCoordinate]);
+ unset($this->hyperlinkCollection[$pCellCoordinate]);
} else {
- $this->_hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
+ $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
}
return $this;
}
@@ -2656,7 +2717,7 @@ public function setHyperlink($pCellCoordinate = 'A1', PHPExcel_Cell_Hyperlink $p
*/
public function hyperlinkExists($pCoordinate = 'A1')
{
- return isset($this->_hyperlinkCollection[$pCoordinate]);
+ return isset($this->hyperlinkCollection[$pCoordinate]);
}
/**
@@ -2666,7 +2727,7 @@ public function hyperlinkExists($pCoordinate = 'A1')
*/
public function getHyperlinkCollection()
{
- return $this->_hyperlinkCollection;
+ return $this->hyperlinkCollection;
}
/**
@@ -2677,13 +2738,13 @@ public function getHyperlinkCollection()
public function getDataValidation($pCellCoordinate = 'A1')
{
// return data validation if we already have one
- if (isset($this->_dataValidationCollection[$pCellCoordinate])) {
- return $this->_dataValidationCollection[$pCellCoordinate];
+ if (isset($this->dataValidationCollection[$pCellCoordinate])) {
+ return $this->dataValidationCollection[$pCellCoordinate];
}
// else create data validation
- $this->_dataValidationCollection[$pCellCoordinate] = new PHPExcel_Cell_DataValidation();
- return $this->_dataValidationCollection[$pCellCoordinate];
+ $this->dataValidationCollection[$pCellCoordinate] = new PHPExcel_Cell_DataValidation();
+ return $this->dataValidationCollection[$pCellCoordinate];
}
/**
@@ -2696,9 +2757,9 @@ public function getDataValidation($pCellCoordinate = 'A1')
public function setDataValidation($pCellCoordinate = 'A1', PHPExcel_Cell_DataValidation $pDataValidation = null)
{
if ($pDataValidation === null) {
- unset($this->_dataValidationCollection[$pCellCoordinate]);
+ unset($this->dataValidationCollection[$pCellCoordinate]);
} else {
- $this->_dataValidationCollection[$pCellCoordinate] = $pDataValidation;
+ $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation;
}
return $this;
}
@@ -2711,7 +2772,7 @@ public function setDataValidation($pCellCoordinate = 'A1', PHPExcel_Cell_DataVal
*/
public function dataValidationExists($pCoordinate = 'A1')
{
- return isset($this->_dataValidationCollection[$pCoordinate]);
+ return isset($this->dataValidationCollection[$pCoordinate]);
}
/**
@@ -2721,7 +2782,7 @@ public function dataValidationExists($pCoordinate = 'A1')
*/
public function getDataValidationCollection()
{
- return $this->_dataValidationCollection;
+ return $this->dataValidationCollection;
}
/**
@@ -2736,18 +2797,26 @@ public function shrinkRangeToFit($range)
$maxRow = $this->getHighestRow();
$maxCol = PHPExcel_Cell::columnIndexFromString($maxCol);
- $rangeBlocks = explode(' ',$range);
+ $rangeBlocks = explode(' ', $range);
foreach ($rangeBlocks as &$rangeSet) {
$rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($rangeSet);
- if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) { $rangeBoundaries[0][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol); }
- if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; }
- if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) { $rangeBoundaries[1][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol); }
- if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; }
+ if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
+ $rangeBoundaries[0][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol);
+ }
+ if ($rangeBoundaries[0][1] > $maxRow) {
+ $rangeBoundaries[0][1] = $maxRow;
+ }
+ if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
+ $rangeBoundaries[1][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol);
+ }
+ if ($rangeBoundaries[1][1] > $maxRow) {
+ $rangeBoundaries[1][1] = $maxRow;
+ }
$rangeSet = $rangeBoundaries[0][0].$rangeBoundaries[0][1].':'.$rangeBoundaries[1][0].$rangeBoundaries[1][1];
}
unset($rangeSet);
- $stRange = implode(' ',$rangeBlocks);
+ $stRange = implode(' ', $rangeBlocks);
return $stRange;
}
@@ -2759,10 +2828,10 @@ public function shrinkRangeToFit($range)
*/
public function getTabColor()
{
- if ($this->_tabColor === null)
- $this->_tabColor = new PHPExcel_Style_Color();
-
- return $this->_tabColor;
+ if ($this->tabColor === null) {
+ $this->tabColor = new PHPExcel_Style_Color();
+ }
+ return $this->tabColor;
}
/**
@@ -2772,8 +2841,8 @@ public function getTabColor()
*/
public function resetTabColor()
{
- $this->_tabColor = null;
- unset($this->_tabColor);
+ $this->tabColor = null;
+ unset($this->tabColor);
return $this;
}
@@ -2785,7 +2854,7 @@ public function resetTabColor()
*/
public function isTabColorSet()
{
- return ($this->_tabColor !== null);
+ return ($this->tabColor !== null);
}
/**
@@ -2806,26 +2875,94 @@ public function copy()
public function __clone()
{
foreach ($this as $key => $val) {
- if ($key == '_parent') {
+ if ($key == 'parent') {
continue;
}
if (is_object($val) || (is_array($val))) {
- if ($key == '_cellCollection') {
- $newCollection = clone $this->_cellCollection;
+ if ($key == 'cellCollection') {
+ $newCollection = clone $this->cellCollection;
$newCollection->copyCellCollection($this);
- $this->_cellCollection = $newCollection;
- } elseif ($key == '_drawingCollection') {
- $newCollection = clone $this->_drawingCollection;
- $this->_drawingCollection = $newCollection;
- } elseif (($key == '_autoFilter') && ($this->_autoFilter instanceof PHPExcel_Worksheet_AutoFilter)) {
- $newAutoFilter = clone $this->_autoFilter;
- $this->_autoFilter = $newAutoFilter;
- $this->_autoFilter->setParent($this);
+ $this->cellCollection = $newCollection;
+ } elseif ($key == 'drawingCollection') {
+ $newCollection = clone $this->drawingCollection;
+ $this->drawingCollection = $newCollection;
+ } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof PHPExcel_Worksheet_AutoFilter)) {
+ $newAutoFilter = clone $this->autoFilter;
+ $this->autoFilter = $newAutoFilter;
+ $this->autoFilter->setParent($this);
} else {
$this->{$key} = unserialize(serialize($val));
}
}
}
}
+/**
+ * Define the code name of the sheet
+ *
+ * @param null|string Same rule as Title minus space not allowed (but, like Excel, change silently space to underscore)
+ * @return objWorksheet
+ * @throws PHPExcel_Exception
+ */
+ public function setCodeName($pValue = null)
+ {
+ // Is this a 'rename' or not?
+ if ($this->getCodeName() == $pValue) {
+ return $this;
+ }
+ $pValue = str_replace(' ', '_', $pValue);//Excel does this automatically without flinching, we are doing the same
+ // Syntax check
+ // throw an exception if not valid
+ self::checkSheetCodeName($pValue);
+
+ // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
+
+ if ($this->getParent()) {
+ // Is there already such sheet name?
+ if ($this->getParent()->sheetCodeNameExists($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->getParent()->sheetCodeNameExists($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);
+ }
+ }
+ }
+
+ $pValue = $pValue . '_' . $i;// ok, we have a valid name
+ //codeName is'nt used in formula : no need to call for an update
+ //return $this->setTitle($altTitle, $updateFormulaCellReferences);
+ }
+ }
+
+ $this->codeName=$pValue;
+ return $this;
+ }
+ /**
+ * Return the code name of the sheet
+ *
+ * @return null|string
+ */
+ public function getCodeName()
+ {
+ return $this->codeName;
+ }
+ /**
+ * Sheet has a code name ?
+ * @return boolean
+ */
+ public function hasCodeName()
+ {
+ return !(is_null($this->codeName));
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/AutoFilter.php b/Classes/PHPExcel/Worksheet/AutoFilter.php
index c39bfbf8a..6ec8a4466 100644
--- a/Classes/PHPExcel/Worksheet/AutoFilter.php
+++ b/Classes/PHPExcel/Worksheet/AutoFilter.php
@@ -1,8 +1,9 @@
range = $pRange;
+ $this->workSheet = $pSheet;
+ }
+
+ /**
+ * Get AutoFilter Parent Worksheet
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function getParent()
+ {
+ return $this->workSheet;
+ }
+
+ /**
+ * Set AutoFilter Parent Worksheet
+ *
+ * @param PHPExcel_Worksheet $pSheet
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function setParent(PHPExcel_Worksheet $pSheet = null)
+ {
+ $this->workSheet = $pSheet;
+
+ return $this;
+ }
+
+ /**
+ * Get AutoFilter Range
+ *
+ * @return string
+ */
+ public function getRange()
+ {
+ return $this->range;
+ }
+
+ /**
+ * Set AutoFilter Range
+ *
+ * @param string $pRange Cell range (i.e. A1:E10)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function setRange($pRange = '')
+ {
+ // Uppercase coordinate
+ $cellAddress = explode('!', strtoupper($pRange));
+ if (count($cellAddress) > 1) {
+ list($worksheet, $pRange) = $cellAddress;
+ }
+
+ if (strpos($pRange, ':') !== false) {
+ $this->range = $pRange;
+ } elseif (empty($pRange)) {
+ $this->range = '';
+ } else {
+ throw new PHPExcel_Exception('Autofilter must be set on a range of cells.');
+ }
+
+ if (empty($pRange)) {
+ // Discard all column rules
+ $this->columns = array();
+ } else {
+ // Discard any column rules that are no longer valid within this range
+ list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range);
+ foreach ($this->columns as $key => $value) {
+ $colIndex = PHPExcel_Cell::columnIndexFromString($key);
+ if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) {
+ unset($this->columns[$key]);
+ }
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get all AutoFilter Columns
+ *
+ * @throws PHPExcel_Exception
+ * @return array of PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function getColumns()
+ {
+ return $this->columns;
+ }
+
+ /**
+ * Validate that the specified column is in the AutoFilter range
+ *
+ * @param string $column Column name (e.g. A)
+ * @throws PHPExcel_Exception
+ * @return integer The column offset within the autofilter range
+ */
+ public function testColumnInRange($column)
+ {
+ if (empty($this->range)) {
+ throw new PHPExcel_Exception("No autofilter range is defined.");
+ }
+
+ $columnIndex = PHPExcel_Cell::columnIndexFromString($column);
+ list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range);
+ if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) {
+ throw new PHPExcel_Exception("Column is outside of current autofilter range.");
+ }
+
+ return $columnIndex - $rangeStart[0];
+ }
+
+ /**
+ * Get a specified AutoFilter Column Offset within the defined AutoFilter range
+ *
+ * @param string $pColumn Column name (e.g. A)
+ * @throws PHPExcel_Exception
+ * @return integer The offset of the specified column within the autofilter range
+ */
+ public function getColumnOffset($pColumn)
+ {
+ return $this->testColumnInRange($pColumn);
+ }
+
+ /**
+ * Get a specified AutoFilter Column
+ *
+ * @param string $pColumn Column name (e.g. A)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function getColumn($pColumn)
+ {
+ $this->testColumnInRange($pColumn);
+
+ if (!isset($this->columns[$pColumn])) {
+ $this->columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this);
+ }
+
+ return $this->columns[$pColumn];
+ }
+
+ /**
+ * Get a specified AutoFilter Column by it's offset
+ *
+ * @param integer $pColumnOffset Column offset within range (starting from 0)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function getColumnByOffset($pColumnOffset = 0)
+ {
+ list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range);
+ $pColumn = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1);
+
+ return $this->getColumn($pColumn);
+ }
+
+ /**
+ * Set AutoFilter
+ *
+ * @param PHPExcel_Worksheet_AutoFilter_Column|string $pColumn
+ * A simple string containing a Column ID like 'A' is permitted
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function setColumn($pColumn)
+ {
+ if ((is_string($pColumn)) && (!empty($pColumn))) {
+ $column = $pColumn;
+ } elseif (is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) {
+ $column = $pColumn->getColumnIndex();
+ } else {
+ throw new PHPExcel_Exception("Column is not within the autofilter range.");
+ }
+ $this->testColumnInRange($column);
+
+ if (is_string($pColumn)) {
+ $this->columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this);
+ } elseif (is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) {
+ $pColumn->setParent($this);
+ $this->columns[$column] = $pColumn;
+ }
+ ksort($this->columns);
+
+ return $this;
+ }
+
+ /**
+ * Clear a specified AutoFilter Column
+ *
+ * @param string $pColumn Column name (e.g. A)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function clearColumn($pColumn)
+ {
+ $this->testColumnInRange($pColumn);
+
+ if (isset($this->columns[$pColumn])) {
+ unset($this->columns[$pColumn]);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Shift an AutoFilter Column Rule to a different column
+ *
+ * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range.
+ * Nor does it verify whether any column rule already exists at $toColumn, but will simply overrideany existing value.
+ * Use with caution.
+ *
+ * @param string $fromColumn Column name (e.g. A)
+ * @param string $toColumn Column name (e.g. B)
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function shiftColumn($fromColumn = null, $toColumn = null)
+ {
+ $fromColumn = strtoupper($fromColumn);
+ $toColumn = strtoupper($toColumn);
+
+ if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) {
+ $this->columns[$fromColumn]->setParent();
+ $this->columns[$fromColumn]->setColumnIndex($toColumn);
+ $this->columns[$toColumn] = $this->columns[$fromColumn];
+ $this->columns[$toColumn]->setParent($this);
+ unset($this->columns[$fromColumn]);
+
+ ksort($this->columns);
+ }
+
+ return $this;
+ }
+
+
+ /**
+ * Test if cell value is in the defined set of values
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $dataSet
+ * @return boolean
+ */
+ private static function filterTestInSimpleDataSet($cellValue, $dataSet)
+ {
+ $dataSetValues = $dataSet['filterValues'];
+ $blanks = $dataSet['blanks'];
+ if (($cellValue == '') || ($cellValue === null)) {
+ return $blanks;
+ }
+ return in_array($cellValue, $dataSetValues);
+ }
+
+ /**
+ * Test if cell value is in the defined set of Excel date values
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $dataSet
+ * @return boolean
+ */
+ private static function filterTestInDateGroupSet($cellValue, $dataSet)
+ {
+ $dateSet = $dataSet['filterValues'];
+ $blanks = $dataSet['blanks'];
+ if (($cellValue == '') || ($cellValue === null)) {
+ return $blanks;
+ }
+
+ if (is_numeric($cellValue)) {
+ $dateValue = PHPExcel_Shared_Date::ExcelToPHP($cellValue);
+ if ($cellValue < 1) {
+ // Just the time part
+ $dtVal = date('His', $dateValue);
+ $dateSet = $dateSet['time'];
+ } elseif ($cellValue == floor($cellValue)) {
+ // Just the date part
+ $dtVal = date('Ymd', $dateValue);
+ $dateSet = $dateSet['date'];
+ } else {
+ // date and time parts
+ $dtVal = date('YmdHis', $dateValue);
+ $dateSet = $dateSet['dateTime'];
+ }
+ foreach ($dateSet as $dateValue) {
+ // Use of substr to extract value at the appropriate group level
+ if (substr($dtVal, 0, strlen($dateValue)) == $dateValue) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Test if cell value is within a set of values defined by a ruleset
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $ruleSet
+ * @return boolean
*/
- public function __construct($pRange = '', PHPExcel_Worksheet $pSheet = NULL)
+ private static function filterTestInCustomDataSet($cellValue, $ruleSet)
+ {
+ $dataSet = $ruleSet['filterRules'];
+ $join = $ruleSet['join'];
+ $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : false;
+
+ if (!$customRuleForBlanks) {
+ // Blank cells are always ignored, so return a FALSE
+ if (($cellValue == '') || ($cellValue === null)) {
+ return false;
+ }
+ }
+ $returnVal = ($join == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
+ foreach ($dataSet as $rule) {
+ if (is_numeric($rule['value'])) {
+ // Numeric values are tested using the appropriate operator
+ switch ($rule['operator']) {
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
+ $retVal = ($cellValue == $rule['value']);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
+ $retVal = ($cellValue != $rule['value']);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN:
+ $retVal = ($cellValue > $rule['value']);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL:
+ $retVal = ($cellValue >= $rule['value']);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN:
+ $retVal = ($cellValue < $rule['value']);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL:
+ $retVal = ($cellValue <= $rule['value']);
+ break;
+ }
+ } elseif ($rule['value'] == '') {
+ switch ($rule['operator']) {
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
+ $retVal = (($cellValue == '') || ($cellValue === null));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
+ $retVal = (($cellValue != '') && ($cellValue !== null));
+ break;
+ default:
+ $retVal = true;
+ break;
+ }
+ } else {
+ // String values are always tested for equality, factoring in for wildcards (hence a regexp test)
+ $retVal = preg_match('/^'.$rule['value'].'$/i', $cellValue);
+ }
+ // If there are multiple conditions, then we need to test both using the appropriate join operator
+ switch ($join) {
+ case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR:
+ $returnVal = $returnVal || $retVal;
+ // Break as soon as we have a TRUE match for OR joins,
+ // to avoid unnecessary additional code execution
+ if ($returnVal) {
+ return $returnVal;
+ }
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND:
+ $returnVal = $returnVal && $retVal;
+ break;
+ }
+ }
+
+ return $returnVal;
+ }
+
+ /**
+ * Test if cell date value is matches a set of values defined by a set of months
+ *
+ * @param mixed $cellValue
+ * @param mixed[] $monthSet
+ * @return boolean
+ */
+ private static function filterTestInPeriodDateSet($cellValue, $monthSet)
+ {
+ // Blank cells are always ignored, so return a FALSE
+ if (($cellValue == '') || ($cellValue === null)) {
+ return false;
+ }
+
+ if (is_numeric($cellValue)) {
+ $dateValue = date('m', PHPExcel_Shared_Date::ExcelToPHP($cellValue));
+ if (in_array($dateValue, $monthSet)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching
+ *
+ * @var array
+ */
+ private static $fromReplace = array('\*', '\?', '~~', '~.*', '~.?');
+ private static $toReplace = array('.*', '.', '~', '\*', '\?');
+
+
+ /**
+ * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation
+ *
+ * @param string $dynamicRuleType
+ * @param PHPExcel_Worksheet_AutoFilter_Column &$filterColumn
+ * @return mixed[]
+ */
+ private function dynamicFilterDateRange($dynamicRuleType, &$filterColumn)
+ {
+ $rDateType = PHPExcel_Calculation_Functions::getReturnDateType();
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $val = $maxVal = null;
+
+ $ruleValues = array();
+ $baseDate = PHPExcel_Calculation_DateTime::DATENOW();
+ // Calculate start/end dates for the required date range based on current date
+ switch ($dynamicRuleType) {
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK:
+ $baseDate = strtotime('-7 days', $baseDate);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK:
+ $baseDate = strtotime('-7 days', $baseDate);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH:
+ $baseDate = strtotime('-1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH:
+ $baseDate = strtotime('+1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER:
+ $baseDate = strtotime('-3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER:
+ $baseDate = strtotime('+3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR:
+ $baseDate = strtotime('-1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR:
+ $baseDate = strtotime('+1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ }
+
+ switch ($dynamicRuleType) {
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW:
+ $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day', $baseDate));
+ $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate);
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE:
+ $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day', $baseDate));
+ $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR:
+ $maxVal = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 31, 12, date('Y', $baseDate)));
+ ++$maxVal;
+ $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER:
+ $thisMonth = date('m', $baseDate);
+ $thisQuarter = floor(--$thisMonth / 3);
+ $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1+$thisQuarter)*3, date('Y', $baseDate)));
+ ++$maxVal;
+ $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1+$thisQuarter*3, date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH:
+ $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), date('m', $baseDate), date('Y', $baseDate)));
+ ++$maxVal;
+ $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK:
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK:
+ $dayOfWeek = date('w', $baseDate);
+ $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate) - $dayOfWeek;
+ $maxVal = $val + 7;
+ break;
+ }
+
+ switch ($dynamicRuleType) {
+ // Adjust Today dates for Yesterday and Tomorrow
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY:
+ --$maxVal;
+ --$val;
+ break;
+ case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW:
+ ++$maxVal;
+ ++$val;
+ break;
+ }
+
+ // Set the filter column rule attributes ready for writing
+ $filterColumn->setAttributes(array('val' => $val, 'maxVal' => $maxVal));
+
+ // Set the rules for identifying rows for hide/show
+ $ruleValues[] = array('operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val);
+ $ruleValues[] = array('operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal);
+ PHPExcel_Calculation_Functions::setReturnDateType($rDateType);
+
+ return array('method' => 'filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND));
+ }
+
+ private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue)
{
- $this->_range = $pRange;
- $this->_workSheet = $pSheet;
+ $range = $columnID.$startRow.':'.$columnID.$endRow;
+ $dataValues = PHPExcel_Calculation_Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false));
+
+ $dataValues = array_filter($dataValues);
+ if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) {
+ rsort($dataValues);
+ } else {
+ sort($dataValues);
+ }
+
+ return array_pop(array_slice($dataValues, 0, $ruleValue));
}
- /**
- * Get AutoFilter Parent Worksheet
- *
- * @return PHPExcel_Worksheet
- */
- public function getParent() {
- return $this->_workSheet;
- }
-
- /**
- * Set AutoFilter Parent Worksheet
- *
- * @param PHPExcel_Worksheet
- * @return PHPExcel_Worksheet_AutoFilter
- */
- public function setParent(PHPExcel_Worksheet $pSheet = NULL) {
- $this->_workSheet = $pSheet;
-
- return $this;
- }
-
- /**
- * Get AutoFilter Range
- *
- * @return string
- */
- public function getRange() {
- return $this->_range;
- }
-
- /**
- * Set AutoFilter Range
- *
- * @param string $pRange Cell range (i.e. A1:E10)
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter
- */
- public function setRange($pRange = '') {
- // Uppercase coordinate
- $cellAddress = explode('!',strtoupper($pRange));
- if (count($cellAddress) > 1) {
- list($worksheet,$pRange) = $cellAddress;
- }
-
- if (strpos($pRange,':') !== FALSE) {
- $this->_range = $pRange;
- } elseif(empty($pRange)) {
- $this->_range = '';
- } else {
- throw new PHPExcel_Exception('Autofilter must be set on a range of cells.');
- }
-
- if (empty($pRange)) {
- // Discard all column rules
- $this->_columns = array();
- } else {
- // Discard any column rules that are no longer valid within this range
- list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range);
- foreach($this->_columns as $key => $value) {
- $colIndex = PHPExcel_Cell::columnIndexFromString($key);
- if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) {
- unset($this->_columns[$key]);
- }
- }
- }
-
- return $this;
- }
-
- /**
- * Get all AutoFilter Columns
- *
- * @throws PHPExcel_Exception
- * @return array of PHPExcel_Worksheet_AutoFilter_Column
- */
- public function getColumns() {
- return $this->_columns;
- }
-
- /**
- * Validate that the specified column is in the AutoFilter range
- *
- * @param string $column Column name (e.g. A)
- * @throws PHPExcel_Exception
- * @return integer The column offset within the autofilter range
- */
- public function testColumnInRange($column) {
- if (empty($this->_range)) {
- throw new PHPExcel_Exception("No autofilter range is defined.");
- }
-
- $columnIndex = PHPExcel_Cell::columnIndexFromString($column);
- list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range);
- if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) {
- throw new PHPExcel_Exception("Column is outside of current autofilter range.");
- }
-
- return $columnIndex - $rangeStart[0];
- }
-
- /**
- * Get a specified AutoFilter Column Offset within the defined AutoFilter range
- *
- * @param string $pColumn Column name (e.g. A)
- * @throws PHPExcel_Exception
- * @return integer The offset of the specified column within the autofilter range
- */
- public function getColumnOffset($pColumn) {
- return $this->testColumnInRange($pColumn);
- }
-
- /**
- * Get a specified AutoFilter Column
- *
- * @param string $pColumn Column name (e.g. A)
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function getColumn($pColumn) {
- $this->testColumnInRange($pColumn);
-
- if (!isset($this->_columns[$pColumn])) {
- $this->_columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this);
- }
-
- return $this->_columns[$pColumn];
- }
-
- /**
- * Get a specified AutoFilter Column by it's offset
- *
- * @param integer $pColumnOffset Column offset within range (starting from 0)
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function getColumnByOffset($pColumnOffset = 0) {
- list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range);
- $pColumn = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1);
-
- return $this->getColumn($pColumn);
- }
-
- /**
- * Set AutoFilter
- *
- * @param PHPExcel_Worksheet_AutoFilter_Column|string $pColumn
- * A simple string containing a Column ID like 'A' is permitted
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter
- */
- public function setColumn($pColumn)
- {
- if ((is_string($pColumn)) && (!empty($pColumn))) {
- $column = $pColumn;
- } elseif(is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) {
- $column = $pColumn->getColumnIndex();
- } else {
- throw new PHPExcel_Exception("Column is not within the autofilter range.");
- }
- $this->testColumnInRange($column);
-
- if (is_string($pColumn)) {
- $this->_columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this);
- } elseif(is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) {
- $pColumn->setParent($this);
- $this->_columns[$column] = $pColumn;
- }
- ksort($this->_columns);
-
- return $this;
- }
-
- /**
- * Clear a specified AutoFilter Column
- *
- * @param string $pColumn Column name (e.g. A)
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter
- */
- public function clearColumn($pColumn) {
- $this->testColumnInRange($pColumn);
-
- if (isset($this->_columns[$pColumn])) {
- unset($this->_columns[$pColumn]);
- }
-
- return $this;
- }
-
- /**
- * Shift an AutoFilter Column Rule to a different column
- *
- * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range.
- * Nor does it verify whether any column rule already exists at $toColumn, but will simply overrideany existing value.
- * Use with caution.
- *
- * @param string $fromColumn Column name (e.g. A)
- * @param string $toColumn Column name (e.g. B)
- * @return PHPExcel_Worksheet_AutoFilter
- */
- public function shiftColumn($fromColumn=NULL,$toColumn=NULL) {
- $fromColumn = strtoupper($fromColumn);
- $toColumn = strtoupper($toColumn);
-
- if (($fromColumn !== NULL) && (isset($this->_columns[$fromColumn])) && ($toColumn !== NULL)) {
- $this->_columns[$fromColumn]->setParent();
- $this->_columns[$fromColumn]->setColumnIndex($toColumn);
- $this->_columns[$toColumn] = $this->_columns[$fromColumn];
- $this->_columns[$toColumn]->setParent($this);
- unset($this->_columns[$fromColumn]);
-
- ksort($this->_columns);
- }
-
- return $this;
- }
-
-
- /**
- * Test if cell value is in the defined set of values
- *
- * @param mixed $cellValue
- * @param mixed[] $dataSet
- * @return boolean
- */
- private static function _filterTestInSimpleDataSet($cellValue,$dataSet)
- {
- $dataSetValues = $dataSet['filterValues'];
- $blanks = $dataSet['blanks'];
- if (($cellValue == '') || ($cellValue === NULL)) {
- return $blanks;
- }
- return in_array($cellValue,$dataSetValues);
- }
-
- /**
- * Test if cell value is in the defined set of Excel date values
- *
- * @param mixed $cellValue
- * @param mixed[] $dataSet
- * @return boolean
- */
- private static function _filterTestInDateGroupSet($cellValue,$dataSet)
- {
- $dateSet = $dataSet['filterValues'];
- $blanks = $dataSet['blanks'];
- if (($cellValue == '') || ($cellValue === NULL)) {
- return $blanks;
- }
-
- if (is_numeric($cellValue)) {
- $dateValue = PHPExcel_Shared_Date::ExcelToPHP($cellValue);
- if ($cellValue < 1) {
- // Just the time part
- $dtVal = date('His',$dateValue);
- $dateSet = $dateSet['time'];
- } elseif($cellValue == floor($cellValue)) {
- // Just the date part
- $dtVal = date('Ymd',$dateValue);
- $dateSet = $dateSet['date'];
- } else {
- // date and time parts
- $dtVal = date('YmdHis',$dateValue);
- $dateSet = $dateSet['dateTime'];
- }
- foreach($dateSet as $dateValue) {
- // Use of substr to extract value at the appropriate group level
- if (substr($dtVal,0,strlen($dateValue)) == $dateValue)
- return TRUE;
- }
- }
-
- return FALSE;
- }
-
- /**
- * Test if cell value is within a set of values defined by a ruleset
- *
- * @param mixed $cellValue
- * @param mixed[] $dataSet
- * @return boolean
- */
- private static function _filterTestInCustomDataSet($cellValue,$ruleSet)
- {
- $dataSet = $ruleSet['filterRules'];
- $join = $ruleSet['join'];
- $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : FALSE;
-
- if (!$customRuleForBlanks) {
- // Blank cells are always ignored, so return a FALSE
- if (($cellValue == '') || ($cellValue === NULL)) {
- return FALSE;
- }
- }
- $returnVal = ($join == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
- foreach($dataSet as $rule) {
- if (is_numeric($rule['value'])) {
- // Numeric values are tested using the appropriate operator
- switch ($rule['operator']) {
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL :
- $retVal = ($cellValue == $rule['value']);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL :
- $retVal = ($cellValue != $rule['value']);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN :
- $retVal = ($cellValue > $rule['value']);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL :
- $retVal = ($cellValue >= $rule['value']);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN :
- $retVal = ($cellValue < $rule['value']);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL :
- $retVal = ($cellValue <= $rule['value']);
- break;
- }
- } elseif($rule['value'] == '') {
- switch ($rule['operator']) {
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL :
- $retVal = (($cellValue == '') || ($cellValue === NULL));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL :
- $retVal = (($cellValue != '') && ($cellValue !== NULL));
- break;
- default :
- $retVal = TRUE;
- break;
- }
- } else {
- // String values are always tested for equality, factoring in for wildcards (hence a regexp test)
- $retVal = preg_match('/^'.$rule['value'].'$/i',$cellValue);
- }
- // If there are multiple conditions, then we need to test both using the appropriate join operator
- switch ($join) {
- case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR :
- $returnVal = $returnVal || $retVal;
- // Break as soon as we have a TRUE match for OR joins,
- // to avoid unnecessary additional code execution
- if ($returnVal)
- return $returnVal;
- break;
- case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND :
- $returnVal = $returnVal && $retVal;
- break;
- }
- }
-
- return $returnVal;
- }
-
- /**
- * Test if cell date value is matches a set of values defined by a set of months
- *
- * @param mixed $cellValue
- * @param mixed[] $dataSet
- * @return boolean
- */
- private static function _filterTestInPeriodDateSet($cellValue,$monthSet)
- {
- // Blank cells are always ignored, so return a FALSE
- if (($cellValue == '') || ($cellValue === NULL)) {
- return FALSE;
- }
-
- if (is_numeric($cellValue)) {
- $dateValue = date('m',PHPExcel_Shared_Date::ExcelToPHP($cellValue));
- if (in_array($dateValue,$monthSet)) {
- return TRUE;
- }
- }
-
- return FALSE;
- }
-
- /**
- * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching
- *
- * @var array
- */
- private static $_fromReplace = array('\*', '\?', '~~', '~.*', '~.?');
- private static $_toReplace = array('.*', '.', '~', '\*', '\?');
-
-
- /**
- * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation
- *
- * @param string $dynamicRuleType
- * @param PHPExcel_Worksheet_AutoFilter_Column $filterColumn
- * @return mixed[]
- */
- private function _dynamicFilterDateRange($dynamicRuleType, &$filterColumn)
- {
- $rDateType = PHPExcel_Calculation_Functions::getReturnDateType();
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $val = $maxVal = NULL;
-
- $ruleValues = array();
- $baseDate = PHPExcel_Calculation_DateTime::DATENOW();
- // Calculate start/end dates for the required date range based on current date
- switch ($dynamicRuleType) {
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK :
- $baseDate = strtotime('-7 days',$baseDate);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK :
- $baseDate = strtotime('-7 days',$baseDate);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH :
- $baseDate = strtotime('-1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH :
- $baseDate = strtotime('+1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER :
- $baseDate = strtotime('-3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER :
- $baseDate = strtotime('+3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR :
- $baseDate = strtotime('-1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR :
- $baseDate = strtotime('+1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- }
-
- switch ($dynamicRuleType) {
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW :
- $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate));
- $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate);
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE :
- $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate));
- $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR :
- $maxVal = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,31,12,date('Y',$baseDate)));
- ++$maxVal;
- $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER :
- $thisMonth = date('m',$baseDate);
- $thisQuarter = floor(--$thisMonth / 3);
- $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),(1+$thisQuarter)*3,date('Y',$baseDate)));
- ++$maxVal;
- $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1+$thisQuarter*3,date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH :
- $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),date('m',$baseDate),date('Y',$baseDate)));
- ++$maxVal;
- $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate)));
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK :
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK :
- $dayOfWeek = date('w',$baseDate);
- $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate) - $dayOfWeek;
- $maxVal = $val + 7;
- break;
- }
-
- switch ($dynamicRuleType) {
- // Adjust Today dates for Yesterday and Tomorrow
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY :
- --$maxVal;
- --$val;
- break;
- case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW :
- ++$maxVal;
- ++$val;
- break;
- }
-
- // Set the filter column rule attributes ready for writing
- $filterColumn->setAttributes(array( 'val' => $val,
- 'maxVal' => $maxVal
- )
- );
-
- // Set the rules for identifying rows for hide/show
- $ruleValues[] = array( 'operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
- 'value' => $val
- );
- $ruleValues[] = array( 'operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN,
- 'value' => $maxVal
- );
- PHPExcel_Calculation_Functions::setReturnDateType($rDateType);
-
- return array(
- 'method' => '_filterTestInCustomDataSet',
- 'arguments' => array( 'filterRules' => $ruleValues,
- 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND
- )
- );
- }
-
- private function _calculateTopTenValue($columnID,$startRow,$endRow,$ruleType,$ruleValue) {
- $range = $columnID.$startRow.':'.$columnID.$endRow;
- $dataValues = PHPExcel_Calculation_Functions::flattenArray(
- $this->_workSheet->rangeToArray($range,NULL,TRUE,FALSE)
- );
-
- $dataValues = array_filter($dataValues);
- if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) {
- rsort($dataValues);
- } else {
- sort($dataValues);
- }
-
- return array_pop(array_slice($dataValues,0,$ruleValue));
- }
-
- /**
- * 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();
- 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
- list($periodType,$period) = sscanf($dynamicRuleType,'%[A-Z]%d');
- 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);
+ /**
+ * 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;
- }
-
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- if ($key == '_workSheet') {
- // Detach from worksheet
- $this->{$key} = NULL;
- } else {
- $this->{$key} = clone $value;
- }
- } elseif ((is_array($value)) && ($key == '_columns')) {
- // The columns array of PHPExcel_Worksheet_AutoFilter objects
- $this->{$key} = array();
- foreach ($value as $k => $v) {
- $this->{$key}[$k] = clone $v;
- // attach the new cloned Column to this new cloned Autofilter object
- $this->{$key}[$k]->setParent($this);
- }
- } else {
- $this->{$key} = $value;
- }
- }
- }
-
- /**
- * toString method replicates previous behavior by returning the range if object is
- * referenced as a property of its parent.
- */
- public function __toString() {
- return (string) $this->_range;
- }
+ // 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;
+ }
+
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ if ($key == 'workSheet') {
+ // Detach from worksheet
+ $this->{$key} = null;
+ } else {
+ $this->{$key} = clone $value;
+ }
+ } elseif ((is_array($value)) && ($key == 'columns')) {
+ // The columns array of PHPExcel_Worksheet_AutoFilter objects
+ $this->{$key} = array();
+ foreach ($value as $k => $v) {
+ $this->{$key}[$k] = clone $v;
+ // attach the new cloned Column to this new cloned Autofilter object
+ $this->{$key}[$k]->setParent($this);
+ }
+ } else {
+ $this->{$key} = $value;
+ }
+ }
+ }
+
+ /**
+ * toString method replicates previous behavior by returning the range if object is
+ * referenced as a property of its parent.
+ */
+ public function __toString()
+ {
+ return (string) $this->range;
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/AutoFilter/Column.php b/Classes/PHPExcel/Worksheet/AutoFilter/Column.php
index 9a743520c..d64fd8165 100644
--- a/Classes/PHPExcel/Worksheet/AutoFilter/Column.php
+++ b/Classes/PHPExcel/Worksheet/AutoFilter/Column.php
@@ -1,8 +1,9 @@
_columnIndex = $pColumn;
- $this->_parent = $pParent;
- }
-
- /**
- * Get AutoFilter Column Index
- *
- * @return string
- */
- public function getColumnIndex() {
- return $this->_columnIndex;
- }
-
- /**
- * Set AutoFilter Column Index
- *
- * @param string $pColumn Column (e.g. A)
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function setColumnIndex($pColumn) {
- // Uppercase coordinate
- $pColumn = strtoupper($pColumn);
- if ($this->_parent !== NULL) {
- $this->_parent->testColumnInRange($pColumn);
- }
-
- $this->_columnIndex = $pColumn;
-
- return $this;
- }
-
- /**
- * Get this Column's AutoFilter Parent
- *
- * @return PHPExcel_Worksheet_AutoFilter
- */
- public function getParent() {
- return $this->_parent;
- }
-
- /**
- * Set this Column's AutoFilter Parent
- *
- * @param PHPExcel_Worksheet_AutoFilter
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function setParent(PHPExcel_Worksheet_AutoFilter $pParent = NULL) {
- $this->_parent = $pParent;
-
- return $this;
- }
-
- /**
- * Get AutoFilter Type
- *
- * @return string
- */
- public function getFilterType() {
- return $this->_filterType;
- }
-
- /**
- * Set AutoFilter Type
- *
- * @param string $pFilterType
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function setFilterType($pFilterType = self::AUTOFILTER_FILTERTYPE_FILTER) {
- if (!in_array($pFilterType,self::$_filterTypes)) {
- throw new PHPExcel_Exception('Invalid filter type for column AutoFilter.');
- }
-
- $this->_filterType = $pFilterType;
-
- return $this;
- }
-
- /**
- * Get AutoFilter Multiple Rules And/Or Join
- *
- * @return string
- */
- public function getJoin() {
- return $this->_join;
- }
-
- /**
- * Set AutoFilter Multiple Rules And/Or
- *
- * @param string $pJoin And/Or
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function setJoin($pJoin = self::AUTOFILTER_COLUMN_JOIN_OR) {
- // Lowercase And/Or
- $pJoin = strtolower($pJoin);
- if (!in_array($pJoin,self::$_ruleJoins)) {
- throw new PHPExcel_Exception('Invalid rule connection for column AutoFilter.');
- }
-
- $this->_join = $pJoin;
-
- return $this;
- }
-
- /**
- * Set AutoFilter Attributes
- *
- * @param string[] $pAttributes
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function setAttributes($pAttributes = array()) {
- $this->_attributes = $pAttributes;
-
- return $this;
- }
-
- /**
- * Set An AutoFilter Attribute
- *
- * @param string $pName Attribute Name
- * @param string $pValue Attribute Value
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function setAttribute($pName, $pValue) {
- $this->_attributes[$pName] = $pValue;
-
- return $this;
- }
-
- /**
- * Get AutoFilter Column Attributes
- *
- * @return string
- */
- public function getAttributes() {
- return $this->_attributes;
- }
-
- /**
- * Get specific AutoFilter Column Attribute
- *
- * @param string $pName Attribute Name
- * @return string
- */
- public function getAttribute($pName) {
- if (isset($this->_attributes[$pName]))
- return $this->_attributes[$pName];
- return NULL;
- }
-
- /**
- * Get all AutoFilter Column Rules
- *
- * @throws PHPExcel_Exception
- * @return array of PHPExcel_Worksheet_AutoFilter_Column_Rule
- */
- public function getRules() {
- return $this->_ruleset;
- }
-
- /**
- * Get a specified AutoFilter Column Rule
- *
- * @param integer $pIndex Rule index in the ruleset array
- * @return PHPExcel_Worksheet_AutoFilter_Column_Rule
- */
- public function getRule($pIndex) {
- if (!isset($this->_ruleset[$pIndex])) {
- $this->_ruleset[$pIndex] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this);
- }
- return $this->_ruleset[$pIndex];
- }
-
- /**
- * Create a new AutoFilter Column Rule in the ruleset
- *
- * @return PHPExcel_Worksheet_AutoFilter_Column_Rule
- */
- public function createRule() {
- $this->_ruleset[] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this);
-
- return end($this->_ruleset);
- }
-
- /**
- * Add a new AutoFilter Column Rule to the ruleset
- *
- * @param PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule
- * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned
- * @return PHPExcel_Worksheet_AutoFilter_Column|PHPExcel_Worksheet_AutoFilter_Column_Rule
- */
- public function addRule(PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule, $returnRule=TRUE) {
- $pRule->setParent($this);
- $this->_ruleset[] = $pRule;
-
- return ($returnRule) ? $pRule : $this;
- }
-
- /**
- * Delete a specified AutoFilter Column Rule
- * If the number of rules is reduced to 1, then we reset And/Or logic to Or
- *
- * @param integer $pIndex Rule index in the ruleset array
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function deleteRule($pIndex) {
- if (isset($this->_ruleset[$pIndex])) {
- unset($this->_ruleset[$pIndex]);
- // If we've just deleted down to a single rule, then reset And/Or joining to Or
- if (count($this->_ruleset) <= 1) {
- $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
- }
- }
-
- return $this;
- }
-
- /**
- * Delete all AutoFilter Column Rules
- *
- * @return PHPExcel_Worksheet_AutoFilter_Column
- */
- public function clearRules() {
- $this->_ruleset = array();
- $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
-
- return $this;
- }
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- if ($key == '_parent') {
- // Detach from autofilter parent
- $this->$key = NULL;
- } else {
- $this->$key = clone $value;
- }
- } elseif ((is_array($value)) && ($key == '_ruleset')) {
- // The columns array of PHPExcel_Worksheet_AutoFilter objects
- $this->$key = array();
- foreach ($value as $k => $v) {
- $this->$key[$k] = clone $v;
- // attach the new cloned Rule to this new cloned Autofilter Cloned object
- $this->$key[$k]->setParent($this);
- }
- } else {
- $this->$key = $value;
- }
- }
- }
-
+ const AUTOFILTER_FILTERTYPE_FILTER = 'filters';
+ const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters';
+ // Supports no more than 2 rules, with an And/Or join criteria
+ // if more than 1 rule is defined
+ const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter';
+ // Even though the filter rule is constant, the filtered data can vary
+ // e.g. filtered by date = TODAY
+ const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10';
+
+ /**
+ * Types of autofilter rules
+ *
+ * @var string[]
+ */
+ private static $filterTypes = array(
+ // Currently we're not handling
+ // colorFilter
+ // extLst
+ // iconFilter
+ self::AUTOFILTER_FILTERTYPE_FILTER,
+ self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER,
+ self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER,
+ self::AUTOFILTER_FILTERTYPE_TOPTENFILTER,
+ );
+
+ /* Multiple Rule Connections */
+ const AUTOFILTER_COLUMN_JOIN_AND = 'and';
+ const AUTOFILTER_COLUMN_JOIN_OR = 'or';
+
+ /**
+ * Join options for autofilter rules
+ *
+ * @var string[]
+ */
+ private static $ruleJoins = array(
+ self::AUTOFILTER_COLUMN_JOIN_AND,
+ self::AUTOFILTER_COLUMN_JOIN_OR,
+ );
+
+ /**
+ * Autofilter
+ *
+ * @var PHPExcel_Worksheet_AutoFilter
+ */
+ private $parent;
+
+
+ /**
+ * Autofilter Column Index
+ *
+ * @var string
+ */
+ private $columnIndex = '';
+
+
+ /**
+ * Autofilter Column Filter Type
+ *
+ * @var string
+ */
+ private $filterType = self::AUTOFILTER_FILTERTYPE_FILTER;
+
+
+ /**
+ * Autofilter Multiple Rules And/Or
+ *
+ * @var string
+ */
+ private $join = self::AUTOFILTER_COLUMN_JOIN_OR;
+
+
+ /**
+ * Autofilter Column Rules
+ *
+ * @var array of PHPExcel_Worksheet_AutoFilter_Column_Rule
+ */
+ private $ruleset = array();
+
+
+ /**
+ * Autofilter Column Dynamic Attributes
+ *
+ * @var array of mixed
+ */
+ private $attributes = array();
+
+
+ /**
+ * Create a new PHPExcel_Worksheet_AutoFilter_Column
+ *
+ * @param string $pColumn Column (e.g. A)
+ * @param PHPExcel_Worksheet_AutoFilter $pParent Autofilter for this column
+ */
+ public function __construct($pColumn, PHPExcel_Worksheet_AutoFilter $pParent = null)
+ {
+ $this->columnIndex = $pColumn;
+ $this->parent = $pParent;
+ }
+
+ /**
+ * Get AutoFilter Column Index
+ *
+ * @return string
+ */
+ public function getColumnIndex()
+ {
+ return $this->columnIndex;
+ }
+
+ /**
+ * Set AutoFilter Column Index
+ *
+ * @param string $pColumn Column (e.g. A)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function setColumnIndex($pColumn)
+ {
+ // Uppercase coordinate
+ $pColumn = strtoupper($pColumn);
+ if ($this->parent !== null) {
+ $this->parent->testColumnInRange($pColumn);
+ }
+
+ $this->columnIndex = $pColumn;
+
+ return $this;
+ }
+
+ /**
+ * Get this Column's AutoFilter Parent
+ *
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function getParent()
+ {
+ return $this->parent;
+ }
+
+ /**
+ * Set this Column's AutoFilter Parent
+ *
+ * @param PHPExcel_Worksheet_AutoFilter
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function setParent(PHPExcel_Worksheet_AutoFilter $pParent = null)
+ {
+ $this->parent = $pParent;
+
+ return $this;
+ }
+
+ /**
+ * Get AutoFilter Type
+ *
+ * @return string
+ */
+ public function getFilterType()
+ {
+ return $this->filterType;
+ }
+
+ /**
+ * Set AutoFilter Type
+ *
+ * @param string $pFilterType
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function setFilterType($pFilterType = self::AUTOFILTER_FILTERTYPE_FILTER)
+ {
+ if (!in_array($pFilterType, self::$filterTypes)) {
+ throw new PHPExcel_Exception('Invalid filter type for column AutoFilter.');
+ }
+
+ $this->filterType = $pFilterType;
+
+ return $this;
+ }
+
+ /**
+ * Get AutoFilter Multiple Rules And/Or Join
+ *
+ * @return string
+ */
+ public function getJoin()
+ {
+ return $this->join;
+ }
+
+ /**
+ * Set AutoFilter Multiple Rules And/Or
+ *
+ * @param string $pJoin And/Or
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function setJoin($pJoin = self::AUTOFILTER_COLUMN_JOIN_OR)
+ {
+ // Lowercase And/Or
+ $pJoin = strtolower($pJoin);
+ if (!in_array($pJoin, self::$ruleJoins)) {
+ throw new PHPExcel_Exception('Invalid rule connection for column AutoFilter.');
+ }
+
+ $this->join = $pJoin;
+
+ return $this;
+ }
+
+ /**
+ * Set AutoFilter Attributes
+ *
+ * @param string[] $pAttributes
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function setAttributes($pAttributes = array())
+ {
+ $this->attributes = $pAttributes;
+
+ return $this;
+ }
+
+ /**
+ * Set An AutoFilter Attribute
+ *
+ * @param string $pName Attribute Name
+ * @param string $pValue Attribute Value
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function setAttribute($pName, $pValue)
+ {
+ $this->attributes[$pName] = $pValue;
+
+ return $this;
+ }
+
+ /**
+ * Get AutoFilter Column Attributes
+ *
+ * @return string
+ */
+ public function getAttributes()
+ {
+ return $this->attributes;
+ }
+
+ /**
+ * Get specific AutoFilter Column Attribute
+ *
+ * @param string $pName Attribute Name
+ * @return string
+ */
+ public function getAttribute($pName)
+ {
+ if (isset($this->attributes[$pName])) {
+ return $this->attributes[$pName];
+ }
+ return null;
+ }
+
+ /**
+ * Get all AutoFilter Column Rules
+ *
+ * @throws PHPExcel_Exception
+ * @return array of PHPExcel_Worksheet_AutoFilter_Column_Rule
+ */
+ public function getRules()
+ {
+ return $this->ruleset;
+ }
+
+ /**
+ * Get a specified AutoFilter Column Rule
+ *
+ * @param integer $pIndex Rule index in the ruleset array
+ * @return PHPExcel_Worksheet_AutoFilter_Column_Rule
+ */
+ public function getRule($pIndex)
+ {
+ if (!isset($this->ruleset[$pIndex])) {
+ $this->ruleset[$pIndex] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this);
+ }
+ return $this->ruleset[$pIndex];
+ }
+
+ /**
+ * Create a new AutoFilter Column Rule in the ruleset
+ *
+ * @return PHPExcel_Worksheet_AutoFilter_Column_Rule
+ */
+ public function createRule()
+ {
+ $this->ruleset[] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this);
+
+ return end($this->ruleset);
+ }
+
+ /**
+ * Add a new AutoFilter Column Rule to the ruleset
+ *
+ * @param PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule
+ * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned
+ * @return PHPExcel_Worksheet_AutoFilter_Column|PHPExcel_Worksheet_AutoFilter_Column_Rule
+ */
+ public function addRule(PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule, $returnRule = true)
+ {
+ $pRule->setParent($this);
+ $this->ruleset[] = $pRule;
+
+ return ($returnRule) ? $pRule : $this;
+ }
+
+ /**
+ * Delete a specified AutoFilter Column Rule
+ * If the number of rules is reduced to 1, then we reset And/Or logic to Or
+ *
+ * @param integer $pIndex Rule index in the ruleset array
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function deleteRule($pIndex)
+ {
+ if (isset($this->ruleset[$pIndex])) {
+ unset($this->ruleset[$pIndex]);
+ // If we've just deleted down to a single rule, then reset And/Or joining to Or
+ if (count($this->ruleset) <= 1) {
+ $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Delete all AutoFilter Column Rules
+ *
+ * @return PHPExcel_Worksheet_AutoFilter_Column
+ */
+ public function clearRules()
+ {
+ $this->ruleset = array();
+ $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
+
+ return $this;
+ }
+
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ if ($key == 'parent') {
+ // Detach from autofilter parent
+ $this->$key = null;
+ } else {
+ $this->$key = clone $value;
+ }
+ } elseif ((is_array($value)) && ($key == 'ruleset')) {
+ // The columns array of PHPExcel_Worksheet_AutoFilter objects
+ $this->$key = array();
+ foreach ($value as $k => $v) {
+ $this->$key[$k] = clone $v;
+ // attach the new cloned Rule to this new cloned Autofilter Cloned object
+ $this->$key[$k]->setParent($this);
+ }
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
index 771358bc2..39ad18bf3 100644
--- a/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
+++ b/Classes/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
@@ -1,8 +1,9 @@
- *
- * $objDrawing->setResizeProportional(true);
- * $objDrawing->setWidthAndHeight(160,120);
- *
- *
+ * Example:
+ *
+ * $objDrawing->setResizeProportional(true);
+ * $objDrawing->setWidthAndHeight(160,120);
+ *
+ *
* @author Vincent@luo MSN:kele_100@hotmail.com
* @param int $width
* @param int $height
* @return PHPExcel_Worksheet_BaseDrawing
*/
- public function setWidthAndHeight($width = 0, $height = 0) {
- $xratio = $width / $this->_width;
- $yratio = $height / $this->_height;
- if ($this->_resizeProportional && !($width == 0 || $height == 0)) {
- if (($xratio * $this->_height) < $height) {
- $this->_height = ceil($xratio * $this->_height);
- $this->_width = $width;
- } else {
- $this->_width = ceil($yratio * $this->_width);
- $this->_height = $height;
- }
- }
- return $this;
- }
+ public function setWidthAndHeight($width = 0, $height = 0)
+ {
+ $xratio = $width / ($this->width != 0 ? $this->width : 1);
+ $yratio = $height / ($this->height != 0 ? $this->height : 1);
+ if ($this->resizeProportional && !($width == 0 || $height == 0)) {
+ if (($xratio * $this->height) < $height) {
+ $this->height = ceil($xratio * $this->height);
+ $this->width = $width;
+ } else {
+ $this->width = ceil($yratio * $this->width);
+ $this->height = $height;
+ }
+ } else {
+ $this->width = $width;
+ $this->height = $height;
+ }
+
+ return $this;
+ }
/**
* Get ResizeProportional
*
* @return boolean
*/
- public function getResizeProportional() {
- return $this->_resizeProportional;
+ public function getResizeProportional()
+ {
+ return $this->resizeProportional;
}
/**
@@ -402,9 +417,10 @@ public function getResizeProportional() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_BaseDrawing
*/
- public function setResizeProportional($pValue = true) {
- $this->_resizeProportional = $pValue;
- return $this;
+ public function setResizeProportional($pValue = true)
+ {
+ $this->resizeProportional = $pValue;
+ return $this;
}
/**
@@ -412,8 +428,9 @@ public function setResizeProportional($pValue = true) {
*
* @return int
*/
- public function getRotation() {
- return $this->_rotation;
+ public function getRotation()
+ {
+ return $this->rotation;
}
/**
@@ -422,9 +439,10 @@ public function getRotation() {
* @param int $pValue
* @return PHPExcel_Worksheet_BaseDrawing
*/
- public function setRotation($pValue = 0) {
- $this->_rotation = $pValue;
- return $this;
+ public function setRotation($pValue = 0)
+ {
+ $this->rotation = $pValue;
+ return $this;
}
/**
@@ -432,54 +450,58 @@ public function setRotation($pValue = 0) {
*
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function getShadow() {
- return $this->_shadow;
+ public function getShadow()
+ {
+ return $this->shadow;
}
/**
* Set Shadow
*
- * @param PHPExcel_Worksheet_Drawing_Shadow $pValue
- * @throws PHPExcel_Exception
+ * @param PHPExcel_Worksheet_Drawing_Shadow $pValue
+ * @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_BaseDrawing
*/
- public function setShadow(PHPExcel_Worksheet_Drawing_Shadow $pValue = null) {
- $this->_shadow = $pValue;
- return $this;
+ public function setShadow(PHPExcel_Worksheet_Drawing_Shadow $pValue = null)
+ {
+ $this->shadow = $pValue;
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_name
- . $this->_description
- . $this->_worksheet->getHashCode()
- . $this->_coordinates
- . $this->_offsetX
- . $this->_offsetY
- . $this->_width
- . $this->_height
- . $this->_rotation
- . $this->_shadow->getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ return md5(
+ $this->name .
+ $this->description .
+ $this->worksheet->getHashCode() .
+ $this->coordinates .
+ $this->offsetX .
+ $this->offsetY .
+ $this->width .
+ $this->height .
+ $this->rotation .
+ $this->shadow->getHashCode() .
+ __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/CellIterator.php b/Classes/PHPExcel/Worksheet/CellIterator.php
index 2378340d8..151c17f53 100644
--- a/Classes/PHPExcel/Worksheet/CellIterator.php
+++ b/Classes/PHPExcel/Worksheet/CellIterator.php
@@ -1,8 +1,9 @@
_subject = $subject;
- $this->_rowIndex = $rowIndex;
- }
-
- /**
- * Destructor
- */
- public function __destruct() {
- unset($this->_subject);
- }
-
- /**
- * Rewind iterator
- */
- public function rewind() {
- $this->_position = 0;
- }
+ /**
+ * PHPExcel_Worksheet to iterate
+ *
+ * @var PHPExcel_Worksheet
+ */
+ protected $subject;
/**
- * Current PHPExcel_Cell
+ * Current iterator position
*
- * @return PHPExcel_Cell
+ * @var mixed
*/
- public function current() {
- return $this->_subject->getCellByColumnAndRow($this->_position, $this->_rowIndex);
- }
+ protected $position = null;
/**
- * Current key
+ * Iterate only existing cells
*
- * @return int
+ * @var boolean
*/
- public function key() {
- return $this->_position;
- }
+ protected $onlyExistingCells = false;
/**
- * Next value
+ * Destructor
*/
- public function next() {
- ++$this->_position;
+ public function __destruct()
+ {
+ unset($this->subject);
}
/**
- * Are there any more PHPExcel_Cell instances available?
+ * Get loop only existing cells
*
* @return boolean
*/
- public function valid() {
- // columnIndexFromString() returns an index based at one,
- // treat it as a count when comparing it to the base zero
- // position.
- $columnCount = PHPExcel_Cell::columnIndexFromString($this->_subject->getHighestColumn());
-
- if ($this->_onlyExistingCells) {
- // If we aren't looking at an existing cell, either
- // because the first column doesn't exist or next() has
- // been called onto a nonexistent cell, then loop until we
- // find one, or pass the last column.
- while ($this->_position < $columnCount &&
- !$this->_subject->cellExistsByColumnAndRow($this->_position, $this->_rowIndex)) {
- ++$this->_position;
- }
- }
-
- return $this->_position < $columnCount;
+ public function getIterateOnlyExistingCells()
+ {
+ return $this->onlyExistingCells;
}
- /**
- * Get loop only existing cells
- *
- * @return boolean
- */
- public function getIterateOnlyExistingCells() {
- return $this->_onlyExistingCells;
- }
+ /**
+ * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary
+ *
+ * @throws PHPExcel_Exception
+ */
+ abstract protected function adjustForExistingOnlyRange();
+
+ /**
+ * Set the iterator to loop only existing cells
+ *
+ * @param boolean $value
+ * @throws PHPExcel_Exception
+ */
+ public function setIterateOnlyExistingCells($value = true)
+ {
+ $this->onlyExistingCells = (boolean) $value;
- /**
- * Set the iterator to loop only existing cells
- *
- * @param boolean $value
- */
- public function setIterateOnlyExistingCells($value = true) {
- $this->_onlyExistingCells = $value;
+ $this->adjustForExistingOnlyRange();
}
}
diff --git a/Classes/PHPExcel/Worksheet/Column.php b/Classes/PHPExcel/Worksheet/Column.php
new file mode 100644
index 000000000..6d3f36d17
--- /dev/null
+++ b/Classes/PHPExcel/Worksheet/Column.php
@@ -0,0 +1,86 @@
+parent = $parent;
+ $this->columnIndex = $columnIndex;
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->parent);
+ }
+
+ /**
+ * Get column index
+ *
+ * @return string
+ */
+ public function getColumnIndex()
+ {
+ return $this->columnIndex;
+ }
+
+ /**
+ * Get cell iterator
+ *
+ * @param integer $startRow The row number at which to start iterating
+ * @param integer $endRow Optionally, the row number at which to stop iterating
+ * @return PHPExcel_Worksheet_CellIterator
+ */
+ public function getCellIterator($startRow = 1, $endRow = null)
+ {
+ return new PHPExcel_Worksheet_ColumnCellIterator($this->parent, $this->columnIndex, $startRow, $endRow);
+ }
+}
diff --git a/Classes/PHPExcel/Worksheet/ColumnCellIterator.php b/Classes/PHPExcel/Worksheet/ColumnCellIterator.php
new file mode 100644
index 000000000..7b8c2190a
--- /dev/null
+++ b/Classes/PHPExcel/Worksheet/ColumnCellIterator.php
@@ -0,0 +1,216 @@
+subject = $subject;
+ $this->columnIndex = PHPExcel_Cell::columnIndexFromString($columnIndex) - 1;
+ $this->resetEnd($endRow);
+ $this->resetStart($startRow);
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->subject);
+ }
+
+ /**
+ * (Re)Set the start row and the current row pointer
+ *
+ * @param integer $startRow The row number at which to start iterating
+ * @return PHPExcel_Worksheet_ColumnCellIterator
+ * @throws PHPExcel_Exception
+ */
+ public function resetStart($startRow = 1)
+ {
+ $this->startRow = $startRow;
+ $this->adjustForExistingOnlyRange();
+ $this->seek($startRow);
+
+ return $this;
+ }
+
+ /**
+ * (Re)Set the end row
+ *
+ * @param integer $endRow The row number at which to stop iterating
+ * @return PHPExcel_Worksheet_ColumnCellIterator
+ * @throws PHPExcel_Exception
+ */
+ public function resetEnd($endRow = null)
+ {
+ $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow();
+ $this->adjustForExistingOnlyRange();
+
+ return $this;
+ }
+
+ /**
+ * Set the row pointer to the selected row
+ *
+ * @param integer $row The row number to set the current pointer at
+ * @return PHPExcel_Worksheet_ColumnCellIterator
+ * @throws PHPExcel_Exception
+ */
+ public function seek($row = 1)
+ {
+ if (($row < $this->startRow) || ($row > $this->endRow)) {
+ throw new PHPExcel_Exception("Row $row is out of range ({$this->startRow} - {$this->endRow})");
+ } elseif ($this->onlyExistingCells && !($this->subject->cellExistsByColumnAndRow($this->columnIndex, $row))) {
+ throw new PHPExcel_Exception('In "IterateOnlyExistingCells" mode and Cell does not exist');
+ }
+ $this->position = $row;
+
+ return $this;
+ }
+
+ /**
+ * Rewind the iterator to the starting row
+ */
+ public function rewind()
+ {
+ $this->position = $this->startRow;
+ }
+
+ /**
+ * Return the current cell in this worksheet column
+ *
+ * @return PHPExcel_Worksheet_Row
+ */
+ public function current()
+ {
+ return $this->subject->getCellByColumnAndRow($this->columnIndex, $this->position);
+ }
+
+ /**
+ * Return the current iterator key
+ *
+ * @return int
+ */
+ public function key()
+ {
+ return $this->position;
+ }
+
+ /**
+ * Set the iterator to its next value
+ */
+ public function next()
+ {
+ do {
+ ++$this->position;
+ } while (($this->onlyExistingCells) &&
+ (!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->position)) &&
+ ($this->position <= $this->endRow));
+ }
+
+ /**
+ * Set the iterator to its previous value
+ */
+ public function prev()
+ {
+ if ($this->position <= $this->startRow) {
+ throw new PHPExcel_Exception("Row is already at the beginning of range ({$this->startRow} - {$this->endRow})");
+ }
+
+ do {
+ --$this->position;
+ } while (($this->onlyExistingCells) &&
+ (!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->position)) &&
+ ($this->position >= $this->startRow));
+ }
+
+ /**
+ * Indicate if more rows exist in the worksheet range of rows that we're iterating
+ *
+ * @return boolean
+ */
+ public function valid()
+ {
+ return $this->position <= $this->endRow;
+ }
+
+ /**
+ * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary
+ *
+ * @throws PHPExcel_Exception
+ */
+ protected function adjustForExistingOnlyRange()
+ {
+ if ($this->onlyExistingCells) {
+ while ((!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->startRow)) &&
+ ($this->startRow <= $this->endRow)) {
+ ++$this->startRow;
+ }
+ if ($this->startRow > $this->endRow) {
+ throw new PHPExcel_Exception('No cells exist within the specified range');
+ }
+ while ((!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->endRow)) &&
+ ($this->endRow >= $this->startRow)) {
+ --$this->endRow;
+ }
+ if ($this->endRow < $this->startRow) {
+ throw new PHPExcel_Exception('No cells exist within the specified range');
+ }
+ }
+ }
+}
diff --git a/Classes/PHPExcel/Worksheet/ColumnDimension.php b/Classes/PHPExcel/Worksheet/ColumnDimension.php
index 3f7cad184..405b8258e 100644
--- a/Classes/PHPExcel/Worksheet/ColumnDimension.php
+++ b/Classes/PHPExcel/Worksheet/ColumnDimension.php
@@ -1,8 +1,9 @@
_columnIndex = $pIndex;
+ // Initialise values
+ $this->columnIndex = $pIndex;
- // set default index to cellXf
- $this->_xfIndex = 0;
+ // set dimension as unformatted by default
+ parent::__construct(0);
}
/**
@@ -105,8 +69,9 @@ public function __construct($pIndex = 'A')
*
* @return string
*/
- public function getColumnIndex() {
- return $this->_columnIndex;
+ public function getColumnIndex()
+ {
+ return $this->columnIndex;
}
/**
@@ -115,9 +80,10 @@ public function getColumnIndex() {
* @param string $pValue
* @return PHPExcel_Worksheet_ColumnDimension
*/
- public function setColumnIndex($pValue) {
- $this->_columnIndex = $pValue;
- return $this;
+ public function setColumnIndex($pValue)
+ {
+ $this->columnIndex = $pValue;
+ return $this;
}
/**
@@ -125,8 +91,9 @@ public function setColumnIndex($pValue) {
*
* @return double
*/
- public function getWidth() {
- return $this->_width;
+ public function getWidth()
+ {
+ return $this->width;
}
/**
@@ -135,9 +102,10 @@ public function getWidth() {
* @param double $pValue
* @return PHPExcel_Worksheet_ColumnDimension
*/
- public function setWidth($pValue = -1) {
- $this->_width = $pValue;
- return $this;
+ public function setWidth($pValue = -1)
+ {
+ $this->width = $pValue;
+ return $this;
}
/**
@@ -145,8 +113,9 @@ public function setWidth($pValue = -1) {
*
* @return bool
*/
- public function getAutoSize() {
- return $this->_autoSize;
+ public function getAutoSize()
+ {
+ return $this->autoSize;
}
/**
@@ -155,112 +124,9 @@ public function getAutoSize() {
* @param bool $pValue
* @return PHPExcel_Worksheet_ColumnDimension
*/
- public function setAutoSize($pValue = false) {
- $this->_autoSize = $pValue;
- return $this;
- }
-
- /**
- * Get Visible
- *
- * @return bool
- */
- public function getVisible() {
- return $this->_visible;
- }
-
- /**
- * Set Visible
- *
- * @param bool $pValue
- * @return PHPExcel_Worksheet_ColumnDimension
- */
- public function setVisible($pValue = true) {
- $this->_visible = $pValue;
- return $this;
- }
-
- /**
- * Get Outline Level
- *
- * @return int
- */
- public function getOutlineLevel() {
- return $this->_outlineLevel;
- }
-
- /**
- * Set Outline Level
- *
- * Value must be between 0 and 7
- *
- * @param int $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_ColumnDimension
- */
- public function setOutlineLevel($pValue) {
- if ($pValue < 0 || $pValue > 7) {
- throw new PHPExcel_Exception("Outline level must range between 0 and 7.");
- }
-
- $this->_outlineLevel = $pValue;
- return $this;
- }
-
- /**
- * Get Collapsed
- *
- * @return bool
- */
- public function getCollapsed() {
- return $this->_collapsed;
- }
-
- /**
- * Set Collapsed
- *
- * @param bool $pValue
- * @return PHPExcel_Worksheet_ColumnDimension
- */
- public function setCollapsed($pValue = true) {
- $this->_collapsed = $pValue;
- return $this;
+ public function setAutoSize($pValue = false)
+ {
+ $this->autoSize = $pValue;
+ return $this;
}
-
- /**
- * Get index to cellXf
- *
- * @return int
- */
- public function getXfIndex()
- {
- return $this->_xfIndex;
- }
-
- /**
- * Set index to cellXf
- *
- * @param int $pValue
- * @return PHPExcel_Worksheet_ColumnDimension
- */
- public function setXfIndex($pValue = 0)
- {
- $this->_xfIndex = $pValue;
- return $this;
- }
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
-
}
diff --git a/Classes/PHPExcel/Worksheet/ColumnIterator.php b/Classes/PHPExcel/Worksheet/ColumnIterator.php
new file mode 100644
index 000000000..0db3e5347
--- /dev/null
+++ b/Classes/PHPExcel/Worksheet/ColumnIterator.php
@@ -0,0 +1,201 @@
+subject = $subject;
+ $this->resetEnd($endColumn);
+ $this->resetStart($startColumn);
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->subject);
+ }
+
+ /**
+ * (Re)Set the start column and the current column pointer
+ *
+ * @param integer $startColumn The column address at which to start iterating
+ * @return PHPExcel_Worksheet_ColumnIterator
+ * @throws PHPExcel_Exception
+ */
+ public function resetStart($startColumn = 'A')
+ {
+ $startColumnIndex = PHPExcel_Cell::columnIndexFromString($startColumn) - 1;
+ if ($startColumnIndex > PHPExcel_Cell::columnIndexFromString($this->subject->getHighestColumn()) - 1) {
+ throw new PHPExcel_Exception("Start column ({$startColumn}) is beyond highest column ({$this->subject->getHighestColumn()})");
+ }
+
+ $this->startColumn = $startColumnIndex;
+ if ($this->endColumn < $this->startColumn) {
+ $this->endColumn = $this->startColumn;
+ }
+ $this->seek($startColumn);
+
+ return $this;
+ }
+
+ /**
+ * (Re)Set the end column
+ *
+ * @param string $endColumn The column address at which to stop iterating
+ * @return PHPExcel_Worksheet_ColumnIterator
+ */
+ public function resetEnd($endColumn = null)
+ {
+ $endColumn = ($endColumn) ? $endColumn : $this->subject->getHighestColumn();
+ $this->endColumn = PHPExcel_Cell::columnIndexFromString($endColumn) - 1;
+
+ return $this;
+ }
+
+ /**
+ * Set the column pointer to the selected column
+ *
+ * @param string $column The column address to set the current pointer at
+ * @return PHPExcel_Worksheet_ColumnIterator
+ * @throws PHPExcel_Exception
+ */
+ public function seek($column = 'A')
+ {
+ $column = PHPExcel_Cell::columnIndexFromString($column) - 1;
+ if (($column < $this->startColumn) || ($column > $this->endColumn)) {
+ throw new PHPExcel_Exception("Column $column is out of range ({$this->startColumn} - {$this->endColumn})");
+ }
+ $this->position = $column;
+
+ return $this;
+ }
+
+ /**
+ * Rewind the iterator to the starting column
+ */
+ public function rewind()
+ {
+ $this->position = $this->startColumn;
+ }
+
+ /**
+ * Return the current column in this worksheet
+ *
+ * @return PHPExcel_Worksheet_Column
+ */
+ public function current()
+ {
+ return new PHPExcel_Worksheet_Column($this->subject, PHPExcel_Cell::stringFromColumnIndex($this->position));
+ }
+
+ /**
+ * Return the current iterator key
+ *
+ * @return string
+ */
+ public function key()
+ {
+ return PHPExcel_Cell::stringFromColumnIndex($this->position);
+ }
+
+ /**
+ * Set the iterator to its next value
+ */
+ public function next()
+ {
+ ++$this->position;
+ }
+
+ /**
+ * Set the iterator to its previous value
+ *
+ * @throws PHPExcel_Exception
+ */
+ public function prev()
+ {
+ if ($this->position <= $this->startColumn) {
+ throw new PHPExcel_Exception(
+ "Column is already at the beginning of range (" .
+ PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . " - " .
+ PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . ")"
+ );
+ }
+
+ --$this->position;
+ }
+
+ /**
+ * Indicate if more columns exist in the worksheet range of columns that we're iterating
+ *
+ * @return boolean
+ */
+ public function valid()
+ {
+ return $this->position <= $this->endColumn;
+ }
+}
diff --git a/Classes/PHPExcel/Worksheet/Dimension.php b/Classes/PHPExcel/Worksheet/Dimension.php
new file mode 100644
index 000000000..84f692cb5
--- /dev/null
+++ b/Classes/PHPExcel/Worksheet/Dimension.php
@@ -0,0 +1,178 @@
+xfIndex = $initialValue;
+ }
+
+ /**
+ * Get Visible
+ *
+ * @return bool
+ */
+ public function getVisible()
+ {
+ return $this->visible;
+ }
+
+ /**
+ * Set Visible
+ *
+ * @param bool $pValue
+ * @return PHPExcel_Worksheet_Dimension
+ */
+ public function setVisible($pValue = true)
+ {
+ $this->visible = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Outline Level
+ *
+ * @return int
+ */
+ public function getOutlineLevel()
+ {
+ return $this->outlineLevel;
+ }
+
+ /**
+ * Set Outline Level
+ *
+ * Value must be between 0 and 7
+ *
+ * @param int $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_Dimension
+ */
+ public function setOutlineLevel($pValue)
+ {
+ if ($pValue < 0 || $pValue > 7) {
+ throw new PHPExcel_Exception("Outline level must range between 0 and 7.");
+ }
+
+ $this->outlineLevel = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Collapsed
+ *
+ * @return bool
+ */
+ public function getCollapsed()
+ {
+ return $this->collapsed;
+ }
+
+ /**
+ * Set Collapsed
+ *
+ * @param bool $pValue
+ * @return PHPExcel_Worksheet_Dimension
+ */
+ public function setCollapsed($pValue = true)
+ {
+ $this->collapsed = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get index to cellXf
+ *
+ * @return int
+ */
+ public function getXfIndex()
+ {
+ return $this->xfIndex;
+ }
+
+ /**
+ * Set index to cellXf
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_Dimension
+ */
+ public function setXfIndex($pValue = 0)
+ {
+ $this->xfIndex = $pValue;
+ return $this;
+ }
+
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
+}
diff --git a/Classes/PHPExcel/Worksheet/Drawing.php b/Classes/PHPExcel/Worksheet/Drawing.php
index 922bbb439..e39d3eb91 100644
--- a/Classes/PHPExcel/Worksheet/Drawing.php
+++ b/Classes/PHPExcel/Worksheet/Drawing.php
@@ -1,8 +1,9 @@
_path = '';
+ // Initialise values
+ $this->path = '';
- // Initialize parent
- parent::__construct();
+ // Initialize parent
+ parent::__construct();
}
/**
@@ -59,8 +51,9 @@ public function __construct()
*
* @return string
*/
- public function getFilename() {
- return basename($this->_path);
+ public function getFilename()
+ {
+ return basename($this->path);
}
/**
@@ -68,10 +61,11 @@ public function getFilename() {
*
* @return string
*/
- public function getIndexedFilename() {
- $fileName = $this->getFilename();
- $fileName = str_replace(' ', '_', $fileName);
- return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension();
+ public function getIndexedFilename()
+ {
+ $fileName = $this->getFilename();
+ $fileName = str_replace(' ', '_', $fileName);
+ return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension();
}
/**
@@ -79,9 +73,10 @@ public function getIndexedFilename() {
*
* @return string
*/
- public function getExtension() {
- $exploded = explode(".", basename($this->_path));
- return $exploded[count($exploded) - 1];
+ public function getExtension()
+ {
+ $exploded = explode(".", basename($this->path));
+ return $exploded[count($exploded) - 1];
}
/**
@@ -89,60 +84,64 @@ public function getExtension() {
*
* @return string
*/
- public function getPath() {
- return $this->_path;
+ public function getPath()
+ {
+ return $this->path;
}
/**
* Set Path
*
- * @param string $pValue File path
- * @param boolean $pVerifyFile Verify file
- * @throws PHPExcel_Exception
+ * @param string $pValue File path
+ * @param boolean $pVerifyFile Verify file
+ * @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_Drawing
*/
- public function setPath($pValue = '', $pVerifyFile = true) {
- if ($pVerifyFile) {
- if (file_exists($pValue)) {
- $this->_path = $pValue;
+ public function setPath($pValue = '', $pVerifyFile = true)
+ {
+ if ($pVerifyFile) {
+ if (file_exists($pValue)) {
+ $this->path = $pValue;
- if ($this->_width == 0 && $this->_height == 0) {
- // Get width/height
- list($this->_width, $this->_height) = getimagesize($pValue);
- }
- } else {
- throw new PHPExcel_Exception("File $pValue not found!");
- }
- } else {
- $this->_path = $pValue;
- }
- return $this;
+ if ($this->width == 0 && $this->height == 0) {
+ // Get width/height
+ list($this->width, $this->height) = getimagesize($pValue);
+ }
+ } else {
+ throw new PHPExcel_Exception("File $pValue not found!");
+ }
+ } else {
+ $this->path = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_path
- . parent::getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ return md5(
+ $this->path .
+ parent::getHashCode() .
+ __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Drawing/Shadow.php b/Classes/PHPExcel/Worksheet/Drawing/Shadow.php
index 01474cbb0..84db91d57 100644
--- a/Classes/PHPExcel/Worksheet/Drawing/Shadow.php
+++ b/Classes/PHPExcel/Worksheet/Drawing/Shadow.php
@@ -1,8 +1,9 @@
_visible = false;
- $this->_blurRadius = 6;
- $this->_distance = 2;
- $this->_direction = 0;
- $this->_alignment = PHPExcel_Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT;
- $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK);
- $this->_alpha = 50;
+ // Initialise values
+ $this->visible = false;
+ $this->blurRadius = 6;
+ $this->distance = 2;
+ $this->direction = 0;
+ $this->alignment = PHPExcel_Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT;
+ $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK);
+ $this->alpha = 50;
}
/**
@@ -118,8 +110,9 @@ public function __construct()
*
* @return boolean
*/
- public function getVisible() {
- return $this->_visible;
+ public function getVisible()
+ {
+ return $this->visible;
}
/**
@@ -128,9 +121,10 @@ public function getVisible() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setVisible($pValue = false) {
- $this->_visible = $pValue;
- return $this;
+ public function setVisible($pValue = false)
+ {
+ $this->visible = $pValue;
+ return $this;
}
/**
@@ -138,8 +132,9 @@ public function setVisible($pValue = false) {
*
* @return int
*/
- public function getBlurRadius() {
- return $this->_blurRadius;
+ public function getBlurRadius()
+ {
+ return $this->blurRadius;
}
/**
@@ -148,9 +143,10 @@ public function getBlurRadius() {
* @param int $pValue
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setBlurRadius($pValue = 6) {
- $this->_blurRadius = $pValue;
- return $this;
+ public function setBlurRadius($pValue = 6)
+ {
+ $this->blurRadius = $pValue;
+ return $this;
}
/**
@@ -158,8 +154,9 @@ public function setBlurRadius($pValue = 6) {
*
* @return int
*/
- public function getDistance() {
- return $this->_distance;
+ public function getDistance()
+ {
+ return $this->distance;
}
/**
@@ -168,9 +165,10 @@ public function getDistance() {
* @param int $pValue
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setDistance($pValue = 2) {
- $this->_distance = $pValue;
- return $this;
+ public function setDistance($pValue = 2)
+ {
+ $this->distance = $pValue;
+ return $this;
}
/**
@@ -178,8 +176,9 @@ public function setDistance($pValue = 2) {
*
* @return int
*/
- public function getDirection() {
- return $this->_direction;
+ public function getDirection()
+ {
+ return $this->direction;
}
/**
@@ -188,9 +187,10 @@ public function getDirection() {
* @param int $pValue
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setDirection($pValue = 0) {
- $this->_direction = $pValue;
- return $this;
+ public function setDirection($pValue = 0)
+ {
+ $this->direction = $pValue;
+ return $this;
}
/**
@@ -198,8 +198,9 @@ public function setDirection($pValue = 0) {
*
* @return int
*/
- public function getAlignment() {
- return $this->_alignment;
+ public function getAlignment()
+ {
+ return $this->alignment;
}
/**
@@ -208,9 +209,10 @@ public function getAlignment() {
* @param int $pValue
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setAlignment($pValue = 0) {
- $this->_alignment = $pValue;
- return $this;
+ public function setAlignment($pValue = 0)
+ {
+ $this->alignment = $pValue;
+ return $this;
}
/**
@@ -218,20 +220,22 @@ public function setAlignment($pValue = 0) {
*
* @return PHPExcel_Style_Color
*/
- public function getColor() {
- return $this->_color;
+ public function getColor()
+ {
+ return $this->color;
}
/**
* Set Color
*
- * @param PHPExcel_Style_Color $pValue
- * @throws PHPExcel_Exception
+ * @param PHPExcel_Style_Color $pValue
+ * @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setColor(PHPExcel_Style_Color $pValue = null) {
- $this->_color = $pValue;
- return $this;
+ public function setColor(PHPExcel_Style_Color $pValue = null)
+ {
+ $this->color = $pValue;
+ return $this;
}
/**
@@ -239,8 +243,9 @@ public function setColor(PHPExcel_Style_Color $pValue = null) {
*
* @return int
*/
- public function getAlpha() {
- return $this->_alpha;
+ public function getAlpha()
+ {
+ return $this->alpha;
}
/**
@@ -249,40 +254,43 @@ public function getAlpha() {
* @param int $pValue
* @return PHPExcel_Worksheet_Drawing_Shadow
*/
- public function setAlpha($pValue = 0) {
- $this->_alpha = $pValue;
- return $this;
+ public function setAlpha($pValue = 0)
+ {
+ $this->alpha = $pValue;
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- ($this->_visible ? 't' : 'f')
- . $this->_blurRadius
- . $this->_distance
- . $this->_direction
- . $this->_alignment
- . $this->_color->getHashCode()
- . $this->_alpha
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ return md5(
+ ($this->visible ? 't' : 'f') .
+ $this->blurRadius .
+ $this->distance .
+ $this->direction .
+ $this->alignment .
+ $this->color->getHashCode() .
+ $this->alpha .
+ __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/HeaderFooter.php b/Classes/PHPExcel/Worksheet/HeaderFooter.php
index 162482393..3a88923fc 100644
--- a/Classes/PHPExcel/Worksheet/HeaderFooter.php
+++ b/Classes/PHPExcel/Worksheet/HeaderFooter.php
@@ -1,8 +1,8 @@
* Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970:
@@ -37,7 +32,7 @@
*
* Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on
* the second line (center section).
- * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D
+ * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D
*
* General Rules:
* There is no required order in which these codes must appear.
@@ -89,96 +84,93 @@
* &H - code for "shadow style"
*
*
- * @category PHPExcel
- * @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Worksheet_HeaderFooter
{
- /* Header/footer image location */
- const IMAGE_HEADER_LEFT = 'LH';
- const IMAGE_HEADER_CENTER = 'CH';
- const IMAGE_HEADER_RIGHT = 'RH';
- const IMAGE_FOOTER_LEFT = 'LF';
- const IMAGE_FOOTER_CENTER = 'CF';
- const IMAGE_FOOTER_RIGHT = 'RF';
-
- /**
- * OddHeader
- *
- * @var string
- */
- private $_oddHeader = '';
-
- /**
- * OddFooter
- *
- * @var string
- */
- private $_oddFooter = '';
-
- /**
- * EvenHeader
- *
- * @var string
- */
- private $_evenHeader = '';
-
- /**
- * EvenFooter
- *
- * @var string
- */
- private $_evenFooter = '';
-
- /**
- * FirstHeader
- *
- * @var string
- */
- private $_firstHeader = '';
-
- /**
- * FirstFooter
- *
- * @var string
- */
- private $_firstFooter = '';
-
- /**
- * Different header for Odd/Even, defaults to false
- *
- * @var boolean
- */
- private $_differentOddEven = false;
-
- /**
- * Different header for first page, defaults to false
- *
- * @var boolean
- */
- private $_differentFirst = false;
-
- /**
- * Scale with document, defaults to true
- *
- * @var boolean
- */
- private $_scaleWithDocument = true;
-
- /**
- * Align with margins, defaults to true
- *
- * @var boolean
- */
- private $_alignWithMargins = true;
-
- /**
- * Header/footer images
- *
- * @var PHPExcel_Worksheet_HeaderFooterDrawing[]
- */
- private $_headerFooterImages = array();
+ /* Header/footer image location */
+ const IMAGE_HEADER_LEFT = 'LH';
+ const IMAGE_HEADER_CENTER = 'CH';
+ const IMAGE_HEADER_RIGHT = 'RH';
+ const IMAGE_FOOTER_LEFT = 'LF';
+ const IMAGE_FOOTER_CENTER = 'CF';
+ const IMAGE_FOOTER_RIGHT = 'RF';
+
+ /**
+ * OddHeader
+ *
+ * @var string
+ */
+ private $oddHeader = '';
+
+ /**
+ * OddFooter
+ *
+ * @var string
+ */
+ private $oddFooter = '';
+
+ /**
+ * EvenHeader
+ *
+ * @var string
+ */
+ private $evenHeader = '';
+
+ /**
+ * EvenFooter
+ *
+ * @var string
+ */
+ private $evenFooter = '';
+
+ /**
+ * FirstHeader
+ *
+ * @var string
+ */
+ private $firstHeader = '';
+
+ /**
+ * FirstFooter
+ *
+ * @var string
+ */
+ private $firstFooter = '';
+
+ /**
+ * Different header for Odd/Even, defaults to false
+ *
+ * @var boolean
+ */
+ private $differentOddEven = false;
+
+ /**
+ * Different header for first page, defaults to false
+ *
+ * @var boolean
+ */
+ private $differentFirst = false;
+
+ /**
+ * Scale with document, defaults to true
+ *
+ * @var boolean
+ */
+ private $scaleWithDocument = true;
+
+ /**
+ * Align with margins, defaults to true
+ *
+ * @var boolean
+ */
+ private $alignWithMargins = true;
+
+ /**
+ * Header/footer images
+ *
+ * @var PHPExcel_Worksheet_HeaderFooterDrawing[]
+ */
+ private $headerFooterImages = array();
/**
* Create a new PHPExcel_Worksheet_HeaderFooter
@@ -192,8 +184,9 @@ public function __construct()
*
* @return string
*/
- public function getOddHeader() {
- return $this->_oddHeader;
+ public function getOddHeader()
+ {
+ return $this->oddHeader;
}
/**
@@ -202,9 +195,10 @@ public function getOddHeader() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setOddHeader($pValue) {
- $this->_oddHeader = $pValue;
- return $this;
+ public function setOddHeader($pValue)
+ {
+ $this->oddHeader = $pValue;
+ return $this;
}
/**
@@ -212,8 +206,9 @@ public function setOddHeader($pValue) {
*
* @return string
*/
- public function getOddFooter() {
- return $this->_oddFooter;
+ public function getOddFooter()
+ {
+ return $this->oddFooter;
}
/**
@@ -222,9 +217,10 @@ public function getOddFooter() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setOddFooter($pValue) {
- $this->_oddFooter = $pValue;
- return $this;
+ public function setOddFooter($pValue)
+ {
+ $this->oddFooter = $pValue;
+ return $this;
}
/**
@@ -232,8 +228,9 @@ public function setOddFooter($pValue) {
*
* @return string
*/
- public function getEvenHeader() {
- return $this->_evenHeader;
+ public function getEvenHeader()
+ {
+ return $this->evenHeader;
}
/**
@@ -242,9 +239,10 @@ public function getEvenHeader() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setEvenHeader($pValue) {
- $this->_evenHeader = $pValue;
- return $this;
+ public function setEvenHeader($pValue)
+ {
+ $this->evenHeader = $pValue;
+ return $this;
}
/**
@@ -252,8 +250,9 @@ public function setEvenHeader($pValue) {
*
* @return string
*/
- public function getEvenFooter() {
- return $this->_evenFooter;
+ public function getEvenFooter()
+ {
+ return $this->evenFooter;
}
/**
@@ -262,9 +261,10 @@ public function getEvenFooter() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setEvenFooter($pValue) {
- $this->_evenFooter = $pValue;
- return $this;
+ public function setEvenFooter($pValue)
+ {
+ $this->evenFooter = $pValue;
+ return $this;
}
/**
@@ -272,8 +272,9 @@ public function setEvenFooter($pValue) {
*
* @return string
*/
- public function getFirstHeader() {
- return $this->_firstHeader;
+ public function getFirstHeader()
+ {
+ return $this->firstHeader;
}
/**
@@ -282,9 +283,10 @@ public function getFirstHeader() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setFirstHeader($pValue) {
- $this->_firstHeader = $pValue;
- return $this;
+ public function setFirstHeader($pValue)
+ {
+ $this->firstHeader = $pValue;
+ return $this;
}
/**
@@ -292,8 +294,9 @@ public function setFirstHeader($pValue) {
*
* @return string
*/
- public function getFirstFooter() {
- return $this->_firstFooter;
+ public function getFirstFooter()
+ {
+ return $this->firstFooter;
}
/**
@@ -302,9 +305,10 @@ public function getFirstFooter() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setFirstFooter($pValue) {
- $this->_firstFooter = $pValue;
- return $this;
+ public function setFirstFooter($pValue)
+ {
+ $this->firstFooter = $pValue;
+ return $this;
}
/**
@@ -312,8 +316,9 @@ public function setFirstFooter($pValue) {
*
* @return boolean
*/
- public function getDifferentOddEven() {
- return $this->_differentOddEven;
+ public function getDifferentOddEven()
+ {
+ return $this->differentOddEven;
}
/**
@@ -322,9 +327,10 @@ public function getDifferentOddEven() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setDifferentOddEven($pValue = false) {
- $this->_differentOddEven = $pValue;
- return $this;
+ public function setDifferentOddEven($pValue = false)
+ {
+ $this->differentOddEven = $pValue;
+ return $this;
}
/**
@@ -332,8 +338,9 @@ public function setDifferentOddEven($pValue = false) {
*
* @return boolean
*/
- public function getDifferentFirst() {
- return $this->_differentFirst;
+ public function getDifferentFirst()
+ {
+ return $this->differentFirst;
}
/**
@@ -342,9 +349,10 @@ public function getDifferentFirst() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setDifferentFirst($pValue = false) {
- $this->_differentFirst = $pValue;
- return $this;
+ public function setDifferentFirst($pValue = false)
+ {
+ $this->differentFirst = $pValue;
+ return $this;
}
/**
@@ -352,8 +360,9 @@ public function setDifferentFirst($pValue = false) {
*
* @return boolean
*/
- public function getScaleWithDocument() {
- return $this->_scaleWithDocument;
+ public function getScaleWithDocument()
+ {
+ return $this->scaleWithDocument;
}
/**
@@ -362,9 +371,10 @@ public function getScaleWithDocument() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setScaleWithDocument($pValue = true) {
- $this->_scaleWithDocument = $pValue;
- return $this;
+ public function setScaleWithDocument($pValue = true)
+ {
+ $this->scaleWithDocument = $pValue;
+ return $this;
}
/**
@@ -372,8 +382,9 @@ public function setScaleWithDocument($pValue = true) {
*
* @return boolean
*/
- public function getAlignWithMargins() {
- return $this->_alignWithMargins;
+ public function getAlignWithMargins()
+ {
+ return $this->alignWithMargins;
}
/**
@@ -382,9 +393,10 @@ public function getAlignWithMargins() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setAlignWithMargins($pValue = true) {
- $this->_alignWithMargins = $pValue;
- return $this;
+ public function setAlignWithMargins($pValue = true)
+ {
+ $this->alignWithMargins = $pValue;
+ return $this;
}
/**
@@ -395,9 +407,10 @@ public function setAlignWithMargins($pValue = true) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) {
- $this->_headerFooterImages[$location] = $image;
- return $this;
+ public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT)
+ {
+ $this->headerFooterImages[$location] = $image;
+ return $this;
}
/**
@@ -407,11 +420,12 @@ public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function removeImage($location = self::IMAGE_HEADER_LEFT) {
- if (isset($this->_headerFooterImages[$location])) {
- unset($this->_headerFooterImages[$location]);
- }
- return $this;
+ public function removeImage($location = self::IMAGE_HEADER_LEFT)
+ {
+ if (isset($this->headerFooterImages[$location])) {
+ unset($this->headerFooterImages[$location]);
+ }
+ return $this;
}
/**
@@ -421,13 +435,14 @@ public function removeImage($location = self::IMAGE_HEADER_LEFT) {
* @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setImages($images) {
- if (!is_array($images)) {
- throw new PHPExcel_Exception('Invalid parameter!');
- }
+ public function setImages($images)
+ {
+ if (!is_array($images)) {
+ throw new PHPExcel_Exception('Invalid parameter!');
+ }
- $this->_headerFooterImages = $images;
- return $this;
+ $this->headerFooterImages = $images;
+ return $this;
}
/**
@@ -435,31 +450,45 @@ public function setImages($images) {
*
* @return PHPExcel_Worksheet_HeaderFooterDrawing[]
*/
- public function getImages() {
- // Sort array
- $images = array();
- if (isset($this->_headerFooterImages[self::IMAGE_HEADER_LEFT])) $images[self::IMAGE_HEADER_LEFT] = $this->_headerFooterImages[self::IMAGE_HEADER_LEFT];
- if (isset($this->_headerFooterImages[self::IMAGE_HEADER_CENTER])) $images[self::IMAGE_HEADER_CENTER] = $this->_headerFooterImages[self::IMAGE_HEADER_CENTER];
- if (isset($this->_headerFooterImages[self::IMAGE_HEADER_RIGHT])) $images[self::IMAGE_HEADER_RIGHT] = $this->_headerFooterImages[self::IMAGE_HEADER_RIGHT];
- if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_LEFT])) $images[self::IMAGE_FOOTER_LEFT] = $this->_headerFooterImages[self::IMAGE_FOOTER_LEFT];
- if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_CENTER])) $images[self::IMAGE_FOOTER_CENTER] = $this->_headerFooterImages[self::IMAGE_FOOTER_CENTER];
- if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT])) $images[self::IMAGE_FOOTER_RIGHT] = $this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT];
- $this->_headerFooterImages = $images;
-
- return $this->_headerFooterImages;
+ public function getImages()
+ {
+ // Sort array
+ $images = array();
+ if (isset($this->headerFooterImages[self::IMAGE_HEADER_LEFT])) {
+ $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT];
+ }
+ if (isset($this->headerFooterImages[self::IMAGE_HEADER_CENTER])) {
+ $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER];
+ }
+ if (isset($this->headerFooterImages[self::IMAGE_HEADER_RIGHT])) {
+ $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT];
+ }
+ if (isset($this->headerFooterImages[self::IMAGE_FOOTER_LEFT])) {
+ $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT];
+ }
+ if (isset($this->headerFooterImages[self::IMAGE_FOOTER_CENTER])) {
+ $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER];
+ }
+ if (isset($this->headerFooterImages[self::IMAGE_FOOTER_RIGHT])) {
+ $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT];
+ }
+ $this->headerFooterImages = $images;
+
+ return $this->headerFooterImages;
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php b/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php
index 2e178f109..a491f4ba6 100644
--- a/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php
+++ b/Classes/PHPExcel/Worksheet/HeaderFooterDrawing.php
@@ -1,8 +1,9 @@
_path = '';
- $this->_name = '';
- $this->_offsetX = 0;
- $this->_offsetY = 0;
- $this->_width = 0;
- $this->_height = 0;
- $this->_resizeProportional = true;
+ // Initialise values
+ $this->path = '';
+ $this->name = '';
+ $this->offsetX = 0;
+ $this->offsetY = 0;
+ $this->width = 0;
+ $this->height = 0;
+ $this->resizeProportional = true;
}
/**
@@ -104,8 +96,9 @@ public function __construct()
*
* @return string
*/
- public function getName() {
- return $this->_name;
+ public function getName()
+ {
+ return $this->name;
}
/**
@@ -114,9 +107,10 @@ public function getName() {
* @param string $pValue
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setName($pValue = '') {
- $this->_name = $pValue;
- return $this;
+ public function setName($pValue = '')
+ {
+ $this->name = $pValue;
+ return $this;
}
/**
@@ -124,8 +118,9 @@ public function setName($pValue = '') {
*
* @return int
*/
- public function getOffsetX() {
- return $this->_offsetX;
+ public function getOffsetX()
+ {
+ return $this->offsetX;
}
/**
@@ -134,9 +129,10 @@ public function getOffsetX() {
* @param int $pValue
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setOffsetX($pValue = 0) {
- $this->_offsetX = $pValue;
- return $this;
+ public function setOffsetX($pValue = 0)
+ {
+ $this->offsetX = $pValue;
+ return $this;
}
/**
@@ -144,8 +140,9 @@ public function setOffsetX($pValue = 0) {
*
* @return int
*/
- public function getOffsetY() {
- return $this->_offsetY;
+ public function getOffsetY()
+ {
+ return $this->offsetY;
}
/**
@@ -154,9 +151,10 @@ public function getOffsetY() {
* @param int $pValue
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setOffsetY($pValue = 0) {
- $this->_offsetY = $pValue;
- return $this;
+ public function setOffsetY($pValue = 0)
+ {
+ $this->offsetY = $pValue;
+ return $this;
}
/**
@@ -164,8 +162,9 @@ public function setOffsetY($pValue = 0) {
*
* @return int
*/
- public function getWidth() {
- return $this->_width;
+ public function getWidth()
+ {
+ return $this->width;
}
/**
@@ -174,17 +173,18 @@ public function getWidth() {
* @param int $pValue
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setWidth($pValue = 0) {
- // Resize proportional?
- if ($this->_resizeProportional && $pValue != 0) {
- $ratio = $this->_width / $this->_height;
- $this->_height = round($ratio * $pValue);
- }
+ public function setWidth($pValue = 0)
+ {
+ // Resize proportional?
+ if ($this->resizeProportional && $pValue != 0) {
+ $ratio = $this->width / $this->height;
+ $this->height = round($ratio * $pValue);
+ }
- // Set width
- $this->_width = $pValue;
+ // Set width
+ $this->width = $pValue;
- return $this;
+ return $this;
}
/**
@@ -192,8 +192,9 @@ public function setWidth($pValue = 0) {
*
* @return int
*/
- public function getHeight() {
- return $this->_height;
+ public function getHeight()
+ {
+ return $this->height;
}
/**
@@ -202,54 +203,57 @@ public function getHeight() {
* @param int $pValue
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setHeight($pValue = 0) {
- // Resize proportional?
- if ($this->_resizeProportional && $pValue != 0) {
- $ratio = $this->_width / $this->_height;
- $this->_width = round($ratio * $pValue);
- }
+ public function setHeight($pValue = 0)
+ {
+ // Resize proportional?
+ if ($this->resizeProportional && $pValue != 0) {
+ $ratio = $this->width / $this->height;
+ $this->width = round($ratio * $pValue);
+ }
- // Set height
- $this->_height = $pValue;
+ // Set height
+ $this->height = $pValue;
- return $this;
+ return $this;
}
/**
* Set width and height with proportional resize
- * Example:
- *
+ * Example:
+ *
+ *
* @author Vincent@luo MSN:kele_100@hotmail.com
* @param int $width
* @param int $height
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setWidthAndHeight($width = 0, $height = 0) {
- $xratio = $width / $this->_width;
- $yratio = $height / $this->_height;
- if ($this->_resizeProportional && !($width == 0 || $height == 0)) {
- if (($xratio * $this->_height) < $height) {
- $this->_height = ceil($xratio * $this->_height);
- $this->_width = $width;
- } else {
- $this->_width = ceil($yratio * $this->_width);
- $this->_height = $height;
- }
- }
- return $this;
- }
+ public function setWidthAndHeight($width = 0, $height = 0)
+ {
+ $xratio = $width / $this->width;
+ $yratio = $height / $this->height;
+ if ($this->resizeProportional && !($width == 0 || $height == 0)) {
+ if (($xratio * $this->height) < $height) {
+ $this->height = ceil($xratio * $this->height);
+ $this->width = $width;
+ } else {
+ $this->width = ceil($yratio * $this->width);
+ $this->height = $height;
+ }
+ }
+ return $this;
+ }
/**
* Get ResizeProportional
*
* @return boolean
*/
- public function getResizeProportional() {
- return $this->_resizeProportional;
+ public function getResizeProportional()
+ {
+ return $this->resizeProportional;
}
/**
@@ -258,9 +262,10 @@ public function getResizeProportional() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setResizeProportional($pValue = true) {
- $this->_resizeProportional = $pValue;
- return $this;
+ public function setResizeProportional($pValue = true)
+ {
+ $this->resizeProportional = $pValue;
+ return $this;
}
/**
@@ -268,8 +273,9 @@ public function setResizeProportional($pValue = true) {
*
* @return string
*/
- public function getFilename() {
- return basename($this->_path);
+ public function getFilename()
+ {
+ return basename($this->path);
}
/**
@@ -277,8 +283,9 @@ public function getFilename() {
*
* @return string
*/
- public function getExtension() {
- $parts = explode(".", basename($this->_path));
+ public function getExtension()
+ {
+ $parts = explode(".", basename($this->path));
return end($parts);
}
@@ -287,64 +294,68 @@ public function getExtension() {
*
* @return string
*/
- public function getPath() {
- return $this->_path;
+ public function getPath()
+ {
+ return $this->path;
}
/**
* Set Path
*
- * @param string $pValue File path
- * @param boolean $pVerifyFile Verify file
- * @throws PHPExcel_Exception
+ * @param string $pValue File path
+ * @param boolean $pVerifyFile Verify file
+ * @throws PHPExcel_Exception
* @return PHPExcel_Worksheet_HeaderFooterDrawing
*/
- public function setPath($pValue = '', $pVerifyFile = true) {
- if ($pVerifyFile) {
- if (file_exists($pValue)) {
- $this->_path = $pValue;
-
- if ($this->_width == 0 && $this->_height == 0) {
- // Get width/height
- list($this->_width, $this->_height) = getimagesize($pValue);
- }
- } else {
- throw new PHPExcel_Exception("File $pValue not found!");
- }
- } else {
- $this->_path = $pValue;
- }
- return $this;
+ public function setPath($pValue = '', $pVerifyFile = true)
+ {
+ if ($pVerifyFile) {
+ if (file_exists($pValue)) {
+ $this->path = $pValue;
+
+ if ($this->width == 0 && $this->height == 0) {
+ // Get width/height
+ list($this->width, $this->height) = getimagesize($pValue);
+ }
+ } else {
+ throw new PHPExcel_Exception("File $pValue not found!");
+ }
+ } else {
+ $this->path = $pValue;
+ }
+ return $this;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_path
- . $this->_name
- . $this->_offsetX
- . $this->_offsetY
- . $this->_width
- . $this->_height
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ return md5(
+ $this->path .
+ $this->name .
+ $this->offsetX .
+ $this->offsetY .
+ $this->width .
+ $this->height .
+ __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/MemoryDrawing.php b/Classes/PHPExcel/Worksheet/MemoryDrawing.php
index c3a5b3bc7..438ed2c58 100644
--- a/Classes/PHPExcel/Worksheet/MemoryDrawing.php
+++ b/Classes/PHPExcel/Worksheet/MemoryDrawing.php
@@ -1,8 +1,9 @@
_imageResource = null;
- $this->_renderingFunction = self::RENDERING_DEFAULT;
- $this->_mimeType = self::MIMETYPE_DEFAULT;
- $this->_uniqueName = md5(rand(0, 9999). time() . rand(0, 9999));
-
- // Initialize parent
- parent::__construct();
+ // Initialise values
+ $this->imageResource = null;
+ $this->renderingFunction = self::RENDERING_DEFAULT;
+ $this->mimeType = self::MIMETYPE_DEFAULT;
+ $this->uniqueName = md5(rand(0, 9999). time() . rand(0, 9999));
+
+ // Initialize parent
+ parent::__construct();
}
/**
@@ -95,25 +87,27 @@ public function __construct()
*
* @return resource
*/
- public function getImageResource() {
- return $this->_imageResource;
+ public function getImageResource()
+ {
+ return $this->imageResource;
}
/**
* Set image resource
*
- * @param $value resource
+ * @param $value resource
* @return PHPExcel_Worksheet_MemoryDrawing
*/
- public function setImageResource($value = null) {
- $this->_imageResource = $value;
-
- if (!is_null($this->_imageResource)) {
- // Get width/height
- $this->_width = imagesx($this->_imageResource);
- $this->_height = imagesy($this->_imageResource);
- }
- return $this;
+ public function setImageResource($value = null)
+ {
+ $this->imageResource = $value;
+
+ if (!is_null($this->imageResource)) {
+ // Get width/height
+ $this->width = imagesx($this->imageResource);
+ $this->height = imagesy($this->imageResource);
+ }
+ return $this;
}
/**
@@ -121,8 +115,9 @@ public function setImageResource($value = null) {
*
* @return string
*/
- public function getRenderingFunction() {
- return $this->_renderingFunction;
+ public function getRenderingFunction()
+ {
+ return $this->renderingFunction;
}
/**
@@ -131,9 +126,10 @@ public function getRenderingFunction() {
* @param string $value
* @return PHPExcel_Worksheet_MemoryDrawing
*/
- public function setRenderingFunction($value = PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT) {
- $this->_renderingFunction = $value;
- return $this;
+ public function setRenderingFunction($value = PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT)
+ {
+ $this->renderingFunction = $value;
+ return $this;
}
/**
@@ -141,8 +137,9 @@ public function setRenderingFunction($value = PHPExcel_Worksheet_MemoryDrawing::
*
* @return string
*/
- public function getMimeType() {
- return $this->_mimeType;
+ public function getMimeType()
+ {
+ return $this->mimeType;
}
/**
@@ -151,9 +148,10 @@ public function getMimeType() {
* @param string $value
* @return PHPExcel_Worksheet_MemoryDrawing
*/
- public function setMimeType($value = PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT) {
- $this->_mimeType = $value;
- return $this;
+ public function setMimeType($value = PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT)
+ {
+ $this->mimeType = $value;
+ return $this;
}
/**
@@ -161,40 +159,43 @@ public function setMimeType($value = PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_
*
* @return string
*/
- public function getIndexedFilename() {
- $extension = strtolower($this->getMimeType());
- $extension = explode('/', $extension);
- $extension = $extension[1];
+ public function getIndexedFilename()
+ {
+ $extension = strtolower($this->getMimeType());
+ $extension = explode('/', $extension);
+ $extension = $extension[1];
- return $this->_uniqueName . $this->getImageIndex() . '.' . $extension;
+ return $this->uniqueName . $this->getImageIndex() . '.' . $extension;
}
- /**
- * Get hash code
- *
- * @return string Hash code
- */
- public function getHashCode() {
- return md5(
- $this->_renderingFunction
- . $this->_mimeType
- . $this->_uniqueName
- . parent::getHashCode()
- . __CLASS__
- );
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ return md5(
+ $this->renderingFunction .
+ $this->mimeType .
+ $this->uniqueName .
+ parent::getHashCode() .
+ __CLASS__
+ );
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/PageMargins.php b/Classes/PHPExcel/Worksheet/PageMargins.php
index 4221efd44..70f5ee0f5 100644
--- a/Classes/PHPExcel/Worksheet/PageMargins.php
+++ b/Classes/PHPExcel/Worksheet/PageMargins.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,8 +20,8 @@
*
* @category PHPExcel
* @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,51 +31,51 @@
*
* @category PHPExcel
* @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Worksheet_PageMargins
{
- /**
- * Left
- *
- * @var double
- */
- private $_left = 0.7;
-
- /**
- * Right
- *
- * @var double
- */
- private $_right = 0.7;
-
- /**
- * Top
- *
- * @var double
- */
- private $_top = 0.75;
-
- /**
- * Bottom
- *
- * @var double
- */
- private $_bottom = 0.75;
-
- /**
- * Header
- *
- * @var double
- */
- private $_header = 0.3;
-
- /**
- * Footer
- *
- * @var double
- */
- private $_footer = 0.3;
+ /**
+ * Left
+ *
+ * @var double
+ */
+ private $left = 0.7;
+
+ /**
+ * Right
+ *
+ * @var double
+ */
+ private $right = 0.7;
+
+ /**
+ * Top
+ *
+ * @var double
+ */
+ private $top = 0.75;
+
+ /**
+ * Bottom
+ *
+ * @var double
+ */
+ private $bottom = 0.75;
+
+ /**
+ * Header
+ *
+ * @var double
+ */
+ private $header = 0.3;
+
+ /**
+ * Footer
+ *
+ * @var double
+ */
+ private $footer = 0.3;
/**
* Create a new PHPExcel_Worksheet_PageMargins
@@ -89,8 +89,9 @@ public function __construct()
*
* @return double
*/
- public function getLeft() {
- return $this->_left;
+ public function getLeft()
+ {
+ return $this->left;
}
/**
@@ -99,9 +100,10 @@ public function getLeft() {
* @param double $pValue
* @return PHPExcel_Worksheet_PageMargins
*/
- public function setLeft($pValue) {
- $this->_left = $pValue;
- return $this;
+ public function setLeft($pValue)
+ {
+ $this->left = $pValue;
+ return $this;
}
/**
@@ -109,8 +111,9 @@ public function setLeft($pValue) {
*
* @return double
*/
- public function getRight() {
- return $this->_right;
+ public function getRight()
+ {
+ return $this->right;
}
/**
@@ -119,9 +122,10 @@ public function getRight() {
* @param double $pValue
* @return PHPExcel_Worksheet_PageMargins
*/
- public function setRight($pValue) {
- $this->_right = $pValue;
- return $this;
+ public function setRight($pValue)
+ {
+ $this->right = $pValue;
+ return $this;
}
/**
@@ -129,8 +133,9 @@ public function setRight($pValue) {
*
* @return double
*/
- public function getTop() {
- return $this->_top;
+ public function getTop()
+ {
+ return $this->top;
}
/**
@@ -139,9 +144,10 @@ public function getTop() {
* @param double $pValue
* @return PHPExcel_Worksheet_PageMargins
*/
- public function setTop($pValue) {
- $this->_top = $pValue;
- return $this;
+ public function setTop($pValue)
+ {
+ $this->top = $pValue;
+ return $this;
}
/**
@@ -149,8 +155,9 @@ public function setTop($pValue) {
*
* @return double
*/
- public function getBottom() {
- return $this->_bottom;
+ public function getBottom()
+ {
+ return $this->bottom;
}
/**
@@ -159,9 +166,10 @@ public function getBottom() {
* @param double $pValue
* @return PHPExcel_Worksheet_PageMargins
*/
- public function setBottom($pValue) {
- $this->_bottom = $pValue;
- return $this;
+ public function setBottom($pValue)
+ {
+ $this->bottom = $pValue;
+ return $this;
}
/**
@@ -169,8 +177,9 @@ public function setBottom($pValue) {
*
* @return double
*/
- public function getHeader() {
- return $this->_header;
+ public function getHeader()
+ {
+ return $this->header;
}
/**
@@ -179,9 +188,10 @@ public function getHeader() {
* @param double $pValue
* @return PHPExcel_Worksheet_PageMargins
*/
- public function setHeader($pValue) {
- $this->_header = $pValue;
- return $this;
+ public function setHeader($pValue)
+ {
+ $this->header = $pValue;
+ return $this;
}
/**
@@ -189,8 +199,9 @@ public function setHeader($pValue) {
*
* @return double
*/
- public function getFooter() {
- return $this->_footer;
+ public function getFooter()
+ {
+ return $this->footer;
}
/**
@@ -199,22 +210,24 @@ public function getFooter() {
* @param double $pValue
* @return PHPExcel_Worksheet_PageMargins
*/
- public function setFooter($pValue) {
- $this->_footer = $pValue;
- return $this;
+ public function setFooter($pValue)
+ {
+ $this->footer = $pValue;
+ return $this;
}
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/PageSetup.php b/Classes/PHPExcel/Worksheet/PageSetup.php
index c94a02776..c67053e6b 100644
--- a/Classes/PHPExcel/Worksheet/PageSetup.php
+++ b/Classes/PHPExcel/Worksheet/PageSetup.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,8 +20,8 @@
*
* @category PHPExcel
* @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -102,177 +102,177 @@
*
* @category PHPExcel
* @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Worksheet_PageSetup
{
- /* Paper size */
- const PAPERSIZE_LETTER = 1;
- const PAPERSIZE_LETTER_SMALL = 2;
- const PAPERSIZE_TABLOID = 3;
- const PAPERSIZE_LEDGER = 4;
- const PAPERSIZE_LEGAL = 5;
- const PAPERSIZE_STATEMENT = 6;
- const PAPERSIZE_EXECUTIVE = 7;
- const PAPERSIZE_A3 = 8;
- const PAPERSIZE_A4 = 9;
- const PAPERSIZE_A4_SMALL = 10;
- const PAPERSIZE_A5 = 11;
- const PAPERSIZE_B4 = 12;
- const PAPERSIZE_B5 = 13;
- const PAPERSIZE_FOLIO = 14;
- const PAPERSIZE_QUARTO = 15;
- const PAPERSIZE_STANDARD_1 = 16;
- const PAPERSIZE_STANDARD_2 = 17;
- const PAPERSIZE_NOTE = 18;
- const PAPERSIZE_NO9_ENVELOPE = 19;
- const PAPERSIZE_NO10_ENVELOPE = 20;
- const PAPERSIZE_NO11_ENVELOPE = 21;
- const PAPERSIZE_NO12_ENVELOPE = 22;
- const PAPERSIZE_NO14_ENVELOPE = 23;
- const PAPERSIZE_C = 24;
- const PAPERSIZE_D = 25;
- const PAPERSIZE_E = 26;
- const PAPERSIZE_DL_ENVELOPE = 27;
- const PAPERSIZE_C5_ENVELOPE = 28;
- const PAPERSIZE_C3_ENVELOPE = 29;
- const PAPERSIZE_C4_ENVELOPE = 30;
- const PAPERSIZE_C6_ENVELOPE = 31;
- const PAPERSIZE_C65_ENVELOPE = 32;
- const PAPERSIZE_B4_ENVELOPE = 33;
- const PAPERSIZE_B5_ENVELOPE = 34;
- const PAPERSIZE_B6_ENVELOPE = 35;
- const PAPERSIZE_ITALY_ENVELOPE = 36;
- const PAPERSIZE_MONARCH_ENVELOPE = 37;
- const PAPERSIZE_6_3_4_ENVELOPE = 38;
- const PAPERSIZE_US_STANDARD_FANFOLD = 39;
- const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40;
- const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41;
- const PAPERSIZE_ISO_B4 = 42;
- const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43;
- const PAPERSIZE_STANDARD_PAPER_1 = 44;
- const PAPERSIZE_STANDARD_PAPER_2 = 45;
- const PAPERSIZE_STANDARD_PAPER_3 = 46;
- const PAPERSIZE_INVITE_ENVELOPE = 47;
- const PAPERSIZE_LETTER_EXTRA_PAPER = 48;
- const PAPERSIZE_LEGAL_EXTRA_PAPER = 49;
- const PAPERSIZE_TABLOID_EXTRA_PAPER = 50;
- const PAPERSIZE_A4_EXTRA_PAPER = 51;
- const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52;
- const PAPERSIZE_A4_TRANSVERSE_PAPER = 53;
- const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54;
- const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55;
- const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56;
- const PAPERSIZE_LETTER_PLUS_PAPER = 57;
- const PAPERSIZE_A4_PLUS_PAPER = 58;
- const PAPERSIZE_A5_TRANSVERSE_PAPER = 59;
- const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60;
- const PAPERSIZE_A3_EXTRA_PAPER = 61;
- const PAPERSIZE_A5_EXTRA_PAPER = 62;
- const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63;
- const PAPERSIZE_A2_PAPER = 64;
- const PAPERSIZE_A3_TRANSVERSE_PAPER = 65;
- const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66;
-
- /* Page orientation */
- const ORIENTATION_DEFAULT = 'default';
- const ORIENTATION_LANDSCAPE = 'landscape';
- const ORIENTATION_PORTRAIT = 'portrait';
-
- /* Print Range Set Method */
- const SETPRINTRANGE_OVERWRITE = 'O';
- const SETPRINTRANGE_INSERT = 'I';
-
-
- /**
- * Paper size
- *
- * @var int
- */
- private $_paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER;
-
- /**
- * Orientation
- *
- * @var string
- */
- private $_orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT;
-
- /**
- * Scale (Print Scale)
- *
- * Print scaling. Valid values range from 10 to 400
- * This setting is overridden when fitToWidth and/or fitToHeight are in use
- *
- * @var int?
- */
- private $_scale = 100;
-
- /**
- * Fit To Page
- * Whether scale or fitToWith / fitToHeight applies
- *
- * @var boolean
- */
- private $_fitToPage = FALSE;
-
- /**
- * Fit To Height
- * Number of vertical pages to fit on
- *
- * @var int?
- */
- private $_fitToHeight = 1;
-
- /**
- * Fit To Width
- * Number of horizontal pages to fit on
- *
- * @var int?
- */
- private $_fitToWidth = 1;
-
- /**
- * Columns to repeat at left
- *
- * @var array Containing start column and end column, empty array if option unset
- */
- private $_columnsToRepeatAtLeft = array('', '');
-
- /**
- * Rows to repeat at top
- *
- * @var array Containing start row number and end row number, empty array if option unset
- */
- private $_rowsToRepeatAtTop = array(0, 0);
-
- /**
- * Center page horizontally
- *
- * @var boolean
- */
- private $_horizontalCentered = FALSE;
-
- /**
- * Center page vertically
- *
- * @var boolean
- */
- private $_verticalCentered = FALSE;
-
- /**
- * Print area
- *
- * @var string
- */
- private $_printArea = NULL;
-
- /**
- * First page number
- *
- * @var int
- */
- private $_firstPageNumber = NULL;
+ /* Paper size */
+ const PAPERSIZE_LETTER = 1;
+ const PAPERSIZE_LETTER_SMALL = 2;
+ const PAPERSIZE_TABLOID = 3;
+ const PAPERSIZE_LEDGER = 4;
+ const PAPERSIZE_LEGAL = 5;
+ const PAPERSIZE_STATEMENT = 6;
+ const PAPERSIZE_EXECUTIVE = 7;
+ const PAPERSIZE_A3 = 8;
+ const PAPERSIZE_A4 = 9;
+ const PAPERSIZE_A4_SMALL = 10;
+ const PAPERSIZE_A5 = 11;
+ const PAPERSIZE_B4 = 12;
+ const PAPERSIZE_B5 = 13;
+ const PAPERSIZE_FOLIO = 14;
+ const PAPERSIZE_QUARTO = 15;
+ const PAPERSIZE_STANDARD_1 = 16;
+ const PAPERSIZE_STANDARD_2 = 17;
+ const PAPERSIZE_NOTE = 18;
+ const PAPERSIZE_NO9_ENVELOPE = 19;
+ const PAPERSIZE_NO10_ENVELOPE = 20;
+ const PAPERSIZE_NO11_ENVELOPE = 21;
+ const PAPERSIZE_NO12_ENVELOPE = 22;
+ const PAPERSIZE_NO14_ENVELOPE = 23;
+ const PAPERSIZE_C = 24;
+ const PAPERSIZE_D = 25;
+ const PAPERSIZE_E = 26;
+ const PAPERSIZE_DL_ENVELOPE = 27;
+ const PAPERSIZE_C5_ENVELOPE = 28;
+ const PAPERSIZE_C3_ENVELOPE = 29;
+ const PAPERSIZE_C4_ENVELOPE = 30;
+ const PAPERSIZE_C6_ENVELOPE = 31;
+ const PAPERSIZE_C65_ENVELOPE = 32;
+ const PAPERSIZE_B4_ENVELOPE = 33;
+ const PAPERSIZE_B5_ENVELOPE = 34;
+ const PAPERSIZE_B6_ENVELOPE = 35;
+ const PAPERSIZE_ITALY_ENVELOPE = 36;
+ const PAPERSIZE_MONARCH_ENVELOPE = 37;
+ const PAPERSIZE_6_3_4_ENVELOPE = 38;
+ const PAPERSIZE_US_STANDARD_FANFOLD = 39;
+ const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40;
+ const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41;
+ const PAPERSIZE_ISO_B4 = 42;
+ const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43;
+ const PAPERSIZE_STANDARD_PAPER_1 = 44;
+ const PAPERSIZE_STANDARD_PAPER_2 = 45;
+ const PAPERSIZE_STANDARD_PAPER_3 = 46;
+ const PAPERSIZE_INVITE_ENVELOPE = 47;
+ const PAPERSIZE_LETTER_EXTRA_PAPER = 48;
+ const PAPERSIZE_LEGAL_EXTRA_PAPER = 49;
+ const PAPERSIZE_TABLOID_EXTRA_PAPER = 50;
+ const PAPERSIZE_A4_EXTRA_PAPER = 51;
+ const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52;
+ const PAPERSIZE_A4_TRANSVERSE_PAPER = 53;
+ const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54;
+ const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55;
+ const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56;
+ const PAPERSIZE_LETTER_PLUS_PAPER = 57;
+ const PAPERSIZE_A4_PLUS_PAPER = 58;
+ const PAPERSIZE_A5_TRANSVERSE_PAPER = 59;
+ const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60;
+ const PAPERSIZE_A3_EXTRA_PAPER = 61;
+ const PAPERSIZE_A5_EXTRA_PAPER = 62;
+ const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63;
+ const PAPERSIZE_A2_PAPER = 64;
+ const PAPERSIZE_A3_TRANSVERSE_PAPER = 65;
+ const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66;
+
+ /* Page orientation */
+ const ORIENTATION_DEFAULT = 'default';
+ const ORIENTATION_LANDSCAPE = 'landscape';
+ const ORIENTATION_PORTRAIT = 'portrait';
+
+ /* Print Range Set Method */
+ const SETPRINTRANGE_OVERWRITE = 'O';
+ const SETPRINTRANGE_INSERT = 'I';
+
+
+ /**
+ * Paper size
+ *
+ * @var int
+ */
+ private $paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER;
+
+ /**
+ * Orientation
+ *
+ * @var string
+ */
+ private $orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT;
+
+ /**
+ * Scale (Print Scale)
+ *
+ * Print scaling. Valid values range from 10 to 400
+ * This setting is overridden when fitToWidth and/or fitToHeight are in use
+ *
+ * @var int?
+ */
+ private $scale = 100;
+
+ /**
+ * Fit To Page
+ * Whether scale or fitToWith / fitToHeight applies
+ *
+ * @var boolean
+ */
+ private $fitToPage = false;
+
+ /**
+ * Fit To Height
+ * Number of vertical pages to fit on
+ *
+ * @var int?
+ */
+ private $fitToHeight = 1;
+
+ /**
+ * Fit To Width
+ * Number of horizontal pages to fit on
+ *
+ * @var int?
+ */
+ private $fitToWidth = 1;
+
+ /**
+ * Columns to repeat at left
+ *
+ * @var array Containing start column and end column, empty array if option unset
+ */
+ private $columnsToRepeatAtLeft = array('', '');
+
+ /**
+ * Rows to repeat at top
+ *
+ * @var array Containing start row number and end row number, empty array if option unset
+ */
+ private $rowsToRepeatAtTop = array(0, 0);
+
+ /**
+ * Center page horizontally
+ *
+ * @var boolean
+ */
+ private $horizontalCentered = false;
+
+ /**
+ * Center page vertically
+ *
+ * @var boolean
+ */
+ private $verticalCentered = false;
+
+ /**
+ * Print area
+ *
+ * @var string
+ */
+ private $printArea = null;
+
+ /**
+ * First page number
+ *
+ * @var int
+ */
+ private $firstPageNumber = null;
/**
* Create a new PHPExcel_Worksheet_PageSetup
@@ -286,8 +286,9 @@ public function __construct()
*
* @return int
*/
- public function getPaperSize() {
- return $this->_paperSize;
+ public function getPaperSize()
+ {
+ return $this->paperSize;
}
/**
@@ -296,9 +297,10 @@ public function getPaperSize() {
* @param int $pValue
* @return PHPExcel_Worksheet_PageSetup
*/
- public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) {
- $this->_paperSize = $pValue;
- return $this;
+ public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER)
+ {
+ $this->paperSize = $pValue;
+ return $this;
}
/**
@@ -306,8 +308,9 @@ public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_L
*
* @return string
*/
- public function getOrientation() {
- return $this->_orientation;
+ public function getOrientation()
+ {
+ return $this->orientation;
}
/**
@@ -316,450 +319,485 @@ public function getOrientation() {
* @param string $pValue
* @return PHPExcel_Worksheet_PageSetup
*/
- public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) {
- $this->_orientation = $pValue;
- return $this;
- }
-
- /**
- * Get Scale
- *
- * @return int?
- */
- public function getScale() {
- return $this->_scale;
- }
-
- /**
- * Set Scale
- *
- * Print scaling. Valid values range from 10 to 400
- * This setting is overridden when fitToWidth and/or fitToHeight are in use
- *
- * @param int? $pValue
- * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
- * @return PHPExcel_Worksheet_PageSetup
- * @throws PHPExcel_Exception
- */
- public function setScale($pValue = 100, $pUpdate = true) {
- // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
- // but it is apparently still able to handle any scale >= 0, where 0 results in 100
- if (($pValue >= 0) || is_null($pValue)) {
- $this->_scale = $pValue;
- if ($pUpdate) {
- $this->_fitToPage = false;
- }
- } else {
- throw new PHPExcel_Exception("Scale must not be negative");
- }
- return $this;
- }
-
- /**
- * Get Fit To Page
- *
- * @return boolean
- */
- public function getFitToPage() {
- return $this->_fitToPage;
- }
-
- /**
- * Set Fit To Page
- *
- * @param boolean $pValue
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setFitToPage($pValue = TRUE) {
- $this->_fitToPage = $pValue;
- return $this;
- }
-
- /**
- * Get Fit To Height
- *
- * @return int?
- */
- public function getFitToHeight() {
- return $this->_fitToHeight;
- }
-
- /**
- * Set Fit To Height
- *
- * @param int? $pValue
- * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setFitToHeight($pValue = 1, $pUpdate = TRUE) {
- $this->_fitToHeight = $pValue;
- if ($pUpdate) {
- $this->_fitToPage = TRUE;
- }
- return $this;
- }
-
- /**
- * Get Fit To Width
- *
- * @return int?
- */
- public function getFitToWidth() {
- return $this->_fitToWidth;
- }
-
- /**
- * Set Fit To Width
- *
- * @param int? $pValue
- * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setFitToWidth($pValue = 1, $pUpdate = TRUE) {
- $this->_fitToWidth = $pValue;
- if ($pUpdate) {
- $this->_fitToPage = TRUE;
- }
- return $this;
- }
-
- /**
- * Is Columns to repeat at left set?
- *
- * @return boolean
- */
- public function isColumnsToRepeatAtLeftSet() {
- if (is_array($this->_columnsToRepeatAtLeft)) {
- if ($this->_columnsToRepeatAtLeft[0] != '' && $this->_columnsToRepeatAtLeft[1] != '') {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Get Columns to repeat at left
- *
- * @return array Containing start column and end column, empty array if option unset
- */
- public function getColumnsToRepeatAtLeft() {
- return $this->_columnsToRepeatAtLeft;
- }
-
- /**
- * Set Columns to repeat at left
- *
- * @param array $pValue Containing start column and end column, empty array if option unset
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setColumnsToRepeatAtLeft($pValue = null) {
- if (is_array($pValue)) {
- $this->_columnsToRepeatAtLeft = $pValue;
- }
- return $this;
- }
-
- /**
- * Set Columns to repeat at left by start and end
- *
- * @param string $pStart
- * @param string $pEnd
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') {
- $this->_columnsToRepeatAtLeft = array($pStart, $pEnd);
- return $this;
- }
-
- /**
- * Is Rows to repeat at top set?
- *
- * @return boolean
- */
- public function isRowsToRepeatAtTopSet() {
- if (is_array($this->_rowsToRepeatAtTop)) {
- if ($this->_rowsToRepeatAtTop[0] != 0 && $this->_rowsToRepeatAtTop[1] != 0) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Get Rows to repeat at top
- *
- * @return array Containing start column and end column, empty array if option unset
- */
- public function getRowsToRepeatAtTop() {
- return $this->_rowsToRepeatAtTop;
- }
-
- /**
- * Set Rows to repeat at top
- *
- * @param array $pValue Containing start column and end column, empty array if option unset
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setRowsToRepeatAtTop($pValue = null) {
- if (is_array($pValue)) {
- $this->_rowsToRepeatAtTop = $pValue;
- }
- return $this;
- }
-
- /**
- * Set Rows to repeat at top by start and end
- *
- * @param int $pStart
- * @param int $pEnd
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) {
- $this->_rowsToRepeatAtTop = array($pStart, $pEnd);
- return $this;
- }
-
- /**
- * Get center page horizontally
- *
- * @return bool
- */
- public function getHorizontalCentered() {
- return $this->_horizontalCentered;
- }
-
- /**
- * Set center page horizontally
- *
- * @param bool $value
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setHorizontalCentered($value = false) {
- $this->_horizontalCentered = $value;
- return $this;
- }
-
- /**
- * Get center page vertically
- *
- * @return bool
- */
- public function getVerticalCentered() {
- return $this->_verticalCentered;
- }
-
- /**
- * Set center page vertically
- *
- * @param bool $value
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function setVerticalCentered($value = false) {
- $this->_verticalCentered = $value;
- return $this;
- }
-
- /**
- * Get print area
- *
- * @param int $index Identifier for a specific print area range if several ranges have been set
- * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string
- * Otherwise, the specific range identified by the value of $index will be returned
- * Print areas are numbered from 1
- * @throws PHPExcel_Exception
- * @return string
- */
- public function getPrintArea($index = 0) {
- if ($index == 0) {
- return $this->_printArea;
- }
- $printAreas = explode(',',$this->_printArea);
- if (isset($printAreas[$index-1])) {
- return $printAreas[$index-1];
- }
- throw new PHPExcel_Exception("Requested Print Area does not exist");
- }
-
- /**
- * Is print area set?
- *
- * @param int $index Identifier for a specific print area range if several ranges have been set
- * Default behaviour, or an index value of 0, will identify whether any print range is set
- * Otherwise, existence of the range identified by the value of $index will be returned
- * Print areas are numbered from 1
- * @return boolean
- */
- public function isPrintAreaSet($index = 0) {
- if ($index == 0) {
- return !is_null($this->_printArea);
- }
- $printAreas = explode(',',$this->_printArea);
- return isset($printAreas[$index-1]);
- }
-
- /**
- * Clear a print area
- *
- * @param int $index Identifier for a specific print area range if several ranges have been set
- * Default behaviour, or an index value of 0, will clear all print ranges that are set
- * Otherwise, the range identified by the value of $index will be removed from the series
- * Print areas are numbered from 1
- * @return PHPExcel_Worksheet_PageSetup
- */
- public function clearPrintArea($index = 0) {
- if ($index == 0) {
- $this->_printArea = NULL;
- } else {
- $printAreas = explode(',',$this->_printArea);
- if (isset($printAreas[$index-1])) {
- unset($printAreas[$index-1]);
- $this->_printArea = implode(',',$printAreas);
- }
- }
-
- return $this;
- }
-
- /**
- * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'
- *
- * @param string $value
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
- * entry in the print areas list; a negative index value will identify which entry to
- * overwrite working bacward through the print area to the list, with the last entry as -1.
- * Specifying an index value of 0, will overwrite all existing print ranges.
- * When the method is "I"nsert, then a positive index will insert after that indexed entry in
- * the print areas list, while a negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @param string $method Determines the method used when setting multiple print areas
- * Default behaviour, or the "O" method, overwrites existing print area
- * The "I" method, inserts the new print area before any specified index, or at the end of the list
- * @return PHPExcel_Worksheet_PageSetup
- * @throws PHPExcel_Exception
- */
- public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) {
- if (strpos($value,'!') !== false) {
- throw new PHPExcel_Exception('Cell coordinate must not specify a worksheet.');
- } elseif (strpos($value,':') === false) {
- throw new PHPExcel_Exception('Cell coordinate must be a range of cells.');
- } elseif (strpos($value,'$') !== false) {
- throw new PHPExcel_Exception('Cell coordinate must not be absolute.');
- }
- $value = strtoupper($value);
-
- if ($method == self::SETPRINTRANGE_OVERWRITE) {
- if ($index == 0) {
- $this->_printArea = $value;
- } else {
- $printAreas = explode(',',$this->_printArea);
- if($index < 0) {
- $index = count($printAreas) - abs($index) + 1;
- }
- if (($index <= 0) || ($index > count($printAreas))) {
- throw new PHPExcel_Exception('Invalid index for setting print range.');
- }
- $printAreas[$index-1] = $value;
- $this->_printArea = implode(',',$printAreas);
- }
- } elseif($method == self::SETPRINTRANGE_INSERT) {
- if ($index == 0) {
- $this->_printArea .= ($this->_printArea == '') ? $value : ','.$value;
- } else {
- $printAreas = explode(',',$this->_printArea);
- if($index < 0) {
- $index = abs($index) - 1;
- }
- if ($index > count($printAreas)) {
- throw new PHPExcel_Exception('Invalid index for setting print range.');
- }
- $printAreas = array_merge(array_slice($printAreas,0,$index),array($value),array_slice($printAreas,$index));
- $this->_printArea = implode(',',$printAreas);
- }
- } else {
- throw new PHPExcel_Exception('Invalid method for setting print range.');
- }
-
- return $this;
- }
-
- /**
- * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas
- *
- * @param string $value
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * A positive index will insert after that indexed entry in the print areas list, while a
- * negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @return PHPExcel_Worksheet_PageSetup
- * @throws PHPExcel_Exception
- */
- public function addPrintArea($value, $index = -1) {
- return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT);
- }
-
- /**
- * Set print area
- *
- * @param int $column1 Column 1
- * @param int $row1 Row 1
- * @param int $column2 Column 2
- * @param int $row2 Row 2
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
- * entry in the print areas list; a negative index value will identify which entry to
- * overwrite working bacward through the print area to the list, with the last entry as -1.
- * Specifying an index value of 0, will overwrite all existing print ranges.
- * When the method is "I"nsert, then a positive index will insert after that indexed entry in
- * the print areas list, while a negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @param string $method Determines the method used when setting multiple print areas
- * Default behaviour, or the "O" method, overwrites existing print area
- * The "I" method, inserts the new print area before any specified index, or at the end of the list
- * @return PHPExcel_Worksheet_PageSetup
- * @throws PHPExcel_Exception
- */
+ public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT)
+ {
+ $this->orientation = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Scale
+ *
+ * @return int?
+ */
+ public function getScale()
+ {
+ return $this->scale;
+ }
+
+ /**
+ * Set Scale
+ *
+ * Print scaling. Valid values range from 10 to 400
+ * This setting is overridden when fitToWidth and/or fitToHeight are in use
+ *
+ * @param int? $pValue
+ * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
+ * @return PHPExcel_Worksheet_PageSetup
+ * @throws PHPExcel_Exception
+ */
+ public function setScale($pValue = 100, $pUpdate = true)
+ {
+ // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
+ // but it is apparently still able to handle any scale >= 0, where 0 results in 100
+ if (($pValue >= 0) || is_null($pValue)) {
+ $this->scale = $pValue;
+ if ($pUpdate) {
+ $this->fitToPage = false;
+ }
+ } else {
+ throw new PHPExcel_Exception("Scale must not be negative");
+ }
+ return $this;
+ }
+
+ /**
+ * Get Fit To Page
+ *
+ * @return boolean
+ */
+ public function getFitToPage()
+ {
+ return $this->fitToPage;
+ }
+
+ /**
+ * Set Fit To Page
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setFitToPage($pValue = true)
+ {
+ $this->fitToPage = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Fit To Height
+ *
+ * @return int?
+ */
+ public function getFitToHeight()
+ {
+ return $this->fitToHeight;
+ }
+
+ /**
+ * Set Fit To Height
+ *
+ * @param int? $pValue
+ * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setFitToHeight($pValue = 1, $pUpdate = true)
+ {
+ $this->fitToHeight = $pValue;
+ if ($pUpdate) {
+ $this->fitToPage = true;
+ }
+ return $this;
+ }
+
+ /**
+ * Get Fit To Width
+ *
+ * @return int?
+ */
+ public function getFitToWidth()
+ {
+ return $this->fitToWidth;
+ }
+
+ /**
+ * Set Fit To Width
+ *
+ * @param int? $pValue
+ * @param boolean $pUpdate Update fitToPage so it applies rather than scaling
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setFitToWidth($pValue = 1, $pUpdate = true)
+ {
+ $this->fitToWidth = $pValue;
+ if ($pUpdate) {
+ $this->fitToPage = true;
+ }
+ return $this;
+ }
+
+ /**
+ * Is Columns to repeat at left set?
+ *
+ * @return boolean
+ */
+ public function isColumnsToRepeatAtLeftSet()
+ {
+ if (is_array($this->columnsToRepeatAtLeft)) {
+ if ($this->columnsToRepeatAtLeft[0] != '' && $this->columnsToRepeatAtLeft[1] != '') {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Get Columns to repeat at left
+ *
+ * @return array Containing start column and end column, empty array if option unset
+ */
+ public function getColumnsToRepeatAtLeft()
+ {
+ return $this->columnsToRepeatAtLeft;
+ }
+
+ /**
+ * Set Columns to repeat at left
+ *
+ * @param array $pValue Containing start column and end column, empty array if option unset
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setColumnsToRepeatAtLeft($pValue = null)
+ {
+ if (is_array($pValue)) {
+ $this->columnsToRepeatAtLeft = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Set Columns to repeat at left by start and end
+ *
+ * @param string $pStart
+ * @param string $pEnd
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A')
+ {
+ $this->columnsToRepeatAtLeft = array($pStart, $pEnd);
+ return $this;
+ }
+
+ /**
+ * Is Rows to repeat at top set?
+ *
+ * @return boolean
+ */
+ public function isRowsToRepeatAtTopSet()
+ {
+ if (is_array($this->rowsToRepeatAtTop)) {
+ if ($this->rowsToRepeatAtTop[0] != 0 && $this->rowsToRepeatAtTop[1] != 0) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Get Rows to repeat at top
+ *
+ * @return array Containing start column and end column, empty array if option unset
+ */
+ public function getRowsToRepeatAtTop()
+ {
+ return $this->rowsToRepeatAtTop;
+ }
+
+ /**
+ * Set Rows to repeat at top
+ *
+ * @param array $pValue Containing start column and end column, empty array if option unset
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setRowsToRepeatAtTop($pValue = null)
+ {
+ if (is_array($pValue)) {
+ $this->rowsToRepeatAtTop = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Set Rows to repeat at top by start and end
+ *
+ * @param int $pStart
+ * @param int $pEnd
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1)
+ {
+ $this->rowsToRepeatAtTop = array($pStart, $pEnd);
+ return $this;
+ }
+
+ /**
+ * Get center page horizontally
+ *
+ * @return bool
+ */
+ public function getHorizontalCentered()
+ {
+ return $this->horizontalCentered;
+ }
+
+ /**
+ * Set center page horizontally
+ *
+ * @param bool $value
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setHorizontalCentered($value = false)
+ {
+ $this->horizontalCentered = $value;
+ return $this;
+ }
+
+ /**
+ * Get center page vertically
+ *
+ * @return bool
+ */
+ public function getVerticalCentered()
+ {
+ return $this->verticalCentered;
+ }
+
+ /**
+ * Set center page vertically
+ *
+ * @param bool $value
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setVerticalCentered($value = false)
+ {
+ $this->verticalCentered = $value;
+ return $this;
+ }
+
+ /**
+ * Get print area
+ *
+ * @param int $index Identifier for a specific print area range if several ranges have been set
+ * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string
+ * Otherwise, the specific range identified by the value of $index will be returned
+ * Print areas are numbered from 1
+ * @throws PHPExcel_Exception
+ * @return string
+ */
+ public function getPrintArea($index = 0)
+ {
+ if ($index == 0) {
+ return $this->printArea;
+ }
+ $printAreas = explode(',', $this->printArea);
+ if (isset($printAreas[$index-1])) {
+ return $printAreas[$index-1];
+ }
+ throw new PHPExcel_Exception("Requested Print Area does not exist");
+ }
+
+ /**
+ * Is print area set?
+ *
+ * @param int $index Identifier for a specific print area range if several ranges have been set
+ * Default behaviour, or an index value of 0, will identify whether any print range is set
+ * Otherwise, existence of the range identified by the value of $index will be returned
+ * Print areas are numbered from 1
+ * @return boolean
+ */
+ public function isPrintAreaSet($index = 0)
+ {
+ if ($index == 0) {
+ return !is_null($this->printArea);
+ }
+ $printAreas = explode(',', $this->printArea);
+ return isset($printAreas[$index-1]);
+ }
+
+ /**
+ * Clear a print area
+ *
+ * @param int $index Identifier for a specific print area range if several ranges have been set
+ * Default behaviour, or an index value of 0, will clear all print ranges that are set
+ * Otherwise, the range identified by the value of $index will be removed from the series
+ * Print areas are numbered from 1
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function clearPrintArea($index = 0)
+ {
+ if ($index == 0) {
+ $this->printArea = null;
+ } else {
+ $printAreas = explode(',', $this->printArea);
+ if (isset($printAreas[$index-1])) {
+ unset($printAreas[$index-1]);
+ $this->printArea = implode(',', $printAreas);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'
+ *
+ * @param string $value
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
+ * entry in the print areas list; a negative index value will identify which entry to
+ * overwrite working bacward through the print area to the list, with the last entry as -1.
+ * Specifying an index value of 0, will overwrite all existing print ranges.
+ * When the method is "I"nsert, then a positive index will insert after that indexed entry in
+ * the print areas list, while a negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @param string $method Determines the method used when setting multiple print areas
+ * Default behaviour, or the "O" method, overwrites existing print area
+ * The "I" method, inserts the new print area before any specified index, or at the end of the list
+ * @return PHPExcel_Worksheet_PageSetup
+ * @throws PHPExcel_Exception
+ */
+ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE)
+ {
+ if (strpos($value, '!') !== false) {
+ throw new PHPExcel_Exception('Cell coordinate must not specify a worksheet.');
+ } elseif (strpos($value, ':') === false) {
+ throw new PHPExcel_Exception('Cell coordinate must be a range of cells.');
+ } elseif (strpos($value, '$') !== false) {
+ throw new PHPExcel_Exception('Cell coordinate must not be absolute.');
+ }
+ $value = strtoupper($value);
+
+ if ($method == self::SETPRINTRANGE_OVERWRITE) {
+ if ($index == 0) {
+ $this->printArea = $value;
+ } else {
+ $printAreas = explode(',', $this->printArea);
+ if ($index < 0) {
+ $index = count($printAreas) - abs($index) + 1;
+ }
+ if (($index <= 0) || ($index > count($printAreas))) {
+ throw new PHPExcel_Exception('Invalid index for setting print range.');
+ }
+ $printAreas[$index-1] = $value;
+ $this->printArea = implode(',', $printAreas);
+ }
+ } elseif ($method == self::SETPRINTRANGE_INSERT) {
+ if ($index == 0) {
+ $this->printArea .= ($this->printArea == '') ? $value : ','.$value;
+ } else {
+ $printAreas = explode(',', $this->printArea);
+ if ($index < 0) {
+ $index = abs($index) - 1;
+ }
+ if ($index > count($printAreas)) {
+ throw new PHPExcel_Exception('Invalid index for setting print range.');
+ }
+ $printAreas = array_merge(array_slice($printAreas, 0, $index), array($value), array_slice($printAreas, $index));
+ $this->printArea = implode(',', $printAreas);
+ }
+ } else {
+ throw new PHPExcel_Exception('Invalid method for setting print range.');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas
+ *
+ * @param string $value
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * A positive index will insert after that indexed entry in the print areas list, while a
+ * negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @return PHPExcel_Worksheet_PageSetup
+ * @throws PHPExcel_Exception
+ */
+ public function addPrintArea($value, $index = -1)
+ {
+ return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT);
+ }
+
+ /**
+ * Set print area
+ *
+ * @param int $column1 Column 1
+ * @param int $row1 Row 1
+ * @param int $column2 Column 2
+ * @param int $row2 Row 2
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * When the method is "O"verwrite, then a positive integer index will overwrite that indexed
+ * entry in the print areas list; a negative index value will identify which entry to
+ * overwrite working bacward through the print area to the list, with the last entry as -1.
+ * Specifying an index value of 0, will overwrite all existing print ranges.
+ * When the method is "I"nsert, then a positive index will insert after that indexed entry in
+ * the print areas list, while a negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @param string $method Determines the method used when setting multiple print areas
+ * Default behaviour, or the "O" method, overwrites existing print area
+ * The "I" method, inserts the new print area before any specified index, or at the end of the list
+ * @return PHPExcel_Worksheet_PageSetup
+ * @throws PHPExcel_Exception
+ */
public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE)
{
- return $this->setPrintArea(PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, $index, $method);
- }
-
- /**
- * Add a new print area to the list of print areas
- *
- * @param int $column1 Start Column for the print area
- * @param int $row1 Start Row for the print area
- * @param int $column2 End Column for the print area
- * @param int $row2 End Row for the print area
- * @param int $index Identifier for a specific print area range allowing several ranges to be set
- * A positive index will insert after that indexed entry in the print areas list, while a
- * negative index will insert before the indexed entry.
- * Specifying an index value of 0, will always append the new print range at the end of the
- * list.
- * Print areas are numbered from 1
- * @return PHPExcel_Worksheet_PageSetup
- * @throws PHPExcel_Exception
- */
+ return $this->setPrintArea(
+ PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2,
+ $index,
+ $method
+ );
+ }
+
+ /**
+ * Add a new print area to the list of print areas
+ *
+ * @param int $column1 Start Column for the print area
+ * @param int $row1 Start Row for the print area
+ * @param int $column2 End Column for the print area
+ * @param int $row2 End Row for the print area
+ * @param int $index Identifier for a specific print area range allowing several ranges to be set
+ * A positive index will insert after that indexed entry in the print areas list, while a
+ * negative index will insert before the indexed entry.
+ * Specifying an index value of 0, will always append the new print range at the end of the
+ * list.
+ * Print areas are numbered from 1
+ * @return PHPExcel_Worksheet_PageSetup
+ * @throws PHPExcel_Exception
+ */
public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1)
{
- return $this->setPrintArea(PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT);
- }
+ return $this->setPrintArea(
+ PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2,
+ $index,
+ self::SETPRINTRANGE_INSERT
+ );
+ }
- /**
- * Get first page number
- *
- * @return int
- */
- public function getFirstPageNumber() {
- return $this->_firstPageNumber;
+ /**
+ * Get first page number
+ *
+ * @return int
+ */
+ public function getFirstPageNumber()
+ {
+ return $this->firstPageNumber;
}
/**
@@ -768,9 +806,10 @@ public function getFirstPageNumber() {
* @param int $value
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function setFirstPageNumber($value = null) {
- $this->_firstPageNumber = $value;
- return $this;
+ public function setFirstPageNumber($value = null)
+ {
+ $this->firstPageNumber = $value;
+ return $this;
}
/**
@@ -778,21 +817,23 @@ public function setFirstPageNumber($value = null) {
*
* @return PHPExcel_Worksheet_HeaderFooter
*/
- public function resetFirstPageNumber() {
- return $this->setFirstPageNumber(null);
- }
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ public function resetFirstPageNumber()
+ {
+ return $this->setFirstPageNumber(null);
+ }
+
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Protection.php b/Classes/PHPExcel/Worksheet/Protection.php
index f4222fc71..00633eeb7 100644
--- a/Classes/PHPExcel/Worksheet/Protection.php
+++ b/Classes/PHPExcel/Worksheet/Protection.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,8 +20,8 @@
*
* @category PHPExcel
* @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,128 +31,128 @@
*
* @category PHPExcel
* @package PHPExcel_Worksheet
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Worksheet_Protection
{
- /**
- * Sheet
- *
- * @var boolean
- */
- private $_sheet = false;
-
- /**
- * Objects
- *
- * @var boolean
- */
- private $_objects = false;
-
- /**
- * Scenarios
- *
- * @var boolean
- */
- private $_scenarios = false;
-
- /**
- * Format cells
- *
- * @var boolean
- */
- private $_formatCells = false;
-
- /**
- * Format columns
- *
- * @var boolean
- */
- private $_formatColumns = false;
-
- /**
- * Format rows
- *
- * @var boolean
- */
- private $_formatRows = false;
-
- /**
- * Insert columns
- *
- * @var boolean
- */
- private $_insertColumns = false;
-
- /**
- * Insert rows
- *
- * @var boolean
- */
- private $_insertRows = false;
-
- /**
- * Insert hyperlinks
- *
- * @var boolean
- */
- private $_insertHyperlinks = false;
-
- /**
- * Delete columns
- *
- * @var boolean
- */
- private $_deleteColumns = false;
-
- /**
- * Delete rows
- *
- * @var boolean
- */
- private $_deleteRows = false;
-
- /**
- * Select locked cells
- *
- * @var boolean
- */
- private $_selectLockedCells = false;
-
- /**
- * Sort
- *
- * @var boolean
- */
- private $_sort = false;
-
- /**
- * AutoFilter
- *
- * @var boolean
- */
- private $_autoFilter = false;
-
- /**
- * Pivot tables
- *
- * @var boolean
- */
- private $_pivotTables = false;
-
- /**
- * Select unlocked cells
- *
- * @var boolean
- */
- private $_selectUnlockedCells = false;
-
- /**
- * Password
- *
- * @var string
- */
- private $_password = '';
+ /**
+ * Sheet
+ *
+ * @var boolean
+ */
+ private $sheet = false;
+
+ /**
+ * Objects
+ *
+ * @var boolean
+ */
+ private $objects = false;
+
+ /**
+ * Scenarios
+ *
+ * @var boolean
+ */
+ private $scenarios = false;
+
+ /**
+ * Format cells
+ *
+ * @var boolean
+ */
+ private $formatCells = false;
+
+ /**
+ * Format columns
+ *
+ * @var boolean
+ */
+ private $formatColumns = false;
+
+ /**
+ * Format rows
+ *
+ * @var boolean
+ */
+ private $formatRows = false;
+
+ /**
+ * Insert columns
+ *
+ * @var boolean
+ */
+ private $insertColumns = false;
+
+ /**
+ * Insert rows
+ *
+ * @var boolean
+ */
+ private $insertRows = false;
+
+ /**
+ * Insert hyperlinks
+ *
+ * @var boolean
+ */
+ private $insertHyperlinks = false;
+
+ /**
+ * Delete columns
+ *
+ * @var boolean
+ */
+ private $deleteColumns = false;
+
+ /**
+ * Delete rows
+ *
+ * @var boolean
+ */
+ private $deleteRows = false;
+
+ /**
+ * Select locked cells
+ *
+ * @var boolean
+ */
+ private $selectLockedCells = false;
+
+ /**
+ * Sort
+ *
+ * @var boolean
+ */
+ private $sort = false;
+
+ /**
+ * AutoFilter
+ *
+ * @var boolean
+ */
+ private $autoFilter = false;
+
+ /**
+ * Pivot tables
+ *
+ * @var boolean
+ */
+ private $pivotTables = false;
+
+ /**
+ * Select unlocked cells
+ *
+ * @var boolean
+ */
+ private $selectUnlockedCells = false;
+
+ /**
+ * Password
+ *
+ * @var string
+ */
+ private $password = '';
/**
* Create a new PHPExcel_Worksheet_Protection
@@ -166,23 +166,24 @@ public function __construct()
*
* @return boolean
*/
- function isProtectionEnabled() {
- return $this->_sheet ||
- $this->_objects ||
- $this->_scenarios ||
- $this->_formatCells ||
- $this->_formatColumns ||
- $this->_formatRows ||
- $this->_insertColumns ||
- $this->_insertRows ||
- $this->_insertHyperlinks ||
- $this->_deleteColumns ||
- $this->_deleteRows ||
- $this->_selectLockedCells ||
- $this->_sort ||
- $this->_autoFilter ||
- $this->_pivotTables ||
- $this->_selectUnlockedCells;
+ public function isProtectionEnabled()
+ {
+ return $this->sheet ||
+ $this->objects ||
+ $this->scenarios ||
+ $this->formatCells ||
+ $this->formatColumns ||
+ $this->formatRows ||
+ $this->insertColumns ||
+ $this->insertRows ||
+ $this->insertHyperlinks ||
+ $this->deleteColumns ||
+ $this->deleteRows ||
+ $this->selectLockedCells ||
+ $this->sort ||
+ $this->autoFilter ||
+ $this->pivotTables ||
+ $this->selectUnlockedCells;
}
/**
@@ -190,8 +191,9 @@ function isProtectionEnabled() {
*
* @return boolean
*/
- function getSheet() {
- return $this->_sheet;
+ public function getSheet()
+ {
+ return $this->sheet;
}
/**
@@ -200,9 +202,10 @@ function getSheet() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setSheet($pValue = false) {
- $this->_sheet = $pValue;
- return $this;
+ public function setSheet($pValue = false)
+ {
+ $this->sheet = $pValue;
+ return $this;
}
/**
@@ -210,8 +213,9 @@ function setSheet($pValue = false) {
*
* @return boolean
*/
- function getObjects() {
- return $this->_objects;
+ public function getObjects()
+ {
+ return $this->objects;
}
/**
@@ -220,9 +224,10 @@ function getObjects() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setObjects($pValue = false) {
- $this->_objects = $pValue;
- return $this;
+ public function setObjects($pValue = false)
+ {
+ $this->objects = $pValue;
+ return $this;
}
/**
@@ -230,8 +235,9 @@ function setObjects($pValue = false) {
*
* @return boolean
*/
- function getScenarios() {
- return $this->_scenarios;
+ public function getScenarios()
+ {
+ return $this->scenarios;
}
/**
@@ -240,9 +246,10 @@ function getScenarios() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setScenarios($pValue = false) {
- $this->_scenarios = $pValue;
- return $this;
+ public function setScenarios($pValue = false)
+ {
+ $this->scenarios = $pValue;
+ return $this;
}
/**
@@ -250,8 +257,9 @@ function setScenarios($pValue = false) {
*
* @return boolean
*/
- function getFormatCells() {
- return $this->_formatCells;
+ public function getFormatCells()
+ {
+ return $this->formatCells;
}
/**
@@ -260,9 +268,10 @@ function getFormatCells() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setFormatCells($pValue = false) {
- $this->_formatCells = $pValue;
- return $this;
+ public function setFormatCells($pValue = false)
+ {
+ $this->formatCells = $pValue;
+ return $this;
}
/**
@@ -270,8 +279,9 @@ function setFormatCells($pValue = false) {
*
* @return boolean
*/
- function getFormatColumns() {
- return $this->_formatColumns;
+ public function getFormatColumns()
+ {
+ return $this->formatColumns;
}
/**
@@ -280,9 +290,10 @@ function getFormatColumns() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setFormatColumns($pValue = false) {
- $this->_formatColumns = $pValue;
- return $this;
+ public function setFormatColumns($pValue = false)
+ {
+ $this->formatColumns = $pValue;
+ return $this;
}
/**
@@ -290,8 +301,9 @@ function setFormatColumns($pValue = false) {
*
* @return boolean
*/
- function getFormatRows() {
- return $this->_formatRows;
+ public function getFormatRows()
+ {
+ return $this->formatRows;
}
/**
@@ -300,9 +312,10 @@ function getFormatRows() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setFormatRows($pValue = false) {
- $this->_formatRows = $pValue;
- return $this;
+ public function setFormatRows($pValue = false)
+ {
+ $this->formatRows = $pValue;
+ return $this;
}
/**
@@ -310,8 +323,9 @@ function setFormatRows($pValue = false) {
*
* @return boolean
*/
- function getInsertColumns() {
- return $this->_insertColumns;
+ public function getInsertColumns()
+ {
+ return $this->insertColumns;
}
/**
@@ -320,9 +334,10 @@ function getInsertColumns() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setInsertColumns($pValue = false) {
- $this->_insertColumns = $pValue;
- return $this;
+ public function setInsertColumns($pValue = false)
+ {
+ $this->insertColumns = $pValue;
+ return $this;
}
/**
@@ -330,8 +345,9 @@ function setInsertColumns($pValue = false) {
*
* @return boolean
*/
- function getInsertRows() {
- return $this->_insertRows;
+ public function getInsertRows()
+ {
+ return $this->insertRows;
}
/**
@@ -340,9 +356,10 @@ function getInsertRows() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setInsertRows($pValue = false) {
- $this->_insertRows = $pValue;
- return $this;
+ public function setInsertRows($pValue = false)
+ {
+ $this->insertRows = $pValue;
+ return $this;
}
/**
@@ -350,8 +367,9 @@ function setInsertRows($pValue = false) {
*
* @return boolean
*/
- function getInsertHyperlinks() {
- return $this->_insertHyperlinks;
+ public function getInsertHyperlinks()
+ {
+ return $this->insertHyperlinks;
}
/**
@@ -360,9 +378,10 @@ function getInsertHyperlinks() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setInsertHyperlinks($pValue = false) {
- $this->_insertHyperlinks = $pValue;
- return $this;
+ public function setInsertHyperlinks($pValue = false)
+ {
+ $this->insertHyperlinks = $pValue;
+ return $this;
}
/**
@@ -370,8 +389,9 @@ function setInsertHyperlinks($pValue = false) {
*
* @return boolean
*/
- function getDeleteColumns() {
- return $this->_deleteColumns;
+ public function getDeleteColumns()
+ {
+ return $this->deleteColumns;
}
/**
@@ -380,9 +400,10 @@ function getDeleteColumns() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setDeleteColumns($pValue = false) {
- $this->_deleteColumns = $pValue;
- return $this;
+ public function setDeleteColumns($pValue = false)
+ {
+ $this->deleteColumns = $pValue;
+ return $this;
}
/**
@@ -390,8 +411,9 @@ function setDeleteColumns($pValue = false) {
*
* @return boolean
*/
- function getDeleteRows() {
- return $this->_deleteRows;
+ public function getDeleteRows()
+ {
+ return $this->deleteRows;
}
/**
@@ -400,9 +422,10 @@ function getDeleteRows() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setDeleteRows($pValue = false) {
- $this->_deleteRows = $pValue;
- return $this;
+ public function setDeleteRows($pValue = false)
+ {
+ $this->deleteRows = $pValue;
+ return $this;
}
/**
@@ -410,8 +433,9 @@ function setDeleteRows($pValue = false) {
*
* @return boolean
*/
- function getSelectLockedCells() {
- return $this->_selectLockedCells;
+ public function getSelectLockedCells()
+ {
+ return $this->selectLockedCells;
}
/**
@@ -420,9 +444,10 @@ function getSelectLockedCells() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setSelectLockedCells($pValue = false) {
- $this->_selectLockedCells = $pValue;
- return $this;
+ public function setSelectLockedCells($pValue = false)
+ {
+ $this->selectLockedCells = $pValue;
+ return $this;
}
/**
@@ -430,8 +455,9 @@ function setSelectLockedCells($pValue = false) {
*
* @return boolean
*/
- function getSort() {
- return $this->_sort;
+ public function getSort()
+ {
+ return $this->sort;
}
/**
@@ -440,9 +466,10 @@ function getSort() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setSort($pValue = false) {
- $this->_sort = $pValue;
- return $this;
+ public function setSort($pValue = false)
+ {
+ $this->sort = $pValue;
+ return $this;
}
/**
@@ -450,8 +477,9 @@ function setSort($pValue = false) {
*
* @return boolean
*/
- function getAutoFilter() {
- return $this->_autoFilter;
+ public function getAutoFilter()
+ {
+ return $this->autoFilter;
}
/**
@@ -460,9 +488,10 @@ function getAutoFilter() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setAutoFilter($pValue = false) {
- $this->_autoFilter = $pValue;
- return $this;
+ public function setAutoFilter($pValue = false)
+ {
+ $this->autoFilter = $pValue;
+ return $this;
}
/**
@@ -470,8 +499,9 @@ function setAutoFilter($pValue = false) {
*
* @return boolean
*/
- function getPivotTables() {
- return $this->_pivotTables;
+ public function getPivotTables()
+ {
+ return $this->pivotTables;
}
/**
@@ -480,9 +510,10 @@ function getPivotTables() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setPivotTables($pValue = false) {
- $this->_pivotTables = $pValue;
- return $this;
+ public function setPivotTables($pValue = false)
+ {
+ $this->pivotTables = $pValue;
+ return $this;
}
/**
@@ -490,8 +521,9 @@ function setPivotTables($pValue = false) {
*
* @return boolean
*/
- function getSelectUnlockedCells() {
- return $this->_selectUnlockedCells;
+ public function getSelectUnlockedCells()
+ {
+ return $this->selectUnlockedCells;
}
/**
@@ -500,9 +532,10 @@ function getSelectUnlockedCells() {
* @param boolean $pValue
* @return PHPExcel_Worksheet_Protection
*/
- function setSelectUnlockedCells($pValue = false) {
- $this->_selectUnlockedCells = $pValue;
- return $this;
+ public function setSelectUnlockedCells($pValue = false)
+ {
+ $this->selectUnlockedCells = $pValue;
+ return $this;
}
/**
@@ -510,36 +543,39 @@ function setSelectUnlockedCells($pValue = false) {
*
* @return string
*/
- function getPassword() {
- return $this->_password;
+ public function getPassword()
+ {
+ return $this->password;
}
/**
* Set Password
*
- * @param string $pValue
- * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
+ * @param string $pValue
+ * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
* @return PHPExcel_Worksheet_Protection
*/
- function setPassword($pValue = '', $pAlreadyHashed = false) {
- if (!$pAlreadyHashed) {
- $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue);
- }
- $this->_password = $pValue;
- return $this;
- }
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ public function setPassword($pValue = '', $pAlreadyHashed = false)
+ {
+ if (!$pAlreadyHashed) {
+ $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue);
+ }
+ $this->password = $pValue;
+ return $this;
+ }
+
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/Row.php b/Classes/PHPExcel/Worksheet/Row.php
index 0a4d1db01..4f6034f53 100644
--- a/Classes/PHPExcel/Worksheet/Row.php
+++ b/Classes/PHPExcel/Worksheet/Row.php
@@ -1,8 +1,9 @@
_parent = $parent;
- $this->_rowIndex = $rowIndex;
- }
+ /**
+ * Create a new row
+ *
+ * @param PHPExcel_Worksheet $parent
+ * @param int $rowIndex
+ */
+ public function __construct(PHPExcel_Worksheet $parent = null, $rowIndex = 1)
+ {
+ // Set parent and row index
+ $this->parent = $parent;
+ $this->rowIndex = $rowIndex;
+ }
- /**
- * Destructor
- */
- public function __destruct() {
- unset($this->_parent);
- }
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->parent);
+ }
- /**
- * Get row index
- *
- * @return int
- */
- public function getRowIndex() {
- return $this->_rowIndex;
- }
+ /**
+ * Get row index
+ *
+ * @return int
+ */
+ public function getRowIndex()
+ {
+ return $this->rowIndex;
+ }
- /**
- * Get cell iterator
- *
- * @return PHPExcel_Worksheet_CellIterator
- */
- public function getCellIterator() {
- return new PHPExcel_Worksheet_CellIterator($this->_parent, $this->_rowIndex);
- }
+ /**
+ * Get cell iterator
+ *
+ * @param string $startColumn The column address at which to start iterating
+ * @param string $endColumn Optionally, the column address at which to stop iterating
+ * @return PHPExcel_Worksheet_CellIterator
+ */
+ public function getCellIterator($startColumn = 'A', $endColumn = null)
+ {
+ return new PHPExcel_Worksheet_RowCellIterator($this->parent, $this->rowIndex, $startColumn, $endColumn);
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/RowCellIterator.php b/Classes/PHPExcel/Worksheet/RowCellIterator.php
new file mode 100644
index 000000000..90eb9c9f2
--- /dev/null
+++ b/Classes/PHPExcel/Worksheet/RowCellIterator.php
@@ -0,0 +1,225 @@
+subject = $subject;
+ $this->rowIndex = $rowIndex;
+ $this->resetEnd($endColumn);
+ $this->resetStart($startColumn);
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->subject);
+ }
+
+ /**
+ * (Re)Set the start column and the current column pointer
+ *
+ * @param integer $startColumn The column address at which to start iterating
+ * @return PHPExcel_Worksheet_RowCellIterator
+ * @throws PHPExcel_Exception
+ */
+ public function resetStart($startColumn = 'A')
+ {
+ $startColumnIndex = PHPExcel_Cell::columnIndexFromString($startColumn) - 1;
+ $this->startColumn = $startColumnIndex;
+ $this->adjustForExistingOnlyRange();
+ $this->seek(PHPExcel_Cell::stringFromColumnIndex($this->startColumn));
+
+ return $this;
+ }
+
+ /**
+ * (Re)Set the end column
+ *
+ * @param string $endColumn The column address at which to stop iterating
+ * @return PHPExcel_Worksheet_RowCellIterator
+ * @throws PHPExcel_Exception
+ */
+ public function resetEnd($endColumn = null)
+ {
+ $endColumn = ($endColumn) ? $endColumn : $this->subject->getHighestColumn();
+ $this->endColumn = PHPExcel_Cell::columnIndexFromString($endColumn) - 1;
+ $this->adjustForExistingOnlyRange();
+
+ return $this;
+ }
+
+ /**
+ * Set the column pointer to the selected column
+ *
+ * @param string $column The column address to set the current pointer at
+ * @return PHPExcel_Worksheet_RowCellIterator
+ * @throws PHPExcel_Exception
+ */
+ public function seek($column = 'A')
+ {
+ $column = PHPExcel_Cell::columnIndexFromString($column) - 1;
+ if (($column < $this->startColumn) || ($column > $this->endColumn)) {
+ throw new PHPExcel_Exception("Column $column is out of range ({$this->startColumn} - {$this->endColumn})");
+ } elseif ($this->onlyExistingCells && !($this->subject->cellExistsByColumnAndRow($column, $this->rowIndex))) {
+ throw new PHPExcel_Exception('In "IterateOnlyExistingCells" mode and Cell does not exist');
+ }
+ $this->position = $column;
+
+ return $this;
+ }
+
+ /**
+ * Rewind the iterator to the starting column
+ */
+ public function rewind()
+ {
+ $this->position = $this->startColumn;
+ }
+
+ /**
+ * Return the current cell in this worksheet row
+ *
+ * @return PHPExcel_Cell
+ */
+ public function current()
+ {
+ return $this->subject->getCellByColumnAndRow($this->position, $this->rowIndex);
+ }
+
+ /**
+ * Return the current iterator key
+ *
+ * @return string
+ */
+ public function key()
+ {
+ return PHPExcel_Cell::stringFromColumnIndex($this->position);
+ }
+
+ /**
+ * Set the iterator to its next value
+ */
+ public function next()
+ {
+ do {
+ ++$this->position;
+ } while (($this->onlyExistingCells) &&
+ (!$this->subject->cellExistsByColumnAndRow($this->position, $this->rowIndex)) &&
+ ($this->position <= $this->endColumn));
+ }
+
+ /**
+ * Set the iterator to its previous value
+ *
+ * @throws PHPExcel_Exception
+ */
+ public function prev()
+ {
+ if ($this->position <= $this->startColumn) {
+ throw new PHPExcel_Exception(
+ "Column is already at the beginning of range (" .
+ PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . " - " .
+ PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . ")"
+ );
+ }
+
+ do {
+ --$this->position;
+ } while (($this->onlyExistingCells) &&
+ (!$this->subject->cellExistsByColumnAndRow($this->position, $this->rowIndex)) &&
+ ($this->position >= $this->startColumn));
+ }
+
+ /**
+ * Indicate if more columns exist in the worksheet range of columns that we're iterating
+ *
+ * @return boolean
+ */
+ public function valid()
+ {
+ return $this->position <= $this->endColumn;
+ }
+
+ /**
+ * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary
+ *
+ * @throws PHPExcel_Exception
+ */
+ protected function adjustForExistingOnlyRange()
+ {
+ if ($this->onlyExistingCells) {
+ while ((!$this->subject->cellExistsByColumnAndRow($this->startColumn, $this->rowIndex)) &&
+ ($this->startColumn <= $this->endColumn)) {
+ ++$this->startColumn;
+ }
+ if ($this->startColumn > $this->endColumn) {
+ throw new PHPExcel_Exception('No cells exist within the specified range');
+ }
+ while ((!$this->subject->cellExistsByColumnAndRow($this->endColumn, $this->rowIndex)) &&
+ ($this->endColumn >= $this->startColumn)) {
+ --$this->endColumn;
+ }
+ if ($this->endColumn < $this->startColumn) {
+ throw new PHPExcel_Exception('No cells exist within the specified range');
+ }
+ }
+ }
+}
diff --git a/Classes/PHPExcel/Worksheet/RowDimension.php b/Classes/PHPExcel/Worksheet/RowDimension.php
index 6e8944d6a..c1474862c 100644
--- a/Classes/PHPExcel/Worksheet/RowDimension.php
+++ b/Classes/PHPExcel/Worksheet/RowDimension.php
@@ -1,8 +1,9 @@
_rowIndex = $pIndex;
+ // Initialise values
+ $this->rowIndex = $pIndex;
- // set row dimension as unformatted by default
- $this->_xfIndex = null;
+ // set dimension as unformatted by default
+ parent::__construct(null);
}
/**
@@ -105,8 +69,9 @@ public function __construct($pIndex = 0)
*
* @return int
*/
- public function getRowIndex() {
- return $this->_rowIndex;
+ public function getRowIndex()
+ {
+ return $this->rowIndex;
}
/**
@@ -115,9 +80,10 @@ public function getRowIndex() {
* @param int $pValue
* @return PHPExcel_Worksheet_RowDimension
*/
- public function setRowIndex($pValue) {
- $this->_rowIndex = $pValue;
- return $this;
+ public function setRowIndex($pValue)
+ {
+ $this->rowIndex = $pValue;
+ return $this;
}
/**
@@ -125,8 +91,9 @@ public function setRowIndex($pValue) {
*
* @return double
*/
- public function getRowHeight() {
- return $this->_rowHeight;
+ public function getRowHeight()
+ {
+ return $this->height;
}
/**
@@ -135,131 +102,31 @@ public function getRowHeight() {
* @param double $pValue
* @return PHPExcel_Worksheet_RowDimension
*/
- public function setRowHeight($pValue = -1) {
- $this->_rowHeight = $pValue;
- return $this;
- }
-
- /**
- * Get ZeroHeight
- *
- * @return bool
- */
- public function getzeroHeight() {
- return $this->_zeroHeight;
- }
-
- /**
- * Set ZeroHeight
- *
- * @param bool $pValue
- * @return PHPExcel_Worksheet_RowDimension
- */
- public function setzeroHeight($pValue = false) {
- $this->_zeroHeight = $pValue;
- return $this;
- }
-
- /**
- * Get Visible
- *
- * @return bool
- */
- public function getVisible() {
- return $this->_visible;
- }
-
- /**
- * Set Visible
- *
- * @param bool $pValue
- * @return PHPExcel_Worksheet_RowDimension
- */
- public function setVisible($pValue = true) {
- $this->_visible = $pValue;
- return $this;
- }
-
- /**
- * Get Outline Level
- *
- * @return int
- */
- public function getOutlineLevel() {
- return $this->_outlineLevel;
- }
-
- /**
- * Set Outline Level
- *
- * Value must be between 0 and 7
- *
- * @param int $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_RowDimension
- */
- public function setOutlineLevel($pValue) {
- if ($pValue < 0 || $pValue > 7) {
- throw new PHPExcel_Exception("Outline level must range between 0 and 7.");
- }
-
- $this->_outlineLevel = $pValue;
- return $this;
+ public function setRowHeight($pValue = -1)
+ {
+ $this->height = $pValue;
+ return $this;
}
/**
- * Get Collapsed
+ * Get ZeroHeight
*
* @return bool
*/
- public function getCollapsed() {
- return $this->_collapsed;
+ public function getZeroHeight()
+ {
+ return $this->zeroHeight;
}
/**
- * Set Collapsed
+ * Set ZeroHeight
*
* @param bool $pValue
* @return PHPExcel_Worksheet_RowDimension
*/
- public function setCollapsed($pValue = true) {
- $this->_collapsed = $pValue;
- return $this;
+ public function setZeroHeight($pValue = false)
+ {
+ $this->zeroHeight = $pValue;
+ return $this;
}
-
- /**
- * Get index to cellXf
- *
- * @return int
- */
- public function getXfIndex()
- {
- return $this->_xfIndex;
- }
-
- /**
- * Set index to cellXf
- *
- * @param int $pValue
- * @return PHPExcel_Worksheet_RowDimension
- */
- public function setXfIndex($pValue = 0)
- {
- $this->_xfIndex = $pValue;
- return $this;
- }
-
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
}
diff --git a/Classes/PHPExcel/Worksheet/RowIterator.php b/Classes/PHPExcel/Worksheet/RowIterator.php
index c03038c40..9ddb3e030 100644
--- a/Classes/PHPExcel/Worksheet/RowIterator.php
+++ b/Classes/PHPExcel/Worksheet/RowIterator.php
@@ -1,8 +1,9 @@
_subject = $subject;
- $this->resetStart($startRow);
- }
-
- /**
- * Destructor
- */
- public function __destruct() {
- unset($this->_subject);
- }
-
- /**
- * (Re)Set the start row and the current row pointer
- *
- * @param integer $startRow The row number at which to start iterating
- */
- public function resetStart($startRow = 1) {
- $this->_startRow = $startRow;
- $this->seek($startRow);
- }
-
- /**
- * Set the row pointer to the selected row
- *
- * @param integer $row The row number to set the current pointer at
- */
- public function seek($row = 1) {
- $this->_position = $row;
- }
-
- /**
- * Rewind the iterator to the starting row
- */
- public function rewind() {
- $this->_position = $this->_startRow;
- }
-
- /**
- * Return the current row in this worksheet
- *
- * @return PHPExcel_Worksheet_Row
- */
- public function current() {
- return new PHPExcel_Worksheet_Row($this->_subject, $this->_position);
- }
-
- /**
- * Return the current iterator key
- *
- * @return int
- */
- public function key() {
- return $this->_position;
- }
-
- /**
- * Set the iterator to its next value
- */
- public function next() {
- ++$this->_position;
- }
-
- /**
- * Set the iterator to its previous value
- */
- public function prev() {
- if ($this->_position > 1)
- --$this->_position;
- }
-
- /**
- * Indicate if more rows exist in the worksheet
- *
- * @return boolean
- */
- public function valid() {
- return $this->_position <= $this->_subject->getHighestRow();
- }
+ /**
+ * PHPExcel_Worksheet to iterate
+ *
+ * @var PHPExcel_Worksheet
+ */
+ private $subject;
+
+ /**
+ * Current iterator position
+ *
+ * @var int
+ */
+ private $position = 1;
+
+ /**
+ * Start position
+ *
+ * @var int
+ */
+ private $startRow = 1;
+
+
+ /**
+ * End position
+ *
+ * @var int
+ */
+ private $endRow = 1;
+
+
+ /**
+ * Create a new row iterator
+ *
+ * @param PHPExcel_Worksheet $subject The worksheet to iterate over
+ * @param integer $startRow The row number at which to start iterating
+ * @param integer $endRow Optionally, the row number at which to stop iterating
+ */
+ public function __construct(PHPExcel_Worksheet $subject, $startRow = 1, $endRow = null)
+ {
+ // Set subject
+ $this->subject = $subject;
+ $this->resetEnd($endRow);
+ $this->resetStart($startRow);
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->subject);
+ }
+
+ /**
+ * (Re)Set the start row and the current row pointer
+ *
+ * @param integer $startRow The row number at which to start iterating
+ * @return PHPExcel_Worksheet_RowIterator
+ * @throws PHPExcel_Exception
+ */
+ public function resetStart($startRow = 1)
+ {
+ if ($startRow > $this->subject->getHighestRow()) {
+ throw new PHPExcel_Exception("Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})");
+ }
+
+ $this->startRow = $startRow;
+ if ($this->endRow < $this->startRow) {
+ $this->endRow = $this->startRow;
+ }
+ $this->seek($startRow);
+
+ return $this;
+ }
+
+ /**
+ * (Re)Set the end row
+ *
+ * @param integer $endRow The row number at which to stop iterating
+ * @return PHPExcel_Worksheet_RowIterator
+ */
+ public function resetEnd($endRow = null)
+ {
+ $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow();
+
+ return $this;
+ }
+
+ /**
+ * Set the row pointer to the selected row
+ *
+ * @param integer $row The row number to set the current pointer at
+ * @return PHPExcel_Worksheet_RowIterator
+ * @throws PHPExcel_Exception
+ */
+ public function seek($row = 1)
+ {
+ if (($row < $this->startRow) || ($row > $this->endRow)) {
+ throw new PHPExcel_Exception("Row $row is out of range ({$this->startRow} - {$this->endRow})");
+ }
+ $this->position = $row;
+
+ return $this;
+ }
+
+ /**
+ * Rewind the iterator to the starting row
+ */
+ public function rewind()
+ {
+ $this->position = $this->startRow;
+ }
+
+ /**
+ * Return the current row in this worksheet
+ *
+ * @return PHPExcel_Worksheet_Row
+ */
+ public function current()
+ {
+ return new PHPExcel_Worksheet_Row($this->subject, $this->position);
+ }
+
+ /**
+ * Return the current iterator key
+ *
+ * @return int
+ */
+ public function key()
+ {
+ return $this->position;
+ }
+
+ /**
+ * Set the iterator to its next value
+ */
+ public function next()
+ {
+ ++$this->position;
+ }
+
+ /**
+ * Set the iterator to its previous value
+ */
+ public function prev()
+ {
+ if ($this->position <= $this->startRow) {
+ throw new PHPExcel_Exception("Row is already at the beginning of range ({$this->startRow} - {$this->endRow})");
+ }
+
+ --$this->position;
+ }
+
+ /**
+ * Indicate if more rows exist in the worksheet range of rows that we're iterating
+ *
+ * @return boolean
+ */
+ public function valid()
+ {
+ return $this->position <= $this->endRow;
+ }
}
diff --git a/Classes/PHPExcel/Worksheet/SheetView.php b/Classes/PHPExcel/Worksheet/SheetView.php
index 30dbc2be3..5aaef3ba3 100644
--- a/Classes/PHPExcel/Worksheet/SheetView.php
+++ b/Classes/PHPExcel/Worksheet/SheetView.php
@@ -1,8 +1,9 @@
_zoomScale;
- }
-
- /**
- * Set ZoomScale
- *
- * Valid values range from 10 to 400.
- *
- * @param int $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_SheetView
- */
- public function setZoomScale($pValue = 100) {
- // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
- // but it is apparently still able to handle any scale >= 1
- if (($pValue >= 1) || is_null($pValue)) {
- $this->_zoomScale = $pValue;
- } else {
- throw new PHPExcel_Exception("Scale must be greater than or equal to 1.");
- }
- return $this;
- }
+ /**
+ * Get ZoomScale
+ *
+ * @return int
+ */
+ public function getZoomScale()
+ {
+ return $this->zoomScale;
+ }
- /**
- * Get ZoomScaleNormal
- *
- * @return int
- */
- public function getZoomScaleNormal() {
- return $this->_zoomScaleNormal;
- }
+ /**
+ * Set ZoomScale
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @param int $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_SheetView
+ */
+ public function setZoomScale($pValue = 100)
+ {
+ // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
+ // but it is apparently still able to handle any scale >= 1
+ if (($pValue >= 1) || is_null($pValue)) {
+ $this->zoomScale = $pValue;
+ } else {
+ throw new PHPExcel_Exception("Scale must be greater than or equal to 1.");
+ }
+ return $this;
+ }
- /**
- * Set ZoomScale
- *
- * Valid values range from 10 to 400.
- *
- * @param int $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_SheetView
- */
- public function setZoomScaleNormal($pValue = 100) {
- if (($pValue >= 1) || is_null($pValue)) {
- $this->_zoomScaleNormal = $pValue;
- } else {
- throw new PHPExcel_Exception("Scale must be greater than or equal to 1.");
- }
- return $this;
- }
+ /**
+ * Get ZoomScaleNormal
+ *
+ * @return int
+ */
+ public function getZoomScaleNormal()
+ {
+ return $this->zoomScaleNormal;
+ }
- /**
- * Get View
- *
- * @return string
- */
- public function getView() {
- return $this->_sheetviewType;
- }
+ /**
+ * Set ZoomScale
+ *
+ * Valid values range from 10 to 400.
+ *
+ * @param int $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_SheetView
+ */
+ public function setZoomScaleNormal($pValue = 100)
+ {
+ if (($pValue >= 1) || is_null($pValue)) {
+ $this->zoomScaleNormal = $pValue;
+ } else {
+ throw new PHPExcel_Exception("Scale must be greater than or equal to 1.");
+ }
+ return $this;
+ }
- /**
- * Set View
- *
- * Valid values are
- * 'normal' self::SHEETVIEW_NORMAL
- * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT
- * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW
- *
- * @param string $pValue
- * @throws PHPExcel_Exception
- * @return PHPExcel_Worksheet_SheetView
- */
- public function setView($pValue = NULL) {
- // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview'
- // via the user interface
- if ($pValue === NULL)
- $pValue = self::SHEETVIEW_NORMAL;
- if (in_array($pValue, self::$_sheetViewTypes)) {
- $this->_sheetviewType = $pValue;
- } else {
- throw new PHPExcel_Exception("Invalid sheetview layout type.");
- }
+ /**
+ * Get View
+ *
+ * @return string
+ */
+ public function getView()
+ {
+ return $this->sheetviewType;
+ }
- return $this;
- }
+ /**
+ * Set View
+ *
+ * Valid values are
+ * 'normal' self::SHEETVIEW_NORMAL
+ * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT
+ * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW
+ *
+ * @param string $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_SheetView
+ */
+ public function setView($pValue = null)
+ {
+ // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface
+ if ($pValue === null) {
+ $pValue = self::SHEETVIEW_NORMAL;
+ }
+ if (in_array($pValue, self::$sheetViewTypes)) {
+ $this->sheetviewType = $pValue;
+ } else {
+ throw new PHPExcel_Exception("Invalid sheetview layout type.");
+ }
+
+ return $this;
+ }
- /**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
- */
- public function __clone() {
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone()
+ {
+ $vars = get_object_vars($this);
+ foreach ($vars as $key => $value) {
+ if (is_object($value)) {
+ $this->$key = clone $value;
+ } else {
+ $this->$key = $value;
+ }
+ }
+ }
}
diff --git a/Classes/PHPExcel/WorksheetIterator.php b/Classes/PHPExcel/WorksheetIterator.php
index cceec417c..cb1b28118 100644
--- a/Classes/PHPExcel/WorksheetIterator.php
+++ b/Classes/PHPExcel/WorksheetIterator.php
@@ -1,8 +1,9 @@
_subject = $subject;
+ $this->subject = $subject;
}
/**
@@ -67,7 +57,7 @@ public function __construct(PHPExcel $subject = null)
*/
public function __destruct()
{
- unset($this->_subject);
+ unset($this->subject);
}
/**
@@ -75,7 +65,7 @@ public function __destruct()
*/
public function rewind()
{
- $this->_position = 0;
+ $this->position = 0;
}
/**
@@ -85,7 +75,7 @@ public function rewind()
*/
public function current()
{
- return $this->_subject->getSheet($this->_position);
+ return $this->subject->getSheet($this->position);
}
/**
@@ -95,7 +85,7 @@ public function current()
*/
public function key()
{
- return $this->_position;
+ return $this->position;
}
/**
@@ -103,7 +93,7 @@ public function key()
*/
public function next()
{
- ++$this->_position;
+ ++$this->position;
}
/**
@@ -113,6 +103,6 @@ public function next()
*/
public function valid()
{
- return $this->_position < $this->_subject->getSheetCount();
+ return $this->position < $this->subject->getSheetCount();
}
}
diff --git a/Classes/PHPExcel/Writer/Abstract.php b/Classes/PHPExcel/Writer/Abstract.php
index 7aa50ccaa..2a797a948 100644
--- a/Classes/PHPExcel/Writer/Abstract.php
+++ b/Classes/PHPExcel/Writer/Abstract.php
@@ -1,8 +1,9 @@
_includeCharts;
- }
+ /**
+ * Write charts in workbook?
+ * If this is true, then the Writer will write definitions for any charts that exist in the PHPExcel object.
+ * If false (the default) it will ignore any charts defined in the PHPExcel object.
+ *
+ * @return boolean
+ */
+ public function getIncludeCharts()
+ {
+ return $this->includeCharts;
+ }
- /**
- * Set write charts in workbook
- * Set to true, to advise the Writer to include any charts that exist in the PHPExcel object.
- * Set to false (the default) to ignore charts.
- *
- * @param boolean $pValue
- * @return PHPExcel_Writer_IWriter
- */
- public function setIncludeCharts($pValue = FALSE) {
- $this->_includeCharts = (boolean) $pValue;
- return $this;
- }
+ /**
+ * Set write charts in workbook
+ * Set to true, to advise the Writer to include any charts that exist in the PHPExcel object.
+ * Set to false (the default) to ignore charts.
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Writer_IWriter
+ */
+ public function setIncludeCharts($pValue = false)
+ {
+ $this->includeCharts = (boolean) $pValue;
+ return $this;
+ }
/**
* Get Pre-Calculate Formulas flag
- * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving,
- * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet
- * viewer when opening the file
- * If false, then formulae are not calculated on save. This is faster for saving in PHPExcel, but slower
- * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself
+ * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving,
+ * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet
+ * viewer when opening the file
+ * If false, then formulae are not calculated on save. This is faster for saving in PHPExcel, but slower
+ * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself
*
* @return boolean
*/
- public function getPreCalculateFormulas() {
- return $this->_preCalculateFormulas;
+ public function getPreCalculateFormulas()
+ {
+ return $this->preCalculateFormulas;
}
/**
* Set Pre-Calculate Formulas
- * Set to true (the default) to advise the Writer to calculate all formulae on save
- * Set to false to prevent precalculation of formulae on save.
+ * Set to true (the default) to advise the Writer to calculate all formulae on save
+ * Set to false to prevent precalculation of formulae on save.
*
- * @param boolean $pValue Pre-Calculate Formulas?
- * @return PHPExcel_Writer_IWriter
+ * @param boolean $pValue Pre-Calculate Formulas?
+ * @return PHPExcel_Writer_IWriter
*/
- public function setPreCalculateFormulas($pValue = TRUE) {
- $this->_preCalculateFormulas = (boolean) $pValue;
- return $this;
+ public function setPreCalculateFormulas($pValue = true)
+ {
+ $this->preCalculateFormulas = (boolean) $pValue;
+ return $this;
}
- /**
- * Get use disk caching where possible?
- *
- * @return boolean
- */
- public function getUseDiskCaching() {
- return $this->_useDiskCaching;
- }
+ /**
+ * Get use disk caching where possible?
+ *
+ * @return boolean
+ */
+ public function getUseDiskCaching()
+ {
+ return $this->_useDiskCaching;
+ }
- /**
- * Set use disk caching where possible?
- *
- * @param boolean $pValue
- * @param string $pDirectory Disk caching directory
- * @throws PHPExcel_Writer_Exception when directory does not exist
- * @return PHPExcel_Writer_Excel2007
- */
- public function setUseDiskCaching($pValue = FALSE, $pDirectory = NULL) {
- $this->_useDiskCaching = $pValue;
+ /**
+ * Set use disk caching where possible?
+ *
+ * @param boolean $pValue
+ * @param string $pDirectory Disk caching directory
+ * @throws PHPExcel_Writer_Exception when directory does not exist
+ * @return PHPExcel_Writer_Excel2007
+ */
+ public function setUseDiskCaching($pValue = false, $pDirectory = null)
+ {
+ $this->_useDiskCaching = $pValue;
- if ($pDirectory !== NULL) {
- if (is_dir($pDirectory)) {
- $this->_diskCachingDirectory = $pDirectory;
- } else {
- throw new PHPExcel_Writer_Exception("Directory does not exist: $pDirectory");
- }
- }
- return $this;
- }
+ if ($pDirectory !== null) {
+ if (is_dir($pDirectory)) {
+ $this->_diskCachingDirectory = $pDirectory;
+ } else {
+ throw new PHPExcel_Writer_Exception("Directory does not exist: $pDirectory");
+ }
+ }
+ return $this;
+ }
- /**
- * Get disk caching directory
- *
- * @return string
- */
- public function getDiskCachingDirectory() {
- return $this->_diskCachingDirectory;
- }
+ /**
+ * Get disk caching directory
+ *
+ * @return string
+ */
+ public function getDiskCachingDirectory()
+ {
+ return $this->_diskCachingDirectory;
+ }
}
diff --git a/Classes/PHPExcel/Writer/CSV.php b/Classes/PHPExcel/Writer/CSV.php
index 2ff5b410e..e59c30130 100644
--- a/Classes/PHPExcel/Writer/CSV.php
+++ b/Classes/PHPExcel/Writer/CSV.php
@@ -1,8 +1,9 @@
_phpExcel = $phpExcel;
- }
-
- /**
- * 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()->writeDebugLog;
- PHPExcel_Calculation::getInstance()->writeDebugLog = 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) {
- // Write the UTF-16LE BOM code
- fwrite($fileHandle, "\xFF\xFE"); // Excel uses UTF-16LE encoding
- $this->setEnclosure(); // Default enclosure is "
- $this->setDelimiter("\t"); // Excel delimiter is a TAB
- } elseif ($this->_useBOM) {
- // Write the UTF-8 BOM code
- fwrite($fileHandle, "\xEF\xBB\xBF");
- }
-
- // Identify the range that we need to extract from the worksheet
- $maxCol = $sheet->getHighestColumn();
- $maxRow = $sheet->getHighestRow();
-
- // 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()->writeDebugLog = $saveDebugLog;
- }
-
- /**
- * Get delimiter
- *
- * @return string
- */
- public function getDelimiter() {
- return $this->_delimiter;
- }
-
- /**
- * Set delimiter
- *
- * @param string $pValue Delimiter, defaults to ,
- * @return PHPExcel_Writer_CSV
- */
- public function setDelimiter($pValue = ',') {
- $this->_delimiter = $pValue;
- return $this;
- }
-
- /**
- * Get enclosure
- *
- * @return string
- */
- public function getEnclosure() {
- return $this->_enclosure;
- }
-
- /**
- * Set enclosure
- *
- * @param string $pValue Enclosure, defaults to "
- * @return PHPExcel_Writer_CSV
- */
- public function setEnclosure($pValue = '"') {
- if ($pValue == '') {
- $pValue = null;
- }
- $this->_enclosure = $pValue;
- return $this;
- }
-
- /**
- * Get line ending
- *
- * @return string
- */
- public function getLineEnding() {
- return $this->_lineEnding;
- }
-
- /**
- * Set line ending
- *
- * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL)
- * @return PHPExcel_Writer_CSV
- */
- public function setLineEnding($pValue = PHP_EOL) {
- $this->_lineEnding = $pValue;
- return $this;
- }
-
- /**
- * Get whether BOM should be used
- *
- * @return boolean
- */
- public function getUseBOM() {
- return $this->_useBOM;
- }
-
- /**
- * Set whether BOM should be used
- *
- * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false
- * @return PHPExcel_Writer_CSV
- */
- public function setUseBOM($pValue = false) {
- $this->_useBOM = $pValue;
- return $this;
- }
-
- /**
- * Get whether the file should be saved with full Excel Compatibility
- *
- * @return boolean
- */
- public function getExcelCompatibility() {
- return $this->_excelCompatibility;
- }
-
- /**
- * Set whether the file should be saved with full Excel Compatibility
- *
- * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file
- * Note that this overrides other settings such as useBOM, enclosure and delimiter
- * @return PHPExcel_Writer_CSV
- */
- public function setExcelCompatibility($pValue = false) {
- $this->_excelCompatibility = $pValue;
- return $this;
- }
-
- /**
- * Get sheet index
- *
- * @return int
- */
- public function getSheetIndex() {
- return $this->_sheetIndex;
- }
-
- /**
- * Set sheet index
- *
- * @param int $pValue Sheet index
- * @return PHPExcel_Writer_CSV
- */
- public function setSheetIndex($pValue = 0) {
- $this->_sheetIndex = $pValue;
- return $this;
- }
-
- /**
- * Write line to CSV file
- *
- * @param mixed $pFileHandle PHP filehandle
- * @param array $pValues Array containing values in a row
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeLine($pFileHandle = null, $pValues = null) {
- if (is_array($pValues)) {
- // No leading delimiter
- $writeDelimiter = false;
-
- // Build the line
- $line = '';
-
- foreach ($pValues as $element) {
- // Escape enclosures
- $element = str_replace($this->_enclosure, $this->_enclosure . $this->_enclosure, $element);
-
- // Add delimiter
- if ($writeDelimiter) {
- $line .= $this->_delimiter;
- } else {
- $writeDelimiter = true;
- }
-
- // Add enclosed string
- $line .= $this->_enclosure . $element . $this->_enclosure;
- }
-
- // Add line ending
- $line .= $this->_lineEnding;
-
- // Write to file
- if ($this->_excelCompatibility) {
- fwrite($pFileHandle, mb_convert_encoding($line,"UTF-16LE","UTF-8"));
- } else {
- fwrite($pFileHandle, $line);
- }
- } else {
- throw new PHPExcel_Writer_Exception("Invalid data row passed to CSV writer.");
- }
- }
-
+class PHPExcel_Writer_CSV extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter
+{
+ /**
+ * PHPExcel object
+ *
+ * @var PHPExcel
+ */
+ private $phpExcel;
+
+ /**
+ * Delimiter
+ *
+ * @var string
+ */
+ private $delimiter = ',';
+
+ /**
+ * Enclosure
+ *
+ * @var string
+ */
+ private $enclosure = '"';
+
+ /**
+ * Line ending
+ *
+ * @var string
+ */
+ private $lineEnding = PHP_EOL;
+
+ /**
+ * Sheet index to write
+ *
+ * @var int
+ */
+ private $sheetIndex = 0;
+
+ /**
+ * Whether to write a BOM (for UTF8).
+ *
+ * @var boolean
+ */
+ private $useBOM = false;
+
+ /**
+ * Whether to write a Separator line as the first line of the file
+ * sep=x
+ *
+ * @var boolean
+ */
+ private $includeSeparatorLine = false;
+
+ /**
+ * Whether to write a fully Excel compatible CSV file.
+ *
+ * @var boolean
+ */
+ private $excelCompatibility = false;
+
+ /**
+ * Create a new PHPExcel_Writer_CSV
+ *
+ * @param PHPExcel $phpExcel PHPExcel object
+ */
+ public function __construct(PHPExcel $phpExcel)
+ {
+ $this->phpExcel = $phpExcel;
+ }
+
+ /**
+ * 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) {
+ $this->setUseBOM(true); // Enforce UTF-8 BOM Header
+ $this->setIncludeSeparatorLine(true); // Set separator line
+ $this->setEnclosure('"'); // Set enclosure to "
+ $this->setDelimiter(";"); // Set delimiter to a semi-colon
+ $this->setLineEnding("\r\n");
+ }
+ if ($this->useBOM) {
+ // Write the UTF-8 BOM code if required
+ fwrite($fileHandle, "\xEF\xBB\xBF");
+ }
+ if ($this->includeSeparatorLine) {
+ // Write the separator line if required
+ fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding);
+ }
+
+ // 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);
+ }
+
+ /**
+ * Get delimiter
+ *
+ * @return string
+ */
+ public function getDelimiter()
+ {
+ return $this->delimiter;
+ }
+
+ /**
+ * Set delimiter
+ *
+ * @param string $pValue Delimiter, defaults to ,
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setDelimiter($pValue = ',')
+ {
+ $this->delimiter = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get enclosure
+ *
+ * @return string
+ */
+ public function getEnclosure()
+ {
+ return $this->enclosure;
+ }
+
+ /**
+ * Set enclosure
+ *
+ * @param string $pValue Enclosure, defaults to "
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setEnclosure($pValue = '"')
+ {
+ if ($pValue == '') {
+ $pValue = null;
+ }
+ $this->enclosure = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get line ending
+ *
+ * @return string
+ */
+ public function getLineEnding()
+ {
+ return $this->lineEnding;
+ }
+
+ /**
+ * Set line ending
+ *
+ * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL)
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setLineEnding($pValue = PHP_EOL)
+ {
+ $this->lineEnding = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get whether BOM should be used
+ *
+ * @return boolean
+ */
+ public function getUseBOM()
+ {
+ return $this->useBOM;
+ }
+
+ /**
+ * Set whether BOM should be used
+ *
+ * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setUseBOM($pValue = false)
+ {
+ $this->useBOM = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get whether a separator line should be included
+ *
+ * @return boolean
+ */
+ public function getIncludeSeparatorLine()
+ {
+ return $this->includeSeparatorLine;
+ }
+
+ /**
+ * Set whether a separator line should be included as the first line of the file
+ *
+ * @param boolean $pValue Use separator line? Defaults to false
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setIncludeSeparatorLine($pValue = false)
+ {
+ $this->includeSeparatorLine = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get whether the file should be saved with full Excel Compatibility
+ *
+ * @return boolean
+ */
+ public function getExcelCompatibility()
+ {
+ return $this->excelCompatibility;
+ }
+
+ /**
+ * Set whether the file should be saved with full Excel Compatibility
+ *
+ * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file
+ * Note that this overrides other settings such as useBOM, enclosure and delimiter
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setExcelCompatibility($pValue = false)
+ {
+ $this->excelCompatibility = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get sheet index
+ *
+ * @return int
+ */
+ public function getSheetIndex()
+ {
+ return $this->sheetIndex;
+ }
+
+ /**
+ * Set sheet index
+ *
+ * @param int $pValue Sheet index
+ * @return PHPExcel_Writer_CSV
+ */
+ public function setSheetIndex($pValue = 0)
+ {
+ $this->sheetIndex = $pValue;
+ return $this;
+ }
+
+ /**
+ * Write line to CSV file
+ *
+ * @param mixed $pFileHandle PHP filehandle
+ * @param array $pValues Array containing values in a row
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeLine($pFileHandle = null, $pValues = null)
+ {
+ if (is_array($pValues)) {
+ // No leading delimiter
+ $writeDelimiter = false;
+
+ // Build the line
+ $line = '';
+
+ foreach ($pValues as $element) {
+ // Escape enclosures
+ $element = str_replace($this->enclosure, $this->enclosure . $this->enclosure, $element);
+
+ // Add delimiter
+ if ($writeDelimiter) {
+ $line .= $this->delimiter;
+ } else {
+ $writeDelimiter = true;
+ }
+
+ // Add enclosed string
+ $line .= $this->enclosure . $element . $this->enclosure;
+ }
+
+ // Add line ending
+ $line .= $this->lineEnding;
+
+ // Write to file
+ fwrite($pFileHandle, $line);
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid data row passed to CSV writer.");
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007.php b/Classes/PHPExcel/Writer/Excel2007.php
index a74350ca5..11d354b4a 100644
--- a/Classes/PHPExcel/Writer/Excel2007.php
+++ b/Classes/PHPExcel/Writer/Excel2007.php
@@ -1,8 +1,9 @@
setPHPExcel($pPHPExcel);
-
- $writerPartsArray = array( 'stringtable' => 'PHPExcel_Writer_Excel2007_StringTable',
- 'contenttypes' => 'PHPExcel_Writer_Excel2007_ContentTypes',
- 'docprops' => 'PHPExcel_Writer_Excel2007_DocProps',
- 'rels' => 'PHPExcel_Writer_Excel2007_Rels',
- 'theme' => 'PHPExcel_Writer_Excel2007_Theme',
- 'style' => 'PHPExcel_Writer_Excel2007_Style',
- 'workbook' => 'PHPExcel_Writer_Excel2007_Workbook',
- 'worksheet' => 'PHPExcel_Writer_Excel2007_Worksheet',
- 'drawing' => 'PHPExcel_Writer_Excel2007_Drawing',
- 'comments' => 'PHPExcel_Writer_Excel2007_Comments',
- 'chart' => 'PHPExcel_Writer_Excel2007_Chart',
- );
-
- // Initialise writer parts
- // and Assign their parent IWriters
- foreach ($writerPartsArray as $writer => $class) {
- $this->_writerParts[$writer] = new $class($this);
- }
-
- $hashTablesArray = array( '_stylesConditionalHashTable', '_fillHashTable', '_fontHashTable',
- '_bordersHashTable', '_numFmtHashTable', '_drawingHashTable'
- );
-
- // Set HashTable variables
- foreach ($hashTablesArray as $tableName) {
- $this->$tableName = new PHPExcel_HashTable();
- }
+ // Assign PHPExcel
+ $this->setPHPExcel($pPHPExcel);
+
+ $writerPartsArray = array( 'stringtable' => 'PHPExcel_Writer_Excel2007_StringTable',
+ 'contenttypes' => 'PHPExcel_Writer_Excel2007_ContentTypes',
+ 'docprops' => 'PHPExcel_Writer_Excel2007_DocProps',
+ 'rels' => 'PHPExcel_Writer_Excel2007_Rels',
+ 'theme' => 'PHPExcel_Writer_Excel2007_Theme',
+ 'style' => 'PHPExcel_Writer_Excel2007_Style',
+ 'workbook' => 'PHPExcel_Writer_Excel2007_Workbook',
+ 'worksheet' => 'PHPExcel_Writer_Excel2007_Worksheet',
+ 'drawing' => 'PHPExcel_Writer_Excel2007_Drawing',
+ 'comments' => 'PHPExcel_Writer_Excel2007_Comments',
+ 'chart' => 'PHPExcel_Writer_Excel2007_Chart',
+ 'relsvba' => 'PHPExcel_Writer_Excel2007_RelsVBA',
+ 'relsribbonobjects' => 'PHPExcel_Writer_Excel2007_RelsRibbon'
+ );
+
+ // Initialise writer parts
+ // and Assign their parent IWriters
+ foreach ($writerPartsArray as $writer => $class) {
+ $this->writerParts[$writer] = new $class($this);
+ }
+
+ $hashTablesArray = array( 'stylesConditionalHashTable', 'fillHashTable', 'fontHashTable',
+ 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable',
+ 'styleHashTable'
+ );
+
+ // Set HashTable variables
+ foreach ($hashTablesArray as $tableName) {
+ $this->$tableName = new PHPExcel_HashTable();
+ }
}
- /**
- * Get writer part
- *
- * @param string $pPartName Writer part name
- * @return PHPExcel_Writer_Excel2007_WriterPart
- */
- public function getWriterPart($pPartName = '') {
- if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) {
- return $this->_writerParts[strtolower($pPartName)];
- } else {
- return null;
- }
- }
-
- /**
- * 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()->writeDebugLog;
- PHPExcel_Calculation::getInstance()->writeDebugLog = 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->_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));
-
- // 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()->writeDebugLog = $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.");
- }
- }
-
- /**
- * Get PHPExcel object
- *
- * @return PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function getPHPExcel() {
- if ($this->_spreadSheet !== null) {
- return $this->_spreadSheet;
- } else {
- throw new PHPExcel_Writer_Exception("No PHPExcel assigned.");
- }
- }
-
- /**
- * Set PHPExcel object
- *
- * @param PHPExcel $pPHPExcel PHPExcel object
- * @throws PHPExcel_Writer_Exception
- * @return PHPExcel_Writer_Excel2007
- */
- public function setPHPExcel(PHPExcel $pPHPExcel = null) {
- $this->_spreadSheet = $pPHPExcel;
- return $this;
- }
+ /**
+ * Get writer part
+ *
+ * @param string $pPartName Writer part name
+ * @return PHPExcel_Writer_Excel2007_WriterPart
+ */
+ public function getWriterPart($pPartName = '')
+ {
+ if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
+ return $this->writerParts[strtolower($pPartName)];
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * 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, $this->preCalculateFormulas));
+ $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);
+ } elseif ($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.");
+ }
+ }
+
+ /**
+ * Get PHPExcel object
+ *
+ * @return PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function getPHPExcel()
+ {
+ if ($this->spreadSheet !== null) {
+ return $this->spreadSheet;
+ } else {
+ throw new PHPExcel_Writer_Exception("No PHPExcel object assigned.");
+ }
+ }
+
+ /**
+ * Set PHPExcel object
+ *
+ * @param PHPExcel $pPHPExcel PHPExcel object
+ * @throws PHPExcel_Writer_Exception
+ * @return PHPExcel_Writer_Excel2007
+ */
+ public function setPHPExcel(PHPExcel $pPHPExcel = null)
+ {
+ $this->spreadSheet = $pPHPExcel;
+ return $this;
+ }
/**
* Get string table
*
* @return string[]
*/
- public function getStringTable() {
- return $this->_stringTable;
+ public function getStringTable()
+ {
+ return $this->stringTable;
+ }
+
+ /**
+ * Get PHPExcel_Style HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getStyleHashTable()
+ {
+ return $this->styleHashTable;
}
/**
@@ -400,8 +454,9 @@ public function getStringTable() {
*
* @return PHPExcel_HashTable
*/
- public function getStylesConditionalHashTable() {
- return $this->_stylesConditionalHashTable;
+ public function getStylesConditionalHashTable()
+ {
+ return $this->stylesConditionalHashTable;
}
/**
@@ -409,8 +464,9 @@ public function getStylesConditionalHashTable() {
*
* @return PHPExcel_HashTable
*/
- public function getFillHashTable() {
- return $this->_fillHashTable;
+ public function getFillHashTable()
+ {
+ return $this->fillHashTable;
}
/**
@@ -418,8 +474,9 @@ public function getFillHashTable() {
*
* @return PHPExcel_HashTable
*/
- public function getFontHashTable() {
- return $this->_fontHashTable;
+ public function getFontHashTable()
+ {
+ return $this->fontHashTable;
}
/**
@@ -427,8 +484,9 @@ public function getFontHashTable() {
*
* @return PHPExcel_HashTable
*/
- public function getBordersHashTable() {
- return $this->_bordersHashTable;
+ public function getBordersHashTable()
+ {
+ return $this->bordersHashTable;
}
/**
@@ -436,8 +494,9 @@ public function getBordersHashTable() {
*
* @return PHPExcel_HashTable
*/
- public function getNumFmtHashTable() {
- return $this->_numFmtHashTable;
+ public function getNumFmtHashTable()
+ {
+ return $this->numFmtHashTable;
}
/**
@@ -445,8 +504,9 @@ public function getNumFmtHashTable() {
*
* @return PHPExcel_HashTable
*/
- public function getDrawingHashTable() {
- return $this->_drawingHashTable;
+ public function getDrawingHashTable()
+ {
+ return $this->drawingHashTable;
}
/**
@@ -454,19 +514,20 @@ public function getDrawingHashTable() {
*
* @return boolean
*/
- public function getOffice2003Compatibility() {
- return $this->_office2003compatibility;
+ public function getOffice2003Compatibility()
+ {
+ return $this->office2003compatibility;
}
/**
* Set Office2003 compatibility
*
- * @param boolean $pValue Office2003 compatibility?
+ * @param boolean $pValue Office2003 compatibility?
* @return PHPExcel_Writer_Excel2007
*/
- public function setOffice2003Compatibility($pValue = false) {
- $this->_office2003compatibility = $pValue;
- return $this;
+ public function setOffice2003Compatibility($pValue = false)
+ {
+ $this->office2003compatibility = $pValue;
+ return $this;
}
-
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Chart.php b/Classes/PHPExcel/Writer/Excel2007/Chart.php
index 9ef40f5d6..92fa21506 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Chart.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Chart.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
- // Ensure that data series values are up-to-date before we save
- $pChart->refresh();
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // c:chartSpace
- $objWriter->startElement('c:chartSpace');
- $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
- $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
-
- $objWriter->startElement('c:date1904');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- $objWriter->startElement('c:lang');
- $objWriter->writeAttribute('val', "en-GB");
- $objWriter->endElement();
- $objWriter->startElement('c:roundedCorners');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $this->_writeAlternateContent($objWriter);
-
- $objWriter->startElement('c:chart');
-
- $this->_writeTitle($pChart->getTitle(), $objWriter);
-
- $objWriter->startElement('c:autoTitleDeleted');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $this->_writePlotArea($pChart->getPlotArea(),
- $pChart->getXAxisLabel(),
- $pChart->getYAxisLabel(),
- $objWriter,
- $pChart->getWorksheet()
- );
-
- $this->_writeLegend($pChart->getLegend(), $objWriter);
-
-
- $objWriter->startElement('c:plotVisOnly');
- $objWriter->writeAttribute('val', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:dispBlanksAs');
- $objWriter->writeAttribute('val', "gap");
- $objWriter->endElement();
-
- $objWriter->startElement('c:showDLblsOverMax');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $this->_writePrintSettings($objWriter);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write Chart Title
- *
- * @param PHPExcel_Chart_Title $title
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeTitle(PHPExcel_Chart_Title $title = null, $objWriter)
- {
- if (is_null($title)) {
- return;
- }
-
- $objWriter->startElement('c:title');
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:rich');
-
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
-
- $caption = $title->getCaption();
- if ((is_array($caption)) && (count($caption) > 0))
- $caption = $caption[0];
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a');
-
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- $layout = $title->getLayout();
- $this->_writeLayout($layout, $objWriter);
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Chart Legend
- *
- * @param PHPExcel_Chart_Legend $legend
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeLegend(PHPExcel_Chart_Legend $legend = null, $objWriter)
- {
- if (is_null($legend)) {
- return;
- }
-
- $objWriter->startElement('c:legend');
-
- $objWriter->startElement('c:legendPos');
- $objWriter->writeAttribute('val', $legend->getPosition());
- $objWriter->endElement();
-
- $layout = $legend->getLayout();
- $this->_writeLayout($layout, $objWriter);
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0');
- $objWriter->endElement();
-
- $objWriter->startElement('c:txPr');
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
- $objWriter->startElement('a:pPr');
- $objWriter->writeAttribute('rtl', 0);
-
- $objWriter->startElement('a:defRPr');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('a:endParaRPr');
- $objWriter->writeAttribute('lang', "en-US");
- $objWriter->endElement();
-
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Chart Plot Area
- *
- * @param PHPExcel_Chart_PlotArea $plotArea
- * @param PHPExcel_Chart_Title $xAxisLabel
- * @param PHPExcel_Chart_Title $yAxisLabel
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePlotArea(PHPExcel_Chart_PlotArea $plotArea,
- PHPExcel_Chart_Title $xAxisLabel = NULL,
- PHPExcel_Chart_Title $yAxisLabel = NULL,
- $objWriter,
- PHPExcel_Worksheet $pSheet)
- {
- if (is_null($plotArea)) {
- return;
- }
-
- $id1 = $id2 = 0;
- $this->_seriesIndex = 0;
- $objWriter->startElement('c:plotArea');
-
- $layout = $plotArea->getLayout();
-
- $this->_writeLayout($layout, $objWriter);
-
- $chartTypes = self::_getChartType($plotArea);
- $catIsMultiLevelSeries = $valIsMultiLevelSeries = FALSE;
- $plotGroupingType = '';
- foreach($chartTypes as $chartType) {
- $objWriter->startElement('c:'.$chartType);
-
- $groupCount = $plotArea->getPlotGroupCount();
- for($i = 0; $i < $groupCount; ++$i) {
- $plotGroup = $plotArea->getPlotGroupByIndex($i);
- $groupType = $plotGroup->getPlotType();
- if ($groupType == $chartType) {
-
- $plotStyle = $plotGroup->getPlotStyle();
- if ($groupType === PHPExcel_Chart_DataSeries::TYPE_RADARCHART) {
- $objWriter->startElement('c:radarStyle');
- $objWriter->writeAttribute('val', $plotStyle );
- $objWriter->endElement();
- } elseif ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART) {
- $objWriter->startElement('c:scatterStyle');
- $objWriter->writeAttribute('val', $plotStyle );
- $objWriter->endElement();
- }
-
- $this->_writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet);
- }
- }
-
- $this->_writeDataLbls($objWriter, $layout);
-
- if ($chartType === PHPExcel_Chart_DataSeries::TYPE_LINECHART) {
- // Line only, Line3D can't be smoothed
-
- $objWriter->startElement('c:smooth');
- $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine() );
- $objWriter->endElement();
- } elseif (($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) ||
- ($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) {
-
- $objWriter->startElement('c:gapWidth');
- $objWriter->writeAttribute('val', 150 );
- $objWriter->endElement();
-
- if ($plotGroupingType == 'percentStacked' ||
- $plotGroupingType == 'stacked') {
-
- $objWriter->startElement('c:overlap');
- $objWriter->writeAttribute('val', 100 );
- $objWriter->endElement();
- }
- } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
-
- $objWriter->startElement('c:bubbleScale');
- $objWriter->writeAttribute('val', 25 );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showNegBubbles');
- $objWriter->writeAttribute('val', 0 );
- $objWriter->endElement();
- } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) {
-
- $objWriter->startElement('c:hiLowLines');
- $objWriter->endElement();
- }
-
- // Generate 2 unique numbers to use for axId values
-// $id1 = $id2 = rand(10000000,99999999);
-// do {
-// $id2 = rand(10000000,99999999);
-// } while ($id1 == $id2);
- $id1 = '75091328';
- $id2 = '75089408';
-
- if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) &&
- ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) &&
- ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
-
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id1 );
- $objWriter->endElement();
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id2 );
- $objWriter->endElement();
- } else {
- $objWriter->startElement('c:firstSliceAng');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- if ($chartType === PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) {
-
- $objWriter->startElement('c:holeSize');
- $objWriter->writeAttribute('val', 50);
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- }
-
- if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) &&
- ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) &&
- ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
-
- if ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
- $this->_writeValAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries);
- } else {
- $this->_writeCatAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries);
- }
-
- $this->_writeValAx($objWriter,$plotArea,$yAxisLabel,$chartType,$id1,$id2,$valIsMultiLevelSeries);
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Data Labels
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Chart_Layout $chartLayout Chart layout
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDataLbls($objWriter, $chartLayout)
- {
- $objWriter->startElement('c:dLbls');
-
- $objWriter->startElement('c:showLegendKey');
- $showLegendKey = (empty($chartLayout)) ? 0 : $chartLayout->getShowLegendKey();
- $objWriter->writeAttribute('val', ((empty($showLegendKey)) ? 0 : 1) );
- $objWriter->endElement();
-
-
- $objWriter->startElement('c:showVal');
- $showVal = (empty($chartLayout)) ? 0 : $chartLayout->getShowVal();
- $objWriter->writeAttribute('val', ((empty($showVal)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showCatName');
- $showCatName = (empty($chartLayout)) ? 0 : $chartLayout->getShowCatName();
- $objWriter->writeAttribute('val', ((empty($showCatName)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showSerName');
- $showSerName = (empty($chartLayout)) ? 0 : $chartLayout->getShowSerName();
- $objWriter->writeAttribute('val', ((empty($showSerName)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showPercent');
- $showPercent = (empty($chartLayout)) ? 0 : $chartLayout->getShowPercent();
- $objWriter->writeAttribute('val', ((empty($showPercent)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showBubbleSize');
- $showBubbleSize = (empty($chartLayout)) ? 0 : $chartLayout->getShowBubbleSize();
- $objWriter->writeAttribute('val', ((empty($showBubbleSize)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->startElement('c:showLeaderLines');
- $showLeaderLines = (empty($chartLayout)) ? 1 : $chartLayout->getShowLeaderLines();
- $objWriter->writeAttribute('val', ((empty($showLeaderLines)) ? 0 : 1) );
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Category Axis
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Chart_PlotArea $plotArea
- * @param PHPExcel_Chart_Title $xAxisLabel
- * @param string $groupType Chart type
- * @param string $id1
- * @param string $id2
- * @param boolean $isMultiLevelSeries
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeCatAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)
- {
- $objWriter->startElement('c:catAx');
-
- if ($id1 > 0) {
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id1);
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:scaling');
- $objWriter->startElement('c:orientation');
- $objWriter->writeAttribute('val', "minMax");
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('c:delete');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->startElement('c:axPos');
- $objWriter->writeAttribute('val', "b");
- $objWriter->endElement();
-
- if (!is_null($xAxisLabel)) {
- $objWriter->startElement('c:title');
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:rich');
-
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
- $objWriter->startElement('a:r');
-
- $caption = $xAxisLabel->getCaption();
- if (is_array($caption))
- $caption = $caption[0];
- $objWriter->startElement('a:t');
-// $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $caption ));
- $objWriter->endElement();
-
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- $layout = $xAxisLabel->getLayout();
- $this->_writeLayout($layout, $objWriter);
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- }
-
- $objWriter->startElement('c:numFmt');
- $objWriter->writeAttribute('formatCode', "General");
- $objWriter->writeAttribute('sourceLinked', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:majorTickMark');
- $objWriter->writeAttribute('val', "out");
- $objWriter->endElement();
-
- $objWriter->startElement('c:minorTickMark');
- $objWriter->writeAttribute('val', "none");
- $objWriter->endElement();
-
- $objWriter->startElement('c:tickLblPos');
- $objWriter->writeAttribute('val', "nextTo");
- $objWriter->endElement();
-
- if ($id2 > 0) {
- $objWriter->startElement('c:crossAx');
- $objWriter->writeAttribute('val', $id2);
- $objWriter->endElement();
-
- $objWriter->startElement('c:crosses');
- $objWriter->writeAttribute('val', "autoZero");
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:auto');
- $objWriter->writeAttribute('val', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:lblAlgn');
- $objWriter->writeAttribute('val', "ctr");
- $objWriter->endElement();
-
- $objWriter->startElement('c:lblOffset');
- $objWriter->writeAttribute('val', 100);
- $objWriter->endElement();
-
- if ($isMultiLevelSeries) {
- $objWriter->startElement('c:noMultiLvlLbl');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
- $objWriter->endElement();
-
- }
-
-
- /**
- * Write Value Axis
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Chart_PlotArea $plotArea
- * @param PHPExcel_Chart_Title $yAxisLabel
- * @param string $groupType Chart type
- * @param string $id1
- * @param string $id2
- * @param boolean $isMultiLevelSeries
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeValAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)
- {
- $objWriter->startElement('c:valAx');
-
- if ($id2 > 0) {
- $objWriter->startElement('c:axId');
- $objWriter->writeAttribute('val', $id2);
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:scaling');
- $objWriter->startElement('c:orientation');
- $objWriter->writeAttribute('val', "minMax");
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('c:delete');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->startElement('c:axPos');
- $objWriter->writeAttribute('val', "l");
- $objWriter->endElement();
-
- $objWriter->startElement('c:majorGridlines');
- $objWriter->endElement();
-
- if (!is_null($yAxisLabel)) {
- $objWriter->startElement('c:title');
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:rich');
-
- $objWriter->startElement('a:bodyPr');
- $objWriter->endElement();
-
- $objWriter->startElement('a:lstStyle');
- $objWriter->endElement();
-
- $objWriter->startElement('a:p');
- $objWriter->startElement('a:r');
-
- $caption = $yAxisLabel->getCaption();
- if (is_array($caption))
- $caption = $caption[0];
- $objWriter->startElement('a:t');
-// $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $caption ));
- $objWriter->endElement();
-
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
- $layout = $yAxisLabel->getLayout();
- $this->_writeLayout($layout, $objWriter);
- }
-
- $objWriter->startElement('c:overlay');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- $objWriter->startElement('c:numFmt');
- $objWriter->writeAttribute('formatCode', "General");
- $objWriter->writeAttribute('sourceLinked', 1);
- $objWriter->endElement();
-
- $objWriter->startElement('c:majorTickMark');
- $objWriter->writeAttribute('val', "out");
- $objWriter->endElement();
-
- $objWriter->startElement('c:minorTickMark');
- $objWriter->writeAttribute('val', "none");
- $objWriter->endElement();
-
- $objWriter->startElement('c:tickLblPos');
- $objWriter->writeAttribute('val', "nextTo");
- $objWriter->endElement();
-
- if ($id1 > 0) {
- $objWriter->startElement('c:crossAx');
- $objWriter->writeAttribute('val', $id2);
- $objWriter->endElement();
-
- $objWriter->startElement('c:crosses');
- $objWriter->writeAttribute('val', "autoZero");
- $objWriter->endElement();
-
- $objWriter->startElement('c:crossBetween');
- $objWriter->writeAttribute('val', "midCat");
- $objWriter->endElement();
- }
-
- if ($isMultiLevelSeries) {
- if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
- $objWriter->startElement('c:noMultiLvlLbl');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
- }
- $objWriter->endElement();
-
- }
-
-
- /**
- * Get the data series type(s) for a chart plot series
- *
- * @param PHPExcel_Chart_PlotArea $plotArea
- * @return string|array
- * @throws PHPExcel_Writer_Exception
- */
- private static function _getChartType($plotArea)
- {
- $groupCount = $plotArea->getPlotGroupCount();
-
- if ($groupCount == 1) {
- $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType());
- } else {
- $chartTypes = array();
- for($i = 0; $i < $groupCount; ++$i) {
- $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType();
- }
- $chartType = array_unique($chartTypes);
- if (count($chartTypes) == 0) {
- throw new PHPExcel_Writer_Exception('Chart is not yet implemented');
- }
- }
-
- return $chartType;
- }
-
- /**
- * Write Plot Group (series of related plots)
- *
- * @param PHPExcel_Chart_DataSeries $plotGroup
- * @param string $groupType Type of plot for dataseries
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param boolean &$catIsMultiLevelSeries Is category a multi-series category
- * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set
- * @param string &$plotGroupingType Type of grouping for multi-series values
- * @param PHPExcel_Worksheet $pSheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePlotGroup( $plotGroup,
- $groupType,
- $objWriter,
- &$catIsMultiLevelSeries,
- &$valIsMultiLevelSeries,
- &$plotGroupingType,
- PHPExcel_Worksheet $pSheet
- )
- {
- if (is_null($plotGroup)) {
- return;
- }
-
- if (($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) {
- $objWriter->startElement('c:barDir');
- $objWriter->writeAttribute('val', $plotGroup->getPlotDirection());
- $objWriter->endElement();
- }
-
- if (!is_null($plotGroup->getPlotGrouping())) {
- $plotGroupingType = $plotGroup->getPlotGrouping();
- $objWriter->startElement('c:grouping');
- $objWriter->writeAttribute('val', $plotGroupingType);
- $objWriter->endElement();
- }
-
- // Get these details before the loop, because we can use the count to check for varyColors
- $plotSeriesOrder = $plotGroup->getPlotOrder();
- $plotSeriesCount = count($plotSeriesOrder);
-
- if (($groupType !== PHPExcel_Chart_DataSeries::TYPE_RADARCHART) &&
- ($groupType !== PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) {
-
- if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_LINECHART) {
- if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) ||
- ($plotSeriesCount > 1)) {
- $objWriter->startElement('c:varyColors');
- $objWriter->writeAttribute('val', 1);
- $objWriter->endElement();
- } else {
- $objWriter->startElement('c:varyColors');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
- }
- }
-
- foreach($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {
- $objWriter->startElement('c:ser');
-
- $objWriter->startElement('c:idx');
- $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesIdx);
- $objWriter->endElement();
-
- $objWriter->startElement('c:order');
- $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesRef);
- $objWriter->endElement();
-
- if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
-
- $objWriter->startElement('c:dPt');
- $objWriter->startElement('c:idx');
- $objWriter->writeAttribute('val', 3);
- $objWriter->endElement();
-
- $objWriter->startElement('c:bubble3D');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
-
- $objWriter->startElement('c:spPr');
- $objWriter->startElement('a:solidFill');
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', 'FF9900');
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- }
-
- // Labels
- $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef);
- if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) {
- $objWriter->startElement('c:tx');
- $objWriter->startElement('c:strRef');
- $this->_writePlotSeriesLabel($plotSeriesLabel, $objWriter);
- $objWriter->endElement();
- $objWriter->endElement();
- }
-
- // Formatting for the points
- if ($groupType == PHPExcel_Chart_DataSeries::TYPE_LINECHART) {
- $objWriter->startElement('c:spPr');
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', 12700);
- $objWriter->endElement();
- $objWriter->endElement();
- }
-
- $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef);
- if ($plotSeriesValues) {
- $plotSeriesMarker = $plotSeriesValues->getPointMarker();
- if ($plotSeriesMarker) {
- $objWriter->startElement('c:marker');
- $objWriter->startElement('c:symbol');
- $objWriter->writeAttribute('val', $plotSeriesMarker);
- $objWriter->endElement();
-
- if ($plotSeriesMarker !== 'none') {
- $objWriter->startElement('c:size');
- $objWriter->writeAttribute('val', 3);
- $objWriter->endElement();
- }
- $objWriter->endElement();
- }
- }
-
- if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) ||
- ($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D) ||
- ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART)) {
-
- $objWriter->startElement('c:invertIfNegative');
- $objWriter->writeAttribute('val', 0);
- $objWriter->endElement();
- }
-
- // Category Labels
- $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesRef);
- if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) {
- $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries();
-
- if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) ||
- ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
-
- if (!is_null($plotGroup->getPlotStyle())) {
- $plotStyle = $plotGroup->getPlotStyle();
- if ($plotStyle) {
- $objWriter->startElement('c:explosion');
- $objWriter->writeAttribute('val', 25);
- $objWriter->endElement();
- }
- }
- }
-
- if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) ||
- ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) {
- $objWriter->startElement('c:xVal');
- } else {
- $objWriter->startElement('c:cat');
- }
-
- $this->_writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str', $pSheet);
- $objWriter->endElement();
- }
-
- // Values
- if ($plotSeriesValues) {
- $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries();
-
- if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) ||
- ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) {
- $objWriter->startElement('c:yVal');
- } else {
- $objWriter->startElement('c:val');
- }
-
- $this->_writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num', $pSheet);
- $objWriter->endElement();
- }
-
- if ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
- $this->_writeBubbles($plotSeriesValues, $objWriter, $pSheet);
- }
-
- $objWriter->endElement();
-
- }
-
- $this->_seriesIndex += $plotSeriesIdx + 1;
- }
-
- /**
- * Write Plot Series Label
- *
- * @param PHPExcel_Chart_DataSeriesValues $plotSeriesLabel
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePlotSeriesLabel($plotSeriesLabel, $objWriter)
- {
- if (is_null($plotSeriesLabel)) {
- return;
- }
-
- $objWriter->startElement('c:f');
- $objWriter->writeRawData($plotSeriesLabel->getDataSource());
- $objWriter->endElement();
-
- $objWriter->startElement('c:strCache');
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesLabel->getPointCount() );
- $objWriter->endElement();
-
- foreach($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotLabelKey );
-
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( $plotLabelValue );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- $objWriter->endElement();
-
- }
-
- /**
- * Write Plot Series Values
- *
- * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $groupType Type of plot for dataseries
- * @param string $dataType Datatype of series values
- * @param PHPExcel_Worksheet $pSheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePlotSeriesValues( $plotSeriesValues,
- $objWriter,
- $groupType,
- $dataType='str',
- PHPExcel_Worksheet $pSheet
- )
- {
- if (is_null($plotSeriesValues)) {
- return;
- }
-
- if ($plotSeriesValues->isMultiLevelSeries()) {
- $levelCount = $plotSeriesValues->multiLevelCount();
-
- $objWriter->startElement('c:multiLvlStrRef');
-
- $objWriter->startElement('c:f');
- $objWriter->writeRawData( $plotSeriesValues->getDataSource() );
- $objWriter->endElement();
-
- $objWriter->startElement('c:multiLvlStrCache');
-
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
- $objWriter->endElement();
-
- for ($level = 0; $level < $levelCount; ++$level) {
- $objWriter->startElement('c:lvl');
-
- foreach($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) {
- if (isset($plotSeriesValue[$level])) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotSeriesKey );
-
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( $plotSeriesValue[$level] );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- } else {
- $objWriter->startElement('c:'.$dataType.'Ref');
-
- $objWriter->startElement('c:f');
- $objWriter->writeRawData( $plotSeriesValues->getDataSource() );
- $objWriter->endElement();
-
- $objWriter->startElement('c:'.$dataType.'Cache');
-
- if (($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART) &&
- ($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) &&
- ($groupType != PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
-
- if (($plotSeriesValues->getFormatCode() !== NULL) &&
- ($plotSeriesValues->getFormatCode() !== '')) {
- $objWriter->startElement('c:formatCode');
- $objWriter->writeRawData( $plotSeriesValues->getFormatCode() );
- $objWriter->endElement();
- }
- }
-
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
- $objWriter->endElement();
-
- $dataValues = $plotSeriesValues->getDataValues();
- if (!empty($dataValues)) {
- if (is_array($dataValues)) {
- foreach($dataValues as $plotSeriesKey => $plotSeriesValue) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotSeriesKey );
-
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( $plotSeriesValue );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Bubble Chart Details
- *
- * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeBubbles($plotSeriesValues, $objWriter, PHPExcel_Worksheet $pSheet)
- {
- if (is_null($plotSeriesValues)) {
- return;
- }
-
- $objWriter->startElement('c:bubbleSize');
- $objWriter->startElement('c:numLit');
-
- $objWriter->startElement('c:formatCode');
- $objWriter->writeRawData( 'General' );
- $objWriter->endElement();
-
- $objWriter->startElement('c:ptCount');
- $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() );
- $objWriter->endElement();
-
- $dataValues = $plotSeriesValues->getDataValues();
- if (!empty($dataValues)) {
- if (is_array($dataValues)) {
- foreach($dataValues as $plotSeriesKey => $plotSeriesValue) {
- $objWriter->startElement('c:pt');
- $objWriter->writeAttribute('idx', $plotSeriesKey );
- $objWriter->startElement('c:v');
- $objWriter->writeRawData( 1 );
- $objWriter->endElement();
- $objWriter->endElement();
- }
- }
- }
-
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('c:bubble3D');
- $objWriter->writeAttribute('val', 0 );
- $objWriter->endElement();
- }
-
- /**
- * Write Layout
- *
- * @param PHPExcel_Chart_Layout $layout
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeLayout(PHPExcel_Chart_Layout $layout = NULL, $objWriter)
- {
- $objWriter->startElement('c:layout');
-
- if (!is_null($layout)) {
- $objWriter->startElement('c:manualLayout');
-
- $layoutTarget = $layout->getLayoutTarget();
- if (!is_null($layoutTarget)) {
- $objWriter->startElement('c:layoutTarget');
- $objWriter->writeAttribute('val', $layoutTarget);
- $objWriter->endElement();
- }
-
- $xMode = $layout->getXMode();
- if (!is_null($xMode)) {
- $objWriter->startElement('c:xMode');
- $objWriter->writeAttribute('val', $xMode);
- $objWriter->endElement();
- }
-
- $yMode = $layout->getYMode();
- if (!is_null($yMode)) {
- $objWriter->startElement('c:yMode');
- $objWriter->writeAttribute('val', $yMode);
- $objWriter->endElement();
- }
-
- $x = $layout->getXPosition();
- if (!is_null($x)) {
- $objWriter->startElement('c:x');
- $objWriter->writeAttribute('val', $x);
- $objWriter->endElement();
- }
-
- $y = $layout->getYPosition();
- if (!is_null($y)) {
- $objWriter->startElement('c:y');
- $objWriter->writeAttribute('val', $y);
- $objWriter->endElement();
- }
-
- $w = $layout->getWidth();
- if (!is_null($w)) {
- $objWriter->startElement('c:w');
- $objWriter->writeAttribute('val', $w);
- $objWriter->endElement();
- }
-
- $h = $layout->getHeight();
- if (!is_null($h)) {
- $objWriter->startElement('c:h');
- $objWriter->writeAttribute('val', $h);
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Alternate Content block
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeAlternateContent($objWriter)
- {
- $objWriter->startElement('mc:AlternateContent');
- $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
-
- $objWriter->startElement('mc:Choice');
- $objWriter->writeAttribute('xmlns:c14', 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart');
- $objWriter->writeAttribute('Requires', 'c14');
-
- $objWriter->startElement('c14:style');
- $objWriter->writeAttribute('val', '102');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('mc:Fallback');
- $objWriter->startElement('c:style');
- $objWriter->writeAttribute('val', '2');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Printer Settings
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePrintSettings($objWriter)
- {
- $objWriter->startElement('c:printSettings');
-
- $objWriter->startElement('c:headerFooter');
- $objWriter->endElement();
-
- $objWriter->startElement('c:pageMargins');
- $objWriter->writeAttribute('footer', 0.3);
- $objWriter->writeAttribute('header', 0.3);
- $objWriter->writeAttribute('r', 0.7);
- $objWriter->writeAttribute('l', 0.7);
- $objWriter->writeAttribute('t', 0.75);
- $objWriter->writeAttribute('b', 0.75);
- $objWriter->endElement();
-
- $objWriter->startElement('c:pageSetup');
- $objWriter->writeAttribute('orientation', "portrait");
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
+ protected $calculateCellValues;
+
+ /**
+ * Write charts to XML format
+ *
+ * @param PHPExcel_Chart $pChart
+ *
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeChart(PHPExcel_Chart $pChart = null, $calculateCellValues = true)
+ {
+ $this->calculateCellValues = $calculateCellValues;
+
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+ // Ensure that data series values are up-to-date before we save
+ if ($this->calculateCellValues) {
+ $pChart->refresh();
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // c:chartSpace
+ $objWriter->startElement('c:chartSpace');
+ $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
+ $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+
+ $objWriter->startElement('c:date1904');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ $objWriter->startElement('c:lang');
+ $objWriter->writeAttribute('val', "en-GB");
+ $objWriter->endElement();
+ $objWriter->startElement('c:roundedCorners');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $this->writeAlternateContent($objWriter);
+
+ $objWriter->startElement('c:chart');
+
+ $this->writeTitle($pChart->getTitle(), $objWriter);
+
+ $objWriter->startElement('c:autoTitleDeleted');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $this->writePlotArea($pChart->getPlotArea(), $pChart->getXAxisLabel(), $pChart->getYAxisLabel(), $objWriter, $pChart->getWorksheet(), $pChart->getChartAxisX(), $pChart->getChartAxisY(), $pChart->getMajorGridlines(), $pChart->getMinorGridlines());
+
+ $this->writeLegend($pChart->getLegend(), $objWriter);
+
+ $objWriter->startElement('c:plotVisOnly');
+ $objWriter->writeAttribute('val', 1);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:dispBlanksAs');
+ $objWriter->writeAttribute('val', "gap");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showDLblsOverMax');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $this->writePrintSettings($objWriter);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write Chart Title
+ *
+ * @param PHPExcel_Chart_Title $title
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeTitle(PHPExcel_Chart_Title $title = null, $objWriter)
+ {
+ if (is_null($title)) {
+ return;
+ }
+
+ $objWriter->startElement('c:title');
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:rich');
+
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+
+ $caption = $title->getCaption();
+ if ((is_array($caption)) && (count($caption) > 0)) {
+ $caption = $caption[0];
+ }
+ $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a');
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $this->writeLayout($title->getLayout(), $objWriter);
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Chart Legend
+ *
+ * @param PHPExcel_Chart_Legend $legend
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeLegend(PHPExcel_Chart_Legend $legend = null, $objWriter)
+ {
+ if (is_null($legend)) {
+ return;
+ }
+
+ $objWriter->startElement('c:legend');
+
+ $objWriter->startElement('c:legendPos');
+ $objWriter->writeAttribute('val', $legend->getPosition());
+ $objWriter->endElement();
+
+ $this->writeLayout($legend->getLayout(), $objWriter);
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:txPr');
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+ $objWriter->startElement('a:pPr');
+ $objWriter->writeAttribute('rtl', 0);
+
+ $objWriter->startElement('a:defRPr');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:endParaRPr');
+ $objWriter->writeAttribute('lang', "en-US");
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Chart Plot Area
+ *
+ * @param PHPExcel_Chart_PlotArea $plotArea
+ * @param PHPExcel_Chart_Title $xAxisLabel
+ * @param PHPExcel_Chart_Title $yAxisLabel
+ * @param PHPExcel_Chart_Axis $xAxis
+ * @param PHPExcel_Chart_Axis $yAxis
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePlotArea(PHPExcel_Chart_PlotArea $plotArea, PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, $objWriter, PHPExcel_Worksheet $pSheet, PHPExcel_Chart_Axis $xAxis, PHPExcel_Chart_Axis $yAxis, PHPExcel_Chart_GridLines $majorGridlines, PHPExcel_Chart_GridLines $minorGridlines)
+ {
+ if (is_null($plotArea)) {
+ return;
+ }
+
+ $id1 = $id2 = 0;
+ $this->_seriesIndex = 0;
+ $objWriter->startElement('c:plotArea');
+
+ $layout = $plotArea->getLayout();
+
+ $this->writeLayout($layout, $objWriter);
+
+ $chartTypes = self::getChartType($plotArea);
+ $catIsMultiLevelSeries = $valIsMultiLevelSeries = false;
+ $plotGroupingType = '';
+ foreach ($chartTypes as $chartType) {
+ $objWriter->startElement('c:' . $chartType);
+
+ $groupCount = $plotArea->getPlotGroupCount();
+ for ($i = 0; $i < $groupCount; ++$i) {
+ $plotGroup = $plotArea->getPlotGroupByIndex($i);
+ $groupType = $plotGroup->getPlotType();
+ if ($groupType == $chartType) {
+ $plotStyle = $plotGroup->getPlotStyle();
+ if ($groupType === PHPExcel_Chart_DataSeries::TYPE_RADARCHART) {
+ $objWriter->startElement('c:radarStyle');
+ $objWriter->writeAttribute('val', $plotStyle);
+ $objWriter->endElement();
+ } elseif ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART) {
+ $objWriter->startElement('c:scatterStyle');
+ $objWriter->writeAttribute('val', $plotStyle);
+ $objWriter->endElement();
+ }
+
+ $this->writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet);
+ }
+ }
+
+ $this->writeDataLabels($objWriter, $layout);
+
+ if ($chartType === PHPExcel_Chart_DataSeries::TYPE_LINECHART) {
+ // Line only, Line3D can't be smoothed
+
+ $objWriter->startElement('c:smooth');
+ $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine());
+ $objWriter->endElement();
+ } elseif (($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) ||($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) {
+ $objWriter->startElement('c:gapWidth');
+ $objWriter->writeAttribute('val', 150);
+ $objWriter->endElement();
+
+ if ($plotGroupingType == 'percentStacked' || $plotGroupingType == 'stacked') {
+ $objWriter->startElement('c:overlap');
+ $objWriter->writeAttribute('val', 100);
+ $objWriter->endElement();
+ }
+ } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
+ $objWriter->startElement('c:bubbleScale');
+ $objWriter->writeAttribute('val', 25);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showNegBubbles');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) {
+ $objWriter->startElement('c:hiLowLines');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:upDownBars');
+
+ $objWriter->startElement('c:gapWidth');
+ $objWriter->writeAttribute('val', 300);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:upBars');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:downBars');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ // Generate 2 unique numbers to use for axId values
+ // $id1 = $id2 = rand(10000000,99999999);
+ // do {
+ // $id2 = rand(10000000,99999999);
+ // } while ($id1 == $id2);
+ $id1 = '75091328';
+ $id2 = '75089408';
+
+ if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id1);
+ $objWriter->endElement();
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:firstSliceAng');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ if ($chartType === PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) {
+ $objWriter->startElement('c:holeSize');
+ $objWriter->writeAttribute('val', 50);
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
+ if ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
+ $this->writeValueAxis($objWriter, $plotArea, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines);
+ } else {
+ $this->writeCategoryAxis($objWriter, $plotArea, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $yAxis);
+ }
+
+ $this->writeValueAxis($objWriter, $plotArea, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines);
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Data Labels
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Chart_Layout $chartLayout Chart layout
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDataLabels($objWriter, $chartLayout)
+ {
+ $objWriter->startElement('c:dLbls');
+
+ $objWriter->startElement('c:showLegendKey');
+ $showLegendKey = (empty($chartLayout)) ? 0 : $chartLayout->getShowLegendKey();
+ $objWriter->writeAttribute('val', ((empty($showLegendKey)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showVal');
+ $showVal = (empty($chartLayout)) ? 0 : $chartLayout->getShowVal();
+ $objWriter->writeAttribute('val', ((empty($showVal)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showCatName');
+ $showCatName = (empty($chartLayout)) ? 0 : $chartLayout->getShowCatName();
+ $objWriter->writeAttribute('val', ((empty($showCatName)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showSerName');
+ $showSerName = (empty($chartLayout)) ? 0 : $chartLayout->getShowSerName();
+ $objWriter->writeAttribute('val', ((empty($showSerName)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showPercent');
+ $showPercent = (empty($chartLayout)) ? 0 : $chartLayout->getShowPercent();
+ $objWriter->writeAttribute('val', ((empty($showPercent)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showBubbleSize');
+ $showBubbleSize = (empty($chartLayout)) ? 0 : $chartLayout->getShowBubbleSize();
+ $objWriter->writeAttribute('val', ((empty($showBubbleSize)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:showLeaderLines');
+ $showLeaderLines = (empty($chartLayout)) ? 1 : $chartLayout->getShowLeaderLines();
+ $objWriter->writeAttribute('val', ((empty($showLeaderLines)) ? 0 : 1));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Category Axis
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Chart_PlotArea $plotArea
+ * @param PHPExcel_Chart_Title $xAxisLabel
+ * @param string $groupType Chart type
+ * @param string $id1
+ * @param string $id2
+ * @param boolean $isMultiLevelSeries
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCategoryAxis($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis)
+ {
+ $objWriter->startElement('c:catAx');
+
+ if ($id1 > 0) {
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id1);
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:scaling');
+ $objWriter->startElement('c:orientation');
+ $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('orientation'));
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:delete');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:axPos');
+ $objWriter->writeAttribute('val', "b");
+ $objWriter->endElement();
+
+ if (!is_null($xAxisLabel)) {
+ $objWriter->startElement('c:title');
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:rich');
+
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+ $objWriter->startElement('a:r');
+
+ $caption = $xAxisLabel->getCaption();
+ if (is_array($caption)) {
+ $caption = $caption[0];
+ }
+ $objWriter->startElement('a:t');
+ // $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($caption));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $layout = $xAxisLabel->getLayout();
+ $this->writeLayout($layout, $objWriter);
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:numFmt');
+ $objWriter->writeAttribute('formatCode', $yAxis->getAxisNumberFormat());
+ $objWriter->writeAttribute('sourceLinked', $yAxis->getAxisNumberSourceLinked());
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:majorTickMark');
+ $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_tick_mark'));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:minorTickMark');
+ $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_tick_mark'));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:tickLblPos');
+ $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('axis_labels'));
+ $objWriter->endElement();
+
+ if ($id2 > 0) {
+ $objWriter->startElement('c:crossAx');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:crosses');
+ $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('horizontal_crosses'));
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:auto');
+ $objWriter->writeAttribute('val', 1);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:lblAlgn');
+ $objWriter->writeAttribute('val', "ctr");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:lblOffset');
+ $objWriter->writeAttribute('val', 100);
+ $objWriter->endElement();
+
+ if ($isMultiLevelSeries) {
+ $objWriter->startElement('c:noMultiLvlLbl');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Value Axis
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Chart_PlotArea $plotArea
+ * @param PHPExcel_Chart_Title $yAxisLabel
+ * @param string $groupType Chart type
+ * @param string $id1
+ * @param string $id2
+ * @param boolean $isMultiLevelSeries
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeValueAxis($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines)
+ {
+ $objWriter->startElement('c:valAx');
+
+ if ($id2 > 0) {
+ $objWriter->startElement('c:axId');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:scaling');
+
+ if (!is_null($xAxis->getAxisOptionsProperty('maximum'))) {
+ $objWriter->startElement('c:max');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('maximum'));
+ $objWriter->endElement();
+ }
+
+ if (!is_null($xAxis->getAxisOptionsProperty('minimum'))) {
+ $objWriter->startElement('c:min');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minimum'));
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:orientation');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('orientation'));
+
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:delete');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:axPos');
+ $objWriter->writeAttribute('val', "l");
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:majorGridlines');
+ $objWriter->startElement('c:spPr');
+
+ if (!is_null($majorGridlines->getLineColorProperty('value'))) {
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', $majorGridlines->getLineStyleProperty('width'));
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement("a:{$majorGridlines->getLineColorProperty('type')}");
+ $objWriter->writeAttribute('val', $majorGridlines->getLineColorProperty('value'));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $majorGridlines->getLineColorProperty('alpha'));
+ $objWriter->endElement(); //end alpha
+ $objWriter->endElement(); //end srgbClr
+ $objWriter->endElement(); //end solidFill
+
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', $majorGridlines->getLineStyleProperty('dash'));
+ $objWriter->endElement();
+
+ if ($majorGridlines->getLineStyleProperty('join') == 'miter') {
+ $objWriter->startElement('a:miter');
+ $objWriter->writeAttribute('lim', '800000');
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('a:bevel');
+ $objWriter->endElement();
+ }
+
+ if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) {
+ $objWriter->startElement('a:headEnd');
+ $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')));
+ $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('head', 'w'));
+ $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('head', 'len'));
+ $objWriter->endElement();
+ }
+
+ if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) {
+ $objWriter->startElement('a:tailEnd');
+ $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')));
+ $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('end', 'w'));
+ $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('end', 'len'));
+ $objWriter->endElement();
+ }
+ $objWriter->endElement(); //end ln
+ }
+ $objWriter->startElement('a:effectLst');
+
+ if (!is_null($majorGridlines->getGlowSize())) {
+ $objWriter->startElement('a:glow');
+ $objWriter->writeAttribute('rad', $majorGridlines->getGlowSize());
+ $objWriter->startElement("a:{$majorGridlines->getGlowColor('type')}");
+ $objWriter->writeAttribute('val', $majorGridlines->getGlowColor('value'));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $majorGridlines->getGlowColor('alpha'));
+ $objWriter->endElement(); //end alpha
+ $objWriter->endElement(); //end schemeClr
+ $objWriter->endElement(); //end glow
+ }
+
+ if (!is_null($majorGridlines->getShadowProperty('presets'))) {
+ $objWriter->startElement("a:{$majorGridlines->getShadowProperty('effect')}");
+ if (!is_null($majorGridlines->getShadowProperty('blur'))) {
+ $objWriter->writeAttribute('blurRad', $majorGridlines->getShadowProperty('blur'));
+ }
+ if (!is_null($majorGridlines->getShadowProperty('distance'))) {
+ $objWriter->writeAttribute('dist', $majorGridlines->getShadowProperty('distance'));
+ }
+ if (!is_null($majorGridlines->getShadowProperty('direction'))) {
+ $objWriter->writeAttribute('dir', $majorGridlines->getShadowProperty('direction'));
+ }
+ if (!is_null($majorGridlines->getShadowProperty('algn'))) {
+ $objWriter->writeAttribute('algn', $majorGridlines->getShadowProperty('algn'));
+ }
+ if (!is_null($majorGridlines->getShadowProperty(array('size', 'sx')))) {
+ $objWriter->writeAttribute('sx', $majorGridlines->getShadowProperty(array('size', 'sx')));
+ }
+ if (!is_null($majorGridlines->getShadowProperty(array('size', 'sy')))) {
+ $objWriter->writeAttribute('sy', $majorGridlines->getShadowProperty(array('size', 'sy')));
+ }
+ if (!is_null($majorGridlines->getShadowProperty(array('size', 'kx')))) {
+ $objWriter->writeAttribute('kx', $majorGridlines->getShadowProperty(array('size', 'kx')));
+ }
+ if (!is_null($majorGridlines->getShadowProperty('rotWithShape'))) {
+ $objWriter->writeAttribute('rotWithShape', $majorGridlines->getShadowProperty('rotWithShape'));
+ }
+ $objWriter->startElement("a:{$majorGridlines->getShadowProperty(array('color', 'type'))}");
+ $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'value')));
+
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'alpha')));
+ $objWriter->endElement(); //end alpha
+
+ $objWriter->endElement(); //end color:type
+ $objWriter->endElement(); //end shadow
+ }
+
+ if (!is_null($majorGridlines->getSoftEdgesSize())) {
+ $objWriter->startElement('a:softEdge');
+ $objWriter->writeAttribute('rad', $majorGridlines->getSoftEdgesSize());
+ $objWriter->endElement(); //end softEdge
+ }
+
+ $objWriter->endElement(); //end effectLst
+ $objWriter->endElement(); //end spPr
+ $objWriter->endElement(); //end majorGridLines
+
+ if ($minorGridlines->getObjectState()) {
+ $objWriter->startElement('c:minorGridlines');
+ $objWriter->startElement('c:spPr');
+
+ if (!is_null($minorGridlines->getLineColorProperty('value'))) {
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', $minorGridlines->getLineStyleProperty('width'));
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement("a:{$minorGridlines->getLineColorProperty('type')}");
+ $objWriter->writeAttribute('val', $minorGridlines->getLineColorProperty('value'));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $minorGridlines->getLineColorProperty('alpha'));
+ $objWriter->endElement(); //end alpha
+ $objWriter->endElement(); //end srgbClr
+ $objWriter->endElement(); //end solidFill
+
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', $minorGridlines->getLineStyleProperty('dash'));
+ $objWriter->endElement();
+
+ if ($minorGridlines->getLineStyleProperty('join') == 'miter') {
+ $objWriter->startElement('a:miter');
+ $objWriter->writeAttribute('lim', '800000');
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('a:bevel');
+ $objWriter->endElement();
+ }
+
+ if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) {
+ $objWriter->startElement('a:headEnd');
+ $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')));
+ $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('head', 'w'));
+ $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('head', 'len'));
+ $objWriter->endElement();
+ }
+
+ if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) {
+ $objWriter->startElement('a:tailEnd');
+ $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')));
+ $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('end', 'w'));
+ $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('end', 'len'));
+ $objWriter->endElement();
+ }
+ $objWriter->endElement(); //end ln
+ }
+
+ $objWriter->startElement('a:effectLst');
+
+ if (!is_null($minorGridlines->getGlowSize())) {
+ $objWriter->startElement('a:glow');
+ $objWriter->writeAttribute('rad', $minorGridlines->getGlowSize());
+ $objWriter->startElement("a:{$minorGridlines->getGlowColor('type')}");
+ $objWriter->writeAttribute('val', $minorGridlines->getGlowColor('value'));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $minorGridlines->getGlowColor('alpha'));
+ $objWriter->endElement(); //end alpha
+ $objWriter->endElement(); //end schemeClr
+ $objWriter->endElement(); //end glow
+ }
+
+ if (!is_null($minorGridlines->getShadowProperty('presets'))) {
+ $objWriter->startElement("a:{$minorGridlines->getShadowProperty('effect')}");
+ if (!is_null($minorGridlines->getShadowProperty('blur'))) {
+ $objWriter->writeAttribute('blurRad', $minorGridlines->getShadowProperty('blur'));
+ }
+ if (!is_null($minorGridlines->getShadowProperty('distance'))) {
+ $objWriter->writeAttribute('dist', $minorGridlines->getShadowProperty('distance'));
+ }
+ if (!is_null($minorGridlines->getShadowProperty('direction'))) {
+ $objWriter->writeAttribute('dir', $minorGridlines->getShadowProperty('direction'));
+ }
+ if (!is_null($minorGridlines->getShadowProperty('algn'))) {
+ $objWriter->writeAttribute('algn', $minorGridlines->getShadowProperty('algn'));
+ }
+ if (!is_null($minorGridlines->getShadowProperty(array('size', 'sx')))) {
+ $objWriter->writeAttribute('sx', $minorGridlines->getShadowProperty(array('size', 'sx')));
+ }
+ if (!is_null($minorGridlines->getShadowProperty(array('size', 'sy')))) {
+ $objWriter->writeAttribute('sy', $minorGridlines->getShadowProperty(array('size', 'sy')));
+ }
+ if (!is_null($minorGridlines->getShadowProperty(array('size', 'kx')))) {
+ $objWriter->writeAttribute('kx', $minorGridlines->getShadowProperty(array('size', 'kx')));
+ }
+ if (!is_null($minorGridlines->getShadowProperty('rotWithShape'))) {
+ $objWriter->writeAttribute('rotWithShape', $minorGridlines->getShadowProperty('rotWithShape'));
+ }
+ $objWriter->startElement("a:{$minorGridlines->getShadowProperty(array('color', 'type'))}");
+ $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'value')));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'alpha')));
+ $objWriter->endElement(); //end alpha
+ $objWriter->endElement(); //end color:type
+ $objWriter->endElement(); //end shadow
+ }
+
+ if (!is_null($minorGridlines->getSoftEdgesSize())) {
+ $objWriter->startElement('a:softEdge');
+ $objWriter->writeAttribute('rad', $minorGridlines->getSoftEdgesSize());
+ $objWriter->endElement(); //end softEdge
+ }
+
+ $objWriter->endElement(); //end effectLst
+ $objWriter->endElement(); //end spPr
+ $objWriter->endElement(); //end minorGridLines
+ }
+
+ if (!is_null($yAxisLabel)) {
+ $objWriter->startElement('c:title');
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:rich');
+
+ $objWriter->startElement('a:bodyPr');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:lstStyle');
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:p');
+ $objWriter->startElement('a:r');
+
+ $caption = $yAxisLabel->getCaption();
+ if (is_array($caption)) {
+ $caption = $caption[0];
+ }
+
+ $objWriter->startElement('a:t');
+ // $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($caption));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
+ $layout = $yAxisLabel->getLayout();
+ $this->writeLayout($layout, $objWriter);
+ }
+
+ $objWriter->startElement('c:overlay');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:numFmt');
+ $objWriter->writeAttribute('formatCode', $xAxis->getAxisNumberFormat());
+ $objWriter->writeAttribute('sourceLinked', $xAxis->getAxisNumberSourceLinked());
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:majorTickMark');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_tick_mark'));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:minorTickMark');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_tick_mark'));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:tickLblPos');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('axis_labels'));
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:spPr');
+
+ if (!is_null($xAxis->getFillProperty('value'))) {
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement("a:" . $xAxis->getFillProperty('type'));
+ $objWriter->writeAttribute('val', $xAxis->getFillProperty('value'));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $xAxis->getFillProperty('alpha'));
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('a:ln');
+
+ $objWriter->writeAttribute('w', $xAxis->getLineStyleProperty('width'));
+ $objWriter->writeAttribute('cap', $xAxis->getLineStyleProperty('cap'));
+ $objWriter->writeAttribute('cmpd', $xAxis->getLineStyleProperty('compound'));
+
+ if (!is_null($xAxis->getLineProperty('value'))) {
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement("a:" . $xAxis->getLineProperty('type'));
+ $objWriter->writeAttribute('val', $xAxis->getLineProperty('value'));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $xAxis->getLineProperty('alpha'));
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', $xAxis->getLineStyleProperty('dash'));
+ $objWriter->endElement();
+
+ if ($xAxis->getLineStyleProperty('join') == 'miter') {
+ $objWriter->startElement('a:miter');
+ $objWriter->writeAttribute('lim', '800000');
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('a:bevel');
+ $objWriter->endElement();
+ }
+
+ if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'head', 'type')))) {
+ $objWriter->startElement('a:headEnd');
+ $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'head', 'type')));
+ $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('head'));
+ $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('head'));
+ $objWriter->endElement();
+ }
+
+ if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'end', 'type')))) {
+ $objWriter->startElement('a:tailEnd');
+ $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'end', 'type')));
+ $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('end'));
+ $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('end'));
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:effectLst');
+
+ if (!is_null($xAxis->getGlowProperty('size'))) {
+ $objWriter->startElement('a:glow');
+ $objWriter->writeAttribute('rad', $xAxis->getGlowProperty('size'));
+ $objWriter->startElement("a:{$xAxis->getGlowProperty(array('color','type'))}");
+ $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','value')));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','alpha')));
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ if (!is_null($xAxis->getShadowProperty('presets'))) {
+ $objWriter->startElement("a:{$xAxis->getShadowProperty('effect')}");
+
+ if (!is_null($xAxis->getShadowProperty('blur'))) {
+ $objWriter->writeAttribute('blurRad', $xAxis->getShadowProperty('blur'));
+ }
+ if (!is_null($xAxis->getShadowProperty('distance'))) {
+ $objWriter->writeAttribute('dist', $xAxis->getShadowProperty('distance'));
+ }
+ if (!is_null($xAxis->getShadowProperty('direction'))) {
+ $objWriter->writeAttribute('dir', $xAxis->getShadowProperty('direction'));
+ }
+ if (!is_null($xAxis->getShadowProperty('algn'))) {
+ $objWriter->writeAttribute('algn', $xAxis->getShadowProperty('algn'));
+ }
+ if (!is_null($xAxis->getShadowProperty(array('size','sx')))) {
+ $objWriter->writeAttribute('sx', $xAxis->getShadowProperty(array('size','sx')));
+ }
+ if (!is_null($xAxis->getShadowProperty(array('size','sy')))) {
+ $objWriter->writeAttribute('sy', $xAxis->getShadowProperty(array('size','sy')));
+ }
+ if (!is_null($xAxis->getShadowProperty(array('size','kx')))) {
+ $objWriter->writeAttribute('kx', $xAxis->getShadowProperty(array('size','kx')));
+ }
+ if (!is_null($xAxis->getShadowProperty('rotWithShape'))) {
+ $objWriter->writeAttribute('rotWithShape', $xAxis->getShadowProperty('rotWithShape'));
+ }
+
+ $objWriter->startElement("a:{$xAxis->getShadowProperty(array('color','type'))}");
+ $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','value')));
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','alpha')));
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ if (!is_null($xAxis->getSoftEdgesSize())) {
+ $objWriter->startElement('a:softEdge');
+ $objWriter->writeAttribute('rad', $xAxis->getSoftEdgesSize());
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement(); //effectList
+ $objWriter->endElement(); //end spPr
+
+ if ($id1 > 0) {
+ $objWriter->startElement('c:crossAx');
+ $objWriter->writeAttribute('val', $id2);
+ $objWriter->endElement();
+
+ if (!is_null($xAxis->getAxisOptionsProperty('horizontal_crosses_value'))) {
+ $objWriter->startElement('c:crossesAt');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses_value'));
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:crosses');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses'));
+ $objWriter->endElement();
+ }
+
+ $objWriter->startElement('c:crossBetween');
+ $objWriter->writeAttribute('val', "midCat");
+ $objWriter->endElement();
+
+ if (!is_null($xAxis->getAxisOptionsProperty('major_unit'))) {
+ $objWriter->startElement('c:majorUnit');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_unit'));
+ $objWriter->endElement();
+ }
+
+ if (!is_null($xAxis->getAxisOptionsProperty('minor_unit'))) {
+ $objWriter->startElement('c:minorUnit');
+ $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_unit'));
+ $objWriter->endElement();
+ }
+ }
+
+ if ($isMultiLevelSeries) {
+ if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
+ $objWriter->startElement('c:noMultiLvlLbl');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Get the data series type(s) for a chart plot series
+ *
+ * @param PHPExcel_Chart_PlotArea $plotArea
+ *
+ * @return string|array
+ * @throws PHPExcel_Writer_Exception
+ */
+ private static function getChartType($plotArea)
+ {
+ $groupCount = $plotArea->getPlotGroupCount();
+
+ if ($groupCount == 1) {
+ $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType());
+ } else {
+ $chartTypes = array();
+ for ($i = 0; $i < $groupCount; ++$i) {
+ $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType();
+ }
+ $chartType = array_unique($chartTypes);
+ if (count($chartTypes) == 0) {
+ throw new PHPExcel_Writer_Exception('Chart is not yet implemented');
+ }
+ }
+
+ return $chartType;
+ }
+
+ /**
+ * Write Plot Group (series of related plots)
+ *
+ * @param PHPExcel_Chart_DataSeries $plotGroup
+ * @param string $groupType Type of plot for dataseries
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param boolean &$catIsMultiLevelSeries Is category a multi-series category
+ * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set
+ * @param string &$plotGroupingType Type of grouping for multi-series values
+ * @param PHPExcel_Worksheet $pSheet
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType, PHPExcel_Worksheet $pSheet)
+ {
+ if (is_null($plotGroup)) {
+ return;
+ }
+
+ if (($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) {
+ $objWriter->startElement('c:barDir');
+ $objWriter->writeAttribute('val', $plotGroup->getPlotDirection());
+ $objWriter->endElement();
+ }
+
+ if (!is_null($plotGroup->getPlotGrouping())) {
+ $plotGroupingType = $plotGroup->getPlotGrouping();
+ $objWriter->startElement('c:grouping');
+ $objWriter->writeAttribute('val', $plotGroupingType);
+ $objWriter->endElement();
+ }
+
+ // Get these details before the loop, because we can use the count to check for varyColors
+ $plotSeriesOrder = $plotGroup->getPlotOrder();
+ $plotSeriesCount = count($plotSeriesOrder);
+
+ if (($groupType !== PHPExcel_Chart_DataSeries::TYPE_RADARCHART) && ($groupType !== PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) {
+ if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_LINECHART) {
+ if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) || ($plotSeriesCount > 1)) {
+ $objWriter->startElement('c:varyColors');
+ $objWriter->writeAttribute('val', 1);
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:varyColors');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {
+ $objWriter->startElement('c:ser');
+
+ $objWriter->startElement('c:idx');
+ $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesIdx);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:order');
+ $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesRef);
+ $objWriter->endElement();
+
+ if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
+ $objWriter->startElement('c:dPt');
+ $objWriter->startElement('c:idx');
+ $objWriter->writeAttribute('val', 3);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:bubble3D');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:spPr');
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FF9900');
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ // Labels
+ $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef);
+ if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) {
+ $objWriter->startElement('c:tx');
+ $objWriter->startElement('c:strRef');
+ $this->writePlotSeriesLabel($plotSeriesLabel, $objWriter);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ // Formatting for the points
+ if (($groupType == PHPExcel_Chart_DataSeries::TYPE_LINECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) {
+ $objWriter->startElement('c:spPr');
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', 12700);
+ if ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) {
+ $objWriter->startElement('a:noFill');
+ $objWriter->endElement();
+ }
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+
+ $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef);
+ if ($plotSeriesValues) {
+ $plotSeriesMarker = $plotSeriesValues->getPointMarker();
+ if ($plotSeriesMarker) {
+ $objWriter->startElement('c:marker');
+ $objWriter->startElement('c:symbol');
+ $objWriter->writeAttribute('val', $plotSeriesMarker);
+ $objWriter->endElement();
+
+ if ($plotSeriesMarker !== 'none') {
+ $objWriter->startElement('c:size');
+ $objWriter->writeAttribute('val', 3);
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART)) {
+ $objWriter->startElement('c:invertIfNegative');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+
+ // Category Labels
+ $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesRef);
+ if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) {
+ $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries();
+
+ if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
+ if (!is_null($plotGroup->getPlotStyle())) {
+ $plotStyle = $plotGroup->getPlotStyle();
+ if ($plotStyle) {
+ $objWriter->startElement('c:explosion');
+ $objWriter->writeAttribute('val', 25);
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) {
+ $objWriter->startElement('c:xVal');
+ } else {
+ $objWriter->startElement('c:cat');
+ }
+
+ $this->writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str', $pSheet);
+ $objWriter->endElement();
+ }
+
+ // Values
+ if ($plotSeriesValues) {
+ $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries();
+
+ if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) {
+ $objWriter->startElement('c:yVal');
+ } else {
+ $objWriter->startElement('c:val');
+ }
+
+ $this->writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num', $pSheet);
+ $objWriter->endElement();
+ }
+
+ if ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {
+ $this->writeBubbles($plotSeriesValues, $objWriter, $pSheet);
+ }
+
+ $objWriter->endElement();
+ }
+
+ $this->_seriesIndex += $plotSeriesIdx + 1;
+ }
+
+ /**
+ * Write Plot Series Label
+ *
+ * @param PHPExcel_Chart_DataSeriesValues $plotSeriesLabel
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePlotSeriesLabel($plotSeriesLabel, $objWriter)
+ {
+ if (is_null($plotSeriesLabel)) {
+ return;
+ }
+
+ $objWriter->startElement('c:f');
+ $objWriter->writeRawData($plotSeriesLabel->getDataSource());
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:strCache');
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesLabel->getPointCount());
+ $objWriter->endElement();
+
+ foreach ($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotLabelKey);
+
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData($plotLabelValue);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Plot Series Values
+ *
+ * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $groupType Type of plot for dataseries
+ * @param string $dataType Datatype of series values
+ * @param PHPExcel_Worksheet $pSheet
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, $dataType = 'str', PHPExcel_Worksheet $pSheet)
+ {
+ if (is_null($plotSeriesValues)) {
+ return;
+ }
+
+ if ($plotSeriesValues->isMultiLevelSeries()) {
+ $levelCount = $plotSeriesValues->multiLevelCount();
+
+ $objWriter->startElement('c:multiLvlStrRef');
+
+ $objWriter->startElement('c:f');
+ $objWriter->writeRawData($plotSeriesValues->getDataSource());
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:multiLvlStrCache');
+
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount());
+ $objWriter->endElement();
+
+ for ($level = 0; $level < $levelCount; ++$level) {
+ $objWriter->startElement('c:lvl');
+
+ foreach ($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) {
+ if (isset($plotSeriesValue[$level])) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotSeriesKey);
+
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData($plotSeriesValue[$level]);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ } else {
+ $objWriter->startElement('c:' . $dataType . 'Ref');
+
+ $objWriter->startElement('c:f');
+ $objWriter->writeRawData($plotSeriesValues->getDataSource());
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:' . $dataType . 'Cache');
+
+ if (($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($groupType != PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {
+ if (($plotSeriesValues->getFormatCode() !== null) && ($plotSeriesValues->getFormatCode() !== '')) {
+ $objWriter->startElement('c:formatCode');
+ $objWriter->writeRawData($plotSeriesValues->getFormatCode());
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount());
+ $objWriter->endElement();
+
+ $dataValues = $plotSeriesValues->getDataValues();
+ if (!empty($dataValues)) {
+ if (is_array($dataValues)) {
+ foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotSeriesKey);
+
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData($plotSeriesValue);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Bubble Chart Details
+ *
+ * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeBubbles($plotSeriesValues, $objWriter, PHPExcel_Worksheet $pSheet)
+ {
+ if (is_null($plotSeriesValues)) {
+ return;
+ }
+
+ $objWriter->startElement('c:bubbleSize');
+ $objWriter->startElement('c:numLit');
+
+ $objWriter->startElement('c:formatCode');
+ $objWriter->writeRawData('General');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:ptCount');
+ $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount());
+ $objWriter->endElement();
+
+ $dataValues = $plotSeriesValues->getDataValues();
+ if (!empty($dataValues)) {
+ if (is_array($dataValues)) {
+ foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) {
+ $objWriter->startElement('c:pt');
+ $objWriter->writeAttribute('idx', $plotSeriesKey);
+ $objWriter->startElement('c:v');
+ $objWriter->writeRawData(1);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
+ }
+ }
+
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:bubble3D');
+ $objWriter->writeAttribute('val', 0);
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Layout
+ *
+ * @param PHPExcel_Chart_Layout $layout
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeLayout(PHPExcel_Chart_Layout $layout = null, $objWriter)
+ {
+ $objWriter->startElement('c:layout');
+
+ if (!is_null($layout)) {
+ $objWriter->startElement('c:manualLayout');
+
+ $layoutTarget = $layout->getLayoutTarget();
+ if (!is_null($layoutTarget)) {
+ $objWriter->startElement('c:layoutTarget');
+ $objWriter->writeAttribute('val', $layoutTarget);
+ $objWriter->endElement();
+ }
+
+ $xMode = $layout->getXMode();
+ if (!is_null($xMode)) {
+ $objWriter->startElement('c:xMode');
+ $objWriter->writeAttribute('val', $xMode);
+ $objWriter->endElement();
+ }
+
+ $yMode = $layout->getYMode();
+ if (!is_null($yMode)) {
+ $objWriter->startElement('c:yMode');
+ $objWriter->writeAttribute('val', $yMode);
+ $objWriter->endElement();
+ }
+
+ $x = $layout->getXPosition();
+ if (!is_null($x)) {
+ $objWriter->startElement('c:x');
+ $objWriter->writeAttribute('val', $x);
+ $objWriter->endElement();
+ }
+
+ $y = $layout->getYPosition();
+ if (!is_null($y)) {
+ $objWriter->startElement('c:y');
+ $objWriter->writeAttribute('val', $y);
+ $objWriter->endElement();
+ }
+
+ $w = $layout->getWidth();
+ if (!is_null($w)) {
+ $objWriter->startElement('c:w');
+ $objWriter->writeAttribute('val', $w);
+ $objWriter->endElement();
+ }
+
+ $h = $layout->getHeight();
+ if (!is_null($h)) {
+ $objWriter->startElement('c:h');
+ $objWriter->writeAttribute('val', $h);
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Alternate Content block
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeAlternateContent($objWriter)
+ {
+ $objWriter->startElement('mc:AlternateContent');
+ $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
+
+ $objWriter->startElement('mc:Choice');
+ $objWriter->writeAttribute('xmlns:c14', 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart');
+ $objWriter->writeAttribute('Requires', 'c14');
+
+ $objWriter->startElement('c14:style');
+ $objWriter->writeAttribute('val', '102');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('mc:Fallback');
+ $objWriter->startElement('c:style');
+ $objWriter->writeAttribute('val', '2');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Printer Settings
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ *
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePrintSettings($objWriter)
+ {
+ $objWriter->startElement('c:printSettings');
+
+ $objWriter->startElement('c:headerFooter');
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:pageMargins');
+ $objWriter->writeAttribute('footer', 0.3);
+ $objWriter->writeAttribute('header', 0.3);
+ $objWriter->writeAttribute('r', 0.7);
+ $objWriter->writeAttribute('l', 0.7);
+ $objWriter->writeAttribute('t', 0.75);
+ $objWriter->writeAttribute('b', 0.75);
+ $objWriter->endElement();
+
+ $objWriter->startElement('c:pageSetup');
+ $objWriter->writeAttribute('orientation', "portrait");
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Comments.php b/Classes/PHPExcel/Writer/Excel2007/Comments.php
index 5859896be..7139f6c49 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Comments.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Comments.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Comments cache
- $comments = $pWorksheet->getComments();
-
- // Authors cache
- $authors = array();
- $authorId = 0;
- foreach ($comments as $comment) {
- if (!isset($authors[$comment->getAuthor()])) {
- $authors[$comment->getAuthor()] = $authorId++;
- }
- }
-
- // comments
- $objWriter->startElement('comments');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
-
- // Loop through authors
- $objWriter->startElement('authors');
- foreach ($authors as $author => $index) {
- $objWriter->writeElement('author', $author);
- }
- $objWriter->endElement();
-
- // Loop through comments
- $objWriter->startElement('commentList');
- foreach ($comments as $key => $value) {
- $this->_writeComment($objWriter, $key, $value, $authors);
- }
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write comment to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pCellReference Cell reference
- * @param PHPExcel_Comment $pComment Comment
- * @param array $pAuthors Array of authors
- * @throws PHPExcel_Writer_Exception
- */
- public function _writeComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null, $pAuthors = null)
- {
- // comment
- $objWriter->startElement('comment');
- $objWriter->writeAttribute('ref', $pCellReference);
- $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]);
-
- // text
- $objWriter->startElement('text');
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText());
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write VML comments to XML format
- *
- * @param PHPExcel_Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeVMLComments(PHPExcel_Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Comments cache
- $comments = $pWorksheet->getComments();
-
- // xml
- $objWriter->startElement('xml');
- $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
- $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
- $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
-
- // o:shapelayout
- $objWriter->startElement('o:shapelayout');
- $objWriter->writeAttribute('v:ext', 'edit');
-
- // o:idmap
- $objWriter->startElement('o:idmap');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('data', '1');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // v:shapetype
- $objWriter->startElement('v:shapetype');
- $objWriter->writeAttribute('id', '_x0000_t202');
- $objWriter->writeAttribute('coordsize', '21600,21600');
- $objWriter->writeAttribute('o:spt', '202');
- $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe');
-
- // v:stroke
- $objWriter->startElement('v:stroke');
- $objWriter->writeAttribute('joinstyle', 'miter');
- $objWriter->endElement();
-
- // v:path
- $objWriter->startElement('v:path');
- $objWriter->writeAttribute('gradientshapeok', 't');
- $objWriter->writeAttribute('o:connecttype', 'rect');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // Loop through comments
- foreach ($comments as $key => $value) {
- $this->_writeVMLComment($objWriter, $key, $value);
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write VML comment to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pCellReference Cell reference
- * @param PHPExcel_Comment $pComment Comment
- * @throws PHPExcel_Writer_Exception
- */
- public function _writeVMLComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null)
- {
- // Metadata
- list($column, $row) = PHPExcel_Cell::coordinateFromString($pCellReference);
- $column = PHPExcel_Cell::columnIndexFromString($column);
- $id = 1024 + $column + $row;
- $id = substr($id, 0, 4);
-
- // v:shape
- $objWriter->startElement('v:shape');
- $objWriter->writeAttribute('id', '_x0000_s' . $id);
- $objWriter->writeAttribute('type', '#_x0000_t202');
- $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden'));
- $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB());
- $objWriter->writeAttribute('o:insetmode', 'auto');
-
- // v:fill
- $objWriter->startElement('v:fill');
- $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB());
- $objWriter->endElement();
-
- // v:shadow
- $objWriter->startElement('v:shadow');
- $objWriter->writeAttribute('on', 't');
- $objWriter->writeAttribute('color', 'black');
- $objWriter->writeAttribute('obscured', 't');
- $objWriter->endElement();
-
- // v:path
- $objWriter->startElement('v:path');
- $objWriter->writeAttribute('o:connecttype', 'none');
- $objWriter->endElement();
-
- // v:textbox
- $objWriter->startElement('v:textbox');
- $objWriter->writeAttribute('style', 'mso-direction-alt:auto');
-
- // div
- $objWriter->startElement('div');
- $objWriter->writeAttribute('style', 'text-align:left');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // x:ClientData
- $objWriter->startElement('x:ClientData');
- $objWriter->writeAttribute('ObjectType', 'Note');
-
- // x:MoveWithCells
- $objWriter->writeElement('x:MoveWithCells', '');
-
- // x:SizeWithCells
- $objWriter->writeElement('x:SizeWithCells', '');
-
- // x:Anchor
- //$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18');
-
- // x:AutoFill
- $objWriter->writeElement('x:AutoFill', 'False');
-
- // x:Row
- $objWriter->writeElement('x:Row', ($row - 1));
-
- // x:Column
- $objWriter->writeElement('x:Column', ($column - 1));
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
+ /**
+ * Write comments to XML format
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeComments(PHPExcel_Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Comments cache
+ $comments = $pWorksheet->getComments();
+
+ // Authors cache
+ $authors = array();
+ $authorId = 0;
+ foreach ($comments as $comment) {
+ if (!isset($authors[$comment->getAuthor()])) {
+ $authors[$comment->getAuthor()] = $authorId++;
+ }
+ }
+
+ // comments
+ $objWriter->startElement('comments');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+
+ // Loop through authors
+ $objWriter->startElement('authors');
+ foreach ($authors as $author => $index) {
+ $objWriter->writeElement('author', $author);
+ }
+ $objWriter->endElement();
+
+ // Loop through comments
+ $objWriter->startElement('commentList');
+ foreach ($comments as $key => $value) {
+ $this->writeComment($objWriter, $key, $value, $authors);
+ }
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write comment to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pCellReference Cell reference
+ * @param PHPExcel_Comment $pComment Comment
+ * @param array $pAuthors Array of authors
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null, $pAuthors = null)
+ {
+ // comment
+ $objWriter->startElement('comment');
+ $objWriter->writeAttribute('ref', $pCellReference);
+ $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]);
+
+ // text
+ $objWriter->startElement('text');
+ $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write VML comments to XML format
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeVMLComments(PHPExcel_Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Comments cache
+ $comments = $pWorksheet->getComments();
+
+ // xml
+ $objWriter->startElement('xml');
+ $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
+ $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
+ $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
+
+ // o:shapelayout
+ $objWriter->startElement('o:shapelayout');
+ $objWriter->writeAttribute('v:ext', 'edit');
+
+ // o:idmap
+ $objWriter->startElement('o:idmap');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('data', '1');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // v:shapetype
+ $objWriter->startElement('v:shapetype');
+ $objWriter->writeAttribute('id', '_x0000_t202');
+ $objWriter->writeAttribute('coordsize', '21600,21600');
+ $objWriter->writeAttribute('o:spt', '202');
+ $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe');
+
+ // v:stroke
+ $objWriter->startElement('v:stroke');
+ $objWriter->writeAttribute('joinstyle', 'miter');
+ $objWriter->endElement();
+
+ // v:path
+ $objWriter->startElement('v:path');
+ $objWriter->writeAttribute('gradientshapeok', 't');
+ $objWriter->writeAttribute('o:connecttype', 'rect');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // Loop through comments
+ foreach ($comments as $key => $value) {
+ $this->writeVMLComment($objWriter, $key, $value);
+ }
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write VML comment to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pCellReference Cell reference
+ * @param PHPExcel_Comment $pComment Comment
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeVMLComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null)
+ {
+ // Metadata
+ list($column, $row) = PHPExcel_Cell::coordinateFromString($pCellReference);
+ $column = PHPExcel_Cell::columnIndexFromString($column);
+ $id = 1024 + $column + $row;
+ $id = substr($id, 0, 4);
+
+ // v:shape
+ $objWriter->startElement('v:shape');
+ $objWriter->writeAttribute('id', '_x0000_s' . $id);
+ $objWriter->writeAttribute('type', '#_x0000_t202');
+ $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden'));
+ $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB());
+ $objWriter->writeAttribute('o:insetmode', 'auto');
+
+ // v:fill
+ $objWriter->startElement('v:fill');
+ $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB());
+ $objWriter->endElement();
+
+ // v:shadow
+ $objWriter->startElement('v:shadow');
+ $objWriter->writeAttribute('on', 't');
+ $objWriter->writeAttribute('color', 'black');
+ $objWriter->writeAttribute('obscured', 't');
+ $objWriter->endElement();
+
+ // v:path
+ $objWriter->startElement('v:path');
+ $objWriter->writeAttribute('o:connecttype', 'none');
+ $objWriter->endElement();
+
+ // v:textbox
+ $objWriter->startElement('v:textbox');
+ $objWriter->writeAttribute('style', 'mso-direction-alt:auto');
+
+ // div
+ $objWriter->startElement('div');
+ $objWriter->writeAttribute('style', 'text-align:left');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // x:ClientData
+ $objWriter->startElement('x:ClientData');
+ $objWriter->writeAttribute('ObjectType', 'Note');
+
+ // x:MoveWithCells
+ $objWriter->writeElement('x:MoveWithCells', '');
+
+ // x:SizeWithCells
+ $objWriter->writeElement('x:SizeWithCells', '');
+
+ // x:Anchor
+ //$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18');
+
+ // x:AutoFill
+ $objWriter->writeElement('x:AutoFill', 'False');
+
+ // x:Row
+ $objWriter->writeElement('x:Row', ($row - 1));
+
+ // x:Column
+ $objWriter->writeElement('x:Column', ($column - 1));
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
index a9b1dd92c..0d9118990 100644
--- a/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
+++ b/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Types
- $objWriter->startElement('Types');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');
-
- // Theme
- $this->_writeOverrideContentType(
- $objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'
- );
-
- // Styles
- $this->_writeOverrideContentType(
- $objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'
- );
-
- // Rels
- $this->_writeDefaultContentType(
- $objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'
- );
-
- // XML
- $this->_writeDefaultContentType(
- $objWriter, 'xml', 'application/xml'
- );
-
- // VML
- $this->_writeDefaultContentType(
- $objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'
- );
-
- // Workbook
- $this->_writeOverrideContentType(
- $objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'
- );
-
- // DocProps
- $this->_writeOverrideContentType(
- $objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'
- );
-
- $this->_writeOverrideContentType(
- $objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'
- );
-
- $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
- if (!empty($customPropertyList)) {
- $this->_writeOverrideContentType(
- $objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'
- );
- }
-
- // Worksheets
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'
- );
- }
-
- // Shared strings
- $this->_writeOverrideContentType(
- $objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'
- );
-
- // Add worksheet relationship content types
- $chart = 1;
- for ($i = 0; $i < $sheetCount; ++$i) {
- $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection();
- $drawingCount = count($drawings);
- $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0;
-
- // We need a drawing relationship for the worksheet if we have either drawings or charts
- if (($drawingCount > 0) || ($chartCount > 0)) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'
- );
- }
-
- // If we have charts, then we need a chart relationship for every individual chart
- if ($chartCount > 0) {
- for ($c = 0; $c < $chartCount; ++$c) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
- );
- }
- }
- }
-
- // Comments
- for ($i = 0; $i < $sheetCount; ++$i) {
- if (count($pPHPExcel->getSheet($i)->getComments()) > 0) {
- $this->_writeOverrideContentType(
- $objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'
- );
- }
- }
-
- // Add media content-types
- $aMediaContentTypes = array();
- $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count();
- for ($i = 0; $i < $mediaCount; ++$i) {
- $extension = '';
- $mimeType = '';
-
- if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {
- $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension());
- $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath() );
- } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) {
- $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType());
- $extension = explode('/', $extension);
- $extension = $extension[1];
-
- $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType();
- }
-
- if (!isset( $aMediaContentTypes[$extension]) ) {
- $aMediaContentTypes[$extension] = $mimeType;
-
- $this->_writeDefaultContentType(
- $objWriter, $extension, $mimeType
- );
- }
- }
-
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) {
- foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) {
- if (!isset( $aMediaContentTypes[strtolower($image->getExtension())]) ) {
- $aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType( $image->getPath() );
-
- $this->_writeDefaultContentType(
- $objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]
- );
- }
- }
- }
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Get image mime type
- *
- * @param string $pFile Filename
- * @return string Mime Type
- * @throws PHPExcel_Writer_Exception
- */
- private function _getImageMimeType($pFile = '')
- {
- if (PHPExcel_Shared_File::file_exists($pFile)) {
- $image = getimagesize($pFile);
- return image_type_to_mime_type($image[2]);
- } else {
- throw new PHPExcel_Writer_Exception("File $pFile does not exist");
- }
- }
-
- /**
- * Write Default content type
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pPartname Part name
- * @param string $pContentType Content type
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDefaultContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
- {
- if ($pPartname != '' && $pContentType != '') {
- // Write content type
- $objWriter->startElement('Default');
- $objWriter->writeAttribute('Extension', $pPartname);
- $objWriter->writeAttribute('ContentType', $pContentType);
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write Override content type
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pPartname Part name
- * @param string $pContentType Content type
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeOverrideContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
- {
- if ($pPartname != '' && $pContentType != '') {
- // Write content type
- $objWriter->startElement('Override');
- $objWriter->writeAttribute('PartName', $pPartname);
- $objWriter->writeAttribute('ContentType', $pContentType);
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
+ /**
+ * Write content types to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeContentTypes(PHPExcel $pPHPExcel = null, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Types
+ $objWriter->startElement('Types');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');
+
+ // Theme
+ $this->writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml');
+
+ // Styles
+ $this->writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml');
+
+ // Rels
+ $this->writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml');
+
+ // XML
+ $this->writeDefaultContentType($objWriter, 'xml', 'application/xml');
+
+ // VML
+ $this->writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing');
+
+ // Workbook
+ if ($pPHPExcel->hasMacros()) { //Macros in workbook ?
+ // Yes : not standard content but "macroEnabled"
+ $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml');
+ //... and define a new type for the VBA project
+ $this->writeDefaultContentType($objWriter, 'bin', 'application/vnd.ms-office.vbaProject');
+ if ($pPHPExcel->hasMacrosCertificate()) {// signed macros ?
+ // Yes : add needed information
+ $this->writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature');
+ }
+ } else {// no macros in workbook, so standard type
+ $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml');
+ }
+
+ // DocProps
+ $this->writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml');
+
+ $this->writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml');
+
+ $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
+ if (!empty($customPropertyList)) {
+ $this->writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml');
+ }
+
+ // Worksheets
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $this->writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml');
+ }
+
+ // Shared strings
+ $this->writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml');
+
+ // Add worksheet relationship content types
+ $chart = 1;
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection();
+ $drawingCount = count($drawings);
+ $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0;
+
+ // We need a drawing relationship for the worksheet if we have either drawings or charts
+ if (($drawingCount > 0) || ($chartCount > 0)) {
+ $this->writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml');
+ }
+
+ // If we have charts, then we need a chart relationship for every individual chart
+ if ($chartCount > 0) {
+ for ($c = 0; $c < $chartCount; ++$c) {
+ $this->writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml');
+ }
+ }
+ }
+
+ // Comments
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ if (count($pPHPExcel->getSheet($i)->getComments()) > 0) {
+ $this->writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml');
+ }
+ }
+
+ // Add media content-types
+ $aMediaContentTypes = array();
+ $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count();
+ for ($i = 0; $i < $mediaCount; ++$i) {
+ $extension = '';
+ $mimeType = '';
+
+ if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {
+ $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension());
+ $mimeType = $this->getImageMimeType($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath());
+ } elseif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) {
+ $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType());
+ $extension = explode('/', $extension);
+ $extension = $extension[1];
+
+ $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType();
+ }
+
+ if (!isset( $aMediaContentTypes[$extension])) {
+ $aMediaContentTypes[$extension] = $mimeType;
+
+ $this->writeDefaultContentType($objWriter, $extension, $mimeType);
+ }
+ }
+ if ($pPHPExcel->hasRibbonBinObjects()) {
+ // Some additional objects in the ribbon ?
+ // we need to write "Extension" but not already write for media content
+ $tabRibbonTypes=array_diff($pPHPExcel->getRibbonBinObjects('types'), array_keys($aMediaContentTypes));
+ foreach ($tabRibbonTypes as $aRibbonType) {
+ $mimeType='image/.'.$aRibbonType;//we wrote $mimeType like customUI Editor
+ $this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType);
+ }
+ }
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) {
+ foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) {
+ if (!isset( $aMediaContentTypes[strtolower($image->getExtension())])) {
+ $aMediaContentTypes[strtolower($image->getExtension())] = $this->getImageMimeType($image->getPath());
+
+ $this->writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]);
+ }
+ }
+ }
+ }
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Get image mime type
+ *
+ * @param string $pFile Filename
+ * @return string Mime Type
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function getImageMimeType($pFile = '')
+ {
+ if (PHPExcel_Shared_File::file_exists($pFile)) {
+ $image = getimagesize($pFile);
+ return image_type_to_mime_type($image[2]);
+ } else {
+ throw new PHPExcel_Writer_Exception("File $pFile does not exist");
+ }
+ }
+
+ /**
+ * Write Default content type
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pPartname Part name
+ * @param string $pContentType Content type
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDefaultContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
+ {
+ if ($pPartname != '' && $pContentType != '') {
+ // Write content type
+ $objWriter->startElement('Default');
+ $objWriter->writeAttribute('Extension', $pPartname);
+ $objWriter->writeAttribute('ContentType', $pContentType);
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write Override content type
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pPartname Part name
+ * @param string $pContentType Content type
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeOverrideContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '')
+ {
+ if ($pPartname != '' && $pContentType != '') {
+ // Write content type
+ $objWriter->startElement('Override');
+ $objWriter->writeAttribute('PartName', $pPartname);
+ $objWriter->writeAttribute('ContentType', $pContentType);
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/DocProps.php b/Classes/PHPExcel/Writer/Excel2007/DocProps.php
index 67ad72df2..fef3d9371 100644
--- a/Classes/PHPExcel/Writer/Excel2007/DocProps.php
+++ b/Classes/PHPExcel/Writer/Excel2007/DocProps.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Properties
- $objWriter->startElement('Properties');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties');
- $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
-
- // Application
- $objWriter->writeElement('Application', 'Microsoft Excel');
-
- // DocSecurity
- $objWriter->writeElement('DocSecurity', '0');
-
- // ScaleCrop
- $objWriter->writeElement('ScaleCrop', 'false');
-
- // HeadingPairs
- $objWriter->startElement('HeadingPairs');
-
- // Vector
- $objWriter->startElement('vt:vector');
- $objWriter->writeAttribute('size', '2');
- $objWriter->writeAttribute('baseType', 'variant');
-
- // Variant
- $objWriter->startElement('vt:variant');
- $objWriter->writeElement('vt:lpstr', 'Worksheets');
- $objWriter->endElement();
-
- // Variant
- $objWriter->startElement('vt:variant');
- $objWriter->writeElement('vt:i4', $pPHPExcel->getSheetCount());
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // TitlesOfParts
- $objWriter->startElement('TitlesOfParts');
-
- // Vector
- $objWriter->startElement('vt:vector');
- $objWriter->writeAttribute('size', $pPHPExcel->getSheetCount());
- $objWriter->writeAttribute('baseType', 'lpstr');
-
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- $objWriter->writeElement('vt:lpstr', $pPHPExcel->getSheet($i)->getTitle());
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // Company
- $objWriter->writeElement('Company', $pPHPExcel->getProperties()->getCompany());
-
- // Company
- $objWriter->writeElement('Manager', $pPHPExcel->getProperties()->getManager());
-
- // LinksUpToDate
- $objWriter->writeElement('LinksUpToDate', 'false');
-
- // SharedDoc
- $objWriter->writeElement('SharedDoc', 'false');
-
- // HyperlinksChanged
- $objWriter->writeElement('HyperlinksChanged', 'false');
-
- // AppVersion
- $objWriter->writeElement('AppVersion', '12.0000');
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write docProps/core.xml to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeDocPropsCore(PHPExcel $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // cp:coreProperties
- $objWriter->startElement('cp:coreProperties');
- $objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
- $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
- $objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/');
- $objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/');
- $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
-
- // dc:creator
- $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator());
-
- // cp:lastModifiedBy
- $objWriter->writeElement('cp:lastModifiedBy', $pPHPExcel->getProperties()->getLastModifiedBy());
-
- // dcterms:created
- $objWriter->startElement('dcterms:created');
- $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
- $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getCreated()));
- $objWriter->endElement();
-
- // dcterms:modified
- $objWriter->startElement('dcterms:modified');
- $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
- $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getModified()));
- $objWriter->endElement();
-
- // dc:title
- $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle());
-
- // dc:description
- $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription());
-
- // dc:subject
- $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject());
-
- // cp:keywords
- $objWriter->writeElement('cp:keywords', $pPHPExcel->getProperties()->getKeywords());
-
- // cp:category
- $objWriter->writeElement('cp:category', $pPHPExcel->getProperties()->getCategory());
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write docProps/custom.xml to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeDocPropsCustom(PHPExcel $pPHPExcel = null)
- {
- $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
- if (empty($customPropertyList)) {
- return;
- }
-
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // cp:coreProperties
- $objWriter->startElement('Properties');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties');
- $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
-
-
- foreach($customPropertyList as $key => $customProperty) {
- $propertyValue = $pPHPExcel->getProperties()->getCustomPropertyValue($customProperty);
- $propertyType = $pPHPExcel->getProperties()->getCustomPropertyType($customProperty);
-
- $objWriter->startElement('property');
- $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}');
- $objWriter->writeAttribute('pid', $key+2);
- $objWriter->writeAttribute('name', $customProperty);
-
- switch($propertyType) {
- case 'i' :
- $objWriter->writeElement('vt:i4', $propertyValue);
- break;
- case 'f' :
- $objWriter->writeElement('vt:r8', $propertyValue);
- break;
- case 'b' :
- $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
- break;
- case 'd' :
- $objWriter->startElement('vt:filetime');
- $objWriter->writeRawData(date(DATE_W3C, $propertyValue));
- $objWriter->endElement();
- break;
- default :
- $objWriter->writeElement('vt:lpwstr', $propertyValue);
- break;
- }
-
- $objWriter->endElement();
- }
-
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
+ /**
+ * Write docProps/app.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeDocPropsApp(PHPExcel $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Properties
+ $objWriter->startElement('Properties');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties');
+ $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
+
+ // Application
+ $objWriter->writeElement('Application', 'Microsoft Excel');
+
+ // DocSecurity
+ $objWriter->writeElement('DocSecurity', '0');
+
+ // ScaleCrop
+ $objWriter->writeElement('ScaleCrop', 'false');
+
+ // HeadingPairs
+ $objWriter->startElement('HeadingPairs');
+
+ // Vector
+ $objWriter->startElement('vt:vector');
+ $objWriter->writeAttribute('size', '2');
+ $objWriter->writeAttribute('baseType', 'variant');
+
+ // Variant
+ $objWriter->startElement('vt:variant');
+ $objWriter->writeElement('vt:lpstr', 'Worksheets');
+ $objWriter->endElement();
+
+ // Variant
+ $objWriter->startElement('vt:variant');
+ $objWriter->writeElement('vt:i4', $pPHPExcel->getSheetCount());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // TitlesOfParts
+ $objWriter->startElement('TitlesOfParts');
+
+ // Vector
+ $objWriter->startElement('vt:vector');
+ $objWriter->writeAttribute('size', $pPHPExcel->getSheetCount());
+ $objWriter->writeAttribute('baseType', 'lpstr');
+
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $objWriter->writeElement('vt:lpstr', $pPHPExcel->getSheet($i)->getTitle());
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // Company
+ $objWriter->writeElement('Company', $pPHPExcel->getProperties()->getCompany());
+
+ // Company
+ $objWriter->writeElement('Manager', $pPHPExcel->getProperties()->getManager());
+
+ // LinksUpToDate
+ $objWriter->writeElement('LinksUpToDate', 'false');
+
+ // SharedDoc
+ $objWriter->writeElement('SharedDoc', 'false');
+
+ // HyperlinksChanged
+ $objWriter->writeElement('HyperlinksChanged', 'false');
+
+ // AppVersion
+ $objWriter->writeElement('AppVersion', '12.0000');
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write docProps/core.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeDocPropsCore(PHPExcel $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // cp:coreProperties
+ $objWriter->startElement('cp:coreProperties');
+ $objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
+ $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
+ $objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/');
+ $objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/');
+ $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
+
+ // dc:creator
+ $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator());
+
+ // cp:lastModifiedBy
+ $objWriter->writeElement('cp:lastModifiedBy', $pPHPExcel->getProperties()->getLastModifiedBy());
+
+ // dcterms:created
+ $objWriter->startElement('dcterms:created');
+ $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
+ $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getCreated()));
+ $objWriter->endElement();
+
+ // dcterms:modified
+ $objWriter->startElement('dcterms:modified');
+ $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
+ $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getModified()));
+ $objWriter->endElement();
+
+ // dc:title
+ $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle());
+
+ // dc:description
+ $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription());
+
+ // dc:subject
+ $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject());
+
+ // cp:keywords
+ $objWriter->writeElement('cp:keywords', $pPHPExcel->getProperties()->getKeywords());
+
+ // cp:category
+ $objWriter->writeElement('cp:category', $pPHPExcel->getProperties()->getCategory());
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write docProps/custom.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeDocPropsCustom(PHPExcel $pPHPExcel = null)
+ {
+ $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
+ if (empty($customPropertyList)) {
+ return;
+ }
+
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // cp:coreProperties
+ $objWriter->startElement('Properties');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties');
+ $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
+
+
+ foreach ($customPropertyList as $key => $customProperty) {
+ $propertyValue = $pPHPExcel->getProperties()->getCustomPropertyValue($customProperty);
+ $propertyType = $pPHPExcel->getProperties()->getCustomPropertyType($customProperty);
+
+ $objWriter->startElement('property');
+ $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}');
+ $objWriter->writeAttribute('pid', $key+2);
+ $objWriter->writeAttribute('name', $customProperty);
+
+ switch ($propertyType) {
+ case 'i':
+ $objWriter->writeElement('vt:i4', $propertyValue);
+ break;
+ case 'f':
+ $objWriter->writeElement('vt:r8', $propertyValue);
+ break;
+ case 'b':
+ $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
+ break;
+ case 'd':
+ $objWriter->startElement('vt:filetime');
+ $objWriter->writeRawData(date(DATE_W3C, $propertyValue));
+ $objWriter->endElement();
+ break;
+ default:
+ $objWriter->writeElement('vt:lpwstr', $propertyValue);
+ break;
+ }
+
+ $objWriter->endElement();
+ }
+
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Drawing.php b/Classes/PHPExcel/Writer/Excel2007/Drawing.php
index fbb355665..281438889 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Drawing.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Drawing.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // xdr:wsDr
- $objWriter->startElement('xdr:wsDr');
- $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
- $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
-
- // Loop through images and write drawings
- $i = 1;
- $iterator = $pWorksheet->getDrawingCollection()->getIterator();
- while ($iterator->valid()) {
- $this->_writeDrawing($objWriter, $iterator->current(), $i);
-
- $iterator->next();
- ++$i;
- }
-
- if ($includeCharts) {
- $chartCount = $pWorksheet->getChartCount();
- // Loop through charts and write the chart position
- if ($chartCount > 0) {
- for ($c = 0; $c < $chartCount; ++$c) {
- $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i);
- }
- }
- }
-
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write drawings to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Chart $pChart
- * @param int $pRelationId
- * @throws PHPExcel_Writer_Exception
- */
- public function _writeChart(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Chart $pChart = null, $pRelationId = -1)
- {
- $tl = $pChart->getTopLeftPosition();
- $tl['colRow'] = PHPExcel_Cell::coordinateFromString($tl['cell']);
- $br = $pChart->getBottomRightPosition();
- $br['colRow'] = PHPExcel_Cell::coordinateFromString($br['cell']);
-
- $objWriter->startElement('xdr:twoCellAnchor');
-
- $objWriter->startElement('xdr:from');
- $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($tl['colRow'][0]) - 1);
- $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['xOffset']));
- $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
- $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['yOffset']));
- $objWriter->endElement();
- $objWriter->startElement('xdr:to');
- $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($br['colRow'][0]) - 1);
- $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['xOffset']));
- $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
- $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['yOffset']));
- $objWriter->endElement();
-
- $objWriter->startElement('xdr:graphicFrame');
- $objWriter->writeAttribute('macro', '');
- $objWriter->startElement('xdr:nvGraphicFramePr');
- $objWriter->startElement('xdr:cNvPr');
- $objWriter->writeAttribute('name', 'Chart '.$pRelationId);
- $objWriter->writeAttribute('id', 1025 * $pRelationId);
- $objWriter->endElement();
- $objWriter->startElement('xdr:cNvGraphicFramePr');
- $objWriter->startElement('a:graphicFrameLocks');
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('xdr:xfrm');
- $objWriter->startElement('a:off');
- $objWriter->writeAttribute('x', '0');
- $objWriter->writeAttribute('y', '0');
- $objWriter->endElement();
- $objWriter->startElement('a:ext');
- $objWriter->writeAttribute('cx', '0');
- $objWriter->writeAttribute('cy', '0');
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('a:graphic');
- $objWriter->startElement('a:graphicData');
- $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
- $objWriter->startElement('c:chart');
- $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- $objWriter->writeAttribute('r:id', 'rId'.$pRelationId);
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
- $objWriter->endElement();
-
- $objWriter->startElement('xdr:clientData');
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write drawings to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet_BaseDrawing $pDrawing
- * @param int $pRelationId
- * @throws PHPExcel_Writer_Exception
- */
- public function _writeDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1)
- {
- if ($pRelationId >= 0) {
- // xdr:oneCellAnchor
- $objWriter->startElement('xdr:oneCellAnchor');
- // Image location
- $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates());
- $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]);
-
- // xdr:from
- $objWriter->startElement('xdr:from');
- $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
- $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX()));
- $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
- $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY()));
- $objWriter->endElement();
-
- // xdr:ext
- $objWriter->startElement('xdr:ext');
- $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth()));
- $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight()));
- $objWriter->endElement();
-
- // xdr:pic
- $objWriter->startElement('xdr:pic');
-
- // xdr:nvPicPr
- $objWriter->startElement('xdr:nvPicPr');
-
- // xdr:cNvPr
- $objWriter->startElement('xdr:cNvPr');
- $objWriter->writeAttribute('id', $pRelationId);
- $objWriter->writeAttribute('name', $pDrawing->getName());
- $objWriter->writeAttribute('descr', $pDrawing->getDescription());
- $objWriter->endElement();
-
- // xdr:cNvPicPr
- $objWriter->startElement('xdr:cNvPicPr');
-
- // a:picLocks
- $objWriter->startElement('a:picLocks');
- $objWriter->writeAttribute('noChangeAspect', '1');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // xdr:blipFill
- $objWriter->startElement('xdr:blipFill');
-
- // a:blip
- $objWriter->startElement('a:blip');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);
- $objWriter->endElement();
-
- // a:stretch
- $objWriter->startElement('a:stretch');
- $objWriter->writeElement('a:fillRect', null);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // xdr:spPr
- $objWriter->startElement('xdr:spPr');
-
- // a:xfrm
- $objWriter->startElement('a:xfrm');
- $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation()));
- $objWriter->endElement();
-
- // a:prstGeom
- $objWriter->startElement('a:prstGeom');
- $objWriter->writeAttribute('prst', 'rect');
-
- // a:avLst
- $objWriter->writeElement('a:avLst', null);
-
- $objWriter->endElement();
-
-// // a:solidFill
-// $objWriter->startElement('a:solidFill');
-
-// // a:srgbClr
-// $objWriter->startElement('a:srgbClr');
-// $objWriter->writeAttribute('val', 'FFFFFF');
+ /**
+ * Write drawings to XML format
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @param int &$chartRef Chart ID
+ * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // xdr:wsDr
+ $objWriter->startElement('xdr:wsDr');
+ $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
+ $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
+
+ // Loop through images and write drawings
+ $i = 1;
+ $iterator = $pWorksheet->getDrawingCollection()->getIterator();
+ while ($iterator->valid()) {
+ $this->writeDrawing($objWriter, $iterator->current(), $i);
+
+ $iterator->next();
+ ++$i;
+ }
+
+ if ($includeCharts) {
+ $chartCount = $pWorksheet->getChartCount();
+ // Loop through charts and write the chart position
+ if ($chartCount > 0) {
+ for ($c = 0; $c < $chartCount; ++$c) {
+ $this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i);
+ }
+ }
+ }
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write drawings to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Chart $pChart
+ * @param int $pRelationId
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeChart(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Chart $pChart = null, $pRelationId = -1)
+ {
+ $tl = $pChart->getTopLeftPosition();
+ $tl['colRow'] = PHPExcel_Cell::coordinateFromString($tl['cell']);
+ $br = $pChart->getBottomRightPosition();
+ $br['colRow'] = PHPExcel_Cell::coordinateFromString($br['cell']);
+
+ $objWriter->startElement('xdr:twoCellAnchor');
+
+ $objWriter->startElement('xdr:from');
+ $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($tl['colRow'][0]) - 1);
+ $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['xOffset']));
+ $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
+ $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['yOffset']));
+ $objWriter->endElement();
+ $objWriter->startElement('xdr:to');
+ $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($br['colRow'][0]) - 1);
+ $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['xOffset']));
+ $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
+ $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['yOffset']));
+ $objWriter->endElement();
+
+ $objWriter->startElement('xdr:graphicFrame');
+ $objWriter->writeAttribute('macro', '');
+ $objWriter->startElement('xdr:nvGraphicFramePr');
+ $objWriter->startElement('xdr:cNvPr');
+ $objWriter->writeAttribute('name', 'Chart '.$pRelationId);
+ $objWriter->writeAttribute('id', 1025 * $pRelationId);
+ $objWriter->endElement();
+ $objWriter->startElement('xdr:cNvGraphicFramePr');
+ $objWriter->startElement('a:graphicFrameLocks');
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('xdr:xfrm');
+ $objWriter->startElement('a:off');
+ $objWriter->writeAttribute('x', '0');
+ $objWriter->writeAttribute('y', '0');
+ $objWriter->endElement();
+ $objWriter->startElement('a:ext');
+ $objWriter->writeAttribute('cx', '0');
+ $objWriter->writeAttribute('cy', '0');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('a:graphic');
+ $objWriter->startElement('a:graphicData');
+ $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
+ $objWriter->startElement('c:chart');
+ $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $objWriter->writeAttribute('r:id', 'rId'.$pRelationId);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ $objWriter->startElement('xdr:clientData');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write drawings to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet_BaseDrawing $pDrawing
+ * @param int $pRelationId
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1)
+ {
+ if ($pRelationId >= 0) {
+ // xdr:oneCellAnchor
+ $objWriter->startElement('xdr:oneCellAnchor');
+ // Image location
+ $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates());
+ $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]);
+
+ // xdr:from
+ $objWriter->startElement('xdr:from');
+ $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
+ $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX()));
+ $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
+ $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY()));
+ $objWriter->endElement();
+
+ // xdr:ext
+ $objWriter->startElement('xdr:ext');
+ $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth()));
+ $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight()));
+ $objWriter->endElement();
+
+ // xdr:pic
+ $objWriter->startElement('xdr:pic');
+
+ // xdr:nvPicPr
+ $objWriter->startElement('xdr:nvPicPr');
+
+ // xdr:cNvPr
+ $objWriter->startElement('xdr:cNvPr');
+ $objWriter->writeAttribute('id', $pRelationId);
+ $objWriter->writeAttribute('name', $pDrawing->getName());
+ $objWriter->writeAttribute('descr', $pDrawing->getDescription());
+ $objWriter->endElement();
+
+ // xdr:cNvPicPr
+ $objWriter->startElement('xdr:cNvPicPr');
+
+ // a:picLocks
+ $objWriter->startElement('a:picLocks');
+ $objWriter->writeAttribute('noChangeAspect', '1');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // xdr:blipFill
+ $objWriter->startElement('xdr:blipFill');
+
+ // a:blip
+ $objWriter->startElement('a:blip');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);
+ $objWriter->endElement();
+
+ // a:stretch
+ $objWriter->startElement('a:stretch');
+ $objWriter->writeElement('a:fillRect', null);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // xdr:spPr
+ $objWriter->startElement('xdr:spPr');
+
+ // a:xfrm
+ $objWriter->startElement('a:xfrm');
+ $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation()));
+ $objWriter->endElement();
+
+ // a:prstGeom
+ $objWriter->startElement('a:prstGeom');
+ $objWriter->writeAttribute('prst', 'rect');
+
+ // a:avLst
+ $objWriter->writeElement('a:avLst', null);
+
+ $objWriter->endElement();
+
+// // a:solidFill
+// $objWriter->startElement('a:solidFill');
+
+// // a:srgbClr
+// $objWriter->startElement('a:srgbClr');
+// $objWriter->writeAttribute('val', 'FFFFFF');
///* SHADE
-// // a:shade
-// $objWriter->startElement('a:shade');
-// $objWriter->writeAttribute('val', '85000');
-// $objWriter->endElement();
+// // a:shade
+// $objWriter->startElement('a:shade');
+// $objWriter->writeAttribute('val', '85000');
+// $objWriter->endElement();
//*/
-// $objWriter->endElement();
+// $objWriter->endElement();
-// $objWriter->endElement();
+// $objWriter->endElement();
/*
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '88900');
- $objWriter->writeAttribute('cap', 'sq');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '88900');
+ $objWriter->writeAttribute('cap', 'sq');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', 'FFFFFF');
- $objWriter->endElement();
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FFFFFF');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:miter
- $objWriter->startElement('a:miter');
- $objWriter->writeAttribute('lim', '800000');
- $objWriter->endElement();
+ // a:miter
+ $objWriter->startElement('a:miter');
+ $objWriter->writeAttribute('lim', '800000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
*/
- if ($pDrawing->getShadow()->getVisible()) {
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ if ($pDrawing->getShadow()->getVisible()) {
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
- $objWriter->writeAttribute('dist', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
- $objWriter->writeAttribute('dir', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
- $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
+ $objWriter->writeAttribute('dist', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
+ $objWriter->writeAttribute('dir', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
+ $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
- }
+ $objWriter->endElement();
+ }
/*
- // a:scene3d
- $objWriter->startElement('a:scene3d');
+ // a:scene3d
+ $objWriter->startElement('a:scene3d');
- // a:camera
- $objWriter->startElement('a:camera');
- $objWriter->writeAttribute('prst', 'orthographicFront');
- $objWriter->endElement();
+ // a:camera
+ $objWriter->startElement('a:camera');
+ $objWriter->writeAttribute('prst', 'orthographicFront');
+ $objWriter->endElement();
- // a:lightRig
- $objWriter->startElement('a:lightRig');
- $objWriter->writeAttribute('rig', 'twoPt');
- $objWriter->writeAttribute('dir', 't');
+ // a:lightRig
+ $objWriter->startElement('a:lightRig');
+ $objWriter->writeAttribute('rig', 'twoPt');
+ $objWriter->writeAttribute('dir', 't');
- // a:rot
- $objWriter->startElement('a:rot');
- $objWriter->writeAttribute('lat', '0');
- $objWriter->writeAttribute('lon', '0');
- $objWriter->writeAttribute('rev', '0');
- $objWriter->endElement();
+ // a:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
*/
/*
- // a:sp3d
- $objWriter->startElement('a:sp3d');
+ // a:sp3d
+ $objWriter->startElement('a:sp3d');
- // a:bevelT
- $objWriter->startElement('a:bevelT');
- $objWriter->writeAttribute('w', '25400');
- $objWriter->writeAttribute('h', '19050');
- $objWriter->endElement();
+ // a:bevelT
+ $objWriter->startElement('a:bevelT');
+ $objWriter->writeAttribute('w', '25400');
+ $objWriter->writeAttribute('h', '19050');
+ $objWriter->endElement();
- // a:contourClr
- $objWriter->startElement('a:contourClr');
+ // a:contourClr
+ $objWriter->startElement('a:contourClr');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', 'FFFFFF');
- $objWriter->endElement();
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FFFFFF');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
*/
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // xdr:clientData
- $objWriter->writeElement('xdr:clientData', null);
-
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write VML header/footer images to XML format
- *
- * @param PHPExcel_Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeVMLHeaderFooterImages(PHPExcel_Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Header/footer images
- $images = $pWorksheet->getHeaderFooter()->getImages();
-
- // xml
- $objWriter->startElement('xml');
- $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
- $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
- $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
-
- // o:shapelayout
- $objWriter->startElement('o:shapelayout');
- $objWriter->writeAttribute('v:ext', 'edit');
-
- // o:idmap
- $objWriter->startElement('o:idmap');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('data', '1');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // v:shapetype
- $objWriter->startElement('v:shapetype');
- $objWriter->writeAttribute('id', '_x0000_t75');
- $objWriter->writeAttribute('coordsize', '21600,21600');
- $objWriter->writeAttribute('o:spt', '75');
- $objWriter->writeAttribute('o:preferrelative', 't');
- $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe');
- $objWriter->writeAttribute('filled', 'f');
- $objWriter->writeAttribute('stroked', 'f');
-
- // v:stroke
- $objWriter->startElement('v:stroke');
- $objWriter->writeAttribute('joinstyle', 'miter');
- $objWriter->endElement();
-
- // v:formulas
- $objWriter->startElement('v:formulas');
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @0 1 0');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum 0 0 @1');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @2 1 2');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @0 0 1');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @6 1 2');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @8 21600 0');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight');
- $objWriter->endElement();
-
- // v:f
- $objWriter->startElement('v:f');
- $objWriter->writeAttribute('eqn', 'sum @10 21600 0');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // v:path
- $objWriter->startElement('v:path');
- $objWriter->writeAttribute('o:extrusionok', 'f');
- $objWriter->writeAttribute('gradientshapeok', 't');
- $objWriter->writeAttribute('o:connecttype', 'rect');
- $objWriter->endElement();
-
- // o:lock
- $objWriter->startElement('o:lock');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('aspectratio', 't');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // Loop through images
- foreach ($images as $key => $value) {
- $this->_writeVMLHeaderFooterImage($objWriter, $key, $value);
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write VML comment to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pReference Reference
- * @param PHPExcel_Worksheet_HeaderFooterDrawing $pImage Image
- * @throws PHPExcel_Writer_Exception
- */
- public function _writeVMLHeaderFooterImage(PHPExcel_Shared_XMLWriter $objWriter = null, $pReference = '', PHPExcel_Worksheet_HeaderFooterDrawing $pImage = null)
- {
- // Calculate object id
- preg_match('{(\d+)}', md5($pReference), $m);
- $id = 1500 + (substr($m[1], 0, 2) * 1);
-
- // Calculate offset
- $width = $pImage->getWidth();
- $height = $pImage->getHeight();
- $marginLeft = $pImage->getOffsetX();
- $marginTop = $pImage->getOffsetY();
-
- // v:shape
- $objWriter->startElement('v:shape');
- $objWriter->writeAttribute('id', $pReference);
- $objWriter->writeAttribute('o:spid', '_x0000_s' . $id);
- $objWriter->writeAttribute('type', '#_x0000_t75');
- $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1");
-
- // v:imagedata
- $objWriter->startElement('v:imagedata');
- $objWriter->writeAttribute('o:relid', 'rId' . $pReference);
- $objWriter->writeAttribute('o:title', $pImage->getName());
- $objWriter->endElement();
-
- // o:lock
- $objWriter->startElement('o:lock');
- $objWriter->writeAttribute('v:ext', 'edit');
- $objWriter->writeAttribute('rotation', 't');
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
-
- /**
- * Get an array of all drawings
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Worksheet_Drawing[] All drawings in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allDrawings(PHPExcel $pPHPExcel = null)
- {
- // Get an array of all drawings
- $aDrawings = array();
-
- // Loop through PHPExcel
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- // Loop through images and add to array
- $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator();
- while ($iterator->valid()) {
- $aDrawings[] = $iterator->current();
-
- $iterator->next();
- }
- }
-
- return $aDrawings;
- }
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // xdr:clientData
+ $objWriter->writeElement('xdr:clientData', null);
+
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write VML header/footer images to XML format
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeVMLHeaderFooterImages(PHPExcel_Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Header/footer images
+ $images = $pWorksheet->getHeaderFooter()->getImages();
+
+ // xml
+ $objWriter->startElement('xml');
+ $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
+ $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
+ $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
+
+ // o:shapelayout
+ $objWriter->startElement('o:shapelayout');
+ $objWriter->writeAttribute('v:ext', 'edit');
+
+ // o:idmap
+ $objWriter->startElement('o:idmap');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('data', '1');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // v:shapetype
+ $objWriter->startElement('v:shapetype');
+ $objWriter->writeAttribute('id', '_x0000_t75');
+ $objWriter->writeAttribute('coordsize', '21600,21600');
+ $objWriter->writeAttribute('o:spt', '75');
+ $objWriter->writeAttribute('o:preferrelative', 't');
+ $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe');
+ $objWriter->writeAttribute('filled', 'f');
+ $objWriter->writeAttribute('stroked', 'f');
+
+ // v:stroke
+ $objWriter->startElement('v:stroke');
+ $objWriter->writeAttribute('joinstyle', 'miter');
+ $objWriter->endElement();
+
+ // v:formulas
+ $objWriter->startElement('v:formulas');
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @0 1 0');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum 0 0 @1');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @2 1 2');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @0 0 1');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @6 1 2');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @8 21600 0');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight');
+ $objWriter->endElement();
+
+ // v:f
+ $objWriter->startElement('v:f');
+ $objWriter->writeAttribute('eqn', 'sum @10 21600 0');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // v:path
+ $objWriter->startElement('v:path');
+ $objWriter->writeAttribute('o:extrusionok', 'f');
+ $objWriter->writeAttribute('gradientshapeok', 't');
+ $objWriter->writeAttribute('o:connecttype', 'rect');
+ $objWriter->endElement();
+
+ // o:lock
+ $objWriter->startElement('o:lock');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('aspectratio', 't');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // Loop through images
+ foreach ($images as $key => $value) {
+ $this->writeVMLHeaderFooterImage($objWriter, $key, $value);
+ }
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write VML comment to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pReference Reference
+ * @param PHPExcel_Worksheet_HeaderFooterDrawing $pImage Image
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeVMLHeaderFooterImage(PHPExcel_Shared_XMLWriter $objWriter = null, $pReference = '', PHPExcel_Worksheet_HeaderFooterDrawing $pImage = null)
+ {
+ // Calculate object id
+ preg_match('{(\d+)}', md5($pReference), $m);
+ $id = 1500 + (substr($m[1], 0, 2) * 1);
+
+ // Calculate offset
+ $width = $pImage->getWidth();
+ $height = $pImage->getHeight();
+ $marginLeft = $pImage->getOffsetX();
+ $marginTop = $pImage->getOffsetY();
+
+ // v:shape
+ $objWriter->startElement('v:shape');
+ $objWriter->writeAttribute('id', $pReference);
+ $objWriter->writeAttribute('o:spid', '_x0000_s' . $id);
+ $objWriter->writeAttribute('type', '#_x0000_t75');
+ $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1");
+
+ // v:imagedata
+ $objWriter->startElement('v:imagedata');
+ $objWriter->writeAttribute('o:relid', 'rId' . $pReference);
+ $objWriter->writeAttribute('o:title', $pImage->getName());
+ $objWriter->endElement();
+
+ // o:lock
+ $objWriter->startElement('o:lock');
+ $objWriter->writeAttribute('v:ext', 'edit');
+ $objWriter->writeAttribute('rotation', 't');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+
+ /**
+ * Get an array of all drawings
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Worksheet_Drawing[] All drawings in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allDrawings(PHPExcel $pPHPExcel = null)
+ {
+ // Get an array of all drawings
+ $aDrawings = array();
+
+ // Loop through PHPExcel
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ // Loop through images and add to array
+ $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator();
+ while ($iterator->valid()) {
+ $aDrawings[] = $iterator->current();
+
+ $iterator->next();
+ }
+ }
+
+ return $aDrawings;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Rels.php b/Classes/PHPExcel/Writer/Excel2007/Rels.php
index 606e8c79e..14ff33710 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Rels.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Rels.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
-
- $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
- if (!empty($customPropertyList)) {
- // Relationship docProps/app.xml
- $this->_writeRelationship(
- $objWriter,
- 4,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
- 'docProps/custom.xml'
- );
-
- }
-
- // Relationship docProps/app.xml
- $this->_writeRelationship(
- $objWriter,
- 3,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
- 'docProps/app.xml'
- );
-
- // Relationship docProps/core.xml
- $this->_writeRelationship(
- $objWriter,
- 2,
- 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
- 'docProps/core.xml'
- );
-
- // Relationship xl/workbook.xml
- $this->_writeRelationship(
- $objWriter,
- 1,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
- 'xl/workbook.xml'
- );
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write workbook relationships to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeWorkbookRelationships(PHPExcel $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
-
- // Relationship styles.xml
- $this->_writeRelationship(
- $objWriter,
- 1,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
- 'styles.xml'
- );
-
- // Relationship theme/theme1.xml
- $this->_writeRelationship(
- $objWriter,
- 2,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
- 'theme/theme1.xml'
- );
-
- // Relationship sharedStrings.xml
- $this->_writeRelationship(
- $objWriter,
- 3,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
- 'sharedStrings.xml'
- );
-
- // Relationships with sheets
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- $this->_writeRelationship(
- $objWriter,
- ($i + 1 + 3),
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
- 'worksheets/sheet' . ($i + 1) . '.xml'
- );
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write worksheet relationships to XML format
- *
- * Numbering is as follows:
- * rId1 - Drawings
- * rId_hyperlink_x - Hyperlinks
- *
- * @param PHPExcel_Worksheet $pWorksheet
- * @param int $pWorksheetId
- * @param boolean $includeCharts Flag indicating if we should write charts
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeWorksheetRelationships(PHPExcel_Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
-
- // Write drawing relationships?
- $d = 0;
- if ($includeCharts) {
- $charts = $pWorksheet->getChartCollection();
- } else {
- $charts = array();
- }
- if (($pWorksheet->getDrawingCollection()->count() > 0) ||
- (count($charts) > 0)) {
- $this->_writeRelationship(
- $objWriter,
- ++$d,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
- '../drawings/drawing' . $pWorksheetId . '.xml'
- );
- }
-
- // Write chart relationships?
-// $chartCount = 0;
-// $charts = $pWorksheet->getChartCollection();
-// echo 'Chart Rels: ' , count($charts) , '
* $objDrawing->setResizeProportional(true);
* $objDrawing->setWidthAndHeight(160,120);
- *
- *
+ *
';
-// if (count($charts) > 0) {
-// foreach($charts as $chart) {
-// $this->_writeRelationship(
-// $objWriter,
-// ++$d,
-// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
-// '../charts/chart' . ++$chartCount . '.xml'
-// );
-// }
-// }
+ /**
+ * Write relationships to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeRelationships(PHPExcel $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+
+ $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();
+ if (!empty($customPropertyList)) {
+ // Relationship docProps/app.xml
+ $this->writeRelationship(
+ $objWriter,
+ 4,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
+ 'docProps/custom.xml'
+ );
+
+ }
+
+ // Relationship docProps/app.xml
+ $this->writeRelationship(
+ $objWriter,
+ 3,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
+ 'docProps/app.xml'
+ );
+
+ // Relationship docProps/core.xml
+ $this->writeRelationship(
+ $objWriter,
+ 2,
+ 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
+ 'docProps/core.xml'
+ );
+
+ // Relationship xl/workbook.xml
+ $this->writeRelationship(
+ $objWriter,
+ 1,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
+ 'xl/workbook.xml'
+ );
+ // a custom UI in workbook ?
+ if ($pPHPExcel->hasRibbon()) {
+ $this->writeRelationShip(
+ $objWriter,
+ 5,
+ 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility',
+ $pPHPExcel->getRibbonXMLData('target')
+ );
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write workbook relationships to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeWorkbookRelationships(PHPExcel $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+
+ // Relationship styles.xml
+ $this->writeRelationship(
+ $objWriter,
+ 1,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
+ 'styles.xml'
+ );
+
+ // Relationship theme/theme1.xml
+ $this->writeRelationship(
+ $objWriter,
+ 2,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
+ 'theme/theme1.xml'
+ );
+
+ // Relationship sharedStrings.xml
+ $this->writeRelationship(
+ $objWriter,
+ 3,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
+ 'sharedStrings.xml'
+ );
+
+ // Relationships with sheets
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ $this->writeRelationship(
+ $objWriter,
+ ($i + 1 + 3),
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
+ 'worksheets/sheet' . ($i + 1) . '.xml'
+ );
+ }
+ // Relationships for vbaProject if needed
+ // id : just after the last sheet
+ if ($pPHPExcel->hasMacros()) {
+ $this->writeRelationShip(
+ $objWriter,
+ ($i + 1 + 3),
+ 'http://schemas.microsoft.com/office/2006/relationships/vbaProject',
+ 'vbaProject.bin'
+ );
+ ++$i;//increment i if needed for an another relation
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write worksheet relationships to XML format
+ *
+ * Numbering is as follows:
+ * rId1 - Drawings
+ * rId_hyperlink_x - Hyperlinks
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @param int $pWorksheetId
+ * @param boolean $includeCharts Flag indicating if we should write charts
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeWorksheetRelationships(PHPExcel_Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+
+ // Write drawing relationships?
+ $d = 0;
+ if ($includeCharts) {
+ $charts = $pWorksheet->getChartCollection();
+ } else {
+ $charts = array();
+ }
+ if (($pWorksheet->getDrawingCollection()->count() > 0) ||
+ (count($charts) > 0)) {
+ $this->writeRelationship(
+ $objWriter,
+ ++$d,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
+ '../drawings/drawing' . $pWorksheetId . '.xml'
+ );
+ }
+
+ // Write chart relationships?
+// $chartCount = 0;
+// $charts = $pWorksheet->getChartCollection();
+// echo 'Chart Rels: ' , count($charts) , '
';
+// if (count($charts) > 0) {
+// foreach ($charts as $chart) {
+// $this->writeRelationship(
+// $objWriter,
+// ++$d,
+// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
+// '../charts/chart' . ++$chartCount . '.xml'
+// );
+// }
+// }
//
- // Write hyperlink relationships?
- $i = 1;
- foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
- if (!$hyperlink->isInternal()) {
- $this->_writeRelationship(
- $objWriter,
- '_hyperlink_' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
- $hyperlink->getUrl(),
- 'External'
- );
-
- ++$i;
- }
- }
-
- // Write comments relationship?
- $i = 1;
- if (count($pWorksheet->getComments()) > 0) {
- $this->_writeRelationship(
- $objWriter,
- '_comments_vml' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
- '../drawings/vmlDrawing' . $pWorksheetId . '.vml'
- );
-
- $this->_writeRelationship(
- $objWriter,
- '_comments' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
- '../comments' . $pWorksheetId . '.xml'
- );
- }
-
- // Write header/footer relationship?
- $i = 1;
- if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
- $this->_writeRelationship(
- $objWriter,
- '_headerfooter_vml' . $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
- '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
- );
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write drawing relationships to XML format
- *
- * @param PHPExcel_Worksheet $pWorksheet
- * @param int &$chartRef Chart ID
- * @param boolean $includeCharts Flag indicating if we should write charts
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
-
- // Loop through images and write relationships
- $i = 1;
- $iterator = $pWorksheet->getDrawingCollection()->getIterator();
- while ($iterator->valid()) {
- if ($iterator->current() instanceof PHPExcel_Worksheet_Drawing
- || $iterator->current() instanceof PHPExcel_Worksheet_MemoryDrawing) {
- // Write relationship for image drawing
- $this->_writeRelationship(
- $objWriter,
- $i,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
- '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename())
- );
- }
-
- $iterator->next();
- ++$i;
- }
-
- if ($includeCharts) {
- // Loop through charts and write relationships
- $chartCount = $pWorksheet->getChartCount();
- if ($chartCount > 0) {
- for ($c = 0; $c < $chartCount; ++$c) {
- $this->_writeRelationship(
- $objWriter,
- $i++,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
- '../charts/chart' . ++$chartRef . '.xml'
- );
- }
- }
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write header/footer drawing relationships to XML format
- *
- * @param PHPExcel_Worksheet $pWorksheet
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeHeaderFooterDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Relationships
- $objWriter->startElement('Relationships');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
-
- // Loop through images and write relationships
- foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
- // Write relationship for image drawing
- $this->_writeRelationship(
- $objWriter,
- $key,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
- '../media/' . $value->getIndexedFilename()
- );
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write Override content type
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param int $pId Relationship ID. rId will be prepended!
- * @param string $pType Relationship type
- * @param string $pTarget Relationship target
- * @param string $pTargetMode Relationship target mode
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeRelationship(PHPExcel_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '')
- {
- if ($pType != '' && $pTarget != '') {
- // Write relationship
- $objWriter->startElement('Relationship');
- $objWriter->writeAttribute('Id', 'rId' . $pId);
- $objWriter->writeAttribute('Type', $pType);
- $objWriter->writeAttribute('Target', $pTarget);
-
- if ($pTargetMode != '') {
- $objWriter->writeAttribute('TargetMode', $pTargetMode);
- }
-
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
+ // Write hyperlink relationships?
+ $i = 1;
+ foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
+ if (!$hyperlink->isInternal()) {
+ $this->writeRelationship(
+ $objWriter,
+ '_hyperlink_' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
+ $hyperlink->getUrl(),
+ 'External'
+ );
+
+ ++$i;
+ }
+ }
+
+ // Write comments relationship?
+ $i = 1;
+ if (count($pWorksheet->getComments()) > 0) {
+ $this->writeRelationship(
+ $objWriter,
+ '_comments_vml' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
+ '../drawings/vmlDrawing' . $pWorksheetId . '.vml'
+ );
+
+ $this->writeRelationship(
+ $objWriter,
+ '_comments' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
+ '../comments' . $pWorksheetId . '.xml'
+ );
+ }
+
+ // Write header/footer relationship?
+ $i = 1;
+ if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
+ $this->writeRelationship(
+ $objWriter,
+ '_headerfooter_vml' . $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
+ '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
+ );
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write drawing relationships to XML format
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @param int &$chartRef Chart ID
+ * @param boolean $includeCharts Flag indicating if we should write charts
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+
+ // Loop through images and write relationships
+ $i = 1;
+ $iterator = $pWorksheet->getDrawingCollection()->getIterator();
+ while ($iterator->valid()) {
+ if ($iterator->current() instanceof PHPExcel_Worksheet_Drawing
+ || $iterator->current() instanceof PHPExcel_Worksheet_MemoryDrawing) {
+ // Write relationship for image drawing
+ $this->writeRelationship(
+ $objWriter,
+ $i,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
+ '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename())
+ );
+ }
+
+ $iterator->next();
+ ++$i;
+ }
+
+ if ($includeCharts) {
+ // Loop through charts and write relationships
+ $chartCount = $pWorksheet->getChartCount();
+ if ($chartCount > 0) {
+ for ($c = 0; $c < $chartCount; ++$c) {
+ $this->writeRelationship(
+ $objWriter,
+ $i++,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
+ '../charts/chart' . ++$chartRef . '.xml'
+ );
+ }
+ }
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write header/footer drawing relationships to XML format
+ *
+ * @param PHPExcel_Worksheet $pWorksheet
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeHeaderFooterDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+
+ // Loop through images and write relationships
+ foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
+ // Write relationship for image drawing
+ $this->writeRelationship(
+ $objWriter,
+ $key,
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
+ '../media/' . $value->getIndexedFilename()
+ );
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write Override content type
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param int $pId Relationship ID. rId will be prepended!
+ * @param string $pType Relationship type
+ * @param string $pTarget Relationship target
+ * @param string $pTargetMode Relationship target mode
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeRelationship(PHPExcel_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '')
+ {
+ if ($pType != '' && $pTarget != '') {
+ // Write relationship
+ $objWriter->startElement('Relationship');
+ $objWriter->writeAttribute('Id', 'rId' . $pId);
+ $objWriter->writeAttribute('Type', $pType);
+ $objWriter->writeAttribute('Target', $pTarget);
+
+ if ($pTargetMode != '') {
+ $objWriter->writeAttribute('TargetMode', $pTargetMode);
+ }
+
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/RelsRibbon.php b/Classes/PHPExcel/Writer/Excel2007/RelsRibbon.php
new file mode 100644
index 000000000..5a4a9fc09
--- /dev/null
+++ b/Classes/PHPExcel/Writer/Excel2007/RelsRibbon.php
@@ -0,0 +1,67 @@
+getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ $localRels = $pPHPExcel->getRibbonBinObjects('names');
+ if (is_array($localRels)) {
+ foreach ($localRels as $aId => $aTarget) {
+ $objWriter->startElement('Relationship');
+ $objWriter->writeAttribute('Id', $aId);
+ $objWriter->writeAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image');
+ $objWriter->writeAttribute('Target', $aTarget);
+ $objWriter->endElement();
+ }
+ }
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+}
diff --git a/Classes/PHPExcel/Writer/Excel2007/RelsVBA.php b/Classes/PHPExcel/Writer/Excel2007/RelsVBA.php
new file mode 100644
index 000000000..bee0e6436
--- /dev/null
+++ b/Classes/PHPExcel/Writer/Excel2007/RelsVBA.php
@@ -0,0 +1,63 @@
+getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Relationships
+ $objWriter->startElement('Relationships');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ $objWriter->startElement('Relationship');
+ $objWriter->writeAttribute('Id', 'rId1');
+ $objWriter->writeAttribute('Type', 'http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature');
+ $objWriter->writeAttribute('Target', 'vbaProjectSignature.bin');
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+
+ }
+}
diff --git a/Classes/PHPExcel/Writer/Excel2007/StringTable.php b/Classes/PHPExcel/Writer/Excel2007/StringTable.php
index e43d0f0fd..fccec669f 100644
--- a/Classes/PHPExcel/Writer/Excel2007/StringTable.php
+++ b/Classes/PHPExcel/Writer/Excel2007/StringTable.php
@@ -1,8 +1,9 @@
flipStringTable($aStringTable);
-
- // Loop through cells
- foreach ($pSheet->getCellCollection() as $cellID) {
- $cell = $pSheet->getCell($cellID);
- $cellValue = $cell->getValue();
- if (!is_object($cellValue) &&
- ($cellValue !== NULL) &&
- $cellValue !== '' &&
- !isset($aFlippedStringTable[$cellValue]) &&
- ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING2 || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_NULL)) {
- $aStringTable[] = $cellValue;
- $aFlippedStringTable[$cellValue] = true;
- } elseif ($cellValue instanceof PHPExcel_RichText &&
- ($cellValue !== NULL) &&
- !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
- $aStringTable[] = $cellValue;
- $aFlippedStringTable[$cellValue->getHashCode()] = true;
- }
- }
-
- // Return
- return $aStringTable;
- } else {
- throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed.");
- }
- }
-
- /**
- * Write string table to XML format
- *
- * @param string[] $pStringTable
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeStringTable($pStringTable = null)
- {
- if ($pStringTable !== NULL) {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // String table
- $objWriter->startElement('sst');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('uniqueCount', count($pStringTable));
-
- // Loop through string table
- foreach ($pStringTable as $textElement) {
- $objWriter->startElement('si');
-
- if (! $textElement instanceof PHPExcel_RichText) {
- $textToWrite = PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $textElement );
- $objWriter->startElement('t');
- if ($textToWrite !== trim($textToWrite)) {
- $objWriter->writeAttribute('xml:space', 'preserve');
- }
- $objWriter->writeRawData($textToWrite);
- $objWriter->endElement();
- } else if ($textElement instanceof PHPExcel_RichText) {
- $this->writeRichText($objWriter, $textElement);
- }
-
+ /**
+ * Create worksheet stringtable
+ *
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @param string[] $pExistingTable Existing table to eventually merge with
+ * @return string[] String table for worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function createStringTable($pSheet = null, $pExistingTable = null)
+ {
+ if ($pSheet !== null) {
+ // Create string lookup table
+ $aStringTable = array();
+ $cellCollection = null;
+ $aFlippedStringTable = null; // For faster lookup
+
+ // Is an existing table given?
+ if (($pExistingTable !== null) && is_array($pExistingTable)) {
+ $aStringTable = $pExistingTable;
+ }
+
+ // Fill index array
+ $aFlippedStringTable = $this->flipStringTable($aStringTable);
+
+ // Loop through cells
+ foreach ($pSheet->getCellCollection() as $cellID) {
+ $cell = $pSheet->getCell($cellID);
+ $cellValue = $cell->getValue();
+ if (!is_object($cellValue) &&
+ ($cellValue !== null) &&
+ $cellValue !== '' &&
+ !isset($aFlippedStringTable[$cellValue]) &&
+ ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING2 || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_NULL)) {
+ $aStringTable[] = $cellValue;
+ $aFlippedStringTable[$cellValue] = true;
+ } elseif ($cellValue instanceof PHPExcel_RichText &&
+ ($cellValue !== null) &&
+ !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
+ $aStringTable[] = $cellValue;
+ $aFlippedStringTable[$cellValue->getHashCode()] = true;
+ }
+ }
+
+ return $aStringTable;
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed.");
+ }
+ }
+
+ /**
+ * Write string table to XML format
+ *
+ * @param string[] $pStringTable
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeStringTable($pStringTable = null)
+ {
+ if ($pStringTable !== null) {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // String table
+ $objWriter->startElement('sst');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $objWriter->writeAttribute('uniqueCount', count($pStringTable));
+
+ // Loop through string table
+ foreach ($pStringTable as $textElement) {
+ $objWriter->startElement('si');
+
+ if (! $textElement instanceof PHPExcel_RichText) {
+ $textToWrite = PHPExcel_Shared_String::ControlCharacterPHP2OOXML($textElement);
+ $objWriter->startElement('t');
+ if ($textToWrite !== trim($textToWrite)) {
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ }
+ $objWriter->writeRawData($textToWrite);
+ $objWriter->endElement();
+ } elseif ($textElement instanceof PHPExcel_RichText) {
+ $this->writeRichText($objWriter, $textElement);
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid string table array passed.");
+ }
+ }
+
+ /**
+ * Write Rich Text
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_RichText $pRichText Rich text
+ * @param string $prefix Optional Namespace prefix
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeRichText(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_RichText $pRichText = null, $prefix = null)
+ {
+ if ($prefix !== null) {
+ $prefix .= ':';
+ }
+
+ // Loop through rich text elements
+ $elements = $pRichText->getRichTextElements();
+ foreach ($elements as $element) {
+ // r
+ $objWriter->startElement($prefix.'r');
+
+ // rPr
+ if ($element instanceof PHPExcel_RichText_Run) {
+ // rPr
+ $objWriter->startElement($prefix.'rPr');
+
+ // rFont
+ $objWriter->startElement($prefix.'rFont');
+ $objWriter->writeAttribute('val', $element->getFont()->getName());
+ $objWriter->endElement();
+
+ // Bold
+ $objWriter->startElement($prefix.'b');
+ $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
+ $objWriter->endElement();
+
+ // Italic
+ $objWriter->startElement($prefix.'i');
+ $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
+ $objWriter->endElement();
+
+ // Superscript / subscript
+ if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
+ $objWriter->startElement($prefix.'vertAlign');
+ if ($element->getFont()->getSuperScript()) {
+ $objWriter->writeAttribute('val', 'superscript');
+ } elseif ($element->getFont()->getSubScript()) {
+ $objWriter->writeAttribute('val', 'subscript');
+ }
$objWriter->endElement();
- }
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid string table array passed.");
- }
- }
-
- /**
- * Write Rich Text
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_RichText $pRichText Rich text
- * @param string $prefix Optional Namespace prefix
- * @throws PHPExcel_Writer_Exception
- */
- public function writeRichText(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_RichText $pRichText = null, $prefix=NULL)
- {
- if ($prefix !== NULL)
- $prefix .= ':';
- // Loop through rich text elements
- $elements = $pRichText->getRichTextElements();
- foreach ($elements as $element) {
- // r
- $objWriter->startElement($prefix.'r');
-
- // rPr
- if ($element instanceof PHPExcel_RichText_Run) {
- // rPr
- $objWriter->startElement($prefix.'rPr');
-
- // rFont
- $objWriter->startElement($prefix.'rFont');
- $objWriter->writeAttribute('val', $element->getFont()->getName());
- $objWriter->endElement();
-
- // Bold
- $objWriter->startElement($prefix.'b');
- $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
- $objWriter->endElement();
-
- // Italic
- $objWriter->startElement($prefix.'i');
- $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
- $objWriter->endElement();
-
- // Superscript / subscript
- if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
- $objWriter->startElement($prefix.'vertAlign');
- if ($element->getFont()->getSuperScript()) {
- $objWriter->writeAttribute('val', 'superscript');
- } else if ($element->getFont()->getSubScript()) {
- $objWriter->writeAttribute('val', 'subscript');
- }
- $objWriter->endElement();
- }
-
- // Strikethrough
- $objWriter->startElement($prefix.'strike');
- $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
- $objWriter->endElement();
-
- // Color
- $objWriter->startElement($prefix.'color');
- $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
- $objWriter->endElement();
-
- // Size
- $objWriter->startElement($prefix.'sz');
- $objWriter->writeAttribute('val', $element->getFont()->getSize());
- $objWriter->endElement();
-
- // Underline
- $objWriter->startElement($prefix.'u');
- $objWriter->writeAttribute('val', $element->getFont()->getUnderline());
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- // t
- $objWriter->startElement($prefix.'t');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $element->getText() ));
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Rich Text
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string|PHPExcel_RichText $pRichText text string or Rich text
- * @param string $prefix Optional Namespace prefix
- * @throws PHPExcel_Writer_Exception
- */
- public function writeRichTextForCharts(PHPExcel_Shared_XMLWriter $objWriter = null, $pRichText = null, $prefix=NULL)
- {
- if (!$pRichText instanceof PHPExcel_RichText) {
- $textRun = $pRichText;
- $pRichText = new PHPExcel_RichText();
- $pRichText->createTextRun($textRun);
- }
-
- if ($prefix !== NULL)
- $prefix .= ':';
- // Loop through rich text elements
- $elements = $pRichText->getRichTextElements();
- foreach ($elements as $element) {
- // r
- $objWriter->startElement($prefix.'r');
-
- // rPr
- $objWriter->startElement($prefix.'rPr');
-
- // Bold
- $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
- // Italic
- $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
- // Underline
- $underlineType = $element->getFont()->getUnderline();
- switch($underlineType) {
- case 'single' :
- $underlineType = 'sng';
- break;
- case 'double' :
- $underlineType = 'dbl';
- break;
- }
- $objWriter->writeAttribute('u', $underlineType);
- // Strikethrough
- $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
-
- // rFont
- $objWriter->startElement($prefix.'latin');
- $objWriter->writeAttribute('typeface', $element->getFont()->getName());
- $objWriter->endElement();
-
- // Superscript / subscript
-// if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
-// $objWriter->startElement($prefix.'vertAlign');
-// if ($element->getFont()->getSuperScript()) {
-// $objWriter->writeAttribute('val', 'superscript');
-// } else if ($element->getFont()->getSubScript()) {
-// $objWriter->writeAttribute('val', 'subscript');
-// }
-// $objWriter->endElement();
-// }
+ }
+
+ // Strikethrough
+ $objWriter->startElement($prefix.'strike');
+ $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
+ $objWriter->endElement();
+
+ // Color
+ $objWriter->startElement($prefix.'color');
+ $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
+ $objWriter->endElement();
+
+ // Size
+ $objWriter->startElement($prefix.'sz');
+ $objWriter->writeAttribute('val', $element->getFont()->getSize());
+ $objWriter->endElement();
+
+ // Underline
+ $objWriter->startElement($prefix.'u');
+ $objWriter->writeAttribute('val', $element->getFont()->getUnderline());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ // t
+ $objWriter->startElement($prefix.'t');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($element->getText()));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Rich Text
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string|PHPExcel_RichText $pRichText text string or Rich text
+ * @param string $prefix Optional Namespace prefix
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeRichTextForCharts(PHPExcel_Shared_XMLWriter $objWriter = null, $pRichText = null, $prefix = null)
+ {
+ if (!$pRichText instanceof PHPExcel_RichText) {
+ $textRun = $pRichText;
+ $pRichText = new PHPExcel_RichText();
+ $pRichText->createTextRun($textRun);
+ }
+
+ if ($prefix !== null) {
+ $prefix .= ':';
+ }
+
+ // Loop through rich text elements
+ $elements = $pRichText->getRichTextElements();
+ foreach ($elements as $element) {
+ // r
+ $objWriter->startElement($prefix.'r');
+
+ // rPr
+ $objWriter->startElement($prefix.'rPr');
+
+ // Bold
+ $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
+ // Italic
+ $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
+ // Underline
+ $underlineType = $element->getFont()->getUnderline();
+ switch ($underlineType) {
+ case 'single':
+ $underlineType = 'sng';
+ break;
+ case 'double':
+ $underlineType = 'dbl';
+ break;
+ }
+ $objWriter->writeAttribute('u', $underlineType);
+ // Strikethrough
+ $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
+
+ // rFont
+ $objWriter->startElement($prefix.'latin');
+ $objWriter->writeAttribute('typeface', $element->getFont()->getName());
+ $objWriter->endElement();
+
+ // Superscript / subscript
+// if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
+// $objWriter->startElement($prefix.'vertAlign');
+// if ($element->getFont()->getSuperScript()) {
+// $objWriter->writeAttribute('val', 'superscript');
+// } elseif ($element->getFont()->getSubScript()) {
+// $objWriter->writeAttribute('val', 'subscript');
+// }
+// $objWriter->endElement();
+// }
//
- $objWriter->endElement();
-
- // t
- $objWriter->startElement($prefix.'t');
-// $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains
- $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $element->getText() ));
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Flip string table (for index searching)
- *
- * @param array $stringTable Stringtable
- * @return array
- */
- public function flipStringTable($stringTable = array()) {
- // Return value
- $returnValue = array();
-
- // Loop through stringtable and add flipped items to $returnValue
- foreach ($stringTable as $key => $value) {
- if (! $value instanceof PHPExcel_RichText) {
- $returnValue[$value] = $key;
- } else if ($value instanceof PHPExcel_RichText) {
- $returnValue[$value->getHashCode()] = $key;
- }
- }
-
- // Return
- return $returnValue;
- }
+ $objWriter->endElement();
+
+ // t
+ $objWriter->startElement($prefix.'t');
+// $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains
+ $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($element->getText()));
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Flip string table (for index searching)
+ *
+ * @param array $stringTable Stringtable
+ * @return array
+ */
+ public function flipStringTable($stringTable = array())
+ {
+ // Return value
+ $returnValue = array();
+
+ // Loop through stringtable and add flipped items to $returnValue
+ foreach ($stringTable as $key => $value) {
+ if (! $value instanceof PHPExcel_RichText) {
+ $returnValue[$value] = $key;
+ } elseif ($value instanceof PHPExcel_RichText) {
+ $returnValue[$value->getHashCode()] = $key;
+ }
+ }
+
+ return $returnValue;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Style.php b/Classes/PHPExcel/Writer/Excel2007/Style.php
index 90b5e9545..d3f0af7b2 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Style.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Style.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // styleSheet
- $objWriter->startElement('styleSheet');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
-
- // numFmts
- $objWriter->startElement('numFmts');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count());
-
- // numFmt
- for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) {
- $this->_writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i);
- }
-
- $objWriter->endElement();
-
- // fonts
- $objWriter->startElement('fonts');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count());
-
- // font
- for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) {
- $this->_writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i));
- }
-
- $objWriter->endElement();
-
- // fills
- $objWriter->startElement('fills');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count());
-
- // fill
- for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) {
- $this->_writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i));
- }
-
- $objWriter->endElement();
-
- // borders
- $objWriter->startElement('borders');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count());
-
- // border
- for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) {
- $this->_writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i));
- }
-
- $objWriter->endElement();
-
- // cellStyleXfs
- $objWriter->startElement('cellStyleXfs');
- $objWriter->writeAttribute('count', 1);
-
- // xf
- $objWriter->startElement('xf');
- $objWriter->writeAttribute('numFmtId', 0);
- $objWriter->writeAttribute('fontId', 0);
- $objWriter->writeAttribute('fillId', 0);
- $objWriter->writeAttribute('borderId', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // cellXfs
- $objWriter->startElement('cellXfs');
- $objWriter->writeAttribute('count', count($pPHPExcel->getCellXfCollection()));
-
- // xf
- foreach ($pPHPExcel->getCellXfCollection() as $cellXf) {
- $this->_writeCellStyleXf($objWriter, $cellXf, $pPHPExcel);
- }
-
- $objWriter->endElement();
-
- // cellStyles
- $objWriter->startElement('cellStyles');
- $objWriter->writeAttribute('count', 1);
-
- // cellStyle
- $objWriter->startElement('cellStyle');
- $objWriter->writeAttribute('name', 'Normal');
- $objWriter->writeAttribute('xfId', 0);
- $objWriter->writeAttribute('builtinId', 0);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // dxfs
- $objWriter->startElement('dxfs');
- $objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count());
-
- // dxf
- for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) {
- $this->_writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle());
- }
-
- $objWriter->endElement();
-
- // tableStyles
- $objWriter->startElement('tableStyles');
- $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9');
- $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write Fill
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style_Fill $pFill Fill style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null)
- {
- // Check if this is a pattern type or gradient type
- if ($pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR ||
- $pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_PATH) {
- // Gradient fill
- $this->_writeGradientFill($objWriter, $pFill);
- } elseif($pFill->getFillType() !== NULL) {
- // Pattern fill
- $this->_writePatternFill($objWriter, $pFill);
- }
- }
-
- /**
- * Write Gradient Fill
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style_Fill $pFill Fill style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeGradientFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null)
- {
- // fill
- $objWriter->startElement('fill');
-
- // gradientFill
- $objWriter->startElement('gradientFill');
- $objWriter->writeAttribute('type', $pFill->getFillType());
- $objWriter->writeAttribute('degree', $pFill->getRotation());
-
- // stop
- $objWriter->startElement('stop');
- $objWriter->writeAttribute('position', '0');
-
- // color
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // stop
- $objWriter->startElement('stop');
- $objWriter->writeAttribute('position', '1');
-
- // color
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Pattern Fill
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style_Fill $pFill Fill style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePatternFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null)
- {
- // fill
- $objWriter->startElement('fill');
-
- // patternFill
- $objWriter->startElement('patternFill');
- $objWriter->writeAttribute('patternType', $pFill->getFillType());
-
- if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) {
- // fgColor
- if ($pFill->getStartColor()->getARGB()) {
- $objWriter->startElement('fgColor');
- $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
- $objWriter->endElement();
- }
- }
- if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) {
- // bgColor
- if ($pFill->getEndColor()->getARGB()) {
- $objWriter->startElement('bgColor');
- $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write Font
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style_Font $pFont Font style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeFont(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Font $pFont = null)
- {
- // font
- $objWriter->startElement('font');
- // Weird! The order of these elements actually makes a difference when opening Excel2007
- // files in Excel2003 with the compatibility pack. It's not documented behaviour,
- // and makes for a real WTF!
-
- // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does
- // for conditional formatting). Otherwise it will apparently not be picked up in conditional
- // formatting style dialog
- if ($pFont->getBold() !== NULL) {
- $objWriter->startElement('b');
- $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0');
- $objWriter->endElement();
- }
-
- // Italic
- if ($pFont->getItalic() !== NULL) {
- $objWriter->startElement('i');
- $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0');
- $objWriter->endElement();
- }
-
- // Strikethrough
- if ($pFont->getStrikethrough() !== NULL) {
- $objWriter->startElement('strike');
- $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0');
- $objWriter->endElement();
- }
-
- // Underline
- if ($pFont->getUnderline() !== NULL) {
- $objWriter->startElement('u');
- $objWriter->writeAttribute('val', $pFont->getUnderline());
- $objWriter->endElement();
- }
-
- // Superscript / subscript
- if ($pFont->getSuperScript() === TRUE || $pFont->getSubScript() === TRUE) {
- $objWriter->startElement('vertAlign');
- if ($pFont->getSuperScript() === TRUE) {
- $objWriter->writeAttribute('val', 'superscript');
- } else if ($pFont->getSubScript() === TRUE) {
- $objWriter->writeAttribute('val', 'subscript');
- }
- $objWriter->endElement();
- }
-
- // Size
- if ($pFont->getSize() !== NULL) {
- $objWriter->startElement('sz');
- $objWriter->writeAttribute('val', $pFont->getSize());
- $objWriter->endElement();
- }
-
- // Foreground color
- if ($pFont->getColor()->getARGB() !== NULL) {
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB());
- $objWriter->endElement();
- }
-
- // Name
- if ($pFont->getName() !== NULL) {
- $objWriter->startElement('name');
- $objWriter->writeAttribute('val', $pFont->getName());
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Border
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style_Borders $pBorders Borders style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeBorder(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Borders $pBorders = null)
- {
- // Write border
- $objWriter->startElement('border');
- // Diagonal?
- switch ($pBorders->getDiagonalDirection()) {
- case PHPExcel_Style_Borders::DIAGONAL_UP:
- $objWriter->writeAttribute('diagonalUp', 'true');
- $objWriter->writeAttribute('diagonalDown', 'false');
- break;
- case PHPExcel_Style_Borders::DIAGONAL_DOWN:
- $objWriter->writeAttribute('diagonalUp', 'false');
- $objWriter->writeAttribute('diagonalDown', 'true');
- break;
- case PHPExcel_Style_Borders::DIAGONAL_BOTH:
- $objWriter->writeAttribute('diagonalUp', 'true');
- $objWriter->writeAttribute('diagonalDown', 'true');
- break;
- }
-
- // BorderPr
- $this->_writeBorderPr($objWriter, 'left', $pBorders->getLeft());
- $this->_writeBorderPr($objWriter, 'right', $pBorders->getRight());
- $this->_writeBorderPr($objWriter, 'top', $pBorders->getTop());
- $this->_writeBorderPr($objWriter, 'bottom', $pBorders->getBottom());
- $this->_writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal());
- $objWriter->endElement();
- }
-
- /**
- * Write Cell Style Xf
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style $pStyle Style
- * @param PHPExcel $pPHPExcel Workbook
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeCellStyleXf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null, PHPExcel $pPHPExcel = null)
- {
- // xf
- $objWriter->startElement('xf');
- $objWriter->writeAttribute('xfId', 0);
- $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode()));
-
- if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) {
- $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164) );
- } else {
- $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode());
- }
-
- $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode()));
- $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode()));
-
- // Apply styles?
- $objWriter->writeAttribute('applyFont', ($pPHPExcel->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyNumberFormat', ($pPHPExcel->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyFill', ($pPHPExcel->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyBorder', ($pPHPExcel->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyAlignment', ($pPHPExcel->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0');
- if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('applyProtection', 'true');
- }
-
- // alignment
- $objWriter->startElement('alignment');
- $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
- $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
-
- $textRotation = 0;
- if ($pStyle->getAlignment()->getTextRotation() >= 0) {
- $textRotation = $pStyle->getAlignment()->getTextRotation();
- } else if ($pStyle->getAlignment()->getTextRotation() < 0) {
- $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
- }
- $objWriter->writeAttribute('textRotation', $textRotation);
-
- $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false'));
- $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
-
- if ($pStyle->getAlignment()->getIndent() > 0) {
- $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent());
- }
- $objWriter->endElement();
-
- // protection
- if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
- $objWriter->startElement('protection');
- if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- if ($pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Cell Style Dxf
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style $pStyle Style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeCellStyleDxf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null)
- {
- // dxf
- $objWriter->startElement('dxf');
-
- // font
- $this->_writeFont($objWriter, $pStyle->getFont());
-
- // numFmt
- $this->_writeNumFmt($objWriter, $pStyle->getNumberFormat());
-
- // fill
- $this->_writeFill($objWriter, $pStyle->getFill());
-
- // alignment
- $objWriter->startElement('alignment');
- if ($pStyle->getAlignment()->getHorizontal() !== NULL) {
- $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
- }
- if ($pStyle->getAlignment()->getVertical() !== NULL) {
- $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
- }
-
- if ($pStyle->getAlignment()->getTextRotation() !== NULL) {
- $textRotation = 0;
- if ($pStyle->getAlignment()->getTextRotation() >= 0) {
- $textRotation = $pStyle->getAlignment()->getTextRotation();
- } else if ($pStyle->getAlignment()->getTextRotation() < 0) {
- $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
- }
- $objWriter->writeAttribute('textRotation', $textRotation);
- }
- $objWriter->endElement();
-
- // border
- $this->_writeBorder($objWriter, $pStyle->getBorders());
-
- // protection
- if (($pStyle->getProtection()->getLocked() !== NULL) ||
- ($pStyle->getProtection()->getHidden() !== NULL)) {
- if ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT ||
- $pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT) {
- $objWriter->startElement('protection');
- if (($pStyle->getProtection()->getLocked() !== NULL) &&
- ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) {
- $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- if (($pStyle->getProtection()->getHidden() !== NULL) &&
- ($pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) {
- $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
- }
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write BorderPr
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pName Element name
- * @param PHPExcel_Style_Border $pBorder Border style
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeBorderPr(PHPExcel_Shared_XMLWriter $objWriter = null, $pName = 'left', PHPExcel_Style_Border $pBorder = null)
- {
- // Write BorderPr
- if ($pBorder->getBorderStyle() != PHPExcel_Style_Border::BORDER_NONE) {
- $objWriter->startElement($pName);
- $objWriter->writeAttribute('style', $pBorder->getBorderStyle());
-
- // color
- $objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB());
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write NumberFormat
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Style_NumberFormat $pNumberFormat Number Format
- * @param int $pId Number Format identifier
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeNumFmt(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_NumberFormat $pNumberFormat = null, $pId = 0)
- {
- // Translate formatcode
- $formatCode = $pNumberFormat->getFormatCode();
-
- // numFmt
- if ($formatCode !== NULL) {
- $objWriter->startElement('numFmt');
- $objWriter->writeAttribute('numFmtId', ($pId + 164));
- $objWriter->writeAttribute('formatCode', $formatCode);
- $objWriter->endElement();
- }
- }
-
- /**
- * Get an array of all styles
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Style[] All styles in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allStyles(PHPExcel $pPHPExcel = null)
- {
- $aStyles = $pPHPExcel->getCellXfCollection();
-
- return $aStyles;
- }
-
- /**
- * Get an array of all conditional styles
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Style_Conditional[] All conditional styles in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allConditionalStyles(PHPExcel $pPHPExcel = null)
- {
- // Get an array of all styles
- $aStyles = array();
-
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- foreach ($pPHPExcel->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) {
- foreach ($conditionalStyles as $conditionalStyle) {
- $aStyles[] = $conditionalStyle;
- }
- }
- }
-
- return $aStyles;
- }
-
- /**
- * Get an array of all fills
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Style_Fill[] All fills in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allFills(PHPExcel $pPHPExcel = null)
- {
- // Get an array of unique fills
- $aFills = array();
-
- // Two first fills are predefined
- $fill0 = new PHPExcel_Style_Fill();
- $fill0->setFillType(PHPExcel_Style_Fill::FILL_NONE);
- $aFills[] = $fill0;
-
- $fill1 = new PHPExcel_Style_Fill();
- $fill1->setFillType(PHPExcel_Style_Fill::FILL_PATTERN_GRAY125);
- $aFills[] = $fill1;
- // The remaining fills
- $aStyles = $this->allStyles($pPHPExcel);
- foreach ($aStyles as $style) {
- if (!array_key_exists($style->getFill()->getHashCode(), $aFills)) {
- $aFills[ $style->getFill()->getHashCode() ] = $style->getFill();
- }
- }
-
- return $aFills;
- }
-
- /**
- * Get an array of all fonts
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Style_Font[] All fonts in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allFonts(PHPExcel $pPHPExcel = null)
- {
- // Get an array of unique fonts
- $aFonts = array();
- $aStyles = $this->allStyles($pPHPExcel);
-
- foreach ($aStyles as $style) {
- if (!array_key_exists($style->getFont()->getHashCode(), $aFonts)) {
- $aFonts[ $style->getFont()->getHashCode() ] = $style->getFont();
- }
- }
-
- return $aFonts;
- }
-
- /**
- * Get an array of all borders
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Style_Borders[] All borders in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allBorders(PHPExcel $pPHPExcel = null)
- {
- // Get an array of unique borders
- $aBorders = array();
- $aStyles = $this->allStyles($pPHPExcel);
-
- foreach ($aStyles as $style) {
- if (!array_key_exists($style->getBorders()->getHashCode(), $aBorders)) {
- $aBorders[ $style->getBorders()->getHashCode() ] = $style->getBorders();
- }
- }
-
- return $aBorders;
- }
-
- /**
- * Get an array of all number formats
- *
- * @param PHPExcel $pPHPExcel
- * @return PHPExcel_Style_NumberFormat[] All number formats in PHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- public function allNumberFormats(PHPExcel $pPHPExcel = null)
- {
- // Get an array of unique number formats
- $aNumFmts = array();
- $aStyles = $this->allStyles($pPHPExcel);
-
- foreach ($aStyles as $style) {
- if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !array_key_exists($style->getNumberFormat()->getHashCode(), $aNumFmts)) {
- $aNumFmts[ $style->getNumberFormat()->getHashCode() ] = $style->getNumberFormat();
- }
- }
-
- return $aNumFmts;
- }
+ /**
+ * Write styles to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeStyles(PHPExcel $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // styleSheet
+ $objWriter->startElement('styleSheet');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+
+ // numFmts
+ $objWriter->startElement('numFmts');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count());
+
+ // numFmt
+ for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) {
+ $this->writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i);
+ }
+
+ $objWriter->endElement();
+
+ // fonts
+ $objWriter->startElement('fonts');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count());
+
+ // font
+ for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) {
+ $this->writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i));
+ }
+
+ $objWriter->endElement();
+
+ // fills
+ $objWriter->startElement('fills');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count());
+
+ // fill
+ for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) {
+ $this->writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i));
+ }
+
+ $objWriter->endElement();
+
+ // borders
+ $objWriter->startElement('borders');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count());
+
+ // border
+ for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) {
+ $this->writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i));
+ }
+
+ $objWriter->endElement();
+
+ // cellStyleXfs
+ $objWriter->startElement('cellStyleXfs');
+ $objWriter->writeAttribute('count', 1);
+
+ // xf
+ $objWriter->startElement('xf');
+ $objWriter->writeAttribute('numFmtId', 0);
+ $objWriter->writeAttribute('fontId', 0);
+ $objWriter->writeAttribute('fillId', 0);
+ $objWriter->writeAttribute('borderId', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // cellXfs
+ $objWriter->startElement('cellXfs');
+ $objWriter->writeAttribute('count', count($pPHPExcel->getCellXfCollection()));
+
+ // xf
+ foreach ($pPHPExcel->getCellXfCollection() as $cellXf) {
+ $this->writeCellStyleXf($objWriter, $cellXf, $pPHPExcel);
+ }
+
+ $objWriter->endElement();
+
+ // cellStyles
+ $objWriter->startElement('cellStyles');
+ $objWriter->writeAttribute('count', 1);
+
+ // cellStyle
+ $objWriter->startElement('cellStyle');
+ $objWriter->writeAttribute('name', 'Normal');
+ $objWriter->writeAttribute('xfId', 0);
+ $objWriter->writeAttribute('builtinId', 0);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // dxfs
+ $objWriter->startElement('dxfs');
+ $objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count());
+
+ // dxf
+ for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) {
+ $this->writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle());
+ }
+
+ $objWriter->endElement();
+
+ // tableStyles
+ $objWriter->startElement('tableStyles');
+ $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9');
+ $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write Fill
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style_Fill $pFill Fill style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null)
+ {
+ // Check if this is a pattern type or gradient type
+ if ($pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR ||
+ $pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_PATH) {
+ // Gradient fill
+ $this->writeGradientFill($objWriter, $pFill);
+ } elseif ($pFill->getFillType() !== null) {
+ // Pattern fill
+ $this->writePatternFill($objWriter, $pFill);
+ }
+ }
+
+ /**
+ * Write Gradient Fill
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style_Fill $pFill Fill style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeGradientFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null)
+ {
+ // fill
+ $objWriter->startElement('fill');
+
+ // gradientFill
+ $objWriter->startElement('gradientFill');
+ $objWriter->writeAttribute('type', $pFill->getFillType());
+ $objWriter->writeAttribute('degree', $pFill->getRotation());
+
+ // stop
+ $objWriter->startElement('stop');
+ $objWriter->writeAttribute('position', '0');
+
+ // color
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // stop
+ $objWriter->startElement('stop');
+ $objWriter->writeAttribute('position', '1');
+
+ // color
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Pattern Fill
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style_Fill $pFill Fill style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePatternFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null)
+ {
+ // fill
+ $objWriter->startElement('fill');
+
+ // patternFill
+ $objWriter->startElement('patternFill');
+ $objWriter->writeAttribute('patternType', $pFill->getFillType());
+
+ if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) {
+ // fgColor
+ if ($pFill->getStartColor()->getARGB()) {
+ $objWriter->startElement('fgColor');
+ $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
+ $objWriter->endElement();
+ }
+ }
+ if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) {
+ // bgColor
+ if ($pFill->getEndColor()->getARGB()) {
+ $objWriter->startElement('bgColor');
+ $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Font
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style_Font $pFont Font style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeFont(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Font $pFont = null)
+ {
+ // font
+ $objWriter->startElement('font');
+ // Weird! The order of these elements actually makes a difference when opening Excel2007
+ // files in Excel2003 with the compatibility pack. It's not documented behaviour,
+ // and makes for a real WTF!
+
+ // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does
+ // for conditional formatting). Otherwise it will apparently not be picked up in conditional
+ // formatting style dialog
+ if ($pFont->getBold() !== null) {
+ $objWriter->startElement('b');
+ $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0');
+ $objWriter->endElement();
+ }
+
+ // Italic
+ if ($pFont->getItalic() !== null) {
+ $objWriter->startElement('i');
+ $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0');
+ $objWriter->endElement();
+ }
+
+ // Strikethrough
+ if ($pFont->getStrikethrough() !== null) {
+ $objWriter->startElement('strike');
+ $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0');
+ $objWriter->endElement();
+ }
+
+ // Underline
+ if ($pFont->getUnderline() !== null) {
+ $objWriter->startElement('u');
+ $objWriter->writeAttribute('val', $pFont->getUnderline());
+ $objWriter->endElement();
+ }
+
+ // Superscript / subscript
+ if ($pFont->getSuperScript() === true || $pFont->getSubScript() === true) {
+ $objWriter->startElement('vertAlign');
+ if ($pFont->getSuperScript() === true) {
+ $objWriter->writeAttribute('val', 'superscript');
+ } elseif ($pFont->getSubScript() === true) {
+ $objWriter->writeAttribute('val', 'subscript');
+ }
+ $objWriter->endElement();
+ }
+
+ // Size
+ if ($pFont->getSize() !== null) {
+ $objWriter->startElement('sz');
+ $objWriter->writeAttribute('val', $pFont->getSize());
+ $objWriter->endElement();
+ }
+
+ // Foreground color
+ if ($pFont->getColor()->getARGB() !== null) {
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB());
+ $objWriter->endElement();
+ }
+
+ // Name
+ if ($pFont->getName() !== null) {
+ $objWriter->startElement('name');
+ $objWriter->writeAttribute('val', $pFont->getName());
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Border
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style_Borders $pBorders Borders style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeBorder(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Borders $pBorders = null)
+ {
+ // Write border
+ $objWriter->startElement('border');
+ // Diagonal?
+ switch ($pBorders->getDiagonalDirection()) {
+ case PHPExcel_Style_Borders::DIAGONAL_UP:
+ $objWriter->writeAttribute('diagonalUp', 'true');
+ $objWriter->writeAttribute('diagonalDown', 'false');
+ break;
+ case PHPExcel_Style_Borders::DIAGONAL_DOWN:
+ $objWriter->writeAttribute('diagonalUp', 'false');
+ $objWriter->writeAttribute('diagonalDown', 'true');
+ break;
+ case PHPExcel_Style_Borders::DIAGONAL_BOTH:
+ $objWriter->writeAttribute('diagonalUp', 'true');
+ $objWriter->writeAttribute('diagonalDown', 'true');
+ break;
+ }
+
+ // BorderPr
+ $this->writeBorderPr($objWriter, 'left', $pBorders->getLeft());
+ $this->writeBorderPr($objWriter, 'right', $pBorders->getRight());
+ $this->writeBorderPr($objWriter, 'top', $pBorders->getTop());
+ $this->writeBorderPr($objWriter, 'bottom', $pBorders->getBottom());
+ $this->writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal());
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Cell Style Xf
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style $pStyle Style
+ * @param PHPExcel $pPHPExcel Workbook
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCellStyleXf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null, PHPExcel $pPHPExcel = null)
+ {
+ // xf
+ $objWriter->startElement('xf');
+ $objWriter->writeAttribute('xfId', 0);
+ $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode()));
+ if ($pStyle->getQuotePrefix()) {
+ $objWriter->writeAttribute('quotePrefix', 1);
+ }
+
+ if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) {
+ $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164));
+ } else {
+ $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode());
+ }
+
+ $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode()));
+ $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode()));
+
+ // Apply styles?
+ $objWriter->writeAttribute('applyFont', ($pPHPExcel->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyNumberFormat', ($pPHPExcel->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyFill', ($pPHPExcel->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyBorder', ($pPHPExcel->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0');
+ $objWriter->writeAttribute('applyAlignment', ($pPHPExcel->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0');
+ if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('applyProtection', 'true');
+ }
+
+ // alignment
+ $objWriter->startElement('alignment');
+ $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
+ $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
+
+ $textRotation = 0;
+ if ($pStyle->getAlignment()->getTextRotation() >= 0) {
+ $textRotation = $pStyle->getAlignment()->getTextRotation();
+ } elseif ($pStyle->getAlignment()->getTextRotation() < 0) {
+ $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
+ }
+ $objWriter->writeAttribute('textRotation', $textRotation);
+
+ $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false'));
+ $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
+
+ if ($pStyle->getAlignment()->getIndent() > 0) {
+ $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent());
+ }
+ if ($pStyle->getAlignment()->getReadorder() > 0) {
+ $objWriter->writeAttribute('readingOrder', $pStyle->getAlignment()->getReadorder());
+ }
+ $objWriter->endElement();
+
+ // protection
+ if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->startElement('protection');
+ if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ if ($pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Cell Style Dxf
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style $pStyle Style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCellStyleDxf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null)
+ {
+ // dxf
+ $objWriter->startElement('dxf');
+
+ // font
+ $this->writeFont($objWriter, $pStyle->getFont());
+
+ // numFmt
+ $this->writeNumFmt($objWriter, $pStyle->getNumberFormat());
+
+ // fill
+ $this->writeFill($objWriter, $pStyle->getFill());
+
+ // alignment
+ $objWriter->startElement('alignment');
+ if ($pStyle->getAlignment()->getHorizontal() !== null) {
+ $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
+ }
+ if ($pStyle->getAlignment()->getVertical() !== null) {
+ $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
+ }
+
+ if ($pStyle->getAlignment()->getTextRotation() !== null) {
+ $textRotation = 0;
+ if ($pStyle->getAlignment()->getTextRotation() >= 0) {
+ $textRotation = $pStyle->getAlignment()->getTextRotation();
+ } elseif ($pStyle->getAlignment()->getTextRotation() < 0) {
+ $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
+ }
+ $objWriter->writeAttribute('textRotation', $textRotation);
+ }
+ $objWriter->endElement();
+
+ // border
+ $this->writeBorder($objWriter, $pStyle->getBorders());
+
+ // protection
+ if (($pStyle->getProtection()->getLocked() !== null) || ($pStyle->getProtection()->getHidden() !== null)) {
+ if ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT ||
+ $pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT) {
+ $objWriter->startElement('protection');
+ if (($pStyle->getProtection()->getLocked() !== null) &&
+ ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) {
+ $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ if (($pStyle->getProtection()->getHidden() !== null) &&
+ ($pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) {
+ $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ }
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write BorderPr
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pName Element name
+ * @param PHPExcel_Style_Border $pBorder Border style
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeBorderPr(PHPExcel_Shared_XMLWriter $objWriter = null, $pName = 'left', PHPExcel_Style_Border $pBorder = null)
+ {
+ // Write BorderPr
+ if ($pBorder->getBorderStyle() != PHPExcel_Style_Border::BORDER_NONE) {
+ $objWriter->startElement($pName);
+ $objWriter->writeAttribute('style', $pBorder->getBorderStyle());
+
+ // color
+ $objWriter->startElement('color');
+ $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB());
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write NumberFormat
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Style_NumberFormat $pNumberFormat Number Format
+ * @param int $pId Number Format identifier
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeNumFmt(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_NumberFormat $pNumberFormat = null, $pId = 0)
+ {
+ // Translate formatcode
+ $formatCode = $pNumberFormat->getFormatCode();
+
+ // numFmt
+ if ($formatCode !== null) {
+ $objWriter->startElement('numFmt');
+ $objWriter->writeAttribute('numFmtId', ($pId + 164));
+ $objWriter->writeAttribute('formatCode', $formatCode);
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Get an array of all styles
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Style[] All styles in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allStyles(PHPExcel $pPHPExcel = null)
+ {
+ return $pPHPExcel->getCellXfCollection();
+ }
+
+ /**
+ * Get an array of all conditional styles
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Style_Conditional[] All conditional styles in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allConditionalStyles(PHPExcel $pPHPExcel = null)
+ {
+ // Get an array of all styles
+ $aStyles = array();
+
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ foreach ($pPHPExcel->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) {
+ foreach ($conditionalStyles as $conditionalStyle) {
+ $aStyles[] = $conditionalStyle;
+ }
+ }
+ }
+
+ return $aStyles;
+ }
+
+ /**
+ * Get an array of all fills
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Style_Fill[] All fills in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allFills(PHPExcel $pPHPExcel = null)
+ {
+ // Get an array of unique fills
+ $aFills = array();
+
+ // Two first fills are predefined
+ $fill0 = new PHPExcel_Style_Fill();
+ $fill0->setFillType(PHPExcel_Style_Fill::FILL_NONE);
+ $aFills[] = $fill0;
+
+ $fill1 = new PHPExcel_Style_Fill();
+ $fill1->setFillType(PHPExcel_Style_Fill::FILL_PATTERN_GRAY125);
+ $aFills[] = $fill1;
+ // The remaining fills
+ $aStyles = $this->allStyles($pPHPExcel);
+ foreach ($aStyles as $style) {
+ if (!array_key_exists($style->getFill()->getHashCode(), $aFills)) {
+ $aFills[ $style->getFill()->getHashCode() ] = $style->getFill();
+ }
+ }
+
+ return $aFills;
+ }
+
+ /**
+ * Get an array of all fonts
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Style_Font[] All fonts in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allFonts(PHPExcel $pPHPExcel = null)
+ {
+ // Get an array of unique fonts
+ $aFonts = array();
+ $aStyles = $this->allStyles($pPHPExcel);
+
+ foreach ($aStyles as $style) {
+ if (!array_key_exists($style->getFont()->getHashCode(), $aFonts)) {
+ $aFonts[ $style->getFont()->getHashCode() ] = $style->getFont();
+ }
+ }
+
+ return $aFonts;
+ }
+
+ /**
+ * Get an array of all borders
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Style_Borders[] All borders in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allBorders(PHPExcel $pPHPExcel = null)
+ {
+ // Get an array of unique borders
+ $aBorders = array();
+ $aStyles = $this->allStyles($pPHPExcel);
+
+ foreach ($aStyles as $style) {
+ if (!array_key_exists($style->getBorders()->getHashCode(), $aBorders)) {
+ $aBorders[ $style->getBorders()->getHashCode() ] = $style->getBorders();
+ }
+ }
+
+ return $aBorders;
+ }
+
+ /**
+ * Get an array of all number formats
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return PHPExcel_Style_NumberFormat[] All number formats in PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function allNumberFormats(PHPExcel $pPHPExcel = null)
+ {
+ // Get an array of unique number formats
+ $aNumFmts = array();
+ $aStyles = $this->allStyles($pPHPExcel);
+
+ foreach ($aStyles as $style) {
+ if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !array_key_exists($style->getNumberFormat()->getHashCode(), $aNumFmts)) {
+ $aNumFmts[ $style->getNumberFormat()->getHashCode() ] = $style->getNumberFormat();
+ }
+ }
+
+ return $aNumFmts;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Theme.php b/Classes/PHPExcel/Writer/Excel2007/Theme.php
index ce3a8c2c8..223e40241 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Theme.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Theme.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,8 +20,8 @@
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel2007
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,841 +31,839 @@
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel2007
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Writer_Excel2007_Theme extends PHPExcel_Writer_Excel2007_WriterPart
{
- /**
- * Map of Major fonts to write
- * @static array of string
- *
- */
- private static $_majorFonts = array(
- 'Jpan' => 'MS Pゴシック',
- 'Hang' => '맑은 고딕',
- 'Hans' => '宋体',
- 'Hant' => '新細明體',
- 'Arab' => 'Times New Roman',
- 'Hebr' => 'Times New Roman',
- 'Thai' => 'Tahoma',
- 'Ethi' => 'Nyala',
- 'Beng' => 'Vrinda',
- 'Gujr' => 'Shruti',
- 'Khmr' => 'MoolBoran',
- 'Knda' => 'Tunga',
- 'Guru' => 'Raavi',
- 'Cans' => 'Euphemia',
- 'Cher' => 'Plantagenet Cherokee',
- 'Yiii' => 'Microsoft Yi Baiti',
- 'Tibt' => 'Microsoft Himalaya',
- 'Thaa' => 'MV Boli',
- 'Deva' => 'Mangal',
- 'Telu' => 'Gautami',
- 'Taml' => 'Latha',
- 'Syrc' => 'Estrangelo Edessa',
- 'Orya' => 'Kalinga',
- 'Mlym' => 'Kartika',
- 'Laoo' => 'DokChampa',
- 'Sinh' => 'Iskoola Pota',
- 'Mong' => 'Mongolian Baiti',
- 'Viet' => 'Times New Roman',
- 'Uigh' => 'Microsoft Uighur',
- 'Geor' => 'Sylfaen',
- );
-
- /**
- * Map of Minor fonts to write
- * @static array of string
- *
- */
- private static $_minorFonts = array(
- 'Jpan' => 'MS Pゴシック',
- 'Hang' => '맑은 고딕',
- 'Hans' => '宋体',
- 'Hant' => '新細明體',
- 'Arab' => 'Arial',
- 'Hebr' => 'Arial',
- 'Thai' => 'Tahoma',
- 'Ethi' => 'Nyala',
- 'Beng' => 'Vrinda',
- 'Gujr' => 'Shruti',
- 'Khmr' => 'DaunPenh',
- 'Knda' => 'Tunga',
- 'Guru' => 'Raavi',
- 'Cans' => 'Euphemia',
- 'Cher' => 'Plantagenet Cherokee',
- 'Yiii' => 'Microsoft Yi Baiti',
- 'Tibt' => 'Microsoft Himalaya',
- 'Thaa' => 'MV Boli',
- 'Deva' => 'Mangal',
- 'Telu' => 'Gautami',
- 'Taml' => 'Latha',
- 'Syrc' => 'Estrangelo Edessa',
- 'Orya' => 'Kalinga',
- 'Mlym' => 'Kartika',
- 'Laoo' => 'DokChampa',
- 'Sinh' => 'Iskoola Pota',
- 'Mong' => 'Mongolian Baiti',
- 'Viet' => 'Arial',
- 'Uigh' => 'Microsoft Uighur',
- 'Geor' => 'Sylfaen',
- );
-
- /**
- * Map of core colours
- * @static array of string
- *
- */
- private static $_colourScheme = array(
- 'dk2' => '1F497D',
- 'lt2' => 'EEECE1',
- 'accent1' => '4F81BD',
- 'accent2' => 'C0504D',
- 'accent3' => '9BBB59',
- 'accent4' => '8064A2',
- 'accent5' => '4BACC6',
- 'accent6' => 'F79646',
- 'hlink' => '0000FF',
- 'folHlink' => '800080',
- );
-
- /**
- * Write theme to XML format
- *
- * @param PHPExcel $pPHPExcel
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeTheme(PHPExcel $pPHPExcel = null)
- {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // a:theme
- $objWriter->startElement('a:theme');
- $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
- $objWriter->writeAttribute('name', 'Office Theme');
-
- // a:themeElements
- $objWriter->startElement('a:themeElements');
-
- // a:clrScheme
- $objWriter->startElement('a:clrScheme');
- $objWriter->writeAttribute('name', 'Office');
-
- // a:dk1
- $objWriter->startElement('a:dk1');
-
- // a:sysClr
- $objWriter->startElement('a:sysClr');
- $objWriter->writeAttribute('val', 'windowText');
- $objWriter->writeAttribute('lastClr', '000000');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:lt1
- $objWriter->startElement('a:lt1');
-
- // a:sysClr
- $objWriter->startElement('a:sysClr');
- $objWriter->writeAttribute('val', 'window');
- $objWriter->writeAttribute('lastClr', 'FFFFFF');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:dk2
- $this->_writeColourScheme($objWriter);
-
- $objWriter->endElement();
-
- // a:fontScheme
- $objWriter->startElement('a:fontScheme');
- $objWriter->writeAttribute('name', 'Office');
-
- // a:majorFont
- $objWriter->startElement('a:majorFont');
- $this->_writeFonts($objWriter, 'Cambria', self::$_majorFonts);
- $objWriter->endElement();
-
- // a:minorFont
- $objWriter->startElement('a:minorFont');
- $this->_writeFonts($objWriter, 'Calibri', self::$_minorFonts);
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:fmtScheme
- $objWriter->startElement('a:fmtScheme');
- $objWriter->writeAttribute('name', 'Office');
-
- // a:fillStyleLst
- $objWriter->startElement('a:fillStyleLst');
-
- // a:solidFill
- $objWriter->startElement('a:solidFill');
-
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ /**
+ * Map of Major fonts to write
+ * @static array of string
+ *
+ */
+ private static $majorFonts = array(
+ 'Jpan' => 'MS Pゴシック',
+ 'Hang' => '맑은 고딕',
+ 'Hans' => '宋体',
+ 'Hant' => '新細明體',
+ 'Arab' => 'Times New Roman',
+ 'Hebr' => 'Times New Roman',
+ 'Thai' => 'Tahoma',
+ 'Ethi' => 'Nyala',
+ 'Beng' => 'Vrinda',
+ 'Gujr' => 'Shruti',
+ 'Khmr' => 'MoolBoran',
+ 'Knda' => 'Tunga',
+ 'Guru' => 'Raavi',
+ 'Cans' => 'Euphemia',
+ 'Cher' => 'Plantagenet Cherokee',
+ 'Yiii' => 'Microsoft Yi Baiti',
+ 'Tibt' => 'Microsoft Himalaya',
+ 'Thaa' => 'MV Boli',
+ 'Deva' => 'Mangal',
+ 'Telu' => 'Gautami',
+ 'Taml' => 'Latha',
+ 'Syrc' => 'Estrangelo Edessa',
+ 'Orya' => 'Kalinga',
+ 'Mlym' => 'Kartika',
+ 'Laoo' => 'DokChampa',
+ 'Sinh' => 'Iskoola Pota',
+ 'Mong' => 'Mongolian Baiti',
+ 'Viet' => 'Times New Roman',
+ 'Uigh' => 'Microsoft Uighur',
+ 'Geor' => 'Sylfaen',
+ );
+
+ /**
+ * Map of Minor fonts to write
+ * @static array of string
+ *
+ */
+ private static $minorFonts = array(
+ 'Jpan' => 'MS Pゴシック',
+ 'Hang' => '맑은 고딕',
+ 'Hans' => '宋体',
+ 'Hant' => '新細明體',
+ 'Arab' => 'Arial',
+ 'Hebr' => 'Arial',
+ 'Thai' => 'Tahoma',
+ 'Ethi' => 'Nyala',
+ 'Beng' => 'Vrinda',
+ 'Gujr' => 'Shruti',
+ 'Khmr' => 'DaunPenh',
+ 'Knda' => 'Tunga',
+ 'Guru' => 'Raavi',
+ 'Cans' => 'Euphemia',
+ 'Cher' => 'Plantagenet Cherokee',
+ 'Yiii' => 'Microsoft Yi Baiti',
+ 'Tibt' => 'Microsoft Himalaya',
+ 'Thaa' => 'MV Boli',
+ 'Deva' => 'Mangal',
+ 'Telu' => 'Gautami',
+ 'Taml' => 'Latha',
+ 'Syrc' => 'Estrangelo Edessa',
+ 'Orya' => 'Kalinga',
+ 'Mlym' => 'Kartika',
+ 'Laoo' => 'DokChampa',
+ 'Sinh' => 'Iskoola Pota',
+ 'Mong' => 'Mongolian Baiti',
+ 'Viet' => 'Arial',
+ 'Uigh' => 'Microsoft Uighur',
+ 'Geor' => 'Sylfaen',
+ );
+
+ /**
+ * Map of core colours
+ * @static array of string
+ *
+ */
+ private static $colourScheme = array(
+ 'dk2' => '1F497D',
+ 'lt2' => 'EEECE1',
+ 'accent1' => '4F81BD',
+ 'accent2' => 'C0504D',
+ 'accent3' => '9BBB59',
+ 'accent4' => '8064A2',
+ 'accent5' => '4BACC6',
+ 'accent6' => 'F79646',
+ 'hlink' => '0000FF',
+ 'folHlink' => '800080',
+ );
+
+ /**
+ * Write theme to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeTheme(PHPExcel $pPHPExcel = null)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // a:theme
+ $objWriter->startElement('a:theme');
+ $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
+ $objWriter->writeAttribute('name', 'Office Theme');
+
+ // a:themeElements
+ $objWriter->startElement('a:themeElements');
+
+ // a:clrScheme
+ $objWriter->startElement('a:clrScheme');
+ $objWriter->writeAttribute('name', 'Office');
+
+ // a:dk1
+ $objWriter->startElement('a:dk1');
+
+ // a:sysClr
+ $objWriter->startElement('a:sysClr');
+ $objWriter->writeAttribute('val', 'windowText');
+ $objWriter->writeAttribute('lastClr', '000000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:lt1
+ $objWriter->startElement('a:lt1');
+
+ // a:sysClr
+ $objWriter->startElement('a:sysClr');
+ $objWriter->writeAttribute('val', 'window');
+ $objWriter->writeAttribute('lastClr', 'FFFFFF');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:dk2
+ $this->writeColourScheme($objWriter);
+
+ $objWriter->endElement();
+
+ // a:fontScheme
+ $objWriter->startElement('a:fontScheme');
+ $objWriter->writeAttribute('name', 'Office');
+
+ // a:majorFont
+ $objWriter->startElement('a:majorFont');
+ $this->writeFonts($objWriter, 'Cambria', self::$majorFonts);
+ $objWriter->endElement();
+
+ // a:minorFont
+ $objWriter->startElement('a:minorFont');
+ $this->writeFonts($objWriter, 'Calibri', self::$minorFonts);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:fmtScheme
+ $objWriter->startElement('a:fmtScheme');
+ $objWriter->writeAttribute('name', 'Office');
+
+ // a:fillStyleLst
+ $objWriter->startElement('a:fillStyleLst');
+
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '50000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '50000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '300000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '35000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '35000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '37000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '37000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '300000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '15000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '15000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '350000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lin
- $objWriter->startElement('a:lin');
- $objWriter->writeAttribute('ang', '16200000');
- $objWriter->writeAttribute('scaled', '1');
- $objWriter->endElement();
+ // a:lin
+ $objWriter->startElement('a:lin');
+ $objWriter->writeAttribute('ang', '16200000');
+ $objWriter->writeAttribute('scaled', '1');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '51000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '51000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '130000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '130000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '80000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '80000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '93000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '93000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '130000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '130000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '94000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '94000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '135000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '135000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lin
- $objWriter->startElement('a:lin');
- $objWriter->writeAttribute('ang', '16200000');
- $objWriter->writeAttribute('scaled', '0');
- $objWriter->endElement();
+ // a:lin
+ $objWriter->startElement('a:lin');
+ $objWriter->writeAttribute('ang', '16200000');
+ $objWriter->writeAttribute('scaled', '0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lnStyleLst
- $objWriter->startElement('a:lnStyleLst');
+ // a:lnStyleLst
+ $objWriter->startElement('a:lnStyleLst');
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '9525');
- $objWriter->writeAttribute('cap', 'flat');
- $objWriter->writeAttribute('cmpd', 'sng');
- $objWriter->writeAttribute('algn', 'ctr');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '9525');
+ $objWriter->writeAttribute('cap', 'flat');
+ $objWriter->writeAttribute('cmpd', 'sng');
+ $objWriter->writeAttribute('algn', 'ctr');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '95000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '95000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '105000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '105000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:prstDash
- $objWriter->startElement('a:prstDash');
- $objWriter->writeAttribute('val', 'solid');
- $objWriter->endElement();
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '25400');
- $objWriter->writeAttribute('cap', 'flat');
- $objWriter->writeAttribute('cmpd', 'sng');
- $objWriter->writeAttribute('algn', 'ctr');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '25400');
+ $objWriter->writeAttribute('cap', 'flat');
+ $objWriter->writeAttribute('cmpd', 'sng');
+ $objWriter->writeAttribute('algn', 'ctr');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:prstDash
- $objWriter->startElement('a:prstDash');
- $objWriter->writeAttribute('val', 'solid');
- $objWriter->endElement();
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:ln
- $objWriter->startElement('a:ln');
- $objWriter->writeAttribute('w', '38100');
- $objWriter->writeAttribute('cap', 'flat');
- $objWriter->writeAttribute('cmpd', 'sng');
- $objWriter->writeAttribute('algn', 'ctr');
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '38100');
+ $objWriter->writeAttribute('cap', 'flat');
+ $objWriter->writeAttribute('cmpd', 'sng');
+ $objWriter->writeAttribute('algn', 'ctr');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:prstDash
- $objWriter->startElement('a:prstDash');
- $objWriter->writeAttribute('val', 'solid');
- $objWriter->endElement();
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:effectStyleLst
- $objWriter->startElement('a:effectStyleLst');
+ // a:effectStyleLst
+ $objWriter->startElement('a:effectStyleLst');
- // a:effectStyle
- $objWriter->startElement('a:effectStyle');
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', '40000');
- $objWriter->writeAttribute('dist', '20000');
- $objWriter->writeAttribute('dir', '5400000');
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', '40000');
+ $objWriter->writeAttribute('dist', '20000');
+ $objWriter->writeAttribute('dir', '5400000');
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', '000000');
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', '38000');
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '38000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:effectStyle
- $objWriter->startElement('a:effectStyle');
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', '40000');
- $objWriter->writeAttribute('dist', '23000');
- $objWriter->writeAttribute('dir', '5400000');
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', '40000');
+ $objWriter->writeAttribute('dist', '23000');
+ $objWriter->writeAttribute('dir', '5400000');
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', '000000');
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', '35000');
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '35000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:effectStyle
- $objWriter->startElement('a:effectStyle');
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
- // a:effectLst
- $objWriter->startElement('a:effectLst');
+ // a:effectLst
+ $objWriter->startElement('a:effectLst');
- // a:outerShdw
- $objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', '40000');
- $objWriter->writeAttribute('dist', '23000');
- $objWriter->writeAttribute('dir', '5400000');
- $objWriter->writeAttribute('rotWithShape', '0');
+ // a:outerShdw
+ $objWriter->startElement('a:outerShdw');
+ $objWriter->writeAttribute('blurRad', '40000');
+ $objWriter->writeAttribute('dist', '23000');
+ $objWriter->writeAttribute('dir', '5400000');
+ $objWriter->writeAttribute('rotWithShape', '0');
- // a:srgbClr
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', '000000');
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
- // a:alpha
- $objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', '35000');
- $objWriter->endElement();
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '35000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:scene3d
- $objWriter->startElement('a:scene3d');
+ // a:scene3d
+ $objWriter->startElement('a:scene3d');
- // a:camera
- $objWriter->startElement('a:camera');
- $objWriter->writeAttribute('prst', 'orthographicFront');
+ // a:camera
+ $objWriter->startElement('a:camera');
+ $objWriter->writeAttribute('prst', 'orthographicFront');
- // a:rot
- $objWriter->startElement('a:rot');
- $objWriter->writeAttribute('lat', '0');
- $objWriter->writeAttribute('lon', '0');
- $objWriter->writeAttribute('rev', '0');
- $objWriter->endElement();
+ // a:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '0');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:lightRig
- $objWriter->startElement('a:lightRig');
- $objWriter->writeAttribute('rig', 'threePt');
- $objWriter->writeAttribute('dir', 't');
+ // a:lightRig
+ $objWriter->startElement('a:lightRig');
+ $objWriter->writeAttribute('rig', 'threePt');
+ $objWriter->writeAttribute('dir', 't');
- // a:rot
- $objWriter->startElement('a:rot');
- $objWriter->writeAttribute('lat', '0');
- $objWriter->writeAttribute('lon', '0');
- $objWriter->writeAttribute('rev', '1200000');
- $objWriter->endElement();
+ // a:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '1200000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:sp3d
- $objWriter->startElement('a:sp3d');
+ // a:sp3d
+ $objWriter->startElement('a:sp3d');
- // a:bevelT
- $objWriter->startElement('a:bevelT');
- $objWriter->writeAttribute('w', '63500');
- $objWriter->writeAttribute('h', '25400');
- $objWriter->endElement();
+ // a:bevelT
+ $objWriter->startElement('a:bevelT');
+ $objWriter->writeAttribute('w', '63500');
+ $objWriter->writeAttribute('h', '25400');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:bgFillStyleLst
- $objWriter->startElement('a:bgFillStyleLst');
+ // a:bgFillStyleLst
+ $objWriter->startElement('a:bgFillStyleLst');
- // a:solidFill
- $objWriter->startElement('a:solidFill');
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
- $objWriter->endElement();
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '40000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '40000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '350000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '40000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '40000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '45000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '45000');
+ $objWriter->endElement();
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '99000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '99000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '350000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '20000');
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '20000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '255000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '255000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:path
- $objWriter->startElement('a:path');
- $objWriter->writeAttribute('path', 'circle');
+ // a:path
+ $objWriter->startElement('a:path');
+ $objWriter->writeAttribute('path', 'circle');
- // a:fillToRect
- $objWriter->startElement('a:fillToRect');
- $objWriter->writeAttribute('l', '50000');
- $objWriter->writeAttribute('t', '-80000');
- $objWriter->writeAttribute('r', '50000');
- $objWriter->writeAttribute('b', '180000');
- $objWriter->endElement();
+ // a:fillToRect
+ $objWriter->startElement('a:fillToRect');
+ $objWriter->writeAttribute('l', '50000');
+ $objWriter->writeAttribute('t', '-80000');
+ $objWriter->writeAttribute('r', '50000');
+ $objWriter->writeAttribute('b', '180000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gradFill
- $objWriter->startElement('a:gradFill');
- $objWriter->writeAttribute('rotWithShape', '1');
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
- // a:gsLst
- $objWriter->startElement('a:gsLst');
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '0');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:tint
- $objWriter->startElement('a:tint');
- $objWriter->writeAttribute('val', '80000');
- $objWriter->endElement();
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '80000');
+ $objWriter->endElement();
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '300000');
- $objWriter->endElement();
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
- // a:gs
- $objWriter->startElement('a:gs');
- $objWriter->writeAttribute('pos', '100000');
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
- // a:schemeClr
- $objWriter->startElement('a:schemeClr');
- $objWriter->writeAttribute('val', 'phClr');
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
- // a:shade
- $objWriter->startElement('a:shade');
- $objWriter->writeAttribute('val', '30000');
- $objWriter->endElement();
-
- // a:satMod
- $objWriter->startElement('a:satMod');
- $objWriter->writeAttribute('val', '200000');
- $objWriter->endElement();
-
- $objWriter->endElement();
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '30000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '200000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement();
+
+ // a:path
+ $objWriter->startElement('a:path');
+ $objWriter->writeAttribute('path', 'circle');
+
+ // a:fillToRect
+ $objWriter->startElement('a:fillToRect');
+ $objWriter->writeAttribute('l', '50000');
+ $objWriter->writeAttribute('t', '50000');
+ $objWriter->writeAttribute('r', '50000');
+ $objWriter->writeAttribute('b', '50000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:objectDefaults
+ $objWriter->writeElement('a:objectDefaults', null);
- $objWriter->endElement();
-
- // a:path
- $objWriter->startElement('a:path');
- $objWriter->writeAttribute('path', 'circle');
-
- // a:fillToRect
- $objWriter->startElement('a:fillToRect');
- $objWriter->writeAttribute('l', '50000');
- $objWriter->writeAttribute('t', '50000');
- $objWriter->writeAttribute('r', '50000');
- $objWriter->writeAttribute('b', '50000');
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- $objWriter->endElement();
-
- // a:objectDefaults
- $objWriter->writeElement('a:objectDefaults', null);
-
- // a:extraClrSchemeLst
- $objWriter->writeElement('a:extraClrSchemeLst', null);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write fonts to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter
- * @param string $latinFont
- * @param array of string $fontSet
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeFonts($objWriter, $latinFont, $fontSet)
- {
- // a:latin
- $objWriter->startElement('a:latin');
- $objWriter->writeAttribute('typeface', $latinFont);
- $objWriter->endElement();
-
- // a:ea
- $objWriter->startElement('a:ea');
- $objWriter->writeAttribute('typeface', '');
- $objWriter->endElement();
-
- // a:cs
- $objWriter->startElement('a:cs');
- $objWriter->writeAttribute('typeface', '');
- $objWriter->endElement();
-
- foreach($fontSet as $fontScript => $typeface) {
- $objWriter->startElement('a:font');
- $objWriter->writeAttribute('script', $fontScript);
- $objWriter->writeAttribute('typeface', $typeface);
- $objWriter->endElement();
- }
-
- }
-
- /**
- * Write colour scheme to XML format
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeColourScheme($objWriter)
- {
- foreach(self::$_colourScheme as $colourName => $colourValue) {
- $objWriter->startElement('a:'.$colourName);
-
- $objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', $colourValue);
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- }
+ // a:extraClrSchemeLst
+ $objWriter->writeElement('a:extraClrSchemeLst', null);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write fonts to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter
+ * @param string $latinFont
+ * @param array of string $fontSet
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeFonts($objWriter, $latinFont, $fontSet)
+ {
+ // a:latin
+ $objWriter->startElement('a:latin');
+ $objWriter->writeAttribute('typeface', $latinFont);
+ $objWriter->endElement();
+
+ // a:ea
+ $objWriter->startElement('a:ea');
+ $objWriter->writeAttribute('typeface', '');
+ $objWriter->endElement();
+
+ // a:cs
+ $objWriter->startElement('a:cs');
+ $objWriter->writeAttribute('typeface', '');
+ $objWriter->endElement();
+
+ foreach ($fontSet as $fontScript => $typeface) {
+ $objWriter->startElement('a:font');
+ $objWriter->writeAttribute('script', $fontScript);
+ $objWriter->writeAttribute('typeface', $typeface);
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write colour scheme to XML format
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeColourScheme($objWriter)
+ {
+ foreach (self::$colourScheme as $colourName => $colourValue) {
+ $objWriter->startElement('a:'.$colourName);
+
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', $colourValue);
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Workbook.php b/Classes/PHPExcel/Writer/Excel2007/Workbook.php
index 6f3e44a25..87c877ea9 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Workbook.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Workbook.php
@@ -1,8 +1,9 @@
getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // workbook
- $objWriter->startElement('workbook');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
-
- // fileVersion
- $this->_writeFileVersion($objWriter);
-
- // workbookPr
- $this->_writeWorkbookPr($objWriter);
-
- // workbookProtection
- $this->_writeWorkbookProtection($objWriter, $pPHPExcel);
-
- // bookViews
- if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
- $this->_writeBookViews($objWriter, $pPHPExcel);
- }
-
- // sheets
- $this->_writeSheets($objWriter, $pPHPExcel);
-
- // definedNames
- $this->_writeDefinedNames($objWriter, $pPHPExcel);
-
- // calcPr
- $this->_writeCalcPr($objWriter,$recalcRequired);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- }
-
- /**
- * Write file version
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeFileVersion(PHPExcel_Shared_XMLWriter $objWriter = null)
- {
- $objWriter->startElement('fileVersion');
- $objWriter->writeAttribute('appName', 'xl');
- $objWriter->writeAttribute('lastEdited', '4');
- $objWriter->writeAttribute('lowestEdited', '4');
- $objWriter->writeAttribute('rupBuild', '4505');
- $objWriter->endElement();
- }
-
- /**
- * Write WorkbookPr
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeWorkbookPr(PHPExcel_Shared_XMLWriter $objWriter = null)
- {
- $objWriter->startElement('workbookPr');
-
- if (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) {
- $objWriter->writeAttribute('date1904', '1');
- }
-
- $objWriter->writeAttribute('codeName', 'ThisWorkbook');
-
- $objWriter->endElement();
- }
-
- /**
- * Write BookViews
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel $pPHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeBookViews(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
- {
- // bookViews
- $objWriter->startElement('bookViews');
-
- // workbookView
- $objWriter->startElement('workbookView');
-
- $objWriter->writeAttribute('activeTab', $pPHPExcel->getActiveSheetIndex());
- $objWriter->writeAttribute('autoFilterDateGrouping', '1');
- $objWriter->writeAttribute('firstSheet', '0');
- $objWriter->writeAttribute('minimized', '0');
- $objWriter->writeAttribute('showHorizontalScroll', '1');
- $objWriter->writeAttribute('showSheetTabs', '1');
- $objWriter->writeAttribute('showVerticalScroll', '1');
- $objWriter->writeAttribute('tabRatio', '600');
- $objWriter->writeAttribute('visibility', 'visible');
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write WorkbookProtection
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel $pPHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeWorkbookProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
- {
- if ($pPHPExcel->getSecurity()->isSecurityEnabled()) {
- $objWriter->startElement('workbookProtection');
- $objWriter->writeAttribute('lockRevision', ($pPHPExcel->getSecurity()->getLockRevision() ? 'true' : 'false'));
- $objWriter->writeAttribute('lockStructure', ($pPHPExcel->getSecurity()->getLockStructure() ? 'true' : 'false'));
- $objWriter->writeAttribute('lockWindows', ($pPHPExcel->getSecurity()->getLockWindows() ? 'true' : 'false'));
-
- if ($pPHPExcel->getSecurity()->getRevisionsPassword() != '') {
- $objWriter->writeAttribute('revisionsPassword', $pPHPExcel->getSecurity()->getRevisionsPassword());
- }
-
- if ($pPHPExcel->getSecurity()->getWorkbookPassword() != '') {
- $objWriter->writeAttribute('workbookPassword', $pPHPExcel->getSecurity()->getWorkbookPassword());
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write calcPr
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeCalcPr(PHPExcel_Shared_XMLWriter $objWriter = null, $recalcRequired = TRUE)
- {
- $objWriter->startElement('calcPr');
-
- $objWriter->writeAttribute('calcId', '124519');
- $objWriter->writeAttribute('calcMode', 'auto');
- // fullCalcOnLoad isn't needed if we've recalculating for the save
- $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? '0' : '1');
-
- $objWriter->endElement();
- }
-
- /**
- * Write sheets
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel $pPHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheets(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
- {
- // Write sheets
- $objWriter->startElement('sheets');
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- // sheet
- $this->_writeSheet(
- $objWriter,
- $pPHPExcel->getSheet($i)->getTitle(),
- ($i + 1),
- ($i + 1 + 3),
- $pPHPExcel->getSheet($i)->getSheetState()
- );
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write sheet
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param string $pSheetname Sheet name
- * @param int $pSheetId Sheet id
- * @param int $pRelId Relationship ID
- * @param string $sheetState Sheet state (visible, hidden, veryHidden)
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheet(PHPExcel_Shared_XMLWriter $objWriter = null, $pSheetname = '', $pSheetId = 1, $pRelId = 1, $sheetState = 'visible')
- {
- if ($pSheetname != '') {
- // Write sheet
- $objWriter->startElement('sheet');
- $objWriter->writeAttribute('name', $pSheetname);
- $objWriter->writeAttribute('sheetId', $pSheetId);
- if ($sheetState != 'visible' && $sheetState != '') {
- $objWriter->writeAttribute('state', $sheetState);
- }
- $objWriter->writeAttribute('r:id', 'rId' . $pRelId);
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write Defined Names
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel $pPHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDefinedNames(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
- {
- // Write defined names
- $objWriter->startElement('definedNames');
-
- // Named ranges
- if (count($pPHPExcel->getNamedRanges()) > 0) {
- // Named ranges
- $this->_writeNamedRanges($objWriter, $pPHPExcel);
- }
-
- // Other defined names
- $sheetCount = $pPHPExcel->getSheetCount();
- for ($i = 0; $i < $sheetCount; ++$i) {
- // definedName for autoFilter
- $this->_writeDefinedNameForAutofilter($objWriter, $pPHPExcel->getSheet($i), $i);
-
- // definedName for Print_Titles
- $this->_writeDefinedNameForPrintTitles($objWriter, $pPHPExcel->getSheet($i), $i);
-
- // definedName for Print_Area
- $this->_writeDefinedNameForPrintArea($objWriter, $pPHPExcel->getSheet($i), $i);
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write named ranges
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel $pPHPExcel
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeNamedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel)
- {
- // Loop named ranges
- $namedRanges = $pPHPExcel->getNamedRanges();
- foreach ($namedRanges as $namedRange) {
- $this->_writeDefinedNameForNamedRange($objWriter, $namedRange);
- }
- }
-
- /**
- * Write Defined Name for named range
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_NamedRange $pNamedRange
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDefinedNameForNamedRange(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_NamedRange $pNamedRange)
- {
- // definedName for named range
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', $pNamedRange->getName());
- if ($pNamedRange->getLocalOnly()) {
- $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope()));
- }
-
- // Create absolute coordinate and write as raw text
- $range = PHPExcel_Cell::splitRange($pNamedRange->getRange());
- for ($i = 0; $i < count($range); $i++) {
- $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteReference($range[$i][0]);
- if (isset($range[$i][1])) {
- $range[$i][1] = PHPExcel_Cell::absoluteReference($range[$i][1]);
- }
- }
- $range = PHPExcel_Cell::buildRange($range);
-
- $objWriter->writeRawData($range);
-
- $objWriter->endElement();
- }
-
- /**
- * Write Defined Name for autoFilter
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet
- * @param int $pSheetId
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDefinedNameForAutofilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0)
- {
- // definedName for autoFilter
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
- $objWriter->writeAttribute('localSheetId', $pSheetId);
- $objWriter->writeAttribute('hidden', '1');
-
- // Create absolute coordinate and write as raw text
- $range = PHPExcel_Cell::splitRange($autoFilterRange);
- $range = $range[0];
- // Strip any worksheet ref so we can make the cell ref absolute
- if (strpos($range[0],'!') !== false) {
- list($ws,$range[0]) = explode('!',$range[0]);
- }
-
- $range[0] = PHPExcel_Cell::absoluteCoordinate($range[0]);
- $range[1] = PHPExcel_Cell::absoluteCoordinate($range[1]);
- $range = implode(':', $range);
-
- $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Defined Name for PrintTitles
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet
- * @param int $pSheetId
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDefinedNameForPrintTitles(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0)
- {
- // definedName for PrintTitles
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', '_xlnm.Print_Titles');
- $objWriter->writeAttribute('localSheetId', $pSheetId);
-
- // Setting string
- $settingString = '';
-
- // Columns to repeat
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
- $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
-
- $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
- }
-
- // Rows to repeat
- if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
- $settingString .= ',';
- }
-
- $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
-
- $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
- }
-
- $objWriter->writeRawData($settingString);
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Defined Name for PrintTitles
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet
- * @param int $pSheetId
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDefinedNameForPrintArea(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0)
- {
- // definedName for PrintArea
- if ($pSheet->getPageSetup()->isPrintAreaSet()) {
- $objWriter->startElement('definedName');
- $objWriter->writeAttribute('name', '_xlnm.Print_Area');
- $objWriter->writeAttribute('localSheetId', $pSheetId);
-
- // Setting string
- $settingString = '';
-
- // Print area
- $printArea = PHPExcel_Cell::splitRange($pSheet->getPageSetup()->getPrintArea());
-
- $chunks = array();
- foreach ($printArea as $printAreaRect) {
- $printAreaRect[0] = PHPExcel_Cell::absoluteReference($printAreaRect[0]);
- $printAreaRect[1] = PHPExcel_Cell::absoluteReference($printAreaRect[1]);
- $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
- }
-
- $objWriter->writeRawData(implode(',', $chunks));
-
- $objWriter->endElement();
- }
- }
+ /**
+ * Write workbook to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeWorkbook(PHPExcel $pPHPExcel = null, $recalcRequired = false)
+ {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // workbook
+ $objWriter->startElement('workbook');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+
+ // fileVersion
+ $this->writeFileVersion($objWriter);
+
+ // workbookPr
+ $this->writeWorkbookPr($objWriter);
+
+ // workbookProtection
+ $this->writeWorkbookProtection($objWriter, $pPHPExcel);
+
+ // bookViews
+ if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
+ $this->writeBookViews($objWriter, $pPHPExcel);
+ }
+
+ // sheets
+ $this->writeSheets($objWriter, $pPHPExcel);
+
+ // definedNames
+ $this->writeDefinedNames($objWriter, $pPHPExcel);
+
+ // calcPr
+ $this->writeCalcPr($objWriter, $recalcRequired);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write file version
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeFileVersion(PHPExcel_Shared_XMLWriter $objWriter = null)
+ {
+ $objWriter->startElement('fileVersion');
+ $objWriter->writeAttribute('appName', 'xl');
+ $objWriter->writeAttribute('lastEdited', '4');
+ $objWriter->writeAttribute('lowestEdited', '4');
+ $objWriter->writeAttribute('rupBuild', '4505');
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write WorkbookPr
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeWorkbookPr(PHPExcel_Shared_XMLWriter $objWriter = null)
+ {
+ $objWriter->startElement('workbookPr');
+
+ if (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) {
+ $objWriter->writeAttribute('date1904', '1');
+ }
+
+ $objWriter->writeAttribute('codeName', 'ThisWorkbook');
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write BookViews
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel $pPHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeBookViews(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
+ {
+ // bookViews
+ $objWriter->startElement('bookViews');
+
+ // workbookView
+ $objWriter->startElement('workbookView');
+
+ $objWriter->writeAttribute('activeTab', $pPHPExcel->getActiveSheetIndex());
+ $objWriter->writeAttribute('autoFilterDateGrouping', '1');
+ $objWriter->writeAttribute('firstSheet', '0');
+ $objWriter->writeAttribute('minimized', '0');
+ $objWriter->writeAttribute('showHorizontalScroll', '1');
+ $objWriter->writeAttribute('showSheetTabs', '1');
+ $objWriter->writeAttribute('showVerticalScroll', '1');
+ $objWriter->writeAttribute('tabRatio', '600');
+ $objWriter->writeAttribute('visibility', 'visible');
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write WorkbookProtection
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel $pPHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeWorkbookProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
+ {
+ if ($pPHPExcel->getSecurity()->isSecurityEnabled()) {
+ $objWriter->startElement('workbookProtection');
+ $objWriter->writeAttribute('lockRevision', ($pPHPExcel->getSecurity()->getLockRevision() ? 'true' : 'false'));
+ $objWriter->writeAttribute('lockStructure', ($pPHPExcel->getSecurity()->getLockStructure() ? 'true' : 'false'));
+ $objWriter->writeAttribute('lockWindows', ($pPHPExcel->getSecurity()->getLockWindows() ? 'true' : 'false'));
+
+ if ($pPHPExcel->getSecurity()->getRevisionsPassword() != '') {
+ $objWriter->writeAttribute('revisionsPassword', $pPHPExcel->getSecurity()->getRevisionsPassword());
+ }
+
+ if ($pPHPExcel->getSecurity()->getWorkbookPassword() != '') {
+ $objWriter->writeAttribute('workbookPassword', $pPHPExcel->getSecurity()->getWorkbookPassword());
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write calcPr
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCalcPr(PHPExcel_Shared_XMLWriter $objWriter = null, $recalcRequired = true)
+ {
+ $objWriter->startElement('calcPr');
+
+ // Set the calcid to a higher value than Excel itself will use, otherwise Excel will always recalc
+ // If MS Excel does do a recalc, then users opening a file in MS Excel will be prompted to save on exit
+ // because the file has changed
+ $objWriter->writeAttribute('calcId', '999999');
+ $objWriter->writeAttribute('calcMode', 'auto');
+ // fullCalcOnLoad isn't needed if we've recalculating for the save
+ $objWriter->writeAttribute('calcCompleted', ($recalcRequired) ? 1 : 0);
+ $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? 0 : 1);
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write sheets
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel $pPHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheets(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
+ {
+ // Write sheets
+ $objWriter->startElement('sheets');
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ // sheet
+ $this->writeSheet(
+ $objWriter,
+ $pPHPExcel->getSheet($i)->getTitle(),
+ ($i + 1),
+ ($i + 1 + 3),
+ $pPHPExcel->getSheet($i)->getSheetState()
+ );
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write sheet
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param string $pSheetname Sheet name
+ * @param int $pSheetId Sheet id
+ * @param int $pRelId Relationship ID
+ * @param string $sheetState Sheet state (visible, hidden, veryHidden)
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheet(PHPExcel_Shared_XMLWriter $objWriter = null, $pSheetname = '', $pSheetId = 1, $pRelId = 1, $sheetState = 'visible')
+ {
+ if ($pSheetname != '') {
+ // Write sheet
+ $objWriter->startElement('sheet');
+ $objWriter->writeAttribute('name', $pSheetname);
+ $objWriter->writeAttribute('sheetId', $pSheetId);
+ if ($sheetState != 'visible' && $sheetState != '') {
+ $objWriter->writeAttribute('state', $sheetState);
+ }
+ $objWriter->writeAttribute('r:id', 'rId' . $pRelId);
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write Defined Names
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel $pPHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDefinedNames(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null)
+ {
+ // Write defined names
+ $objWriter->startElement('definedNames');
+
+ // Named ranges
+ if (count($pPHPExcel->getNamedRanges()) > 0) {
+ // Named ranges
+ $this->writeNamedRanges($objWriter, $pPHPExcel);
+ }
+
+ // Other defined names
+ $sheetCount = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheetCount; ++$i) {
+ // definedName for autoFilter
+ $this->writeDefinedNameForAutofilter($objWriter, $pPHPExcel->getSheet($i), $i);
+
+ // definedName for Print_Titles
+ $this->writeDefinedNameForPrintTitles($objWriter, $pPHPExcel->getSheet($i), $i);
+
+ // definedName for Print_Area
+ $this->writeDefinedNameForPrintArea($objWriter, $pPHPExcel->getSheet($i), $i);
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write named ranges
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel $pPHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeNamedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel)
+ {
+ // Loop named ranges
+ $namedRanges = $pPHPExcel->getNamedRanges();
+ foreach ($namedRanges as $namedRange) {
+ $this->writeDefinedNameForNamedRange($objWriter, $namedRange);
+ }
+ }
+
+ /**
+ * Write Defined Name for named range
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_NamedRange $pNamedRange
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDefinedNameForNamedRange(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_NamedRange $pNamedRange)
+ {
+ // definedName for named range
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', $pNamedRange->getName());
+ if ($pNamedRange->getLocalOnly()) {
+ $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope()));
+ }
+
+ // Create absolute coordinate and write as raw text
+ $range = PHPExcel_Cell::splitRange($pNamedRange->getRange());
+ for ($i = 0; $i < count($range); $i++) {
+ $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteReference($range[$i][0]);
+ if (isset($range[$i][1])) {
+ $range[$i][1] = PHPExcel_Cell::absoluteReference($range[$i][1]);
+ }
+ }
+ $range = PHPExcel_Cell::buildRange($range);
+
+ $objWriter->writeRawData($range);
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Defined Name for autoFilter
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet
+ * @param int $pSheetId
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDefinedNameForAutofilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0)
+ {
+ // definedName for autoFilter
+ $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
+ $objWriter->writeAttribute('localSheetId', $pSheetId);
+ $objWriter->writeAttribute('hidden', '1');
+
+ // Create absolute coordinate and write as raw text
+ $range = PHPExcel_Cell::splitRange($autoFilterRange);
+ $range = $range[0];
+ // Strip any worksheet ref so we can make the cell ref absolute
+ if (strpos($range[0], '!') !== false) {
+ list($ws, $range[0]) = explode('!', $range[0]);
+ }
+
+ $range[0] = PHPExcel_Cell::absoluteCoordinate($range[0]);
+ $range[1] = PHPExcel_Cell::absoluteCoordinate($range[1]);
+ $range = implode(':', $range);
+
+ $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Defined Name for PrintTitles
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet
+ * @param int $pSheetId
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDefinedNameForPrintTitles(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0)
+ {
+ // definedName for PrintTitles
+ if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', '_xlnm.Print_Titles');
+ $objWriter->writeAttribute('localSheetId', $pSheetId);
+
+ // Setting string
+ $settingString = '';
+
+ // Columns to repeat
+ if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
+ $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
+
+ $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
+ }
+
+ // Rows to repeat
+ if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
+ if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
+ $settingString .= ',';
+ }
+
+ $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
+
+ $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
+ }
+
+ $objWriter->writeRawData($settingString);
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Defined Name for PrintTitles
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet
+ * @param int $pSheetId
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDefinedNameForPrintArea(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0)
+ {
+ // definedName for PrintArea
+ if ($pSheet->getPageSetup()->isPrintAreaSet()) {
+ $objWriter->startElement('definedName');
+ $objWriter->writeAttribute('name', '_xlnm.Print_Area');
+ $objWriter->writeAttribute('localSheetId', $pSheetId);
+
+ // Setting string
+ $settingString = '';
+
+ // Print area
+ $printArea = PHPExcel_Cell::splitRange($pSheet->getPageSetup()->getPrintArea());
+
+ $chunks = array();
+ foreach ($printArea as $printAreaRect) {
+ $printAreaRect[0] = PHPExcel_Cell::absoluteReference($printAreaRect[0]);
+ $printAreaRect[1] = PHPExcel_Cell::absoluteReference($printAreaRect[1]);
+ $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
+ }
+
+ $objWriter->writeRawData(implode(',', $chunks));
+
+ $objWriter->endElement();
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php
index 977f172de..c211403e3 100644
--- a/Classes/PHPExcel/Writer/Excel2007/Worksheet.php
+++ b/Classes/PHPExcel/Writer/Excel2007/Worksheet.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -19,10 +19,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
- * @package PHPExcel_Writer_Excel2007
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
- * @version ##VERSION##, ##DATE##
+ * @package PHPExcel_Writer_Excel2007
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @version ##VERSION##, ##DATE##
*/
@@ -30,1188 +30,1190 @@
* PHPExcel_Writer_Excel2007_Worksheet
*
* @category PHPExcel
- * @package PHPExcel_Writer_Excel2007
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @package PHPExcel_Writer_Excel2007
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_WriterPart
{
- /**
- * Write worksheet to XML format
- *
- * @param PHPExcel_Worksheet $pSheet
- * @param string[] $pStringTable
- * @param boolean $includeCharts Flag indicating if we should write charts
- * @return string XML Output
- * @throws PHPExcel_Writer_Exception
- */
- public function writeWorksheet($pSheet = null, $pStringTable = null, $includeCharts = FALSE)
- {
- if (!is_null($pSheet)) {
- // Create XML writer
- $objWriter = null;
- if ($this->getParentWriter()->getUseDiskCaching()) {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
- } else {
- $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
- }
-
- // XML header
- $objWriter->startDocument('1.0','UTF-8','yes');
-
- // Worksheet
- $objWriter->startElement('worksheet');
- $objWriter->writeAttribute('xml:space', 'preserve');
- $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
-
- // sheetPr
- $this->_writeSheetPr($objWriter, $pSheet);
-
- // Dimension
- $this->_writeDimension($objWriter, $pSheet);
-
- // sheetViews
- $this->_writeSheetViews($objWriter, $pSheet);
-
- // sheetFormatPr
- $this->_writeSheetFormatPr($objWriter, $pSheet);
-
- // cols
- $this->_writeCols($objWriter, $pSheet);
-
- // sheetData
- $this->_writeSheetData($objWriter, $pSheet, $pStringTable);
-
- // sheetProtection
- $this->_writeSheetProtection($objWriter, $pSheet);
-
- // protectedRanges
- $this->_writeProtectedRanges($objWriter, $pSheet);
-
- // autoFilter
- $this->_writeAutoFilter($objWriter, $pSheet);
-
- // mergeCells
- $this->_writeMergeCells($objWriter, $pSheet);
-
- // conditionalFormatting
- $this->_writeConditionalFormatting($objWriter, $pSheet);
-
- // dataValidations
- $this->_writeDataValidations($objWriter, $pSheet);
-
- // hyperlinks
- $this->_writeHyperlinks($objWriter, $pSheet);
-
- // Print options
- $this->_writePrintOptions($objWriter, $pSheet);
-
- // Page margins
- $this->_writePageMargins($objWriter, $pSheet);
-
- // Page setup
- $this->_writePageSetup($objWriter, $pSheet);
-
- // Header / footer
- $this->_writeHeaderFooter($objWriter, $pSheet);
-
- // Breaks
- $this->_writeBreaks($objWriter, $pSheet);
-
- // Drawings and/or Charts
- $this->_writeDrawings($objWriter, $pSheet, $includeCharts);
-
- // LegacyDrawing
- $this->_writeLegacyDrawing($objWriter, $pSheet);
-
- // LegacyDrawingHF
- $this->_writeLegacyDrawingHF($objWriter, $pSheet);
-
- $objWriter->endElement();
-
- // Return
- return $objWriter->getData();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed.");
- }
- }
-
- /**
- * Write SheetPr
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheetPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // sheetPr
- $objWriter->startElement('sheetPr');
- //$objWriter->writeAttribute('codeName', $pSheet->getTitle());
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- $objWriter->writeAttribute('filterMode', 1);
- $pSheet->getAutoFilter()->showHideRows();
- }
-
- // tabColor
- if ($pSheet->isTabColorSet()) {
- $objWriter->startElement('tabColor');
- $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB());
- $objWriter->endElement();
- }
-
- // outlinePr
- $objWriter->startElement('outlinePr');
- $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0'));
- $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0'));
- $objWriter->endElement();
-
- // pageSetUpPr
- if ($pSheet->getPageSetup()->getFitToPage()) {
- $objWriter->startElement('pageSetUpPr');
- $objWriter->writeAttribute('fitToPage', '1');
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Dimension
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDimension(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // dimension
- $objWriter->startElement('dimension');
- $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension());
- $objWriter->endElement();
- }
-
- /**
- * Write SheetViews
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheetViews(PHPExcel_Shared_XMLWriter $objWriter = NULL, PHPExcel_Worksheet $pSheet = NULL)
- {
- // sheetViews
- $objWriter->startElement('sheetViews');
-
- // Sheet selected?
- $sheetSelected = false;
- if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex())
- $sheetSelected = true;
-
-
- // sheetView
- $objWriter->startElement('sheetView');
- $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
- $objWriter->writeAttribute('workbookViewId', '0');
-
- // Zoom scales
- if ($pSheet->getSheetView()->getZoomScale() != 100) {
- $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale());
- }
- if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) {
- $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal());
- }
-
- // View Layout Type
- if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) {
- $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView());
- }
-
- // Gridlines
- if ($pSheet->getShowGridlines()) {
- $objWriter->writeAttribute('showGridLines', 'true');
- } else {
- $objWriter->writeAttribute('showGridLines', 'false');
- }
-
- // Row and column headers
- if ($pSheet->getShowRowColHeaders()) {
- $objWriter->writeAttribute('showRowColHeaders', '1');
- } else {
- $objWriter->writeAttribute('showRowColHeaders', '0');
- }
-
- // Right-to-left
- if ($pSheet->getRightToLeft()) {
- $objWriter->writeAttribute('rightToLeft', 'true');
- }
-
- $activeCell = $pSheet->getActiveCell();
-
- // Pane
- $pane = '';
- $topLeftCell = $pSheet->getFreezePane();
- if (($topLeftCell != '') && ($topLeftCell != 'A1')) {
- $activeCell = $topLeftCell;
- // Calculate freeze coordinates
- $xSplit = $ySplit = 0;
-
- list($xSplit, $ySplit) = PHPExcel_Cell::coordinateFromString($topLeftCell);
- $xSplit = PHPExcel_Cell::columnIndexFromString($xSplit);
-
- // pane
- $pane = 'topRight';
- $objWriter->startElement('pane');
- if ($xSplit > 1)
- $objWriter->writeAttribute('xSplit', $xSplit - 1);
- if ($ySplit > 1) {
- $objWriter->writeAttribute('ySplit', $ySplit - 1);
- $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft';
- }
- $objWriter->writeAttribute('topLeftCell', $topLeftCell);
- $objWriter->writeAttribute('activePane', $pane);
- $objWriter->writeAttribute('state', 'frozen');
- $objWriter->endElement();
-
- if (($xSplit > 1) && ($ySplit > 1)) {
- // Write additional selections if more than two panes (ie both an X and a Y split)
- $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'topRight'); $objWriter->endElement();
- $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement();
- }
- }
-
- // Selection
-// if ($pane != '') {
- // Only need to write selection element if we have a split pane
- // We cheat a little by over-riding the active cell selection, setting it to the split cell
- $objWriter->startElement('selection');
- if ($pane != '') {
- $objWriter->writeAttribute('pane', $pane);
- }
- $objWriter->writeAttribute('activeCell', $activeCell);
- $objWriter->writeAttribute('sqref', $activeCell);
- $objWriter->endElement();
-// }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
-
- /**
- * Write SheetFormatPr
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheetFormatPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // sheetFormatPr
- $objWriter->startElement('sheetFormatPr');
-
- // Default row height
- if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) {
- $objWriter->writeAttribute('customHeight', 'true');
- $objWriter->writeAttribute('defaultRowHeight', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultRowDimension()->getRowHeight()));
- } else {
- $objWriter->writeAttribute('defaultRowHeight', '14.4');
- }
-
- // Set Zero Height row
- if ((string)$pSheet->getDefaultRowDimension()->getzeroHeight() == '1' ||
- strtolower((string)$pSheet->getDefaultRowDimension()->getzeroHeight()) == 'true' ) {
- $objWriter->writeAttribute('zeroHeight', '1');
- }
-
- // Default column width
- if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) {
- $objWriter->writeAttribute('defaultColWidth', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultColumnDimension()->getWidth()));
- }
-
- // Outline level - row
- $outlineLevelRow = 0;
- foreach ($pSheet->getRowDimensions() as $dimension) {
- if ($dimension->getOutlineLevel() > $outlineLevelRow) {
- $outlineLevelRow = $dimension->getOutlineLevel();
- }
- }
- $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow);
-
- // Outline level - column
- $outlineLevelCol = 0;
- foreach ($pSheet->getColumnDimensions() as $dimension) {
- if ($dimension->getOutlineLevel() > $outlineLevelCol) {
- $outlineLevelCol = $dimension->getOutlineLevel();
- }
- }
- $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol);
-
- $objWriter->endElement();
- }
-
- /**
- * Write Cols
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeCols(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // cols
- if (count($pSheet->getColumnDimensions()) > 0) {
- $objWriter->startElement('cols');
-
- $pSheet->calculateColumnWidths();
-
- // Loop through column dimensions
- foreach ($pSheet->getColumnDimensions() as $colDimension) {
- // col
- $objWriter->startElement('col');
- $objWriter->writeAttribute('min', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex()));
- $objWriter->writeAttribute('max', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex()));
-
- if ($colDimension->getWidth() < 0) {
- // No width set, apply default of 10
- $objWriter->writeAttribute('width', '9.10');
- } else {
- // Width set
- $objWriter->writeAttribute('width', PHPExcel_Shared_String::FormatNumber($colDimension->getWidth()));
- }
-
- // Column visibility
- if ($colDimension->getVisible() == false) {
- $objWriter->writeAttribute('hidden', 'true');
- }
-
- // Auto size?
- if ($colDimension->getAutoSize()) {
- $objWriter->writeAttribute('bestFit', 'true');
- }
-
- // Custom width?
- if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) {
- $objWriter->writeAttribute('customWidth', 'true');
- }
-
- // Collapsed
- if ($colDimension->getCollapsed() == true) {
- $objWriter->writeAttribute('collapsed', 'true');
- }
-
- // Outline level
- if ($colDimension->getOutlineLevel() > 0) {
- $objWriter->writeAttribute('outlineLevel', $colDimension->getOutlineLevel());
- }
-
- // Style
- $objWriter->writeAttribute('style', $colDimension->getXfIndex());
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write SheetProtection
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheetProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // sheetProtection
- $objWriter->startElement('sheetProtection');
-
- if ($pSheet->getProtection()->getPassword() != '') {
- $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword());
- }
-
- $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false'));
- $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false'));
- $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false'));
- $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false'));
- $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false'));
- $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false'));
- $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false'));
- $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false'));
- $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false'));
- $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false'));
- $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false'));
- $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false'));
- $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false'));
- $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false'));
- $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false'));
- $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false'));
- $objWriter->endElement();
- }
-
- /**
- * Write ConditionalFormatting
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeConditionalFormatting(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // Conditional id
- $id = 1;
-
- // Loop through styles in the current worksheet
- foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
- foreach ($conditionalStyles as $conditional) {
- // WHY was this again?
- // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ) == '') {
- // continue;
- // }
- if ($conditional->getConditionType() != PHPExcel_Style_Conditional::CONDITION_NONE) {
- // conditionalFormatting
- $objWriter->startElement('conditionalFormatting');
- $objWriter->writeAttribute('sqref', $cellCoordinate);
-
- // cfRule
- $objWriter->startElement('cfRule');
- $objWriter->writeAttribute('type', $conditional->getConditionType());
- $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ));
- $objWriter->writeAttribute('priority', $id++);
-
- if (($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS
- ||
- $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT)
- && $conditional->getOperatorType() != PHPExcel_Style_Conditional::OPERATOR_NONE) {
- $objWriter->writeAttribute('operator', $conditional->getOperatorType());
- }
-
- if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
- && !is_null($conditional->getText())) {
- $objWriter->writeAttribute('text', $conditional->getText());
- }
-
- if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_CONTAINSTEXT
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))');
- } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BEGINSWITH
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
- } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_ENDSWITH
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
- } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
- && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_NOTCONTAINS
- && !is_null($conditional->getText())) {
- $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))');
- } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS
- || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
- || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) {
- foreach ($conditional->getConditions() as $formula) {
- // Formula
- $objWriter->writeElement('formula', $formula);
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
- }
- }
-
- /**
- * Write DataValidations
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDataValidations(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // Datavalidation collection
- $dataValidationCollection = $pSheet->getDataValidationCollection();
-
- // Write data validations?
- if (!empty($dataValidationCollection)) {
- $objWriter->startElement('dataValidations');
- $objWriter->writeAttribute('count', count($dataValidationCollection));
-
- foreach ($dataValidationCollection as $coordinate => $dv) {
- $objWriter->startElement('dataValidation');
-
- if ($dv->getType() != '') {
- $objWriter->writeAttribute('type', $dv->getType());
- }
-
- if ($dv->getErrorStyle() != '') {
- $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
- }
-
- if ($dv->getOperator() != '') {
- $objWriter->writeAttribute('operator', $dv->getOperator());
- }
-
- $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
- $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
- $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
- $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
-
- if ($dv->getErrorTitle() !== '') {
- $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
- }
- if ($dv->getError() !== '') {
- $objWriter->writeAttribute('error', $dv->getError());
- }
- if ($dv->getPromptTitle() !== '') {
- $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
- }
- if ($dv->getPrompt() !== '') {
- $objWriter->writeAttribute('prompt', $dv->getPrompt());
- }
-
- $objWriter->writeAttribute('sqref', $coordinate);
-
- if ($dv->getFormula1() !== '') {
- $objWriter->writeElement('formula1', $dv->getFormula1());
- }
- if ($dv->getFormula2() !== '') {
- $objWriter->writeElement('formula2', $dv->getFormula2());
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write Hyperlinks
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeHyperlinks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // Hyperlink collection
- $hyperlinkCollection = $pSheet->getHyperlinkCollection();
-
- // Relation ID
- $relationId = 1;
-
- // Write hyperlinks?
- if (!empty($hyperlinkCollection)) {
- $objWriter->startElement('hyperlinks');
-
- foreach ($hyperlinkCollection as $coordinate => $hyperlink) {
- $objWriter->startElement('hyperlink');
-
- $objWriter->writeAttribute('ref', $coordinate);
- if (!$hyperlink->isInternal()) {
- $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId);
- ++$relationId;
- } else {
- $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl()));
- }
-
- if ($hyperlink->getTooltip() != '') {
- $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip());
- }
-
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write ProtectedRanges
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeProtectedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- if (count($pSheet->getProtectedCells()) > 0) {
- // protectedRanges
- $objWriter->startElement('protectedRanges');
-
- // Loop protectedRanges
- foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) {
- // protectedRange
- $objWriter->startElement('protectedRange');
- $objWriter->writeAttribute('name', 'p' . md5($protectedCell));
- $objWriter->writeAttribute('sqref', $protectedCell);
- if (!empty($passwordHash)) {
- $objWriter->writeAttribute('password', $passwordHash);
- }
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write MergeCells
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeMergeCells(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- if (count($pSheet->getMergeCells()) > 0) {
- // mergeCells
- $objWriter->startElement('mergeCells');
-
- // Loop mergeCells
- foreach ($pSheet->getMergeCells() as $mergeCell) {
- // mergeCell
- $objWriter->startElement('mergeCell');
- $objWriter->writeAttribute('ref', $mergeCell);
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write PrintOptions
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePrintOptions(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // printOptions
- $objWriter->startElement('printOptions');
-
- $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true': 'false'));
- $objWriter->writeAttribute('gridLinesSet', 'true');
-
- if ($pSheet->getPageSetup()->getHorizontalCentered()) {
- $objWriter->writeAttribute('horizontalCentered', 'true');
- }
-
- if ($pSheet->getPageSetup()->getVerticalCentered()) {
- $objWriter->writeAttribute('verticalCentered', 'true');
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write PageMargins
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePageMargins(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // pageMargins
- $objWriter->startElement('pageMargins');
- $objWriter->writeAttribute('left', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()));
- $objWriter->writeAttribute('right', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()));
- $objWriter->writeAttribute('top', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()));
- $objWriter->writeAttribute('bottom', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()));
- $objWriter->writeAttribute('header', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getHeader()));
- $objWriter->writeAttribute('footer', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getFooter()));
- $objWriter->endElement();
- }
-
- /**
- * Write AutoFilter
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeAutoFilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- // autoFilter
- $objWriter->startElement('autoFilter');
-
- // Strip any worksheet reference from the filter coordinates
- $range = PHPExcel_Cell::splitRange($autoFilterRange);
- $range = $range[0];
- // Strip any worksheet ref
- if (strpos($range[0],'!') !== false) {
- list($ws,$range[0]) = explode('!',$range[0]);
- }
- $range = implode(':', $range);
-
- $objWriter->writeAttribute('ref', str_replace('$','',$range));
-
- $columns = $pSheet->getAutoFilter()->getColumns();
- if (count($columns > 0)) {
- foreach($columns as $columnID => $column) {
- $rules = $column->getRules();
- if (count($rules > 0)) {
- $objWriter->startElement('filterColumn');
- $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID));
-
- $objWriter->startElement( $column->getFilterType());
- if ($column->getJoin() == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) {
- $objWriter->writeAttribute('and', 1);
- }
-
- foreach ($rules as $rule) {
- if (($column->getFilterType() === PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) &&
- ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) &&
- ($rule->getValue() === '')) {
- // Filter rule for Blanks
- $objWriter->writeAttribute('blank', 1);
- } elseif($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) {
- // Dynamic Filter Rule
- $objWriter->writeAttribute('type', $rule->getGrouping());
- $val = $column->getAttribute('val');
- if ($val !== NULL) {
- $objWriter->writeAttribute('val', $val);
- }
- $maxVal = $column->getAttribute('maxVal');
- if ($maxVal !== NULL) {
- $objWriter->writeAttribute('maxVal', $maxVal);
- }
- } elseif($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) {
- // Top 10 Filter Rule
- $objWriter->writeAttribute('val', $rule->getValue());
- $objWriter->writeAttribute('percent', (($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0'));
- $objWriter->writeAttribute('top', (($rule->getGrouping() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0'));
- } else {
- // Filter, DateGroupItem or CustomFilter
- $objWriter->startElement($rule->getRuleType());
-
- if ($rule->getOperator() !== PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) {
- $objWriter->writeAttribute('operator', $rule->getOperator());
- }
- if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) {
- // Date Group filters
- foreach($rule->getValue() as $key => $value) {
- if ($value > '') $objWriter->writeAttribute($key, $value);
- }
- $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping());
- } else {
- $objWriter->writeAttribute('val', $rule->getValue());
- }
-
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
-
- $objWriter->endElement();
- }
- }
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write PageSetup
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writePageSetup(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // pageSetup
- $objWriter->startElement('pageSetup');
- $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize());
- $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation());
-
- if (!is_null($pSheet->getPageSetup()->getScale())) {
- $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale());
- }
- if (!is_null($pSheet->getPageSetup()->getFitToHeight())) {
- $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight());
- } else {
- $objWriter->writeAttribute('fitToHeight', '0');
- }
- if (!is_null($pSheet->getPageSetup()->getFitToWidth())) {
- $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth());
- } else {
- $objWriter->writeAttribute('fitToWidth', '0');
- }
- if (!is_null($pSheet->getPageSetup()->getFirstPageNumber())) {
- $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber());
- $objWriter->writeAttribute('useFirstPageNumber', '1');
- }
-
- $objWriter->endElement();
- }
-
- /**
- * Write Header / Footer
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeHeaderFooter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // headerFooter
- $objWriter->startElement('headerFooter');
- $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
- $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
- $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
- $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
-
- $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader());
- $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter());
- $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader());
- $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter());
- $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader());
- $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter());
- $objWriter->endElement();
- }
-
- /**
- * Write Breaks
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeBreaks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // Get row and column breaks
- $aRowBreaks = array();
- $aColumnBreaks = array();
- foreach ($pSheet->getBreaks() as $cell => $breakType) {
- if ($breakType == PHPExcel_Worksheet::BREAK_ROW) {
- $aRowBreaks[] = $cell;
- } else if ($breakType == PHPExcel_Worksheet::BREAK_COLUMN) {
- $aColumnBreaks[] = $cell;
- }
- }
-
- // rowBreaks
- if (!empty($aRowBreaks)) {
- $objWriter->startElement('rowBreaks');
- $objWriter->writeAttribute('count', count($aRowBreaks));
- $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks));
-
- foreach ($aRowBreaks as $cell) {
- $coords = PHPExcel_Cell::coordinateFromString($cell);
-
- $objWriter->startElement('brk');
- $objWriter->writeAttribute('id', $coords[1]);
- $objWriter->writeAttribute('man', '1');
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
-
- // Second, write column breaks
- if (!empty($aColumnBreaks)) {
- $objWriter->startElement('colBreaks');
- $objWriter->writeAttribute('count', count($aColumnBreaks));
- $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks));
-
- foreach ($aColumnBreaks as $cell) {
- $coords = PHPExcel_Cell::coordinateFromString($cell);
-
- $objWriter->startElement('brk');
- $objWriter->writeAttribute('id', PHPExcel_Cell::columnIndexFromString($coords[0]) - 1);
- $objWriter->writeAttribute('man', '1');
- $objWriter->endElement();
- }
-
- $objWriter->endElement();
- }
- }
-
- /**
- * Write SheetData
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @param string[] $pStringTable String table
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeSheetData(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pStringTable = null)
- {
- if (is_array($pStringTable)) {
- // Flipped stringtable, for faster index searching
- $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable);
-
- // sheetData
- $objWriter->startElement('sheetData');
-
- // Get column count
- $colCount = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn());
-
- // Highest row number
- $highestRow = $pSheet->getHighestRow();
-
- // Loop through cells
- $cellsByRow = array();
- foreach ($pSheet->getCellCollection() as $cellID) {
- $cellAddress = PHPExcel_Cell::coordinateFromString($cellID);
- $cellsByRow[$cellAddress[1]][] = $cellID;
- }
-
- $currentRow = 0;
- while($currentRow++ < $highestRow) {
- // Get row dimension
- $rowDimension = $pSheet->getRowDimension($currentRow);
-
- // Write current row?
- $writeCurrentRow = isset($cellsByRow[$currentRow]) ||
- $rowDimension->getRowHeight() >= 0 ||
- $rowDimension->getVisible() == false ||
- $rowDimension->getCollapsed() == true ||
- $rowDimension->getOutlineLevel() > 0 ||
- $rowDimension->getXfIndex() !== null;
-
- if ($writeCurrentRow) {
- // Start a new row
- $objWriter->startElement('row');
- $objWriter->writeAttribute('r', $currentRow);
- $objWriter->writeAttribute('spans', '1:' . $colCount);
-
- // Row dimensions
- if ($rowDimension->getRowHeight() >= 0) {
- $objWriter->writeAttribute('customHeight', '1');
- $objWriter->writeAttribute('ht', PHPExcel_Shared_String::FormatNumber($rowDimension->getRowHeight()));
- }
-
- // Row visibility
- if ($rowDimension->getVisible() == false) {
- $objWriter->writeAttribute('hidden', 'true');
- }
-
- // Collapsed
- if ($rowDimension->getCollapsed() == true) {
- $objWriter->writeAttribute('collapsed', 'true');
- }
-
- // Outline level
- if ($rowDimension->getOutlineLevel() > 0) {
- $objWriter->writeAttribute('outlineLevel', $rowDimension->getOutlineLevel());
- }
-
- // Style
- if ($rowDimension->getXfIndex() !== null) {
- $objWriter->writeAttribute('s', $rowDimension->getXfIndex());
- $objWriter->writeAttribute('customFormat', '1');
- }
-
- // Write cells
- if (isset($cellsByRow[$currentRow])) {
- foreach($cellsByRow[$currentRow] as $cellAddress) {
- // Write cell
- $this->_writeCell($objWriter, $pSheet, $cellAddress, $pStringTable, $aFlippedStringTable);
- }
- }
-
- // End row
- $objWriter->endElement();
- }
- }
-
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write Cell
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @param PHPExcel_Cell $pCellAddress Cell Address
- * @param string[] $pStringTable String table
- * @param string[] $pFlippedStringTable String table (flipped), for faster index searching
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeCell(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pCellAddress = null, $pStringTable = null, $pFlippedStringTable = null)
- {
- if (is_array($pStringTable) && is_array($pFlippedStringTable)) {
- // Cell
- $pCell = $pSheet->getCell($pCellAddress);
- $objWriter->startElement('c');
- $objWriter->writeAttribute('r', $pCellAddress);
-
- // Sheet styles
- if ($pCell->getXfIndex() != '') {
- $objWriter->writeAttribute('s', $pCell->getXfIndex());
- }
-
- // If cell value is supplied, write cell value
- $cellValue = $pCell->getValue();
- if (is_object($cellValue) || $cellValue !== '') {
- // Map type
- $mappedType = $pCell->getDataType();
-
- // Write data type depending on its type
- switch (strtolower($mappedType)) {
- case 'inlinestr': // Inline string
- case 's': // String
- case 'b': // Boolean
- $objWriter->writeAttribute('t', $mappedType);
- break;
- case 'f': // Formula
- $calculatedValue = null;
- if ($this->getParentWriter()->getPreCalculateFormulas()) {
- $calculatedValue = $pCell->getCalculatedValue();
- } else {
- $calculatedValue = $cellValue;
- }
- if (is_string($calculatedValue)) {
- $objWriter->writeAttribute('t', 'str');
- }
- break;
- case 'e': // Error
- $objWriter->writeAttribute('t', $mappedType);
- }
-
- // Write data depending on its type
- switch (strtolower($mappedType)) {
- case 'inlinestr': // Inline string
- if (! $cellValue instanceof PHPExcel_RichText) {
- $objWriter->writeElement('t', PHPExcel_Shared_String::ControlCharacterPHP2OOXML( htmlspecialchars($cellValue) ) );
- } else if ($cellValue instanceof PHPExcel_RichText) {
- $objWriter->startElement('is');
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue);
- $objWriter->endElement();
- }
-
- break;
- case 's': // String
- if (! $cellValue instanceof PHPExcel_RichText) {
- if (isset($pFlippedStringTable[$cellValue])) {
- $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]);
- }
- } else if ($cellValue instanceof PHPExcel_RichText) {
- $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]);
- }
-
- break;
- case 'f': // Formula
- $attributes = $pCell->getFormulaAttributes();
- if($attributes['t'] == 'array') {
- $objWriter->startElement('f');
- $objWriter->writeAttribute('t', 'array');
- $objWriter->writeAttribute('ref', $pCellAddress);
- $objWriter->writeAttribute('aca', '1');
- $objWriter->writeAttribute('ca', '1');
- $objWriter->text(substr($cellValue, 1));
- $objWriter->endElement();
- } else {
- $objWriter->writeElement('f', substr($cellValue, 1));
- }
- if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
- if ($this->getParentWriter()->getPreCalculateFormulas()) {
- $calculatedValue = $pCell->getCalculatedValue();
- if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') {
- $objWriter->writeElement('v', PHPExcel_Shared_String::FormatNumber($calculatedValue));
- } else {
- $objWriter->writeElement('v', '0');
- }
- } else {
- $objWriter->writeElement('v', '0');
- }
- }
- break;
- case 'n': // Numeric
- // force point as decimal separator in case current locale uses comma
- $objWriter->writeElement('v', str_replace(',', '.', $cellValue));
- break;
- case 'b': // Boolean
- $objWriter->writeElement('v', ($cellValue ? '1' : '0'));
- break;
- case 'e': // Error
- if (substr($cellValue, 0, 1) == '=') {
- $objWriter->writeElement('f', substr($cellValue, 1));
- $objWriter->writeElement('v', substr($cellValue, 1));
- } else {
- $objWriter->writeElement('v', $cellValue);
- }
-
- break;
- }
- }
-
- $objWriter->endElement();
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Write Drawings
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeDrawings(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $includeCharts = FALSE)
- {
- $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0;
- // If sheet contains drawings, add the relationships
- if (($pSheet->getDrawingCollection()->count() > 0) ||
- ($chartCount > 0)) {
- $objWriter->startElement('drawing');
- $objWriter->writeAttribute('r:id', 'rId1');
- $objWriter->endElement();
- }
- }
-
- /**
- * Write LegacyDrawing
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeLegacyDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // If sheet contains comments, add the relationships
- if (count($pSheet->getComments()) > 0) {
- $objWriter->startElement('legacyDrawing');
- $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
- $objWriter->endElement();
- }
- }
-
- /**
- * Write LegacyDrawingHF
- *
- * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
- * @param PHPExcel_Worksheet $pSheet Worksheet
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeLegacyDrawingHF(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
- {
- // If sheet contains images, add the relationships
- if (count($pSheet->getHeaderFooter()->getImages()) > 0) {
- $objWriter->startElement('legacyDrawingHF');
- $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
- $objWriter->endElement();
- }
- }
+ /**
+ * Write worksheet to XML format
+ *
+ * @param PHPExcel_Worksheet $pSheet
+ * @param string[] $pStringTable
+ * @param boolean $includeCharts Flag indicating if we should write charts
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function writeWorksheet($pSheet = null, $pStringTable = null, $includeCharts = false)
+ {
+ if (!is_null($pSheet)) {
+ // Create XML writer
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8', 'yes');
+
+ // Worksheet
+ $objWriter->startElement('worksheet');
+ $objWriter->writeAttribute('xml:space', 'preserve');
+ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+
+ // sheetPr
+ $this->writeSheetPr($objWriter, $pSheet);
+
+ // Dimension
+ $this->writeDimension($objWriter, $pSheet);
+
+ // sheetViews
+ $this->writeSheetViews($objWriter, $pSheet);
+
+ // sheetFormatPr
+ $this->writeSheetFormatPr($objWriter, $pSheet);
+
+ // cols
+ $this->writeCols($objWriter, $pSheet);
+
+ // sheetData
+ $this->writeSheetData($objWriter, $pSheet, $pStringTable);
+
+ // sheetProtection
+ $this->writeSheetProtection($objWriter, $pSheet);
+
+ // protectedRanges
+ $this->writeProtectedRanges($objWriter, $pSheet);
+
+ // autoFilter
+ $this->writeAutoFilter($objWriter, $pSheet);
+
+ // mergeCells
+ $this->writeMergeCells($objWriter, $pSheet);
+
+ // conditionalFormatting
+ $this->writeConditionalFormatting($objWriter, $pSheet);
+
+ // dataValidations
+ $this->writeDataValidations($objWriter, $pSheet);
+
+ // hyperlinks
+ $this->writeHyperlinks($objWriter, $pSheet);
+
+ // Print options
+ $this->writePrintOptions($objWriter, $pSheet);
+
+ // Page margins
+ $this->writePageMargins($objWriter, $pSheet);
+
+ // Page setup
+ $this->writePageSetup($objWriter, $pSheet);
+
+ // Header / footer
+ $this->writeHeaderFooter($objWriter, $pSheet);
+
+ // Breaks
+ $this->writeBreaks($objWriter, $pSheet);
+
+ // Drawings and/or Charts
+ $this->writeDrawings($objWriter, $pSheet, $includeCharts);
+
+ // LegacyDrawing
+ $this->writeLegacyDrawing($objWriter, $pSheet);
+
+ // LegacyDrawingHF
+ $this->writeLegacyDrawingHF($objWriter, $pSheet);
+
+ $objWriter->endElement();
+
+ // Return
+ return $objWriter->getData();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed.");
+ }
+ }
+
+ /**
+ * Write SheetPr
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheetPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // sheetPr
+ $objWriter->startElement('sheetPr');
+ //$objWriter->writeAttribute('codeName', $pSheet->getTitle());
+ if ($pSheet->getParent()->hasMacros()) {//if the workbook have macros, we need to have codeName for the sheet
+ if ($pSheet->hasCodeName()==false) {
+ $pSheet->setCodeName($pSheet->getTitle());
+ }
+ $objWriter->writeAttribute('codeName', $pSheet->getCodeName());
+ }
+ $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ $objWriter->writeAttribute('filterMode', 1);
+ $pSheet->getAutoFilter()->showHideRows();
+ }
+
+ // tabColor
+ if ($pSheet->isTabColorSet()) {
+ $objWriter->startElement('tabColor');
+ $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB());
+ $objWriter->endElement();
+ }
+
+ // outlinePr
+ $objWriter->startElement('outlinePr');
+ $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0'));
+ $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0'));
+ $objWriter->endElement();
+
+ // pageSetUpPr
+ if ($pSheet->getPageSetup()->getFitToPage()) {
+ $objWriter->startElement('pageSetUpPr');
+ $objWriter->writeAttribute('fitToPage', '1');
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Dimension
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDimension(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // dimension
+ $objWriter->startElement('dimension');
+ $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension());
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write SheetViews
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheetViews(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // sheetViews
+ $objWriter->startElement('sheetViews');
+
+ // Sheet selected?
+ $sheetSelected = false;
+ if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex()) {
+ $sheetSelected = true;
+ }
+
+ // sheetView
+ $objWriter->startElement('sheetView');
+ $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
+ $objWriter->writeAttribute('workbookViewId', '0');
+
+ // Zoom scales
+ if ($pSheet->getSheetView()->getZoomScale() != 100) {
+ $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale());
+ }
+ if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) {
+ $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal());
+ }
+
+ // View Layout Type
+ if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) {
+ $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView());
+ }
+
+ // Gridlines
+ if ($pSheet->getShowGridlines()) {
+ $objWriter->writeAttribute('showGridLines', 'true');
+ } else {
+ $objWriter->writeAttribute('showGridLines', 'false');
+ }
+
+ // Row and column headers
+ if ($pSheet->getShowRowColHeaders()) {
+ $objWriter->writeAttribute('showRowColHeaders', '1');
+ } else {
+ $objWriter->writeAttribute('showRowColHeaders', '0');
+ }
+
+ // Right-to-left
+ if ($pSheet->getRightToLeft()) {
+ $objWriter->writeAttribute('rightToLeft', 'true');
+ }
+
+ $activeCell = $pSheet->getActiveCell();
+
+ // Pane
+ $pane = '';
+ $topLeftCell = $pSheet->getFreezePane();
+ if (($topLeftCell != '') && ($topLeftCell != 'A1')) {
+ $activeCell = empty($activeCell) ? $topLeftCell : $activeCell;
+ // Calculate freeze coordinates
+ $xSplit = $ySplit = 0;
+
+ list($xSplit, $ySplit) = PHPExcel_Cell::coordinateFromString($topLeftCell);
+ $xSplit = PHPExcel_Cell::columnIndexFromString($xSplit);
+
+ // pane
+ $pane = 'topRight';
+ $objWriter->startElement('pane');
+ if ($xSplit > 1) {
+ $objWriter->writeAttribute('xSplit', $xSplit - 1);
+ }
+ if ($ySplit > 1) {
+ $objWriter->writeAttribute('ySplit', $ySplit - 1);
+ $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft';
+ }
+ $objWriter->writeAttribute('topLeftCell', $topLeftCell);
+ $objWriter->writeAttribute('activePane', $pane);
+ $objWriter->writeAttribute('state', 'frozen');
+ $objWriter->endElement();
+
+ if (($xSplit > 1) && ($ySplit > 1)) {
+ // Write additional selections if more than two panes (ie both an X and a Y split)
+ $objWriter->startElement('selection');
+ $objWriter->writeAttribute('pane', 'topRight');
+ $objWriter->endElement();
+ $objWriter->startElement('selection');
+ $objWriter->writeAttribute('pane', 'bottomLeft');
+ $objWriter->endElement();
+ }
+ }
+
+ // Selection
+// if ($pane != '') {
+ // Only need to write selection element if we have a split pane
+ // We cheat a little by over-riding the active cell selection, setting it to the split cell
+ $objWriter->startElement('selection');
+ if ($pane != '') {
+ $objWriter->writeAttribute('pane', $pane);
+ }
+ $objWriter->writeAttribute('activeCell', $activeCell);
+ $objWriter->writeAttribute('sqref', $activeCell);
+ $objWriter->endElement();
+// }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write SheetFormatPr
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheetFormatPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // sheetFormatPr
+ $objWriter->startElement('sheetFormatPr');
+
+ // Default row height
+ if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) {
+ $objWriter->writeAttribute('customHeight', 'true');
+ $objWriter->writeAttribute('defaultRowHeight', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultRowDimension()->getRowHeight()));
+ } else {
+ $objWriter->writeAttribute('defaultRowHeight', '14.4');
+ }
+
+ // Set Zero Height row
+ if ((string)$pSheet->getDefaultRowDimension()->getZeroHeight() == '1' ||
+ strtolower((string)$pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true') {
+ $objWriter->writeAttribute('zeroHeight', '1');
+ }
+
+ // Default column width
+ if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) {
+ $objWriter->writeAttribute('defaultColWidth', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultColumnDimension()->getWidth()));
+ }
+
+ // Outline level - row
+ $outlineLevelRow = 0;
+ foreach ($pSheet->getRowDimensions() as $dimension) {
+ if ($dimension->getOutlineLevel() > $outlineLevelRow) {
+ $outlineLevelRow = $dimension->getOutlineLevel();
+ }
+ }
+ $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow);
+
+ // Outline level - column
+ $outlineLevelCol = 0;
+ foreach ($pSheet->getColumnDimensions() as $dimension) {
+ if ($dimension->getOutlineLevel() > $outlineLevelCol) {
+ $outlineLevelCol = $dimension->getOutlineLevel();
+ }
+ }
+ $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol);
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Cols
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCols(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // cols
+ if (count($pSheet->getColumnDimensions()) > 0) {
+ $objWriter->startElement('cols');
+
+ $pSheet->calculateColumnWidths();
+
+ // Loop through column dimensions
+ foreach ($pSheet->getColumnDimensions() as $colDimension) {
+ // col
+ $objWriter->startElement('col');
+ $objWriter->writeAttribute('min', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex()));
+ $objWriter->writeAttribute('max', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex()));
+
+ if ($colDimension->getWidth() < 0) {
+ // No width set, apply default of 10
+ $objWriter->writeAttribute('width', '9.10');
+ } else {
+ // Width set
+ $objWriter->writeAttribute('width', PHPExcel_Shared_String::FormatNumber($colDimension->getWidth()));
+ }
+
+ // Column visibility
+ if ($colDimension->getVisible() == false) {
+ $objWriter->writeAttribute('hidden', 'true');
+ }
+
+ // Auto size?
+ if ($colDimension->getAutoSize()) {
+ $objWriter->writeAttribute('bestFit', 'true');
+ }
+
+ // Custom width?
+ if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) {
+ $objWriter->writeAttribute('customWidth', 'true');
+ }
+
+ // Collapsed
+ if ($colDimension->getCollapsed() == true) {
+ $objWriter->writeAttribute('collapsed', 'true');
+ }
+
+ // Outline level
+ if ($colDimension->getOutlineLevel() > 0) {
+ $objWriter->writeAttribute('outlineLevel', $colDimension->getOutlineLevel());
+ }
+
+ // Style
+ $objWriter->writeAttribute('style', $colDimension->getXfIndex());
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write SheetProtection
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheetProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // sheetProtection
+ $objWriter->startElement('sheetProtection');
+
+ if ($pSheet->getProtection()->getPassword() != '') {
+ $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword());
+ }
+
+ $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false'));
+ $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false'));
+ $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false'));
+ $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false'));
+ $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false'));
+ $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false'));
+ $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false'));
+ $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false'));
+ $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false'));
+ $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false'));
+ $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false'));
+ $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false'));
+ $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false'));
+ $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false'));
+ $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false'));
+ $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false'));
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write ConditionalFormatting
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeConditionalFormatting(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // Conditional id
+ $id = 1;
+
+ // Loop through styles in the current worksheet
+ foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
+ foreach ($conditionalStyles as $conditional) {
+ // WHY was this again?
+ // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') {
+ // continue;
+ // }
+ if ($conditional->getConditionType() != PHPExcel_Style_Conditional::CONDITION_NONE) {
+ // conditionalFormatting
+ $objWriter->startElement('conditionalFormatting');
+ $objWriter->writeAttribute('sqref', $cellCoordinate);
+
+ // cfRule
+ $objWriter->startElement('cfRule');
+ $objWriter->writeAttribute('type', $conditional->getConditionType());
+ $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()));
+ $objWriter->writeAttribute('priority', $id++);
+
+ if (($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT)
+ && $conditional->getOperatorType() != PHPExcel_Style_Conditional::OPERATOR_NONE) {
+ $objWriter->writeAttribute('operator', $conditional->getOperatorType());
+ }
+
+ if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
+ && !is_null($conditional->getText())) {
+ $objWriter->writeAttribute('text', $conditional->getText());
+ }
+
+ if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_CONTAINSTEXT
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))');
+ } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BEGINSWITH
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
+ } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_ENDSWITH
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"');
+ } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
+ && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_NOTCONTAINS
+ && !is_null($conditional->getText())) {
+ $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))');
+ } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS
+ || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT
+ || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) {
+ foreach ($conditional->getConditions() as $formula) {
+ // Formula
+ $objWriter->writeElement('formula', $formula);
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+ }
+ }
+
+ /**
+ * Write DataValidations
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDataValidations(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // Datavalidation collection
+ $dataValidationCollection = $pSheet->getDataValidationCollection();
+
+ // Write data validations?
+ if (!empty($dataValidationCollection)) {
+ $objWriter->startElement('dataValidations');
+ $objWriter->writeAttribute('count', count($dataValidationCollection));
+
+ foreach ($dataValidationCollection as $coordinate => $dv) {
+ $objWriter->startElement('dataValidation');
+
+ if ($dv->getType() != '') {
+ $objWriter->writeAttribute('type', $dv->getType());
+ }
+
+ if ($dv->getErrorStyle() != '') {
+ $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
+ }
+
+ if ($dv->getOperator() != '') {
+ $objWriter->writeAttribute('operator', $dv->getOperator());
+ }
+
+ $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
+ $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
+ $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
+ $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
+
+ if ($dv->getErrorTitle() !== '') {
+ $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
+ }
+ if ($dv->getError() !== '') {
+ $objWriter->writeAttribute('error', $dv->getError());
+ }
+ if ($dv->getPromptTitle() !== '') {
+ $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
+ }
+ if ($dv->getPrompt() !== '') {
+ $objWriter->writeAttribute('prompt', $dv->getPrompt());
+ }
+
+ $objWriter->writeAttribute('sqref', $coordinate);
+
+ if ($dv->getFormula1() !== '') {
+ $objWriter->writeElement('formula1', $dv->getFormula1());
+ }
+ if ($dv->getFormula2() !== '') {
+ $objWriter->writeElement('formula2', $dv->getFormula2());
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write Hyperlinks
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeHyperlinks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // Hyperlink collection
+ $hyperlinkCollection = $pSheet->getHyperlinkCollection();
+
+ // Relation ID
+ $relationId = 1;
+
+ // Write hyperlinks?
+ if (!empty($hyperlinkCollection)) {
+ $objWriter->startElement('hyperlinks');
+
+ foreach ($hyperlinkCollection as $coordinate => $hyperlink) {
+ $objWriter->startElement('hyperlink');
+
+ $objWriter->writeAttribute('ref', $coordinate);
+ if (!$hyperlink->isInternal()) {
+ $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId);
+ ++$relationId;
+ } else {
+ $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl()));
+ }
+
+ if ($hyperlink->getTooltip() != '') {
+ $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip());
+ }
+
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write ProtectedRanges
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeProtectedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ if (count($pSheet->getProtectedCells()) > 0) {
+ // protectedRanges
+ $objWriter->startElement('protectedRanges');
+
+ // Loop protectedRanges
+ foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) {
+ // protectedRange
+ $objWriter->startElement('protectedRange');
+ $objWriter->writeAttribute('name', 'p' . md5($protectedCell));
+ $objWriter->writeAttribute('sqref', $protectedCell);
+ if (!empty($passwordHash)) {
+ $objWriter->writeAttribute('password', $passwordHash);
+ }
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write MergeCells
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeMergeCells(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ if (count($pSheet->getMergeCells()) > 0) {
+ // mergeCells
+ $objWriter->startElement('mergeCells');
+
+ // Loop mergeCells
+ foreach ($pSheet->getMergeCells() as $mergeCell) {
+ // mergeCell
+ $objWriter->startElement('mergeCell');
+ $objWriter->writeAttribute('ref', $mergeCell);
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write PrintOptions
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePrintOptions(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // printOptions
+ $objWriter->startElement('printOptions');
+
+ $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true': 'false'));
+ $objWriter->writeAttribute('gridLinesSet', 'true');
+
+ if ($pSheet->getPageSetup()->getHorizontalCentered()) {
+ $objWriter->writeAttribute('horizontalCentered', 'true');
+ }
+
+ if ($pSheet->getPageSetup()->getVerticalCentered()) {
+ $objWriter->writeAttribute('verticalCentered', 'true');
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write PageMargins
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePageMargins(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // pageMargins
+ $objWriter->startElement('pageMargins');
+ $objWriter->writeAttribute('left', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()));
+ $objWriter->writeAttribute('right', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()));
+ $objWriter->writeAttribute('top', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()));
+ $objWriter->writeAttribute('bottom', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()));
+ $objWriter->writeAttribute('header', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getHeader()));
+ $objWriter->writeAttribute('footer', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getFooter()));
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write AutoFilter
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeAutoFilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ // autoFilter
+ $objWriter->startElement('autoFilter');
+
+ // Strip any worksheet reference from the filter coordinates
+ $range = PHPExcel_Cell::splitRange($autoFilterRange);
+ $range = $range[0];
+ // Strip any worksheet ref
+ if (strpos($range[0], '!') !== false) {
+ list($ws, $range[0]) = explode('!', $range[0]);
+ }
+ $range = implode(':', $range);
+
+ $objWriter->writeAttribute('ref', str_replace('$', '', $range));
+
+ $columns = $pSheet->getAutoFilter()->getColumns();
+ if (count($columns > 0)) {
+ foreach ($columns as $columnID => $column) {
+ $rules = $column->getRules();
+ if (count($rules) > 0) {
+ $objWriter->startElement('filterColumn');
+ $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID));
+
+ $objWriter->startElement($column->getFilterType());
+ if ($column->getJoin() == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) {
+ $objWriter->writeAttribute('and', 1);
+ }
+
+ foreach ($rules as $rule) {
+ if (($column->getFilterType() === PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) &&
+ ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) &&
+ ($rule->getValue() === '')) {
+ // Filter rule for Blanks
+ $objWriter->writeAttribute('blank', 1);
+ } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) {
+ // Dynamic Filter Rule
+ $objWriter->writeAttribute('type', $rule->getGrouping());
+ $val = $column->getAttribute('val');
+ if ($val !== null) {
+ $objWriter->writeAttribute('val', $val);
+ }
+ $maxVal = $column->getAttribute('maxVal');
+ if ($maxVal !== null) {
+ $objWriter->writeAttribute('maxVal', $maxVal);
+ }
+ } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) {
+ // Top 10 Filter Rule
+ $objWriter->writeAttribute('val', $rule->getValue());
+ $objWriter->writeAttribute('percent', (($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0'));
+ $objWriter->writeAttribute('top', (($rule->getGrouping() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0'));
+ } else {
+ // Filter, DateGroupItem or CustomFilter
+ $objWriter->startElement($rule->getRuleType());
+
+ if ($rule->getOperator() !== PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) {
+ $objWriter->writeAttribute('operator', $rule->getOperator());
+ }
+ if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) {
+ // Date Group filters
+ foreach ($rule->getValue() as $key => $value) {
+ if ($value > '') {
+ $objWriter->writeAttribute($key, $value);
+ }
+ }
+ $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping());
+ } else {
+ $objWriter->writeAttribute('val', $rule->getValue());
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+ }
+ }
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write PageSetup
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writePageSetup(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // pageSetup
+ $objWriter->startElement('pageSetup');
+ $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize());
+ $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation());
+
+ if (!is_null($pSheet->getPageSetup()->getScale())) {
+ $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale());
+ }
+ if (!is_null($pSheet->getPageSetup()->getFitToHeight())) {
+ $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight());
+ } else {
+ $objWriter->writeAttribute('fitToHeight', '0');
+ }
+ if (!is_null($pSheet->getPageSetup()->getFitToWidth())) {
+ $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth());
+ } else {
+ $objWriter->writeAttribute('fitToWidth', '0');
+ }
+ if (!is_null($pSheet->getPageSetup()->getFirstPageNumber())) {
+ $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber());
+ $objWriter->writeAttribute('useFirstPageNumber', '1');
+ }
+
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Header / Footer
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeHeaderFooter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // headerFooter
+ $objWriter->startElement('headerFooter');
+ $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
+ $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
+ $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
+ $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
+
+ $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader());
+ $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter());
+ $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader());
+ $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter());
+ $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader());
+ $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter());
+ $objWriter->endElement();
+ }
+
+ /**
+ * Write Breaks
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeBreaks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // Get row and column breaks
+ $aRowBreaks = array();
+ $aColumnBreaks = array();
+ foreach ($pSheet->getBreaks() as $cell => $breakType) {
+ if ($breakType == PHPExcel_Worksheet::BREAK_ROW) {
+ $aRowBreaks[] = $cell;
+ } elseif ($breakType == PHPExcel_Worksheet::BREAK_COLUMN) {
+ $aColumnBreaks[] = $cell;
+ }
+ }
+
+ // rowBreaks
+ if (!empty($aRowBreaks)) {
+ $objWriter->startElement('rowBreaks');
+ $objWriter->writeAttribute('count', count($aRowBreaks));
+ $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks));
+
+ foreach ($aRowBreaks as $cell) {
+ $coords = PHPExcel_Cell::coordinateFromString($cell);
+
+ $objWriter->startElement('brk');
+ $objWriter->writeAttribute('id', $coords[1]);
+ $objWriter->writeAttribute('man', '1');
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+
+ // Second, write column breaks
+ if (!empty($aColumnBreaks)) {
+ $objWriter->startElement('colBreaks');
+ $objWriter->writeAttribute('count', count($aColumnBreaks));
+ $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks));
+
+ foreach ($aColumnBreaks as $cell) {
+ $coords = PHPExcel_Cell::coordinateFromString($cell);
+
+ $objWriter->startElement('brk');
+ $objWriter->writeAttribute('id', PHPExcel_Cell::columnIndexFromString($coords[0]) - 1);
+ $objWriter->writeAttribute('man', '1');
+ $objWriter->endElement();
+ }
+
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write SheetData
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @param string[] $pStringTable String table
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeSheetData(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pStringTable = null)
+ {
+ if (is_array($pStringTable)) {
+ // Flipped stringtable, for faster index searching
+ $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable);
+
+ // sheetData
+ $objWriter->startElement('sheetData');
+
+ // Get column count
+ $colCount = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn());
+
+ // Highest row number
+ $highestRow = $pSheet->getHighestRow();
+
+ // Loop through cells
+ $cellsByRow = array();
+ foreach ($pSheet->getCellCollection() as $cellID) {
+ $cellAddress = PHPExcel_Cell::coordinateFromString($cellID);
+ $cellsByRow[$cellAddress[1]][] = $cellID;
+ }
+
+ $currentRow = 0;
+ while ($currentRow++ < $highestRow) {
+ // Get row dimension
+ $rowDimension = $pSheet->getRowDimension($currentRow);
+
+ // Write current row?
+ $writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null;
+
+ if ($writeCurrentRow) {
+ // Start a new row
+ $objWriter->startElement('row');
+ $objWriter->writeAttribute('r', $currentRow);
+ $objWriter->writeAttribute('spans', '1:' . $colCount);
+
+ // Row dimensions
+ if ($rowDimension->getRowHeight() >= 0) {
+ $objWriter->writeAttribute('customHeight', '1');
+ $objWriter->writeAttribute('ht', PHPExcel_Shared_String::FormatNumber($rowDimension->getRowHeight()));
+ }
+
+ // Row visibility
+ if ($rowDimension->getVisible() == false) {
+ $objWriter->writeAttribute('hidden', 'true');
+ }
+
+ // Collapsed
+ if ($rowDimension->getCollapsed() == true) {
+ $objWriter->writeAttribute('collapsed', 'true');
+ }
+
+ // Outline level
+ if ($rowDimension->getOutlineLevel() > 0) {
+ $objWriter->writeAttribute('outlineLevel', $rowDimension->getOutlineLevel());
+ }
+
+ // Style
+ if ($rowDimension->getXfIndex() !== null) {
+ $objWriter->writeAttribute('s', $rowDimension->getXfIndex());
+ $objWriter->writeAttribute('customFormat', '1');
+ }
+
+ // Write cells
+ if (isset($cellsByRow[$currentRow])) {
+ foreach ($cellsByRow[$currentRow] as $cellAddress) {
+ // Write cell
+ $this->writeCell($objWriter, $pSheet, $cellAddress, $pStringTable, $aFlippedStringTable);
+ }
+ }
+
+ // End row
+ $objWriter->endElement();
+ }
+ }
+
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write Cell
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @param PHPExcel_Cell $pCellAddress Cell Address
+ * @param string[] $pStringTable String table
+ * @param string[] $pFlippedStringTable String table (flipped), for faster index searching
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCell(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pCellAddress = null, $pStringTable = null, $pFlippedStringTable = null)
+ {
+ if (is_array($pStringTable) && is_array($pFlippedStringTable)) {
+ // Cell
+ $pCell = $pSheet->getCell($pCellAddress);
+ $objWriter->startElement('c');
+ $objWriter->writeAttribute('r', $pCellAddress);
+
+ // Sheet styles
+ if ($pCell->getXfIndex() != '') {
+ $objWriter->writeAttribute('s', $pCell->getXfIndex());
+ }
+
+ // If cell value is supplied, write cell value
+ $cellValue = $pCell->getValue();
+ if (is_object($cellValue) || $cellValue !== '') {
+ // Map type
+ $mappedType = $pCell->getDataType();
+
+ // Write data type depending on its type
+ switch (strtolower($mappedType)) {
+ case 'inlinestr': // Inline string
+ case 's': // String
+ case 'b': // Boolean
+ $objWriter->writeAttribute('t', $mappedType);
+ break;
+ case 'f': // Formula
+ $calculatedValue = ($this->getParentWriter()->getPreCalculateFormulas()) ?
+ $pCell->getCalculatedValue() :
+ $cellValue;
+ if (is_string($calculatedValue)) {
+ $objWriter->writeAttribute('t', 'str');
+ }
+ break;
+ case 'e': // Error
+ $objWriter->writeAttribute('t', $mappedType);
+ }
+
+ // Write data depending on its type
+ switch (strtolower($mappedType)) {
+ case 'inlinestr': // Inline string
+ if (! $cellValue instanceof PHPExcel_RichText) {
+ $objWriter->writeElement('t', PHPExcel_Shared_String::ControlCharacterPHP2OOXML(htmlspecialchars($cellValue)));
+ } elseif ($cellValue instanceof PHPExcel_RichText) {
+ $objWriter->startElement('is');
+ $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue);
+ $objWriter->endElement();
+ }
+
+ break;
+ case 's': // String
+ if (! $cellValue instanceof PHPExcel_RichText) {
+ if (isset($pFlippedStringTable[$cellValue])) {
+ $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]);
+ }
+ } elseif ($cellValue instanceof PHPExcel_RichText) {
+ $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]);
+ }
+
+ break;
+ case 'f': // Formula
+ $attributes = $pCell->getFormulaAttributes();
+ if ($attributes['t'] == 'array') {
+ $objWriter->startElement('f');
+ $objWriter->writeAttribute('t', 'array');
+ $objWriter->writeAttribute('ref', $pCellAddress);
+ $objWriter->writeAttribute('aca', '1');
+ $objWriter->writeAttribute('ca', '1');
+ $objWriter->text(substr($cellValue, 1));
+ $objWriter->endElement();
+ } else {
+ $objWriter->writeElement('f', substr($cellValue, 1));
+ }
+ if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
+ if ($this->getParentWriter()->getPreCalculateFormulas()) {
+// $calculatedValue = $pCell->getCalculatedValue();
+ if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') {
+ $objWriter->writeElement('v', PHPExcel_Shared_String::FormatNumber($calculatedValue));
+ } else {
+ $objWriter->writeElement('v', '0');
+ }
+ } else {
+ $objWriter->writeElement('v', '0');
+ }
+ }
+ break;
+ case 'n': // Numeric
+ // force point as decimal separator in case current locale uses comma
+ $objWriter->writeElement('v', str_replace(',', '.', $cellValue));
+ break;
+ case 'b': // Boolean
+ $objWriter->writeElement('v', ($cellValue ? '1' : '0'));
+ break;
+ case 'e': // Error
+ if (substr($cellValue, 0, 1) == '=') {
+ $objWriter->writeElement('f', substr($cellValue, 1));
+ $objWriter->writeElement('v', substr($cellValue, 1));
+ } else {
+ $objWriter->writeElement('v', $cellValue);
+ }
+
+ break;
+ }
+ }
+
+ $objWriter->endElement();
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Write Drawings
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @param boolean $includeCharts Flag indicating if we should include drawing details for charts
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeDrawings(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $includeCharts = false)
+ {
+ $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0;
+ // If sheet contains drawings, add the relationships
+ if (($pSheet->getDrawingCollection()->count() > 0) ||
+ ($chartCount > 0)) {
+ $objWriter->startElement('drawing');
+ $objWriter->writeAttribute('r:id', 'rId1');
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write LegacyDrawing
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeLegacyDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // If sheet contains comments, add the relationships
+ if (count($pSheet->getComments()) > 0) {
+ $objWriter->startElement('legacyDrawing');
+ $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write LegacyDrawingHF
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer
+ * @param PHPExcel_Worksheet $pSheet Worksheet
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeLegacyDrawingHF(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)
+ {
+ // If sheet contains images, add the relationships
+ if (count($pSheet->getHeaderFooter()->getImages()) > 0) {
+ $objWriter->startElement('legacyDrawingHF');
+ $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
+ $objWriter->endElement();
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel2007/WriterPart.php b/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
index e1242c84c..806ebe510 100644
--- a/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
+++ b/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
@@ -1,8 +1,9 @@
_parentWriter = $pWriter;
- }
+ /**
+ * Parent IWriter object
+ *
+ * @var PHPExcel_Writer_IWriter
+ */
+ private $parentWriter;
- /**
- * Get parent IWriter object
- *
- * @return PHPExcel_Writer_IWriter
- * @throws PHPExcel_Writer_Exception
- */
- public function getParentWriter() {
- if (!is_null($this->_parentWriter)) {
- return $this->_parentWriter;
- } else {
- throw new PHPExcel_Writer_Exception("No parent PHPExcel_Writer_IWriter assigned.");
- }
- }
+ /**
+ * Set parent IWriter object
+ *
+ * @param PHPExcel_Writer_IWriter $pWriter
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function setParentWriter(PHPExcel_Writer_IWriter $pWriter = null)
+ {
+ $this->parentWriter = $pWriter;
+ }
- /**
- * Set parent IWriter object
- *
- * @param PHPExcel_Writer_IWriter $pWriter
- * @throws PHPExcel_Writer_Exception
- */
- public function __construct(PHPExcel_Writer_IWriter $pWriter = null) {
- if (!is_null($pWriter)) {
- $this->_parentWriter = $pWriter;
- }
- }
+ /**
+ * Get parent IWriter object
+ *
+ * @return PHPExcel_Writer_IWriter
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function getParentWriter()
+ {
+ if (!is_null($this->parentWriter)) {
+ return $this->parentWriter;
+ } else {
+ throw new PHPExcel_Writer_Exception("No parent PHPExcel_Writer_IWriter assigned.");
+ }
+ }
+ /**
+ * Set parent IWriter object
+ *
+ * @param PHPExcel_Writer_IWriter $pWriter
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function __construct(PHPExcel_Writer_IWriter $pWriter = null)
+ {
+ if (!is_null($pWriter)) {
+ $this->parentWriter = $pWriter;
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5.php b/Classes/PHPExcel/Writer/Excel5.php
index 459653c63..2dede819a 100644
--- a/Classes/PHPExcel/Writer/Excel5.php
+++ b/Classes/PHPExcel/Writer/Excel5.php
@@ -1,8 +1,9 @@
_phpExcel = $phpExcel;
-
- $this->_parser = new PHPExcel_Writer_Excel5_Parser();
- }
-
- /**
- * 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()->writeDebugLog;
- PHPExcel_Calculation::getInstance()->writeDebugLog = false;
- $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
-
- // initialize colors array
- $this->_colors = array();
-
- // Initialise workbook writer
- $this->_writerWorkbook = new PHPExcel_Writer_Excel5_Workbook($this->_phpExcel,
- $this->_str_total, $this->_str_unique, $this->_str_table,
- $this->_colors, $this->_parser);
-
- // Initialise worksheet writers
- $countSheets = $this->_phpExcel->getSheetCount();
- for ($i = 0; $i < $countSheets; ++$i) {
- $this->_writerWorksheets[$i] = new PHPExcel_Writer_Excel5_Worksheet($this->_str_total, $this->_str_unique,
- $this->_str_table, $this->_colors,
- $this->_parser,
- $this->_preCalculateFormulas,
- $this->_phpExcel->getSheet($i));
- }
-
- // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook.
- $this->_buildWorksheetEschers();
- $this->_buildWorkbookEscher();
-
- // add 15 identical cell style Xfs
- // for now, we use the first cellXf instead of cellStyleXf
- $cellXfCollection = $this->_phpExcel->getCellXfCollection();
- for ($i = 0; $i < 15; ++$i) {
- $this->_writerWorkbook->addXfWriter($cellXfCollection[0], true);
- }
-
- // add all the cell Xfs
- foreach ($this->_phpExcel->getCellXfCollection() as $style) {
- $this->_writerWorkbook->addXfWriter($style, false);
- }
-
- // add fonts from rich text eleemnts
- for ($i = 0; $i < $countSheets; ++$i) {
- foreach ($this->_writerWorksheets[$i]->_phpSheet->getCellCollection() as $cellID) {
- $cell = $this->_writerWorksheets[$i]->_phpSheet->getCell($cellID);
- $cVal = $cell->getValue();
- if ($cVal instanceof PHPExcel_RichText) {
- $elements = $cVal->getRichTextElements();
- foreach ($elements as $element) {
- if ($element instanceof PHPExcel_RichText_Run) {
- $font = $element->getFont();
- $this->_writerWorksheets[$i]->_fntHashIndex[$font->getHashCode()] = $this->_writerWorkbook->_addFont($font);
- }
- }
- }
- }
- }
-
- // initialize OLE file
- $workbookStreamName = 'Workbook';
- $OLE = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs($workbookStreamName));
-
- // Write the worksheet streams before the global workbook stream,
- // because the byte sizes of these are needed in the global workbook stream
- $worksheetSizes = array();
- for ($i = 0; $i < $countSheets; ++$i) {
- $this->_writerWorksheets[$i]->close();
- $worksheetSizes[] = $this->_writerWorksheets[$i]->_datasize;
- }
-
- // add binary data for global workbook stream
- $OLE->append($this->_writerWorkbook->writeWorkbook($worksheetSizes));
-
- // add binary data for sheet streams
- for ($i = 0; $i < $countSheets; ++$i) {
- $OLE->append($this->_writerWorksheets[$i]->getData());
- }
-
- $this->_documentSummaryInformation = $this->_writeDocumentSummaryInformation();
- // initialize OLE Document Summary Information
- if(isset($this->_documentSummaryInformation) && !empty($this->_documentSummaryInformation)){
- $OLE_DocumentSummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'DocumentSummaryInformation'));
- $OLE_DocumentSummaryInformation->append($this->_documentSummaryInformation);
- }
-
- $this->_summaryInformation = $this->_writeSummaryInformation();
- // initialize OLE Summary Information
- if(isset($this->_summaryInformation) && !empty($this->_summaryInformation)){
- $OLE_SummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'SummaryInformation'));
- $OLE_SummaryInformation->append($this->_summaryInformation);
- }
-
- // define OLE Parts
- $arrRootData = array($OLE);
- // initialize OLE Properties file
- if(isset($OLE_SummaryInformation)){
- $arrRootData[] = $OLE_SummaryInformation;
- }
- // initialize OLE Extended Properties file
- if(isset($OLE_DocumentSummaryInformation)){
- $arrRootData[] = $OLE_DocumentSummaryInformation;
- }
-
- $root = new PHPExcel_Shared_OLE_PPS_Root(time(), time(), $arrRootData);
- // save the OLE file
- $res = $root->save($pFilename);
-
- PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);
- PHPExcel_Calculation::getInstance()->writeDebugLog = $saveDebugLog;
- }
-
- /**
- * Set temporary storage directory
- *
- * @deprecated
- * @param string $pValue Temporary storage directory
- * @throws PHPExcel_Writer_Exception when directory does not exist
- * @return PHPExcel_Writer_Excel5
- */
- public function setTempDir($pValue = '') {
- return $this;
- }
-
- /**
- * Build the Worksheet Escher objects
- *
- */
- private function _buildWorksheetEschers()
- {
- // 1-based index to BstoreContainer
- $blipIndex = 0;
- $lastReducedSpId = 0;
- $lastSpId = 0;
-
- foreach ($this->_phpExcel->getAllsheets() as $sheet) {
- // sheet index
- $sheetIndex = $sheet->getParent()->getIndex($sheet);
-
- $escher = null;
-
- // check if there are any shapes for this sheet
- $filterRange = $sheet->getAutoFilter()->getRange();
- if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) {
- continue;
- }
-
- // create intermediate Escher object
- $escher = new PHPExcel_Shared_Escher();
-
- // dgContainer
- $dgContainer = new PHPExcel_Shared_Escher_DgContainer();
-
- // set the drawing index (we use sheet index + 1)
- $dgId = $sheet->getParent()->getIndex($sheet) + 1;
- $dgContainer->setDgId($dgId);
- $escher->setDgContainer($dgContainer);
-
- // spgrContainer
- $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer();
- $dgContainer->setSpgrContainer($spgrContainer);
-
- // add one shape which is the group shape
- $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
- $spContainer->setSpgr(true);
- $spContainer->setSpType(0);
- $spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10);
- $spgrContainer->addChild($spContainer);
-
- // add the shapes
-
- $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet
-
- foreach ($sheet->getDrawingCollection() as $drawing) {
- ++$blipIndex;
-
- ++$countShapes[$sheetIndex];
-
- // add the shape
- $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
-
- // set the shape type
- $spContainer->setSpType(0x004B);
- // set the shape flag
- $spContainer->setSpFlag(0x02);
-
- // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
- $reducedSpId = $countShapes[$sheetIndex];
- $spId = $reducedSpId
- | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
- $spContainer->setSpId($spId);
-
- // keep track of last reducedSpId
- $lastReducedSpId = $reducedSpId;
-
- // keep track of last spId
- $lastSpId = $spId;
-
- // set the BLIP index
- $spContainer->setOPT(0x4104, $blipIndex);
-
- // set coordinates and offsets, client anchor
- $coordinates = $drawing->getCoordinates();
- $offsetX = $drawing->getOffsetX();
- $offsetY = $drawing->getOffsetY();
- $width = $drawing->getWidth();
- $height = $drawing->getHeight();
-
- $twoAnchor = PHPExcel_Shared_Excel5::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height);
-
- $spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
- $spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
- $spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
- $spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
- $spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
- $spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
-
- $spgrContainer->addChild($spContainer);
- }
-
- // AutoFilters
- if(!empty($filterRange)){
- $rangeBounds = PHPExcel_Cell::rangeBoundaries($filterRange);
- $iNumColStart = $rangeBounds[0][0];
- $iNumColEnd = $rangeBounds[1][0];
-
- $iInc = $iNumColStart;
- while($iInc <= $iNumColEnd){
- ++$countShapes[$sheetIndex];
-
- // create an Drawing Object for the dropdown
- $oDrawing = new PHPExcel_Worksheet_BaseDrawing();
- // get the coordinates of drawing
- $cDrawing = PHPExcel_Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1];
- $oDrawing->setCoordinates($cDrawing);
- $oDrawing->setWorksheet($sheet);
-
- // add the shape
- $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
- // set the shape type
- $spContainer->setSpType(0x00C9);
- // set the shape flag
- $spContainer->setSpFlag(0x01);
-
- // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
- $reducedSpId = $countShapes[$sheetIndex];
- $spId = $reducedSpId
- | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
- $spContainer->setSpId($spId);
-
- // keep track of last reducedSpId
- $lastReducedSpId = $reducedSpId;
-
- // keep track of last spId
- $lastSpId = $spId;
-
- $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping
- $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape
- $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest
- $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash
- $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint
-
- // set coordinates and offsets, client anchor
- $endCoordinates = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::stringFromColumnIndex($iInc - 1));
- $endCoordinates .= $rangeBounds[0][1] + 1;
-
- $spContainer->setStartCoordinates($cDrawing);
- $spContainer->setStartOffsetX(0);
- $spContainer->setStartOffsetY(0);
- $spContainer->setEndCoordinates($endCoordinates);
- $spContainer->setEndOffsetX(0);
- $spContainer->setEndOffsetY(0);
-
- $spgrContainer->addChild($spContainer);
- $iInc++;
- }
- }
-
- // identifier clusters, used for workbook Escher object
- $this->_IDCLs[$dgId] = $lastReducedSpId;
-
- // set last shape index
- $dgContainer->setLastSpId($lastSpId);
-
- // set the Escher object
- $this->_writerWorksheets[$sheetIndex]->setEscher($escher);
- }
- }
-
- /**
- * Build the Escher object corresponding to the MSODRAWINGGROUP record
- */
- private function _buildWorkbookEscher()
- {
- $escher = null;
-
- // any drawings in this workbook?
- $found = false;
- foreach ($this->_phpExcel->getAllSheets() as $sheet) {
- if (count($sheet->getDrawingCollection()) > 0) {
- $found = true;
- break;
- }
- }
-
- // nothing to do if there are no drawings
- if (!$found) {
- return;
- }
-
- // if we reach here, then there are drawings in the workbook
- $escher = new PHPExcel_Shared_Escher();
-
- // dggContainer
- $dggContainer = new PHPExcel_Shared_Escher_DggContainer();
- $escher->setDggContainer($dggContainer);
-
- // set IDCLs (identifier clusters)
- $dggContainer->setIDCLs($this->_IDCLs);
-
- // this loop is for determining maximum shape identifier of all drawing
- $spIdMax = 0;
- $totalCountShapes = 0;
- $countDrawings = 0;
-
- foreach ($this->_phpExcel->getAllsheets() as $sheet) {
- $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet
-
- if (count($sheet->getDrawingCollection()) > 0) {
- ++$countDrawings;
-
- foreach ($sheet->getDrawingCollection() as $drawing) {
- ++$sheetCountShapes;
- ++$totalCountShapes;
-
- $spId = $sheetCountShapes
- | ($this->_phpExcel->getIndex($sheet) + 1) << 10;
- $spIdMax = max($spId, $spIdMax);
- }
- }
- }
-
- $dggContainer->setSpIdMax($spIdMax + 1);
- $dggContainer->setCDgSaved($countDrawings);
- $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing
-
- // bstoreContainer
- $bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer();
- $dggContainer->setBstoreContainer($bstoreContainer);
-
- // the BSE's (all the images)
- foreach ($this->_phpExcel->getAllsheets() as $sheet) {
- foreach ($sheet->getDrawingCollection() as $drawing) {
- if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
-
- $filename = $drawing->getPath();
-
- list($imagesx, $imagesy, $imageFormat) = getimagesize($filename);
-
- switch ($imageFormat) {
-
- case 1: // GIF, not supported by BIFF8, we convert to PNG
- $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- ob_start();
- imagepng(imagecreatefromgif($filename));
- $blipData = ob_get_contents();
- ob_end_clean();
- break;
-
- case 2: // JPEG
- $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
- $blipData = file_get_contents($filename);
- break;
-
- case 3: // PNG
- $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- $blipData = file_get_contents($filename);
- break;
-
- case 6: // Windows DIB (BMP), we convert to PNG
- $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- ob_start();
- imagepng(PHPExcel_Shared_Drawing::imagecreatefrombmp($filename));
- $blipData = ob_get_contents();
- ob_end_clean();
- break;
-
- default: continue 2;
-
- }
-
- $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
- $blip->setData($blipData);
-
- $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE();
- $BSE->setBlipType($blipType);
- $BSE->setBlip($blip);
-
- $bstoreContainer->addBSE($BSE);
-
- } else if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
-
- switch ($drawing->getRenderingFunction()) {
-
- case PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:
- $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
- $renderingFunction = 'imagejpeg';
- break;
-
- case PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:
- case PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:
- case PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:
- $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
- $renderingFunction = 'imagepng';
- break;
-
- }
-
- ob_start();
- call_user_func($renderingFunction, $drawing->getImageResource());
- $blipData = ob_get_contents();
- ob_end_clean();
-
- $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
- $blip->setData($blipData);
-
- $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE();
- $BSE->setBlipType($blipType);
- $BSE->setBlip($blip);
-
- $bstoreContainer->addBSE($BSE);
- }
- }
- }
-
- // Set the Escher object
- $this->_writerWorkbook->setEscher($escher);
- }
-
- /**
- * Build the OLE Part for DocumentSummary Information
- * @return string
- */
- private function _writeDocumentSummaryInformation(){
-
- // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
- $data = pack('v', 0xFFFE);
- // offset: 2; size: 2;
- $data .= pack('v', 0x0000);
- // offset: 4; size: 2; OS version
- $data .= pack('v', 0x0106);
- // offset: 6; size: 2; OS indicator
- $data .= pack('v', 0x0002);
- // offset: 8; size: 16
- $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
- // offset: 24; size: 4; section count
- $data .= pack('V', 0x0001);
-
- // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
- $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9);
- // offset: 44; size: 4; offset of the start
- $data .= pack('V', 0x30);
-
- // SECTION
- $dataSection = array();
- $dataSection_NumProps = 0;
- $dataSection_Summary = '';
- $dataSection_Content = '';
-
- // GKPIDDSI_CODEPAGE: CodePage
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
- 'data' => array('data' => 1252));
- $dataSection_NumProps++;
-
- // GKPIDDSI_CATEGORY : Category
- if($this->_phpExcel->getProperties()->getCategory()){
- $dataProp = $this->_phpExcel->getProperties()->getCategory();
- $dataProp = 'Test result file';
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E),
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // GKPIDDSI_VERSION :Version of the application that wrote the property storage
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x03),
- 'data' => array('pack' => 'V', 'data' => 0x000C0000));
- $dataSection_NumProps++;
- // GKPIDDSI_SCALE : FALSE
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
- // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
- // GKPIDDSI_SHAREDOC : FALSE
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
- // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x0B),
- 'data' => array('data' => false));
- $dataSection_NumProps++;
-
- // GKPIDDSI_DOCSPARTS
- // MS-OSHARED p75 (2.3.3.2.2.1)
- // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9)
- // cElements
- $dataProp = pack('v', 0x0001);
- $dataProp .= pack('v', 0x0000);
- // array of UnalignedLpstr
- // cch
- $dataProp .= pack('v', 0x000A);
- $dataProp .= pack('v', 0x0000);
- // value
- $dataProp .= 'Worksheet'.chr(0);
-
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x101E),
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
-
- // GKPIDDSI_HEADINGPAIR
- // VtVecHeadingPairValue
- // cElements
- $dataProp = pack('v', 0x0002);
- $dataProp .= pack('v', 0x0000);
- // Array of vtHeadingPair
- // vtUnalignedString - headingString
- // stringType
- $dataProp .= pack('v', 0x001E);
- // padding
- $dataProp .= pack('v', 0x0000);
- // UnalignedLpstr
- // cch
- $dataProp .= pack('v', 0x0013);
- $dataProp .= pack('v', 0x0000);
- // value
- $dataProp .= 'Feuilles de calcul';
- // vtUnalignedString - headingParts
- // wType : 0x0003 = 32 bit signed integer
- $dataProp .= pack('v', 0x0300);
- // padding
- $dataProp .= pack('v', 0x0000);
- // value
- $dataProp .= pack('v', 0x0100);
- $dataProp .= pack('v', 0x0000);
- $dataProp .= pack('v', 0x0000);
- $dataProp .= pack('v', 0x0000);
+ /**
+ * PHPExcel object
+ *
+ * @var PHPExcel
+ */
+ private $phpExcel;
+
+ /**
+ * Total number of shared strings in workbook
+ *
+ * @var int
+ */
+ private $strTotal = 0;
+
+ /**
+ * Number of unique shared strings in workbook
+ *
+ * @var int
+ */
+ private $strUnique = 0;
+
+ /**
+ * Array of unique shared strings in workbook
+ *
+ * @var array
+ */
+ private $strTable = array();
+
+ /**
+ * Color cache. Mapping between RGB value and color index.
+ *
+ * @var array
+ */
+ private $colors;
+
+ /**
+ * Formula parser
+ *
+ * @var PHPExcel_Writer_Excel5_Parser
+ */
+ private $parser;
+
+ /**
+ * Identifier clusters for drawings. Used in MSODRAWINGGROUP record.
+ *
+ * @var array
+ */
+ private $IDCLs;
+
+ /**
+ * Basic OLE object summary information
+ *
+ * @var array
+ */
+ private $summaryInformation;
+
+ /**
+ * Extended OLE object document summary information
+ *
+ * @var array
+ */
+ private $documentSummaryInformation;
+
+ /**
+ * Create a new PHPExcel_Writer_Excel5
+ *
+ * @param PHPExcel $phpExcel PHPExcel object
+ */
+ public function __construct(PHPExcel $phpExcel)
+ {
+ $this->phpExcel = $phpExcel;
+
+ $this->parser = new PHPExcel_Writer_Excel5_Parser();
+ }
+
+ /**
+ * 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);
+ $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+
+ // initialize colors array
+ $this->colors = array();
+
+ // Initialise workbook writer
+ $this->writerWorkbook = new PHPExcel_Writer_Excel5_Workbook($this->phpExcel, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser);
+
+ // Initialise worksheet writers
+ $countSheets = $this->phpExcel->getSheetCount();
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $this->writerWorksheets[$i] = new PHPExcel_Writer_Excel5_Worksheet($this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser, $this->preCalculateFormulas, $this->phpExcel->getSheet($i));
+ }
+
+ // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook.
+ $this->buildWorksheetEschers();
+ $this->buildWorkbookEscher();
+
+ // add 15 identical cell style Xfs
+ // for now, we use the first cellXf instead of cellStyleXf
+ $cellXfCollection = $this->phpExcel->getCellXfCollection();
+ for ($i = 0; $i < 15; ++$i) {
+ $this->writerWorkbook->addXfWriter($cellXfCollection[0], true);
+ }
+
+ // add all the cell Xfs
+ foreach ($this->phpExcel->getCellXfCollection() as $style) {
+ $this->writerWorkbook->addXfWriter($style, false);
+ }
+
+ // add fonts from rich text eleemnts
+ for ($i = 0; $i < $countSheets; ++$i) {
+ foreach ($this->writerWorksheets[$i]->phpSheet->getCellCollection() as $cellID) {
+ $cell = $this->writerWorksheets[$i]->phpSheet->getCell($cellID);
+ $cVal = $cell->getValue();
+ if ($cVal instanceof PHPExcel_RichText) {
+ $elements = $cVal->getRichTextElements();
+ foreach ($elements as $element) {
+ if ($element instanceof PHPExcel_RichText_Run) {
+ $font = $element->getFont();
+ $this->writerWorksheets[$i]->fontHashIndex[$font->getHashCode()] = $this->writerWorkbook->addFont($font);
+ }
+ }
+ }
+ }
+ }
+
+ // initialize OLE file
+ $workbookStreamName = 'Workbook';
+ $OLE = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs($workbookStreamName));
+
+ // Write the worksheet streams before the global workbook stream,
+ // because the byte sizes of these are needed in the global workbook stream
+ $worksheetSizes = array();
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $this->writerWorksheets[$i]->close();
+ $worksheetSizes[] = $this->writerWorksheets[$i]->_datasize;
+ }
+
+ // add binary data for global workbook stream
+ $OLE->append($this->writerWorkbook->writeWorkbook($worksheetSizes));
+
+ // add binary data for sheet streams
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $OLE->append($this->writerWorksheets[$i]->getData());
+ }
+
+ $this->documentSummaryInformation = $this->writeDocumentSummaryInformation();
+ // initialize OLE Document Summary Information
+ if (isset($this->documentSummaryInformation) && !empty($this->documentSummaryInformation)) {
+ $OLE_DocumentSummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'DocumentSummaryInformation'));
+ $OLE_DocumentSummaryInformation->append($this->documentSummaryInformation);
+ }
+
+ $this->summaryInformation = $this->writeSummaryInformation();
+ // initialize OLE Summary Information
+ if (isset($this->summaryInformation) && !empty($this->summaryInformation)) {
+ $OLE_SummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'SummaryInformation'));
+ $OLE_SummaryInformation->append($this->summaryInformation);
+ }
+
+ // define OLE Parts
+ $arrRootData = array($OLE);
+ // initialize OLE Properties file
+ if (isset($OLE_SummaryInformation)) {
+ $arrRootData[] = $OLE_SummaryInformation;
+ }
+ // initialize OLE Extended Properties file
+ if (isset($OLE_DocumentSummaryInformation)) {
+ $arrRootData[] = $OLE_DocumentSummaryInformation;
+ }
+
+ $root = new PHPExcel_Shared_OLE_PPS_Root(time(), time(), $arrRootData);
+ // save the OLE file
+ $res = $root->save($pFilename);
+
+ PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);
+ PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ }
+
+ /**
+ * Set temporary storage directory
+ *
+ * @deprecated
+ * @param string $pValue Temporary storage directory
+ * @throws PHPExcel_Writer_Exception when directory does not exist
+ * @return PHPExcel_Writer_Excel5
+ */
+ public function setTempDir($pValue = '')
+ {
+ return $this;
+ }
+
+ /**
+ * Build the Worksheet Escher objects
+ *
+ */
+ private function buildWorksheetEschers()
+ {
+ // 1-based index to BstoreContainer
+ $blipIndex = 0;
+ $lastReducedSpId = 0;
+ $lastSpId = 0;
+
+ foreach ($this->phpExcel->getAllsheets() as $sheet) {
+ // sheet index
+ $sheetIndex = $sheet->getParent()->getIndex($sheet);
+
+ $escher = null;
+
+ // check if there are any shapes for this sheet
+ $filterRange = $sheet->getAutoFilter()->getRange();
+ if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) {
+ continue;
+ }
+
+ // create intermediate Escher object
+ $escher = new PHPExcel_Shared_Escher();
+
+ // dgContainer
+ $dgContainer = new PHPExcel_Shared_Escher_DgContainer();
+
+ // set the drawing index (we use sheet index + 1)
+ $dgId = $sheet->getParent()->getIndex($sheet) + 1;
+ $dgContainer->setDgId($dgId);
+ $escher->setDgContainer($dgContainer);
+
+ // spgrContainer
+ $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer();
+ $dgContainer->setSpgrContainer($spgrContainer);
+
+ // add one shape which is the group shape
+ $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
+ $spContainer->setSpgr(true);
+ $spContainer->setSpType(0);
+ $spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10);
+ $spgrContainer->addChild($spContainer);
+
+ // add the shapes
+
+ $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet
+
+ foreach ($sheet->getDrawingCollection() as $drawing) {
+ ++$blipIndex;
+
+ ++$countShapes[$sheetIndex];
+
+ // add the shape
+ $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
+
+ // set the shape type
+ $spContainer->setSpType(0x004B);
+ // set the shape flag
+ $spContainer->setSpFlag(0x02);
+
+ // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
+ $reducedSpId = $countShapes[$sheetIndex];
+ $spId = $reducedSpId
+ | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
+ $spContainer->setSpId($spId);
+
+ // keep track of last reducedSpId
+ $lastReducedSpId = $reducedSpId;
+
+ // keep track of last spId
+ $lastSpId = $spId;
+
+ // set the BLIP index
+ $spContainer->setOPT(0x4104, $blipIndex);
+
+ // set coordinates and offsets, client anchor
+ $coordinates = $drawing->getCoordinates();
+ $offsetX = $drawing->getOffsetX();
+ $offsetY = $drawing->getOffsetY();
+ $width = $drawing->getWidth();
+ $height = $drawing->getHeight();
+
+ $twoAnchor = PHPExcel_Shared_Excel5::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height);
+
+ $spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
+ $spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
+ $spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
+ $spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
+ $spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
+ $spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
+
+ $spgrContainer->addChild($spContainer);
+ }
+
+ // AutoFilters
+ if (!empty($filterRange)) {
+ $rangeBounds = PHPExcel_Cell::rangeBoundaries($filterRange);
+ $iNumColStart = $rangeBounds[0][0];
+ $iNumColEnd = $rangeBounds[1][0];
+
+ $iInc = $iNumColStart;
+ while ($iInc <= $iNumColEnd) {
+ ++$countShapes[$sheetIndex];
+
+ // create an Drawing Object for the dropdown
+ $oDrawing = new PHPExcel_Worksheet_BaseDrawing();
+ // get the coordinates of drawing
+ $cDrawing = PHPExcel_Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1];
+ $oDrawing->setCoordinates($cDrawing);
+ $oDrawing->setWorksheet($sheet);
+
+ // add the shape
+ $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer();
+ // set the shape type
+ $spContainer->setSpType(0x00C9);
+ // set the shape flag
+ $spContainer->setSpFlag(0x01);
+
+ // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
+ $reducedSpId = $countShapes[$sheetIndex];
+ $spId = $reducedSpId
+ | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
+ $spContainer->setSpId($spId);
+
+ // keep track of last reducedSpId
+ $lastReducedSpId = $reducedSpId;
+
+ // keep track of last spId
+ $lastSpId = $spId;
+
+ $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping
+ $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape
+ $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest
+ $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash
+ $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint
+
+ // set coordinates and offsets, client anchor
+ $endCoordinates = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::stringFromColumnIndex($iInc - 1));
+ $endCoordinates .= $rangeBounds[0][1] + 1;
+
+ $spContainer->setStartCoordinates($cDrawing);
+ $spContainer->setStartOffsetX(0);
+ $spContainer->setStartOffsetY(0);
+ $spContainer->setEndCoordinates($endCoordinates);
+ $spContainer->setEndOffsetX(0);
+ $spContainer->setEndOffsetY(0);
+
+ $spgrContainer->addChild($spContainer);
+ $iInc++;
+ }
+ }
+
+ // identifier clusters, used for workbook Escher object
+ $this->IDCLs[$dgId] = $lastReducedSpId;
+
+ // set last shape index
+ $dgContainer->setLastSpId($lastSpId);
+
+ // set the Escher object
+ $this->writerWorksheets[$sheetIndex]->setEscher($escher);
+ }
+ }
+
+ /**
+ * Build the Escher object corresponding to the MSODRAWINGGROUP record
+ */
+ private function buildWorkbookEscher()
+ {
+ $escher = null;
+
+ // any drawings in this workbook?
+ $found = false;
+ foreach ($this->phpExcel->getAllSheets() as $sheet) {
+ if (count($sheet->getDrawingCollection()) > 0) {
+ $found = true;
+ break;
+ }
+ }
+
+ // nothing to do if there are no drawings
+ if (!$found) {
+ return;
+ }
+
+ // if we reach here, then there are drawings in the workbook
+ $escher = new PHPExcel_Shared_Escher();
+
+ // dggContainer
+ $dggContainer = new PHPExcel_Shared_Escher_DggContainer();
+ $escher->setDggContainer($dggContainer);
+
+ // set IDCLs (identifier clusters)
+ $dggContainer->setIDCLs($this->IDCLs);
+
+ // this loop is for determining maximum shape identifier of all drawing
+ $spIdMax = 0;
+ $totalCountShapes = 0;
+ $countDrawings = 0;
+
+ foreach ($this->phpExcel->getAllsheets() as $sheet) {
+ $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet
+
+ if (count($sheet->getDrawingCollection()) > 0) {
+ ++$countDrawings;
+
+ foreach ($sheet->getDrawingCollection() as $drawing) {
+ ++$sheetCountShapes;
+ ++$totalCountShapes;
+
+ $spId = $sheetCountShapes | ($this->phpExcel->getIndex($sheet) + 1) << 10;
+ $spIdMax = max($spId, $spIdMax);
+ }
+ }
+ }
+
+ $dggContainer->setSpIdMax($spIdMax + 1);
+ $dggContainer->setCDgSaved($countDrawings);
+ $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing
+
+ // bstoreContainer
+ $bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer();
+ $dggContainer->setBstoreContainer($bstoreContainer);
+
+ // the BSE's (all the images)
+ foreach ($this->phpExcel->getAllsheets() as $sheet) {
+ foreach ($sheet->getDrawingCollection() as $drawing) {
+ if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
+ $filename = $drawing->getPath();
+
+ list($imagesx, $imagesy, $imageFormat) = getimagesize($filename);
+
+ switch ($imageFormat) {
+ case 1: // GIF, not supported by BIFF8, we convert to PNG
+ $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ ob_start();
+ imagepng(imagecreatefromgif($filename));
+ $blipData = ob_get_contents();
+ ob_end_clean();
+ break;
+ case 2: // JPEG
+ $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
+ $blipData = file_get_contents($filename);
+ break;
+ case 3: // PNG
+ $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ $blipData = file_get_contents($filename);
+ break;
+ case 6: // Windows DIB (BMP), we convert to PNG
+ $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ ob_start();
+ imagepng(PHPExcel_Shared_Drawing::imagecreatefrombmp($filename));
+ $blipData = ob_get_contents();
+ ob_end_clean();
+ break;
+ default:
+ continue 2;
+ }
+
+ $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
+ $blip->setData($blipData);
+
+ $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE();
+ $BSE->setBlipType($blipType);
+ $BSE->setBlip($blip);
+
+ $bstoreContainer->addBSE($BSE);
+ } elseif ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
+ switch ($drawing->getRenderingFunction()) {
+ case PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:
+ $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;
+ $renderingFunction = 'imagejpeg';
+ break;
+ case PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:
+ case PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:
+ case PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:
+ $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;
+ $renderingFunction = 'imagepng';
+ break;
+ }
+
+ ob_start();
+ call_user_func($renderingFunction, $drawing->getImageResource());
+ $blipData = ob_get_contents();
+ ob_end_clean();
+
+ $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
+ $blip->setData($blipData);
+
+ $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE();
+ $BSE->setBlipType($blipType);
+ $BSE->setBlip($blip);
+
+ $bstoreContainer->addBSE($BSE);
+ }
+ }
+ }
+
+ // Set the Escher object
+ $this->writerWorkbook->setEscher($escher);
+ }
+
+ /**
+ * Build the OLE Part for DocumentSummary Information
+ * @return string
+ */
+ private function writeDocumentSummaryInformation()
+ {
+ // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
+ $data = pack('v', 0xFFFE);
+ // offset: 2; size: 2;
+ $data .= pack('v', 0x0000);
+ // offset: 4; size: 2; OS version
+ $data .= pack('v', 0x0106);
+ // offset: 6; size: 2; OS indicator
+ $data .= pack('v', 0x0002);
+ // offset: 8; size: 16
+ $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
+ // offset: 24; size: 4; section count
+ $data .= pack('V', 0x0001);
+
+ // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
+ $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9);
+ // offset: 44; size: 4; offset of the start
+ $data .= pack('V', 0x30);
+
+ // SECTION
+ $dataSection = array();
+ $dataSection_NumProps = 0;
+ $dataSection_Summary = '';
+ $dataSection_Content = '';
+
+ // GKPIDDSI_CODEPAGE: CodePage
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
+ 'data' => array('data' => 1252));
+ $dataSection_NumProps++;
+
+ // GKPIDDSI_CATEGORY : Category
+ if ($this->phpExcel->getProperties()->getCategory()) {
+ $dataProp = $this->phpExcel->getProperties()->getCategory();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E),
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // GKPIDDSI_VERSION :Version of the application that wrote the property storage
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x03),
+ 'data' => array('pack' => 'V', 'data' => 0x000C0000));
+ $dataSection_NumProps++;
+ // GKPIDDSI_SCALE : FALSE
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+ // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+ // GKPIDDSI_SHAREDOC : FALSE
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+ // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x0B),
+ 'data' => array('data' => false));
+ $dataSection_NumProps++;
+
+ // GKPIDDSI_DOCSPARTS
+ // MS-OSHARED p75 (2.3.3.2.2.1)
+ // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9)
+ // cElements
+ $dataProp = pack('v', 0x0001);
+ $dataProp .= pack('v', 0x0000);
+ // array of UnalignedLpstr
+ // cch
+ $dataProp .= pack('v', 0x000A);
+ $dataProp .= pack('v', 0x0000);
+ // value
+ $dataProp .= 'Worksheet'.chr(0);
+
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x101E),
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+
+ // GKPIDDSI_HEADINGPAIR
+ // VtVecHeadingPairValue
+ // cElements
+ $dataProp = pack('v', 0x0002);
+ $dataProp .= pack('v', 0x0000);
+ // Array of vtHeadingPair
+ // vtUnalignedString - headingString
+ // stringType
+ $dataProp .= pack('v', 0x001E);
+ // padding
+ $dataProp .= pack('v', 0x0000);
+ // UnalignedLpstr
+ // cch
+ $dataProp .= pack('v', 0x0013);
+ $dataProp .= pack('v', 0x0000);
+ // value
+ $dataProp .= 'Feuilles de calcul';
+ // vtUnalignedString - headingParts
+ // wType : 0x0003 = 32 bit signed integer
+ $dataProp .= pack('v', 0x0300);
+ // padding
+ $dataProp .= pack('v', 0x0000);
+ // value
+ $dataProp .= pack('v', 0x0100);
+ $dataProp .= pack('v', 0x0000);
+ $dataProp .= pack('v', 0x0000);
+ $dataProp .= pack('v', 0x0000);
$dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x100C),
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x100C),
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+
+ // 4 Section Length
+ // 4 Property count
+ // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
+ $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
+ foreach ($dataSection as $dataProp) {
+ // Summary
+ $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
+ // Offset
+ $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
+ // DataType
+ $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
+ // Data
+ if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
+
+ $dataSection_Content_Offset += 4 + 4;
+ } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
+
+ $dataSection_Content_Offset += 4 + 4;
+ } elseif ($dataProp['type']['data'] == 0x0B) { // Boolean
+ if ($dataProp['data']['data'] == false) {
+ $dataSection_Content .= pack('V', 0x0000);
+ } else {
+ $dataSection_Content .= pack('V', 0x0001);
+ }
+ $dataSection_Content_Offset += 4 + 4;
+ } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length
+ // Null-terminated string
+ $dataProp['data']['data'] .= chr(0);
+ $dataProp['data']['length'] += 1;
+ // Complete the string with null string for being a %4
+ $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
+ $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
+
+ $dataSection_Content .= pack('V', $dataProp['data']['length']);
+ $dataSection_Content .= $dataProp['data']['data'];
+
+ $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
+ } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ $dataSection_Content .= $dataProp['data']['data'];
+
+ $dataSection_Content_Offset += 4 + 8;
+ } else {
+ // Data Type Not Used at the moment
+ $dataSection_Content .= $dataProp['data']['data'];
+
+ $dataSection_Content_Offset += 4 + $dataProp['data']['length'];
+ }
+ }
+ // Now $dataSection_Content_Offset contains the size of the content
+
+ // section header
+ // offset: $secOffset; size: 4; section length
+ // + x Size of the content (summary + content)
+ $data .= pack('V', $dataSection_Content_Offset);
+ // offset: $secOffset+4; size: 4; property count
+ $data .= pack('V', $dataSection_NumProps);
+ // Section Summary
+ $data .= $dataSection_Summary;
+ // Section Content
+ $data .= $dataSection_Content;
+
+ return $data;
+ }
+
+ /**
+ * Build the OLE Part for Summary Information
+ * @return string
+ */
+ private function writeSummaryInformation()
+ {
+ // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
+ $data = pack('v', 0xFFFE);
+ // offset: 2; size: 2;
+ $data .= pack('v', 0x0000);
+ // offset: 4; size: 2; OS version
+ $data .= pack('v', 0x0106);
+ // offset: 6; size: 2; OS indicator
+ $data .= pack('v', 0x0002);
+ // offset: 8; size: 16
+ $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
+ // offset: 24; size: 4; section count
+ $data .= pack('V', 0x0001);
+
+ // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
+ $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3);
+ // offset: 44; size: 4; offset of the start
+ $data .= pack('V', 0x30);
+
+ // SECTION
+ $dataSection = array();
+ $dataSection_NumProps = 0;
+ $dataSection_Summary = '';
+ $dataSection_Content = '';
+
+ // CodePage : CP-1252
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
+ 'data' => array('data' => 1252));
$dataSection_NumProps++;
- // 4 Section Length
- // 4 Property count
- // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
- $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
- foreach ($dataSection as $dataProp){
- // Summary
- $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
- // Offset
- $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
- // DataType
- $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
- // Data
- if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
-
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
-
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x0B){ // Boolean
- if($dataProp['data']['data'] == false){
- $dataSection_Content .= pack('V', 0x0000);
- } else {
- $dataSection_Content .= pack('V', 0x0001);
- }
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length
- // Null-terminated string
- $dataProp['data']['data'] .= chr(0);
- $dataProp['data']['length'] += 1;
- // Complete the string with null string for being a %4
- $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
- $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
-
- $dataSection_Content .= pack('V', $dataProp['data']['length']);
- $dataSection_Content .= $dataProp['data']['data'];
-
- $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
- }
- elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- $dataSection_Content .= $dataProp['data']['data'];
-
- $dataSection_Content_Offset += 4 + 8;
- }
- else {
- // Data Type Not Used at the moment
- $dataSection_Content .= $dataProp['data']['data'];
-
- $dataSection_Content_Offset += 4 + $dataProp['data']['length'];
- }
- }
- // Now $dataSection_Content_Offset contains the size of the content
-
- // section header
- // offset: $secOffset; size: 4; section length
- // + x Size of the content (summary + content)
- $data .= pack('V', $dataSection_Content_Offset);
- // offset: $secOffset+4; size: 4; property count
- $data .= pack('V', $dataSection_NumProps);
- // Section Summary
- $data .= $dataSection_Summary;
- // Section Content
- $data .= $dataSection_Content;
-
- return $data;
- }
-
- /**
- * Build the OLE Part for Summary Information
- * @return string
- */
- private function _writeSummaryInformation(){
- // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
- $data = pack('v', 0xFFFE);
- // offset: 2; size: 2;
- $data .= pack('v', 0x0000);
- // offset: 4; size: 2; OS version
- $data .= pack('v', 0x0106);
- // offset: 6; size: 2; OS indicator
- $data .= pack('v', 0x0002);
- // offset: 8; size: 16
- $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
- // offset: 24; size: 4; section count
- $data .= pack('V', 0x0001);
-
- // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
- $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3);
- // offset: 44; size: 4; offset of the start
- $data .= pack('V', 0x30);
-
- // SECTION
- $dataSection = array();
- $dataSection_NumProps = 0;
- $dataSection_Summary = '';
- $dataSection_Content = '';
-
- // CodePage : CP-1252
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer
- 'data' => array('data' => 1252));
- $dataSection_NumProps++;
-
- // Title
- if($this->_phpExcel->getProperties()->getTitle()){
- $dataProp = $this->_phpExcel->getProperties()->getTitle();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Subject
- if($this->_phpExcel->getProperties()->getSubject()){
- $dataProp = $this->_phpExcel->getProperties()->getSubject();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Author (Creator)
- if($this->_phpExcel->getProperties()->getCreator()){
- $dataProp = $this->_phpExcel->getProperties()->getCreator();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Keywords
- if($this->_phpExcel->getProperties()->getKeywords()){
- $dataProp = $this->_phpExcel->getProperties()->getKeywords();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Comments (Description)
- if($this->_phpExcel->getProperties()->getDescription()){
- $dataProp = $this->_phpExcel->getProperties()->getDescription();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Last Saved By (LastModifiedBy)
- if($this->_phpExcel->getProperties()->getLastModifiedBy()){
- $dataProp = $this->_phpExcel->getProperties()->getLastModifiedBy();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
- 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
- $dataSection_NumProps++;
- }
- // Created Date/Time
- if($this->_phpExcel->getProperties()->getCreated()){
- $dataProp = $this->_phpExcel->getProperties()->getCreated();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp)));
- $dataSection_NumProps++;
- }
- // Modified Date/Time
- if($this->_phpExcel->getProperties()->getModified()){
- $dataProp = $this->_phpExcel->getProperties()->getModified();
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp)));
- $dataSection_NumProps++;
- }
- // Security
- $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
- 'offset' => array('pack' => 'V'),
- 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer
- 'data' => array('data' => 0x00));
- $dataSection_NumProps++;
-
-
- // 4 Section Length
- // 4 Property count
- // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
- $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
- foreach ($dataSection as $dataProp){
- // Summary
- $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
- // Offset
- $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
- // DataType
- $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
- // Data
- if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
-
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer
- $dataSection_Content .= pack('V', $dataProp['data']['data']);
-
- $dataSection_Content_Offset += 4 + 4;
- }
- elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length
- // Null-terminated string
- $dataProp['data']['data'] .= chr(0);
- $dataProp['data']['length'] += 1;
- // Complete the string with null string for being a %4
- $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
- $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
-
- $dataSection_Content .= pack('V', $dataProp['data']['length']);
- $dataSection_Content .= $dataProp['data']['data'];
-
- $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
- }
- elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
- $dataSection_Content .= $dataProp['data']['data'];
-
- $dataSection_Content_Offset += 4 + 8;
- }
- else {
- // Data Type Not Used at the moment
- }
- }
- // Now $dataSection_Content_Offset contains the size of the content
-
- // section header
- // offset: $secOffset; size: 4; section length
- // + x Size of the content (summary + content)
- $data .= pack('V', $dataSection_Content_Offset);
- // offset: $secOffset+4; size: 4; property count
- $data .= pack('V', $dataSection_NumProps);
- // Section Summary
- $data .= $dataSection_Summary;
- // Section Content
- $data .= $dataSection_Content;
-
- return $data;
- }
-}
\ No newline at end of file
+ // Title
+ if ($this->phpExcel->getProperties()->getTitle()) {
+ $dataProp = $this->phpExcel->getProperties()->getTitle();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Subject
+ if ($this->phpExcel->getProperties()->getSubject()) {
+ $dataProp = $this->phpExcel->getProperties()->getSubject();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Author (Creator)
+ if ($this->phpExcel->getProperties()->getCreator()) {
+ $dataProp = $this->phpExcel->getProperties()->getCreator();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Keywords
+ if ($this->phpExcel->getProperties()->getKeywords()) {
+ $dataProp = $this->phpExcel->getProperties()->getKeywords();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Comments (Description)
+ if ($this->phpExcel->getProperties()->getDescription()) {
+ $dataProp = $this->phpExcel->getProperties()->getDescription();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Last Saved By (LastModifiedBy)
+ if ($this->phpExcel->getProperties()->getLastModifiedBy()) {
+ $dataProp = $this->phpExcel->getProperties()->getLastModifiedBy();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length
+ 'data' => array('data' => $dataProp, 'length' => strlen($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Created Date/Time
+ if ($this->phpExcel->getProperties()->getCreated()) {
+ $dataProp = $this->phpExcel->getProperties()->getCreated();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Modified Date/Time
+ if ($this->phpExcel->getProperties()->getModified()) {
+ $dataProp = $this->phpExcel->getProperties()->getModified();
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp)));
+ $dataSection_NumProps++;
+ }
+ // Security
+ $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13),
+ 'offset' => array('pack' => 'V'),
+ 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer
+ 'data' => array('data' => 0x00));
+ $dataSection_NumProps++;
+
+
+ // 4 Section Length
+ // 4 Property count
+ // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
+ $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
+ foreach ($dataSection as $dataProp) {
+ // Summary
+ $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
+ // Offset
+ $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
+ // DataType
+ $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
+ // Data
+ if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
+
+ $dataSection_Content_Offset += 4 + 4;
+ } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer
+ $dataSection_Content .= pack('V', $dataProp['data']['data']);
+
+ $dataSection_Content_Offset += 4 + 4;
+ } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length
+ // Null-terminated string
+ $dataProp['data']['data'] .= chr(0);
+ $dataProp['data']['length'] += 1;
+ // Complete the string with null string for being a %4
+ $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4));
+ $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
+
+ $dataSection_Content .= pack('V', $dataProp['data']['length']);
+ $dataSection_Content .= $dataProp['data']['data'];
+
+ $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
+ } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
+ $dataSection_Content .= $dataProp['data']['data'];
+
+ $dataSection_Content_Offset += 4 + 8;
+ } else {
+ // Data Type Not Used at the moment
+ }
+ }
+ // Now $dataSection_Content_Offset contains the size of the content
+
+ // section header
+ // offset: $secOffset; size: 4; section length
+ // + x Size of the content (summary + content)
+ $data .= pack('V', $dataSection_Content_Offset);
+ // offset: $secOffset+4; size: 4; property count
+ $data .= pack('V', $dataSection_NumProps);
+ // Section Summary
+ $data .= $dataSection_Summary;
+ // Section Content
+ $data .= $dataSection_Content;
+
+ return $data;
+ }
+}
diff --git a/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php b/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php
index 20c125d0c..a79575239 100644
--- a/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php
+++ b/Classes/PHPExcel/Writer/Excel5/BIFFwriter.php
@@ -1,8 +1,9 @@
little endian, 1 => big endian
- * @var integer
- */
- private static $_byte_order;
-
- /**
- * The string containing the data of the BIFF stream
- * @var string
- */
- public $_data;
-
- /**
- * The size of the data in bytes. Should be the same as strlen($this->_data)
- * @var integer
- */
- public $_datasize;
-
- /**
- * The maximum length for a BIFF record (excluding record header and length field). See _addContinue()
- * @var integer
- * @see _addContinue()
- */
- public $_limit = 8224;
-
- /**
- * Constructor
- */
- public function __construct()
- {
- $this->_data = '';
- $this->_datasize = 0;
-// $this->_limit = 8224;
- }
-
- /**
- * Determine the byte order and store it as class data to avoid
- * recalculating it for each call to new().
- *
- * @return int
- */
- public static function getByteOrder()
- {
- if (!isset(self::$_byte_order)) {
- // Check if "pack" gives the required IEEE 64bit float
- $teststr = pack("d", 1.2345);
- $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
- if ($number == $teststr) {
- $byte_order = 0; // Little Endian
- } elseif ($number == strrev($teststr)){
- $byte_order = 1; // Big Endian
- } else {
- // Give up. I'll fix this in a later version.
- throw new PHPExcel_Writer_Exception("Required floating point format not supported on this platform.");
- }
- self::$_byte_order = $byte_order;
- }
-
- return self::$_byte_order;
- }
-
- /**
- * General storage function
- *
- * @param string $data binary data to append
- * @access private
- */
- function _append($data)
- {
- if (strlen($data) - 4 > $this->_limit) {
- $data = $this->_addContinue($data);
- }
- $this->_data .= $data;
- $this->_datasize += strlen($data);
- }
-
- /**
- * General storage function like _append, but returns string instead of modifying $this->_data
- *
- * @param string $data binary data to write
- * @return string
- */
- public function writeData($data)
- {
- if (strlen($data) - 4 > $this->_limit) {
- $data = $this->_addContinue($data);
- }
- $this->_datasize += strlen($data);
-
- return $data;
- }
-
- /**
- * Writes Excel BOF record to indicate the beginning of a stream or
- * sub-stream in the BIFF file.
- *
- * @param integer $type Type of BIFF file to write: 0x0005 Workbook,
- * 0x0010 Worksheet.
- * @access private
- */
- function _storeBof($type)
- {
- $record = 0x0809; // Record identifier (BIFF5-BIFF8)
- $length = 0x0010;
-
- // by inspection of real files, MS Office Excel 2007 writes the following
- $unknown = pack("VV", 0x000100D1, 0x00000406);
-
- $build = 0x0DBB; // Excel 97
- $year = 0x07CC; // Excel 97
-
- $version = 0x0600; // BIFF8
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $version, $type, $build, $year);
- $this->_append($header . $data . $unknown);
- }
-
- /**
- * Writes Excel EOF record to indicate the end of a BIFF stream.
- *
- * @access private
- */
- function _storeEof()
- {
- $record = 0x000A; // Record identifier
- $length = 0x0000; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $this->_append($header);
- }
-
- /**
- * Writes Excel EOF record to indicate the end of a BIFF stream.
- *
- * @access private
- */
- public function writeEof()
- {
- $record = 0x000A; // Record identifier
- $length = 0x0000; // Number of bytes to follow
- $header = pack("vv", $record, $length);
- return $this->writeData($header);
- }
-
- /**
- * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
- * Excel 97 the limit is 8228 bytes. Records that are longer than these limits
- * must be split up into CONTINUE blocks.
- *
- * This function takes a long BIFF record and inserts CONTINUE records as
- * necessary.
- *
- * @param string $data The original binary data to be written
- * @return string A very convenient string of continue blocks
- * @access private
- */
- function _addContinue($data)
- {
- $limit = $this->_limit;
- $record = 0x003C; // Record identifier
-
- // The first 2080/8224 bytes remain intact. However, we have to change
- // the length field of the record.
- $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit);
-
- $header = pack("vv", $record, $limit); // Headers for continue records
-
- // Retrieve chunks of 2080/8224 bytes +4 for the header.
- $data_length = strlen($data);
- for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) {
- $tmp .= $header;
- $tmp .= substr($data, $i, $limit);
- }
-
- // Retrieve the last chunk of data
- $header = pack("vv", $record, strlen($data) - $i);
- $tmp .= $header;
- $tmp .= substr($data, $i, strlen($data) - $i);
-
- return $tmp;
- }
-
+ /**
+ * The byte order of this architecture. 0 => little endian, 1 => big endian
+ * @var integer
+ */
+ private static $byteOrder;
+
+ /**
+ * The string containing the data of the BIFF stream
+ * @var string
+ */
+ public $_data;
+
+ /**
+ * The size of the data in bytes. Should be the same as strlen($this->_data)
+ * @var integer
+ */
+ public $_datasize;
+
+ /**
+ * The maximum length for a BIFF record (excluding record header and length field). See addContinue()
+ * @var integer
+ * @see addContinue()
+ */
+ private $limit = 8224;
+
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ $this->_data = '';
+ $this->_datasize = 0;
+// $this->limit = 8224;
+ }
+
+ /**
+ * Determine the byte order and store it as class data to avoid
+ * recalculating it for each call to new().
+ *
+ * @return int
+ */
+ public static function getByteOrder()
+ {
+ if (!isset(self::$byteOrder)) {
+ // Check if "pack" gives the required IEEE 64bit float
+ $teststr = pack("d", 1.2345);
+ $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
+ if ($number == $teststr) {
+ $byte_order = 0; // Little Endian
+ } elseif ($number == strrev($teststr)) {
+ $byte_order = 1; // Big Endian
+ } else {
+ // Give up. I'll fix this in a later version.
+ throw new PHPExcel_Writer_Exception("Required floating point format not supported on this platform.");
+ }
+ self::$byteOrder = $byte_order;
+ }
+
+ return self::$byteOrder;
+ }
+
+ /**
+ * General storage function
+ *
+ * @param string $data binary data to append
+ * @access private
+ */
+ protected function append($data)
+ {
+ if (strlen($data) - 4 > $this->limit) {
+ $data = $this->addContinue($data);
+ }
+ $this->_data .= $data;
+ $this->_datasize += strlen($data);
+ }
+
+ /**
+ * General storage function like append, but returns string instead of modifying $this->_data
+ *
+ * @param string $data binary data to write
+ * @return string
+ */
+ public function writeData($data)
+ {
+ if (strlen($data) - 4 > $this->limit) {
+ $data = $this->addContinue($data);
+ }
+ $this->_datasize += strlen($data);
+
+ return $data;
+ }
+
+ /**
+ * Writes Excel BOF record to indicate the beginning of a stream or
+ * sub-stream in the BIFF file.
+ *
+ * @param integer $type Type of BIFF file to write: 0x0005 Workbook,
+ * 0x0010 Worksheet.
+ * @access private
+ */
+ protected function storeBof($type)
+ {
+ $record = 0x0809; // Record identifier (BIFF5-BIFF8)
+ $length = 0x0010;
+
+ // by inspection of real files, MS Office Excel 2007 writes the following
+ $unknown = pack("VV", 0x000100D1, 0x00000406);
+
+ $build = 0x0DBB; // Excel 97
+ $year = 0x07CC; // Excel 97
+
+ $version = 0x0600; // BIFF8
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $version, $type, $build, $year);
+ $this->append($header . $data . $unknown);
+ }
+
+ /**
+ * Writes Excel EOF record to indicate the end of a BIFF stream.
+ *
+ * @access private
+ */
+ protected function storeEof()
+ {
+ $record = 0x000A; // Record identifier
+ $length = 0x0000; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $this->append($header);
+ }
+
+ /**
+ * Writes Excel EOF record to indicate the end of a BIFF stream.
+ *
+ * @access private
+ */
+ public function writeEof()
+ {
+ $record = 0x000A; // Record identifier
+ $length = 0x0000; // Number of bytes to follow
+ $header = pack("vv", $record, $length);
+ return $this->writeData($header);
+ }
+
+ /**
+ * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
+ * Excel 97 the limit is 8228 bytes. Records that are longer than these limits
+ * must be split up into CONTINUE blocks.
+ *
+ * This function takes a long BIFF record and inserts CONTINUE records as
+ * necessary.
+ *
+ * @param string $data The original binary data to be written
+ * @return string A very convenient string of continue blocks
+ * @access private
+ */
+ private function addContinue($data)
+ {
+ $limit = $this->limit;
+ $record = 0x003C; // Record identifier
+
+ // The first 2080/8224 bytes remain intact. However, we have to change
+ // the length field of the record.
+ $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit);
+
+ $header = pack("vv", $record, $limit); // Headers for continue records
+
+ // Retrieve chunks of 2080/8224 bytes +4 for the header.
+ $data_length = strlen($data);
+ for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) {
+ $tmp .= $header;
+ $tmp .= substr($data, $i, $limit);
+ }
+
+ // Retrieve the last chunk of data
+ $header = pack("vv", $record, strlen($data) - $i);
+ $tmp .= $header;
+ $tmp .= substr($data, $i, strlen($data) - $i);
+
+ return $tmp;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Escher.php b/Classes/PHPExcel/Writer/Excel5/Escher.php
index 91fc27b05..c37fda9b6 100644
--- a/Classes/PHPExcel/Writer/Excel5/Escher.php
+++ b/Classes/PHPExcel/Writer/Excel5/Escher.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (c) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,8 +20,8 @@
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel5
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
- * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,507 +31,493 @@
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel5
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Writer_Excel5_Escher
{
- /**
- * The object we are writing
- */
- private $_object;
-
- /**
- * The written binary data
- */
- private $_data;
-
- /**
- * Shape offsets. Positions in binary stream where a new shape record begins
- *
- * @var array
- */
- private $_spOffsets;
-
- /**
- * Shape types.
- *
- * @var array
- */
- private $_spTypes;
-
- /**
- * Constructor
- *
- * @param mixed
- */
- public function __construct($object)
- {
- $this->_object = $object;
- }
-
- /**
- * Process the object to be written
- */
- public function close()
- {
- // initialize
- $this->_data = '';
-
- switch (get_class($this->_object)) {
-
- case 'PHPExcel_Shared_Escher':
- if ($dggContainer = $this->_object->getDggContainer()) {
- $writer = new PHPExcel_Writer_Excel5_Escher($dggContainer);
- $this->_data = $writer->close();
- } else if ($dgContainer = $this->_object->getDgContainer()) {
- $writer = new PHPExcel_Writer_Excel5_Escher($dgContainer);
- $this->_data = $writer->close();
- $this->_spOffsets = $writer->getSpOffsets();
- $this->_spTypes = $writer->getSpTypes();
- }
- break;
-
- case 'PHPExcel_Shared_Escher_DggContainer':
- // this is a container record
-
- // initialize
- $innerData = '';
-
- // write the dgg
- $recVer = 0x0;
- $recInstance = 0x0000;
- $recType = 0xF006;
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- // dgg data
- $dggData =
- pack('VVVV'
- , $this->_object->getSpIdMax() // maximum shape identifier increased by one
- , $this->_object->getCDgSaved() + 1 // number of file identifier clusters increased by one
- , $this->_object->getCSpSaved()
- , $this->_object->getCDgSaved() // count total number of drawings saved
- );
-
- // add file identifier clusters (one per drawing)
- $IDCLs = $this->_object->getIDCLs();
-
- foreach ($IDCLs as $dgId => $maxReducedSpId) {
- $dggData .= pack('VV', $dgId, $maxReducedSpId + 1);
- }
-
- $header = pack('vvV', $recVerInstance, $recType, strlen($dggData));
- $innerData .= $header . $dggData;
-
- // write the bstoreContainer
- if ($bstoreContainer = $this->_object->getBstoreContainer()) {
- $writer = new PHPExcel_Writer_Excel5_Escher($bstoreContainer);
- $innerData .= $writer->close();
- }
-
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF000;
- $length = strlen($innerData);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
-
- $this->_data = $header . $innerData;
- break;
-
- case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer':
- // this is a container record
-
- // initialize
- $innerData = '';
-
- // treat the inner data
- if ($BSECollection = $this->_object->getBSECollection()) {
- foreach ($BSECollection as $BSE) {
- $writer = new PHPExcel_Writer_Excel5_Escher($BSE);
- $innerData .= $writer->close();
- }
- }
-
- // write the record
- $recVer = 0xF;
- $recInstance = count($this->_object->getBSECollection());
- $recType = 0xF001;
- $length = strlen($innerData);
+ /**
+ * The object we are writing
+ */
+ private $object;
+
+ /**
+ * The written binary data
+ */
+ private $data;
+
+ /**
+ * Shape offsets. Positions in binary stream where a new shape record begins
+ *
+ * @var array
+ */
+ private $spOffsets;
+
+ /**
+ * Shape types.
+ *
+ * @var array
+ */
+ private $spTypes;
+
+ /**
+ * Constructor
+ *
+ * @param mixed
+ */
+ public function __construct($object)
+ {
+ $this->object = $object;
+ }
+
+ /**
+ * Process the object to be written
+ */
+ public function close()
+ {
+ // initialize
+ $this->data = '';
+
+ switch (get_class($this->object)) {
+ case 'PHPExcel_Shared_Escher':
+ if ($dggContainer = $this->object->getDggContainer()) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($dggContainer);
+ $this->data = $writer->close();
+ } elseif ($dgContainer = $this->object->getDgContainer()) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($dgContainer);
+ $this->data = $writer->close();
+ $this->spOffsets = $writer->getSpOffsets();
+ $this->spTypes = $writer->getSpTypes();
+ }
+ break;
+ case 'PHPExcel_Shared_Escher_DggContainer':
+ // this is a container record
+
+ // initialize
+ $innerData = '';
+
+ // write the dgg
+ $recVer = 0x0;
+ $recInstance = 0x0000;
+ $recType = 0xF006;
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ // dgg data
+ $dggData =
+ pack(
+ 'VVVV',
+ $this->object->getSpIdMax(), // maximum shape identifier increased by one
+ $this->object->getCDgSaved() + 1, // number of file identifier clusters increased by one
+ $this->object->getCSpSaved(),
+ $this->object->getCDgSaved() // count total number of drawings saved
+ );
+
+ // add file identifier clusters (one per drawing)
+ $IDCLs = $this->object->getIDCLs();
+
+ foreach ($IDCLs as $dgId => $maxReducedSpId) {
+ $dggData .= pack('VV', $dgId, $maxReducedSpId + 1);
+ }
+
+ $header = pack('vvV', $recVerInstance, $recType, strlen($dggData));
+ $innerData .= $header . $dggData;
+
+ // write the bstoreContainer
+ if ($bstoreContainer = $this->object->getBstoreContainer()) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($bstoreContainer);
+ $innerData .= $writer->close();
+ }
+
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF000;
+ $length = strlen($innerData);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+
+ $this->data = $header . $innerData;
+ break;
+ case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer':
+ // this is a container record
+
+ // initialize
+ $innerData = '';
+
+ // treat the inner data
+ if ($BSECollection = $this->object->getBSECollection()) {
+ foreach ($BSECollection as $BSE) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($BSE);
+ $innerData .= $writer->close();
+ }
+ }
+
+ // write the record
+ $recVer = 0xF;
+ $recInstance = count($this->object->getBSECollection());
+ $recType = 0xF001;
+ $length = strlen($innerData);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+
+ $this->data = $header . $innerData;
+ break;
+ case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE':
+ // this is a semi-container record
+
+ // initialize
+ $innerData = '';
+
+ // here we treat the inner data
+ if ($blip = $this->object->getBlip()) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($blip);
+ $innerData .= $writer->close();
+ }
+
+ // initialize
+ $data = '';
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $btWin32 = $this->object->getBlipType();
+ $btMacOS = $this->object->getBlipType();
+ $data .= pack('CC', $btWin32, $btMacOS);
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $rgbUid = pack('VVVV', 0, 0, 0, 0); // todo
+ $data .= $rgbUid;
- $this->_data = $header . $innerData;
- break;
+ $tag = 0;
+ $size = strlen($innerData);
+ $cRef = 1;
+ $foDelay = 0; //todo
+ $unused1 = 0x0;
+ $cbName = 0x0;
+ $unused2 = 0x0;
+ $unused3 = 0x0;
+ $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3);
- case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE':
- // this is a semi-container record
+ $data .= $innerData;
- // initialize
- $innerData = '';
+ // write the record
+ $recVer = 0x2;
+ $recInstance = $this->object->getBlipType();
+ $recType = 0xF007;
+ $length = strlen($data);
- // here we treat the inner data
- if ($blip = $this->_object->getBlip()) {
- $writer = new PHPExcel_Writer_Excel5_Escher($blip);
- $innerData .= $writer->close();
- }
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- // initialize
- $data = '';
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $btWin32 = $this->_object->getBlipType();
- $btMacOS = $this->_object->getBlipType();
- $data .= pack('CC', $btWin32, $btMacOS);
+ $this->data = $header;
- $rgbUid = pack('VVVV', 0,0,0,0); // todo
- $data .= $rgbUid;
+ $this->data .= $data;
+ break;
+ case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip':
+ // this is an atom record
- $tag = 0;
- $size = strlen($innerData);
- $cRef = 1;
- $foDelay = 0; //todo
- $unused1 = 0x0;
- $cbName = 0x0;
- $unused2 = 0x0;
- $unused3 = 0x0;
- $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3);
+ // write the record
+ switch ($this->object->getParent()->getBlipType()) {
+ case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG:
+ // initialize
+ $innerData = '';
- $data .= $innerData;
+ $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo
+ $innerData .= $rgbUid1;
- // write the record
- $recVer = 0x2;
- $recInstance = $this->_object->getBlipType();
- $recType = 0xF007;
- $length = strlen($data);
+ $tag = 0xFF; // todo
+ $innerData .= pack('C', $tag);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $innerData .= $this->object->getData();
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $recVer = 0x0;
+ $recInstance = 0x46A;
+ $recType = 0xF01D;
+ $length = strlen($innerData);
- $this->_data = $header;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $this->_data .= $data;
- break;
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip':
- // this is an atom record
+ $this->data = $header;
- // write the record
- switch ($this->_object->getParent()->getBlipType()) {
+ $this->data .= $innerData;
+ break;
- case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG:
- // initialize
- $innerData = '';
+ case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG:
+ // initialize
+ $innerData = '';
- $rgbUid1 = pack('VVVV', 0,0,0,0); // todo
- $innerData .= $rgbUid1;
+ $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo
+ $innerData .= $rgbUid1;
- $tag = 0xFF; // todo
- $innerData .= pack('C', $tag);
+ $tag = 0xFF; // todo
+ $innerData .= pack('C', $tag);
- $innerData .= $this->_object->getData();
+ $innerData .= $this->object->getData();
- $recVer = 0x0;
- $recInstance = 0x46A;
- $recType = 0xF01D;
- $length = strlen($innerData);
+ $recVer = 0x0;
+ $recInstance = 0x6E0;
+ $recType = 0xF01E;
+ $length = strlen($innerData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $this->_data = $header;
+ $this->data = $header;
- $this->_data .= $innerData;
- break;
+ $this->data .= $innerData;
+ break;
+ }
+ break;
+ case 'PHPExcel_Shared_Escher_DgContainer':
+ // this is a container record
- case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG:
- // initialize
- $innerData = '';
+ // initialize
+ $innerData = '';
- $rgbUid1 = pack('VVVV', 0,0,0,0); // todo
- $innerData .= $rgbUid1;
+ // write the dg
+ $recVer = 0x0;
+ $recInstance = $this->object->getDgId();
+ $recType = 0xF008;
+ $length = 8;
- $tag = 0xFF; // todo
- $innerData .= pack('C', $tag);
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $innerData .= $this->_object->getData();
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $recVer = 0x0;
- $recInstance = 0x6E0;
- $recType = 0xF01E;
- $length = strlen($innerData);
+ // number of shapes in this drawing (including group shape)
+ $countShapes = count($this->object->getSpgrContainer()->getChildren());
+ $innerData .= $header . pack('VV', $countShapes, $this->object->getLastSpId());
+ //$innerData .= $header . pack('VV', 0, 0);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ // write the spgrContainer
+ if ($spgrContainer = $this->object->getSpgrContainer()) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($spgrContainer);
+ $innerData .= $writer->close();
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ // get the shape offsets relative to the spgrContainer record
+ $spOffsets = $writer->getSpOffsets();
+ $spTypes = $writer->getSpTypes();
+
+ // save the shape offsets relative to dgContainer
+ foreach ($spOffsets as & $spOffset) {
+ $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes)
+ }
- $this->_data = $header;
+ $this->spOffsets = $spOffsets;
+ $this->spTypes = $spTypes;
+ }
- $this->_data .= $innerData;
- break;
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF002;
+ $length = strlen($innerData);
- }
- break;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- case 'PHPExcel_Shared_Escher_DgContainer':
- // this is a container record
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- // initialize
- $innerData = '';
+ $this->data = $header . $innerData;
+ break;
+ case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer':
+ // this is a container record
- // write the dg
- $recVer = 0x0;
- $recInstance = $this->_object->getDgId();
- $recType = 0xF008;
- $length = 8;
+ // initialize
+ $innerData = '';
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ // initialize spape offsets
+ $totalSize = 8;
+ $spOffsets = array();
+ $spTypes = array();
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ // treat the inner data
+ foreach ($this->object->getChildren() as $spContainer) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($spContainer);
+ $spData = $writer->close();
+ $innerData .= $spData;
+
+ // save the shape offsets (where new shape records begin)
+ $totalSize += strlen($spData);
+ $spOffsets[] = $totalSize;
+
+ $spTypes = array_merge($spTypes, $writer->getSpTypes());
+ }
- // number of shapes in this drawing (including group shape)
- $countShapes = count($this->_object->getSpgrContainer()->getChildren());
- $innerData .= $header . pack('VV', $countShapes, $this->_object->getLastSpId());
- //$innerData .= $header . pack('VV', 0, 0);
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF003;
+ $length = strlen($innerData);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- // write the spgrContainer
- if ($spgrContainer = $this->_object->getSpgrContainer()) {
- $writer = new PHPExcel_Writer_Excel5_Escher($spgrContainer);
- $innerData .= $writer->close();
+ $this->data = $header . $innerData;
+ $this->spOffsets = $spOffsets;
+ $this->spTypes = $spTypes;
+ break;
+ case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer':
+ // initialize
+ $data = '';
+
+ // build the data
+
+ // write group shape record, if necessary?
+ if ($this->object->getSpgr()) {
+ $recVer = 0x1;
+ $recInstance = 0x0000;
+ $recType = 0xF009;
+ $length = 0x00000010;
- // get the shape offsets relative to the spgrContainer record
- $spOffsets = $writer->getSpOffsets();
- $spTypes = $writer->getSpTypes();
-
- // save the shape offsets relative to dgContainer
- foreach ($spOffsets as & $spOffset) {
- $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes)
- }
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+
+ $data .= $header . pack('VVVV', 0, 0, 0, 0);
+ }
+ $this->spTypes[] = ($this->object->getSpType());
- $this->_spOffsets = $spOffsets;
- $this->_spTypes = $spTypes;
- }
+ // write the shape record
+ $recVer = 0x2;
+ $recInstance = $this->object->getSpType(); // shape type
+ $recType = 0xF00A;
+ $length = 0x00000008;
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF002;
- $length = strlen($innerData);
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . pack('VV', $this->object->getSpId(), $this->object->getSpgr() ? 0x0005 : 0x0A00);
- $this->_data = $header . $innerData;
- break;
- case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer':
- // this is a container record
+ // the options
+ if ($this->object->getOPTCollection()) {
+ $optData = '';
+
+ $recVer = 0x3;
+ $recInstance = count($this->object->getOPTCollection());
+ $recType = 0xF00B;
+ foreach ($this->object->getOPTCollection() as $property => $value) {
+ $optData .= pack('vV', $property, $value);
+ }
+ $length = strlen($optData);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
+
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . $optData;
+ }
+
+ // the client anchor
+ if ($this->object->getStartCoordinates()) {
+ $clientAnchorData = '';
+
+ $recVer = 0x0;
+ $recInstance = 0x0;
+ $recType = 0xF010;
+
+ // start coordinates
+ list($column, $row) = PHPExcel_Cell::coordinateFromString($this->object->getStartCoordinates());
+ $c1 = PHPExcel_Cell::columnIndexFromString($column) - 1;
+ $r1 = $row - 1;
+
+ // start offsetX
+ $startOffsetX = $this->object->getStartOffsetX();
+
+ // start offsetY
+ $startOffsetY = $this->object->getStartOffsetY();
+
+ // end coordinates
+ list($column, $row) = PHPExcel_Cell::coordinateFromString($this->object->getEndCoordinates());
+ $c2 = PHPExcel_Cell::columnIndexFromString($column) - 1;
+ $r2 = $row - 1;
+
+ // end offsetX
+ $endOffsetX = $this->object->getEndOffsetX();
+
+ // end offsetY
+ $endOffsetY = $this->object->getEndOffsetY();
+
+ $clientAnchorData = pack('vvvvvvvvv', $this->object->getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY);
+
+ $length = strlen($clientAnchorData);
- // initialize
- $innerData = '';
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- // initialize spape offsets
- $totalSize = 8;
- $spOffsets = array();
- $spTypes = array();
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . $clientAnchorData;
+ }
- // treat the inner data
- foreach ($this->_object->getChildren() as $spContainer) {
- $writer = new PHPExcel_Writer_Excel5_Escher($spContainer);
- $spData = $writer->close();
- $innerData .= $spData;
+ // the client data, just empty for now
+ if (!$this->object->getSpgr()) {
+ $clientDataData = '';
- // save the shape offsets (where new shape records begin)
- $totalSize += strlen($spData);
- $spOffsets[] = $totalSize;
-
- $spTypes = array_merge($spTypes, $writer->getSpTypes());
- }
+ $recVer = 0x0;
+ $recInstance = 0x0;
+ $recType = 0xF011;
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF003;
- $length = strlen($innerData);
+ $length = strlen($clientDataData);
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- $header = pack('vvV', $recVerInstance, $recType, $length);
+ $header = pack('vvV', $recVerInstance, $recType, $length);
+ $data .= $header . $clientDataData;
+ }
- $this->_data = $header . $innerData;
- $this->_spOffsets = $spOffsets;
- $this->_spTypes = $spTypes;
- break;
+ // write the record
+ $recVer = 0xF;
+ $recInstance = 0x0000;
+ $recType = 0xF004;
+ $length = strlen($data);
+
+ $recVerInstance = $recVer;
+ $recVerInstance |= $recInstance << 4;
- case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer':
- // initialize
- $data = '';
+ $header = pack('vvV', $recVerInstance, $recType, $length);
- // build the data
+ $this->data = $header . $data;
+ break;
+ }
- // write group shape record, if necessary?
- if ($this->_object->getSpgr()) {
- $recVer = 0x1;
- $recInstance = 0x0000;
- $recType = 0xF009;
- $length = 0x00000010;
+ return $this->data;
+ }
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
-
- $data .= $header . pack('VVVV', 0,0,0,0);
- }
- $this->_spTypes[] = ($this->_object->getSpType());
-
- // write the shape record
- $recVer = 0x2;
- $recInstance = $this->_object->getSpType(); // shape type
- $recType = 0xF00A;
- $length = 0x00000008;
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
-
- $data .= $header . pack('VV', $this->_object->getSpId(), $this->_object->getSpgr() ? 0x0005 : 0x0A00);
-
-
- // the options
- if ($this->_object->getOPTCollection()) {
- $optData = '';
-
- $recVer = 0x3;
- $recInstance = count($this->_object->getOPTCollection());
- $recType = 0xF00B;
- foreach ($this->_object->getOPTCollection() as $property => $value) {
- $optData .= pack('vV', $property, $value);
- }
- $length = strlen($optData);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . $optData;
- }
-
- // the client anchor
- if ($this->_object->getStartCoordinates()) {
- $clientAnchorData = '';
-
- $recVer = 0x0;
- $recInstance = 0x0;
- $recType = 0xF010;
-
- // start coordinates
- list($column, $row) = PHPExcel_Cell::coordinateFromString($this->_object->getStartCoordinates());
- $c1 = PHPExcel_Cell::columnIndexFromString($column) - 1;
- $r1 = $row - 1;
-
- // start offsetX
- $startOffsetX = $this->_object->getStartOffsetX();
-
- // start offsetY
- $startOffsetY = $this->_object->getStartOffsetY();
-
- // end coordinates
- list($column, $row) = PHPExcel_Cell::coordinateFromString($this->_object->getEndCoordinates());
- $c2 = PHPExcel_Cell::columnIndexFromString($column) - 1;
- $r2 = $row - 1;
-
- // end offsetX
- $endOffsetX = $this->_object->getEndOffsetX();
-
- // end offsetY
- $endOffsetY = $this->_object->getEndOffsetY();
-
- $clientAnchorData = pack('vvvvvvvvv', $this->_object->getSpFlag(),
- $c1, $startOffsetX, $r1, $startOffsetY,
- $c2, $endOffsetX, $r2, $endOffsetY);
-
- $length = strlen($clientAnchorData);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . $clientAnchorData;
- }
-
- // the client data, just empty for now
- if (!$this->_object->getSpgr()) {
- $clientDataData = '';
-
- $recVer = 0x0;
- $recInstance = 0x0;
- $recType = 0xF011;
-
- $length = strlen($clientDataData);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
- $data .= $header . $clientDataData;
- }
-
- // write the record
- $recVer = 0xF;
- $recInstance = 0x0000;
- $recType = 0xF004;
- $length = strlen($data);
-
- $recVerInstance = $recVer;
- $recVerInstance |= $recInstance << 4;
-
- $header = pack('vvV', $recVerInstance, $recType, $length);
-
- $this->_data = $header . $data;
- break;
-
- }
-
- return $this->_data;
- }
-
- /**
- * Gets the shape offsets
- *
- * @return array
- */
- public function getSpOffsets()
- {
- return $this->_spOffsets;
- }
-
- /**
- * Gets the shape types
- *
- * @return array
- */
- public function getSpTypes()
- {
- return $this->_spTypes;
- }
-
-
+ /**
+ * Gets the shape offsets
+ *
+ * @return array
+ */
+ public function getSpOffsets()
+ {
+ return $this->spOffsets;
+ }
+
+ /**
+ * Gets the shape types
+ *
+ * @return array
+ */
+ public function getSpTypes()
+ {
+ return $this->spTypes;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Font.php b/Classes/PHPExcel/Writer/Excel5/Font.php
index f59cce66e..ed85ff457 100644
--- a/Classes/PHPExcel/Writer/Excel5/Font.php
+++ b/Classes/PHPExcel/Writer/Excel5/Font.php
@@ -1,8 +1,9 @@
_colorIndex = 0x7FFF;
- $this->_font = $font;
- }
+ /**
+ * Constructor
+ *
+ * @param PHPExcel_Style_Font $font
+ */
+ public function __construct(PHPExcel_Style_Font $font = null)
+ {
+ $this->colorIndex = 0x7FFF;
+ $this->font = $font;
+ }
- /**
- * Set the color index
- *
- * @param int $colorIndex
- */
- public function setColorIndex($colorIndex)
- {
- $this->_colorIndex = $colorIndex;
- }
+ /**
+ * Set the color index
+ *
+ * @param int $colorIndex
+ */
+ public function setColorIndex($colorIndex)
+ {
+ $this->colorIndex = $colorIndex;
+ }
- /**
- * Get font record data
- *
- * @return string
- */
- public function writeFont()
- {
- $font_outline = 0;
- $font_shadow = 0;
+ /**
+ * Get font record data
+ *
+ * @return string
+ */
+ public function writeFont()
+ {
+ $font_outline = 0;
+ $font_shadow = 0;
- $icv = $this->_colorIndex; // Index to color palette
- if ($this->_font->getSuperScript()) {
- $sss = 1;
- } else if ($this->_font->getSubScript()) {
- $sss = 2;
- } else {
- $sss = 0;
- }
- $bFamily = 0; // Font family
- $bCharSet = PHPExcel_Shared_Font::getCharsetFromFontName($this->_font->getName()); // Character set
+ $icv = $this->colorIndex; // Index to color palette
+ if ($this->font->getSuperScript()) {
+ $sss = 1;
+ } elseif ($this->font->getSubScript()) {
+ $sss = 2;
+ } else {
+ $sss = 0;
+ }
+ $bFamily = 0; // Font family
+ $bCharSet = PHPExcel_Shared_Font::getCharsetFromFontName($this->font->getName()); // Character set
- $record = 0x31; // Record identifier
- $reserved = 0x00; // Reserved
- $grbit = 0x00; // Font attributes
- if ($this->_font->getItalic()) {
- $grbit |= 0x02;
- }
- if ($this->_font->getStrikethrough()) {
- $grbit |= 0x08;
- }
- if ($font_outline) {
- $grbit |= 0x10;
- }
- if ($font_shadow) {
- $grbit |= 0x20;
- }
+ $record = 0x31; // Record identifier
+ $reserved = 0x00; // Reserved
+ $grbit = 0x00; // Font attributes
+ if ($this->font->getItalic()) {
+ $grbit |= 0x02;
+ }
+ if ($this->font->getStrikethrough()) {
+ $grbit |= 0x08;
+ }
+ if ($font_outline) {
+ $grbit |= 0x10;
+ }
+ if ($font_shadow) {
+ $grbit |= 0x20;
+ }
- $data = pack("vvvvvCCCC",
- $this->_font->getSize() * 20, // Fontsize (in twips)
- $grbit,
- $icv, // Colour
- self::_mapBold($this->_font->getBold()), // Font weight
- $sss, // Superscript/Subscript
- self::_mapUnderline($this->_font->getUnderline()),
- $bFamily,
- $bCharSet,
- $reserved
- );
- $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($this->_font->getName());
+ $data = pack(
+ "vvvvvCCCC",
+ // Fontsize (in twips)
+ $this->font->getSize() * 20,
+ $grbit,
+ // Colour
+ $icv,
+ // Font weight
+ self::mapBold($this->font->getBold()),
+ // Superscript/Subscript
+ $sss,
+ self::mapUnderline($this->font->getUnderline()),
+ $bFamily,
+ $bCharSet,
+ $reserved
+ );
+ $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($this->font->getName());
- $length = strlen($data);
- $header = pack("vv", $record, $length);
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
- return($header . $data);
- }
+ return($header . $data);
+ }
- /**
- * Map to BIFF5-BIFF8 codes for bold
- *
- * @param boolean $bold
- * @return int
- */
- private static function _mapBold($bold) {
- if ($bold) {
- return 0x2BC; // 700 = Bold font weight
- }
- return 0x190; // 400 = Normal font weight
- }
+ /**
+ * Map to BIFF5-BIFF8 codes for bold
+ *
+ * @param boolean $bold
+ * @return int
+ */
+ private static function mapBold($bold)
+ {
+ if ($bold) {
+ return 0x2BC; // 700 = Bold font weight
+ }
+ return 0x190; // 400 = Normal font weight
+ }
- /**
- * Map of BIFF2-BIFF8 codes for underline styles
- * @static array of int
- *
- */
- private static $_mapUnderline = array( PHPExcel_Style_Font::UNDERLINE_NONE => 0x00,
- PHPExcel_Style_Font::UNDERLINE_SINGLE => 0x01,
- PHPExcel_Style_Font::UNDERLINE_DOUBLE => 0x02,
- PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING => 0x21,
- PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING => 0x22,
- );
- /**
- * Map underline
- *
- * @param string
- * @return int
- */
- private static function _mapUnderline($underline) {
- if (isset(self::$_mapUnderline[$underline]))
- return self::$_mapUnderline[$underline];
- return 0x00;
- }
+ /**
+ * Map of BIFF2-BIFF8 codes for underline styles
+ * @static array of int
+ *
+ */
+ private static $mapUnderline = array(
+ PHPExcel_Style_Font::UNDERLINE_NONE => 0x00,
+ PHPExcel_Style_Font::UNDERLINE_SINGLE => 0x01,
+ PHPExcel_Style_Font::UNDERLINE_DOUBLE => 0x02,
+ PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING => 0x21,
+ PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING => 0x22,
+ );
+ /**
+ * Map underline
+ *
+ * @param string
+ * @return int
+ */
+ private static function mapUnderline($underline)
+ {
+ if (isset(self::$mapUnderline[$underline])) {
+ return self::$mapUnderline[$underline];
+ }
+ return 0x00;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Parser.php b/Classes/PHPExcel/Writer/Excel5/Parser.php
index 579fecfac..0cf1c1d65 100644
--- a/Classes/PHPExcel/Writer/Excel5/Parser.php
+++ b/Classes/PHPExcel/Writer/Excel5/Parser.php
@@ -1,8 +1,9 @@
=,;#()"{}
- const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
-
- // Sheet title in quoted form (without surrounding quotes)
- // Invalid sheet title characters cannot occur in the sheet title:
- // *:/\?[] (usual invalid sheet title characters)
- // Single quote is represented as a pair ''
- const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+';
-
- /**
- * The index of the character we are currently looking at
- * @var integer
- */
- public $_current_char;
-
- /**
- * The token we are working on.
- * @var string
- */
- public $_current_token;
-
- /**
- * The formula to parse
- * @var string
- */
- public $_formula;
-
- /**
- * The character ahead of the current char
- * @var string
- */
- public $_lookahead;
-
- /**
- * The parse tree to be generated
- * @var string
- */
- public $_parse_tree;
-
- /**
- * Array of external sheets
- * @var array
- */
- public $_ext_sheets;
-
- /**
- * Array of sheet references in the form of REF structures
- * @var array
- */
- public $_references;
-
- /**
- * The class constructor
- *
- */
- public function __construct()
- {
- $this->_current_char = 0;
- $this->_current_token = ''; // The token we are working on.
- $this->_formula = ''; // The formula to parse.
- $this->_lookahead = ''; // The character ahead of the current char.
- $this->_parse_tree = ''; // The parse tree to be generated.
- $this->_initializeHashes(); // Initialize the hashes: ptg's and function's ptg's
- $this->_ext_sheets = array();
- $this->_references = array();
- }
-
- /**
- * Initialize the ptg and function hashes.
- *
- * @access private
- */
- function _initializeHashes()
- {
- // The Excel ptg indices
- $this->ptg = array(
- 'ptgExp' => 0x01,
- 'ptgTbl' => 0x02,
- 'ptgAdd' => 0x03,
- 'ptgSub' => 0x04,
- 'ptgMul' => 0x05,
- 'ptgDiv' => 0x06,
- 'ptgPower' => 0x07,
- 'ptgConcat' => 0x08,
- 'ptgLT' => 0x09,
- 'ptgLE' => 0x0A,
- 'ptgEQ' => 0x0B,
- 'ptgGE' => 0x0C,
- 'ptgGT' => 0x0D,
- 'ptgNE' => 0x0E,
- 'ptgIsect' => 0x0F,
- 'ptgUnion' => 0x10,
- 'ptgRange' => 0x11,
- 'ptgUplus' => 0x12,
- 'ptgUminus' => 0x13,
- 'ptgPercent' => 0x14,
- 'ptgParen' => 0x15,
- 'ptgMissArg' => 0x16,
- 'ptgStr' => 0x17,
- 'ptgAttr' => 0x19,
- 'ptgSheet' => 0x1A,
- 'ptgEndSheet' => 0x1B,
- 'ptgErr' => 0x1C,
- 'ptgBool' => 0x1D,
- 'ptgInt' => 0x1E,
- 'ptgNum' => 0x1F,
- 'ptgArray' => 0x20,
- 'ptgFunc' => 0x21,
- 'ptgFuncVar' => 0x22,
- 'ptgName' => 0x23,
- 'ptgRef' => 0x24,
- 'ptgArea' => 0x25,
- 'ptgMemArea' => 0x26,
- 'ptgMemErr' => 0x27,
- 'ptgMemNoMem' => 0x28,
- 'ptgMemFunc' => 0x29,
- 'ptgRefErr' => 0x2A,
- 'ptgAreaErr' => 0x2B,
- 'ptgRefN' => 0x2C,
- 'ptgAreaN' => 0x2D,
- 'ptgMemAreaN' => 0x2E,
- 'ptgMemNoMemN' => 0x2F,
- 'ptgNameX' => 0x39,
- 'ptgRef3d' => 0x3A,
- 'ptgArea3d' => 0x3B,
- 'ptgRefErr3d' => 0x3C,
- 'ptgAreaErr3d' => 0x3D,
- 'ptgArrayV' => 0x40,
- 'ptgFuncV' => 0x41,
- 'ptgFuncVarV' => 0x42,
- 'ptgNameV' => 0x43,
- 'ptgRefV' => 0x44,
- 'ptgAreaV' => 0x45,
- 'ptgMemAreaV' => 0x46,
- 'ptgMemErrV' => 0x47,
- 'ptgMemNoMemV' => 0x48,
- 'ptgMemFuncV' => 0x49,
- 'ptgRefErrV' => 0x4A,
- 'ptgAreaErrV' => 0x4B,
- 'ptgRefNV' => 0x4C,
- 'ptgAreaNV' => 0x4D,
- 'ptgMemAreaNV' => 0x4E,
- 'ptgMemNoMemN' => 0x4F,
- 'ptgFuncCEV' => 0x58,
- 'ptgNameXV' => 0x59,
- 'ptgRef3dV' => 0x5A,
- 'ptgArea3dV' => 0x5B,
- 'ptgRefErr3dV' => 0x5C,
- 'ptgAreaErr3d' => 0x5D,
- 'ptgArrayA' => 0x60,
- 'ptgFuncA' => 0x61,
- 'ptgFuncVarA' => 0x62,
- 'ptgNameA' => 0x63,
- 'ptgRefA' => 0x64,
- 'ptgAreaA' => 0x65,
- 'ptgMemAreaA' => 0x66,
- 'ptgMemErrA' => 0x67,
- 'ptgMemNoMemA' => 0x68,
- 'ptgMemFuncA' => 0x69,
- 'ptgRefErrA' => 0x6A,
- 'ptgAreaErrA' => 0x6B,
- 'ptgRefNA' => 0x6C,
- 'ptgAreaNA' => 0x6D,
- 'ptgMemAreaNA' => 0x6E,
- 'ptgMemNoMemN' => 0x6F,
- 'ptgFuncCEA' => 0x78,
- 'ptgNameXA' => 0x79,
- 'ptgRef3dA' => 0x7A,
- 'ptgArea3dA' => 0x7B,
- 'ptgRefErr3dA' => 0x7C,
- 'ptgAreaErr3d' => 0x7D
- );
-
- // Thanks to Michael Meeks and Gnumeric for the initial arg values.
- //
- // The following hash was generated by "function_locale.pl" in the distro.
- // Refer to function_locale.pl for non-English function names.
- //
- // The array elements are as follow:
- // ptg: The Excel function ptg code.
- // args: The number of arguments that the function takes:
- // >=0 is a fixed number of arguments.
- // -1 is a variable number of arguments.
- // class: The reference, value or array class of the function args.
- // vol: The function is volatile.
- //
- $this->_functions = array(
- // function ptg args class vol
- 'COUNT' => array( 0, -1, 0, 0 ),
- 'IF' => array( 1, -1, 1, 0 ),
- 'ISNA' => array( 2, 1, 1, 0 ),
- 'ISERROR' => array( 3, 1, 1, 0 ),
- 'SUM' => array( 4, -1, 0, 0 ),
- 'AVERAGE' => array( 5, -1, 0, 0 ),
- 'MIN' => array( 6, -1, 0, 0 ),
- 'MAX' => array( 7, -1, 0, 0 ),
- 'ROW' => array( 8, -1, 0, 0 ),
- 'COLUMN' => array( 9, -1, 0, 0 ),
- 'NA' => array( 10, 0, 0, 0 ),
- 'NPV' => array( 11, -1, 1, 0 ),
- 'STDEV' => array( 12, -1, 0, 0 ),
- 'DOLLAR' => array( 13, -1, 1, 0 ),
- 'FIXED' => array( 14, -1, 1, 0 ),
- 'SIN' => array( 15, 1, 1, 0 ),
- 'COS' => array( 16, 1, 1, 0 ),
- 'TAN' => array( 17, 1, 1, 0 ),
- 'ATAN' => array( 18, 1, 1, 0 ),
- 'PI' => array( 19, 0, 1, 0 ),
- 'SQRT' => array( 20, 1, 1, 0 ),
- 'EXP' => array( 21, 1, 1, 0 ),
- 'LN' => array( 22, 1, 1, 0 ),
- 'LOG10' => array( 23, 1, 1, 0 ),
- 'ABS' => array( 24, 1, 1, 0 ),
- 'INT' => array( 25, 1, 1, 0 ),
- 'SIGN' => array( 26, 1, 1, 0 ),
- 'ROUND' => array( 27, 2, 1, 0 ),
- 'LOOKUP' => array( 28, -1, 0, 0 ),
- 'INDEX' => array( 29, -1, 0, 1 ),
- 'REPT' => array( 30, 2, 1, 0 ),
- 'MID' => array( 31, 3, 1, 0 ),
- 'LEN' => array( 32, 1, 1, 0 ),
- 'VALUE' => array( 33, 1, 1, 0 ),
- 'TRUE' => array( 34, 0, 1, 0 ),
- 'FALSE' => array( 35, 0, 1, 0 ),
- 'AND' => array( 36, -1, 0, 0 ),
- 'OR' => array( 37, -1, 0, 0 ),
- 'NOT' => array( 38, 1, 1, 0 ),
- 'MOD' => array( 39, 2, 1, 0 ),
- 'DCOUNT' => array( 40, 3, 0, 0 ),
- 'DSUM' => array( 41, 3, 0, 0 ),
- 'DAVERAGE' => array( 42, 3, 0, 0 ),
- 'DMIN' => array( 43, 3, 0, 0 ),
- 'DMAX' => array( 44, 3, 0, 0 ),
- 'DSTDEV' => array( 45, 3, 0, 0 ),
- 'VAR' => array( 46, -1, 0, 0 ),
- 'DVAR' => array( 47, 3, 0, 0 ),
- 'TEXT' => array( 48, 2, 1, 0 ),
- 'LINEST' => array( 49, -1, 0, 0 ),
- 'TREND' => array( 50, -1, 0, 0 ),
- 'LOGEST' => array( 51, -1, 0, 0 ),
- 'GROWTH' => array( 52, -1, 0, 0 ),
- 'PV' => array( 56, -1, 1, 0 ),
- 'FV' => array( 57, -1, 1, 0 ),
- 'NPER' => array( 58, -1, 1, 0 ),
- 'PMT' => array( 59, -1, 1, 0 ),
- 'RATE' => array( 60, -1, 1, 0 ),
- 'MIRR' => array( 61, 3, 0, 0 ),
- 'IRR' => array( 62, -1, 0, 0 ),
- 'RAND' => array( 63, 0, 1, 1 ),
- 'MATCH' => array( 64, -1, 0, 0 ),
- 'DATE' => array( 65, 3, 1, 0 ),
- 'TIME' => array( 66, 3, 1, 0 ),
- 'DAY' => array( 67, 1, 1, 0 ),
- 'MONTH' => array( 68, 1, 1, 0 ),
- 'YEAR' => array( 69, 1, 1, 0 ),
- 'WEEKDAY' => array( 70, -1, 1, 0 ),
- 'HOUR' => array( 71, 1, 1, 0 ),
- 'MINUTE' => array( 72, 1, 1, 0 ),
- 'SECOND' => array( 73, 1, 1, 0 ),
- 'NOW' => array( 74, 0, 1, 1 ),
- 'AREAS' => array( 75, 1, 0, 1 ),
- 'ROWS' => array( 76, 1, 0, 1 ),
- 'COLUMNS' => array( 77, 1, 0, 1 ),
- 'OFFSET' => array( 78, -1, 0, 1 ),
- 'SEARCH' => array( 82, -1, 1, 0 ),
- 'TRANSPOSE' => array( 83, 1, 1, 0 ),
- 'TYPE' => array( 86, 1, 1, 0 ),
- 'ATAN2' => array( 97, 2, 1, 0 ),
- 'ASIN' => array( 98, 1, 1, 0 ),
- 'ACOS' => array( 99, 1, 1, 0 ),
- 'CHOOSE' => array( 100, -1, 1, 0 ),
- 'HLOOKUP' => array( 101, -1, 0, 0 ),
- 'VLOOKUP' => array( 102, -1, 0, 0 ),
- 'ISREF' => array( 105, 1, 0, 0 ),
- 'LOG' => array( 109, -1, 1, 0 ),
- 'CHAR' => array( 111, 1, 1, 0 ),
- 'LOWER' => array( 112, 1, 1, 0 ),
- 'UPPER' => array( 113, 1, 1, 0 ),
- 'PROPER' => array( 114, 1, 1, 0 ),
- 'LEFT' => array( 115, -1, 1, 0 ),
- 'RIGHT' => array( 116, -1, 1, 0 ),
- 'EXACT' => array( 117, 2, 1, 0 ),
- 'TRIM' => array( 118, 1, 1, 0 ),
- 'REPLACE' => array( 119, 4, 1, 0 ),
- 'SUBSTITUTE' => array( 120, -1, 1, 0 ),
- 'CODE' => array( 121, 1, 1, 0 ),
- 'FIND' => array( 124, -1, 1, 0 ),
- 'CELL' => array( 125, -1, 0, 1 ),
- 'ISERR' => array( 126, 1, 1, 0 ),
- 'ISTEXT' => array( 127, 1, 1, 0 ),
- 'ISNUMBER' => array( 128, 1, 1, 0 ),
- 'ISBLANK' => array( 129, 1, 1, 0 ),
- 'T' => array( 130, 1, 0, 0 ),
- 'N' => array( 131, 1, 0, 0 ),
- 'DATEVALUE' => array( 140, 1, 1, 0 ),
- 'TIMEVALUE' => array( 141, 1, 1, 0 ),
- 'SLN' => array( 142, 3, 1, 0 ),
- 'SYD' => array( 143, 4, 1, 0 ),
- 'DDB' => array( 144, -1, 1, 0 ),
- 'INDIRECT' => array( 148, -1, 1, 1 ),
- 'CALL' => array( 150, -1, 1, 0 ),
- 'CLEAN' => array( 162, 1, 1, 0 ),
- 'MDETERM' => array( 163, 1, 2, 0 ),
- 'MINVERSE' => array( 164, 1, 2, 0 ),
- 'MMULT' => array( 165, 2, 2, 0 ),
- 'IPMT' => array( 167, -1, 1, 0 ),
- 'PPMT' => array( 168, -1, 1, 0 ),
- 'COUNTA' => array( 169, -1, 0, 0 ),
- 'PRODUCT' => array( 183, -1, 0, 0 ),
- 'FACT' => array( 184, 1, 1, 0 ),
- 'DPRODUCT' => array( 189, 3, 0, 0 ),
- 'ISNONTEXT' => array( 190, 1, 1, 0 ),
- 'STDEVP' => array( 193, -1, 0, 0 ),
- 'VARP' => array( 194, -1, 0, 0 ),
- 'DSTDEVP' => array( 195, 3, 0, 0 ),
- 'DVARP' => array( 196, 3, 0, 0 ),
- 'TRUNC' => array( 197, -1, 1, 0 ),
- 'ISLOGICAL' => array( 198, 1, 1, 0 ),
- 'DCOUNTA' => array( 199, 3, 0, 0 ),
- 'USDOLLAR' => array( 204, -1, 1, 0 ),
- 'FINDB' => array( 205, -1, 1, 0 ),
- 'SEARCHB' => array( 206, -1, 1, 0 ),
- 'REPLACEB' => array( 207, 4, 1, 0 ),
- 'LEFTB' => array( 208, -1, 1, 0 ),
- 'RIGHTB' => array( 209, -1, 1, 0 ),
- 'MIDB' => array( 210, 3, 1, 0 ),
- 'LENB' => array( 211, 1, 1, 0 ),
- 'ROUNDUP' => array( 212, 2, 1, 0 ),
- 'ROUNDDOWN' => array( 213, 2, 1, 0 ),
- 'ASC' => array( 214, 1, 1, 0 ),
- 'DBCS' => array( 215, 1, 1, 0 ),
- 'RANK' => array( 216, -1, 0, 0 ),
- 'ADDRESS' => array( 219, -1, 1, 0 ),
- 'DAYS360' => array( 220, -1, 1, 0 ),
- 'TODAY' => array( 221, 0, 1, 1 ),
- 'VDB' => array( 222, -1, 1, 0 ),
- 'MEDIAN' => array( 227, -1, 0, 0 ),
- 'SUMPRODUCT' => array( 228, -1, 2, 0 ),
- 'SINH' => array( 229, 1, 1, 0 ),
- 'COSH' => array( 230, 1, 1, 0 ),
- 'TANH' => array( 231, 1, 1, 0 ),
- 'ASINH' => array( 232, 1, 1, 0 ),
- 'ACOSH' => array( 233, 1, 1, 0 ),
- 'ATANH' => array( 234, 1, 1, 0 ),
- 'DGET' => array( 235, 3, 0, 0 ),
- 'INFO' => array( 244, 1, 1, 1 ),
- 'DB' => array( 247, -1, 1, 0 ),
- 'FREQUENCY' => array( 252, 2, 0, 0 ),
- 'ERROR.TYPE' => array( 261, 1, 1, 0 ),
- 'REGISTER.ID' => array( 267, -1, 1, 0 ),
- 'AVEDEV' => array( 269, -1, 0, 0 ),
- 'BETADIST' => array( 270, -1, 1, 0 ),
- 'GAMMALN' => array( 271, 1, 1, 0 ),
- 'BETAINV' => array( 272, -1, 1, 0 ),
- 'BINOMDIST' => array( 273, 4, 1, 0 ),
- 'CHIDIST' => array( 274, 2, 1, 0 ),
- 'CHIINV' => array( 275, 2, 1, 0 ),
- 'COMBIN' => array( 276, 2, 1, 0 ),
- 'CONFIDENCE' => array( 277, 3, 1, 0 ),
- 'CRITBINOM' => array( 278, 3, 1, 0 ),
- 'EVEN' => array( 279, 1, 1, 0 ),
- 'EXPONDIST' => array( 280, 3, 1, 0 ),
- 'FDIST' => array( 281, 3, 1, 0 ),
- 'FINV' => array( 282, 3, 1, 0 ),
- 'FISHER' => array( 283, 1, 1, 0 ),
- 'FISHERINV' => array( 284, 1, 1, 0 ),
- 'FLOOR' => array( 285, 2, 1, 0 ),
- 'GAMMADIST' => array( 286, 4, 1, 0 ),
- 'GAMMAINV' => array( 287, 3, 1, 0 ),
- 'CEILING' => array( 288, 2, 1, 0 ),
- 'HYPGEOMDIST' => array( 289, 4, 1, 0 ),
- 'LOGNORMDIST' => array( 290, 3, 1, 0 ),
- 'LOGINV' => array( 291, 3, 1, 0 ),
- 'NEGBINOMDIST' => array( 292, 3, 1, 0 ),
- 'NORMDIST' => array( 293, 4, 1, 0 ),
- 'NORMSDIST' => array( 294, 1, 1, 0 ),
- 'NORMINV' => array( 295, 3, 1, 0 ),
- 'NORMSINV' => array( 296, 1, 1, 0 ),
- 'STANDARDIZE' => array( 297, 3, 1, 0 ),
- 'ODD' => array( 298, 1, 1, 0 ),
- 'PERMUT' => array( 299, 2, 1, 0 ),
- 'POISSON' => array( 300, 3, 1, 0 ),
- 'TDIST' => array( 301, 3, 1, 0 ),
- 'WEIBULL' => array( 302, 4, 1, 0 ),
- 'SUMXMY2' => array( 303, 2, 2, 0 ),
- 'SUMX2MY2' => array( 304, 2, 2, 0 ),
- 'SUMX2PY2' => array( 305, 2, 2, 0 ),
- 'CHITEST' => array( 306, 2, 2, 0 ),
- 'CORREL' => array( 307, 2, 2, 0 ),
- 'COVAR' => array( 308, 2, 2, 0 ),
- 'FORECAST' => array( 309, 3, 2, 0 ),
- 'FTEST' => array( 310, 2, 2, 0 ),
- 'INTERCEPT' => array( 311, 2, 2, 0 ),
- 'PEARSON' => array( 312, 2, 2, 0 ),
- 'RSQ' => array( 313, 2, 2, 0 ),
- 'STEYX' => array( 314, 2, 2, 0 ),
- 'SLOPE' => array( 315, 2, 2, 0 ),
- 'TTEST' => array( 316, 4, 2, 0 ),
- 'PROB' => array( 317, -1, 2, 0 ),
- 'DEVSQ' => array( 318, -1, 0, 0 ),
- 'GEOMEAN' => array( 319, -1, 0, 0 ),
- 'HARMEAN' => array( 320, -1, 0, 0 ),
- 'SUMSQ' => array( 321, -1, 0, 0 ),
- 'KURT' => array( 322, -1, 0, 0 ),
- 'SKEW' => array( 323, -1, 0, 0 ),
- 'ZTEST' => array( 324, -1, 0, 0 ),
- 'LARGE' => array( 325, 2, 0, 0 ),
- 'SMALL' => array( 326, 2, 0, 0 ),
- 'QUARTILE' => array( 327, 2, 0, 0 ),
- 'PERCENTILE' => array( 328, 2, 0, 0 ),
- 'PERCENTRANK' => array( 329, -1, 0, 0 ),
- 'MODE' => array( 330, -1, 2, 0 ),
- 'TRIMMEAN' => array( 331, 2, 0, 0 ),
- 'TINV' => array( 332, 2, 1, 0 ),
- 'CONCATENATE' => array( 336, -1, 1, 0 ),
- 'POWER' => array( 337, 2, 1, 0 ),
- 'RADIANS' => array( 342, 1, 1, 0 ),
- 'DEGREES' => array( 343, 1, 1, 0 ),
- 'SUBTOTAL' => array( 344, -1, 0, 0 ),
- 'SUMIF' => array( 345, -1, 0, 0 ),
- 'COUNTIF' => array( 346, 2, 0, 0 ),
- 'COUNTBLANK' => array( 347, 1, 0, 0 ),
- 'ISPMT' => array( 350, 4, 1, 0 ),
- 'DATEDIF' => array( 351, 3, 1, 0 ),
- 'DATESTRING' => array( 352, 1, 1, 0 ),
- 'NUMBERSTRING' => array( 353, 2, 1, 0 ),
- 'ROMAN' => array( 354, -1, 1, 0 ),
- 'GETPIVOTDATA' => array( 358, -1, 0, 0 ),
- 'HYPERLINK' => array( 359, -1, 1, 0 ),
- 'PHONETIC' => array( 360, 1, 0, 0 ),
- 'AVERAGEA' => array( 361, -1, 0, 0 ),
- 'MAXA' => array( 362, -1, 0, 0 ),
- 'MINA' => array( 363, -1, 0, 0 ),
- 'STDEVPA' => array( 364, -1, 0, 0 ),
- 'VARPA' => array( 365, -1, 0, 0 ),
- 'STDEVA' => array( 366, -1, 0, 0 ),
- 'VARA' => array( 367, -1, 0, 0 ),
- 'BAHTTEXT' => array( 368, 1, 0, 0 ),
- );
- }
-
- /**
- * Convert a token to the proper ptg value.
- *
- * @access private
- * @param mixed $token The token to convert.
- * @return mixed the converted token on success
- */
- function _convert($token)
- {
- if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) {
- return $this->_convertString($token);
-
- } elseif (is_numeric($token)) {
- return $this->_convertNumber($token);
-
- // match references like A1 or $A$1
- } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) {
- return $this->_convertRef2d($token);
-
- // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
- } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
- return $this->_convertRef3d($token);
-
- // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
- } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) {
- return $this->_convertRef3d($token);
-
- // match ranges like A1:B2 or $A$1:$B$2
- } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
- return $this->_convertRange2d($token);
-
- // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
- } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) {
- return $this->_convertRange3d($token);
-
- // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
- } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) {
- return $this->_convertRange3d($token);
-
- // operators (including parentheses)
- } elseif (isset($this->ptg[$token])) {
- return pack("C", $this->ptg[$token]);
+ /** Constants */
+ // Sheet title in unquoted form
+ // Invalid sheet title characters cannot occur in the sheet title:
+ // *:/\?[]
+ // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
+ // +-% '^&<>=,;#()"{}
+ const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
+
+ // Sheet title in quoted form (without surrounding quotes)
+ // Invalid sheet title characters cannot occur in the sheet title:
+ // *:/\?[] (usual invalid sheet title characters)
+ // Single quote is represented as a pair ''
+ const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+';
+
+ /**
+ * The index of the character we are currently looking at
+ * @var integer
+ */
+ public $currentCharacter;
+
+ /**
+ * The token we are working on.
+ * @var string
+ */
+ public $currentToken;
+
+ /**
+ * The formula to parse
+ * @var string
+ */
+ private $formula;
+
+ /**
+ * The character ahead of the current char
+ * @var string
+ */
+ public $lookAhead;
+
+ /**
+ * The parse tree to be generated
+ * @var string
+ */
+ private $parseTree;
+
+ /**
+ * Array of external sheets
+ * @var array
+ */
+ private $externalSheets;
+
+ /**
+ * Array of sheet references in the form of REF structures
+ * @var array
+ */
+ public $references;
+
+ /**
+ * The class constructor
+ *
+ */
+ public function __construct()
+ {
+ $this->currentCharacter = 0;
+ $this->currentToken = ''; // The token we are working on.
+ $this->formula = ''; // The formula to parse.
+ $this->lookAhead = ''; // The character ahead of the current char.
+ $this->parseTree = ''; // The parse tree to be generated.
+ $this->initializeHashes(); // Initialize the hashes: ptg's and function's ptg's
+ $this->externalSheets = array();
+ $this->references = array();
+ }
+
+ /**
+ * Initialize the ptg and function hashes.
+ *
+ * @access private
+ */
+ private function initializeHashes()
+ {
+ // The Excel ptg indices
+ $this->ptg = array(
+ 'ptgExp' => 0x01,
+ 'ptgTbl' => 0x02,
+ 'ptgAdd' => 0x03,
+ 'ptgSub' => 0x04,
+ 'ptgMul' => 0x05,
+ 'ptgDiv' => 0x06,
+ 'ptgPower' => 0x07,
+ 'ptgConcat' => 0x08,
+ 'ptgLT' => 0x09,
+ 'ptgLE' => 0x0A,
+ 'ptgEQ' => 0x0B,
+ 'ptgGE' => 0x0C,
+ 'ptgGT' => 0x0D,
+ 'ptgNE' => 0x0E,
+ 'ptgIsect' => 0x0F,
+ 'ptgUnion' => 0x10,
+ 'ptgRange' => 0x11,
+ 'ptgUplus' => 0x12,
+ 'ptgUminus' => 0x13,
+ 'ptgPercent' => 0x14,
+ 'ptgParen' => 0x15,
+ 'ptgMissArg' => 0x16,
+ 'ptgStr' => 0x17,
+ 'ptgAttr' => 0x19,
+ 'ptgSheet' => 0x1A,
+ 'ptgEndSheet' => 0x1B,
+ 'ptgErr' => 0x1C,
+ 'ptgBool' => 0x1D,
+ 'ptgInt' => 0x1E,
+ 'ptgNum' => 0x1F,
+ 'ptgArray' => 0x20,
+ 'ptgFunc' => 0x21,
+ 'ptgFuncVar' => 0x22,
+ 'ptgName' => 0x23,
+ 'ptgRef' => 0x24,
+ 'ptgArea' => 0x25,
+ 'ptgMemArea' => 0x26,
+ 'ptgMemErr' => 0x27,
+ 'ptgMemNoMem' => 0x28,
+ 'ptgMemFunc' => 0x29,
+ 'ptgRefErr' => 0x2A,
+ 'ptgAreaErr' => 0x2B,
+ 'ptgRefN' => 0x2C,
+ 'ptgAreaN' => 0x2D,
+ 'ptgMemAreaN' => 0x2E,
+ 'ptgMemNoMemN' => 0x2F,
+ 'ptgNameX' => 0x39,
+ 'ptgRef3d' => 0x3A,
+ 'ptgArea3d' => 0x3B,
+ 'ptgRefErr3d' => 0x3C,
+ 'ptgAreaErr3d' => 0x3D,
+ 'ptgArrayV' => 0x40,
+ 'ptgFuncV' => 0x41,
+ 'ptgFuncVarV' => 0x42,
+ 'ptgNameV' => 0x43,
+ 'ptgRefV' => 0x44,
+ 'ptgAreaV' => 0x45,
+ 'ptgMemAreaV' => 0x46,
+ 'ptgMemErrV' => 0x47,
+ 'ptgMemNoMemV' => 0x48,
+ 'ptgMemFuncV' => 0x49,
+ 'ptgRefErrV' => 0x4A,
+ 'ptgAreaErrV' => 0x4B,
+ 'ptgRefNV' => 0x4C,
+ 'ptgAreaNV' => 0x4D,
+ 'ptgMemAreaNV' => 0x4E,
+ 'ptgMemNoMemN' => 0x4F,
+ 'ptgFuncCEV' => 0x58,
+ 'ptgNameXV' => 0x59,
+ 'ptgRef3dV' => 0x5A,
+ 'ptgArea3dV' => 0x5B,
+ 'ptgRefErr3dV' => 0x5C,
+ 'ptgAreaErr3d' => 0x5D,
+ 'ptgArrayA' => 0x60,
+ 'ptgFuncA' => 0x61,
+ 'ptgFuncVarA' => 0x62,
+ 'ptgNameA' => 0x63,
+ 'ptgRefA' => 0x64,
+ 'ptgAreaA' => 0x65,
+ 'ptgMemAreaA' => 0x66,
+ 'ptgMemErrA' => 0x67,
+ 'ptgMemNoMemA' => 0x68,
+ 'ptgMemFuncA' => 0x69,
+ 'ptgRefErrA' => 0x6A,
+ 'ptgAreaErrA' => 0x6B,
+ 'ptgRefNA' => 0x6C,
+ 'ptgAreaNA' => 0x6D,
+ 'ptgMemAreaNA' => 0x6E,
+ 'ptgMemNoMemN' => 0x6F,
+ 'ptgFuncCEA' => 0x78,
+ 'ptgNameXA' => 0x79,
+ 'ptgRef3dA' => 0x7A,
+ 'ptgArea3dA' => 0x7B,
+ 'ptgRefErr3dA' => 0x7C,
+ 'ptgAreaErr3d' => 0x7D
+ );
+
+ // Thanks to Michael Meeks and Gnumeric for the initial arg values.
+ //
+ // The following hash was generated by "function_locale.pl" in the distro.
+ // Refer to function_locale.pl for non-English function names.
+ //
+ // The array elements are as follow:
+ // ptg: The Excel function ptg code.
+ // args: The number of arguments that the function takes:
+ // >=0 is a fixed number of arguments.
+ // -1 is a variable number of arguments.
+ // class: The reference, value or array class of the function args.
+ // vol: The function is volatile.
+ //
+ $this->functions = array(
+ // function ptg args class vol
+ 'COUNT' => array( 0, -1, 0, 0 ),
+ 'IF' => array( 1, -1, 1, 0 ),
+ 'ISNA' => array( 2, 1, 1, 0 ),
+ 'ISERROR' => array( 3, 1, 1, 0 ),
+ 'SUM' => array( 4, -1, 0, 0 ),
+ 'AVERAGE' => array( 5, -1, 0, 0 ),
+ 'MIN' => array( 6, -1, 0, 0 ),
+ 'MAX' => array( 7, -1, 0, 0 ),
+ 'ROW' => array( 8, -1, 0, 0 ),
+ 'COLUMN' => array( 9, -1, 0, 0 ),
+ 'NA' => array( 10, 0, 0, 0 ),
+ 'NPV' => array( 11, -1, 1, 0 ),
+ 'STDEV' => array( 12, -1, 0, 0 ),
+ 'DOLLAR' => array( 13, -1, 1, 0 ),
+ 'FIXED' => array( 14, -1, 1, 0 ),
+ 'SIN' => array( 15, 1, 1, 0 ),
+ 'COS' => array( 16, 1, 1, 0 ),
+ 'TAN' => array( 17, 1, 1, 0 ),
+ 'ATAN' => array( 18, 1, 1, 0 ),
+ 'PI' => array( 19, 0, 1, 0 ),
+ 'SQRT' => array( 20, 1, 1, 0 ),
+ 'EXP' => array( 21, 1, 1, 0 ),
+ 'LN' => array( 22, 1, 1, 0 ),
+ 'LOG10' => array( 23, 1, 1, 0 ),
+ 'ABS' => array( 24, 1, 1, 0 ),
+ 'INT' => array( 25, 1, 1, 0 ),
+ 'SIGN' => array( 26, 1, 1, 0 ),
+ 'ROUND' => array( 27, 2, 1, 0 ),
+ 'LOOKUP' => array( 28, -1, 0, 0 ),
+ 'INDEX' => array( 29, -1, 0, 1 ),
+ 'REPT' => array( 30, 2, 1, 0 ),
+ 'MID' => array( 31, 3, 1, 0 ),
+ 'LEN' => array( 32, 1, 1, 0 ),
+ 'VALUE' => array( 33, 1, 1, 0 ),
+ 'TRUE' => array( 34, 0, 1, 0 ),
+ 'FALSE' => array( 35, 0, 1, 0 ),
+ 'AND' => array( 36, -1, 0, 0 ),
+ 'OR' => array( 37, -1, 0, 0 ),
+ 'NOT' => array( 38, 1, 1, 0 ),
+ 'MOD' => array( 39, 2, 1, 0 ),
+ 'DCOUNT' => array( 40, 3, 0, 0 ),
+ 'DSUM' => array( 41, 3, 0, 0 ),
+ 'DAVERAGE' => array( 42, 3, 0, 0 ),
+ 'DMIN' => array( 43, 3, 0, 0 ),
+ 'DMAX' => array( 44, 3, 0, 0 ),
+ 'DSTDEV' => array( 45, 3, 0, 0 ),
+ 'VAR' => array( 46, -1, 0, 0 ),
+ 'DVAR' => array( 47, 3, 0, 0 ),
+ 'TEXT' => array( 48, 2, 1, 0 ),
+ 'LINEST' => array( 49, -1, 0, 0 ),
+ 'TREND' => array( 50, -1, 0, 0 ),
+ 'LOGEST' => array( 51, -1, 0, 0 ),
+ 'GROWTH' => array( 52, -1, 0, 0 ),
+ 'PV' => array( 56, -1, 1, 0 ),
+ 'FV' => array( 57, -1, 1, 0 ),
+ 'NPER' => array( 58, -1, 1, 0 ),
+ 'PMT' => array( 59, -1, 1, 0 ),
+ 'RATE' => array( 60, -1, 1, 0 ),
+ 'MIRR' => array( 61, 3, 0, 0 ),
+ 'IRR' => array( 62, -1, 0, 0 ),
+ 'RAND' => array( 63, 0, 1, 1 ),
+ 'MATCH' => array( 64, -1, 0, 0 ),
+ 'DATE' => array( 65, 3, 1, 0 ),
+ 'TIME' => array( 66, 3, 1, 0 ),
+ 'DAY' => array( 67, 1, 1, 0 ),
+ 'MONTH' => array( 68, 1, 1, 0 ),
+ 'YEAR' => array( 69, 1, 1, 0 ),
+ 'WEEKDAY' => array( 70, -1, 1, 0 ),
+ 'HOUR' => array( 71, 1, 1, 0 ),
+ 'MINUTE' => array( 72, 1, 1, 0 ),
+ 'SECOND' => array( 73, 1, 1, 0 ),
+ 'NOW' => array( 74, 0, 1, 1 ),
+ 'AREAS' => array( 75, 1, 0, 1 ),
+ 'ROWS' => array( 76, 1, 0, 1 ),
+ 'COLUMNS' => array( 77, 1, 0, 1 ),
+ 'OFFSET' => array( 78, -1, 0, 1 ),
+ 'SEARCH' => array( 82, -1, 1, 0 ),
+ 'TRANSPOSE' => array( 83, 1, 1, 0 ),
+ 'TYPE' => array( 86, 1, 1, 0 ),
+ 'ATAN2' => array( 97, 2, 1, 0 ),
+ 'ASIN' => array( 98, 1, 1, 0 ),
+ 'ACOS' => array( 99, 1, 1, 0 ),
+ 'CHOOSE' => array( 100, -1, 1, 0 ),
+ 'HLOOKUP' => array( 101, -1, 0, 0 ),
+ 'VLOOKUP' => array( 102, -1, 0, 0 ),
+ 'ISREF' => array( 105, 1, 0, 0 ),
+ 'LOG' => array( 109, -1, 1, 0 ),
+ 'CHAR' => array( 111, 1, 1, 0 ),
+ 'LOWER' => array( 112, 1, 1, 0 ),
+ 'UPPER' => array( 113, 1, 1, 0 ),
+ 'PROPER' => array( 114, 1, 1, 0 ),
+ 'LEFT' => array( 115, -1, 1, 0 ),
+ 'RIGHT' => array( 116, -1, 1, 0 ),
+ 'EXACT' => array( 117, 2, 1, 0 ),
+ 'TRIM' => array( 118, 1, 1, 0 ),
+ 'REPLACE' => array( 119, 4, 1, 0 ),
+ 'SUBSTITUTE' => array( 120, -1, 1, 0 ),
+ 'CODE' => array( 121, 1, 1, 0 ),
+ 'FIND' => array( 124, -1, 1, 0 ),
+ 'CELL' => array( 125, -1, 0, 1 ),
+ 'ISERR' => array( 126, 1, 1, 0 ),
+ 'ISTEXT' => array( 127, 1, 1, 0 ),
+ 'ISNUMBER' => array( 128, 1, 1, 0 ),
+ 'ISBLANK' => array( 129, 1, 1, 0 ),
+ 'T' => array( 130, 1, 0, 0 ),
+ 'N' => array( 131, 1, 0, 0 ),
+ 'DATEVALUE' => array( 140, 1, 1, 0 ),
+ 'TIMEVALUE' => array( 141, 1, 1, 0 ),
+ 'SLN' => array( 142, 3, 1, 0 ),
+ 'SYD' => array( 143, 4, 1, 0 ),
+ 'DDB' => array( 144, -1, 1, 0 ),
+ 'INDIRECT' => array( 148, -1, 1, 1 ),
+ 'CALL' => array( 150, -1, 1, 0 ),
+ 'CLEAN' => array( 162, 1, 1, 0 ),
+ 'MDETERM' => array( 163, 1, 2, 0 ),
+ 'MINVERSE' => array( 164, 1, 2, 0 ),
+ 'MMULT' => array( 165, 2, 2, 0 ),
+ 'IPMT' => array( 167, -1, 1, 0 ),
+ 'PPMT' => array( 168, -1, 1, 0 ),
+ 'COUNTA' => array( 169, -1, 0, 0 ),
+ 'PRODUCT' => array( 183, -1, 0, 0 ),
+ 'FACT' => array( 184, 1, 1, 0 ),
+ 'DPRODUCT' => array( 189, 3, 0, 0 ),
+ 'ISNONTEXT' => array( 190, 1, 1, 0 ),
+ 'STDEVP' => array( 193, -1, 0, 0 ),
+ 'VARP' => array( 194, -1, 0, 0 ),
+ 'DSTDEVP' => array( 195, 3, 0, 0 ),
+ 'DVARP' => array( 196, 3, 0, 0 ),
+ 'TRUNC' => array( 197, -1, 1, 0 ),
+ 'ISLOGICAL' => array( 198, 1, 1, 0 ),
+ 'DCOUNTA' => array( 199, 3, 0, 0 ),
+ 'USDOLLAR' => array( 204, -1, 1, 0 ),
+ 'FINDB' => array( 205, -1, 1, 0 ),
+ 'SEARCHB' => array( 206, -1, 1, 0 ),
+ 'REPLACEB' => array( 207, 4, 1, 0 ),
+ 'LEFTB' => array( 208, -1, 1, 0 ),
+ 'RIGHTB' => array( 209, -1, 1, 0 ),
+ 'MIDB' => array( 210, 3, 1, 0 ),
+ 'LENB' => array( 211, 1, 1, 0 ),
+ 'ROUNDUP' => array( 212, 2, 1, 0 ),
+ 'ROUNDDOWN' => array( 213, 2, 1, 0 ),
+ 'ASC' => array( 214, 1, 1, 0 ),
+ 'DBCS' => array( 215, 1, 1, 0 ),
+ 'RANK' => array( 216, -1, 0, 0 ),
+ 'ADDRESS' => array( 219, -1, 1, 0 ),
+ 'DAYS360' => array( 220, -1, 1, 0 ),
+ 'TODAY' => array( 221, 0, 1, 1 ),
+ 'VDB' => array( 222, -1, 1, 0 ),
+ 'MEDIAN' => array( 227, -1, 0, 0 ),
+ 'SUMPRODUCT' => array( 228, -1, 2, 0 ),
+ 'SINH' => array( 229, 1, 1, 0 ),
+ 'COSH' => array( 230, 1, 1, 0 ),
+ 'TANH' => array( 231, 1, 1, 0 ),
+ 'ASINH' => array( 232, 1, 1, 0 ),
+ 'ACOSH' => array( 233, 1, 1, 0 ),
+ 'ATANH' => array( 234, 1, 1, 0 ),
+ 'DGET' => array( 235, 3, 0, 0 ),
+ 'INFO' => array( 244, 1, 1, 1 ),
+ 'DB' => array( 247, -1, 1, 0 ),
+ 'FREQUENCY' => array( 252, 2, 0, 0 ),
+ 'ERROR.TYPE' => array( 261, 1, 1, 0 ),
+ 'REGISTER.ID' => array( 267, -1, 1, 0 ),
+ 'AVEDEV' => array( 269, -1, 0, 0 ),
+ 'BETADIST' => array( 270, -1, 1, 0 ),
+ 'GAMMALN' => array( 271, 1, 1, 0 ),
+ 'BETAINV' => array( 272, -1, 1, 0 ),
+ 'BINOMDIST' => array( 273, 4, 1, 0 ),
+ 'CHIDIST' => array( 274, 2, 1, 0 ),
+ 'CHIINV' => array( 275, 2, 1, 0 ),
+ 'COMBIN' => array( 276, 2, 1, 0 ),
+ 'CONFIDENCE' => array( 277, 3, 1, 0 ),
+ 'CRITBINOM' => array( 278, 3, 1, 0 ),
+ 'EVEN' => array( 279, 1, 1, 0 ),
+ 'EXPONDIST' => array( 280, 3, 1, 0 ),
+ 'FDIST' => array( 281, 3, 1, 0 ),
+ 'FINV' => array( 282, 3, 1, 0 ),
+ 'FISHER' => array( 283, 1, 1, 0 ),
+ 'FISHERINV' => array( 284, 1, 1, 0 ),
+ 'FLOOR' => array( 285, 2, 1, 0 ),
+ 'GAMMADIST' => array( 286, 4, 1, 0 ),
+ 'GAMMAINV' => array( 287, 3, 1, 0 ),
+ 'CEILING' => array( 288, 2, 1, 0 ),
+ 'HYPGEOMDIST' => array( 289, 4, 1, 0 ),
+ 'LOGNORMDIST' => array( 290, 3, 1, 0 ),
+ 'LOGINV' => array( 291, 3, 1, 0 ),
+ 'NEGBINOMDIST' => array( 292, 3, 1, 0 ),
+ 'NORMDIST' => array( 293, 4, 1, 0 ),
+ 'NORMSDIST' => array( 294, 1, 1, 0 ),
+ 'NORMINV' => array( 295, 3, 1, 0 ),
+ 'NORMSINV' => array( 296, 1, 1, 0 ),
+ 'STANDARDIZE' => array( 297, 3, 1, 0 ),
+ 'ODD' => array( 298, 1, 1, 0 ),
+ 'PERMUT' => array( 299, 2, 1, 0 ),
+ 'POISSON' => array( 300, 3, 1, 0 ),
+ 'TDIST' => array( 301, 3, 1, 0 ),
+ 'WEIBULL' => array( 302, 4, 1, 0 ),
+ 'SUMXMY2' => array( 303, 2, 2, 0 ),
+ 'SUMX2MY2' => array( 304, 2, 2, 0 ),
+ 'SUMX2PY2' => array( 305, 2, 2, 0 ),
+ 'CHITEST' => array( 306, 2, 2, 0 ),
+ 'CORREL' => array( 307, 2, 2, 0 ),
+ 'COVAR' => array( 308, 2, 2, 0 ),
+ 'FORECAST' => array( 309, 3, 2, 0 ),
+ 'FTEST' => array( 310, 2, 2, 0 ),
+ 'INTERCEPT' => array( 311, 2, 2, 0 ),
+ 'PEARSON' => array( 312, 2, 2, 0 ),
+ 'RSQ' => array( 313, 2, 2, 0 ),
+ 'STEYX' => array( 314, 2, 2, 0 ),
+ 'SLOPE' => array( 315, 2, 2, 0 ),
+ 'TTEST' => array( 316, 4, 2, 0 ),
+ 'PROB' => array( 317, -1, 2, 0 ),
+ 'DEVSQ' => array( 318, -1, 0, 0 ),
+ 'GEOMEAN' => array( 319, -1, 0, 0 ),
+ 'HARMEAN' => array( 320, -1, 0, 0 ),
+ 'SUMSQ' => array( 321, -1, 0, 0 ),
+ 'KURT' => array( 322, -1, 0, 0 ),
+ 'SKEW' => array( 323, -1, 0, 0 ),
+ 'ZTEST' => array( 324, -1, 0, 0 ),
+ 'LARGE' => array( 325, 2, 0, 0 ),
+ 'SMALL' => array( 326, 2, 0, 0 ),
+ 'QUARTILE' => array( 327, 2, 0, 0 ),
+ 'PERCENTILE' => array( 328, 2, 0, 0 ),
+ 'PERCENTRANK' => array( 329, -1, 0, 0 ),
+ 'MODE' => array( 330, -1, 2, 0 ),
+ 'TRIMMEAN' => array( 331, 2, 0, 0 ),
+ 'TINV' => array( 332, 2, 1, 0 ),
+ 'CONCATENATE' => array( 336, -1, 1, 0 ),
+ 'POWER' => array( 337, 2, 1, 0 ),
+ 'RADIANS' => array( 342, 1, 1, 0 ),
+ 'DEGREES' => array( 343, 1, 1, 0 ),
+ 'SUBTOTAL' => array( 344, -1, 0, 0 ),
+ 'SUMIF' => array( 345, -1, 0, 0 ),
+ 'COUNTIF' => array( 346, 2, 0, 0 ),
+ 'COUNTBLANK' => array( 347, 1, 0, 0 ),
+ 'ISPMT' => array( 350, 4, 1, 0 ),
+ 'DATEDIF' => array( 351, 3, 1, 0 ),
+ 'DATESTRING' => array( 352, 1, 1, 0 ),
+ 'NUMBERSTRING' => array( 353, 2, 1, 0 ),
+ 'ROMAN' => array( 354, -1, 1, 0 ),
+ 'GETPIVOTDATA' => array( 358, -1, 0, 0 ),
+ 'HYPERLINK' => array( 359, -1, 1, 0 ),
+ 'PHONETIC' => array( 360, 1, 0, 0 ),
+ 'AVERAGEA' => array( 361, -1, 0, 0 ),
+ 'MAXA' => array( 362, -1, 0, 0 ),
+ 'MINA' => array( 363, -1, 0, 0 ),
+ 'STDEVPA' => array( 364, -1, 0, 0 ),
+ 'VARPA' => array( 365, -1, 0, 0 ),
+ 'STDEVA' => array( 366, -1, 0, 0 ),
+ 'VARA' => array( 367, -1, 0, 0 ),
+ 'BAHTTEXT' => array( 368, 1, 0, 0 ),
+ );
+ }
+
+ /**
+ * Convert a token to the proper ptg value.
+ *
+ * @access private
+ * @param mixed $token The token to convert.
+ * @return mixed the converted token on success
+ */
+ private function convert($token)
+ {
+ if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) {
+ return $this->convertString($token);
+
+ } elseif (is_numeric($token)) {
+ return $this->convertNumber($token);
+
+ // match references like A1 or $A$1
+ } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) {
+ return $this->convertRef2d($token);
+
+ // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) {
+ return $this->convertRef3d($token);
+
+ // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) {
+ return $this->convertRef3d($token);
+
+ // match ranges like A1:B2 or $A$1:$B$2
+ } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
+ return $this->convertRange2d($token);
+
+ // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) {
+ return $this->convertRange3d($token);
+
+ // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) {
+ return $this->convertRange3d($token);
+
+ // operators (including parentheses)
+ } elseif (isset($this->ptg[$token])) {
+ return pack("C", $this->ptg[$token]);
// match error codes
- } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') {
- return $this->_convertError($token);
-
- // commented so argument number can be processed correctly. See toReversePolish().
- /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/",$token))
- {
- return($this->_convertFunction($token,$this->_func_args));
- }*/
-
- // if it's an argument, ignore the token (the argument remains)
- } elseif ($token == 'arg') {
- return '';
- }
-
- // TODO: use real error codes
- throw new PHPExcel_Writer_Exception("Unknown token $token");
- }
-
- /**
- * Convert a number token to ptgInt or ptgNum
- *
- * @access private
- * @param mixed $num an integer or double for conversion to its ptg value
- */
- function _convertNumber($num)
- {
- // Integer in the range 0..2**16-1
- if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) {
- return pack("Cv", $this->ptg['ptgInt'], $num);
- } else { // A float
- if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
- $num = strrev($num);
- }
- return pack("Cd", $this->ptg['ptgNum'], $num);
- }
- }
-
- /**
- * Convert a string token to ptgStr
- *
- * @access private
- * @param string $string A string for conversion to its ptg value.
- * @return mixed the converted token on success
- */
- function _convertString($string)
- {
- // chop away beggining and ending quotes
- $string = substr($string, 1, strlen($string) - 2);
- if (strlen($string) > 255) {
- throw new PHPExcel_Writer_Exception("String is too long");
- }
-
- return pack('C', $this->ptg['ptgStr']) . PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($string);
- }
-
- /**
- * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
- * args that it takes.
- *
- * @access private
- * @param string $token The name of the function for convertion to ptg value.
- * @param integer $num_args The number of arguments the function receives.
- * @return string The packed ptg for the function
- */
- function _convertFunction($token, $num_args)
- {
- $args = $this->_functions[$token][1];
-// $volatile = $this->_functions[$token][3];
-
- // Fixed number of args eg. TIME($i,$j,$k).
- if ($args >= 0) {
- return pack("Cv", $this->ptg['ptgFuncV'], $this->_functions[$token][0]);
- }
- // Variable number of args eg. SUM($i,$j,$k, ..).
- if ($args == -1) {
- return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->_functions[$token][0]);
- }
- }
-
- /**
- * Convert an Excel range such as A1:D4 to a ptgRefV.
- *
- * @access private
- * @param string $range An Excel range in the A1:A2
- * @param int $class
- */
- function _convertRange2d($range, $class=0)
- {
-
- // TODO: possible class value 0,1,2 check Formula.pm
- // Split the range into 2 cell refs
- if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
- list($cell1, $cell2) = explode(':', $range);
- } else {
- // TODO: use real error codes
- throw new PHPExcel_Writer_Exception("Unknown range separator");
- }
-
- // Convert the cell references
- list($row1, $col1) = $this->_cellToPackedRowcol($cell1);
- list($row2, $col2) = $this->_cellToPackedRowcol($cell2);
-
- // The ptg value depends on the class of the ptg.
- if ($class == 0) {
- $ptgArea = pack("C", $this->ptg['ptgArea']);
- } elseif ($class == 1) {
- $ptgArea = pack("C", $this->ptg['ptgAreaV']);
- } elseif ($class == 2) {
- $ptgArea = pack("C", $this->ptg['ptgAreaA']);
- } else {
- // TODO: use real error codes
- throw new PHPExcel_Writer_Exception("Unknown class $class");
- }
- return $ptgArea . $row1 . $row2 . $col1. $col2;
- }
-
- /**
- * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
- * a ptgArea3d.
- *
- * @access private
- * @param string $token An Excel range in the Sheet1!A1:A2 format.
- * @return mixed The packed ptgArea3d token on success.
- */
- function _convertRange3d($token)
- {
-// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B)
-
- // Split the ref at the ! symbol
- list($ext_ref, $range) = explode('!', $token);
-
- // Convert the external reference part (different for BIFF8)
- $ext_ref = $this->_getRefIndex($ext_ref);
-
- // Split the range into 2 cell refs
- list($cell1, $cell2) = explode(':', $range);
-
- // Convert the cell references
- if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) {
- list($row1, $col1) = $this->_cellToPackedRowcol($cell1);
- list($row2, $col2) = $this->_cellToPackedRowcol($cell2);
- } else { // It's a rows range (like 26:27)
- list($row1, $col1, $row2, $col2) = $this->_rangeToPackedRange($cell1.':'.$cell2);
- }
-
- // The ptg value depends on the class of the ptg.
-// if ($class == 0) {
- $ptgArea = pack("C", $this->ptg['ptgArea3d']);
-// } elseif ($class == 1) {
-// $ptgArea = pack("C", $this->ptg['ptgArea3dV']);
-// } elseif ($class == 2) {
-// $ptgArea = pack("C", $this->ptg['ptgArea3dA']);
-// } else {
-// throw new PHPExcel_Writer_Exception("Unknown class $class");
-// }
-
- return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2;
- }
-
- /**
- * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
- *
- * @access private
- * @param string $cell An Excel cell reference
- * @return string The cell in packed() format with the corresponding ptg
- */
- function _convertRef2d($cell)
- {
-// $class = 2; // as far as I know, this is magick.
-
- // Convert the cell reference
- $cell_array = $this->_cellToPackedRowcol($cell);
- list($row, $col) = $cell_array;
-
- // The ptg value depends on the class of the ptg.
-// if ($class == 0) {
-// $ptgRef = pack("C", $this->ptg['ptgRef']);
-// } elseif ($class == 1) {
-// $ptgRef = pack("C", $this->ptg['ptgRefV']);
-// } elseif ($class == 2) {
- $ptgRef = pack("C", $this->ptg['ptgRefA']);
-// } else {
-// // TODO: use real error codes
-// throw new PHPExcel_Writer_Exception("Unknown class $class");
-// }
- return $ptgRef.$row.$col;
- }
-
- /**
- * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
- * ptgRef3d.
- *
- * @access private
- * @param string $cell An Excel cell reference
- * @return mixed The packed ptgRef3d token on success.
- */
- function _convertRef3d($cell)
- {
-// $class = 2; // as far as I know, this is magick.
-
- // Split the ref at the ! symbol
- list($ext_ref, $cell) = explode('!', $cell);
-
- // Convert the external reference part (different for BIFF8)
- $ext_ref = $this->_getRefIndex($ext_ref);
-
- // Convert the cell reference part
- list($row, $col) = $this->_cellToPackedRowcol($cell);
-
- // The ptg value depends on the class of the ptg.
-// if ($class == 0) {
-// $ptgRef = pack("C", $this->ptg['ptgRef3d']);
-// } elseif ($class == 1) {
-// $ptgRef = pack("C", $this->ptg['ptgRef3dV']);
-// } elseif ($class == 2) {
- $ptgRef = pack("C", $this->ptg['ptgRef3dA']);
-// } else {
-// throw new PHPExcel_Writer_Exception("Unknown class $class");
-// }
-
- return $ptgRef . $ext_ref. $row . $col;
- }
+ } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') {
+ return $this->convertError($token);
+
+ // commented so argument number can be processed correctly. See toReversePolish().
+ /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token))
+ {
+ return($this->convertFunction($token, $this->_func_args));
+ }*/
+
+ // if it's an argument, ignore the token (the argument remains)
+ } elseif ($token == 'arg') {
+ return '';
+ }
+
+ // TODO: use real error codes
+ throw new PHPExcel_Writer_Exception("Unknown token $token");
+ }
+
+ /**
+ * Convert a number token to ptgInt or ptgNum
+ *
+ * @access private
+ * @param mixed $num an integer or double for conversion to its ptg value
+ */
+ private function convertNumber($num)
+ {
+ // Integer in the range 0..2**16-1
+ if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) {
+ return pack("Cv", $this->ptg['ptgInt'], $num);
+ } else { // A float
+ if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian
+ $num = strrev($num);
+ }
+ return pack("Cd", $this->ptg['ptgNum'], $num);
+ }
+ }
+
+ /**
+ * Convert a string token to ptgStr
+ *
+ * @access private
+ * @param string $string A string for conversion to its ptg value.
+ * @return mixed the converted token on success
+ */
+ private function convertString($string)
+ {
+ // chop away beggining and ending quotes
+ $string = substr($string, 1, strlen($string) - 2);
+ if (strlen($string) > 255) {
+ throw new PHPExcel_Writer_Exception("String is too long");
+ }
+
+ return pack('C', $this->ptg['ptgStr']) . PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($string);
+ }
+
+ /**
+ * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
+ * args that it takes.
+ *
+ * @access private
+ * @param string $token The name of the function for convertion to ptg value.
+ * @param integer $num_args The number of arguments the function receives.
+ * @return string The packed ptg for the function
+ */
+ private function convertFunction($token, $num_args)
+ {
+ $args = $this->functions[$token][1];
+// $volatile = $this->functions[$token][3];
+
+ // Fixed number of args eg. TIME($i, $j, $k).
+ if ($args >= 0) {
+ return pack("Cv", $this->ptg['ptgFuncV'], $this->functions[$token][0]);
+ }
+ // Variable number of args eg. SUM($i, $j, $k, ..).
+ if ($args == -1) {
+ return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]);
+ }
+ }
+
+ /**
+ * Convert an Excel range such as A1:D4 to a ptgRefV.
+ *
+ * @access private
+ * @param string $range An Excel range in the A1:A2
+ * @param int $class
+ */
+ private function convertRange2d($range, $class = 0)
+ {
+
+ // TODO: possible class value 0,1,2 check Formula.pm
+ // Split the range into 2 cell refs
+ if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
+ list($cell1, $cell2) = explode(':', $range);
+ } else {
+ // TODO: use real error codes
+ throw new PHPExcel_Writer_Exception("Unknown range separator");
+ }
+
+ // Convert the cell references
+ list($row1, $col1) = $this->cellToPackedRowcol($cell1);
+ list($row2, $col2) = $this->cellToPackedRowcol($cell2);
+
+ // The ptg value depends on the class of the ptg.
+ if ($class == 0) {
+ $ptgArea = pack("C", $this->ptg['ptgArea']);
+ } elseif ($class == 1) {
+ $ptgArea = pack("C", $this->ptg['ptgAreaV']);
+ } elseif ($class == 2) {
+ $ptgArea = pack("C", $this->ptg['ptgAreaA']);
+ } else {
+ // TODO: use real error codes
+ throw new PHPExcel_Writer_Exception("Unknown class $class");
+ }
+ return $ptgArea . $row1 . $row2 . $col1. $col2;
+ }
+
+ /**
+ * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
+ * a ptgArea3d.
+ *
+ * @access private
+ * @param string $token An Excel range in the Sheet1!A1:A2 format.
+ * @return mixed The packed ptgArea3d token on success.
+ */
+ private function convertRange3d($token)
+ {
+// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B)
+
+ // Split the ref at the ! symbol
+ list($ext_ref, $range) = explode('!', $token);
+
+ // Convert the external reference part (different for BIFF8)
+ $ext_ref = $this->getRefIndex($ext_ref);
+
+ // Split the range into 2 cell refs
+ list($cell1, $cell2) = explode(':', $range);
+
+ // Convert the cell references
+ if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) {
+ list($row1, $col1) = $this->cellToPackedRowcol($cell1);
+ list($row2, $col2) = $this->cellToPackedRowcol($cell2);
+ } else { // It's a rows range (like 26:27)
+ list($row1, $col1, $row2, $col2) = $this->rangeToPackedRange($cell1.':'.$cell2);
+ }
+
+ // The ptg value depends on the class of the ptg.
+// if ($class == 0) {
+ $ptgArea = pack("C", $this->ptg['ptgArea3d']);
+// } elseif ($class == 1) {
+// $ptgArea = pack("C", $this->ptg['ptgArea3dV']);
+// } elseif ($class == 2) {
+// $ptgArea = pack("C", $this->ptg['ptgArea3dA']);
+// } else {
+// throw new PHPExcel_Writer_Exception("Unknown class $class");
+// }
+
+ return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2;
+ }
+
+ /**
+ * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
+ *
+ * @access private
+ * @param string $cell An Excel cell reference
+ * @return string The cell in packed() format with the corresponding ptg
+ */
+ private function convertRef2d($cell)
+ {
+// $class = 2; // as far as I know, this is magick.
+
+ // Convert the cell reference
+ $cell_array = $this->cellToPackedRowcol($cell);
+ list($row, $col) = $cell_array;
+
+ // The ptg value depends on the class of the ptg.
+// if ($class == 0) {
+// $ptgRef = pack("C", $this->ptg['ptgRef']);
+// } elseif ($class == 1) {
+// $ptgRef = pack("C", $this->ptg['ptgRefV']);
+// } elseif ($class == 2) {
+ $ptgRef = pack("C", $this->ptg['ptgRefA']);
+// } else {
+// // TODO: use real error codes
+// throw new PHPExcel_Writer_Exception("Unknown class $class");
+// }
+ return $ptgRef.$row.$col;
+ }
+
+ /**
+ * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
+ * ptgRef3d.
+ *
+ * @access private
+ * @param string $cell An Excel cell reference
+ * @return mixed The packed ptgRef3d token on success.
+ */
+ private function convertRef3d($cell)
+ {
+// $class = 2; // as far as I know, this is magick.
+
+ // Split the ref at the ! symbol
+ list($ext_ref, $cell) = explode('!', $cell);
+
+ // Convert the external reference part (different for BIFF8)
+ $ext_ref = $this->getRefIndex($ext_ref);
+
+ // Convert the cell reference part
+ list($row, $col) = $this->cellToPackedRowcol($cell);
+
+ // The ptg value depends on the class of the ptg.
+// if ($class == 0) {
+// $ptgRef = pack("C", $this->ptg['ptgRef3d']);
+// } elseif ($class == 1) {
+// $ptgRef = pack("C", $this->ptg['ptgRef3dV']);
+// } elseif ($class == 2) {
+ $ptgRef = pack("C", $this->ptg['ptgRef3dA']);
+// } else {
+// throw new PHPExcel_Writer_Exception("Unknown class $class");
+// }
+
+ return $ptgRef . $ext_ref. $row . $col;
+ }
/**
* Convert an error code to a ptgErr
*
- * @access private
- * @param string $errorCode The error code for conversion to its ptg value
- * @return string The error code ptgErr
+ * @access private
+ * @param string $errorCode The error code for conversion to its ptg value
+ * @return string The error code ptgErr
+ */
+ private function convertError($errorCode)
+ {
+ switch ($errorCode) {
+ case '#NULL!':
+ return pack("C", 0x00);
+ case '#DIV/0!':
+ return pack("C", 0x07);
+ case '#VALUE!':
+ return pack("C", 0x0F);
+ case '#REF!':
+ return pack("C", 0x17);
+ case '#NAME?':
+ return pack("C", 0x1D);
+ case '#NUM!':
+ return pack("C", 0x24);
+ case '#N/A':
+ return pack("C", 0x2A);
+ }
+ return pack("C", 0xFF);
+ }
+
+ /**
+ * Convert the sheet name part of an external reference, for example "Sheet1" or
+ * "Sheet1:Sheet2", to a packed structure.
+ *
+ * @access private
+ * @param string $ext_ref The name of the external reference
+ * @return string The reference index in packed() format
+ */
+ private function packExtRef($ext_ref)
+ {
+ $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
+ $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
+
+ // Check if there is a sheet range eg., Sheet1:Sheet2.
+ if (preg_match("/:/", $ext_ref)) {
+ list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
+
+ $sheet1 = $this->getSheetIndex($sheet_name1);
+ if ($sheet1 == -1) {
+ throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula");
+ }
+ $sheet2 = $this->getSheetIndex($sheet_name2);
+ if ($sheet2 == -1) {
+ throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula");
+ }
+
+ // Reverse max and min sheet numbers if necessary
+ if ($sheet1 > $sheet2) {
+ list($sheet1, $sheet2) = array($sheet2, $sheet1);
+ }
+ } else { // Single sheet name only.
+ $sheet1 = $this->getSheetIndex($ext_ref);
+ if ($sheet1 == -1) {
+ throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula");
+ }
+ $sheet2 = $sheet1;
+ }
+
+ // References are stored relative to 0xFFFF.
+ $offset = -1 - $sheet1;
+
+ return pack('vdvv', $offset, 0x00, $sheet1, $sheet2);
+ }
+
+ /**
+ * Look up the REF index that corresponds to an external sheet name
+ * (or range). If it doesn't exist yet add it to the workbook's references
+ * array. It assumes all sheet names given must exist.
+ *
+ * @access private
+ * @param string $ext_ref The name of the external reference
+ * @return mixed The reference index in packed() format on success
+ */
+ private function getRefIndex($ext_ref)
+ {
+ $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
+ $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
+ $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
+
+ // Check if there is a sheet range eg., Sheet1:Sheet2.
+ if (preg_match("/:/", $ext_ref)) {
+ list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
+
+ $sheet1 = $this->getSheetIndex($sheet_name1);
+ if ($sheet1 == -1) {
+ throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula");
+ }
+ $sheet2 = $this->getSheetIndex($sheet_name2);
+ if ($sheet2 == -1) {
+ throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula");
+ }
+
+ // Reverse max and min sheet numbers if necessary
+ if ($sheet1 > $sheet2) {
+ list($sheet1, $sheet2) = array($sheet2, $sheet1);
+ }
+ } else { // Single sheet name only.
+ $sheet1 = $this->getSheetIndex($ext_ref);
+ if ($sheet1 == -1) {
+ throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula");
+ }
+ $sheet2 = $sheet1;
+ }
+
+ // assume all references belong to this document
+ $supbook_index = 0x00;
+ $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
+ $totalreferences = count($this->references);
+ $index = -1;
+ for ($i = 0; $i < $totalreferences; ++$i) {
+ if ($ref == $this->references[$i]) {
+ $index = $i;
+ break;
+ }
+ }
+ // if REF was not found add it to references array
+ if ($index == -1) {
+ $this->references[$totalreferences] = $ref;
+ $index = $totalreferences;
+ }
+
+ return pack('v', $index);
+ }
+
+ /**
+ * Look up the index that corresponds to an external sheet name. The hash of
+ * sheet names is updated by the addworksheet() method of the
+ * PHPExcel_Writer_Excel5_Workbook class.
+ *
+ * @access private
+ * @param string $sheet_name Sheet name
+ * @return integer The sheet index, -1 if the sheet was not found
+ */
+ private function getSheetIndex($sheet_name)
+ {
+ if (!isset($this->externalSheets[$sheet_name])) {
+ return -1;
+ } else {
+ return $this->externalSheets[$sheet_name];
+ }
+ }
+
+ /**
+ * This method is used to update the array of sheet names. It is
+ * called by the addWorksheet() method of the
+ * PHPExcel_Writer_Excel5_Workbook class.
+ *
+ * @access public
+ * @see PHPExcel_Writer_Excel5_Workbook::addWorksheet()
+ * @param string $name The name of the worksheet being added
+ * @param integer $index The index of the worksheet being added
*/
- function _convertError($errorCode)
+ public function setExtSheet($name, $index)
{
- switch ($errorCode) {
- case '#NULL!': return pack("C", 0x00);
- case '#DIV/0!': return pack("C", 0x07);
- case '#VALUE!': return pack("C", 0x0F);
- case '#REF!': return pack("C", 0x17);
- case '#NAME?': return pack("C", 0x1D);
- case '#NUM!': return pack("C", 0x24);
- case '#N/A': return pack("C", 0x2A);
- }
- return pack("C", 0xFF);
+ $this->externalSheets[$name] = $index;
}
- /**
- * Convert the sheet name part of an external reference, for example "Sheet1" or
- * "Sheet1:Sheet2", to a packed structure.
- *
- * @access private
- * @param string $ext_ref The name of the external reference
- * @return string The reference index in packed() format
- */
- function _packExtRef($ext_ref)
- {
- $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
- $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
-
- // Check if there is a sheet range eg., Sheet1:Sheet2.
- if (preg_match("/:/", $ext_ref)) {
- list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
-
- $sheet1 = $this->_getSheetIndex($sheet_name1);
- if ($sheet1 == -1) {
- throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula");
- }
- $sheet2 = $this->_getSheetIndex($sheet_name2);
- if ($sheet2 == -1) {
- throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula");
- }
-
- // Reverse max and min sheet numbers if necessary
- if ($sheet1 > $sheet2) {
- list($sheet1, $sheet2) = array($sheet2, $sheet1);
- }
- } else { // Single sheet name only.
- $sheet1 = $this->_getSheetIndex($ext_ref);
- if ($sheet1 == -1) {
- throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula");
- }
- $sheet2 = $sheet1;
- }
-
- // References are stored relative to 0xFFFF.
- $offset = -1 - $sheet1;
-
- return pack('vdvv', $offset, 0x00, $sheet1, $sheet2);
- }
-
- /**
- * Look up the REF index that corresponds to an external sheet name
- * (or range). If it doesn't exist yet add it to the workbook's references
- * array. It assumes all sheet names given must exist.
- *
- * @access private
- * @param string $ext_ref The name of the external reference
- * @return mixed The reference index in packed() format on success
- */
- function _getRefIndex($ext_ref)
- {
- $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any.
- $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any.
- $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
-
- // Check if there is a sheet range eg., Sheet1:Sheet2.
- if (preg_match("/:/", $ext_ref)) {
- list($sheet_name1, $sheet_name2) = explode(':', $ext_ref);
-
- $sheet1 = $this->_getSheetIndex($sheet_name1);
- if ($sheet1 == -1) {
- throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula");
- }
- $sheet2 = $this->_getSheetIndex($sheet_name2);
- if ($sheet2 == -1) {
- throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula");
- }
-
- // Reverse max and min sheet numbers if necessary
- if ($sheet1 > $sheet2) {
- list($sheet1, $sheet2) = array($sheet2, $sheet1);
- }
- } else { // Single sheet name only.
- $sheet1 = $this->_getSheetIndex($ext_ref);
- if ($sheet1 == -1) {
- throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula");
- }
- $sheet2 = $sheet1;
- }
-
- // assume all references belong to this document
- $supbook_index = 0x00;
- $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
- $total_references = count($this->_references);
- $index = -1;
- for ($i = 0; $i < $total_references; ++$i) {
- if ($ref == $this->_references[$i]) {
- $index = $i;
- break;
- }
- }
- // if REF was not found add it to references array
- if ($index == -1) {
- $this->_references[$total_references] = $ref;
- $index = $total_references;
- }
-
- return pack('v', $index);
- }
-
- /**
- * Look up the index that corresponds to an external sheet name. The hash of
- * sheet names is updated by the addworksheet() method of the
- * PHPExcel_Writer_Excel5_Workbook class.
- *
- * @access private
- * @param string $sheet_name Sheet name
- * @return integer The sheet index, -1 if the sheet was not found
- */
- function _getSheetIndex($sheet_name)
- {
- if (!isset($this->_ext_sheets[$sheet_name])) {
- return -1;
- } else {
- return $this->_ext_sheets[$sheet_name];
- }
- }
-
- /**
- * This method is used to update the array of sheet names. It is
- * called by the addWorksheet() method of the
- * PHPExcel_Writer_Excel5_Workbook class.
- *
- * @access public
- * @see PHPExcel_Writer_Excel5_Workbook::addWorksheet()
- * @param string $name The name of the worksheet being added
- * @param integer $index The index of the worksheet being added
- */
- function setExtSheet($name, $index)
- {
- $this->_ext_sheets[$name] = $index;
- }
-
- /**
- * pack() row and column into the required 3 or 4 byte format.
- *
- * @access private
- * @param string $cell The Excel cell reference to be packed
- * @return array Array containing the row and column in packed() format
- */
- function _cellToPackedRowcol($cell)
- {
- $cell = strtoupper($cell);
- list($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell);
- if ($col >= 256) {
- throw new PHPExcel_Writer_Exception("Column in: $cell greater than 255");
- }
- if ($row >= 65536) {
- throw new PHPExcel_Writer_Exception("Row in: $cell greater than 65536 ");
- }
-
- // Set the high bits to indicate if row or col are relative.
- $col |= $col_rel << 14;
- $col |= $row_rel << 15;
- $col = pack('v', $col);
-
- $row = pack('v', $row);
-
- return array($row, $col);
- }
-
- /**
- * pack() row range into the required 3 or 4 byte format.
- * Just using maximum col/rows, which is probably not the correct solution
- *
- * @access private
- * @param string $range The Excel range to be packed
- * @return array Array containing (row1,col1,row2,col2) in packed() format
- */
- function _rangeToPackedRange($range)
- {
- preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match);
- // return absolute rows if there is a $ in the ref
- $row1_rel = empty($match[1]) ? 1 : 0;
- $row1 = $match[2];
- $row2_rel = empty($match[3]) ? 1 : 0;
- $row2 = $match[4];
- // Convert 1-index to zero-index
- --$row1;
- --$row2;
- // Trick poor inocent Excel
- $col1 = 0;
- $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
-
- // FIXME: this changes for BIFF8
- if (($row1 >= 65536) or ($row2 >= 65536)) {
- throw new PHPExcel_Writer_Exception("Row in: $range greater than 65536 ");
- }
-
- // Set the high bits to indicate if rows are relative.
- $col1 |= $row1_rel << 15;
- $col2 |= $row2_rel << 15;
- $col1 = pack('v', $col1);
- $col2 = pack('v', $col2);
-
- $row1 = pack('v', $row1);
- $row2 = pack('v', $row2);
-
- return array($row1, $col1, $row2, $col2);
- }
-
- /**
- * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
- * indexed row and column number. Also returns two (0,1) values to indicate
- * whether the row or column are relative references.
- *
- * @access private
- * @param string $cell The Excel cell reference in A1 format.
- * @return array
- */
- function _cellToRowcol($cell)
- {
- preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match);
- // return absolute column if there is a $ in the ref
- $col_rel = empty($match[1]) ? 1 : 0;
- $col_ref = $match[2];
- $row_rel = empty($match[3]) ? 1 : 0;
- $row = $match[4];
-
- // Convert base26 column string to a number.
- $expn = strlen($col_ref) - 1;
- $col = 0;
- $col_ref_length = strlen($col_ref);
- for ($i = 0; $i < $col_ref_length; ++$i) {
- $col += (ord($col_ref{$i}) - 64) * pow(26, $expn);
- --$expn;
- }
-
- // Convert 1-index to zero-index
- --$row;
- --$col;
-
- return array($row, $col, $row_rel, $col_rel);
- }
-
- /**
- * Advance to the next valid token.
- *
- * @access private
- */
- function _advance()
- {
- $i = $this->_current_char;
- $formula_length = strlen($this->_formula);
- // eat up white spaces
- if ($i < $formula_length) {
- while ($this->_formula{$i} == " ") {
- ++$i;
- }
-
- if ($i < ($formula_length - 1)) {
- $this->_lookahead = $this->_formula{$i+1};
- }
- $token = '';
- }
-
- while ($i < $formula_length) {
- $token .= $this->_formula{$i};
-
- if ($i < ($formula_length - 1)) {
- $this->_lookahead = $this->_formula{$i+1};
- } else {
- $this->_lookahead = '';
- }
-
- if ($this->_match($token) != '') {
- //if ($i < strlen($this->_formula) - 1) {
- // $this->_lookahead = $this->_formula{$i+1};
- //}
- $this->_current_char = $i + 1;
- $this->_current_token = $token;
- return 1;
- }
-
- if ($i < ($formula_length - 2)) {
- $this->_lookahead = $this->_formula{$i+2};
- } else { // if we run out of characters _lookahead becomes empty
- $this->_lookahead = '';
- }
- ++$i;
- }
- //die("Lexical error ".$this->_current_char);
- }
-
- /**
- * Checks if it's a valid token.
- *
- * @access private
- * @param mixed $token The token to check.
- * @return mixed The checked token or false on failure
- */
- function _match($token)
- {
- switch($token) {
- case "+":
- case "-":
- case "*":
- case "/":
- case "(":
- case ")":
- case ",":
- case ";":
- case ">=":
- case "<=":
- case "=":
- case "<>":
- case "^":
- case "&":
- case "%":
- return $token;
- break;
- case ">":
- if ($this->_lookahead == '=') { // it's a GE token
- break;
- }
- return $token;
- break;
- case "<":
- // it's a LE or a NE token
- if (($this->_lookahead == '=') or ($this->_lookahead == '>')) {
- break;
- }
- return $token;
- break;
- default:
- // if it's a reference A1 or $A$1 or $A1 or A$1
- if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and
- !preg_match("/[0-9]/",$this->_lookahead) and
- ($this->_lookahead != ':') and ($this->_lookahead != '.') and
- ($this->_lookahead != '!'))
- {
- return $token;
- }
- // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead) and
- ($this->_lookahead != ':') and ($this->_lookahead != '.'))
- {
- return $token;
- }
- // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead) and
- ($this->_lookahead != ':') and ($this->_lookahead != '.'))
- {
- return $token;
- }
- // if it's a range A1:A2 or $A$1:$A$2
- elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) and
- !preg_match("/[0-9]/",$this->_lookahead))
- {
- return $token;
- }
- // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead))
- {
- return $token;
- }
- // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and
- !preg_match("/[0-9]/",$this->_lookahead))
- {
- return $token;
- }
- // If it's a number (check that it's not a sheet name or range)
- elseif (is_numeric($token) and
- (!is_numeric($token.$this->_lookahead) or ($this->_lookahead == '')) and
- ($this->_lookahead != '!') and ($this->_lookahead != ':'))
- {
- return $token;
- }
- // If it's a string (of maximum 255 characters)
- elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/",$token) and $this->_lookahead != '"' and (substr_count($token, '"')%2 == 0))
- {
- return $token;
- }
- // If it's an error code
- elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A')
- {
- return $token;
- }
- // if it's a function call
- elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "("))
- {
- return $token;
- }
- // It's an argument of some description (e.g. a named range),
- // precise nature yet to be determined
- elseif(substr($token,-1) == ')') {
- return $token;
- }
- return '';
- }
- }
-
- /**
- * The parsing method. It parses a formula.
- *
- * @access public
- * @param string $formula The formula to parse, without the initial equal
- * sign (=).
- * @return mixed true on success
- */
- function parse($formula)
- {
- $this->_current_char = 0;
- $this->_formula = $formula;
- $this->_lookahead = isset($formula{1}) ? $formula{1} : '';
- $this->_advance();
- $this->_parse_tree = $this->_condition();
- return true;
- }
-
- /**
- * It parses a condition. It assumes the following rule:
- * Cond -> Expr [(">" | "<") Expr]
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _condition()
- {
- $result = $this->_expression();
- if ($this->_current_token == "<") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgLT', $result, $result2);
- } elseif ($this->_current_token == ">") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgGT', $result, $result2);
- } elseif ($this->_current_token == "<=") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgLE', $result, $result2);
- } elseif ($this->_current_token == ">=") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgGE', $result, $result2);
- } elseif ($this->_current_token == "=") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgEQ', $result, $result2);
- } elseif ($this->_current_token == "<>") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgNE', $result, $result2);
- } elseif ($this->_current_token == "&") {
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgConcat', $result, $result2);
- }
- return $result;
- }
-
- /**
- * It parses a expression. It assumes the following rule:
- * Expr -> Term [("+" | "-") Term]
- * -> "string"
- * -> "-" Term : Negative value
- * -> "+" Term : Positive value
- * -> Error code
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _expression()
- {
- // If it's a string return a string node
- if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->_current_token)) {
- $tmp = str_replace('""', '"', $this->_current_token);
- if (($tmp == '"') || ($tmp == '')) $tmp = '""'; // Trap for "" that has been used for an empty string
- $result = $this->_createTree($tmp, '', '');
- $this->_advance();
- return $result;
+ /**
+ * pack() row and column into the required 3 or 4 byte format.
+ *
+ * @access private
+ * @param string $cell The Excel cell reference to be packed
+ * @return array Array containing the row and column in packed() format
+ */
+ private function cellToPackedRowcol($cell)
+ {
+ $cell = strtoupper($cell);
+ list($row, $col, $row_rel, $col_rel) = $this->cellToRowcol($cell);
+ if ($col >= 256) {
+ throw new PHPExcel_Writer_Exception("Column in: $cell greater than 255");
+ }
+ if ($row >= 65536) {
+ throw new PHPExcel_Writer_Exception("Row in: $cell greater than 65536 ");
+ }
+
+ // Set the high bits to indicate if row or col are relative.
+ $col |= $col_rel << 14;
+ $col |= $row_rel << 15;
+ $col = pack('v', $col);
+
+ $row = pack('v', $row);
+
+ return array($row, $col);
+ }
+
+ /**
+ * pack() row range into the required 3 or 4 byte format.
+ * Just using maximum col/rows, which is probably not the correct solution
+ *
+ * @access private
+ * @param string $range The Excel range to be packed
+ * @return array Array containing (row1,col1,row2,col2) in packed() format
+ */
+ private function rangeToPackedRange($range)
+ {
+ preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match);
+ // return absolute rows if there is a $ in the ref
+ $row1_rel = empty($match[1]) ? 1 : 0;
+ $row1 = $match[2];
+ $row2_rel = empty($match[3]) ? 1 : 0;
+ $row2 = $match[4];
+ // Convert 1-index to zero-index
+ --$row1;
+ --$row2;
+ // Trick poor inocent Excel
+ $col1 = 0;
+ $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
+
+ // FIXME: this changes for BIFF8
+ if (($row1 >= 65536) or ($row2 >= 65536)) {
+ throw new PHPExcel_Writer_Exception("Row in: $range greater than 65536 ");
+ }
+
+ // Set the high bits to indicate if rows are relative.
+ $col1 |= $row1_rel << 15;
+ $col2 |= $row2_rel << 15;
+ $col1 = pack('v', $col1);
+ $col2 = pack('v', $col2);
+
+ $row1 = pack('v', $row1);
+ $row2 = pack('v', $row2);
+
+ return array($row1, $col1, $row2, $col2);
+ }
+
+ /**
+ * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
+ * indexed row and column number. Also returns two (0,1) values to indicate
+ * whether the row or column are relative references.
+ *
+ * @access private
+ * @param string $cell The Excel cell reference in A1 format.
+ * @return array
+ */
+ private function cellToRowcol($cell)
+ {
+ preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match);
+ // return absolute column if there is a $ in the ref
+ $col_rel = empty($match[1]) ? 1 : 0;
+ $col_ref = $match[2];
+ $row_rel = empty($match[3]) ? 1 : 0;
+ $row = $match[4];
+
+ // Convert base26 column string to a number.
+ $expn = strlen($col_ref) - 1;
+ $col = 0;
+ $col_ref_length = strlen($col_ref);
+ for ($i = 0; $i < $col_ref_length; ++$i) {
+ $col += (ord($col_ref{$i}) - 64) * pow(26, $expn);
+ --$expn;
+ }
+
+ // Convert 1-index to zero-index
+ --$row;
+ --$col;
+
+ return array($row, $col, $row_rel, $col_rel);
+ }
+
+ /**
+ * Advance to the next valid token.
+ *
+ * @access private
+ */
+ private function advance()
+ {
+ $i = $this->currentCharacter;
+ $formula_length = strlen($this->formula);
+ // eat up white spaces
+ if ($i < $formula_length) {
+ while ($this->formula{$i} == " ") {
+ ++$i;
+ }
+
+ if ($i < ($formula_length - 1)) {
+ $this->lookAhead = $this->formula{$i+1};
+ }
+ $token = '';
+ }
+
+ while ($i < $formula_length) {
+ $token .= $this->formula{$i};
+
+ if ($i < ($formula_length - 1)) {
+ $this->lookAhead = $this->formula{$i+1};
+ } else {
+ $this->lookAhead = '';
+ }
+
+ if ($this->match($token) != '') {
+ //if ($i < strlen($this->formula) - 1) {
+ // $this->lookAhead = $this->formula{$i+1};
+ //}
+ $this->currentCharacter = $i + 1;
+ $this->currentToken = $token;
+ return 1;
+ }
+
+ if ($i < ($formula_length - 2)) {
+ $this->lookAhead = $this->formula{$i+2};
+ } else { // if we run out of characters lookAhead becomes empty
+ $this->lookAhead = '';
+ }
+ ++$i;
+ }
+ //die("Lexical error ".$this->currentCharacter);
+ }
+
+ /**
+ * Checks if it's a valid token.
+ *
+ * @access private
+ * @param mixed $token The token to check.
+ * @return mixed The checked token or false on failure
+ */
+ private function match($token)
+ {
+ switch ($token) {
+ case "+":
+ case "-":
+ case "*":
+ case "/":
+ case "(":
+ case ")":
+ case ",":
+ case ";":
+ case ">=":
+ case "<=":
+ case "=":
+ case "<>":
+ case "^":
+ case "&":
+ case "%":
+ return $token;
+ break;
+ case ">":
+ if ($this->lookAhead == '=') { // it's a GE token
+ break;
+ }
+ return $token;
+ break;
+ case "<":
+ // it's a LE or a NE token
+ if (($this->lookAhead == '=') or ($this->lookAhead == '>')) {
+ break;
+ }
+ return $token;
+ break;
+ default:
+ // if it's a reference A1 or $A$1 or $A1 or A$1
+ if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.') and ($this->lookAhead != '!')) {
+ return $token;
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) {
+ // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
+ return $token;
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) {
+ // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
+ return $token;
+ } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) && !preg_match("/[0-9]/", $this->lookAhead)) {
+ // if it's a range A1:A2 or $A$1:$A$2
+ return $token;
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead)) {
+ // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
+ return $token;
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead)) {
+ // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
+ return $token;
+ } elseif (is_numeric($token) and (!is_numeric($token.$this->lookAhead) or ($this->lookAhead == '')) and ($this->lookAhead != '!') and ($this->lookAhead != ':')) {
+ // If it's a number (check that it's not a sheet name or range)
+ return $token;
+ } elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token) and $this->lookAhead != '"' and (substr_count($token, '"')%2 == 0)) {
+ // If it's a string (of maximum 255 characters)
+ return $token;
+ } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') {
+ // If it's an error code
+ return $token;
+ } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $token) and ($this->lookAhead == "(")) {
+ // if it's a function call
+ return $token;
+ } elseif (substr($token, -1) == ')') {
+ // It's an argument of some description (e.g. a named range),
+ // precise nature yet to be determined
+ return $token;
+ }
+ return '';
+ }
+ }
+
+ /**
+ * The parsing method. It parses a formula.
+ *
+ * @access public
+ * @param string $formula The formula to parse, without the initial equal
+ * sign (=).
+ * @return mixed true on success
+ */
+ public function parse($formula)
+ {
+ $this->currentCharacter = 0;
+ $this->formula = $formula;
+ $this->lookAhead = isset($formula{1}) ? $formula{1} : '';
+ $this->advance();
+ $this->parseTree = $this->condition();
+ return true;
+ }
+
+ /**
+ * It parses a condition. It assumes the following rule:
+ * Cond -> Expr [(">" | "<") Expr]
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ private function condition()
+ {
+ $result = $this->expression();
+ if ($this->currentToken == "<") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgLT', $result, $result2);
+ } elseif ($this->currentToken == ">") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgGT', $result, $result2);
+ } elseif ($this->currentToken == "<=") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgLE', $result, $result2);
+ } elseif ($this->currentToken == ">=") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgGE', $result, $result2);
+ } elseif ($this->currentToken == "=") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgEQ', $result, $result2);
+ } elseif ($this->currentToken == "<>") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgNE', $result, $result2);
+ } elseif ($this->currentToken == "&") {
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgConcat', $result, $result2);
+ }
+ return $result;
+ }
+
+ /**
+ * It parses a expression. It assumes the following rule:
+ * Expr -> Term [("+" | "-") Term]
+ * -> "string"
+ * -> "-" Term : Negative value
+ * -> "+" Term : Positive value
+ * -> Error code
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ private function expression()
+ {
+ // If it's a string return a string node
+ if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->currentToken)) {
+ $tmp = str_replace('""', '"', $this->currentToken);
+ if (($tmp == '"') || ($tmp == '')) {
+ // Trap for "" that has been used for an empty string
+ $tmp = '""';
+ }
+ $result = $this->createTree($tmp, '', '');
+ $this->advance();
+ return $result;
// If it's an error code
- } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->_current_token) or $this->_current_token == '#N/A'){
- $result = $this->_createTree($this->_current_token, 'ptgErr', '');
- $this->_advance();
- return $result;
- // If it's a negative value
- } elseif ($this->_current_token == "-") {
- // catch "-" Term
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgUminus', $result2, '');
- return $result;
+ } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->currentToken) or $this->currentToken == '#N/A') {
+ $result = $this->createTree($this->currentToken, 'ptgErr', '');
+ $this->advance();
+ return $result;
+ // If it's a negative value
+ } elseif ($this->currentToken == "-") {
+ // catch "-" Term
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgUminus', $result2, '');
+ return $result;
// If it's a positive value
- } elseif ($this->_current_token == "+") {
- // catch "+" Term
- $this->_advance();
- $result2 = $this->_expression();
- $result = $this->_createTree('ptgUplus', $result2, '');
- return $result;
- }
- $result = $this->_term();
- while (($this->_current_token == "+") or
- ($this->_current_token == "-") or
- ($this->_current_token == "^")) {
- /**/
- if ($this->_current_token == "+") {
- $this->_advance();
- $result2 = $this->_term();
- $result = $this->_createTree('ptgAdd', $result, $result2);
- } elseif ($this->_current_token == "-") {
- $this->_advance();
- $result2 = $this->_term();
- $result = $this->_createTree('ptgSub', $result, $result2);
- } else {
- $this->_advance();
- $result2 = $this->_term();
- $result = $this->_createTree('ptgPower', $result, $result2);
- }
- }
- return $result;
- }
-
- /**
- * This function just introduces a ptgParen element in the tree, so that Excel
- * doesn't get confused when working with a parenthesized formula afterwards.
- *
- * @access private
- * @see _fact()
- * @return array The parsed ptg'd tree
- */
- function _parenthesizedExpression()
- {
- $result = $this->_createTree('ptgParen', $this->_expression(), '');
- return $result;
- }
-
- /**
- * It parses a term. It assumes the following rule:
- * Term -> Fact [("*" | "/") Fact]
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _term()
- {
- $result = $this->_fact();
- while (($this->_current_token == "*") or
- ($this->_current_token == "/")) {
- /**/
- if ($this->_current_token == "*") {
- $this->_advance();
- $result2 = $this->_fact();
- $result = $this->_createTree('ptgMul', $result, $result2);
- } else {
- $this->_advance();
- $result2 = $this->_fact();
- $result = $this->_createTree('ptgDiv', $result, $result2);
- }
- }
- return $result;
- }
-
- /**
- * It parses a factor. It assumes the following rule:
- * Fact -> ( Expr )
- * | CellRef
- * | CellRange
- * | Number
- * | Function
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _fact()
- {
- if ($this->_current_token == "(") {
- $this->_advance(); // eat the "("
- $result = $this->_parenthesizedExpression();
- if ($this->_current_token != ")") {
- throw new PHPExcel_Writer_Exception("')' token expected.");
- }
- $this->_advance(); // eat the ")"
- return $result;
- }
- // if it's a reference
- if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$this->_current_token))
- {
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token))
- {
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token))
- {
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // if it's a range A1:B2 or $A$1:$B$2
- elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token) or
- preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token))
- {
- // must be an error?
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
- elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token))
- {
- // must be an error?
- //$result = $this->_current_token;
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
- elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token))
- {
- // must be an error?
- //$result = $this->_current_token;
- $result = $this->_createTree($this->_current_token, '', '');
- $this->_advance();
- return $result;
- }
- // If it's a number or a percent
- elseif (is_numeric($this->_current_token))
- {
- if($this->_lookahead == '%'){
- $result = $this->_createTree('ptgPercent', $this->_current_token, '');
- } else {
- $result = $this->_createTree($this->_current_token, '', '');
- }
- $this->_advance();
- return $result;
- }
- // if it's a function call
- elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$this->_current_token))
- {
- $result = $this->_func();
- return $result;
- }
- throw new PHPExcel_Writer_Exception("Syntax error: ".$this->_current_token.
- ", lookahead: ".$this->_lookahead.
- ", current char: ".$this->_current_char);
- }
-
- /**
- * It parses a function call. It assumes the following rule:
- * Func -> ( Expr [,Expr]* )
- *
- * @access private
- * @return mixed The parsed ptg'd tree on success
- */
- function _func()
- {
- $num_args = 0; // number of arguments received
- $function = strtoupper($this->_current_token);
- $result = ''; // initialize result
- $this->_advance();
- $this->_advance(); // eat the "("
- while ($this->_current_token != ')') {
- /**/
- if ($num_args > 0) {
- if ($this->_current_token == "," or
- $this->_current_token == ";")
- {
- $this->_advance(); // eat the "," or ";"
- } else {
- throw new PHPExcel_Writer_Exception("Syntax error: comma expected in ".
- "function $function, arg #{$num_args}");
- }
- $result2 = $this->_condition();
- $result = $this->_createTree('arg', $result, $result2);
- } else { // first argument
- $result2 = $this->_condition();
- $result = $this->_createTree('arg', '', $result2);
- }
- ++$num_args;
- }
- if (!isset($this->_functions[$function])) {
- throw new PHPExcel_Writer_Exception("Function $function() doesn't exist");
- }
- $args = $this->_functions[$function][1];
- // If fixed number of args eg. TIME($i,$j,$k). Check that the number of args is valid.
- if (($args >= 0) and ($args != $num_args)) {
- throw new PHPExcel_Writer_Exception("Incorrect number of arguments in function $function() ");
- }
-
- $result = $this->_createTree($function, $result, $num_args);
- $this->_advance(); // eat the ")"
- return $result;
- }
-
- /**
- * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
- * as elements.
- *
- * @access private
- * @param mixed $value The value of this node.
- * @param mixed $left The left array (sub-tree) or a final node.
- * @param mixed $right The right array (sub-tree) or a final node.
- * @return array A tree
- */
- function _createTree($value, $left, $right)
- {
- return array('value' => $value, 'left' => $left, 'right' => $right);
- }
-
- /**
- * Builds a string containing the tree in reverse polish notation (What you
- * would use in a HP calculator stack).
- * The following tree:
- *
- * +
- * / \
- * 2 3
- *
- * produces: "23+"
- *
- * The following tree:
- *
- * +
- * / \
- * 3 *
- * / \
- * 6 A1
- *
- * produces: "36A1*+"
- *
- * In fact all operands, functions, references, etc... are written as ptg's
- *
- * @access public
- * @param array $tree The optional tree to convert.
- * @return string The tree in reverse polish notation
- */
- function toReversePolish($tree = array())
- {
- $polish = ""; // the string we are going to return
- if (empty($tree)) { // If it's the first call use _parse_tree
- $tree = $this->_parse_tree;
- }
-
- if (is_array($tree['left'])) {
- $converted_tree = $this->toReversePolish($tree['left']);
- $polish .= $converted_tree;
- } elseif ($tree['left'] != '') { // It's a final node
- $converted_tree = $this->_convert($tree['left']);
- $polish .= $converted_tree;
- }
- if (is_array($tree['right'])) {
- $converted_tree = $this->toReversePolish($tree['right']);
- $polish .= $converted_tree;
- } elseif ($tree['right'] != '') { // It's a final node
- $converted_tree = $this->_convert($tree['right']);
- $polish .= $converted_tree;
- }
- // if it's a function convert it here (so we can set it's arguments)
- if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",$tree['value']) and
- !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',$tree['value']) and
- !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",$tree['value']) and
- !is_numeric($tree['value']) and
- !isset($this->ptg[$tree['value']]))
- {
- // left subtree for a function is always an array.
- if ($tree['left'] != '') {
- $left_tree = $this->toReversePolish($tree['left']);
- } else {
- $left_tree = '';
- }
- // add it's left subtree and return.
- return $left_tree.$this->_convertFunction($tree['value'], $tree['right']);
- } else {
- $converted_tree = $this->_convert($tree['value']);
- }
- $polish .= $converted_tree;
- return $polish;
- }
+ } elseif ($this->currentToken == "+") {
+ // catch "+" Term
+ $this->advance();
+ $result2 = $this->expression();
+ $result = $this->createTree('ptgUplus', $result2, '');
+ return $result;
+ }
+ $result = $this->term();
+ while (($this->currentToken == "+") or
+ ($this->currentToken == "-") or
+ ($this->currentToken == "^")) {
+ /**/
+ if ($this->currentToken == "+") {
+ $this->advance();
+ $result2 = $this->term();
+ $result = $this->createTree('ptgAdd', $result, $result2);
+ } elseif ($this->currentToken == "-") {
+ $this->advance();
+ $result2 = $this->term();
+ $result = $this->createTree('ptgSub', $result, $result2);
+ } else {
+ $this->advance();
+ $result2 = $this->term();
+ $result = $this->createTree('ptgPower', $result, $result2);
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * This function just introduces a ptgParen element in the tree, so that Excel
+ * doesn't get confused when working with a parenthesized formula afterwards.
+ *
+ * @access private
+ * @see fact()
+ * @return array The parsed ptg'd tree
+ */
+ private function parenthesizedExpression()
+ {
+ $result = $this->createTree('ptgParen', $this->expression(), '');
+ return $result;
+ }
+
+ /**
+ * It parses a term. It assumes the following rule:
+ * Term -> Fact [("*" | "/") Fact]
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ private function term()
+ {
+ $result = $this->fact();
+ while (($this->currentToken == "*") or
+ ($this->currentToken == "/")) {
+ /**/
+ if ($this->currentToken == "*") {
+ $this->advance();
+ $result2 = $this->fact();
+ $result = $this->createTree('ptgMul', $result, $result2);
+ } else {
+ $this->advance();
+ $result2 = $this->fact();
+ $result = $this->createTree('ptgDiv', $result, $result2);
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * It parses a factor. It assumes the following rule:
+ * Fact -> ( Expr )
+ * | CellRef
+ * | CellRange
+ * | Number
+ * | Function
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ private function fact()
+ {
+ if ($this->currentToken == "(") {
+ $this->advance(); // eat the "("
+ $result = $this->parenthesizedExpression();
+ if ($this->currentToken != ")") {
+ throw new PHPExcel_Writer_Exception("')' token expected.");
+ }
+ $this->advance(); // eat the ")"
+ return $result;
+ }
+ // if it's a reference
+ if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $this->currentToken)) {
+ $result = $this->createTree($this->currentToken, '', '');
+ $this->advance();
+ return $result;
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) {
+ // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
+ $result = $this->createTree($this->currentToken, '', '');
+ $this->advance();
+ return $result;
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) {
+ // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
+ $result = $this->createTree($this->currentToken, '', '');
+ $this->advance();
+ return $result;
+ } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->currentToken) or
+ preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->currentToken)) {
+ // if it's a range A1:B2 or $A$1:$B$2
+ // must be an error?
+ $result = $this->createTree($this->currentToken, '', '');
+ $this->advance();
+ return $result;
+ } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) {
+ // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
+ // must be an error?
+ //$result = $this->currentToken;
+ $result = $this->createTree($this->currentToken, '', '');
+ $this->advance();
+ return $result;
+ } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) {
+ // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
+ // must be an error?
+ //$result = $this->currentToken;
+ $result = $this->createTree($this->currentToken, '', '');
+ $this->advance();
+ return $result;
+ } elseif (is_numeric($this->currentToken)) {
+ // If it's a number or a percent
+ if ($this->lookAhead == '%') {
+ $result = $this->createTree('ptgPercent', $this->currentToken, '');
+ $this->advance(); // Skip the percentage operator once we've pre-built that tree
+ } else {
+ $result = $this->createTree($this->currentToken, '', '');
+ }
+ $this->advance();
+ return $result;
+ } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $this->currentToken)) {
+ // if it's a function call
+ $result = $this->func();
+ return $result;
+ }
+ throw new PHPExcel_Writer_Exception("Syntax error: ".$this->currentToken.", lookahead: ".$this->lookAhead.", current char: ".$this->currentCharacter);
+ }
+
+ /**
+ * It parses a function call. It assumes the following rule:
+ * Func -> ( Expr [,Expr]* )
+ *
+ * @access private
+ * @return mixed The parsed ptg'd tree on success
+ */
+ private function func()
+ {
+ $num_args = 0; // number of arguments received
+ $function = strtoupper($this->currentToken);
+ $result = ''; // initialize result
+ $this->advance();
+ $this->advance(); // eat the "("
+ while ($this->currentToken != ')') {
+ /**/
+ if ($num_args > 0) {
+ if ($this->currentToken == "," || $this->currentToken == ";") {
+ $this->advance(); // eat the "," or ";"
+ } else {
+ throw new PHPExcel_Writer_Exception("Syntax error: comma expected in function $function, arg #{$num_args}");
+ }
+ $result2 = $this->condition();
+ $result = $this->createTree('arg', $result, $result2);
+ } else { // first argument
+ $result2 = $this->condition();
+ $result = $this->createTree('arg', '', $result2);
+ }
+ ++$num_args;
+ }
+ if (!isset($this->functions[$function])) {
+ throw new PHPExcel_Writer_Exception("Function $function() doesn't exist");
+ }
+ $args = $this->functions[$function][1];
+ // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid.
+ if (($args >= 0) and ($args != $num_args)) {
+ throw new PHPExcel_Writer_Exception("Incorrect number of arguments in function $function() ");
+ }
+
+ $result = $this->createTree($function, $result, $num_args);
+ $this->advance(); // eat the ")"
+ return $result;
+ }
+ /**
+ * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
+ * as elements.
+ *
+ * @access private
+ * @param mixed $value The value of this node.
+ * @param mixed $left The left array (sub-tree) or a final node.
+ * @param mixed $right The right array (sub-tree) or a final node.
+ * @return array A tree
+ */
+ private function createTree($value, $left, $right)
+ {
+ return array('value' => $value, 'left' => $left, 'right' => $right);
+ }
+
+ /**
+ * Builds a string containing the tree in reverse polish notation (What you
+ * would use in a HP calculator stack).
+ * The following tree:
+ *
+ * +
+ * / \
+ * 2 3
+ *
+ * produces: "23+"
+ *
+ * The following tree:
+ *
+ * +
+ * / \
+ * 3 *
+ * / \
+ * 6 A1
+ *
+ * produces: "36A1*+"
+ *
+ * In fact all operands, functions, references, etc... are written as ptg's
+ *
+ * @access public
+ * @param array $tree The optional tree to convert.
+ * @return string The tree in reverse polish notation
+ */
+ public function toReversePolish($tree = array())
+ {
+ $polish = ""; // the string we are going to return
+ if (empty($tree)) { // If it's the first call use parseTree
+ $tree = $this->parseTree;
+ }
+
+ if (is_array($tree['left'])) {
+ $converted_tree = $this->toReversePolish($tree['left']);
+ $polish .= $converted_tree;
+ } elseif ($tree['left'] != '') { // It's a final node
+ $converted_tree = $this->convert($tree['left']);
+ $polish .= $converted_tree;
+ }
+ if (is_array($tree['right'])) {
+ $converted_tree = $this->toReversePolish($tree['right']);
+ $polish .= $converted_tree;
+ } elseif ($tree['right'] != '') { // It's a final node
+ $converted_tree = $this->convert($tree['right']);
+ $polish .= $converted_tree;
+ }
+ // if it's a function convert it here (so we can set it's arguments)
+ if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/", $tree['value']) and
+ !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) and
+ !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/", $tree['value']) and
+ !is_numeric($tree['value']) and
+ !isset($this->ptg[$tree['value']])) {
+ // left subtree for a function is always an array.
+ if ($tree['left'] != '') {
+ $left_tree = $this->toReversePolish($tree['left']);
+ } else {
+ $left_tree = '';
+ }
+ // add it's left subtree and return.
+ return $left_tree.$this->convertFunction($tree['value'], $tree['right']);
+ } else {
+ $converted_tree = $this->convert($tree['value']);
+ }
+ $polish .= $converted_tree;
+ return $polish;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Workbook.php b/Classes/PHPExcel/Writer/Excel5/Workbook.php
index b50fa0ff1..8b0684375 100644
--- a/Classes/PHPExcel/Writer/Excel5/Workbook.php
+++ b/Classes/PHPExcel/Writer/Excel5/Workbook.php
@@ -1,8 +1,9 @@
index in workbook
- *
- * @var array
- */
- private $_addedFonts = array();
-
- /**
- * Shared number formats
- *
- * @var array
- */
- private $_numberFormats = array();
-
- /**
- * Added number formats. Maps from numberFormat's hash => index in workbook
- *
- * @var array
- */
- private $_addedNumberFormats = array();
-
- /**
- * Sizes of the binary worksheet streams
- *
- * @var array
- */
- private $_worksheetSizes = array();
-
- /**
- * Offsets of the binary worksheet streams relative to the start of the global workbook stream
- *
- * @var array
- */
- private $_worksheetOffsets = array();
-
- /**
- * Total number of shared strings in workbook
- *
- * @var int
- */
- private $_str_total;
-
- /**
- * Number of unique shared strings in workbook
- *
- * @var int
- */
- private $_str_unique;
-
- /**
- * Array of unique shared strings in workbook
- *
- * @var array
- */
- private $_str_table;
-
- /**
- * Color cache
- */
- private $_colors;
-
- /**
- * Escher object corresponding to MSODRAWINGGROUP
- *
- * @var PHPExcel_Shared_Escher
- */
- private $_escher;
-
-
- /**
- * Class constructor
- *
- * @param PHPExcel $phpExcel The Workbook
- * @param int &$str_total Total number of strings
- * @param int &$str_unique Total number of unique strings
- * @param array &$str_table String Table
- * @param array &$colors Colour Table
- * @param mixed $parser The formula parser created for the Workbook
- */
- public function __construct(PHPExcel $phpExcel = null,
- &$str_total, &$str_unique, &$str_table, &$colors,
- $parser )
- {
- // It needs to call its parent's constructor explicitly
- parent::__construct();
-
- $this->_parser = $parser;
- $this->_biffsize = 0;
- $this->_palette = array();
- $this->_country_code = -1;
-
- $this->_str_total = &$str_total;
- $this->_str_unique = &$str_unique;
- $this->_str_table = &$str_table;
- $this->_colors = &$colors;
- $this->_setPaletteXl97();
-
- $this->_phpExcel = $phpExcel;
-
- // set BIFFwriter limit for CONTINUE records
- // $this->_limit = 8224;
- $this->_codepage = 0x04B0;
-
- // Add empty sheets and Build color cache
- $countSheets = $phpExcel->getSheetCount();
- for ($i = 0; $i < $countSheets; ++$i) {
- $phpSheet = $phpExcel->getSheet($i);
-
- $this->_parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser
-
- $supbook_index = 0x00;
- $ref = pack('vvv', $supbook_index, $i, $i);
- $this->_parser->_references[] = $ref; // Register reference with parser
-
- // Sheet tab colors?
- if ($phpSheet->isTabColorSet()) {
- $this->_addColor($phpSheet->getTabColor()->getRGB());
- }
- }
-
- }
-
- /**
- * Add a new XF writer
- *
- * @param PHPExcel_Style
- * @param boolean Is it a style XF?
- * @return int Index to XF record
- */
- public function addXfWriter($style, $isStyleXf = false)
- {
- $xfWriter = new PHPExcel_Writer_Excel5_Xf($style);
- $xfWriter->setIsStyleXf($isStyleXf);
-
- // Add the font if not already added
- $fontIndex = $this->_addFont($style->getFont());
-
- // Assign the font index to the xf record
- $xfWriter->setFontIndex($fontIndex);
-
- // Background colors, best to treat these after the font so black will come after white in custom palette
- $xfWriter->setFgColor($this->_addColor($style->getFill()->getStartColor()->getRGB()));
- $xfWriter->setBgColor($this->_addColor($style->getFill()->getEndColor()->getRGB()));
- $xfWriter->setBottomColor($this->_addColor($style->getBorders()->getBottom()->getColor()->getRGB()));
- $xfWriter->setTopColor($this->_addColor($style->getBorders()->getTop()->getColor()->getRGB()));
- $xfWriter->setRightColor($this->_addColor($style->getBorders()->getRight()->getColor()->getRGB()));
- $xfWriter->setLeftColor($this->_addColor($style->getBorders()->getLeft()->getColor()->getRGB()));
- $xfWriter->setDiagColor($this->_addColor($style->getBorders()->getDiagonal()->getColor()->getRGB()));
-
- // Add the number format if it is not a built-in one and not already added
- if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
- $numberFormatHashCode = $style->getNumberFormat()->getHashCode();
-
- if (isset($this->_addedNumberFormats[$numberFormatHashCode])) {
- $numberFormatIndex = $this->_addedNumberFormats[$numberFormatHashCode];
- } else {
- $numberFormatIndex = 164 + count($this->_numberFormats);
- $this->_numberFormats[$numberFormatIndex] = $style->getNumberFormat();
- $this->_addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex;
- }
- } else {
- $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode();
- }
-
- // Assign the number format index to xf record
- $xfWriter->setNumberFormatIndex($numberFormatIndex);
-
- $this->_xfWriters[] = $xfWriter;
-
- $xfIndex = count($this->_xfWriters) - 1;
- return $xfIndex;
- }
-
- /**
- * Add a font to added fonts
- *
- * @param PHPExcel_Style_Font $font
- * @return int Index to FONT record
- */
- public function _addFont(PHPExcel_Style_Font $font)
- {
- $fontHashCode = $font->getHashCode();
- if(isset($this->_addedFonts[$fontHashCode])){
- $fontIndex = $this->_addedFonts[$fontHashCode];
- } else {
- $countFonts = count($this->_fontWriters);
- $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1;
-
- $fontWriter = new PHPExcel_Writer_Excel5_Font($font);
- $fontWriter->setColorIndex($this->_addColor($font->getColor()->getRGB()));
- $this->_fontWriters[] = $fontWriter;
-
- $this->_addedFonts[$fontHashCode] = $fontIndex;
- }
- return $fontIndex;
- }
-
- /**
- * Alter color palette adding a custom color
- *
- * @param string $rgb E.g. 'FF00AA'
- * @return int Color index
- */
- private function _addColor($rgb) {
- if (!isset($this->_colors[$rgb])) {
- if (count($this->_colors) < 57) {
- // then we add a custom color altering the palette
- $colorIndex = 8 + count($this->_colors);
- $this->_palette[$colorIndex] =
- array(
- hexdec(substr($rgb, 0, 2)),
- hexdec(substr($rgb, 2, 2)),
- hexdec(substr($rgb, 4)),
- 0
- );
- $this->_colors[$rgb] = $colorIndex;
- } else {
- // no room for more custom colors, just map to black
- $colorIndex = 0;
- }
- } else {
- // fetch already added custom color
- $colorIndex = $this->_colors[$rgb];
- }
-
- return $colorIndex;
- }
-
- /**
- * Sets the colour palette to the Excel 97+ default.
- *
- * @access private
- */
- function _setPaletteXl97()
- {
- $this->_palette = array(
- 0x08 => array(0x00, 0x00, 0x00, 0x00),
- 0x09 => array(0xff, 0xff, 0xff, 0x00),
- 0x0A => array(0xff, 0x00, 0x00, 0x00),
- 0x0B => array(0x00, 0xff, 0x00, 0x00),
- 0x0C => array(0x00, 0x00, 0xff, 0x00),
- 0x0D => array(0xff, 0xff, 0x00, 0x00),
- 0x0E => array(0xff, 0x00, 0xff, 0x00),
- 0x0F => array(0x00, 0xff, 0xff, 0x00),
- 0x10 => array(0x80, 0x00, 0x00, 0x00),
- 0x11 => array(0x00, 0x80, 0x00, 0x00),
- 0x12 => array(0x00, 0x00, 0x80, 0x00),
- 0x13 => array(0x80, 0x80, 0x00, 0x00),
- 0x14 => array(0x80, 0x00, 0x80, 0x00),
- 0x15 => array(0x00, 0x80, 0x80, 0x00),
- 0x16 => array(0xc0, 0xc0, 0xc0, 0x00),
- 0x17 => array(0x80, 0x80, 0x80, 0x00),
- 0x18 => array(0x99, 0x99, 0xff, 0x00),
- 0x19 => array(0x99, 0x33, 0x66, 0x00),
- 0x1A => array(0xff, 0xff, 0xcc, 0x00),
- 0x1B => array(0xcc, 0xff, 0xff, 0x00),
- 0x1C => array(0x66, 0x00, 0x66, 0x00),
- 0x1D => array(0xff, 0x80, 0x80, 0x00),
- 0x1E => array(0x00, 0x66, 0xcc, 0x00),
- 0x1F => array(0xcc, 0xcc, 0xff, 0x00),
- 0x20 => array(0x00, 0x00, 0x80, 0x00),
- 0x21 => array(0xff, 0x00, 0xff, 0x00),
- 0x22 => array(0xff, 0xff, 0x00, 0x00),
- 0x23 => array(0x00, 0xff, 0xff, 0x00),
- 0x24 => array(0x80, 0x00, 0x80, 0x00),
- 0x25 => array(0x80, 0x00, 0x00, 0x00),
- 0x26 => array(0x00, 0x80, 0x80, 0x00),
- 0x27 => array(0x00, 0x00, 0xff, 0x00),
- 0x28 => array(0x00, 0xcc, 0xff, 0x00),
- 0x29 => array(0xcc, 0xff, 0xff, 0x00),
- 0x2A => array(0xcc, 0xff, 0xcc, 0x00),
- 0x2B => array(0xff, 0xff, 0x99, 0x00),
- 0x2C => array(0x99, 0xcc, 0xff, 0x00),
- 0x2D => array(0xff, 0x99, 0xcc, 0x00),
- 0x2E => array(0xcc, 0x99, 0xff, 0x00),
- 0x2F => array(0xff, 0xcc, 0x99, 0x00),
- 0x30 => array(0x33, 0x66, 0xff, 0x00),
- 0x31 => array(0x33, 0xcc, 0xcc, 0x00),
- 0x32 => array(0x99, 0xcc, 0x00, 0x00),
- 0x33 => array(0xff, 0xcc, 0x00, 0x00),
- 0x34 => array(0xff, 0x99, 0x00, 0x00),
- 0x35 => array(0xff, 0x66, 0x00, 0x00),
- 0x36 => array(0x66, 0x66, 0x99, 0x00),
- 0x37 => array(0x96, 0x96, 0x96, 0x00),
- 0x38 => array(0x00, 0x33, 0x66, 0x00),
- 0x39 => array(0x33, 0x99, 0x66, 0x00),
- 0x3A => array(0x00, 0x33, 0x00, 0x00),
- 0x3B => array(0x33, 0x33, 0x00, 0x00),
- 0x3C => array(0x99, 0x33, 0x00, 0x00),
- 0x3D => array(0x99, 0x33, 0x66, 0x00),
- 0x3E => array(0x33, 0x33, 0x99, 0x00),
- 0x3F => array(0x33, 0x33, 0x33, 0x00),
- );
- }
-
- /**
- * Assemble worksheets into a workbook and send the BIFF data to an OLE
- * storage.
- *
- * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams
- * @return string Binary data for workbook stream
- */
- public function writeWorkbook($pWorksheetSizes = null)
- {
- $this->_worksheetSizes = $pWorksheetSizes;
-
- // Calculate the number of selected worksheet tabs and call the finalization
- // methods for each worksheet
- $total_worksheets = $this->_phpExcel->getSheetCount();
-
- // Add part 1 of the Workbook globals, what goes before the SHEET records
- $this->_storeBof(0x0005);
- $this->_writeCodepage();
- $this->_writeWindow1();
-
- $this->_writeDatemode();
- $this->_writeAllFonts();
- $this->_writeAllNumFormats();
- $this->_writeAllXfs();
- $this->_writeAllStyles();
- $this->_writePalette();
-
- // Prepare part 3 of the workbook global stream, what goes after the SHEET records
- $part3 = '';
- if ($this->_country_code != -1) {
- $part3 .= $this->_writeCountry();
- }
- $part3 .= $this->_writeRecalcId();
-
- $part3 .= $this->_writeSupbookInternal();
- /* TODO: store external SUPBOOK records and XCT and CRN records
- in case of external references for BIFF8 */
- $part3 .= $this->_writeExternsheetBiff8();
- $part3 .= $this->_writeAllDefinedNamesBiff8();
- $part3 .= $this->_writeMsoDrawingGroup();
- $part3 .= $this->_writeSharedStringsTable();
-
- $part3 .= $this->writeEof();
-
- // Add part 2 of the Workbook globals, the SHEET records
- $this->_calcSheetOffsets();
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $this->_writeBoundsheet($this->_phpExcel->getSheet($i), $this->_worksheetOffsets[$i]);
- }
-
- // Add part 3 of the Workbook globals
- $this->_data .= $part3;
-
- return $this->_data;
- }
-
- /**
- * Calculate offsets for Worksheet BOF records.
- *
- * @access private
- */
- function _calcSheetOffsets()
- {
- $boundsheet_length = 10; // fixed length for a BOUNDSHEET record
-
- // size of Workbook globals part 1 + 3
- $offset = $this->_datasize;
-
- // add size of Workbook globals part 2, the length of the SHEET records
- $total_worksheets = count($this->_phpExcel->getAllSheets());
- foreach ($this->_phpExcel->getWorksheetIterator() as $sheet) {
- $offset += $boundsheet_length + strlen(PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheet->getTitle()));
- }
-
- // add the sizes of each of the Sheet substreams, respectively
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $this->_worksheetOffsets[$i] = $offset;
- $offset += $this->_worksheetSizes[$i];
- }
- $this->_biffsize = $offset;
- }
-
- /**
- * Store the Excel FONT records.
- */
- private function _writeAllFonts()
- {
- foreach ($this->_fontWriters as $fontWriter) {
- $this->_append($fontWriter->writeFont());
- }
- }
-
- /**
- * Store user defined numerical formats i.e. FORMAT records
- */
- private function _writeAllNumFormats()
- {
- foreach ($this->_numberFormats as $numberFormatIndex => $numberFormat) {
- $this->_writeNumFormat($numberFormat->getFormatCode(), $numberFormatIndex);
- }
- }
-
- /**
- * Write all XF records.
- */
- private function _writeAllXfs()
- {
- foreach ($this->_xfWriters as $xfWriter) {
- $this->_append($xfWriter->writeXf());
- }
- }
-
- /**
- * Write all STYLE records.
- */
- private function _writeAllStyles()
- {
- $this->_writeStyle();
- }
-
- /**
- * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
- * the NAME records.
- */
- private function _writeExterns()
- {
- $countSheets = $this->_phpExcel->getSheetCount();
- // Create EXTERNCOUNT with number of worksheets
- $this->_writeExterncount($countSheets);
-
- // Create EXTERNSHEET for each worksheet
- for ($i = 0; $i < $countSheets; ++$i) {
- $this->_writeExternsheet($this->_phpExcel->getSheet($i)->getTitle());
- }
- }
-
- /**
- * Write the NAME record to define the print area and the repeat rows and cols.
- */
- private function _writeNames()
- {
- // total number of sheets
- $total_worksheets = $this->_phpExcel->getSheetCount();
-
- // Create the print area NAME records
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
- // Write a Name record if the print area has been defined
- if ($sheetSetup->isPrintAreaSet()) {
- // Print area
- $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea());
- $printArea = $printArea[0];
- $printArea[0] = PHPExcel_Cell::coordinateFromString($printArea[0]);
- $printArea[1] = PHPExcel_Cell::coordinateFromString($printArea[1]);
-
- $print_rowmin = $printArea[0][1] - 1;
- $print_rowmax = $printArea[1][1] - 1;
- $print_colmin = PHPExcel_Cell::columnIndexFromString($printArea[0][0]) - 1;
- $print_colmax = PHPExcel_Cell::columnIndexFromString($printArea[1][0]) - 1;
-
- $this->_writeNameShort(
- $i, // sheet index
- 0x06, // NAME type
- $print_rowmin,
- $print_rowmax,
- $print_colmin,
- $print_colmax
- );
- }
- }
-
- // Create the print title NAME records
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
-
- // simultaneous repeatColumns repeatRows
- if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
-
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
-
- $this->_writeNameLong(
- $i, // sheet index
- 0x07, // NAME type
- $rowmin,
- $rowmax,
- $colmin,
- $colmax
- );
-
- // (exclusive) either repeatColumns or repeatRows
- } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
-
- // Columns to repeat
- if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
- } else {
- $colmin = 0;
- $colmax = 255;
- }
-
- // Rows to repeat
- if ($sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
- } else {
- $rowmin = 0;
- $rowmax = 65535;
- }
-
- $this->_writeNameShort(
- $i, // sheet index
- 0x07, // NAME type
- $rowmin,
- $rowmax,
- $colmin,
- $colmax
- );
- }
- }
- }
-
- /**
- * Writes all the DEFINEDNAME records (BIFF8).
- * So far this is only used for repeating rows/columns (print titles) and print areas
- */
- private function _writeAllDefinedNamesBiff8()
- {
- $chunk = '';
-
- // Named ranges
- if (count($this->_phpExcel->getNamedRanges()) > 0) {
- // Loop named ranges
- $namedRanges = $this->_phpExcel->getNamedRanges();
- foreach ($namedRanges as $namedRange) {
-
- // Create absolute coordinate
- $range = PHPExcel_Cell::splitRange($namedRange->getRange());
- for ($i = 0; $i < count($range); $i++) {
- $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteCoordinate($range[$i][0]);
- if (isset($range[$i][1])) {
- $range[$i][1] = PHPExcel_Cell::absoluteCoordinate($range[$i][1]);
- }
- }
- $range = PHPExcel_Cell::buildRange($range); // e.g. Sheet1!$A$1:$B$2
-
- // parse formula
- try {
- $error = $this->_parser->parse($range);
- $formulaData = $this->_parser->toReversePolish();
-
- // make sure tRef3d is of type tRef3dR (0x3A)
- if (isset($formulaData{0}) and ($formulaData{0} == "\x7A" or $formulaData{0} == "\x5A")) {
- $formulaData = "\x3A" . substr($formulaData, 1);
- }
-
- if ($namedRange->getLocalOnly()) {
- // local scope
- $scope = $this->_phpExcel->getIndex($namedRange->getScope()) + 1;
- } else {
- // global scope
- $scope = 0;
- }
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false));
-
- } catch(PHPExcel_Exception $e) {
- // do nothing
- }
- }
- }
-
- // total number of sheets
- $total_worksheets = $this->_phpExcel->getSheetCount();
-
- // write the print titles (repeating rows, columns), if any
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
- // simultaneous repeatColumns repeatRows
- if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
-
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
-
- // construct formula data manually
- $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc
- $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d
- $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d
- $formulaData .= pack('C', 0x10); // tList
-
- // store the DEFINEDNAME record
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
-
- // (exclusive) either repeatColumns or repeatRows
- } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
-
- // Columns to repeat
- if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
- $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
- $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
- $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
- } else {
- $colmin = 0;
- $colmax = 255;
- }
- // Rows to repeat
- if ($sheetSetup->isRowsToRepeatAtTopSet()) {
- $repeat = $sheetSetup->getRowsToRepeatAtTop();
- $rowmin = $repeat[0] - 1;
- $rowmax = $repeat[1] - 1;
- } else {
- $rowmin = 0;
- $rowmax = 65535;
- }
-
- // construct formula data manually because parser does not recognize absolute 3d cell references
- $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax);
-
- // store the DEFINEDNAME record
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
- }
- }
-
- // write the print areas, if any
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup();
- if ($sheetSetup->isPrintAreaSet()) {
- // Print area, e.g. A3:J6,H1:X20
- $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea());
- $countPrintArea = count($printArea);
-
- $formulaData = '';
- for ($j = 0; $j < $countPrintArea; ++$j) {
- $printAreaRect = $printArea[$j]; // e.g. A3:J6
- $printAreaRect[0] = PHPExcel_Cell::coordinateFromString($printAreaRect[0]);
- $printAreaRect[1] = PHPExcel_Cell::coordinateFromString($printAreaRect[1]);
-
- $print_rowmin = $printAreaRect[0][1] - 1;
- $print_rowmax = $printAreaRect[1][1] - 1;
- $print_colmin = PHPExcel_Cell::columnIndexFromString($printAreaRect[0][0]) - 1;
- $print_colmax = PHPExcel_Cell::columnIndexFromString($printAreaRect[1][0]) - 1;
-
- // construct formula data manually because parser does not recognize absolute 3d cell references
- $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax);
-
- if ($j > 0) {
- $formulaData .= pack('C', 0x10); // list operator token ','
- }
- }
-
- // store the DEFINEDNAME record
- $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true));
- }
- }
-
- // write autofilters, if any
- for ($i = 0; $i < $total_worksheets; ++$i) {
- $sheetAutoFilter = $this->_phpExcel->getSheet($i)->getAutoFilter();
- $autoFilterRange = $sheetAutoFilter->getRange();
- if(!empty($autoFilterRange)) {
- $rangeBounds = PHPExcel_Cell::rangeBoundaries($autoFilterRange);
-
- //Autofilter built in name
- $name = pack('C', 0x0D);
-
- $chunk .= $this->writeData($this->_writeShortNameBiff8($name, $i + 1, $rangeBounds, true));
- }
- }
-
- return $chunk;
- }
-
- /**
- * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data
- *
- * @param string $name The name in UTF-8
- * @param string $formulaData The binary formula data
- * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
- * @param boolean $isBuiltIn Built-in name?
- * @return string Complete binary record data
- */
- private function _writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false)
- {
- $record = 0x0018;
-
- // option flags
- $options = $isBuiltIn ? 0x20 : 0x00;
-
- // length of the name, character count
- $nlen = PHPExcel_Shared_String::CountCharacters($name);
-
- // name with stripped length field
- $name = substr(PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($name), 2);
-
- // size of the formula (in bytes)
- $sz = strlen($formulaData);
-
- // combine the parts
- $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0)
- . $name . $formulaData;
- $length = strlen($data);
-
- $header = pack('vv', $record, $length);
-
- return $header . $data;
- }
-
- /**
- * Write a short NAME record
- *
- * @param string $name
- * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
- * @param int[][] $range rangeboundaries
- * @param bool $isHidden
- * @return string Complete binary record data
- * */
- private function _writeShortNameBiff8($name, $sheetIndex = 0, $rangeBounds, $isHidden = false){
- $record = 0x0018;
-
- // option flags
- $options = ($isHidden ? 0x21 : 0x00);
-
- $extra = pack('Cvvvvv',
- 0x3B,
- $sheetIndex - 1,
- $rangeBounds[0][1] - 1,
- $rangeBounds[1][1] - 1,
- $rangeBounds[0][0] - 1,
- $rangeBounds[1][0] - 1);
-
- // size of the formula (in bytes)
- $sz = strlen($extra);
-
- // combine the parts
- $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0)
- . $name . $extra;
- $length = strlen($data);
-
- $header = pack('vv', $record, $length);
-
- return $header . $data;
- }
-
- /**
- * Stores the CODEPAGE biff record.
- */
- private function _writeCodepage()
- {
- $record = 0x0042; // Record identifier
- $length = 0x0002; // Number of bytes to follow
- $cv = $this->_codepage; // The code page
-
- $header = pack('vv', $record, $length);
- $data = pack('v', $cv);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write Excel BIFF WINDOW1 record.
- */
- private function _writeWindow1()
- {
- $record = 0x003D; // Record identifier
- $length = 0x0012; // Number of bytes to follow
-
- $xWn = 0x0000; // Horizontal position of window
- $yWn = 0x0000; // Vertical position of window
- $dxWn = 0x25BC; // Width of window
- $dyWn = 0x1572; // Height of window
-
- $grbit = 0x0038; // Option flags
-
- // not supported by PHPExcel, so there is only one selected sheet, the active
- $ctabsel = 1; // Number of workbook tabs selected
-
- $wTabRatio = 0x0258; // Tab to scrollbar ratio
-
- // not supported by PHPExcel, set to 0
- $itabFirst = 0; // 1st displayed worksheet
- $itabCur = $this->_phpExcel->getActiveSheetIndex(); // Active worksheet
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn,
- $grbit,
- $itabCur, $itabFirst,
- $ctabsel, $wTabRatio);
- $this->_append($header . $data);
- }
-
- /**
- * Writes Excel BIFF BOUNDSHEET record.
- *
- * @param PHPExcel_Worksheet $sheet Worksheet name
- * @param integer $offset Location of worksheet BOF
- */
- private function _writeBoundsheet($sheet, $offset)
- {
- $sheetname = $sheet->getTitle();
- $record = 0x0085; // Record identifier
-
- // sheet state
- switch ($sheet->getSheetState()) {
- case PHPExcel_Worksheet::SHEETSTATE_VISIBLE: $ss = 0x00; break;
- case PHPExcel_Worksheet::SHEETSTATE_HIDDEN: $ss = 0x01; break;
- case PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN: $ss = 0x02; break;
- default: $ss = 0x00; break;
- }
-
- // sheet type
- $st = 0x00;
-
- $grbit = 0x0000; // Visibility and sheet type
-
- $data = pack("VCC", $offset, $ss, $st);
- $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheetname);
-
- $length = strlen($data);
- $header = pack("vv", $record, $length);
- $this->_append($header . $data);
- }
-
- /**
- * Write Internal SUPBOOK record
- */
- private function _writeSupbookInternal()
- {
- $record = 0x01AE; // Record identifier
- $length = 0x0004; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vv", $this->_phpExcel->getSheetCount(), 0x0401);
- return $this->writeData($header . $data);
- }
-
- /**
- * Writes the Excel BIFF EXTERNSHEET record. These references are used by
- * formulas.
- *
- */
- private function _writeExternsheetBiff8()
- {
- $total_references = count($this->_parser->_references);
- $record = 0x0017; // Record identifier
- $length = 2 + 6 * $total_references; // Number of bytes to follow
-
- $supbook_index = 0; // FIXME: only using internal SUPBOOK record
- $header = pack("vv", $record, $length);
- $data = pack('v', $total_references);
- for ($i = 0; $i < $total_references; ++$i) {
- $data .= $this->_parser->_references[$i];
- }
- return $this->writeData($header . $data);
- }
-
- /**
- * Write Excel BIFF STYLE records.
- */
- private function _writeStyle()
- {
- $record = 0x0293; // Record identifier
- $length = 0x0004; // Bytes to follow
-
- $ixfe = 0x8000; // Index to cell style XF
- $BuiltIn = 0x00; // Built-in style
- $iLevel = 0xff; // Outline style level
-
- $header = pack("vv", $record, $length);
- $data = pack("vCC", $ixfe, $BuiltIn, $iLevel);
- $this->_append($header . $data);
- }
-
- /**
- * Writes Excel FORMAT record for non "built-in" numerical formats.
- *
- * @param string $format Custom format string
- * @param integer $ifmt Format index code
- */
- private function _writeNumFormat($format, $ifmt)
- {
- $record = 0x041E; // Record identifier
-
- $numberFormatString = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($format);
- $length = 2 + strlen($numberFormatString); // Number of bytes to follow
-
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $ifmt) . $numberFormatString;
- $this->_append($header . $data);
- }
-
- /**
- * Write DATEMODE record to indicate the date system in use (1904 or 1900).
- */
- private function _writeDatemode()
- {
- $record = 0x0022; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $f1904 = (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) ?
- 1 : 0; // Flag for 1904 date system
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $f1904);
- $this->_append($header . $data);
- }
-
- /**
- * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
- * references in the workbook.
- *
- * Excel only stores references to external sheets that are used in NAME.
- * The workbook NAME record is required to define the print area and the repeat
- * rows and columns.
- *
- * A similar method is used in Worksheet.php for a slightly different purpose.
- *
- * @param integer $cxals Number of external references
- */
- private function _writeExterncount($cxals)
- {
- $record = 0x0016; // Record identifier
- $length = 0x0002; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $cxals);
- $this->_append($header . $data);
- }
-
- /**
- * Writes the Excel BIFF EXTERNSHEET record. These references are used by
- * formulas. NAME record is required to define the print area and the repeat
- * rows and columns.
- *
- * A similar method is used in Worksheet.php for a slightly different purpose.
- *
- * @param string $sheetname Worksheet name
- */
- private function _writeExternsheet($sheetname)
- {
- $record = 0x0017; // Record identifier
- $length = 0x02 + strlen($sheetname); // Number of bytes to follow
-
- $cch = strlen($sheetname); // Length of sheet name
- $rgch = 0x03; // Filename encoding
-
- $header = pack("vv", $record, $length);
- $data = pack("CC", $cch, $rgch);
- $this->_append($header . $data . $sheetname);
- }
-
- /**
- * Store the NAME record in the short format that is used for storing the print
- * area, repeat rows only and repeat columns only.
- *
- * @param integer $index Sheet index
- * @param integer $type Built-in name type
- * @param integer $rowmin Start row
- * @param integer $rowmax End row
- * @param integer $colmin Start colum
- * @param integer $colmax End column
- */
- private function _writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax)
- {
- $record = 0x0018; // Record identifier
- $length = 0x0024; // Number of bytes to follow
-
- $grbit = 0x0020; // Option flags
- $chKey = 0x00; // Keyboard shortcut
- $cch = 0x01; // Length of text name
- $cce = 0x0015; // Length of text definition
- $ixals = $index + 1; // Sheet index
- $itab = $ixals; // Equal to ixals
- $cchCustMenu = 0x00; // Length of cust menu text
- $cchDescription = 0x00; // Length of description text
- $cchHelptopic = 0x00; // Length of help topic text
- $cchStatustext = 0x00; // Length of status bar text
- $rgch = $type; // Built-in name type
-
- $unknown03 = 0x3b;
- $unknown04 = 0xffff-$index;
- $unknown05 = 0x0000;
- $unknown06 = 0x0000;
- $unknown07 = 0x1087;
- $unknown08 = 0x8005;
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $grbit);
- $data .= pack("C", $chKey);
- $data .= pack("C", $cch);
- $data .= pack("v", $cce);
- $data .= pack("v", $ixals);
- $data .= pack("v", $itab);
- $data .= pack("C", $cchCustMenu);
- $data .= pack("C", $cchDescription);
- $data .= pack("C", $cchHelptopic);
- $data .= pack("C", $cchStatustext);
- $data .= pack("C", $rgch);
- $data .= pack("C", $unknown03);
- $data .= pack("v", $unknown04);
- $data .= pack("v", $unknown05);
- $data .= pack("v", $unknown06);
- $data .= pack("v", $unknown07);
- $data .= pack("v", $unknown08);
- $data .= pack("v", $index);
- $data .= pack("v", $index);
- $data .= pack("v", $rowmin);
- $data .= pack("v", $rowmax);
- $data .= pack("C", $colmin);
- $data .= pack("C", $colmax);
- $this->_append($header . $data);
- }
-
- /**
- * Store the NAME record in the long format that is used for storing the repeat
- * rows and columns when both are specified. This shares a lot of code with
- * _writeNameShort() but we use a separate method to keep the code clean.
- * Code abstraction for reuse can be carried too far, and I should know. ;-)
- *
- * @param integer $index Sheet index
- * @param integer $type Built-in name type
- * @param integer $rowmin Start row
- * @param integer $rowmax End row
- * @param integer $colmin Start colum
- * @param integer $colmax End column
- */
- private function _writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax)
- {
- $record = 0x0018; // Record identifier
- $length = 0x003d; // Number of bytes to follow
- $grbit = 0x0020; // Option flags
- $chKey = 0x00; // Keyboard shortcut
- $cch = 0x01; // Length of text name
- $cce = 0x002e; // Length of text definition
- $ixals = $index + 1; // Sheet index
- $itab = $ixals; // Equal to ixals
- $cchCustMenu = 0x00; // Length of cust menu text
- $cchDescription = 0x00; // Length of description text
- $cchHelptopic = 0x00; // Length of help topic text
- $cchStatustext = 0x00; // Length of status bar text
- $rgch = $type; // Built-in name type
-
- $unknown01 = 0x29;
- $unknown02 = 0x002b;
- $unknown03 = 0x3b;
- $unknown04 = 0xffff-$index;
- $unknown05 = 0x0000;
- $unknown06 = 0x0000;
- $unknown07 = 0x1087;
- $unknown08 = 0x8008;
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $grbit);
- $data .= pack("C", $chKey);
- $data .= pack("C", $cch);
- $data .= pack("v", $cce);
- $data .= pack("v", $ixals);
- $data .= pack("v", $itab);
- $data .= pack("C", $cchCustMenu);
- $data .= pack("C", $cchDescription);
- $data .= pack("C", $cchHelptopic);
- $data .= pack("C", $cchStatustext);
- $data .= pack("C", $rgch);
- $data .= pack("C", $unknown01);
- $data .= pack("v", $unknown02);
- // Column definition
- $data .= pack("C", $unknown03);
- $data .= pack("v", $unknown04);
- $data .= pack("v", $unknown05);
- $data .= pack("v", $unknown06);
- $data .= pack("v", $unknown07);
- $data .= pack("v", $unknown08);
- $data .= pack("v", $index);
- $data .= pack("v", $index);
- $data .= pack("v", 0x0000);
- $data .= pack("v", 0x3fff);
- $data .= pack("C", $colmin);
- $data .= pack("C", $colmax);
- // Row definition
- $data .= pack("C", $unknown03);
- $data .= pack("v", $unknown04);
- $data .= pack("v", $unknown05);
- $data .= pack("v", $unknown06);
- $data .= pack("v", $unknown07);
- $data .= pack("v", $unknown08);
- $data .= pack("v", $index);
- $data .= pack("v", $index);
- $data .= pack("v", $rowmin);
- $data .= pack("v", $rowmax);
- $data .= pack("C", 0x00);
- $data .= pack("C", 0xff);
- // End of data
- $data .= pack("C", 0x10);
- $this->_append($header . $data);
- }
-
- /**
- * Stores the COUNTRY record for localization
- *
- * @return string
- */
- private function _writeCountry()
- {
- $record = 0x008C; // Record identifier
- $length = 4; // Number of bytes to follow
-
- $header = pack('vv', $record, $length);
- /* using the same country code always for simplicity */
- $data = pack('vv', $this->_country_code, $this->_country_code);
- //$this->_append($header . $data);
- return $this->writeData($header . $data);
- }
-
- /**
- * Write the RECALCID record
- *
- * @return string
- */
- private function _writeRecalcId()
- {
- $record = 0x01C1; // Record identifier
- $length = 8; // Number of bytes to follow
-
- $header = pack('vv', $record, $length);
-
- // by inspection of real Excel files, MS Office Excel 2007 writes this
- $data = pack('VV', 0x000001C1, 0x00001E667);
-
- return $this->writeData($header . $data);
- }
-
- /**
- * Stores the PALETTE biff record.
- */
- private function _writePalette()
- {
- $aref = $this->_palette;
-
- $record = 0x0092; // Record identifier
- $length = 2 + 4 * count($aref); // Number of bytes to follow
- $ccv = count($aref); // Number of RGB values to follow
- $data = ''; // The RGB data
-
- // Pack the RGB data
- foreach ($aref as $color) {
- foreach ($color as $byte) {
- $data .= pack("C",$byte);
- }
- }
-
- $header = pack("vvv", $record, $length, $ccv);
- $this->_append($header . $data);
- }
-
- /**
- * Handling of the SST continue blocks is complicated by the need to include an
- * additional continuation byte depending on whether the string is split between
- * blocks or whether it starts at the beginning of the block. (There are also
- * additional complications that will arise later when/if Rich Strings are
- * supported).
- *
- * The Excel documentation says that the SST record should be followed by an
- * EXTSST record. The EXTSST record is a hash table that is used to optimise
- * access to SST. However, despite the documentation it doesn't seem to be
- * required so we will ignore it.
- *
- * @return string Binary data
- */
- private function _writeSharedStringsTable()
- {
- // maximum size of record data (excluding record header)
- $continue_limit = 8224;
-
- // initialize array of record data blocks
- $recordDatas = array();
-
- // start SST record data block with total number of strings, total number of unique strings
- $recordData = pack("VV", $this->_str_total, $this->_str_unique);
-
- // loop through all (unique) strings in shared strings table
- foreach (array_keys($this->_str_table) as $string) {
-
- // here $string is a BIFF8 encoded string
-
- // length = character count
- $headerinfo = unpack("vlength/Cencoding", $string);
-
- // currently, this is always 1 = uncompressed
- $encoding = $headerinfo["encoding"];
-
- // initialize finished writing current $string
- $finished = false;
-
- while ($finished === false) {
-
- // normally, there will be only one cycle, but if string cannot immediately be written as is
- // there will be need for more than one cylcle, if string longer than one record data block, there
- // may be need for even more cycles
-
- if (strlen($recordData) + strlen($string) <= $continue_limit) {
- // then we can write the string (or remainder of string) without any problems
- $recordData .= $string;
-
- if (strlen($recordData) + strlen($string) == $continue_limit) {
- // we close the record data block, and initialize a new one
- $recordDatas[] = $recordData;
- $recordData = '';
- }
-
- // we are finished writing this string
- $finished = true;
- } else {
- // special treatment writing the string (or remainder of the string)
- // If the string is very long it may need to be written in more than one CONTINUE record.
-
- // check how many bytes more there is room for in the current record
- $space_remaining = $continue_limit - strlen($recordData);
-
- // minimum space needed
- // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character
- // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character
- $min_space_needed = ($encoding == 1) ? 5 : 4;
-
- // We have two cases
- // 1. space remaining is less than minimum space needed
- // here we must waste the space remaining and move to next record data block
- // 2. space remaining is greater than or equal to minimum space needed
- // here we write as much as we can in the current block, then move to next record data block
-
- // 1. space remaining is less than minimum space needed
- if ($space_remaining < $min_space_needed) {
- // we close the block, store the block data
- $recordDatas[] = $recordData;
-
- // and start new record data block where we start writing the string
- $recordData = '';
-
- // 2. space remaining is greater than or equal to minimum space needed
- } else {
- // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below
- $effective_space_remaining = $space_remaining;
-
- // for uncompressed strings, sometimes effective space remaining is reduced by 1
- if ( $encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1 ) {
- --$effective_space_remaining;
- }
-
- // one block fininshed, store the block data
- $recordData .= substr($string, 0, $effective_space_remaining);
-
- $string = substr($string, $effective_space_remaining); // for next cycle in while loop
- $recordDatas[] = $recordData;
-
- // start new record data block with the repeated option flags
- $recordData = pack('C', $encoding);
- }
- }
- }
- }
-
- // Store the last record data block unless it is empty
- // if there was no need for any continue records, this will be the for SST record data block itself
- if (strlen($recordData) > 0) {
- $recordDatas[] = $recordData;
- }
-
- // combine into one chunk with all the blocks SST, CONTINUE,...
- $chunk = '';
- foreach ($recordDatas as $i => $recordData) {
- // first block should have the SST record header, remaing should have CONTINUE header
- $record = ($i == 0) ? 0x00FC : 0x003C;
-
- $header = pack("vv", $record, strlen($recordData));
- $data = $header . $recordData;
-
- $chunk .= $this->writeData($data);
- }
-
- return $chunk;
- }
-
- /**
- * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records.
- */
- private function _writeMsoDrawingGroup()
- {
- // write the Escher stream if necessary
- if (isset($this->_escher)) {
- $writer = new PHPExcel_Writer_Excel5_Escher($this->_escher);
- $data = $writer->close();
-
- $record = 0x00EB;
- $length = strlen($data);
- $header = pack("vv", $record, $length);
-
- return $this->writeData($header . $data);
-
- } else {
- return '';
- }
- }
-
- /**
- * Get Escher object
- *
- * @return PHPExcel_Shared_Escher
- */
- public function getEscher()
- {
- return $this->_escher;
- }
-
- /**
- * Set Escher object
- *
- * @param PHPExcel_Shared_Escher $pValue
- */
- public function setEscher(PHPExcel_Shared_Escher $pValue = null)
- {
- $this->_escher = $pValue;
- }
+ /**
+ * Formula parser
+ *
+ * @var PHPExcel_Writer_Excel5_Parser
+ */
+ private $parser;
+
+ /**
+ * The BIFF file size for the workbook.
+ * @var integer
+ * @see calcSheetOffsets()
+ */
+ private $biffSize;
+
+ /**
+ * XF Writers
+ * @var PHPExcel_Writer_Excel5_Xf[]
+ */
+ private $xfWriters = array();
+
+ /**
+ * Array containing the colour palette
+ * @var array
+ */
+ private $palette;
+
+ /**
+ * The codepage indicates the text encoding used for strings
+ * @var integer
+ */
+ private $codepage;
+
+ /**
+ * The country code used for localization
+ * @var integer
+ */
+ private $countryCode;
+
+ /**
+ * Workbook
+ * @var PHPExcel
+ */
+ private $phpExcel;
+
+ /**
+ * Fonts writers
+ *
+ * @var PHPExcel_Writer_Excel5_Font[]
+ */
+ private $fontWriters = array();
+
+ /**
+ * Added fonts. Maps from font's hash => index in workbook
+ *
+ * @var array
+ */
+ private $addedFonts = array();
+
+ /**
+ * Shared number formats
+ *
+ * @var array
+ */
+ private $numberFormats = array();
+
+ /**
+ * Added number formats. Maps from numberFormat's hash => index in workbook
+ *
+ * @var array
+ */
+ private $addedNumberFormats = array();
+
+ /**
+ * Sizes of the binary worksheet streams
+ *
+ * @var array
+ */
+ private $worksheetSizes = array();
+
+ /**
+ * Offsets of the binary worksheet streams relative to the start of the global workbook stream
+ *
+ * @var array
+ */
+ private $worksheetOffsets = array();
+
+ /**
+ * Total number of shared strings in workbook
+ *
+ * @var int
+ */
+ private $stringTotal;
+
+ /**
+ * Number of unique shared strings in workbook
+ *
+ * @var int
+ */
+ private $stringUnique;
+
+ /**
+ * Array of unique shared strings in workbook
+ *
+ * @var array
+ */
+ private $stringTable;
+
+ /**
+ * Color cache
+ */
+ private $colors;
+
+ /**
+ * Escher object corresponding to MSODRAWINGGROUP
+ *
+ * @var PHPExcel_Shared_Escher
+ */
+ private $escher;
+
+
+ /**
+ * Class constructor
+ *
+ * @param PHPExcel $phpExcel The Workbook
+ * @param int &$str_total Total number of strings
+ * @param int &$str_unique Total number of unique strings
+ * @param array &$str_table String Table
+ * @param array &$colors Colour Table
+ * @param mixed $parser The formula parser created for the Workbook
+ */
+ public function __construct(PHPExcel $phpExcel = null, &$str_total, &$str_unique, &$str_table, &$colors, $parser)
+ {
+ // It needs to call its parent's constructor explicitly
+ parent::__construct();
+
+ $this->parser = $parser;
+ $this->biffSize = 0;
+ $this->palette = array();
+ $this->countryCode = -1;
+
+ $this->stringTotal = &$str_total;
+ $this->stringUnique = &$str_unique;
+ $this->stringTable = &$str_table;
+ $this->colors = &$colors;
+ $this->setPaletteXl97();
+
+ $this->phpExcel = $phpExcel;
+
+ // set BIFFwriter limit for CONTINUE records
+ // $this->_limit = 8224;
+ $this->codepage = 0x04B0;
+
+ // Add empty sheets and Build color cache
+ $countSheets = $phpExcel->getSheetCount();
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $phpSheet = $phpExcel->getSheet($i);
+
+ $this->parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser
+
+ $supbook_index = 0x00;
+ $ref = pack('vvv', $supbook_index, $i, $i);
+ $this->parser->references[] = $ref; // Register reference with parser
+
+ // Sheet tab colors?
+ if ($phpSheet->isTabColorSet()) {
+ $this->addColor($phpSheet->getTabColor()->getRGB());
+ }
+ }
+
+ }
+
+ /**
+ * Add a new XF writer
+ *
+ * @param PHPExcel_Style
+ * @param boolean Is it a style XF?
+ * @return int Index to XF record
+ */
+ public function addXfWriter($style, $isStyleXf = false)
+ {
+ $xfWriter = new PHPExcel_Writer_Excel5_Xf($style);
+ $xfWriter->setIsStyleXf($isStyleXf);
+
+ // Add the font if not already added
+ $fontIndex = $this->addFont($style->getFont());
+
+ // Assign the font index to the xf record
+ $xfWriter->setFontIndex($fontIndex);
+
+ // Background colors, best to treat these after the font so black will come after white in custom palette
+ $xfWriter->setFgColor($this->addColor($style->getFill()->getStartColor()->getRGB()));
+ $xfWriter->setBgColor($this->addColor($style->getFill()->getEndColor()->getRGB()));
+ $xfWriter->setBottomColor($this->addColor($style->getBorders()->getBottom()->getColor()->getRGB()));
+ $xfWriter->setTopColor($this->addColor($style->getBorders()->getTop()->getColor()->getRGB()));
+ $xfWriter->setRightColor($this->addColor($style->getBorders()->getRight()->getColor()->getRGB()));
+ $xfWriter->setLeftColor($this->addColor($style->getBorders()->getLeft()->getColor()->getRGB()));
+ $xfWriter->setDiagColor($this->addColor($style->getBorders()->getDiagonal()->getColor()->getRGB()));
+
+ // Add the number format if it is not a built-in one and not already added
+ if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
+ $numberFormatHashCode = $style->getNumberFormat()->getHashCode();
+
+ if (isset($this->addedNumberFormats[$numberFormatHashCode])) {
+ $numberFormatIndex = $this->addedNumberFormats[$numberFormatHashCode];
+ } else {
+ $numberFormatIndex = 164 + count($this->numberFormats);
+ $this->numberFormats[$numberFormatIndex] = $style->getNumberFormat();
+ $this->addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex;
+ }
+ } else {
+ $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode();
+ }
+
+ // Assign the number format index to xf record
+ $xfWriter->setNumberFormatIndex($numberFormatIndex);
+
+ $this->xfWriters[] = $xfWriter;
+
+ $xfIndex = count($this->xfWriters) - 1;
+ return $xfIndex;
+ }
+
+ /**
+ * Add a font to added fonts
+ *
+ * @param PHPExcel_Style_Font $font
+ * @return int Index to FONT record
+ */
+ public function addFont(PHPExcel_Style_Font $font)
+ {
+ $fontHashCode = $font->getHashCode();
+ if (isset($this->addedFonts[$fontHashCode])) {
+ $fontIndex = $this->addedFonts[$fontHashCode];
+ } else {
+ $countFonts = count($this->fontWriters);
+ $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1;
+
+ $fontWriter = new PHPExcel_Writer_Excel5_Font($font);
+ $fontWriter->setColorIndex($this->addColor($font->getColor()->getRGB()));
+ $this->fontWriters[] = $fontWriter;
+
+ $this->addedFonts[$fontHashCode] = $fontIndex;
+ }
+ return $fontIndex;
+ }
+
+ /**
+ * Alter color palette adding a custom color
+ *
+ * @param string $rgb E.g. 'FF00AA'
+ * @return int Color index
+ */
+ private function addColor($rgb)
+ {
+ if (!isset($this->colors[$rgb])) {
+ if (count($this->colors) < 57) {
+ // then we add a custom color altering the palette
+ $colorIndex = 8 + count($this->colors);
+ $this->palette[$colorIndex] =
+ array(
+ hexdec(substr($rgb, 0, 2)),
+ hexdec(substr($rgb, 2, 2)),
+ hexdec(substr($rgb, 4)),
+ 0
+ );
+ $this->colors[$rgb] = $colorIndex;
+ } else {
+ // no room for more custom colors, just map to black
+ $colorIndex = 0;
+ }
+ } else {
+ // fetch already added custom color
+ $colorIndex = $this->colors[$rgb];
+ }
+
+ return $colorIndex;
+ }
+
+ /**
+ * Sets the colour palette to the Excel 97+ default.
+ *
+ * @access private
+ */
+ private function setPaletteXl97()
+ {
+ $this->palette = array(
+ 0x08 => array(0x00, 0x00, 0x00, 0x00),
+ 0x09 => array(0xff, 0xff, 0xff, 0x00),
+ 0x0A => array(0xff, 0x00, 0x00, 0x00),
+ 0x0B => array(0x00, 0xff, 0x00, 0x00),
+ 0x0C => array(0x00, 0x00, 0xff, 0x00),
+ 0x0D => array(0xff, 0xff, 0x00, 0x00),
+ 0x0E => array(0xff, 0x00, 0xff, 0x00),
+ 0x0F => array(0x00, 0xff, 0xff, 0x00),
+ 0x10 => array(0x80, 0x00, 0x00, 0x00),
+ 0x11 => array(0x00, 0x80, 0x00, 0x00),
+ 0x12 => array(0x00, 0x00, 0x80, 0x00),
+ 0x13 => array(0x80, 0x80, 0x00, 0x00),
+ 0x14 => array(0x80, 0x00, 0x80, 0x00),
+ 0x15 => array(0x00, 0x80, 0x80, 0x00),
+ 0x16 => array(0xc0, 0xc0, 0xc0, 0x00),
+ 0x17 => array(0x80, 0x80, 0x80, 0x00),
+ 0x18 => array(0x99, 0x99, 0xff, 0x00),
+ 0x19 => array(0x99, 0x33, 0x66, 0x00),
+ 0x1A => array(0xff, 0xff, 0xcc, 0x00),
+ 0x1B => array(0xcc, 0xff, 0xff, 0x00),
+ 0x1C => array(0x66, 0x00, 0x66, 0x00),
+ 0x1D => array(0xff, 0x80, 0x80, 0x00),
+ 0x1E => array(0x00, 0x66, 0xcc, 0x00),
+ 0x1F => array(0xcc, 0xcc, 0xff, 0x00),
+ 0x20 => array(0x00, 0x00, 0x80, 0x00),
+ 0x21 => array(0xff, 0x00, 0xff, 0x00),
+ 0x22 => array(0xff, 0xff, 0x00, 0x00),
+ 0x23 => array(0x00, 0xff, 0xff, 0x00),
+ 0x24 => array(0x80, 0x00, 0x80, 0x00),
+ 0x25 => array(0x80, 0x00, 0x00, 0x00),
+ 0x26 => array(0x00, 0x80, 0x80, 0x00),
+ 0x27 => array(0x00, 0x00, 0xff, 0x00),
+ 0x28 => array(0x00, 0xcc, 0xff, 0x00),
+ 0x29 => array(0xcc, 0xff, 0xff, 0x00),
+ 0x2A => array(0xcc, 0xff, 0xcc, 0x00),
+ 0x2B => array(0xff, 0xff, 0x99, 0x00),
+ 0x2C => array(0x99, 0xcc, 0xff, 0x00),
+ 0x2D => array(0xff, 0x99, 0xcc, 0x00),
+ 0x2E => array(0xcc, 0x99, 0xff, 0x00),
+ 0x2F => array(0xff, 0xcc, 0x99, 0x00),
+ 0x30 => array(0x33, 0x66, 0xff, 0x00),
+ 0x31 => array(0x33, 0xcc, 0xcc, 0x00),
+ 0x32 => array(0x99, 0xcc, 0x00, 0x00),
+ 0x33 => array(0xff, 0xcc, 0x00, 0x00),
+ 0x34 => array(0xff, 0x99, 0x00, 0x00),
+ 0x35 => array(0xff, 0x66, 0x00, 0x00),
+ 0x36 => array(0x66, 0x66, 0x99, 0x00),
+ 0x37 => array(0x96, 0x96, 0x96, 0x00),
+ 0x38 => array(0x00, 0x33, 0x66, 0x00),
+ 0x39 => array(0x33, 0x99, 0x66, 0x00),
+ 0x3A => array(0x00, 0x33, 0x00, 0x00),
+ 0x3B => array(0x33, 0x33, 0x00, 0x00),
+ 0x3C => array(0x99, 0x33, 0x00, 0x00),
+ 0x3D => array(0x99, 0x33, 0x66, 0x00),
+ 0x3E => array(0x33, 0x33, 0x99, 0x00),
+ 0x3F => array(0x33, 0x33, 0x33, 0x00),
+ );
+ }
+
+ /**
+ * Assemble worksheets into a workbook and send the BIFF data to an OLE
+ * storage.
+ *
+ * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams
+ * @return string Binary data for workbook stream
+ */
+ public function writeWorkbook($pWorksheetSizes = null)
+ {
+ $this->worksheetSizes = $pWorksheetSizes;
+
+ // Calculate the number of selected worksheet tabs and call the finalization
+ // methods for each worksheet
+ $total_worksheets = $this->phpExcel->getSheetCount();
+
+ // Add part 1 of the Workbook globals, what goes before the SHEET records
+ $this->storeBof(0x0005);
+ $this->writeCodepage();
+ $this->writeWindow1();
+
+ $this->writeDateMode();
+ $this->writeAllFonts();
+ $this->writeAllNumberFormats();
+ $this->writeAllXfs();
+ $this->writeAllStyles();
+ $this->writePalette();
+
+ // Prepare part 3 of the workbook global stream, what goes after the SHEET records
+ $part3 = '';
+ if ($this->countryCode != -1) {
+ $part3 .= $this->writeCountry();
+ }
+ $part3 .= $this->writeRecalcId();
+
+ $part3 .= $this->writeSupbookInternal();
+ /* TODO: store external SUPBOOK records and XCT and CRN records
+ in case of external references for BIFF8 */
+ $part3 .= $this->writeExternalsheetBiff8();
+ $part3 .= $this->writeAllDefinedNamesBiff8();
+ $part3 .= $this->writeMsoDrawingGroup();
+ $part3 .= $this->writeSharedStringsTable();
+
+ $part3 .= $this->writeEof();
+
+ // Add part 2 of the Workbook globals, the SHEET records
+ $this->calcSheetOffsets();
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $this->writeBoundSheet($this->phpExcel->getSheet($i), $this->worksheetOffsets[$i]);
+ }
+
+ // Add part 3 of the Workbook globals
+ $this->_data .= $part3;
+
+ return $this->_data;
+ }
+
+ /**
+ * Calculate offsets for Worksheet BOF records.
+ *
+ * @access private
+ */
+ private function calcSheetOffsets()
+ {
+ $boundsheet_length = 10; // fixed length for a BOUNDSHEET record
+
+ // size of Workbook globals part 1 + 3
+ $offset = $this->_datasize;
+
+ // add size of Workbook globals part 2, the length of the SHEET records
+ $total_worksheets = count($this->phpExcel->getAllSheets());
+ foreach ($this->phpExcel->getWorksheetIterator() as $sheet) {
+ $offset += $boundsheet_length + strlen(PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheet->getTitle()));
+ }
+
+ // add the sizes of each of the Sheet substreams, respectively
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $this->worksheetOffsets[$i] = $offset;
+ $offset += $this->worksheetSizes[$i];
+ }
+ $this->biffSize = $offset;
+ }
+
+ /**
+ * Store the Excel FONT records.
+ */
+ private function writeAllFonts()
+ {
+ foreach ($this->fontWriters as $fontWriter) {
+ $this->append($fontWriter->writeFont());
+ }
+ }
+
+ /**
+ * Store user defined numerical formats i.e. FORMAT records
+ */
+ private function writeAllNumberFormats()
+ {
+ foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) {
+ $this->writeNumberFormat($numberFormat->getFormatCode(), $numberFormatIndex);
+ }
+ }
+
+ /**
+ * Write all XF records.
+ */
+ private function writeAllXfs()
+ {
+ foreach ($this->xfWriters as $xfWriter) {
+ $this->append($xfWriter->writeXf());
+ }
+ }
+
+ /**
+ * Write all STYLE records.
+ */
+ private function writeAllStyles()
+ {
+ $this->writeStyle();
+ }
+
+ /**
+ * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
+ * the NAME records.
+ */
+ private function writeExternals()
+ {
+ $countSheets = $this->phpExcel->getSheetCount();
+ // Create EXTERNCOUNT with number of worksheets
+ $this->writeExternalCount($countSheets);
+
+ // Create EXTERNSHEET for each worksheet
+ for ($i = 0; $i < $countSheets; ++$i) {
+ $this->writeExternalSheet($this->phpExcel->getSheet($i)->getTitle());
+ }
+ }
+
+ /**
+ * Write the NAME record to define the print area and the repeat rows and cols.
+ */
+ private function writeNames()
+ {
+ // total number of sheets
+ $total_worksheets = $this->phpExcel->getSheetCount();
+
+ // Create the print area NAME records
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup();
+ // Write a Name record if the print area has been defined
+ if ($sheetSetup->isPrintAreaSet()) {
+ // Print area
+ $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea());
+ $printArea = $printArea[0];
+ $printArea[0] = PHPExcel_Cell::coordinateFromString($printArea[0]);
+ $printArea[1] = PHPExcel_Cell::coordinateFromString($printArea[1]);
+
+ $print_rowmin = $printArea[0][1] - 1;
+ $print_rowmax = $printArea[1][1] - 1;
+ $print_colmin = PHPExcel_Cell::columnIndexFromString($printArea[0][0]) - 1;
+ $print_colmax = PHPExcel_Cell::columnIndexFromString($printArea[1][0]) - 1;
+
+ $this->writeNameShort(
+ $i, // sheet index
+ 0x06, // NAME type
+ $print_rowmin,
+ $print_rowmax,
+ $print_colmin,
+ $print_colmax
+ );
+ }
+ }
+
+ // Create the print title NAME records
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup();
+
+ // simultaneous repeatColumns repeatRows
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
+
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+
+ $this->writeNameLong(
+ $i, // sheet index
+ 0x07, // NAME type
+ $rowmin,
+ $rowmax,
+ $colmin,
+ $colmax
+ );
+
+ // (exclusive) either repeatColumns or repeatRows
+ } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
+ // Columns to repeat
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
+ } else {
+ $colmin = 0;
+ $colmax = 255;
+ }
+
+ // Rows to repeat
+ if ($sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+ } else {
+ $rowmin = 0;
+ $rowmax = 65535;
+ }
+
+ $this->writeNameShort(
+ $i, // sheet index
+ 0x07, // NAME type
+ $rowmin,
+ $rowmax,
+ $colmin,
+ $colmax
+ );
+ }
+ }
+ }
+
+ /**
+ * Writes all the DEFINEDNAME records (BIFF8).
+ * So far this is only used for repeating rows/columns (print titles) and print areas
+ */
+ private function writeAllDefinedNamesBiff8()
+ {
+ $chunk = '';
+
+ // Named ranges
+ if (count($this->phpExcel->getNamedRanges()) > 0) {
+ // Loop named ranges
+ $namedRanges = $this->phpExcel->getNamedRanges();
+ foreach ($namedRanges as $namedRange) {
+ // Create absolute coordinate
+ $range = PHPExcel_Cell::splitRange($namedRange->getRange());
+ for ($i = 0; $i < count($range); $i++) {
+ $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteCoordinate($range[$i][0]);
+ if (isset($range[$i][1])) {
+ $range[$i][1] = PHPExcel_Cell::absoluteCoordinate($range[$i][1]);
+ }
+ }
+ $range = PHPExcel_Cell::buildRange($range); // e.g. Sheet1!$A$1:$B$2
+
+ // parse formula
+ try {
+ $error = $this->parser->parse($range);
+ $formulaData = $this->parser->toReversePolish();
+
+ // make sure tRef3d is of type tRef3dR (0x3A)
+ if (isset($formulaData{0}) and ($formulaData{0} == "\x7A" or $formulaData{0} == "\x5A")) {
+ $formulaData = "\x3A" . substr($formulaData, 1);
+ }
+
+ if ($namedRange->getLocalOnly()) {
+ // local scope
+ $scope = $this->phpExcel->getIndex($namedRange->getScope()) + 1;
+ } else {
+ // global scope
+ $scope = 0;
+ }
+ $chunk .= $this->writeData($this->writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false));
+
+ } catch (PHPExcel_Exception $e) {
+ // do nothing
+ }
+ }
+ }
+
+ // total number of sheets
+ $total_worksheets = $this->phpExcel->getSheetCount();
+
+ // write the print titles (repeating rows, columns), if any
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup();
+ // simultaneous repeatColumns repeatRows
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
+
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+
+ // construct formula data manually
+ $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc
+ $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d
+ $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d
+ $formulaData .= pack('C', 0x10); // tList
+
+ // store the DEFINEDNAME record
+ $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
+
+ // (exclusive) either repeatColumns or repeatRows
+ } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
+ // Columns to repeat
+ if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
+ $repeat = $sheetSetup->getColumnsToRepeatAtLeft();
+ $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1;
+ $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1;
+ } else {
+ $colmin = 0;
+ $colmax = 255;
+ }
+ // Rows to repeat
+ if ($sheetSetup->isRowsToRepeatAtTopSet()) {
+ $repeat = $sheetSetup->getRowsToRepeatAtTop();
+ $rowmin = $repeat[0] - 1;
+ $rowmax = $repeat[1] - 1;
+ } else {
+ $rowmin = 0;
+ $rowmax = 65535;
+ }
+
+ // construct formula data manually because parser does not recognize absolute 3d cell references
+ $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax);
+
+ // store the DEFINEDNAME record
+ $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
+ }
+ }
+
+ // write the print areas, if any
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup();
+ if ($sheetSetup->isPrintAreaSet()) {
+ // Print area, e.g. A3:J6,H1:X20
+ $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea());
+ $countPrintArea = count($printArea);
+
+ $formulaData = '';
+ for ($j = 0; $j < $countPrintArea; ++$j) {
+ $printAreaRect = $printArea[$j]; // e.g. A3:J6
+ $printAreaRect[0] = PHPExcel_Cell::coordinateFromString($printAreaRect[0]);
+ $printAreaRect[1] = PHPExcel_Cell::coordinateFromString($printAreaRect[1]);
+
+ $print_rowmin = $printAreaRect[0][1] - 1;
+ $print_rowmax = $printAreaRect[1][1] - 1;
+ $print_colmin = PHPExcel_Cell::columnIndexFromString($printAreaRect[0][0]) - 1;
+ $print_colmax = PHPExcel_Cell::columnIndexFromString($printAreaRect[1][0]) - 1;
+
+ // construct formula data manually because parser does not recognize absolute 3d cell references
+ $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax);
+
+ if ($j > 0) {
+ $formulaData .= pack('C', 0x10); // list operator token ','
+ }
+ }
+
+ // store the DEFINEDNAME record
+ $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true));
+ }
+ }
+
+ // write autofilters, if any
+ for ($i = 0; $i < $total_worksheets; ++$i) {
+ $sheetAutoFilter = $this->phpExcel->getSheet($i)->getAutoFilter();
+ $autoFilterRange = $sheetAutoFilter->getRange();
+ if (!empty($autoFilterRange)) {
+ $rangeBounds = PHPExcel_Cell::rangeBoundaries($autoFilterRange);
+
+ //Autofilter built in name
+ $name = pack('C', 0x0D);
+
+ $chunk .= $this->writeData($this->writeShortNameBiff8($name, $i + 1, $rangeBounds, true));
+ }
+ }
+
+ return $chunk;
+ }
+
+ /**
+ * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data
+ *
+ * @param string $name The name in UTF-8
+ * @param string $formulaData The binary formula data
+ * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
+ * @param boolean $isBuiltIn Built-in name?
+ * @return string Complete binary record data
+ */
+ private function writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false)
+ {
+ $record = 0x0018;
+
+ // option flags
+ $options = $isBuiltIn ? 0x20 : 0x00;
+
+ // length of the name, character count
+ $nlen = PHPExcel_Shared_String::CountCharacters($name);
+
+ // name with stripped length field
+ $name = substr(PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($name), 2);
+
+ // size of the formula (in bytes)
+ $sz = strlen($formulaData);
+
+ // combine the parts
+ $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0)
+ . $name . $formulaData;
+ $length = strlen($data);
+
+ $header = pack('vv', $record, $length);
+
+ return $header . $data;
+ }
+
+ /**
+ * Write a short NAME record
+ *
+ * @param string $name
+ * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global
+ * @param integer[][] $rangeBounds range boundaries
+ * @param boolean $isHidden
+ * @return string Complete binary record data
+ * */
+ private function writeShortNameBiff8($name, $sheetIndex = 0, $rangeBounds, $isHidden = false)
+ {
+ $record = 0x0018;
+
+ // option flags
+ $options = ($isHidden ? 0x21 : 0x00);
+
+ $extra = pack(
+ 'Cvvvvv',
+ 0x3B,
+ $sheetIndex - 1,
+ $rangeBounds[0][1] - 1,
+ $rangeBounds[1][1] - 1,
+ $rangeBounds[0][0] - 1,
+ $rangeBounds[1][0] - 1
+ );
+
+ // size of the formula (in bytes)
+ $sz = strlen($extra);
+
+ // combine the parts
+ $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0)
+ . $name . $extra;
+ $length = strlen($data);
+
+ $header = pack('vv', $record, $length);
+
+ return $header . $data;
+ }
+
+ /**
+ * Stores the CODEPAGE biff record.
+ */
+ private function writeCodepage()
+ {
+ $record = 0x0042; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+ $cv = $this->codepage; // The code page
+
+ $header = pack('vv', $record, $length);
+ $data = pack('v', $cv);
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write Excel BIFF WINDOW1 record.
+ */
+ private function writeWindow1()
+ {
+ $record = 0x003D; // Record identifier
+ $length = 0x0012; // Number of bytes to follow
+
+ $xWn = 0x0000; // Horizontal position of window
+ $yWn = 0x0000; // Vertical position of window
+ $dxWn = 0x25BC; // Width of window
+ $dyWn = 0x1572; // Height of window
+
+ $grbit = 0x0038; // Option flags
+
+ // not supported by PHPExcel, so there is only one selected sheet, the active
+ $ctabsel = 1; // Number of workbook tabs selected
+
+ $wTabRatio = 0x0258; // Tab to scrollbar ratio
+
+ // not supported by PHPExcel, set to 0
+ $itabFirst = 0; // 1st displayed worksheet
+ $itabCur = $this->phpExcel->getActiveSheetIndex(); // Active worksheet
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Writes Excel BIFF BOUNDSHEET record.
+ *
+ * @param PHPExcel_Worksheet $sheet Worksheet name
+ * @param integer $offset Location of worksheet BOF
+ */
+ private function writeBoundSheet($sheet, $offset)
+ {
+ $sheetname = $sheet->getTitle();
+ $record = 0x0085; // Record identifier
+
+ // sheet state
+ switch ($sheet->getSheetState()) {
+ case PHPExcel_Worksheet::SHEETSTATE_VISIBLE:
+ $ss = 0x00;
+ break;
+ case PHPExcel_Worksheet::SHEETSTATE_HIDDEN:
+ $ss = 0x01;
+ break;
+ case PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN:
+ $ss = 0x02;
+ break;
+ default:
+ $ss = 0x00;
+ break;
+ }
+
+ // sheet type
+ $st = 0x00;
+
+ $grbit = 0x0000; // Visibility and sheet type
+
+ $data = pack("VCC", $offset, $ss, $st);
+ $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheetname);
+
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write Internal SUPBOOK record
+ */
+ private function writeSupbookInternal()
+ {
+ $record = 0x01AE; // Record identifier
+ $length = 0x0004; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vv", $this->phpExcel->getSheetCount(), 0x0401);
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Writes the Excel BIFF EXTERNSHEET record. These references are used by
+ * formulas.
+ *
+ */
+ private function writeExternalsheetBiff8()
+ {
+ $totalReferences = count($this->parser->references);
+ $record = 0x0017; // Record identifier
+ $length = 2 + 6 * $totalReferences; // Number of bytes to follow
+
+ $supbook_index = 0; // FIXME: only using internal SUPBOOK record
+ $header = pack("vv", $record, $length);
+ $data = pack('v', $totalReferences);
+ for ($i = 0; $i < $totalReferences; ++$i) {
+ $data .= $this->parser->references[$i];
+ }
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Write Excel BIFF STYLE records.
+ */
+ private function writeStyle()
+ {
+ $record = 0x0293; // Record identifier
+ $length = 0x0004; // Bytes to follow
+
+ $ixfe = 0x8000; // Index to cell style XF
+ $BuiltIn = 0x00; // Built-in style
+ $iLevel = 0xff; // Outline style level
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vCC", $ixfe, $BuiltIn, $iLevel);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Writes Excel FORMAT record for non "built-in" numerical formats.
+ *
+ * @param string $format Custom format string
+ * @param integer $ifmt Format index code
+ */
+ private function writeNumberFormat($format, $ifmt)
+ {
+ $record = 0x041E; // Record identifier
+
+ $numberFormatString = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($format);
+ $length = 2 + strlen($numberFormatString); // Number of bytes to follow
+
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $ifmt) . $numberFormatString;
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write DATEMODE record to indicate the date system in use (1904 or 1900).
+ */
+ private function writeDateMode()
+ {
+ $record = 0x0022; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $f1904 = (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904)
+ ? 1
+ : 0; // Flag for 1904 date system
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $f1904);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
+ * references in the workbook.
+ *
+ * Excel only stores references to external sheets that are used in NAME.
+ * The workbook NAME record is required to define the print area and the repeat
+ * rows and columns.
+ *
+ * A similar method is used in Worksheet.php for a slightly different purpose.
+ *
+ * @param integer $cxals Number of external references
+ */
+ private function writeExternalCount($cxals)
+ {
+ $record = 0x0016; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $cxals);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Writes the Excel BIFF EXTERNSHEET record. These references are used by
+ * formulas. NAME record is required to define the print area and the repeat
+ * rows and columns.
+ *
+ * A similar method is used in Worksheet.php for a slightly different purpose.
+ *
+ * @param string $sheetname Worksheet name
+ */
+ private function writeExternalSheet($sheetname)
+ {
+ $record = 0x0017; // Record identifier
+ $length = 0x02 + strlen($sheetname); // Number of bytes to follow
+
+ $cch = strlen($sheetname); // Length of sheet name
+ $rgch = 0x03; // Filename encoding
+
+ $header = pack("vv", $record, $length);
+ $data = pack("CC", $cch, $rgch);
+ $this->append($header . $data . $sheetname);
+ }
+
+ /**
+ * Store the NAME record in the short format that is used for storing the print
+ * area, repeat rows only and repeat columns only.
+ *
+ * @param integer $index Sheet index
+ * @param integer $type Built-in name type
+ * @param integer $rowmin Start row
+ * @param integer $rowmax End row
+ * @param integer $colmin Start colum
+ * @param integer $colmax End column
+ */
+ private function writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax)
+ {
+ $record = 0x0018; // Record identifier
+ $length = 0x0024; // Number of bytes to follow
+
+ $grbit = 0x0020; // Option flags
+ $chKey = 0x00; // Keyboard shortcut
+ $cch = 0x01; // Length of text name
+ $cce = 0x0015; // Length of text definition
+ $ixals = $index + 1; // Sheet index
+ $itab = $ixals; // Equal to ixals
+ $cchCustMenu = 0x00; // Length of cust menu text
+ $cchDescription = 0x00; // Length of description text
+ $cchHelptopic = 0x00; // Length of help topic text
+ $cchStatustext = 0x00; // Length of status bar text
+ $rgch = $type; // Built-in name type
+
+ $unknown03 = 0x3b;
+ $unknown04 = 0xffff - $index;
+ $unknown05 = 0x0000;
+ $unknown06 = 0x0000;
+ $unknown07 = 0x1087;
+ $unknown08 = 0x8005;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $grbit);
+ $data .= pack("C", $chKey);
+ $data .= pack("C", $cch);
+ $data .= pack("v", $cce);
+ $data .= pack("v", $ixals);
+ $data .= pack("v", $itab);
+ $data .= pack("C", $cchCustMenu);
+ $data .= pack("C", $cchDescription);
+ $data .= pack("C", $cchHelptopic);
+ $data .= pack("C", $cchStatustext);
+ $data .= pack("C", $rgch);
+ $data .= pack("C", $unknown03);
+ $data .= pack("v", $unknown04);
+ $data .= pack("v", $unknown05);
+ $data .= pack("v", $unknown06);
+ $data .= pack("v", $unknown07);
+ $data .= pack("v", $unknown08);
+ $data .= pack("v", $index);
+ $data .= pack("v", $index);
+ $data .= pack("v", $rowmin);
+ $data .= pack("v", $rowmax);
+ $data .= pack("C", $colmin);
+ $data .= pack("C", $colmax);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the NAME record in the long format that is used for storing the repeat
+ * rows and columns when both are specified. This shares a lot of code with
+ * writeNameShort() but we use a separate method to keep the code clean.
+ * Code abstraction for reuse can be carried too far, and I should know. ;-)
+ *
+ * @param integer $index Sheet index
+ * @param integer $type Built-in name type
+ * @param integer $rowmin Start row
+ * @param integer $rowmax End row
+ * @param integer $colmin Start colum
+ * @param integer $colmax End column
+ */
+ private function writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax)
+ {
+ $record = 0x0018; // Record identifier
+ $length = 0x003d; // Number of bytes to follow
+ $grbit = 0x0020; // Option flags
+ $chKey = 0x00; // Keyboard shortcut
+ $cch = 0x01; // Length of text name
+ $cce = 0x002e; // Length of text definition
+ $ixals = $index + 1; // Sheet index
+ $itab = $ixals; // Equal to ixals
+ $cchCustMenu = 0x00; // Length of cust menu text
+ $cchDescription = 0x00; // Length of description text
+ $cchHelptopic = 0x00; // Length of help topic text
+ $cchStatustext = 0x00; // Length of status bar text
+ $rgch = $type; // Built-in name type
+
+ $unknown01 = 0x29;
+ $unknown02 = 0x002b;
+ $unknown03 = 0x3b;
+ $unknown04 = 0xffff-$index;
+ $unknown05 = 0x0000;
+ $unknown06 = 0x0000;
+ $unknown07 = 0x1087;
+ $unknown08 = 0x8008;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $grbit);
+ $data .= pack("C", $chKey);
+ $data .= pack("C", $cch);
+ $data .= pack("v", $cce);
+ $data .= pack("v", $ixals);
+ $data .= pack("v", $itab);
+ $data .= pack("C", $cchCustMenu);
+ $data .= pack("C", $cchDescription);
+ $data .= pack("C", $cchHelptopic);
+ $data .= pack("C", $cchStatustext);
+ $data .= pack("C", $rgch);
+ $data .= pack("C", $unknown01);
+ $data .= pack("v", $unknown02);
+ // Column definition
+ $data .= pack("C", $unknown03);
+ $data .= pack("v", $unknown04);
+ $data .= pack("v", $unknown05);
+ $data .= pack("v", $unknown06);
+ $data .= pack("v", $unknown07);
+ $data .= pack("v", $unknown08);
+ $data .= pack("v", $index);
+ $data .= pack("v", $index);
+ $data .= pack("v", 0x0000);
+ $data .= pack("v", 0x3fff);
+ $data .= pack("C", $colmin);
+ $data .= pack("C", $colmax);
+ // Row definition
+ $data .= pack("C", $unknown03);
+ $data .= pack("v", $unknown04);
+ $data .= pack("v", $unknown05);
+ $data .= pack("v", $unknown06);
+ $data .= pack("v", $unknown07);
+ $data .= pack("v", $unknown08);
+ $data .= pack("v", $index);
+ $data .= pack("v", $index);
+ $data .= pack("v", $rowmin);
+ $data .= pack("v", $rowmax);
+ $data .= pack("C", 0x00);
+ $data .= pack("C", 0xff);
+ // End of data
+ $data .= pack("C", 0x10);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Stores the COUNTRY record for localization
+ *
+ * @return string
+ */
+ private function writeCountry()
+ {
+ $record = 0x008C; // Record identifier
+ $length = 4; // Number of bytes to follow
+
+ $header = pack('vv', $record, $length);
+ /* using the same country code always for simplicity */
+ $data = pack('vv', $this->countryCode, $this->countryCode);
+ //$this->append($header . $data);
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Write the RECALCID record
+ *
+ * @return string
+ */
+ private function writeRecalcId()
+ {
+ $record = 0x01C1; // Record identifier
+ $length = 8; // Number of bytes to follow
+
+ $header = pack('vv', $record, $length);
+
+ // by inspection of real Excel files, MS Office Excel 2007 writes this
+ $data = pack('VV', 0x000001C1, 0x00001E667);
+
+ return $this->writeData($header . $data);
+ }
+
+ /**
+ * Stores the PALETTE biff record.
+ */
+ private function writePalette()
+ {
+ $aref = $this->palette;
+
+ $record = 0x0092; // Record identifier
+ $length = 2 + 4 * count($aref); // Number of bytes to follow
+ $ccv = count($aref); // Number of RGB values to follow
+ $data = ''; // The RGB data
+
+ // Pack the RGB data
+ foreach ($aref as $color) {
+ foreach ($color as $byte) {
+ $data .= pack("C", $byte);
+ }
+ }
+
+ $header = pack("vvv", $record, $length, $ccv);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Handling of the SST continue blocks is complicated by the need to include an
+ * additional continuation byte depending on whether the string is split between
+ * blocks or whether it starts at the beginning of the block. (There are also
+ * additional complications that will arise later when/if Rich Strings are
+ * supported).
+ *
+ * The Excel documentation says that the SST record should be followed by an
+ * EXTSST record. The EXTSST record is a hash table that is used to optimise
+ * access to SST. However, despite the documentation it doesn't seem to be
+ * required so we will ignore it.
+ *
+ * @return string Binary data
+ */
+ private function writeSharedStringsTable()
+ {
+ // maximum size of record data (excluding record header)
+ $continue_limit = 8224;
+
+ // initialize array of record data blocks
+ $recordDatas = array();
+
+ // start SST record data block with total number of strings, total number of unique strings
+ $recordData = pack("VV", $this->stringTotal, $this->stringUnique);
+
+ // loop through all (unique) strings in shared strings table
+ foreach (array_keys($this->stringTable) as $string) {
+ // here $string is a BIFF8 encoded string
+
+ // length = character count
+ $headerinfo = unpack("vlength/Cencoding", $string);
+
+ // currently, this is always 1 = uncompressed
+ $encoding = $headerinfo["encoding"];
+
+ // initialize finished writing current $string
+ $finished = false;
+
+ while ($finished === false) {
+ // normally, there will be only one cycle, but if string cannot immediately be written as is
+ // there will be need for more than one cylcle, if string longer than one record data block, there
+ // may be need for even more cycles
+
+ if (strlen($recordData) + strlen($string) <= $continue_limit) {
+ // then we can write the string (or remainder of string) without any problems
+ $recordData .= $string;
+
+ if (strlen($recordData) + strlen($string) == $continue_limit) {
+ // we close the record data block, and initialize a new one
+ $recordDatas[] = $recordData;
+ $recordData = '';
+ }
+
+ // we are finished writing this string
+ $finished = true;
+ } else {
+ // special treatment writing the string (or remainder of the string)
+ // If the string is very long it may need to be written in more than one CONTINUE record.
+
+ // check how many bytes more there is room for in the current record
+ $space_remaining = $continue_limit - strlen($recordData);
+
+ // minimum space needed
+ // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character
+ // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character
+ $min_space_needed = ($encoding == 1) ? 5 : 4;
+
+ // We have two cases
+ // 1. space remaining is less than minimum space needed
+ // here we must waste the space remaining and move to next record data block
+ // 2. space remaining is greater than or equal to minimum space needed
+ // here we write as much as we can in the current block, then move to next record data block
+
+ // 1. space remaining is less than minimum space needed
+ if ($space_remaining < $min_space_needed) {
+ // we close the block, store the block data
+ $recordDatas[] = $recordData;
+
+ // and start new record data block where we start writing the string
+ $recordData = '';
+
+ // 2. space remaining is greater than or equal to minimum space needed
+ } else {
+ // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below
+ $effective_space_remaining = $space_remaining;
+
+ // for uncompressed strings, sometimes effective space remaining is reduced by 1
+ if ($encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1) {
+ --$effective_space_remaining;
+ }
+
+ // one block fininshed, store the block data
+ $recordData .= substr($string, 0, $effective_space_remaining);
+
+ $string = substr($string, $effective_space_remaining); // for next cycle in while loop
+ $recordDatas[] = $recordData;
+
+ // start new record data block with the repeated option flags
+ $recordData = pack('C', $encoding);
+ }
+ }
+ }
+ }
+
+ // Store the last record data block unless it is empty
+ // if there was no need for any continue records, this will be the for SST record data block itself
+ if (strlen($recordData) > 0) {
+ $recordDatas[] = $recordData;
+ }
+
+ // combine into one chunk with all the blocks SST, CONTINUE,...
+ $chunk = '';
+ foreach ($recordDatas as $i => $recordData) {
+ // first block should have the SST record header, remaing should have CONTINUE header
+ $record = ($i == 0) ? 0x00FC : 0x003C;
+
+ $header = pack("vv", $record, strlen($recordData));
+ $data = $header . $recordData;
+
+ $chunk .= $this->writeData($data);
+ }
+
+ return $chunk;
+ }
+
+ /**
+ * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records.
+ */
+ private function writeMsoDrawingGroup()
+ {
+ // write the Escher stream if necessary
+ if (isset($this->escher)) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($this->escher);
+ $data = $writer->close();
+
+ $record = 0x00EB;
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+
+ return $this->writeData($header . $data);
+ } else {
+ return '';
+ }
+ }
+
+ /**
+ * Get Escher object
+ *
+ * @return PHPExcel_Shared_Escher
+ */
+ public function getEscher()
+ {
+ return $this->escher;
+ }
+
+ /**
+ * Set Escher object
+ *
+ * @param PHPExcel_Shared_Escher $pValue
+ */
+ public function setEscher(PHPExcel_Shared_Escher $pValue = null)
+ {
+ $this->escher = $pValue;
+ }
}
diff --git a/Classes/PHPExcel/Writer/Excel5/Worksheet.php b/Classes/PHPExcel/Writer/Excel5/Worksheet.php
index ff675b4cc..be965e23d 100644
--- a/Classes/PHPExcel/Writer/Excel5/Worksheet.php
+++ b/Classes/PHPExcel/Writer/Excel5/Worksheet.php
@@ -1,8 +1,9 @@
_limit = 8224;
-
-
- $this->_preCalculateFormulas = $preCalculateFormulas;
- $this->_str_total = &$str_total;
- $this->_str_unique = &$str_unique;
- $this->_str_table = &$str_table;
- $this->_colors = &$colors;
- $this->_parser = $parser;
-
- $this->_phpSheet = $phpSheet;
-
- //$this->ext_sheets = array();
- //$this->offset = 0;
- $this->_xls_strmax = 255;
- $this->_colinfo = array();
- $this->_selection = array(0,0,0,0);
- $this->_active_pane = 3;
-
- $this->_print_headers = 0;
-
- $this->_outline_style = 0;
- $this->_outline_below = 1;
- $this->_outline_right = 1;
- $this->_outline_on = 1;
-
- $this->_fntHashIndex = array();
-
- // calculate values for DIMENSIONS record
- $minR = 1;
- $minC = 'A';
-
- $maxR = $this->_phpSheet->getHighestRow();
- $maxC = $this->_phpSheet->getHighestColumn();
-
- // Determine lowest and highest column and row
-// $this->_firstRowIndex = ($minR > 65535) ? 65535 : $minR;
- $this->_lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ;
-
- $this->_firstColumnIndex = PHPExcel_Cell::columnIndexFromString($minC);
- $this->_lastColumnIndex = PHPExcel_Cell::columnIndexFromString($maxC);
-
-// if ($this->_firstColumnIndex > 255) $this->_firstColumnIndex = 255;
- if ($this->_lastColumnIndex > 255) $this->_lastColumnIndex = 255;
-
- $this->_countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
- }
-
- /**
- * Add data to the beginning of the workbook (note the reverse order)
- * and to the end of the workbook.
- *
- * @access public
- * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook()
- */
- function close()
- {
- $_phpSheet = $this->_phpSheet;
-
- $num_sheets = $_phpSheet->getParent()->getSheetCount();
-
- // Write BOF record
- $this->_storeBof(0x0010);
-
- // Write PRINTHEADERS
- $this->_writePrintHeaders();
-
- // Write PRINTGRIDLINES
- $this->_writePrintGridlines();
-
- // Write GRIDSET
- $this->_writeGridset();
-
- // Calculate column widths
- $_phpSheet->calculateColumnWidths();
-
- // Column dimensions
- if (($defaultWidth = $_phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
- $defaultWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($_phpSheet->getParent()->getDefaultStyle()->getFont());
- }
-
- $columnDimensions = $_phpSheet->getColumnDimensions();
- $maxCol = $this->_lastColumnIndex -1;
- for ($i = 0; $i <= $maxCol; ++$i) {
- $hidden = 0;
- $level = 0;
- $xfIndex = 15; // there are 15 cell style Xfs
-
- $width = $defaultWidth;
-
- $columnLetter = PHPExcel_Cell::stringFromColumnIndex($i);
- if (isset($columnDimensions[$columnLetter])) {
- $columnDimension = $columnDimensions[$columnLetter];
- if ($columnDimension->getWidth() >= 0) {
- $width = $columnDimension->getWidth();
- }
- $hidden = $columnDimension->getVisible() ? 0 : 1;
- $level = $columnDimension->getOutlineLevel();
- $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
- }
-
- // Components of _colinfo:
- // $firstcol first column on the range
- // $lastcol last column on the range
- // $width width to set
- // $xfIndex The optional cell style Xf index to apply to the columns
- // $hidden The optional hidden atribute
- // $level The optional outline level
- $this->_colinfo[] = array($i, $i, $width, $xfIndex, $hidden, $level);
- }
-
- // Write GUTS
- $this->_writeGuts();
-
- // Write DEFAULTROWHEIGHT
- $this->_writeDefaultRowHeight();
-
- // Write WSBOOL
- $this->_writeWsbool();
-
- // Write horizontal and vertical page breaks
- $this->_writeBreaks();
-
- // Write page header
- $this->_writeHeader();
-
- // Write page footer
- $this->_writeFooter();
-
- // Write page horizontal centering
- $this->_writeHcenter();
-
- // Write page vertical centering
- $this->_writeVcenter();
-
- // Write left margin
- $this->_writeMarginLeft();
-
- // Write right margin
- $this->_writeMarginRight();
-
- // Write top margin
- $this->_writeMarginTop();
-
- // Write bottom margin
- $this->_writeMarginBottom();
-
- // Write page setup
- $this->_writeSetup();
-
- // Write sheet protection
- $this->_writeProtect();
-
- // Write SCENPROTECT
- $this->_writeScenProtect();
-
- // Write OBJECTPROTECT
- $this->_writeObjectProtect();
-
- // Write sheet password
- $this->_writePassword();
-
- // Write DEFCOLWIDTH record
- $this->_writeDefcol();
-
- // Write the COLINFO records if they exist
- if (!empty($this->_colinfo)) {
- $colcount = count($this->_colinfo);
- for ($i = 0; $i < $colcount; ++$i) {
- $this->_writeColinfo($this->_colinfo[$i]);
- }
- }
- $autoFilterRange = $_phpSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- // Write AUTOFILTERINFO
- $this->_writeAutoFilterInfo();
- }
-
- // Write sheet dimensions
- $this->_writeDimensions();
-
- // Row dimensions
- foreach ($_phpSheet->getRowDimensions() as $rowDimension) {
- $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
- $this->_writeRow( $rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel() );
- }
-
- // Write Cells
- foreach ($_phpSheet->getCellCollection() as $cellID) {
- $cell = $_phpSheet->getCell($cellID);
- $row = $cell->getRow() - 1;
- $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
-
- // Don't break Excel!
-// if ($row + 1 > 65536 or $column + 1 > 256) {
- if ($row > 65535 || $column > 255) {
- break;
- }
-
- // Write cell value
- $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
-
- $cVal = $cell->getValue();
- if ($cVal instanceof PHPExcel_RichText) {
- // $this->_writeString($row, $column, $cVal->getPlainText(), $xfIndex);
- $arrcRun = array();
- $str_len = PHPExcel_Shared_String::CountCharacters($cVal->getPlainText(), 'UTF-8');
- $str_pos = 0;
- $elements = $cVal->getRichTextElements();
- foreach ($elements as $element) {
- // FONT Index
- if ($element instanceof PHPExcel_RichText_Run) {
- $str_fontidx = $this->_fntHashIndex[$element->getFont()->getHashCode()];
- }
- else {
- $str_fontidx = 0;
- }
- $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx);
- // Position FROM
- $str_pos += PHPExcel_Shared_String::CountCharacters($element->getText(), 'UTF-8');
- }
- $this->_writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
- } else {
- switch ($cell->getDatatype()) {
- case PHPExcel_Cell_DataType::TYPE_STRING:
- case PHPExcel_Cell_DataType::TYPE_NULL:
- if ($cVal === '' || $cVal === null) {
- $this->_writeBlank($row, $column, $xfIndex);
- } else {
- $this->_writeString($row, $column, $cVal, $xfIndex);
- }
- break;
-
- case PHPExcel_Cell_DataType::TYPE_NUMERIC:
- $this->_writeNumber($row, $column, $cVal, $xfIndex);
- break;
-
- case PHPExcel_Cell_DataType::TYPE_FORMULA:
- $calculatedValue = $this->_preCalculateFormulas ?
- $cell->getCalculatedValue() : null;
- $this->_writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue);
- break;
-
- case PHPExcel_Cell_DataType::TYPE_BOOL:
- $this->_writeBoolErr($row, $column, $cVal, 0, $xfIndex);
- break;
-
- case PHPExcel_Cell_DataType::TYPE_ERROR:
- $this->_writeBoolErr($row, $column, self::_mapErrorCode($cVal), 1, $xfIndex);
- break;
-
- }
- }
- }
-
- // Append
- $this->_writeMsoDrawing();
-
- // Write WINDOW2 record
- $this->_writeWindow2();
-
- // Write PLV record
- $this->_writePageLayoutView();
-
- // Write ZOOM record
- $this->_writeZoom();
- if ($_phpSheet->getFreezePane()) {
- $this->_writePanes();
- }
-
- // Write SELECTION record
- $this->_writeSelection();
-
- // Write MergedCellsTable Record
- $this->_writeMergedCells();
-
- // Hyperlinks
- foreach ($_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
- list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinate);
-
- $url = $hyperlink->getUrl();
-
- if ( strpos($url, 'sheet://') !== false ) {
- // internal to current workbook
- $url = str_replace('sheet://', 'internal:', $url);
-
- } else if ( preg_match('/^(http:|https:|ftp:|mailto:)/', $url) ) {
- // URL
- // $url = $url;
-
- } else {
- // external (local file)
- $url = 'external:' . $url;
- }
-
- $this->_writeUrl($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $url);
- }
-
- $this->_writeDataValidity();
- $this->_writeSheetLayout();
-
- // Write SHEETPROTECTION record
- $this->_writeSheetProtection();
- $this->_writeRangeProtection();
-
- $arrConditionalStyles = $_phpSheet->getConditionalStylesCollection();
- if(!empty($arrConditionalStyles)){
- $arrConditional = array();
- // @todo CFRule & CFHeader
- // Write CFHEADER record
- $this->_writeCFHeader();
- // Write ConditionalFormattingTable records
- foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
- foreach ($conditionalStyles as $conditional) {
- if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
- || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS){
- if(!in_array($conditional->getHashCode(), $arrConditional)){
- $arrConditional[] = $conditional->getHashCode();
- // Write CFRULE record
- $this->_writeCFRule($conditional);
- }
- }
- }
- }
- }
-
- $this->_storeEof();
- }
-
- /**
- * Write a cell range address in BIFF8
- * always fixed range
- * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format
- *
- * @param string $range E.g. 'A1' or 'A1:B6'
- * @return string Binary data
- */
- private function _writeBIFF8CellRangeAddressFixed($range = 'A1')
- {
- $explodes = explode(':', $range);
-
- // extract first cell, e.g. 'A1'
- $firstCell = $explodes[0];
-
- // extract last cell, e.g. 'B6'
- if (count($explodes) == 1) {
- $lastCell = $firstCell;
- } else {
- $lastCell = $explodes[1];
- }
-
- $firstCellCoordinates = PHPExcel_Cell::coordinateFromString($firstCell); // e.g. array(0, 1)
- $lastCellCoordinates = PHPExcel_Cell::coordinateFromString($lastCell); // e.g. array(1, 6)
-
- return(pack('vvvv',
- $firstCellCoordinates[1] - 1,
- $lastCellCoordinates[1] - 1,
- PHPExcel_Cell::columnIndexFromString($firstCellCoordinates[0]) - 1,
- PHPExcel_Cell::columnIndexFromString($lastCellCoordinates[0]) - 1
- ));
- }
-
- /**
- * Retrieves data from memory in one chunk, or from disk in $buffer
- * sized chunks.
- *
- * @return string The data
- */
- function getData()
- {
- $buffer = 4096;
-
- // Return data stored in memory
- if (isset($this->_data)) {
- $tmp = $this->_data;
- unset($this->_data);
- return $tmp;
- }
- // No data to return
- return false;
- }
-
- /**
- * Set the option to print the row and column headers on the printed page.
- *
- * @access public
- * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
- */
- function printRowColHeaders($print = 1)
- {
- $this->_print_headers = $print;
- }
-
- /**
- * This method sets the properties for outlining and grouping. The defaults
- * correspond to Excel's defaults.
- *
- * @param bool $visible
- * @param bool $symbols_below
- * @param bool $symbols_right
- * @param bool $auto_style
- */
- function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
- {
- $this->_outline_on = $visible;
- $this->_outline_below = $symbols_below;
- $this->_outline_right = $symbols_right;
- $this->_outline_style = $auto_style;
-
- // Ensure this is a boolean vale for Window2
- if ($this->_outline_on) {
- $this->_outline_on = 1;
- }
- }
-
- /**
- * Write a double to the specified row and column (zero indexed).
- * An integer can be written as a double. Excel will display an
- * integer. $format is optional.
- *
- * Returns 0 : normal termination
- * -2 : row or column out of range
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param float $num The number to write
- * @param mixed $xfIndex The optional XF format
- * @return integer
- */
- private function _writeNumber($row, $col, $num, $xfIndex)
- {
- $record = 0x0203; // Record identifier
- $length = 0x000E; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $row, $col, $xfIndex);
- $xl_double = pack("d", $num);
- if (self::getByteOrder()) { // if it's Big Endian
- $xl_double = strrev($xl_double);
- }
-
- $this->_append($header.$data.$xl_double);
- return(0);
- }
-
- /**
- * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
- *
- * @param int $row Row index (0-based)
- * @param int $col Column index (0-based)
- * @param string $str The string
- * @param int $xfIndex Index to XF record
- */
- private function _writeString($row, $col, $str, $xfIndex)
- {
- $this->_writeLabelSst($row, $col, $str, $xfIndex);
- }
-
- /**
- * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
- * It differs from _writeString by the writing of rich text strings.
- * @param int $row Row index (0-based)
- * @param int $col Column index (0-based)
- * @param string $str The string
- * @param mixed $xfIndex The XF format index for the cell
- * @param array $arrcRun Index to Font record and characters beginning
- */
- private function _writeRichTextString($row, $col, $str, $xfIndex, $arrcRun){
- $record = 0x00FD; // Record identifier
- $length = 0x000A; // Bytes to follow
- $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun);
-
- /* check if string is already present */
- if (!isset($this->_str_table[$str])) {
- $this->_str_table[$str] = $this->_str_unique++;
- }
- $this->_str_total++;
-
- $header = pack('vv', $record, $length);
- $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
- $this->_append($header.$data);
- }
-
- /**
- * Write a string to the specified row and column (zero indexed).
- * NOTE: there is an Excel 5 defined limit of 255 characters.
- * $format is optional.
- * Returns 0 : normal termination
- * -2 : row or column out of range
- * -3 : long string truncated to 255 chars
- *
- * @access public
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $str The string to write
- * @param mixed $xfIndex The XF format index for the cell
- * @return integer
- */
- private function _writeLabel($row, $col, $str, $xfIndex)
- {
- $strlen = strlen($str);
- $record = 0x0204; // Record identifier
- $length = 0x0008 + $strlen; // Bytes to follow
-
- $str_error = 0;
-
- if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars
- $str = substr($str, 0, $this->_xls_strmax);
- $length = 0x0008 + $this->_xls_strmax;
- $strlen = $this->_xls_strmax;
- $str_error = -3;
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $row, $col, $xfIndex, $strlen);
- $this->_append($header . $data . $str);
- return($str_error);
- }
-
- /**
- * Write a string to the specified row and column (zero indexed).
- * This is the BIFF8 version (no 255 chars limit).
- * $format is optional.
- * Returns 0 : normal termination
- * -2 : row or column out of range
- * -3 : long string truncated to 255 chars
- *
- * @access public
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $str The string to write
- * @param mixed $xfIndex The XF format index for the cell
- * @return integer
- */
- private function _writeLabelSst($row, $col, $str, $xfIndex)
- {
- $record = 0x00FD; // Record identifier
- $length = 0x000A; // Bytes to follow
-
- $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($str);
-
- /* check if string is already present */
- if (!isset($this->_str_table[$str])) {
- $this->_str_table[$str] = $this->_str_unique++;
- }
- $this->_str_total++;
-
- $header = pack('vv', $record, $length);
- $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]);
- $this->_append($header.$data);
- }
-
- /**
- * Writes a note associated with the cell given by the row and column.
- * NOTE records don't have a length limit.
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $note The note to write
- */
- private function _writeNote($row, $col, $note)
- {
- $note_length = strlen($note);
- $record = 0x001C; // Record identifier
- $max_length = 2048; // Maximun length for a NOTE record
-
- // Length for this record is no more than 2048 + 6
- $length = 0x0006 + min($note_length, 2048);
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $row, $col, $note_length);
- $this->_append($header . $data . substr($note, 0, 2048));
-
- for ($i = $max_length; $i < $note_length; $i += $max_length) {
- $chunk = substr($note, $i, $max_length);
- $length = 0x0006 + strlen($chunk);
- $header = pack("vv", $record, $length);
- $data = pack("vvv", -1, 0, strlen($chunk));
- $this->_append($header.$data.$chunk);
- }
- return(0);
- }
-
- /**
- * Write a blank cell to the specified row and column (zero indexed).
- * A blank cell is used to specify formatting without adding a string
- * or a number.
- *
- * A blank cell without a format serves no purpose. Therefore, we don't write
- * a BLANK record unless a format is specified.
- *
- * Returns 0 : normal termination (including no format)
- * -1 : insufficient number of arguments
- * -2 : row or column out of range
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param mixed $xfIndex The XF format index
- */
- function _writeBlank($row, $col, $xfIndex)
- {
- $record = 0x0201; // Record identifier
- $length = 0x0006; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $row, $col, $xfIndex);
- $this->_append($header . $data);
- return 0;
- }
-
- /**
- * Write a boolean or an error type to the specified row and column (zero indexed)
- *
- * @param int $row Row index (0-based)
- * @param int $col Column index (0-based)
- * @param int $value
- * @param boolean $isError Error or Boolean?
- * @param int $xfIndex
- */
- private function _writeBoolErr($row, $col, $value, $isError, $xfIndex)
- {
- $record = 0x0205;
- $length = 8;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError);
- $this->_append($header . $data);
- return 0;
- }
-
- /**
- * Write a formula to the specified row and column (zero indexed).
- * The textual representation of the formula is passed to the parser in
- * Parser.php which returns a packed binary string.
- *
- * Returns 0 : normal termination
- * -1 : formula errors (bad formula)
- * -2 : row or column out of range
- *
- * @param integer $row Zero indexed row
- * @param integer $col Zero indexed column
- * @param string $formula The formula text string
- * @param mixed $xfIndex The XF format index
- * @param mixed $calculatedValue Calculated value
- * @return integer
- */
- private function _writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
- {
- $record = 0x0006; // Record identifier
-
- // Initialize possible additional value for STRING record that should be written after the FORMULA record?
- $stringValue = null;
-
- // calculated value
- if (isset($calculatedValue)) {
- // Since we can't yet get the data type of the calculated value,
- // we use best effort to determine data type
- if (is_bool($calculatedValue)) {
- // Boolean value
- $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF);
- } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
- // Numeric value
- $num = pack('d', $calculatedValue);
- } elseif (is_string($calculatedValue)) {
- if (array_key_exists($calculatedValue, PHPExcel_Cell_DataType::getErrorCodes())) {
- // Error value
- $num = pack('CCCvCv', 0x02, 0x00, self::_mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF);
- } elseif ($calculatedValue === '') {
- // Empty string (and BIFF8)
- $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
- } else {
- // Non-empty string value (or empty string BIFF5)
- $stringValue = $calculatedValue;
- $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
- }
- } else {
- // We are really not supposed to reach here
- $num = pack('d', 0x00);
- }
- } else {
- $num = pack('d', 0x00);
- }
-
- $grbit = 0x03; // Option flags
- $unknown = 0x0000; // Must be zero
-
- // Strip the '=' or '@' sign at the beginning of the formula string
- if ($formula{0} == '=') {
- $formula = substr($formula,1);
- } else {
- // Error handling
- $this->_writeString($row, $col, 'Unrecognised character for formula');
- return -1;
- }
-
- // Parse the formula using the parser in Parser.php
- try {
- $error = $this->_parser->parse($formula);
- $formula = $this->_parser->toReversePolish();
-
- $formlen = strlen($formula); // Length of the binary string
- $length = 0x16 + $formlen; // Length of the record data
-
- $header = pack("vv", $record, $length);
-
- $data = pack("vvv", $row, $col, $xfIndex)
- . $num
- . pack("vVv", $grbit, $unknown, $formlen);
- $this->_append($header . $data . $formula);
-
- // Append also a STRING record if necessary
- if ($stringValue !== null) {
- $this->_writeStringRecord($stringValue);
- }
-
- return 0;
-
- } catch (PHPExcel_Exception $e) {
- // do nothing
- }
-
- }
-
- /**
- * Write a STRING record. This
- *
- * @param string $stringValue
- */
- private function _writeStringRecord($stringValue)
- {
- $record = 0x0207; // Record identifier
- $data = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($stringValue);
-
- $length = strlen($data);
- $header = pack('vv', $record, $length);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write a hyperlink.
- * This is comprised of two elements: the visible label and
- * the invisible link. The visible label is the same as the link unless an
- * alternative string is specified. The label is written using the
- * _writeString() method. Therefore the 255 characters string limit applies.
- * $string and $format are optional.
- *
- * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
- * directory url.
- *
- * Returns 0 : normal termination
- * -2 : row or column out of range
- * -3 : long string truncated to 255 chars
- *
- * @param integer $row Row
- * @param integer $col Column
- * @param string $url URL string
- * @return integer
- */
- private function _writeUrl($row, $col, $url)
- {
- // Add start row and col to arg list
- return($this->_writeUrlRange($row, $col, $row, $col, $url));
- }
-
- /**
- * This is the more general form of _writeUrl(). It allows a hyperlink to be
- * written to a range of cells. This function also decides the type of hyperlink
- * to be written. These are either, Web (http, ftp, mailto), Internal
- * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlRange($row1, $col1, $row2, $col2, $url)
- {
- // Check for internal/external sheet links or default to web link
- if (preg_match('[^internal:]', $url)) {
- return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url));
- }
- if (preg_match('[^external:]', $url)) {
- return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url));
- }
- return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url));
- }
-
- /**
- * Used to write http, ftp and mailto hyperlinks.
- * The link type ($options) is 0x03 is the same as absolute dir ref without
- * sheet. However it is differentiated by the $unknown2 data stream.
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlWeb($row1, $col1, $row2, $col2, $url)
- {
- $record = 0x01B8; // Record identifier
- $length = 0x00000; // Bytes to follow
-
- // Pack the undocumented parts of the hyperlink stream
- $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
- $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
-
- // Pack the option flags
- $options = pack("V", 0x03);
-
- // Convert URL to a null terminated wchar string
- $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
- $url = $url . "\0\0\0";
-
- // Pack the length of the URL
- $url_len = pack("V", strlen($url));
-
- // Calculate the data length
- $length = 0x34 + strlen($url);
-
- // Pack the header data
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $row1, $row2, $col1, $col2);
-
- // Write the packed data
- $this->_append($header . $data .
- $unknown1 . $options .
- $unknown2 . $url_len . $url);
- return 0;
- }
-
- /**
- * Used to write internal reference hyperlinks such as "Sheet1!A1".
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlInternal($row1, $col1, $row2, $col2, $url)
- {
- $record = 0x01B8; // Record identifier
- $length = 0x00000; // Bytes to follow
-
- // Strip URL type
- $url = preg_replace('/^internal:/', '', $url);
-
- // Pack the undocumented parts of the hyperlink stream
- $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
-
- // Pack the option flags
- $options = pack("V", 0x08);
-
- // Convert the URL type and to a null terminated wchar string
- $url .= "\0";
-
- // character count
- $url_len = PHPExcel_Shared_String::CountCharacters($url);
- $url_len = pack('V', $url_len);
-
- $url = PHPExcel_Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8');
-
- // Calculate the data length
- $length = 0x24 + strlen($url);
-
- // Pack the header data
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $row1, $row2, $col1, $col2);
-
- // Write the packed data
- $this->_append($header . $data .
- $unknown1 . $options .
- $url_len . $url);
- return 0;
- }
-
- /**
- * Write links to external directory names such as 'c:\foo.xls',
- * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
- *
- * Note: Excel writes some relative links with the $dir_long string. We ignore
- * these cases for the sake of simpler code.
- *
- * @access private
- * @see _writeUrl()
- * @param integer $row1 Start row
- * @param integer $col1 Start column
- * @param integer $row2 End row
- * @param integer $col2 End column
- * @param string $url URL string
- * @return integer
- */
- function _writeUrlExternal($row1, $col1, $row2, $col2, $url)
- {
- // Network drives are different. We will handle them separately
- // MS/Novell network drives and shares start with \\
- if (preg_match('[^external:\\\\]', $url)) {
- return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
- }
-
- $record = 0x01B8; // Record identifier
- $length = 0x00000; // Bytes to follow
-
- // Strip URL type and change Unix dir separator to Dos style (if needed)
- //
- $url = preg_replace('/^external:/', '', $url);
- $url = preg_replace('/\//', "\\", $url);
-
- // Determine if the link is relative or absolute:
- // relative if link contains no dir separator, "somefile.xls"
- // relative if link starts with up-dir, "..\..\somefile.xls"
- // otherwise, absolute
-
- $absolute = 0x00; // relative path
- if ( preg_match('/^[A-Z]:/', $url) ) {
- $absolute = 0x02; // absolute path on Windows, e.g. C:\...
- }
- $link_type = 0x01 | $absolute;
-
- // Determine if the link contains a sheet reference and change some of the
- // parameters accordingly.
- // Split the dir name and sheet name (if it exists)
- $dir_long = $url;
- if (preg_match("/\#/", $url)) {
- $link_type |= 0x08;
- }
-
-
- // Pack the link type
- $link_type = pack("V", $link_type);
-
- // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
- $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
- $up_count = pack("v", $up_count);
-
- // Store the short dos dir name (null terminated)
- $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
-
- // Store the long dir name as a wchar string (non-null terminated)
- $dir_long = $dir_long . "\0";
-
- // Pack the lengths of the dir strings
- $dir_short_len = pack("V", strlen($dir_short) );
- $dir_long_len = pack("V", strlen($dir_long) );
- $stream_len = pack("V", 0);//strlen($dir_long) + 0x06);
-
- // Pack the undocumented parts of the hyperlink stream
- $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' );
- $unknown2 = pack("H*",'0303000000000000C000000000000046' );
- $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000');
- $unknown4 = pack("v", 0x03 );
-
- // Pack the main data stream
- $data = pack("vvvv", $row1, $row2, $col1, $col2) .
- $unknown1 .
- $link_type .
- $unknown2 .
- $up_count .
- $dir_short_len.
- $dir_short .
- $unknown3 .
- $stream_len ;/*.
- $dir_long_len .
- $unknown4 .
- $dir_long .
- $sheet_len .
- $sheet ;*/
-
- // Pack the header data
- $length = strlen($data);
- $header = pack("vv", $record, $length);
-
- // Write the packed data
- $this->_append($header. $data);
- return 0;
- }
-
- /**
- * This method is used to set the height and format for a row.
- *
- * @param integer $row The row to set
- * @param integer $height Height we are giving to the row.
- * Use null to set XF without setting height
- * @param integer $xfIndex The optional cell style Xf index to apply to the columns
- * @param bool $hidden The optional hidden attribute
- * @param integer $level The optional outline level for row, in range [0,7]
- */
- private function _writeRow($row, $height, $xfIndex, $hidden = false, $level = 0)
- {
- $record = 0x0208; // Record identifier
- $length = 0x0010; // Number of bytes to follow
-
- $colMic = 0x0000; // First defined column
- $colMac = 0x0000; // Last defined column
- $irwMac = 0x0000; // Used by Excel to optimise loading
- $reserved = 0x0000; // Reserved
- $grbit = 0x0000; // Option flags
- $ixfe = $xfIndex;
-
- if ( $height < 0 ){
- $height = null;
- }
-
- // Use _writeRow($row, null, $XF) to set XF format without setting height
- if ($height != null) {
- $miyRw = $height * 20; // row height
- } else {
- $miyRw = 0xff; // default row height is 256
- }
-
- // Set the options flags. fUnsynced is used to show that the font and row
- // heights are not compatible. This is usually the case for WriteExcel.
- // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
- // is collapsed. Instead it is used to indicate that the previous row is
- // collapsed. The zero height flag, 0x20, is used to collapse a row.
-
- $grbit |= $level;
- if ($hidden) {
- $grbit |= 0x0020;
- }
- if ($height !== null) {
- $grbit |= 0x0040; // fUnsynced
- }
- if ($xfIndex !== 0xF) {
- $grbit |= 0x0080;
- }
- $grbit |= 0x0100;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw,
- $irwMac,$reserved, $grbit, $ixfe);
- $this->_append($header.$data);
- }
-
- /**
- * Writes Excel DIMENSIONS to define the area in which there is data.
- */
- private function _writeDimensions()
- {
- $record = 0x0200; // Record identifier
-
- $length = 0x000E;
- $data = pack('VVvvv'
- , $this->_firstRowIndex
- , $this->_lastRowIndex + 1
- , $this->_firstColumnIndex
- , $this->_lastColumnIndex + 1
- , 0x0000 // reserved
- );
-
- $header = pack("vv", $record, $length);
- $this->_append($header.$data);
- }
-
- /**
- * Write BIFF record Window2.
- */
- private function _writeWindow2()
- {
- $record = 0x023E; // Record identifier
- $length = 0x0012;
-
- $grbit = 0x00B6; // Option flags
- $rwTop = 0x0000; // Top row visible in window
- $colLeft = 0x0000; // Leftmost column visible in window
-
-
- // The options flags that comprise $grbit
- $fDspFmla = 0; // 0 - bit
- $fDspGrid = $this->_phpSheet->getShowGridlines() ? 1 : 0; // 1
- $fDspRwCol = $this->_phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
- $fFrozen = $this->_phpSheet->getFreezePane() ? 1 : 0; // 3
- $fDspZeros = 1; // 4
- $fDefaultHdr = 1; // 5
- $fArabic = $this->_phpSheet->getRightToLeft() ? 1 : 0; // 6
- $fDspGuts = $this->_outline_on; // 7
- $fFrozenNoSplit = 0; // 0 - bit
- // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet
- $fSelected = ($this->_phpSheet === $this->_phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
- $fPaged = 1; // 2
- $fPageBreakPreview = $this->_phpSheet->getSheetView()->getView() === PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW;
-
- $grbit = $fDspFmla;
- $grbit |= $fDspGrid << 1;
- $grbit |= $fDspRwCol << 2;
- $grbit |= $fFrozen << 3;
- $grbit |= $fDspZeros << 4;
- $grbit |= $fDefaultHdr << 5;
- $grbit |= $fArabic << 6;
- $grbit |= $fDspGuts << 7;
- $grbit |= $fFrozenNoSplit << 8;
- $grbit |= $fSelected << 9;
- $grbit |= $fPaged << 10;
- $grbit |= $fPageBreakPreview << 11;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvv", $grbit, $rwTop, $colLeft);
-
- // FIXME !!!
- $rgbHdr = 0x0040; // Row/column heading and gridline color index
- $zoom_factor_page_break = ($fPageBreakPreview? $this->_phpSheet->getSheetView()->getZoomScale() : 0x0000);
- $zoom_factor_normal = $this->_phpSheet->getSheetView()->getZoomScaleNormal();
-
- $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
-
- $this->_append($header.$data);
- }
-
- /**
- * Write BIFF record DEFAULTROWHEIGHT.
- */
- private function _writeDefaultRowHeight()
- {
- $defaultRowHeight = $this->_phpSheet->getDefaultRowDimension()->getRowHeight();
-
- if ($defaultRowHeight < 0) {
- return;
- }
-
- // convert to twips
- $defaultRowHeight = (int) 20 * $defaultRowHeight;
-
- $record = 0x0225; // Record identifier
- $length = 0x0004; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vv", 1, $defaultRowHeight);
- $this->_append($header . $data);
- }
-
- /**
- * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
- */
- private function _writeDefcol()
- {
- $defaultColWidth = 8;
-
- $record = 0x0055; // Record identifier
- $length = 0x0002; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $defaultColWidth);
- $this->_append($header . $data);
- }
-
- /**
- * Write BIFF record COLINFO to define column widths
- *
- * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
- * length record.
- *
- * @param array $col_array This is the only parameter received and is composed of the following:
- * 0 => First formatted column,
- * 1 => Last formatted column,
- * 2 => Col width (8.43 is Excel default),
- * 3 => The optional XF format of the column,
- * 4 => Option flags.
- * 5 => Optional outline level
- */
- private function _writeColinfo($col_array)
- {
- if (isset($col_array[0])) {
- $colFirst = $col_array[0];
- }
- if (isset($col_array[1])) {
- $colLast = $col_array[1];
- }
- if (isset($col_array[2])) {
- $coldx = $col_array[2];
- } else {
- $coldx = 8.43;
- }
- if (isset($col_array[3])) {
- $xfIndex = $col_array[3];
- } else {
- $xfIndex = 15;
- }
- if (isset($col_array[4])) {
- $grbit = $col_array[4];
- } else {
- $grbit = 0;
- }
- if (isset($col_array[5])) {
- $level = $col_array[5];
- } else {
- $level = 0;
- }
- $record = 0x007D; // Record identifier
- $length = 0x000C; // Number of bytes to follow
-
- $coldx *= 256; // Convert to units of 1/256 of a char
-
- $ixfe = $xfIndex;
- $reserved = 0x0000; // Reserved
-
- $level = max(0, min($level, 7));
- $grbit |= $level << 8;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvvv", $colFirst, $colLast, $coldx,
- $ixfe, $grbit, $reserved);
- $this->_append($header.$data);
- }
-
- /**
- * Write BIFF record SELECTION.
- */
- private function _writeSelection()
- {
- // look up the selected cell range
- $selectedCells = $this->_phpSheet->getSelectedCells();
- $selectedCells = PHPExcel_Cell::splitRange($this->_phpSheet->getSelectedCells());
- $selectedCells = $selectedCells[0];
- if (count($selectedCells) == 2) {
- list($first, $last) = $selectedCells;
- } else {
- $first = $selectedCells[0];
- $last = $selectedCells[0];
- }
-
- list($colFirst, $rwFirst) = PHPExcel_Cell::coordinateFromString($first);
- $colFirst = PHPExcel_Cell::columnIndexFromString($colFirst) - 1; // base 0 column index
- --$rwFirst; // base 0 row index
-
- list($colLast, $rwLast) = PHPExcel_Cell::coordinateFromString($last);
- $colLast = PHPExcel_Cell::columnIndexFromString($colLast) - 1; // base 0 column index
- --$rwLast; // base 0 row index
-
- // make sure we are not out of bounds
- $colFirst = min($colFirst, 255);
- $colLast = min($colLast, 255);
-
- $rwFirst = min($rwFirst, 65535);
- $rwLast = min($rwLast, 65535);
-
- $record = 0x001D; // Record identifier
- $length = 0x000F; // Number of bytes to follow
-
- $pnn = $this->_active_pane; // Pane position
- $rwAct = $rwFirst; // Active row
- $colAct = $colFirst; // Active column
- $irefAct = 0; // Active cell ref
- $cref = 1; // Number of refs
-
- if (!isset($rwLast)) {
- $rwLast = $rwFirst; // Last row in reference
- }
- if (!isset($colLast)) {
- $colLast = $colFirst; // Last col in reference
- }
-
- // Swap last row/col for first row/col as necessary
- if ($rwFirst > $rwLast) {
- list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
- }
-
- if ($colFirst > $colLast) {
- list($colFirst, $colLast) = array($colLast, $colFirst);
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct,
- $irefAct, $cref,
- $rwFirst, $rwLast,
- $colFirst, $colLast);
- $this->_append($header . $data);
- }
-
- /**
- * Store the MERGEDCELLS records for all ranges of merged cells
- */
- private function _writeMergedCells()
- {
- $mergeCells = $this->_phpSheet->getMergeCells();
- $countMergeCells = count($mergeCells);
-
- if ($countMergeCells == 0) {
- return;
- }
-
- // maximum allowed number of merged cells per record
- $maxCountMergeCellsPerRecord = 1027;
-
- // record identifier
- $record = 0x00E5;
-
- // counter for total number of merged cells treated so far by the writer
- $i = 0;
-
- // counter for number of merged cells written in record currently being written
- $j = 0;
-
- // initialize record data
- $recordData = '';
-
- // loop through the merged cells
- foreach ($mergeCells as $mergeCell) {
- ++$i;
- ++$j;
-
- // extract the row and column indexes
- $range = PHPExcel_Cell::splitRange($mergeCell);
- list($first, $last) = $range[0];
- list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first);
- list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last);
-
- $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1);
-
- // flush record if we have reached limit for number of merged cells, or reached final merged cell
- if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
- $recordData = pack('v', $j) . $recordData;
- $length = strlen($recordData);
- $header = pack('vv', $record, $length);
- $this->_append($header . $recordData);
-
- // initialize for next record, if any
- $recordData = '';
- $j = 0;
- }
- }
- }
-
- /**
- * Write SHEETLAYOUT record
- */
- private function _writeSheetLayout()
- {
- if (!$this->_phpSheet->isTabColorSet()) {
- return;
- }
-
- $recordData = pack(
- 'vvVVVvv'
- , 0x0862
- , 0x0000 // unused
- , 0x00000000 // unused
- , 0x00000000 // unused
- , 0x00000014 // size of record data
- , $this->_colors[$this->_phpSheet->getTabColor()->getRGB()] // color index
- , 0x0000 // unused
- );
-
- $length = strlen($recordData);
-
- $record = 0x0862; // Record identifier
- $header = pack('vv', $record, $length);
- $this->_append($header . $recordData);
- }
-
- /**
- * Write SHEETPROTECTION
- */
- private function _writeSheetProtection()
- {
- // record identifier
- $record = 0x0867;
-
- // prepare options
- $options = (int) !$this->_phpSheet->getProtection()->getObjects()
- | (int) !$this->_phpSheet->getProtection()->getScenarios() << 1
- | (int) !$this->_phpSheet->getProtection()->getFormatCells() << 2
- | (int) !$this->_phpSheet->getProtection()->getFormatColumns() << 3
- | (int) !$this->_phpSheet->getProtection()->getFormatRows() << 4
- | (int) !$this->_phpSheet->getProtection()->getInsertColumns() << 5
- | (int) !$this->_phpSheet->getProtection()->getInsertRows() << 6
- | (int) !$this->_phpSheet->getProtection()->getInsertHyperlinks() << 7
- | (int) !$this->_phpSheet->getProtection()->getDeleteColumns() << 8
- | (int) !$this->_phpSheet->getProtection()->getDeleteRows() << 9
- | (int) !$this->_phpSheet->getProtection()->getSelectLockedCells() << 10
- | (int) !$this->_phpSheet->getProtection()->getSort() << 11
- | (int) !$this->_phpSheet->getProtection()->getAutoFilter() << 12
- | (int) !$this->_phpSheet->getProtection()->getPivotTables() << 13
- | (int) !$this->_phpSheet->getProtection()->getSelectUnlockedCells() << 14 ;
-
- // record data
- $recordData = pack(
- 'vVVCVVvv'
- , 0x0867 // repeated record identifier
- , 0x0000 // not used
- , 0x0000 // not used
- , 0x00 // not used
- , 0x01000200 // unknown data
- , 0xFFFFFFFF // unknown data
- , $options // options
- , 0x0000 // not used
- );
-
- $length = strlen($recordData);
- $header = pack('vv', $record, $length);
-
- $this->_append($header . $recordData);
- }
-
- /**
- * Write BIFF record RANGEPROTECTION
- *
- * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
- * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
- */
- private function _writeRangeProtection()
- {
- foreach ($this->_phpSheet->getProtectedCells() as $range => $password) {
- // number of ranges, e.g. 'A1:B3 C20:D25'
- $cellRanges = explode(' ', $range);
- $cref = count($cellRanges);
-
- $recordData = pack(
- 'vvVVvCVvVv',
- 0x0868,
- 0x00,
- 0x0000,
- 0x0000,
- 0x02,
- 0x0,
- 0x0000,
- $cref,
- 0x0000,
- 0x00
- );
-
- foreach ($cellRanges as $cellRange) {
- $recordData .= $this->_writeBIFF8CellRangeAddressFixed($cellRange);
- }
-
- // the rgbFeat structure
- $recordData .= pack(
- 'VV',
- 0x0000,
- hexdec($password)
- );
-
- $recordData .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
-
- $length = strlen($recordData);
-
- $record = 0x0868; // Record identifier
- $header = pack("vv", $record, $length);
- $this->_append($header . $recordData);
- }
- }
-
- /**
- * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
- * references in a worksheet.
- *
- * Excel only stores references to external sheets that are used in formulas.
- * For simplicity we store references to all the sheets in the workbook
- * regardless of whether they are used or not. This reduces the overall
- * complexity and eliminates the need for a two way dialogue between the formula
- * parser the worksheet objects.
- *
- * @param integer $count The number of external sheet references in this worksheet
- */
- private function _writeExterncount($count)
- {
- $record = 0x0016; // Record identifier
- $length = 0x0002; // Number of bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $count);
- $this->_append($header . $data);
- }
-
- /**
- * Writes the Excel BIFF EXTERNSHEET record. These references are used by
- * formulas. A formula references a sheet name via an index. Since we store a
- * reference to all of the external worksheets the EXTERNSHEET index is the same
- * as the worksheet index.
- *
- * @param string $sheetname The name of a external worksheet
- */
- private function _writeExternsheet($sheetname)
- {
- $record = 0x0017; // Record identifier
-
- // References to the current sheet are encoded differently to references to
- // external sheets.
- //
- if ($this->_phpSheet->getTitle() == $sheetname) {
- $sheetname = '';
- $length = 0x02; // The following 2 bytes
- $cch = 1; // The following byte
- $rgch = 0x02; // Self reference
- } else {
- $length = 0x02 + strlen($sheetname);
- $cch = strlen($sheetname);
- $rgch = 0x03; // Reference to a sheet in the current workbook
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("CC", $cch, $rgch);
- $this->_append($header . $data . $sheetname);
- }
-
- /**
- * Writes the Excel BIFF PANE record.
- * The panes can either be frozen or thawed (unfrozen).
- * Frozen panes are specified in terms of an integer number of rows and columns.
- * Thawed panes are specified in terms of Excel's units for rows and columns.
- */
- private function _writePanes()
- {
- $panes = array();
- if ($freezePane = $this->_phpSheet->getFreezePane()) {
- list($column, $row) = PHPExcel_Cell::coordinateFromString($freezePane);
- $panes[0] = $row - 1;
- $panes[1] = PHPExcel_Cell::columnIndexFromString($column) - 1;
- } else {
- // thaw panes
- return;
- }
-
- $y = isset($panes[0]) ? $panes[0] : null;
- $x = isset($panes[1]) ? $panes[1] : null;
- $rwTop = isset($panes[2]) ? $panes[2] : null;
- $colLeft = isset($panes[3]) ? $panes[3] : null;
- if (count($panes) > 4) { // if Active pane was received
- $pnnAct = $panes[4];
- } else {
- $pnnAct = null;
- }
- $record = 0x0041; // Record identifier
- $length = 0x000A; // Number of bytes to follow
-
- // Code specific to frozen or thawed panes.
- if ($this->_phpSheet->getFreezePane()) {
- // Set default values for $rwTop and $colLeft
- if (!isset($rwTop)) {
- $rwTop = $y;
- }
- if (!isset($colLeft)) {
- $colLeft = $x;
- }
- } else {
- // Set default values for $rwTop and $colLeft
- if (!isset($rwTop)) {
- $rwTop = 0;
- }
- if (!isset($colLeft)) {
- $colLeft = 0;
- }
-
- // Convert Excel's row and column units to the internal units.
- // The default row height is 12.75
- // The default column width is 8.43
- // The following slope and intersection values were interpolated.
- //
- $y = 20*$y + 255;
- $x = 113.879*$x + 390;
- }
-
-
- // Determine which pane should be active. There is also the undocumented
- // option to override this should it be necessary: may be removed later.
- //
- if (!isset($pnnAct)) {
- if ($x != 0 && $y != 0) {
- $pnnAct = 0; // Bottom right
- }
- if ($x != 0 && $y == 0) {
- $pnnAct = 1; // Top right
- }
- if ($x == 0 && $y != 0) {
- $pnnAct = 2; // Bottom left
- }
- if ($x == 0 && $y == 0) {
- $pnnAct = 3; // Top left
- }
- }
-
- $this->_active_pane = $pnnAct; // Used in _writeSelection
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
- $this->_append($header . $data);
- }
-
- /**
- * Store the page setup SETUP BIFF record.
- */
- private function _writeSetup()
- {
- $record = 0x00A1; // Record identifier
- $length = 0x0022; // Number of bytes to follow
-
- $iPaperSize = $this->_phpSheet->getPageSetup()->getPaperSize(); // Paper size
-
- $iScale = $this->_phpSheet->getPageSetup()->getScale() ?
- $this->_phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
-
- $iPageStart = 0x01; // Starting page number
- $iFitWidth = (int) $this->_phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
- $iFitHeight = (int) $this->_phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
- $grbit = 0x00; // Option flags
- $iRes = 0x0258; // Print resolution
- $iVRes = 0x0258; // Vertical print resolution
-
- $numHdr = $this->_phpSheet->getPageMargins()->getHeader(); // Header Margin
-
- $numFtr = $this->_phpSheet->getPageMargins()->getFooter(); // Footer Margin
- $iCopies = 0x01; // Number of copies
-
- $fLeftToRight = 0x0; // Print over then down
-
- // Page orientation
- $fLandscape = ($this->_phpSheet->getPageSetup()->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ?
- 0x0 : 0x1;
-
- $fNoPls = 0x0; // Setup not read from printer
- $fNoColor = 0x0; // Print black and white
- $fDraft = 0x0; // Print draft quality
- $fNotes = 0x0; // Print notes
- $fNoOrient = 0x0; // Orientation not set
- $fUsePage = 0x0; // Use custom starting page
-
- $grbit = $fLeftToRight;
- $grbit |= $fLandscape << 1;
- $grbit |= $fNoPls << 2;
- $grbit |= $fNoColor << 3;
- $grbit |= $fDraft << 4;
- $grbit |= $fNotes << 5;
- $grbit |= $fNoOrient << 6;
- $grbit |= $fUsePage << 7;
-
- $numHdr = pack("d", $numHdr);
- $numFtr = pack("d", $numFtr);
- if (self::getByteOrder()) { // if it's Big Endian
- $numHdr = strrev($numHdr);
- $numFtr = strrev($numFtr);
- }
-
- $header = pack("vv", $record, $length);
- $data1 = pack("vvvvvvvv", $iPaperSize,
- $iScale,
- $iPageStart,
- $iFitWidth,
- $iFitHeight,
- $grbit,
- $iRes,
- $iVRes);
- $data2 = $numHdr.$numFtr;
- $data3 = pack("v", $iCopies);
- $this->_append($header . $data1 . $data2 . $data3);
- }
-
- /**
- * Store the header caption BIFF record.
- */
- private function _writeHeader()
- {
- $record = 0x0014; // Record identifier
-
- /* removing for now
- // need to fix character count (multibyte!)
- if (strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
- $str = $this->_phpSheet->getHeaderFooter()->getOddHeader(); // header string
- } else {
- $str = '';
- }
- */
-
- $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddHeader());
- $length = strlen($recordData);
-
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $recordData);
- }
-
- /**
- * Store the footer caption BIFF record.
- */
- private function _writeFooter()
- {
- $record = 0x0015; // Record identifier
-
- /* removing for now
- // need to fix character count (multibyte!)
- if (strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
- $str = $this->_phpSheet->getHeaderFooter()->getOddFooter();
- } else {
- $str = '';
- }
- */
-
- $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddFooter());
- $length = strlen($recordData);
-
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $recordData);
- }
-
- /**
- * Store the horizontal centering HCENTER BIFF record.
- *
- * @access private
- */
- private function _writeHcenter()
- {
- $record = 0x0083; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fHCenter = $this->_phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fHCenter);
-
- $this->_append($header.$data);
- }
-
- /**
- * Store the vertical centering VCENTER BIFF record.
- */
- private function _writeVcenter()
- {
- $record = 0x0084; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fVCenter = $this->_phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fVCenter);
- $this->_append($header . $data);
- }
-
- /**
- * Store the LEFTMARGIN BIFF record.
- */
- private function _writeMarginLeft()
- {
- $record = 0x0026; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getLeft(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Store the RIGHTMARGIN BIFF record.
- */
- private function _writeMarginRight()
- {
- $record = 0x0027; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getRight(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Store the TOPMARGIN BIFF record.
- */
- private function _writeMarginTop()
- {
- $record = 0x0028; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getTop(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Store the BOTTOMMARGIN BIFF record.
- */
- private function _writeMarginBottom()
- {
- $record = 0x0029; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $margin = $this->_phpSheet->getPageMargins()->getBottom(); // Margin in inches
-
- $header = pack("vv", $record, $length);
- $data = pack("d", $margin);
- if (self::getByteOrder()) { // if it's Big Endian
- $data = strrev($data);
- }
-
- $this->_append($header . $data);
- }
-
- /**
- * Write the PRINTHEADERS BIFF record.
- */
- private function _writePrintHeaders()
- {
- $record = 0x002a; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fPrintRwCol = $this->_print_headers; // Boolean flag
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fPrintRwCol);
- $this->_append($header . $data);
- }
-
- /**
- * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
- * GRIDSET record.
- */
- private function _writePrintGridlines()
- {
- $record = 0x002b; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fPrintGrid);
- $this->_append($header . $data);
- }
-
- /**
- * Write the GRIDSET BIFF record. Must be used in conjunction with the
- * PRINTGRIDLINES record.
- */
- private function _writeGridset()
- {
- $record = 0x0082; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fGridSet = !$this->_phpSheet->getPrintGridlines(); // Boolean flag
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fGridSet);
- $this->_append($header . $data);
- }
-
- /**
- * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet.
- */
- private function _writeAutoFilterInfo(){
- $record = 0x009D; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $rangeBounds = PHPExcel_Cell::rangeBoundaries($this->_phpSheet->getAutoFilter()->getRange());
- $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0];
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $iNumFilters);
- $this->_append($header . $data);
- }
-
- /**
- * Write the GUTS BIFF record. This is used to configure the gutter margins
- * where Excel outline symbols are displayed. The visibility of the gutters is
- * controlled by a flag in WSBOOL.
- *
- * @see _writeWsbool()
- */
- private function _writeGuts()
- {
- $record = 0x0080; // Record identifier
- $length = 0x0008; // Bytes to follow
-
- $dxRwGut = 0x0000; // Size of row gutter
- $dxColGut = 0x0000; // Size of col gutter
-
- // determine maximum row outline level
- $maxRowOutlineLevel = 0;
- foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) {
- $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
- }
-
- $col_level = 0;
-
- // Calculate the maximum column outline level. The equivalent calculation
- // for the row outline level is carried out in _writeRow().
- $colcount = count($this->_colinfo);
- for ($i = 0; $i < $colcount; ++$i) {
- $col_level = max($this->_colinfo[$i][5], $col_level);
- }
-
- // Set the limits for the outline levels (0 <= x <= 7).
- $col_level = max(0, min($col_level, 7));
-
- // The displayed level is one greater than the max outline levels
- if ($maxRowOutlineLevel) {
- ++$maxRowOutlineLevel;
- }
- if ($col_level) {
- ++$col_level;
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
-
- $this->_append($header.$data);
- }
-
- /**
- * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
- * with the SETUP record.
- */
- private function _writeWsbool()
- {
- $record = 0x0081; // Record identifier
- $length = 0x0002; // Bytes to follow
- $grbit = 0x0000;
-
- // The only option that is of interest is the flag for fit to page. So we
- // set all the options in one go.
- //
- // Set the option flags
- $grbit |= 0x0001; // Auto page breaks visible
- if ($this->_outline_style) {
- $grbit |= 0x0020; // Auto outline styles
- }
- if ($this->_phpSheet->getShowSummaryBelow()) {
- $grbit |= 0x0040; // Outline summary below
- }
- if ($this->_phpSheet->getShowSummaryRight()) {
- $grbit |= 0x0080; // Outline summary right
- }
- if ($this->_phpSheet->getPageSetup()->getFitToPage()) {
- $grbit |= 0x0100; // Page setup fit to page
- }
- if ($this->_outline_on) {
- $grbit |= 0x0400; // Outline symbols displayed
- }
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $grbit);
- $this->_append($header . $data);
- }
-
- /**
- * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
- */
- private function _writeBreaks()
- {
- // initialize
- $vbreaks = array();
- $hbreaks = array();
-
- foreach ($this->_phpSheet->getBreaks() as $cell => $breakType) {
- // Fetch coordinates
- $coordinates = PHPExcel_Cell::coordinateFromString($cell);
-
- // Decide what to do by the type of break
- switch ($breakType) {
- case PHPExcel_Worksheet::BREAK_COLUMN:
- // Add to list of vertical breaks
- $vbreaks[] = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1;
- break;
-
- case PHPExcel_Worksheet::BREAK_ROW:
- // Add to list of horizontal breaks
- $hbreaks[] = $coordinates[1];
- break;
-
- case PHPExcel_Worksheet::BREAK_NONE:
- default:
- // Nothing to do
- break;
- }
- }
-
- //horizontal page breaks
- if (!empty($hbreaks)) {
-
- // Sort and filter array of page breaks
- sort($hbreaks, SORT_NUMERIC);
- if ($hbreaks[0] == 0) { // don't use first break if it's 0
- array_shift($hbreaks);
- }
-
- $record = 0x001b; // Record identifier
- $cbrk = count($hbreaks); // Number of page breaks
- $length = 2 + 6 * $cbrk; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $cbrk);
-
- // Append each page break
- foreach ($hbreaks as $hbreak) {
- $data .= pack("vvv", $hbreak, 0x0000, 0x00ff);
- }
-
- $this->_append($header . $data);
- }
-
- // vertical page breaks
- if (!empty($vbreaks)) {
-
- // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
- // It is slightly higher in Excel 97/200, approx. 1026
- $vbreaks = array_slice($vbreaks, 0, 1000);
-
- // Sort and filter array of page breaks
- sort($vbreaks, SORT_NUMERIC);
- if ($vbreaks[0] == 0) { // don't use first break if it's 0
- array_shift($vbreaks);
- }
-
- $record = 0x001a; // Record identifier
- $cbrk = count($vbreaks); // Number of page breaks
- $length = 2 + 6 * $cbrk; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $cbrk);
-
- // Append each page break
- foreach ($vbreaks as $vbreak) {
- $data .= pack("vvv", $vbreak, 0x0000, 0xffff);
- }
-
- $this->_append($header . $data);
- }
- }
-
- /**
- * Set the Biff PROTECT record to indicate that the worksheet is protected.
- */
- private function _writeProtect()
- {
- // Exit unless sheet protection has been specified
- if (!$this->_phpSheet->getProtection()->getSheet()) {
- return;
- }
-
- $record = 0x0012; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $fLock = 1; // Worksheet is protected
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $fLock);
-
- $this->_append($header.$data);
- }
-
- /**
- * Write SCENPROTECT
- */
- private function _writeScenProtect()
- {
- // Exit if sheet protection is not active
- if (!$this->_phpSheet->getProtection()->getSheet()) {
- return;
- }
-
- // Exit if scenarios are not protected
- if (!$this->_phpSheet->getProtection()->getScenarios()) {
- return;
- }
-
- $record = 0x00DD; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $header = pack('vv', $record, $length);
- $data = pack('v', 1);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write OBJECTPROTECT
- */
- private function _writeObjectProtect()
- {
- // Exit if sheet protection is not active
- if (!$this->_phpSheet->getProtection()->getSheet()) {
- return;
- }
-
- // Exit if objects are not protected
- if (!$this->_phpSheet->getProtection()->getObjects()) {
- return;
- }
-
- $record = 0x0063; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $header = pack('vv', $record, $length);
- $data = pack('v', 1);
-
- $this->_append($header . $data);
- }
-
- /**
- * Write the worksheet PASSWORD record.
- */
- private function _writePassword()
- {
- // Exit unless sheet protection and password have been specified
- if (!$this->_phpSheet->getProtection()->getSheet() || !$this->_phpSheet->getProtection()->getPassword()) {
- return;
- }
-
- $record = 0x0013; // Record identifier
- $length = 0x0002; // Bytes to follow
-
- $wPassword = hexdec($this->_phpSheet->getProtection()->getPassword()); // Encoded password
-
- $header = pack("vv", $record, $length);
- $data = pack("v", $wPassword);
-
- $this->_append($header . $data);
- }
-
- /**
- * Insert a 24bit bitmap image in a worksheet.
- *
- * @access public
- * @param integer $row The row we are going to insert the bitmap into
- * @param integer $col The column we are going to insert the bitmap into
- * @param mixed $bitmap The bitmap filename or GD-image resource
- * @param integer $x The horizontal position (offset) of the image inside the cell.
- * @param integer $y The vertical position (offset) of the image inside the cell.
- * @param float $scale_x The horizontal scale
- * @param float $scale_y The vertical scale
- */
- function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
- {
- $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap));
- list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap);
-
- // Scale the frame of the image.
- $width *= $scale_x;
- $height *= $scale_y;
-
- // Calculate the vertices of the image and write the OBJ record
- $this->_positionImage($col, $row, $x, $y, $width, $height);
-
- // Write the IMDATA record to store the bitmap data
- $record = 0x007f;
- $length = 8 + $size;
- $cf = 0x09;
- $env = 0x01;
- $lcb = $size;
-
- $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
- $this->_append($header.$data);
- }
-
- /**
- * Calculate the vertices that define the position of the image as required by
- * the OBJ record.
- *
- * +------------+------------+
- * | A | B |
- * +-----+------------+------------+
- * | |(x1,y1) | |
- * | 1 |(A1)._______|______ |
- * | | | | |
- * | | | | |
- * +-----+----| BITMAP |-----+
- * | | | | |
- * | 2 | |______________. |
- * | | | (B2)|
- * | | | (x2,y2)|
- * +---- +------------+------------+
- *
- * Example of a bitmap that covers some of the area from cell A1 to cell B2.
- *
- * Based on the width and height of the bitmap we need to calculate 8 vars:
- * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
- * The width and height of the cells are also variable and have to be taken into
- * account.
- * The values of $col_start and $row_start are passed in from the calling
- * function. The values of $col_end and $row_end are calculated by subtracting
- * the width and height of the bitmap from the width and height of the
- * underlying cells.
- * The vertices are expressed as a percentage of the underlying cell width as
- * follows (rhs values are in pixels):
- *
- * x1 = X / W *1024
- * y1 = Y / H *256
- * x2 = (X-1) / W *1024
- * y2 = (Y-1) / H *256
- *
- * Where: X is distance from the left side of the underlying cell
- * Y is distance from the top of the underlying cell
- * W is the width of the cell
- * H is the height of the cell
- * The SDK incorrectly states that the height should be expressed as a
- * percentage of 1024.
- *
- * @access private
- * @param integer $col_start Col containing upper left corner of object
- * @param integer $row_start Row containing top left corner of object
- * @param integer $x1 Distance to left side of object
- * @param integer $y1 Distance to top of object
- * @param integer $width Width of image frame
- * @param integer $height Height of image frame
- */
- function _positionImage($col_start, $row_start, $x1, $y1, $width, $height)
- {
- // Initialise end cell to the same as the start cell
- $col_end = $col_start; // Col containing lower right corner of object
- $row_end = $row_start; // Row containing bottom right corner of object
-
- // Zero the specified offset if greater than the cell dimensions
- if ($x1 >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) {
- $x1 = 0;
- }
- if ($y1 >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1)) {
- $y1 = 0;
- }
-
- $width = $width + $x1 -1;
- $height = $height + $y1 -1;
-
- // Subtract the underlying cell widths to find the end cell of the image
- while ($width >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) {
- $width -= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end));
- ++$col_end;
- }
-
- // Subtract the underlying cell heights to find the end cell of the image
- while ($height >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1)) {
- $height -= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1);
- ++$row_end;
- }
-
- // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
- // with zero eight or width.
- //
- if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) {
- return;
- }
- if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) {
- return;
- }
- if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) == 0) {
- return;
- }
- if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) == 0) {
- return;
- }
-
- // Convert the pixel values to the percentage value expected by Excel
- $x1 = $x1 / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024;
- $y1 = $y1 / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) * 256;
- $x2 = $width / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
- $y2 = $height / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) * 256; // Distance to bottom of object
-
- $this->_writeObjPicture($col_start, $x1,
- $row_start, $y1,
- $col_end, $x2,
- $row_end, $y2);
- }
-
- /**
- * Store the OBJ record that precedes an IMDATA record. This could be generalise
- * to support other Excel objects.
- *
- * @param integer $colL Column containing upper left corner of object
- * @param integer $dxL Distance from left side of cell
- * @param integer $rwT Row containing top left corner of object
- * @param integer $dyT Distance from top of cell
- * @param integer $colR Column containing lower right corner of object
- * @param integer $dxR Distance from right of cell
- * @param integer $rwB Row containing bottom right corner of object
- * @param integer $dyB Distance from bottom of cell
- */
- private function _writeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)
- {
- $record = 0x005d; // Record identifier
- $length = 0x003c; // Bytes to follow
-
- $cObj = 0x0001; // Count of objects in file (set to 1)
- $OT = 0x0008; // Object type. 8 = Picture
- $id = 0x0001; // Object ID
- $grbit = 0x0614; // Option flags
-
- $cbMacro = 0x0000; // Length of FMLA structure
- $Reserved1 = 0x0000; // Reserved
- $Reserved2 = 0x0000; // Reserved
-
- $icvBack = 0x09; // Background colour
- $icvFore = 0x09; // Foreground colour
- $fls = 0x00; // Fill pattern
- $fAuto = 0x00; // Automatic fill
- $icv = 0x08; // Line colour
- $lns = 0xff; // Line style
- $lnw = 0x01; // Line weight
- $fAutoB = 0x00; // Automatic border
- $frs = 0x0000; // Frame style
- $cf = 0x0009; // Image format, 9 = bitmap
- $Reserved3 = 0x0000; // Reserved
- $cbPictFmla = 0x0000; // Length of FMLA structure
- $Reserved4 = 0x0000; // Reserved
- $grbit2 = 0x0001; // Option flags
- $Reserved5 = 0x0000; // Reserved
-
-
- $header = pack("vv", $record, $length);
- $data = pack("V", $cObj);
- $data .= pack("v", $OT);
- $data .= pack("v", $id);
- $data .= pack("v", $grbit);
- $data .= pack("v", $colL);
- $data .= pack("v", $dxL);
- $data .= pack("v", $rwT);
- $data .= pack("v", $dyT);
- $data .= pack("v", $colR);
- $data .= pack("v", $dxR);
- $data .= pack("v", $rwB);
- $data .= pack("v", $dyB);
- $data .= pack("v", $cbMacro);
- $data .= pack("V", $Reserved1);
- $data .= pack("v", $Reserved2);
- $data .= pack("C", $icvBack);
- $data .= pack("C", $icvFore);
- $data .= pack("C", $fls);
- $data .= pack("C", $fAuto);
- $data .= pack("C", $icv);
- $data .= pack("C", $lns);
- $data .= pack("C", $lnw);
- $data .= pack("C", $fAutoB);
- $data .= pack("v", $frs);
- $data .= pack("V", $cf);
- $data .= pack("v", $Reserved3);
- $data .= pack("v", $cbPictFmla);
- $data .= pack("v", $Reserved4);
- $data .= pack("v", $grbit2);
- $data .= pack("V", $Reserved5);
-
- $this->_append($header . $data);
- }
-
- /**
- * Convert a GD-image into the internal format.
- *
- * @access private
- * @param resource $image The image to process
- * @return array Array with data and properties of the bitmap
- */
- function _processBitmapGd($image) {
- $width = imagesx($image);
- $height = imagesy($image);
-
- $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
- for ($j=$height; $j--; ) {
- for ($i=0; $i < $width; ++$i) {
- $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
- foreach (array("red", "green", "blue") as $key) {
- $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
- }
- $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
- }
- if (3*$width % 4) {
- $data .= str_repeat("\x00", 4 - 3*$width % 4);
- }
- }
-
- return array($width, $height, strlen($data), $data);
- }
-
- /**
- * Convert a 24 bit bitmap into the modified internal format used by Windows.
- * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
- * MSDN library.
- *
- * @access private
- * @param string $bitmap The bitmap to process
- * @return array Array with data and properties of the bitmap
- */
- function _processBitmap($bitmap)
- {
- // Open file.
- $bmp_fd = @fopen($bitmap,"rb");
- if (!$bmp_fd) {
- throw new PHPExcel_Writer_Exception("Couldn't import $bitmap");
- }
-
- // Slurp the file into a string.
- $data = fread($bmp_fd, filesize($bitmap));
-
- // Check that the file is big enough to be a bitmap.
- if (strlen($data) <= 0x36) {
- throw new PHPExcel_Writer_Exception("$bitmap doesn't contain enough data.\n");
- }
-
- // The first 2 bytes are used to identify the bitmap.
- $identity = unpack("A2ident", $data);
- if ($identity['ident'] != "BM") {
- throw new PHPExcel_Writer_Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
- }
-
- // Remove bitmap data: ID.
- $data = substr($data, 2);
-
- // Read and remove the bitmap size. This is more reliable than reading
- // the data size at offset 0x22.
- //
- $size_array = unpack("Vsa", substr($data, 0, 4));
- $size = $size_array['sa'];
- $data = substr($data, 4);
- $size -= 0x36; // Subtract size of bitmap header.
- $size += 0x0C; // Add size of BIFF header.
-
- // Remove bitmap data: reserved, offset, header length.
- $data = substr($data, 12);
-
- // Read and remove the bitmap width and height. Verify the sizes.
- $width_and_height = unpack("V2", substr($data, 0, 8));
- $width = $width_and_height[1];
- $height = $width_and_height[2];
- $data = substr($data, 8);
- if ($width > 0xFFFF) {
- throw new PHPExcel_Writer_Exception("$bitmap: largest image width supported is 65k.\n");
- }
- if ($height > 0xFFFF) {
- throw new PHPExcel_Writer_Exception("$bitmap: largest image height supported is 65k.\n");
- }
-
- // Read and remove the bitmap planes and bpp data. Verify them.
- $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
- $data = substr($data, 4);
- if ($planes_and_bitcount[2] != 24) { // Bitcount
- throw new PHPExcel_Writer_Exception("$bitmap isn't a 24bit true color bitmap.\n");
- }
- if ($planes_and_bitcount[1] != 1) {
- throw new PHPExcel_Writer_Exception("$bitmap: only 1 plane supported in bitmap image.\n");
- }
-
- // Read and remove the bitmap compression. Verify compression.
- $compression = unpack("Vcomp", substr($data, 0, 4));
- $data = substr($data, 4);
-
- //$compression = 0;
- if ($compression['comp'] != 0) {
- throw new PHPExcel_Writer_Exception("$bitmap: compression not supported in bitmap image.\n");
- }
-
- // Remove bitmap data: data size, hres, vres, colours, imp. colours.
- $data = substr($data, 20);
-
- // Add the BITMAPCOREHEADER data
- $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
- $data = $header . $data;
-
- return (array($width, $height, $size, $data));
- }
-
- /**
- * Store the window zoom factor. This should be a reduced fraction but for
- * simplicity we will store all fractions with a numerator of 100.
- */
- private function _writeZoom()
- {
- // If scale is 100 we don't need to write a record
- if ($this->_phpSheet->getSheetView()->getZoomScale() == 100) {
- return;
- }
-
- $record = 0x00A0; // Record identifier
- $length = 0x0004; // Bytes to follow
-
- $header = pack("vv", $record, $length);
- $data = pack("vv", $this->_phpSheet->getSheetView()->getZoomScale(), 100);
- $this->_append($header . $data);
- }
-
- /**
- * Get Escher object
- *
- * @return PHPExcel_Shared_Escher
- */
- public function getEscher()
- {
- return $this->_escher;
- }
-
- /**
- * Set Escher object
- *
- * @param PHPExcel_Shared_Escher $pValue
- */
- public function setEscher(PHPExcel_Shared_Escher $pValue = null)
- {
- $this->_escher = $pValue;
- }
-
- /**
- * Write MSODRAWING record
- */
- private function _writeMsoDrawing()
- {
- // write the Escher stream if necessary
- if (isset($this->_escher)) {
- $writer = new PHPExcel_Writer_Excel5_Escher($this->_escher);
- $data = $writer->close();
- $spOffsets = $writer->getSpOffsets();
- $spTypes = $writer->getSpTypes();
- // write the neccesary MSODRAWING, OBJ records
-
- // split the Escher stream
- $spOffsets[0] = 0;
- $nm = count($spOffsets) - 1; // number of shapes excluding first shape
- for ($i = 1; $i <= $nm; ++$i) {
- // MSODRAWING record
- $record = 0x00EC; // Record identifier
-
- // chunk of Escher stream for one shape
- $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);
-
- $length = strlen($dataChunk);
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $dataChunk);
-
- // OBJ record
- $record = 0x005D; // record identifier
- $objData = '';
-
- // ftCmo
- if($spTypes[$i] == 0x00C9){
- // Add ftCmo (common object data) subobject
- $objData .=
- pack('vvvvvVVV'
- , 0x0015 // 0x0015 = ftCmo
- , 0x0012 // length of ftCmo data
- , 0x0014 // object type, 0x0014 = filter
- , $i // object id number, Excel seems to use 1-based index, local for the sheet
- , 0x2101 // option flags, 0x2001 is what OpenOffice.org uses
- , 0 // reserved
- , 0 // reserved
- , 0 // reserved
- );
-
- // Add ftSbs Scroll bar subobject
- $objData .= pack('vv', 0x00C, 0x0014);
- $objData .= pack('H*', '0000000000000000640001000A00000010000100');
- // Add ftLbsData (List box data) subobject
- $objData .= pack('vv', 0x0013, 0x1FEE);
- $objData .= pack('H*', '00000000010001030000020008005700');
- }
- else {
- // Add ftCmo (common object data) subobject
- $objData .=
- pack('vvvvvVVV'
- , 0x0015 // 0x0015 = ftCmo
- , 0x0012 // length of ftCmo data
- , 0x0008 // object type, 0x0008 = picture
- , $i // object id number, Excel seems to use 1-based index, local for the sheet
- , 0x6011 // option flags, 0x6011 is what OpenOffice.org uses
- , 0 // reserved
- , 0 // reserved
- , 0 // reserved
- );
- }
-
- // ftEnd
- $objData .=
- pack('vv'
- , 0x0000 // 0x0000 = ftEnd
- , 0x0000 // length of ftEnd data
- );
-
- $length = strlen($objData);
- $header = pack('vv', $record, $length);
- $this->_append($header . $objData);
- }
- }
- }
-
- /**
- * Store the DATAVALIDATIONS and DATAVALIDATION records.
- */
- private function _writeDataValidity()
- {
- // Datavalidation collection
- $dataValidationCollection = $this->_phpSheet->getDataValidationCollection();
-
- // Write data validations?
- if (!empty($dataValidationCollection)) {
-
- // DATAVALIDATIONS record
- $record = 0x01B2; // Record identifier
- $length = 0x0012; // Bytes to follow
-
- $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
- $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
- $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
- $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
-
- $header = pack('vv', $record, $length);
- $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId,
- count($dataValidationCollection));
- $this->_append($header.$data);
-
- // DATAVALIDATION records
- $record = 0x01BE; // Record identifier
-
- foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
- // initialize record data
- $data = '';
-
- // options
- $options = 0x00000000;
-
- // data type
- $type = $dataValidation->getType();
- switch ($type) {
- case PHPExcel_Cell_DataValidation::TYPE_NONE: $type = 0x00; break;
- case PHPExcel_Cell_DataValidation::TYPE_WHOLE: $type = 0x01; break;
- case PHPExcel_Cell_DataValidation::TYPE_DECIMAL: $type = 0x02; break;
- case PHPExcel_Cell_DataValidation::TYPE_LIST: $type = 0x03; break;
- case PHPExcel_Cell_DataValidation::TYPE_DATE: $type = 0x04; break;
- case PHPExcel_Cell_DataValidation::TYPE_TIME: $type = 0x05; break;
- case PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH: $type = 0x06; break;
- case PHPExcel_Cell_DataValidation::TYPE_CUSTOM: $type = 0x07; break;
- }
- $options |= $type << 0;
-
- // error style
- $errorStyle = $dataValidation->getType();
- switch ($errorStyle) {
- case PHPExcel_Cell_DataValidation::STYLE_STOP: $errorStyle = 0x00; break;
- case PHPExcel_Cell_DataValidation::STYLE_WARNING: $errorStyle = 0x01; break;
- case PHPExcel_Cell_DataValidation::STYLE_INFORMATION: $errorStyle = 0x02; break;
- }
- $options |= $errorStyle << 4;
-
- // explicit formula?
- if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
- $options |= 0x01 << 7;
- }
-
- // empty cells allowed
- $options |= $dataValidation->getAllowBlank() << 8;
-
- // show drop down
- $options |= (!$dataValidation->getShowDropDown()) << 9;
-
- // show input message
- $options |= $dataValidation->getShowInputMessage() << 18;
-
- // show error message
- $options |= $dataValidation->getShowErrorMessage() << 19;
-
- // condition operator
- $operator = $dataValidation->getOperator();
- switch ($operator) {
- case PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN: $operator = 0x00 ; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN: $operator = 0x01 ; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_EQUAL: $operator = 0x02 ; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL: $operator = 0x03 ; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN: $operator = 0x04 ; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN: $operator = 0x05 ; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL: $operator = 0x06; break;
- case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL: $operator = 0x07 ; break;
- }
- $options |= $operator << 20;
-
- $data = pack('V', $options);
-
- // prompt title
- $promptTitle = $dataValidation->getPromptTitle() !== '' ?
- $dataValidation->getPromptTitle() : chr(0);
- $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($promptTitle);
-
- // error title
- $errorTitle = $dataValidation->getErrorTitle() !== '' ?
- $dataValidation->getErrorTitle() : chr(0);
- $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($errorTitle);
-
- // prompt text
- $prompt = $dataValidation->getPrompt() !== '' ?
- $dataValidation->getPrompt() : chr(0);
- $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($prompt);
-
- // error text
- $error = $dataValidation->getError() !== '' ?
- $dataValidation->getError() : chr(0);
- $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($error);
-
- // formula 1
- try {
- $formula1 = $dataValidation->getFormula1();
- if ($type == 0x03) { // list type
- $formula1 = str_replace(',', chr(0), $formula1);
- }
- $this->_parser->parse($formula1);
- $formula1 = $this->_parser->toReversePolish();
- $sz1 = strlen($formula1);
-
- } catch(PHPExcel_Exception $e) {
- $sz1 = 0;
- $formula1 = '';
- }
- $data .= pack('vv', $sz1, 0x0000);
- $data .= $formula1;
-
- // formula 2
- try {
- $formula2 = $dataValidation->getFormula2();
- if ($formula2 === '') {
- throw new PHPExcel_Writer_Exception('No formula2');
- }
- $this->_parser->parse($formula2);
- $formula2 = $this->_parser->toReversePolish();
- $sz2 = strlen($formula2);
-
- } catch(PHPExcel_Exception $e) {
- $sz2 = 0;
- $formula2 = '';
- }
- $data .= pack('vv', $sz2, 0x0000);
- $data .= $formula2;
-
- // cell range address list
- $data .= pack('v', 0x0001);
- $data .= $this->_writeBIFF8CellRangeAddressFixed($cellCoordinate);
-
- $length = strlen($data);
- $header = pack("vv", $record, $length);
-
- $this->_append($header . $data);
- }
- }
- }
-
- /**
- * Map Error code
- *
- * @param string $errorCode
- * @return int
- */
- private static function _mapErrorCode($errorCode) {
- switch ($errorCode) {
- case '#NULL!': return 0x00;
- case '#DIV/0!': return 0x07;
- case '#VALUE!': return 0x0F;
- case '#REF!': return 0x17;
- case '#NAME?': return 0x1D;
- case '#NUM!': return 0x24;
- case '#N/A': return 0x2A;
- }
-
- return 0;
- }
-
- /**
- * Write PLV Record
- */
- private function _writePageLayoutView(){
- $record = 0x088B; // Record identifier
- $length = 0x0010; // Bytes to follow
-
- $rt = 0x088B; // 2
- $grbitFrt = 0x0000; // 2
- $reserved = 0x0000000000000000; // 8
- $wScalvePLV = $this->_phpSheet->getSheetView()->getZoomScale(); // 2
-
- // The options flags that comprise $grbit
- if($this->_phpSheet->getSheetView()->getView() == PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT){
- $fPageLayoutView = 1;
- } else {
- $fPageLayoutView = 0;
- }
- $fRulerVisible = 0;
- $fWhitespaceHidden = 0;
-
- $grbit = $fPageLayoutView; // 2
- $grbit |= $fRulerVisible << 1;
- $grbit |= $fWhitespaceHidden << 3;
-
- $header = pack("vv", $record, $length);
- $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit);
- $this->_append($header . $data);
- }
-
- /**
- * Write CFRule Record
- * @param PHPExcel_Style_Conditional $conditional
- */
- private function _writeCFRule(PHPExcel_Style_Conditional $conditional){
- $record = 0x01B1; // Record identifier
-
- // $type : Type of the CF
- // $operatorType : Comparison operator
- if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION){
- $type = 0x02;
- $operatorType = 0x00;
- } else if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS){
- $type = 0x01;
-
- switch ($conditional->getOperatorType()){
- case PHPExcel_Style_Conditional::OPERATOR_NONE:
- $operatorType = 0x00;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_EQUAL:
- $operatorType = 0x03;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_GREATERTHAN:
- $operatorType = 0x05;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_GREATERTHANOREQUAL:
- $operatorType = 0x07;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_LESSTHAN:
- $operatorType = 0x06;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_LESSTHANOREQUAL:
- $operatorType = 0x08;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_NOTEQUAL:
- $operatorType = 0x04;
- break;
- case PHPExcel_Style_Conditional::OPERATOR_BETWEEN:
- $operatorType = 0x01;
- break;
- // not OPERATOR_NOTBETWEEN 0x02
- }
- }
-
- // $szValue1 : size of the formula data for first value or formula
- // $szValue2 : size of the formula data for second value or formula
- $arrConditions = $conditional->getConditions();
- $numConditions = sizeof($arrConditions);
- if($numConditions == 1){
- $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
- $szValue2 = 0x0000;
- $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
- $operand2 = null;
- } else if($numConditions == 2 && ($conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BETWEEN)){
- $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
- $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000);
- $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
- $operand2 = pack('Cv', 0x1E, $arrConditions[1]);
- } else {
- $szValue1 = 0x0000;
- $szValue2 = 0x0000;
- $operand1 = null;
- $operand2 = null;
- }
-
- // $flags : Option flags
- // Alignment
- $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0);
- $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0);
- $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0);
- $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0);
- $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0);
- $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0);
- if($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0){
- $bFormatAlign = 1;
- } else {
- $bFormatAlign = 0;
- }
- // Protection
- $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0);
- $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0);
- if($bProtLocked == 0 || $bProtHidden == 0){
- $bFormatProt = 1;
- } else {
- $bFormatProt = 0;
- }
- // Border
- $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
- $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
- $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
- $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
- && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
- if($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0){
- $bFormatBorder = 1;
- } else {
- $bFormatBorder = 0;
- }
- // Pattern
- $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1);
- $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1);
- $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1);
- if($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0){
- $bFormatFill = 1;
- } else {
- $bFormatFill = 0;
- }
- // Font
- if($conditional->getStyle()->getFont()->getName() != null
- || $conditional->getStyle()->getFont()->getSize() != null
- || $conditional->getStyle()->getFont()->getBold() != null
- || $conditional->getStyle()->getFont()->getItalic() != null
- || $conditional->getStyle()->getFont()->getSuperScript() != null
- || $conditional->getStyle()->getFont()->getSubScript() != null
- || $conditional->getStyle()->getFont()->getUnderline() != null
- || $conditional->getStyle()->getFont()->getStrikethrough() != null
- || $conditional->getStyle()->getFont()->getColor()->getARGB() != null){
- $bFormatFont = 1;
- } else {
- $bFormatFont = 0;
- }
- // Alignment
- $flags = 0;
- $flags |= (1 == $bAlignHz ? 0x00000001 : 0);
- $flags |= (1 == $bAlignVt ? 0x00000002 : 0);
- $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0);
- $flags |= (1 == $bTxRotation ? 0x00000008 : 0);
- // Justify last line flag
- $flags |= (1 == 1 ? 0x00000010 : 0);
- $flags |= (1 == $bIndent ? 0x00000020 : 0);
- $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0);
- // Default
- $flags |= (1 == 1 ? 0x00000080 : 0);
- // Protection
- $flags |= (1 == $bProtLocked ? 0x00000100 : 0);
- $flags |= (1 == $bProtHidden ? 0x00000200 : 0);
- // Border
- $flags |= (1 == $bBorderLeft ? 0x00000400 : 0);
- $flags |= (1 == $bBorderRight ? 0x00000800 : 0);
- $flags |= (1 == $bBorderTop ? 0x00001000 : 0);
- $flags |= (1 == $bBorderBottom ? 0x00002000 : 0);
- $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border
- $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border
- // Pattern
- $flags |= (1 == $bFillStyle ? 0x00010000 : 0);
- $flags |= (1 == $bFillColor ? 0x00020000 : 0);
- $flags |= (1 == $bFillColorBg ? 0x00040000 : 0);
- $flags |= (1 == 1 ? 0x00380000 : 0);
- // Font
- $flags |= (1 == $bFormatFont ? 0x04000000 : 0);
- // Alignment :
- $flags |= (1 == $bFormatAlign ? 0x08000000 : 0);
- // Border
- $flags |= (1 == $bFormatBorder ? 0x10000000 : 0);
- // Pattern
- $flags |= (1 == $bFormatFill ? 0x20000000 : 0);
- // Protection
- $flags |= (1 == $bFormatProt ? 0x40000000 : 0);
- // Text direction
- $flags |= (1 == 0 ? 0x80000000 : 0);
-
- // Data Blocks
- if($bFormatFont == 1){
- // Font Name
- if($conditional->getStyle()->getFont()->getName() == null){
- $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
- $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
- } else {
- $dataBlockFont = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName());
- }
- // Font Size
- if($conditional->getStyle()->getFont()->getSize() == null){
- $dataBlockFont .= pack('V', 20 * 11);
- } else {
- $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize());
- }
- // Font Options
- $dataBlockFont .= pack('V', 0);
- // Font weight
- if($conditional->getStyle()->getFont()->getBold() == true){
- $dataBlockFont .= pack('v', 0x02BC);
- } else {
- $dataBlockFont .= pack('v', 0x0190);
- }
- // Escapement type
- if($conditional->getStyle()->getFont()->getSubScript() == true){
- $dataBlockFont .= pack('v', 0x02);
- $fontEscapement = 0;
- } else if($conditional->getStyle()->getFont()->getSuperScript() == true){
- $dataBlockFont .= pack('v', 0x01);
- $fontEscapement = 0;
- } else {
- $dataBlockFont .= pack('v', 0x00);
- $fontEscapement = 1;
- }
- // Underline type
- switch ($conditional->getStyle()->getFont()->getUnderline()){
- case PHPExcel_Style_Font::UNDERLINE_NONE : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 0; break;
- case PHPExcel_Style_Font::UNDERLINE_DOUBLE : $dataBlockFont .= pack('C', 0x02); $fontUnderline = 0; break;
- case PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING : $dataBlockFont .= pack('C', 0x22); $fontUnderline = 0; break;
- case PHPExcel_Style_Font::UNDERLINE_SINGLE : $dataBlockFont .= pack('C', 0x01); $fontUnderline = 0; break;
- case PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING : $dataBlockFont .= pack('C', 0x21); $fontUnderline = 0; break;
- default : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 1; break;
- }
- // Not used (3)
- $dataBlockFont .= pack('vC', 0x0000, 0x00);
- // Font color index
- switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) {
- case '000000': $colorIdx = 0x08; break;
- case 'FFFFFF': $colorIdx = 0x09; break;
- case 'FF0000': $colorIdx = 0x0A; break;
- case '00FF00': $colorIdx = 0x0B; break;
- case '0000FF': $colorIdx = 0x0C; break;
- case 'FFFF00': $colorIdx = 0x0D; break;
- case 'FF00FF': $colorIdx = 0x0E; break;
- case '00FFFF': $colorIdx = 0x0F; break;
- case '800000': $colorIdx = 0x10; break;
- case '008000': $colorIdx = 0x11; break;
- case '000080': $colorIdx = 0x12; break;
- case '808000': $colorIdx = 0x13; break;
- case '800080': $colorIdx = 0x14; break;
- case '008080': $colorIdx = 0x15; break;
- case 'C0C0C0': $colorIdx = 0x16; break;
- case '808080': $colorIdx = 0x17; break;
- case '9999FF': $colorIdx = 0x18; break;
- case '993366': $colorIdx = 0x19; break;
- case 'FFFFCC': $colorIdx = 0x1A; break;
- case 'CCFFFF': $colorIdx = 0x1B; break;
- case '660066': $colorIdx = 0x1C; break;
- case 'FF8080': $colorIdx = 0x1D; break;
- case '0066CC': $colorIdx = 0x1E; break;
- case 'CCCCFF': $colorIdx = 0x1F; break;
- case '000080': $colorIdx = 0x20; break;
- case 'FF00FF': $colorIdx = 0x21; break;
- case 'FFFF00': $colorIdx = 0x22; break;
- case '00FFFF': $colorIdx = 0x23; break;
- case '800080': $colorIdx = 0x24; break;
- case '800000': $colorIdx = 0x25; break;
- case '008080': $colorIdx = 0x26; break;
- case '0000FF': $colorIdx = 0x27; break;
- case '00CCFF': $colorIdx = 0x28; break;
- case 'CCFFFF': $colorIdx = 0x29; break;
- case 'CCFFCC': $colorIdx = 0x2A; break;
- case 'FFFF99': $colorIdx = 0x2B; break;
- case '99CCFF': $colorIdx = 0x2C; break;
- case 'FF99CC': $colorIdx = 0x2D; break;
- case 'CC99FF': $colorIdx = 0x2E; break;
- case 'FFCC99': $colorIdx = 0x2F; break;
- case '3366FF': $colorIdx = 0x30; break;
- case '33CCCC': $colorIdx = 0x31; break;
- case '99CC00': $colorIdx = 0x32; break;
- case 'FFCC00': $colorIdx = 0x33; break;
- case 'FF9900': $colorIdx = 0x34; break;
- case 'FF6600': $colorIdx = 0x35; break;
- case '666699': $colorIdx = 0x36; break;
- case '969696': $colorIdx = 0x37; break;
- case '003366': $colorIdx = 0x38; break;
- case '339966': $colorIdx = 0x39; break;
- case '003300': $colorIdx = 0x3A; break;
- case '333300': $colorIdx = 0x3B; break;
- case '993300': $colorIdx = 0x3C; break;
- case '993366': $colorIdx = 0x3D; break;
- case '333399': $colorIdx = 0x3E; break;
- case '333333': $colorIdx = 0x3F; break;
- default: $colorIdx = 0x00; break;
- }
- $dataBlockFont .= pack('V', $colorIdx);
- // Not used (4)
- $dataBlockFont .= pack('V', 0x00000000);
- // Options flags for modified font attributes
- $optionsFlags = 0;
- $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0);
- $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0);
- $optionsFlags |= (1 == 1 ? 0x00000008 : 0);
- $optionsFlags |= (1 == 1 ? 0x00000010 : 0);
- $optionsFlags |= (1 == 0 ? 0x00000020 : 0);
- $optionsFlags |= (1 == 1 ? 0x00000080 : 0);
- $dataBlockFont .= pack('V', $optionsFlags);
- // Escapement type
- $dataBlockFont .= pack('V', $fontEscapement);
- // Underline type
- $dataBlockFont .= pack('V', $fontUnderline);
- // Always
- $dataBlockFont .= pack('V', 0x00000000);
- // Always
- $dataBlockFont .= pack('V', 0x00000000);
- // Not used (8)
- $dataBlockFont .= pack('VV', 0x00000000, 0x00000000);
- // Always
- $dataBlockFont .= pack('v', 0x0001);
- }
- if($bFormatAlign == 1){
- $blockAlign = 0;
- // Alignment and text break
- switch ($conditional->getStyle()->getAlignment()->getHorizontal()){
- case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL : $blockAlign = 0; break;
- case PHPExcel_Style_Alignment::HORIZONTAL_LEFT : $blockAlign = 1; break;
- case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT : $blockAlign = 3; break;
- case PHPExcel_Style_Alignment::HORIZONTAL_CENTER : $blockAlign = 2; break;
- case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS : $blockAlign = 6; break;
- case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY : $blockAlign = 5; break;
- }
- if($conditional->getStyle()->getAlignment()->getWrapText() == true){
- $blockAlign |= 1 << 3;
- } else {
- $blockAlign |= 0 << 3;
- }
- switch ($conditional->getStyle()->getAlignment()->getVertical()){
- case PHPExcel_Style_Alignment::VERTICAL_BOTTOM : $blockAlign = 2 << 4; break;
- case PHPExcel_Style_Alignment::VERTICAL_TOP : $blockAlign = 0 << 4; break;
- case PHPExcel_Style_Alignment::VERTICAL_CENTER : $blockAlign = 1 << 4; break;
- case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY : $blockAlign = 3 << 4; break;
- }
- $blockAlign |= 0 << 7;
-
- // Text rotation angle
- $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation();
-
- // Indentation
- $blockIndent = $conditional->getStyle()->getAlignment()->getIndent();
- if($conditional->getStyle()->getAlignment()->getShrinkToFit() == true){
- $blockIndent |= 1 << 4;
- } else {
- $blockIndent |= 0 << 4;
- }
- $blockIndent |= 0 << 6;
-
- // Relative indentation
- $blockIndentRelative = 255;
-
- $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000);
- }
- if($bFormatBorder == 1){
- $blockLineStyle = 0;
- switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()){
- case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00; break;
- case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01; break;
- case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02; break;
- case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03; break;
- case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04; break;
- case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05; break;
- case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06; break;
- case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08; break;
- case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A; break;
- case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C; break;
- case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D; break;
- }
- switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()){
- case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 4; break;
- case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 4; break;
- case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 4; break;
- case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 4; break;
- case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 4; break;
- case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 4; break;
- case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 4; break;
- case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 4; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 4; break;
- case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 4; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 4; break;
- case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 4; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 4; break;
- case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 4; break;
- }
- switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()){
- case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 8; break;
- case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 8; break;
- case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 8; break;
- case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 8; break;
- case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 8; break;
- case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 8; break;
- case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 8; break;
- case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 8; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 8; break;
- case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 8; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 8; break;
- case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 8; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 8; break;
- case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 8; break;
- }
- switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()){
- case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 12; break;
- case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 12; break;
- case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 12; break;
- case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 12; break;
- case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 12; break;
- case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 12; break;
- case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 12; break;
- case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 12; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 12; break;
- case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 12; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 12; break;
- case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 12; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 12; break;
- case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 12; break;
- }
- //@todo _writeCFRule() => $blockLineStyle => Index Color for left line
- //@todo _writeCFRule() => $blockLineStyle => Index Color for right line
- //@todo _writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off
- //@todo _writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off
- $blockColor = 0;
- //@todo _writeCFRule() => $blockColor => Index Color for top line
- //@todo _writeCFRule() => $blockColor => Index Color for bottom line
- //@todo _writeCFRule() => $blockColor => Index Color for diagonal line
- switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()){
- case PHPExcel_Style_Border::BORDER_NONE : $blockColor |= 0x00 << 21; break;
- case PHPExcel_Style_Border::BORDER_THIN : $blockColor |= 0x01 << 21; break;
- case PHPExcel_Style_Border::BORDER_MEDIUM : $blockColor |= 0x02 << 21; break;
- case PHPExcel_Style_Border::BORDER_DASHED : $blockColor |= 0x03 << 21; break;
- case PHPExcel_Style_Border::BORDER_DOTTED : $blockColor |= 0x04 << 21; break;
- case PHPExcel_Style_Border::BORDER_THICK : $blockColor |= 0x05 << 21; break;
- case PHPExcel_Style_Border::BORDER_DOUBLE : $blockColor |= 0x06 << 21; break;
- case PHPExcel_Style_Border::BORDER_HAIR : $blockColor |= 0x07 << 21; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockColor |= 0x08 << 21; break;
- case PHPExcel_Style_Border::BORDER_DASHDOT : $blockColor |= 0x09 << 21; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockColor |= 0x0A << 21; break;
- case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockColor |= 0x0B << 21; break;
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockColor |= 0x0C << 21; break;
- case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockColor |= 0x0D << 21; break;
- }
- $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor);
- }
- if($bFormatFill == 1){
- // Fill Patern Style
- $blockFillPatternStyle = 0;
- switch ($conditional->getStyle()->getFill()->getFillType()){
- case PHPExcel_Style_Fill::FILL_NONE : $blockFillPatternStyle = 0x00; break;
- case PHPExcel_Style_Fill::FILL_SOLID : $blockFillPatternStyle = 0x01; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY : $blockFillPatternStyle = 0x02; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY : $blockFillPatternStyle = 0x03; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY : $blockFillPatternStyle = 0x04; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL : $blockFillPatternStyle = 0x05; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL : $blockFillPatternStyle = 0x06; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN : $blockFillPatternStyle = 0x07; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKUP : $blockFillPatternStyle = 0x08; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID : $blockFillPatternStyle = 0x09; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS : $blockFillPatternStyle = 0x0A; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL : $blockFillPatternStyle = 0x0B; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL : $blockFillPatternStyle = 0x0C; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN : $blockFillPatternStyle = 0x0D; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP : $blockFillPatternStyle = 0x0E; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID : $blockFillPatternStyle = 0x0F; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS : $blockFillPatternStyle = 0x10; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_GRAY125 : $blockFillPatternStyle = 0x11; break;
- case PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625 : $blockFillPatternStyle = 0x12; break;
- case PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8
- case PHPExcel_Style_Fill::FILL_GRADIENT_PATH : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8
- default : $blockFillPatternStyle = 0x00; break;
- }
- // Color
- switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) {
- case '000000': $colorIdxBg = 0x08; break;
- case 'FFFFFF': $colorIdxBg = 0x09; break;
- case 'FF0000': $colorIdxBg = 0x0A; break;
- case '00FF00': $colorIdxBg = 0x0B; break;
- case '0000FF': $colorIdxBg = 0x0C; break;
- case 'FFFF00': $colorIdxBg = 0x0D; break;
- case 'FF00FF': $colorIdxBg = 0x0E; break;
- case '00FFFF': $colorIdxBg = 0x0F; break;
- case '800000': $colorIdxBg = 0x10; break;
- case '008000': $colorIdxBg = 0x11; break;
- case '000080': $colorIdxBg = 0x12; break;
- case '808000': $colorIdxBg = 0x13; break;
- case '800080': $colorIdxBg = 0x14; break;
- case '008080': $colorIdxBg = 0x15; break;
- case 'C0C0C0': $colorIdxBg = 0x16; break;
- case '808080': $colorIdxBg = 0x17; break;
- case '9999FF': $colorIdxBg = 0x18; break;
- case '993366': $colorIdxBg = 0x19; break;
- case 'FFFFCC': $colorIdxBg = 0x1A; break;
- case 'CCFFFF': $colorIdxBg = 0x1B; break;
- case '660066': $colorIdxBg = 0x1C; break;
- case 'FF8080': $colorIdxBg = 0x1D; break;
- case '0066CC': $colorIdxBg = 0x1E; break;
- case 'CCCCFF': $colorIdxBg = 0x1F; break;
- case '000080': $colorIdxBg = 0x20; break;
- case 'FF00FF': $colorIdxBg = 0x21; break;
- case 'FFFF00': $colorIdxBg = 0x22; break;
- case '00FFFF': $colorIdxBg = 0x23; break;
- case '800080': $colorIdxBg = 0x24; break;
- case '800000': $colorIdxBg = 0x25; break;
- case '008080': $colorIdxBg = 0x26; break;
- case '0000FF': $colorIdxBg = 0x27; break;
- case '00CCFF': $colorIdxBg = 0x28; break;
- case 'CCFFFF': $colorIdxBg = 0x29; break;
- case 'CCFFCC': $colorIdxBg = 0x2A; break;
- case 'FFFF99': $colorIdxBg = 0x2B; break;
- case '99CCFF': $colorIdxBg = 0x2C; break;
- case 'FF99CC': $colorIdxBg = 0x2D; break;
- case 'CC99FF': $colorIdxBg = 0x2E; break;
- case 'FFCC99': $colorIdxBg = 0x2F; break;
- case '3366FF': $colorIdxBg = 0x30; break;
- case '33CCCC': $colorIdxBg = 0x31; break;
- case '99CC00': $colorIdxBg = 0x32; break;
- case 'FFCC00': $colorIdxBg = 0x33; break;
- case 'FF9900': $colorIdxBg = 0x34; break;
- case 'FF6600': $colorIdxBg = 0x35; break;
- case '666699': $colorIdxBg = 0x36; break;
- case '969696': $colorIdxBg = 0x37; break;
- case '003366': $colorIdxBg = 0x38; break;
- case '339966': $colorIdxBg = 0x39; break;
- case '003300': $colorIdxBg = 0x3A; break;
- case '333300': $colorIdxBg = 0x3B; break;
- case '993300': $colorIdxBg = 0x3C; break;
- case '993366': $colorIdxBg = 0x3D; break;
- case '333399': $colorIdxBg = 0x3E; break;
- case '333333': $colorIdxBg = 0x3F; break;
- default: $colorIdxBg = 0x41; break;
- }
- // Fg Color
- switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) {
- case '000000': $colorIdxFg = 0x08; break;
- case 'FFFFFF': $colorIdxFg = 0x09; break;
- case 'FF0000': $colorIdxFg = 0x0A; break;
- case '00FF00': $colorIdxFg = 0x0B; break;
- case '0000FF': $colorIdxFg = 0x0C; break;
- case 'FFFF00': $colorIdxFg = 0x0D; break;
- case 'FF00FF': $colorIdxFg = 0x0E; break;
- case '00FFFF': $colorIdxFg = 0x0F; break;
- case '800000': $colorIdxFg = 0x10; break;
- case '008000': $colorIdxFg = 0x11; break;
- case '000080': $colorIdxFg = 0x12; break;
- case '808000': $colorIdxFg = 0x13; break;
- case '800080': $colorIdxFg = 0x14; break;
- case '008080': $colorIdxFg = 0x15; break;
- case 'C0C0C0': $colorIdxFg = 0x16; break;
- case '808080': $colorIdxFg = 0x17; break;
- case '9999FF': $colorIdxFg = 0x18; break;
- case '993366': $colorIdxFg = 0x19; break;
- case 'FFFFCC': $colorIdxFg = 0x1A; break;
- case 'CCFFFF': $colorIdxFg = 0x1B; break;
- case '660066': $colorIdxFg = 0x1C; break;
- case 'FF8080': $colorIdxFg = 0x1D; break;
- case '0066CC': $colorIdxFg = 0x1E; break;
- case 'CCCCFF': $colorIdxFg = 0x1F; break;
- case '000080': $colorIdxFg = 0x20; break;
- case 'FF00FF': $colorIdxFg = 0x21; break;
- case 'FFFF00': $colorIdxFg = 0x22; break;
- case '00FFFF': $colorIdxFg = 0x23; break;
- case '800080': $colorIdxFg = 0x24; break;
- case '800000': $colorIdxFg = 0x25; break;
- case '008080': $colorIdxFg = 0x26; break;
- case '0000FF': $colorIdxFg = 0x27; break;
- case '00CCFF': $colorIdxFg = 0x28; break;
- case 'CCFFFF': $colorIdxFg = 0x29; break;
- case 'CCFFCC': $colorIdxFg = 0x2A; break;
- case 'FFFF99': $colorIdxFg = 0x2B; break;
- case '99CCFF': $colorIdxFg = 0x2C; break;
- case 'FF99CC': $colorIdxFg = 0x2D; break;
- case 'CC99FF': $colorIdxFg = 0x2E; break;
- case 'FFCC99': $colorIdxFg = 0x2F; break;
- case '3366FF': $colorIdxFg = 0x30; break;
- case '33CCCC': $colorIdxFg = 0x31; break;
- case '99CC00': $colorIdxFg = 0x32; break;
- case 'FFCC00': $colorIdxFg = 0x33; break;
- case 'FF9900': $colorIdxFg = 0x34; break;
- case 'FF6600': $colorIdxFg = 0x35; break;
- case '666699': $colorIdxFg = 0x36; break;
- case '969696': $colorIdxFg = 0x37; break;
- case '003366': $colorIdxFg = 0x38; break;
- case '339966': $colorIdxFg = 0x39; break;
- case '003300': $colorIdxFg = 0x3A; break;
- case '333300': $colorIdxFg = 0x3B; break;
- case '993300': $colorIdxFg = 0x3C; break;
- case '993366': $colorIdxFg = 0x3D; break;
- case '333399': $colorIdxFg = 0x3E; break;
- case '333333': $colorIdxFg = 0x3F; break;
- default: $colorIdxFg = 0x40; break;
- }
- $dataBlockFill = pack('v', $blockFillPatternStyle);
- $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7));
- }
- if($bFormatProt == 1){
- $dataBlockProtection = 0;
- if($conditional->getStyle()->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED){
- $dataBlockProtection = 1;
- }
- if($conditional->getStyle()->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED){
- $dataBlockProtection = 1 << 1;
- }
- }
-
- $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000);
- if($bFormatFont == 1){ // Block Formatting : OK
- $data .= $dataBlockFont;
- }
- if($bFormatAlign == 1){
- $data .= $dataBlockAlign;
- }
- if($bFormatBorder == 1){
- $data .= $dataBlockBorder;
- }
- if($bFormatFill == 1){ // Block Formatting : OK
- $data .= $dataBlockFill;
- }
- if($bFormatProt == 1){
- $data .= $dataBlockProtection;
- }
- if(!is_null($operand1)){
- $data .= $operand1;
- }
- if(!is_null($operand2)){
- $data .= $operand2;
- }
- $header = pack('vv', $record, strlen($data));
- $this->_append($header . $data);
- }
-
- /**
- * Write CFHeader record
- */
- private function _writeCFHeader(){
- $record = 0x01B0; // Record identifier
- $length = 0x0016; // Bytes to follow
-
- $numColumnMin = null;
- $numColumnMax = null;
- $numRowMin = null;
- $numRowMax = null;
- $arrConditional = array();
- foreach ($this->_phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
- foreach ($conditionalStyles as $conditional) {
- if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
- || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS){
- if(!in_array($conditional->getHashCode(), $arrConditional)){
- $arrConditional[] = $conditional->getHashCode();
- }
- // Cells
- $arrCoord = PHPExcel_Cell::coordinateFromString($cellCoordinate);
- if(!is_numeric($arrCoord[0])){
- $arrCoord[0] = PHPExcel_Cell::columnIndexFromString($arrCoord[0]);
- }
- if(is_null($numColumnMin) || ($numColumnMin > $arrCoord[0])){
- $numColumnMin = $arrCoord[0];
- }
- if(is_null($numColumnMax) || ($numColumnMax < $arrCoord[0])){
- $numColumnMax = $arrCoord[0];
- }
- if(is_null($numRowMin) || ($numRowMin > $arrCoord[1])){
- $numRowMin = $arrCoord[1];
- }
- if(is_null($numRowMax) || ($numRowMax < $arrCoord[1])){
- $numRowMax = $arrCoord[1];
- }
- }
- }
- }
- $needRedraw = 1;
- $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1);
-
- $header = pack('vv', $record, $length);
- $data = pack('vv', count($arrConditional), $needRedraw);
- $data .= $cellRange;
- $data .= pack('v', 0x0001);
- $data .= $cellRange;
- $this->_append($header . $data);
- }
-}
\ No newline at end of file
+ /**
+ * Formula parser
+ *
+ * @var PHPExcel_Writer_Excel5_Parser
+ */
+ private $parser;
+
+ /**
+ * Maximum number of characters for a string (LABEL record in BIFF5)
+ * @var integer
+ */
+ private $xlsStringMaxLength;
+
+ /**
+ * Array containing format information for columns
+ * @var array
+ */
+ private $columnInfo;
+
+ /**
+ * Array containing the selected area for the worksheet
+ * @var array
+ */
+ private $selection;
+
+ /**
+ * The active pane for the worksheet
+ * @var integer
+ */
+ private $activePane;
+
+ /**
+ * Whether to use outline.
+ * @var integer
+ */
+ private $outlineOn;
+
+ /**
+ * Auto outline styles.
+ * @var bool
+ */
+ private $outlineStyle;
+
+ /**
+ * Whether to have outline summary below.
+ * @var bool
+ */
+ private $outlineBelow;
+
+ /**
+ * Whether to have outline summary at the right.
+ * @var bool
+ */
+ private $outlineRight;
+
+ /**
+ * Reference to the total number of strings in the workbook
+ * @var integer
+ */
+ private $stringTotal;
+
+ /**
+ * Reference to the number of unique strings in the workbook
+ * @var integer
+ */
+ private $stringUnique;
+
+ /**
+ * Reference to the array containing all the unique strings in the workbook
+ * @var array
+ */
+ private $stringTable;
+
+ /**
+ * Color cache
+ */
+ private $colors;
+
+ /**
+ * Index of first used row (at least 0)
+ * @var int
+ */
+ private $firstRowIndex;
+
+ /**
+ * Index of last used row. (no used rows means -1)
+ * @var int
+ */
+ private $lastRowIndex;
+
+ /**
+ * Index of first used column (at least 0)
+ * @var int
+ */
+ private $firstColumnIndex;
+
+ /**
+ * Index of last used column (no used columns means -1)
+ * @var int
+ */
+ private $lastColumnIndex;
+
+ /**
+ * Sheet object
+ * @var PHPExcel_Worksheet
+ */
+ public $phpSheet;
+
+ /**
+ * Count cell style Xfs
+ *
+ * @var int
+ */
+ private $countCellStyleXfs;
+
+ /**
+ * Escher object corresponding to MSODRAWING
+ *
+ * @var PHPExcel_Shared_Escher
+ */
+ private $escher;
+
+ /**
+ * Array of font hashes associated to FONT records index
+ *
+ * @var array
+ */
+ public $fontHashIndex;
+
+ /**
+ * Constructor
+ *
+ * @param int &$str_total Total number of strings
+ * @param int &$str_unique Total number of unique strings
+ * @param array &$str_table String Table
+ * @param array &$colors Colour Table
+ * @param mixed $parser The formula parser created for the Workbook
+ * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written
+ * @param string $phpSheet The worksheet to write
+ * @param PHPExcel_Worksheet $phpSheet
+ */
+ public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, $parser, $preCalculateFormulas, $phpSheet)
+ {
+ // It needs to call its parent's constructor explicitly
+ parent::__construct();
+
+ // change BIFFwriter limit for CONTINUE records
+// $this->_limit = 8224;
+
+
+ $this->_preCalculateFormulas = $preCalculateFormulas;
+ $this->stringTotal = &$str_total;
+ $this->stringUnique = &$str_unique;
+ $this->stringTable = &$str_table;
+ $this->colors = &$colors;
+ $this->parser = $parser;
+
+ $this->phpSheet = $phpSheet;
+
+ //$this->ext_sheets = array();
+ //$this->offset = 0;
+ $this->xlsStringMaxLength = 255;
+ $this->columnInfo = array();
+ $this->selection = array(0,0,0,0);
+ $this->activePane = 3;
+
+ $this->_print_headers = 0;
+
+ $this->outlineStyle = 0;
+ $this->outlineBelow = 1;
+ $this->outlineRight = 1;
+ $this->outlineOn = 1;
+
+ $this->fontHashIndex = array();
+
+ // calculate values for DIMENSIONS record
+ $minR = 1;
+ $minC = 'A';
+
+ $maxR = $this->phpSheet->getHighestRow();
+ $maxC = $this->phpSheet->getHighestColumn();
+
+ // Determine lowest and highest column and row
+// $this->firstRowIndex = ($minR > 65535) ? 65535 : $minR;
+ $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ;
+
+ $this->firstColumnIndex = PHPExcel_Cell::columnIndexFromString($minC);
+ $this->lastColumnIndex = PHPExcel_Cell::columnIndexFromString($maxC);
+
+// if ($this->firstColumnIndex > 255) $this->firstColumnIndex = 255;
+ if ($this->lastColumnIndex > 255) {
+ $this->lastColumnIndex = 255;
+ }
+
+ $this->countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
+ }
+
+ /**
+ * Add data to the beginning of the workbook (note the reverse order)
+ * and to the end of the workbook.
+ *
+ * @access public
+ * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook()
+ */
+ public function close()
+ {
+ $phpSheet = $this->phpSheet;
+
+ $num_sheets = $phpSheet->getParent()->getSheetCount();
+
+ // Write BOF record
+ $this->storeBof(0x0010);
+
+ // Write PRINTHEADERS
+ $this->writePrintHeaders();
+
+ // Write PRINTGRIDLINES
+ $this->writePrintGridlines();
+
+ // Write GRIDSET
+ $this->writeGridset();
+
+ // Calculate column widths
+ $phpSheet->calculateColumnWidths();
+
+ // Column dimensions
+ if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
+ $defaultWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($phpSheet->getParent()->getDefaultStyle()->getFont());
+ }
+
+ $columnDimensions = $phpSheet->getColumnDimensions();
+ $maxCol = $this->lastColumnIndex -1;
+ for ($i = 0; $i <= $maxCol; ++$i) {
+ $hidden = 0;
+ $level = 0;
+ $xfIndex = 15; // there are 15 cell style Xfs
+
+ $width = $defaultWidth;
+
+ $columnLetter = PHPExcel_Cell::stringFromColumnIndex($i);
+ if (isset($columnDimensions[$columnLetter])) {
+ $columnDimension = $columnDimensions[$columnLetter];
+ if ($columnDimension->getWidth() >= 0) {
+ $width = $columnDimension->getWidth();
+ }
+ $hidden = $columnDimension->getVisible() ? 0 : 1;
+ $level = $columnDimension->getOutlineLevel();
+ $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
+ }
+
+ // Components of columnInfo:
+ // $firstcol first column on the range
+ // $lastcol last column on the range
+ // $width width to set
+ // $xfIndex The optional cell style Xf index to apply to the columns
+ // $hidden The optional hidden atribute
+ // $level The optional outline level
+ $this->columnInfo[] = array($i, $i, $width, $xfIndex, $hidden, $level);
+ }
+
+ // Write GUTS
+ $this->writeGuts();
+
+ // Write DEFAULTROWHEIGHT
+ $this->writeDefaultRowHeight();
+ // Write WSBOOL
+ $this->writeWsbool();
+ // Write horizontal and vertical page breaks
+ $this->writeBreaks();
+ // Write page header
+ $this->writeHeader();
+ // Write page footer
+ $this->writeFooter();
+ // Write page horizontal centering
+ $this->writeHcenter();
+ // Write page vertical centering
+ $this->writeVcenter();
+ // Write left margin
+ $this->writeMarginLeft();
+ // Write right margin
+ $this->writeMarginRight();
+ // Write top margin
+ $this->writeMarginTop();
+ // Write bottom margin
+ $this->writeMarginBottom();
+ // Write page setup
+ $this->writeSetup();
+ // Write sheet protection
+ $this->writeProtect();
+ // Write SCENPROTECT
+ $this->writeScenProtect();
+ // Write OBJECTPROTECT
+ $this->writeObjectProtect();
+ // Write sheet password
+ $this->writePassword();
+ // Write DEFCOLWIDTH record
+ $this->writeDefcol();
+
+ // Write the COLINFO records if they exist
+ if (!empty($this->columnInfo)) {
+ $colcount = count($this->columnInfo);
+ for ($i = 0; $i < $colcount; ++$i) {
+ $this->writeColinfo($this->columnInfo[$i]);
+ }
+ }
+ $autoFilterRange = $phpSheet->getAutoFilter()->getRange();
+ if (!empty($autoFilterRange)) {
+ // Write AUTOFILTERINFO
+ $this->writeAutoFilterInfo();
+ }
+
+ // Write sheet dimensions
+ $this->writeDimensions();
+
+ // Row dimensions
+ foreach ($phpSheet->getRowDimensions() as $rowDimension) {
+ $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
+ $this->writeRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel());
+ }
+
+ // Write Cells
+ foreach ($phpSheet->getCellCollection() as $cellID) {
+ $cell = $phpSheet->getCell($cellID);
+ $row = $cell->getRow() - 1;
+ $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
+
+ // Don't break Excel!
+// if ($row + 1 > 65536 or $column + 1 > 256) {
+ if ($row > 65535 || $column > 255) {
+ break;
+ }
+
+ // Write cell value
+ $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
+
+ $cVal = $cell->getValue();
+ if ($cVal instanceof PHPExcel_RichText) {
+ // $this->writeString($row, $column, $cVal->getPlainText(), $xfIndex);
+ $arrcRun = array();
+ $str_len = PHPExcel_Shared_String::CountCharacters($cVal->getPlainText(), 'UTF-8');
+ $str_pos = 0;
+ $elements = $cVal->getRichTextElements();
+ foreach ($elements as $element) {
+ // FONT Index
+ if ($element instanceof PHPExcel_RichText_Run) {
+ $str_fontidx = $this->fontHashIndex[$element->getFont()->getHashCode()];
+ } else {
+ $str_fontidx = 0;
+ }
+ $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx);
+ // Position FROM
+ $str_pos += PHPExcel_Shared_String::CountCharacters($element->getText(), 'UTF-8');
+ }
+ $this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
+ } else {
+ switch ($cell->getDatatype()) {
+ case PHPExcel_Cell_DataType::TYPE_STRING:
+ case PHPExcel_Cell_DataType::TYPE_NULL:
+ if ($cVal === '' || $cVal === null) {
+ $this->writeBlank($row, $column, $xfIndex);
+ } else {
+ $this->writeString($row, $column, $cVal, $xfIndex);
+ }
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_NUMERIC:
+ $this->writeNumber($row, $column, $cVal, $xfIndex);
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_FORMULA:
+ $calculatedValue = $this->_preCalculateFormulas ?
+ $cell->getCalculatedValue() : null;
+ $this->writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue);
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_BOOL:
+ $this->writeBoolErr($row, $column, $cVal, 0, $xfIndex);
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_ERROR:
+ $this->writeBoolErr($row, $column, self::mapErrorCode($cVal), 1, $xfIndex);
+ break;
+
+ }
+ }
+ }
+
+ // Append
+ $this->writeMsoDrawing();
+
+ // Write WINDOW2 record
+ $this->writeWindow2();
+
+ // Write PLV record
+ $this->writePageLayoutView();
+
+ // Write ZOOM record
+ $this->writeZoom();
+ if ($phpSheet->getFreezePane()) {
+ $this->writePanes();
+ }
+
+ // Write SELECTION record
+ $this->writeSelection();
+
+ // Write MergedCellsTable Record
+ $this->writeMergedCells();
+
+ // Hyperlinks
+ foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
+ list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinate);
+
+ $url = $hyperlink->getUrl();
+
+ if (strpos($url, 'sheet://') !== false) {
+ // internal to current workbook
+ $url = str_replace('sheet://', 'internal:', $url);
+
+ } elseif (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) {
+ // URL
+ // $url = $url;
+
+ } else {
+ // external (local file)
+ $url = 'external:' . $url;
+ }
+
+ $this->writeUrl($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $url);
+ }
+
+ $this->writeDataValidity();
+ $this->writeSheetLayout();
+
+ // Write SHEETPROTECTION record
+ $this->writeSheetProtection();
+ $this->writeRangeProtection();
+
+ $arrConditionalStyles = $phpSheet->getConditionalStylesCollection();
+ if (!empty($arrConditionalStyles)) {
+ $arrConditional = array();
+ // @todo CFRule & CFHeader
+ // Write CFHEADER record
+ $this->writeCFHeader();
+ // Write ConditionalFormattingTable records
+ foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
+ foreach ($conditionalStyles as $conditional) {
+ if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
+ || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS) {
+ if (!in_array($conditional->getHashCode(), $arrConditional)) {
+ $arrConditional[] = $conditional->getHashCode();
+ // Write CFRULE record
+ $this->writeCFRule($conditional);
+ }
+ }
+ }
+ }
+ }
+
+ $this->storeEof();
+ }
+
+ /**
+ * Write a cell range address in BIFF8
+ * always fixed range
+ * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format
+ *
+ * @param string $range E.g. 'A1' or 'A1:B6'
+ * @return string Binary data
+ */
+ private function writeBIFF8CellRangeAddressFixed($range = 'A1')
+ {
+ $explodes = explode(':', $range);
+
+ // extract first cell, e.g. 'A1'
+ $firstCell = $explodes[0];
+
+ // extract last cell, e.g. 'B6'
+ if (count($explodes) == 1) {
+ $lastCell = $firstCell;
+ } else {
+ $lastCell = $explodes[1];
+ }
+
+ $firstCellCoordinates = PHPExcel_Cell::coordinateFromString($firstCell); // e.g. array(0, 1)
+ $lastCellCoordinates = PHPExcel_Cell::coordinateFromString($lastCell); // e.g. array(1, 6)
+
+ return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, PHPExcel_Cell::columnIndexFromString($firstCellCoordinates[0]) - 1, PHPExcel_Cell::columnIndexFromString($lastCellCoordinates[0]) - 1);
+ }
+
+ /**
+ * Retrieves data from memory in one chunk, or from disk in $buffer
+ * sized chunks.
+ *
+ * @return string The data
+ */
+ public function getData()
+ {
+ $buffer = 4096;
+
+ // Return data stored in memory
+ if (isset($this->_data)) {
+ $tmp = $this->_data;
+ unset($this->_data);
+ return $tmp;
+ }
+ // No data to return
+ return false;
+ }
+
+ /**
+ * Set the option to print the row and column headers on the printed page.
+ *
+ * @access public
+ * @param integer $print Whether to print the headers or not. Defaults to 1 (print).
+ */
+ public function printRowColHeaders($print = 1)
+ {
+ $this->_print_headers = $print;
+ }
+
+ /**
+ * This method sets the properties for outlining and grouping. The defaults
+ * correspond to Excel's defaults.
+ *
+ * @param bool $visible
+ * @param bool $symbols_below
+ * @param bool $symbols_right
+ * @param bool $auto_style
+ */
+ public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false)
+ {
+ $this->outlineOn = $visible;
+ $this->outlineBelow = $symbols_below;
+ $this->outlineRight = $symbols_right;
+ $this->outlineStyle = $auto_style;
+
+ // Ensure this is a boolean vale for Window2
+ if ($this->outlineOn) {
+ $this->outlineOn = 1;
+ }
+ }
+
+ /**
+ * Write a double to the specified row and column (zero indexed).
+ * An integer can be written as a double. Excel will display an
+ * integer. $format is optional.
+ *
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param float $num The number to write
+ * @param mixed $xfIndex The optional XF format
+ * @return integer
+ */
+ private function writeNumber($row, $col, $num, $xfIndex)
+ {
+ $record = 0x0203; // Record identifier
+ $length = 0x000E; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $row, $col, $xfIndex);
+ $xl_double = pack("d", $num);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $xl_double = strrev($xl_double);
+ }
+
+ $this->append($header.$data.$xl_double);
+ return(0);
+ }
+
+ /**
+ * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
+ *
+ * @param int $row Row index (0-based)
+ * @param int $col Column index (0-based)
+ * @param string $str The string
+ * @param int $xfIndex Index to XF record
+ */
+ private function writeString($row, $col, $str, $xfIndex)
+ {
+ $this->writeLabelSst($row, $col, $str, $xfIndex);
+ }
+
+ /**
+ * Write a LABELSST record or a LABEL record. Which one depends on BIFF version
+ * It differs from writeString by the writing of rich text strings.
+ * @param int $row Row index (0-based)
+ * @param int $col Column index (0-based)
+ * @param string $str The string
+ * @param mixed $xfIndex The XF format index for the cell
+ * @param array $arrcRun Index to Font record and characters beginning
+ */
+ private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun)
+ {
+ $record = 0x00FD; // Record identifier
+ $length = 0x000A; // Bytes to follow
+ $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun);
+
+ /* check if string is already present */
+ if (!isset($this->stringTable[$str])) {
+ $this->stringTable[$str] = $this->stringUnique++;
+ }
+ $this->stringTotal++;
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
+ $this->append($header.$data);
+ }
+
+ /**
+ * Write a string to the specified row and column (zero indexed).
+ * NOTE: there is an Excel 5 defined limit of 255 characters.
+ * $format is optional.
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ * -3 : long string truncated to 255 chars
+ *
+ * @access public
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $str The string to write
+ * @param mixed $xfIndex The XF format index for the cell
+ * @return integer
+ */
+ private function writeLabel($row, $col, $str, $xfIndex)
+ {
+ $strlen = strlen($str);
+ $record = 0x0204; // Record identifier
+ $length = 0x0008 + $strlen; // Bytes to follow
+
+ $str_error = 0;
+
+ if ($strlen > $this->xlsStringMaxLength) { // LABEL must be < 255 chars
+ $str = substr($str, 0, $this->xlsStringMaxLength);
+ $length = 0x0008 + $this->xlsStringMaxLength;
+ $strlen = $this->xlsStringMaxLength;
+ $str_error = -3;
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $row, $col, $xfIndex, $strlen);
+ $this->append($header . $data . $str);
+ return($str_error);
+ }
+
+ /**
+ * Write a string to the specified row and column (zero indexed).
+ * This is the BIFF8 version (no 255 chars limit).
+ * $format is optional.
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ * -3 : long string truncated to 255 chars
+ *
+ * @access public
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $str The string to write
+ * @param mixed $xfIndex The XF format index for the cell
+ * @return integer
+ */
+ private function writeLabelSst($row, $col, $str, $xfIndex)
+ {
+ $record = 0x00FD; // Record identifier
+ $length = 0x000A; // Bytes to follow
+
+ $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($str);
+
+ /* check if string is already present */
+ if (!isset($this->stringTable[$str])) {
+ $this->stringTable[$str] = $this->stringUnique++;
+ }
+ $this->stringTotal++;
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
+ $this->append($header.$data);
+ }
+
+ /**
+ * Writes a note associated with the cell given by the row and column.
+ * NOTE records don't have a length limit.
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $note The note to write
+ */
+ private function writeNote($row, $col, $note)
+ {
+ $note_length = strlen($note);
+ $record = 0x001C; // Record identifier
+ $max_length = 2048; // Maximun length for a NOTE record
+
+ // Length for this record is no more than 2048 + 6
+ $length = 0x0006 + min($note_length, 2048);
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $row, $col, $note_length);
+ $this->append($header . $data . substr($note, 0, 2048));
+
+ for ($i = $max_length; $i < $note_length; $i += $max_length) {
+ $chunk = substr($note, $i, $max_length);
+ $length = 0x0006 + strlen($chunk);
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", -1, 0, strlen($chunk));
+ $this->append($header.$data.$chunk);
+ }
+ return(0);
+ }
+
+ /**
+ * Write a blank cell to the specified row and column (zero indexed).
+ * A blank cell is used to specify formatting without adding a string
+ * or a number.
+ *
+ * A blank cell without a format serves no purpose. Therefore, we don't write
+ * a BLANK record unless a format is specified.
+ *
+ * Returns 0 : normal termination (including no format)
+ * -1 : insufficient number of arguments
+ * -2 : row or column out of range
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param mixed $xfIndex The XF format index
+ */
+ public function writeBlank($row, $col, $xfIndex)
+ {
+ $record = 0x0201; // Record identifier
+ $length = 0x0006; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $row, $col, $xfIndex);
+ $this->append($header . $data);
+ return 0;
+ }
+
+ /**
+ * Write a boolean or an error type to the specified row and column (zero indexed)
+ *
+ * @param int $row Row index (0-based)
+ * @param int $col Column index (0-based)
+ * @param int $value
+ * @param boolean $isError Error or Boolean?
+ * @param int $xfIndex
+ */
+ private function writeBoolErr($row, $col, $value, $isError, $xfIndex)
+ {
+ $record = 0x0205;
+ $length = 8;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError);
+ $this->append($header . $data);
+ return 0;
+ }
+
+ /**
+ * Write a formula to the specified row and column (zero indexed).
+ * The textual representation of the formula is passed to the parser in
+ * Parser.php which returns a packed binary string.
+ *
+ * Returns 0 : normal termination
+ * -1 : formula errors (bad formula)
+ * -2 : row or column out of range
+ *
+ * @param integer $row Zero indexed row
+ * @param integer $col Zero indexed column
+ * @param string $formula The formula text string
+ * @param mixed $xfIndex The XF format index
+ * @param mixed $calculatedValue Calculated value
+ * @return integer
+ */
+ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
+ {
+ $record = 0x0006; // Record identifier
+
+ // Initialize possible additional value for STRING record that should be written after the FORMULA record?
+ $stringValue = null;
+
+ // calculated value
+ if (isset($calculatedValue)) {
+ // Since we can't yet get the data type of the calculated value,
+ // we use best effort to determine data type
+ if (is_bool($calculatedValue)) {
+ // Boolean value
+ $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF);
+ } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
+ // Numeric value
+ $num = pack('d', $calculatedValue);
+ } elseif (is_string($calculatedValue)) {
+ if (array_key_exists($calculatedValue, PHPExcel_Cell_DataType::getErrorCodes())) {
+ // Error value
+ $num = pack('CCCvCv', 0x02, 0x00, self::mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF);
+ } elseif ($calculatedValue === '') {
+ // Empty string (and BIFF8)
+ $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
+ } else {
+ // Non-empty string value (or empty string BIFF5)
+ $stringValue = $calculatedValue;
+ $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
+ }
+ } else {
+ // We are really not supposed to reach here
+ $num = pack('d', 0x00);
+ }
+ } else {
+ $num = pack('d', 0x00);
+ }
+
+ $grbit = 0x03; // Option flags
+ $unknown = 0x0000; // Must be zero
+
+ // Strip the '=' or '@' sign at the beginning of the formula string
+ if ($formula{0} == '=') {
+ $formula = substr($formula, 1);
+ } else {
+ // Error handling
+ $this->writeString($row, $col, 'Unrecognised character for formula');
+ return -1;
+ }
+
+ // Parse the formula using the parser in Parser.php
+ try {
+ $error = $this->parser->parse($formula);
+ $formula = $this->parser->toReversePolish();
+
+ $formlen = strlen($formula); // Length of the binary string
+ $length = 0x16 + $formlen; // Length of the record data
+
+ $header = pack("vv", $record, $length);
+
+ $data = pack("vvv", $row, $col, $xfIndex)
+ . $num
+ . pack("vVv", $grbit, $unknown, $formlen);
+ $this->append($header . $data . $formula);
+
+ // Append also a STRING record if necessary
+ if ($stringValue !== null) {
+ $this->writeStringRecord($stringValue);
+ }
+
+ return 0;
+
+ } catch (PHPExcel_Exception $e) {
+ // do nothing
+ }
+
+ }
+
+ /**
+ * Write a STRING record. This
+ *
+ * @param string $stringValue
+ */
+ private function writeStringRecord($stringValue)
+ {
+ $record = 0x0207; // Record identifier
+ $data = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($stringValue);
+
+ $length = strlen($data);
+ $header = pack('vv', $record, $length);
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write a hyperlink.
+ * This is comprised of two elements: the visible label and
+ * the invisible link. The visible label is the same as the link unless an
+ * alternative string is specified. The label is written using the
+ * writeString() method. Therefore the 255 characters string limit applies.
+ * $string and $format are optional.
+ *
+ * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external
+ * directory url.
+ *
+ * Returns 0 : normal termination
+ * -2 : row or column out of range
+ * -3 : long string truncated to 255 chars
+ *
+ * @param integer $row Row
+ * @param integer $col Column
+ * @param string $url URL string
+ * @return integer
+ */
+ private function writeUrl($row, $col, $url)
+ {
+ // Add start row and col to arg list
+ return($this->writeUrlRange($row, $col, $row, $col, $url));
+ }
+
+ /**
+ * This is the more general form of writeUrl(). It allows a hyperlink to be
+ * written to a range of cells. This function also decides the type of hyperlink
+ * to be written. These are either, Web (http, ftp, mailto), Internal
+ * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
+ *
+ * @access private
+ * @see writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ public function writeUrlRange($row1, $col1, $row2, $col2, $url)
+ {
+ // Check for internal/external sheet links or default to web link
+ if (preg_match('[^internal:]', $url)) {
+ return($this->writeUrlInternal($row1, $col1, $row2, $col2, $url));
+ }
+ if (preg_match('[^external:]', $url)) {
+ return($this->writeUrlExternal($row1, $col1, $row2, $col2, $url));
+ }
+ return($this->writeUrlWeb($row1, $col1, $row2, $col2, $url));
+ }
+
+ /**
+ * Used to write http, ftp and mailto hyperlinks.
+ * The link type ($options) is 0x03 is the same as absolute dir ref without
+ * sheet. However it is differentiated by the $unknown2 data stream.
+ *
+ * @access private
+ * @see writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ public function writeUrlWeb($row1, $col1, $row2, $col2, $url)
+ {
+ $record = 0x01B8; // Record identifier
+ $length = 0x00000; // Bytes to follow
+
+ // Pack the undocumented parts of the hyperlink stream
+ $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
+ $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B");
+
+ // Pack the option flags
+ $options = pack("V", 0x03);
+
+ // Convert URL to a null terminated wchar string
+ $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
+ $url = $url . "\0\0\0";
+
+ // Pack the length of the URL
+ $url_len = pack("V", strlen($url));
+
+ // Calculate the data length
+ $length = 0x34 + strlen($url);
+
+ // Pack the header data
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $row1, $row2, $col1, $col2);
+
+ // Write the packed data
+ $this->append($header . $data .
+ $unknown1 . $options .
+ $unknown2 . $url_len . $url);
+ return 0;
+ }
+
+ /**
+ * Used to write internal reference hyperlinks such as "Sheet1!A1".
+ *
+ * @access private
+ * @see writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ public function writeUrlInternal($row1, $col1, $row2, $col2, $url)
+ {
+ $record = 0x01B8; // Record identifier
+ $length = 0x00000; // Bytes to follow
+
+ // Strip URL type
+ $url = preg_replace('/^internal:/', '', $url);
+
+ // Pack the undocumented parts of the hyperlink stream
+ $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000");
+
+ // Pack the option flags
+ $options = pack("V", 0x08);
+
+ // Convert the URL type and to a null terminated wchar string
+ $url .= "\0";
+
+ // character count
+ $url_len = PHPExcel_Shared_String::CountCharacters($url);
+ $url_len = pack('V', $url_len);
+
+ $url = PHPExcel_Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8');
+
+ // Calculate the data length
+ $length = 0x24 + strlen($url);
+
+ // Pack the header data
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $row1, $row2, $col1, $col2);
+
+ // Write the packed data
+ $this->append($header . $data .
+ $unknown1 . $options .
+ $url_len . $url);
+ return 0;
+ }
+
+ /**
+ * Write links to external directory names such as 'c:\foo.xls',
+ * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
+ *
+ * Note: Excel writes some relative links with the $dir_long string. We ignore
+ * these cases for the sake of simpler code.
+ *
+ * @access private
+ * @see writeUrl()
+ * @param integer $row1 Start row
+ * @param integer $col1 Start column
+ * @param integer $row2 End row
+ * @param integer $col2 End column
+ * @param string $url URL string
+ * @return integer
+ */
+ public function writeUrlExternal($row1, $col1, $row2, $col2, $url)
+ {
+ // Network drives are different. We will handle them separately
+ // MS/Novell network drives and shares start with \\
+ if (preg_match('[^external:\\\\]', $url)) {
+ return; //($this->writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format));
+ }
+
+ $record = 0x01B8; // Record identifier
+ $length = 0x00000; // Bytes to follow
+
+ // Strip URL type and change Unix dir separator to Dos style (if needed)
+ //
+ $url = preg_replace('/^external:/', '', $url);
+ $url = preg_replace('/\//', "\\", $url);
+
+ // Determine if the link is relative or absolute:
+ // relative if link contains no dir separator, "somefile.xls"
+ // relative if link starts with up-dir, "..\..\somefile.xls"
+ // otherwise, absolute
+
+ $absolute = 0x00; // relative path
+ if (preg_match('/^[A-Z]:/', $url)) {
+ $absolute = 0x02; // absolute path on Windows, e.g. C:\...
+ }
+ $link_type = 0x01 | $absolute;
+
+ // Determine if the link contains a sheet reference and change some of the
+ // parameters accordingly.
+ // Split the dir name and sheet name (if it exists)
+ $dir_long = $url;
+ if (preg_match("/\#/", $url)) {
+ $link_type |= 0x08;
+ }
+
+
+ // Pack the link type
+ $link_type = pack("V", $link_type);
+
+ // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
+ $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless);
+ $up_count = pack("v", $up_count);
+
+ // Store the short dos dir name (null terminated)
+ $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0";
+
+ // Store the long dir name as a wchar string (non-null terminated)
+ $dir_long = $dir_long . "\0";
+
+ // Pack the lengths of the dir strings
+ $dir_short_len = pack("V", strlen($dir_short));
+ $dir_long_len = pack("V", strlen($dir_long));
+ $stream_len = pack("V", 0); //strlen($dir_long) + 0x06);
+
+ // Pack the undocumented parts of the hyperlink stream
+ $unknown1 = pack("H*", 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
+ $unknown2 = pack("H*", '0303000000000000C000000000000046');
+ $unknown3 = pack("H*", 'FFFFADDE000000000000000000000000000000000000000');
+ $unknown4 = pack("v", 0x03);
+
+ // Pack the main data stream
+ $data = pack("vvvv", $row1, $row2, $col1, $col2) .
+ $unknown1 .
+ $link_type .
+ $unknown2 .
+ $up_count .
+ $dir_short_len.
+ $dir_short .
+ $unknown3 .
+ $stream_len ;/*.
+ $dir_long_len .
+ $unknown4 .
+ $dir_long .
+ $sheet_len .
+ $sheet ;*/
+
+ // Pack the header data
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+
+ // Write the packed data
+ $this->append($header. $data);
+ return 0;
+ }
+
+ /**
+ * This method is used to set the height and format for a row.
+ *
+ * @param integer $row The row to set
+ * @param integer $height Height we are giving to the row.
+ * Use null to set XF without setting height
+ * @param integer $xfIndex The optional cell style Xf index to apply to the columns
+ * @param bool $hidden The optional hidden attribute
+ * @param integer $level The optional outline level for row, in range [0,7]
+ */
+ private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0)
+ {
+ $record = 0x0208; // Record identifier
+ $length = 0x0010; // Number of bytes to follow
+
+ $colMic = 0x0000; // First defined column
+ $colMac = 0x0000; // Last defined column
+ $irwMac = 0x0000; // Used by Excel to optimise loading
+ $reserved = 0x0000; // Reserved
+ $grbit = 0x0000; // Option flags
+ $ixfe = $xfIndex;
+
+ if ($height < 0) {
+ $height = null;
+ }
+
+ // Use writeRow($row, null, $XF) to set XF format without setting height
+ if ($height != null) {
+ $miyRw = $height * 20; // row height
+ } else {
+ $miyRw = 0xff; // default row height is 256
+ }
+
+ // Set the options flags. fUnsynced is used to show that the font and row
+ // heights are not compatible. This is usually the case for WriteExcel.
+ // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
+ // is collapsed. Instead it is used to indicate that the previous row is
+ // collapsed. The zero height flag, 0x20, is used to collapse a row.
+
+ $grbit |= $level;
+ if ($hidden) {
+ $grbit |= 0x0030;
+ }
+ if ($height !== null) {
+ $grbit |= 0x0040; // fUnsynced
+ }
+ if ($xfIndex !== 0xF) {
+ $grbit |= 0x0080;
+ }
+ $grbit |= 0x0100;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe);
+ $this->append($header.$data);
+ }
+
+ /**
+ * Writes Excel DIMENSIONS to define the area in which there is data.
+ */
+ private function writeDimensions()
+ {
+ $record = 0x0200; // Record identifier
+
+ $length = 0x000E;
+ $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved
+
+ $header = pack("vv", $record, $length);
+ $this->append($header.$data);
+ }
+
+ /**
+ * Write BIFF record Window2.
+ */
+ private function writeWindow2()
+ {
+ $record = 0x023E; // Record identifier
+ $length = 0x0012;
+
+ $grbit = 0x00B6; // Option flags
+ $rwTop = 0x0000; // Top row visible in window
+ $colLeft = 0x0000; // Leftmost column visible in window
+
+
+ // The options flags that comprise $grbit
+ $fDspFmla = 0; // 0 - bit
+ $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1
+ $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
+ $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3
+ $fDspZeros = 1; // 4
+ $fDefaultHdr = 1; // 5
+ $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6
+ $fDspGuts = $this->outlineOn; // 7
+ $fFrozenNoSplit = 0; // 0 - bit
+ // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet
+ $fSelected = ($this->phpSheet === $this->phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
+ $fPaged = 1; // 2
+ $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW;
+
+ $grbit = $fDspFmla;
+ $grbit |= $fDspGrid << 1;
+ $grbit |= $fDspRwCol << 2;
+ $grbit |= $fFrozen << 3;
+ $grbit |= $fDspZeros << 4;
+ $grbit |= $fDefaultHdr << 5;
+ $grbit |= $fArabic << 6;
+ $grbit |= $fDspGuts << 7;
+ $grbit |= $fFrozenNoSplit << 8;
+ $grbit |= $fSelected << 9;
+ $grbit |= $fPaged << 10;
+ $grbit |= $fPageBreakPreview << 11;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvv", $grbit, $rwTop, $colLeft);
+
+ // FIXME !!!
+ $rgbHdr = 0x0040; // Row/column heading and gridline color index
+ $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000);
+ $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal();
+
+ $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
+
+ $this->append($header.$data);
+ }
+
+ /**
+ * Write BIFF record DEFAULTROWHEIGHT.
+ */
+ private function writeDefaultRowHeight()
+ {
+ $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight();
+
+ if ($defaultRowHeight < 0) {
+ return;
+ }
+
+ // convert to twips
+ $defaultRowHeight = (int) 20 * $defaultRowHeight;
+
+ $record = 0x0225; // Record identifier
+ $length = 0x0004; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vv", 1, $defaultRowHeight);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
+ */
+ private function writeDefcol()
+ {
+ $defaultColWidth = 8;
+
+ $record = 0x0055; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $defaultColWidth);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write BIFF record COLINFO to define column widths
+ *
+ * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
+ * length record.
+ *
+ * @param array $col_array This is the only parameter received and is composed of the following:
+ * 0 => First formatted column,
+ * 1 => Last formatted column,
+ * 2 => Col width (8.43 is Excel default),
+ * 3 => The optional XF format of the column,
+ * 4 => Option flags.
+ * 5 => Optional outline level
+ */
+ private function writeColinfo($col_array)
+ {
+ if (isset($col_array[0])) {
+ $colFirst = $col_array[0];
+ }
+ if (isset($col_array[1])) {
+ $colLast = $col_array[1];
+ }
+ if (isset($col_array[2])) {
+ $coldx = $col_array[2];
+ } else {
+ $coldx = 8.43;
+ }
+ if (isset($col_array[3])) {
+ $xfIndex = $col_array[3];
+ } else {
+ $xfIndex = 15;
+ }
+ if (isset($col_array[4])) {
+ $grbit = $col_array[4];
+ } else {
+ $grbit = 0;
+ }
+ if (isset($col_array[5])) {
+ $level = $col_array[5];
+ } else {
+ $level = 0;
+ }
+ $record = 0x007D; // Record identifier
+ $length = 0x000C; // Number of bytes to follow
+
+ $coldx *= 256; // Convert to units of 1/256 of a char
+
+ $ixfe = $xfIndex;
+ $reserved = 0x0000; // Reserved
+
+ $level = max(0, min($level, 7));
+ $grbit |= $level << 8;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvvv", $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved);
+ $this->append($header.$data);
+ }
+
+ /**
+ * Write BIFF record SELECTION.
+ */
+ private function writeSelection()
+ {
+ // look up the selected cell range
+ $selectedCells = $this->phpSheet->getSelectedCells();
+ $selectedCells = PHPExcel_Cell::splitRange($this->phpSheet->getSelectedCells());
+ $selectedCells = $selectedCells[0];
+ if (count($selectedCells) == 2) {
+ list($first, $last) = $selectedCells;
+ } else {
+ $first = $selectedCells[0];
+ $last = $selectedCells[0];
+ }
+
+ list($colFirst, $rwFirst) = PHPExcel_Cell::coordinateFromString($first);
+ $colFirst = PHPExcel_Cell::columnIndexFromString($colFirst) - 1; // base 0 column index
+ --$rwFirst; // base 0 row index
+
+ list($colLast, $rwLast) = PHPExcel_Cell::coordinateFromString($last);
+ $colLast = PHPExcel_Cell::columnIndexFromString($colLast) - 1; // base 0 column index
+ --$rwLast; // base 0 row index
+
+ // make sure we are not out of bounds
+ $colFirst = min($colFirst, 255);
+ $colLast = min($colLast, 255);
+
+ $rwFirst = min($rwFirst, 65535);
+ $rwLast = min($rwLast, 65535);
+
+ $record = 0x001D; // Record identifier
+ $length = 0x000F; // Number of bytes to follow
+
+ $pnn = $this->activePane; // Pane position
+ $rwAct = $rwFirst; // Active row
+ $colAct = $colFirst; // Active column
+ $irefAct = 0; // Active cell ref
+ $cref = 1; // Number of refs
+
+ if (!isset($rwLast)) {
+ $rwLast = $rwFirst; // Last row in reference
+ }
+ if (!isset($colLast)) {
+ $colLast = $colFirst; // Last col in reference
+ }
+
+ // Swap last row/col for first row/col as necessary
+ if ($rwFirst > $rwLast) {
+ list($rwFirst, $rwLast) = array($rwLast, $rwFirst);
+ }
+
+ if ($colFirst > $colLast) {
+ list($colFirst, $colLast) = array($colLast, $colFirst);
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the MERGEDCELLS records for all ranges of merged cells
+ */
+ private function writeMergedCells()
+ {
+ $mergeCells = $this->phpSheet->getMergeCells();
+ $countMergeCells = count($mergeCells);
+
+ if ($countMergeCells == 0) {
+ return;
+ }
+
+ // maximum allowed number of merged cells per record
+ $maxCountMergeCellsPerRecord = 1027;
+
+ // record identifier
+ $record = 0x00E5;
+
+ // counter for total number of merged cells treated so far by the writer
+ $i = 0;
+
+ // counter for number of merged cells written in record currently being written
+ $j = 0;
+
+ // initialize record data
+ $recordData = '';
+
+ // loop through the merged cells
+ foreach ($mergeCells as $mergeCell) {
+ ++$i;
+ ++$j;
+
+ // extract the row and column indexes
+ $range = PHPExcel_Cell::splitRange($mergeCell);
+ list($first, $last) = $range[0];
+ list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first);
+ list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last);
+
+ $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1);
+
+ // flush record if we have reached limit for number of merged cells, or reached final merged cell
+ if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) {
+ $recordData = pack('v', $j) . $recordData;
+ $length = strlen($recordData);
+ $header = pack('vv', $record, $length);
+ $this->append($header . $recordData);
+
+ // initialize for next record, if any
+ $recordData = '';
+ $j = 0;
+ }
+ }
+ }
+
+ /**
+ * Write SHEETLAYOUT record
+ */
+ private function writeSheetLayout()
+ {
+ if (!$this->phpSheet->isTabColorSet()) {
+ return;
+ }
+
+ $recordData = pack(
+ 'vvVVVvv',
+ 0x0862,
+ 0x0000, // unused
+ 0x00000000, // unused
+ 0x00000000, // unused
+ 0x00000014, // size of record data
+ $this->colors[$this->phpSheet->getTabColor()->getRGB()], // color index
+ 0x0000 // unused
+ );
+
+ $length = strlen($recordData);
+
+ $record = 0x0862; // Record identifier
+ $header = pack('vv', $record, $length);
+ $this->append($header . $recordData);
+ }
+
+ /**
+ * Write SHEETPROTECTION
+ */
+ private function writeSheetProtection()
+ {
+ // record identifier
+ $record = 0x0867;
+
+ // prepare options
+ $options = (int) !$this->phpSheet->getProtection()->getObjects()
+ | (int) !$this->phpSheet->getProtection()->getScenarios() << 1
+ | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2
+ | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3
+ | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4
+ | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5
+ | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6
+ | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7
+ | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8
+ | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9
+ | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10
+ | (int) !$this->phpSheet->getProtection()->getSort() << 11
+ | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12
+ | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13
+ | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14 ;
+
+ // record data
+ $recordData = pack(
+ 'vVVCVVvv',
+ 0x0867, // repeated record identifier
+ 0x0000, // not used
+ 0x0000, // not used
+ 0x00, // not used
+ 0x01000200, // unknown data
+ 0xFFFFFFFF, // unknown data
+ $options, // options
+ 0x0000 // not used
+ );
+
+ $length = strlen($recordData);
+ $header = pack('vv', $record, $length);
+
+ $this->append($header . $recordData);
+ }
+
+ /**
+ * Write BIFF record RANGEPROTECTION
+ *
+ * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records
+ * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records
+ */
+ private function writeRangeProtection()
+ {
+ foreach ($this->phpSheet->getProtectedCells() as $range => $password) {
+ // number of ranges, e.g. 'A1:B3 C20:D25'
+ $cellRanges = explode(' ', $range);
+ $cref = count($cellRanges);
+
+ $recordData = pack(
+ 'vvVVvCVvVv',
+ 0x0868,
+ 0x00,
+ 0x0000,
+ 0x0000,
+ 0x02,
+ 0x0,
+ 0x0000,
+ $cref,
+ 0x0000,
+ 0x00
+ );
+
+ foreach ($cellRanges as $cellRange) {
+ $recordData .= $this->writeBIFF8CellRangeAddressFixed($cellRange);
+ }
+
+ // the rgbFeat structure
+ $recordData .= pack(
+ 'VV',
+ 0x0000,
+ hexdec($password)
+ );
+
+ $recordData .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
+
+ $length = strlen($recordData);
+
+ $record = 0x0868; // Record identifier
+ $header = pack("vv", $record, $length);
+ $this->append($header . $recordData);
+ }
+ }
+
+ /**
+ * Write BIFF record EXTERNCOUNT to indicate the number of external sheet
+ * references in a worksheet.
+ *
+ * Excel only stores references to external sheets that are used in formulas.
+ * For simplicity we store references to all the sheets in the workbook
+ * regardless of whether they are used or not. This reduces the overall
+ * complexity and eliminates the need for a two way dialogue between the formula
+ * parser the worksheet objects.
+ *
+ * @param integer $count The number of external sheet references in this worksheet
+ */
+ private function writeExterncount($count)
+ {
+ $record = 0x0016; // Record identifier
+ $length = 0x0002; // Number of bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $count);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Writes the Excel BIFF EXTERNSHEET record. These references are used by
+ * formulas. A formula references a sheet name via an index. Since we store a
+ * reference to all of the external worksheets the EXTERNSHEET index is the same
+ * as the worksheet index.
+ *
+ * @param string $sheetname The name of a external worksheet
+ */
+ private function writeExternsheet($sheetname)
+ {
+ $record = 0x0017; // Record identifier
+
+ // References to the current sheet are encoded differently to references to
+ // external sheets.
+ //
+ if ($this->phpSheet->getTitle() == $sheetname) {
+ $sheetname = '';
+ $length = 0x02; // The following 2 bytes
+ $cch = 1; // The following byte
+ $rgch = 0x02; // Self reference
+ } else {
+ $length = 0x02 + strlen($sheetname);
+ $cch = strlen($sheetname);
+ $rgch = 0x03; // Reference to a sheet in the current workbook
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("CC", $cch, $rgch);
+ $this->append($header . $data . $sheetname);
+ }
+
+ /**
+ * Writes the Excel BIFF PANE record.
+ * The panes can either be frozen or thawed (unfrozen).
+ * Frozen panes are specified in terms of an integer number of rows and columns.
+ * Thawed panes are specified in terms of Excel's units for rows and columns.
+ */
+ private function writePanes()
+ {
+ $panes = array();
+ if ($freezePane = $this->phpSheet->getFreezePane()) {
+ list($column, $row) = PHPExcel_Cell::coordinateFromString($freezePane);
+ $panes[0] = $row - 1;
+ $panes[1] = PHPExcel_Cell::columnIndexFromString($column) - 1;
+ } else {
+ // thaw panes
+ return;
+ }
+
+ $y = isset($panes[0]) ? $panes[0] : null;
+ $x = isset($panes[1]) ? $panes[1] : null;
+ $rwTop = isset($panes[2]) ? $panes[2] : null;
+ $colLeft = isset($panes[3]) ? $panes[3] : null;
+ if (count($panes) > 4) { // if Active pane was received
+ $pnnAct = $panes[4];
+ } else {
+ $pnnAct = null;
+ }
+ $record = 0x0041; // Record identifier
+ $length = 0x000A; // Number of bytes to follow
+
+ // Code specific to frozen or thawed panes.
+ if ($this->phpSheet->getFreezePane()) {
+ // Set default values for $rwTop and $colLeft
+ if (!isset($rwTop)) {
+ $rwTop = $y;
+ }
+ if (!isset($colLeft)) {
+ $colLeft = $x;
+ }
+ } else {
+ // Set default values for $rwTop and $colLeft
+ if (!isset($rwTop)) {
+ $rwTop = 0;
+ }
+ if (!isset($colLeft)) {
+ $colLeft = 0;
+ }
+
+ // Convert Excel's row and column units to the internal units.
+ // The default row height is 12.75
+ // The default column width is 8.43
+ // The following slope and intersection values were interpolated.
+ //
+ $y = 20*$y + 255;
+ $x = 113.879*$x + 390;
+ }
+
+
+ // Determine which pane should be active. There is also the undocumented
+ // option to override this should it be necessary: may be removed later.
+ //
+ if (!isset($pnnAct)) {
+ if ($x != 0 && $y != 0) {
+ $pnnAct = 0; // Bottom right
+ }
+ if ($x != 0 && $y == 0) {
+ $pnnAct = 1; // Top right
+ }
+ if ($x == 0 && $y != 0) {
+ $pnnAct = 2; // Bottom left
+ }
+ if ($x == 0 && $y == 0) {
+ $pnnAct = 3; // Top left
+ }
+ }
+
+ $this->activePane = $pnnAct; // Used in writeSelection
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the page setup SETUP BIFF record.
+ */
+ private function writeSetup()
+ {
+ $record = 0x00A1; // Record identifier
+ $length = 0x0022; // Number of bytes to follow
+
+ $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size
+
+ $iScale = $this->phpSheet->getPageSetup()->getScale() ?
+ $this->phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor
+
+ $iPageStart = 0x01; // Starting page number
+ $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
+ $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
+ $grbit = 0x00; // Option flags
+ $iRes = 0x0258; // Print resolution
+ $iVRes = 0x0258; // Vertical print resolution
+
+ $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin
+
+ $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin
+ $iCopies = 0x01; // Number of copies
+
+ $fLeftToRight = 0x0; // Print over then down
+
+ // Page orientation
+ $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ?
+ 0x0 : 0x1;
+
+ $fNoPls = 0x0; // Setup not read from printer
+ $fNoColor = 0x0; // Print black and white
+ $fDraft = 0x0; // Print draft quality
+ $fNotes = 0x0; // Print notes
+ $fNoOrient = 0x0; // Orientation not set
+ $fUsePage = 0x0; // Use custom starting page
+
+ $grbit = $fLeftToRight;
+ $grbit |= $fLandscape << 1;
+ $grbit |= $fNoPls << 2;
+ $grbit |= $fNoColor << 3;
+ $grbit |= $fDraft << 4;
+ $grbit |= $fNotes << 5;
+ $grbit |= $fNoOrient << 6;
+ $grbit |= $fUsePage << 7;
+
+ $numHdr = pack("d", $numHdr);
+ $numFtr = pack("d", $numFtr);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $numHdr = strrev($numHdr);
+ $numFtr = strrev($numFtr);
+ }
+
+ $header = pack("vv", $record, $length);
+ $data1 = pack("vvvvvvvv", $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes);
+ $data2 = $numHdr.$numFtr;
+ $data3 = pack("v", $iCopies);
+ $this->append($header . $data1 . $data2 . $data3);
+ }
+
+ /**
+ * Store the header caption BIFF record.
+ */
+ private function writeHeader()
+ {
+ $record = 0x0014; // Record identifier
+
+ /* removing for now
+ // need to fix character count (multibyte!)
+ if (strlen($this->phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
+ $str = $this->phpSheet->getHeaderFooter()->getOddHeader(); // header string
+ } else {
+ $str = '';
+ }
+ */
+
+ $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader());
+ $length = strlen($recordData);
+
+ $header = pack("vv", $record, $length);
+
+ $this->append($header . $recordData);
+ }
+
+ /**
+ * Store the footer caption BIFF record.
+ */
+ private function writeFooter()
+ {
+ $record = 0x0015; // Record identifier
+
+ /* removing for now
+ // need to fix character count (multibyte!)
+ if (strlen($this->phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
+ $str = $this->phpSheet->getHeaderFooter()->getOddFooter();
+ } else {
+ $str = '';
+ }
+ */
+
+ $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter());
+ $length = strlen($recordData);
+
+ $header = pack("vv", $record, $length);
+
+ $this->append($header . $recordData);
+ }
+
+ /**
+ * Store the horizontal centering HCENTER BIFF record.
+ *
+ * @access private
+ */
+ private function writeHcenter()
+ {
+ $record = 0x0083; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fHCenter);
+
+ $this->append($header.$data);
+ }
+
+ /**
+ * Store the vertical centering VCENTER BIFF record.
+ */
+ private function writeVcenter()
+ {
+ $record = 0x0084; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fVCenter);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the LEFTMARGIN BIFF record.
+ */
+ private function writeMarginLeft()
+ {
+ $record = 0x0026; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the RIGHTMARGIN BIFF record.
+ */
+ private function writeMarginRight()
+ {
+ $record = 0x0027; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the TOPMARGIN BIFF record.
+ */
+ private function writeMarginTop()
+ {
+ $record = 0x0028; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Store the BOTTOMMARGIN BIFF record.
+ */
+ private function writeMarginBottom()
+ {
+ $record = 0x0029; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches
+
+ $header = pack("vv", $record, $length);
+ $data = pack("d", $margin);
+ if (self::getByteOrder()) { // if it's Big Endian
+ $data = strrev($data);
+ }
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the PRINTHEADERS BIFF record.
+ */
+ private function writePrintHeaders()
+ {
+ $record = 0x002a; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fPrintRwCol = $this->_print_headers; // Boolean flag
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fPrintRwCol);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
+ * GRIDSET record.
+ */
+ private function writePrintGridlines()
+ {
+ $record = 0x002b; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fPrintGrid);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the GRIDSET BIFF record. Must be used in conjunction with the
+ * PRINTGRIDLINES record.
+ */
+ private function writeGridset()
+ {
+ $record = 0x0082; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fGridSet);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet.
+ */
+ private function writeAutoFilterInfo()
+ {
+ $record = 0x009D; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $rangeBounds = PHPExcel_Cell::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange());
+ $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0];
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $iNumFilters);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the GUTS BIFF record. This is used to configure the gutter margins
+ * where Excel outline symbols are displayed. The visibility of the gutters is
+ * controlled by a flag in WSBOOL.
+ *
+ * @see writeWsbool()
+ */
+ private function writeGuts()
+ {
+ $record = 0x0080; // Record identifier
+ $length = 0x0008; // Bytes to follow
+
+ $dxRwGut = 0x0000; // Size of row gutter
+ $dxColGut = 0x0000; // Size of col gutter
+
+ // determine maximum row outline level
+ $maxRowOutlineLevel = 0;
+ foreach ($this->phpSheet->getRowDimensions() as $rowDimension) {
+ $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
+ }
+
+ $col_level = 0;
+
+ // Calculate the maximum column outline level. The equivalent calculation
+ // for the row outline level is carried out in writeRow().
+ $colcount = count($this->columnInfo);
+ for ($i = 0; $i < $colcount; ++$i) {
+ $col_level = max($this->columnInfo[$i][5], $col_level);
+ }
+
+ // Set the limits for the outline levels (0 <= x <= 7).
+ $col_level = max(0, min($col_level, 7));
+
+ // The displayed level is one greater than the max outline levels
+ if ($maxRowOutlineLevel) {
+ ++$maxRowOutlineLevel;
+ }
+ if ($col_level) {
+ ++$col_level;
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
+
+ $this->append($header.$data);
+ }
+
+ /**
+ * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
+ * with the SETUP record.
+ */
+ private function writeWsbool()
+ {
+ $record = 0x0081; // Record identifier
+ $length = 0x0002; // Bytes to follow
+ $grbit = 0x0000;
+
+ // The only option that is of interest is the flag for fit to page. So we
+ // set all the options in one go.
+ //
+ // Set the option flags
+ $grbit |= 0x0001; // Auto page breaks visible
+ if ($this->outlineStyle) {
+ $grbit |= 0x0020; // Auto outline styles
+ }
+ if ($this->phpSheet->getShowSummaryBelow()) {
+ $grbit |= 0x0040; // Outline summary below
+ }
+ if ($this->phpSheet->getShowSummaryRight()) {
+ $grbit |= 0x0080; // Outline summary right
+ }
+ if ($this->phpSheet->getPageSetup()->getFitToPage()) {
+ $grbit |= 0x0100; // Page setup fit to page
+ }
+ if ($this->outlineOn) {
+ $grbit |= 0x0400; // Outline symbols displayed
+ }
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $grbit);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
+ */
+ private function writeBreaks()
+ {
+ // initialize
+ $vbreaks = array();
+ $hbreaks = array();
+
+ foreach ($this->phpSheet->getBreaks() as $cell => $breakType) {
+ // Fetch coordinates
+ $coordinates = PHPExcel_Cell::coordinateFromString($cell);
+
+ // Decide what to do by the type of break
+ switch ($breakType) {
+ case PHPExcel_Worksheet::BREAK_COLUMN:
+ // Add to list of vertical breaks
+ $vbreaks[] = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1;
+ break;
+ case PHPExcel_Worksheet::BREAK_ROW:
+ // Add to list of horizontal breaks
+ $hbreaks[] = $coordinates[1];
+ break;
+ case PHPExcel_Worksheet::BREAK_NONE:
+ default:
+ // Nothing to do
+ break;
+ }
+ }
+
+ //horizontal page breaks
+ if (!empty($hbreaks)) {
+ // Sort and filter array of page breaks
+ sort($hbreaks, SORT_NUMERIC);
+ if ($hbreaks[0] == 0) { // don't use first break if it's 0
+ array_shift($hbreaks);
+ }
+
+ $record = 0x001b; // Record identifier
+ $cbrk = count($hbreaks); // Number of page breaks
+ $length = 2 + 6 * $cbrk; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $cbrk);
+
+ // Append each page break
+ foreach ($hbreaks as $hbreak) {
+ $data .= pack("vvv", $hbreak, 0x0000, 0x00ff);
+ }
+
+ $this->append($header . $data);
+ }
+
+ // vertical page breaks
+ if (!empty($vbreaks)) {
+ // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
+ // It is slightly higher in Excel 97/200, approx. 1026
+ $vbreaks = array_slice($vbreaks, 0, 1000);
+
+ // Sort and filter array of page breaks
+ sort($vbreaks, SORT_NUMERIC);
+ if ($vbreaks[0] == 0) { // don't use first break if it's 0
+ array_shift($vbreaks);
+ }
+
+ $record = 0x001a; // Record identifier
+ $cbrk = count($vbreaks); // Number of page breaks
+ $length = 2 + 6 * $cbrk; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $cbrk);
+
+ // Append each page break
+ foreach ($vbreaks as $vbreak) {
+ $data .= pack("vvv", $vbreak, 0x0000, 0xffff);
+ }
+
+ $this->append($header . $data);
+ }
+ }
+
+ /**
+ * Set the Biff PROTECT record to indicate that the worksheet is protected.
+ */
+ private function writeProtect()
+ {
+ // Exit unless sheet protection has been specified
+ if (!$this->phpSheet->getProtection()->getSheet()) {
+ return;
+ }
+
+ $record = 0x0012; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $fLock = 1; // Worksheet is protected
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $fLock);
+
+ $this->append($header.$data);
+ }
+
+ /**
+ * Write SCENPROTECT
+ */
+ private function writeScenProtect()
+ {
+ // Exit if sheet protection is not active
+ if (!$this->phpSheet->getProtection()->getSheet()) {
+ return;
+ }
+
+ // Exit if scenarios are not protected
+ if (!$this->phpSheet->getProtection()->getScenarios()) {
+ return;
+ }
+
+ $record = 0x00DD; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $header = pack('vv', $record, $length);
+ $data = pack('v', 1);
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write OBJECTPROTECT
+ */
+ private function writeObjectProtect()
+ {
+ // Exit if sheet protection is not active
+ if (!$this->phpSheet->getProtection()->getSheet()) {
+ return;
+ }
+
+ // Exit if objects are not protected
+ if (!$this->phpSheet->getProtection()->getObjects()) {
+ return;
+ }
+
+ $record = 0x0063; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $header = pack('vv', $record, $length);
+ $data = pack('v', 1);
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write the worksheet PASSWORD record.
+ */
+ private function writePassword()
+ {
+ // Exit unless sheet protection and password have been specified
+ if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword()) {
+ return;
+ }
+
+ $record = 0x0013; // Record identifier
+ $length = 0x0002; // Bytes to follow
+
+ $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password
+
+ $header = pack("vv", $record, $length);
+ $data = pack("v", $wPassword);
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Insert a 24bit bitmap image in a worksheet.
+ *
+ * @access public
+ * @param integer $row The row we are going to insert the bitmap into
+ * @param integer $col The column we are going to insert the bitmap into
+ * @param mixed $bitmap The bitmap filename or GD-image resource
+ * @param integer $x The horizontal position (offset) of the image inside the cell.
+ * @param integer $y The vertical position (offset) of the image inside the cell.
+ * @param float $scale_x The horizontal scale
+ * @param float $scale_y The vertical scale
+ */
+ public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1)
+ {
+ $bitmap_array = (is_resource($bitmap) ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap));
+ list($width, $height, $size, $data) = $bitmap_array; //$this->processBitmap($bitmap);
+
+ // Scale the frame of the image.
+ $width *= $scale_x;
+ $height *= $scale_y;
+
+ // Calculate the vertices of the image and write the OBJ record
+ $this->positionImage($col, $row, $x, $y, $width, $height);
+
+ // Write the IMDATA record to store the bitmap data
+ $record = 0x007f;
+ $length = 8 + $size;
+ $cf = 0x09;
+ $env = 0x01;
+ $lcb = $size;
+
+ $header = pack("vvvvV", $record, $length, $cf, $env, $lcb);
+ $this->append($header.$data);
+ }
+
+ /**
+ * Calculate the vertices that define the position of the image as required by
+ * the OBJ record.
+ *
+ * +------------+------------+
+ * | A | B |
+ * +-----+------------+------------+
+ * | |(x1,y1) | |
+ * | 1 |(A1)._______|______ |
+ * | | | | |
+ * | | | | |
+ * +-----+----| BITMAP |-----+
+ * | | | | |
+ * | 2 | |______________. |
+ * | | | (B2)|
+ * | | | (x2,y2)|
+ * +---- +------------+------------+
+ *
+ * Example of a bitmap that covers some of the area from cell A1 to cell B2.
+ *
+ * Based on the width and height of the bitmap we need to calculate 8 vars:
+ * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
+ * The width and height of the cells are also variable and have to be taken into
+ * account.
+ * The values of $col_start and $row_start are passed in from the calling
+ * function. The values of $col_end and $row_end are calculated by subtracting
+ * the width and height of the bitmap from the width and height of the
+ * underlying cells.
+ * The vertices are expressed as a percentage of the underlying cell width as
+ * follows (rhs values are in pixels):
+ *
+ * x1 = X / W *1024
+ * y1 = Y / H *256
+ * x2 = (X-1) / W *1024
+ * y2 = (Y-1) / H *256
+ *
+ * Where: X is distance from the left side of the underlying cell
+ * Y is distance from the top of the underlying cell
+ * W is the width of the cell
+ * H is the height of the cell
+ * The SDK incorrectly states that the height should be expressed as a
+ * percentage of 1024.
+ *
+ * @access private
+ * @param integer $col_start Col containing upper left corner of object
+ * @param integer $row_start Row containing top left corner of object
+ * @param integer $x1 Distance to left side of object
+ * @param integer $y1 Distance to top of object
+ * @param integer $width Width of image frame
+ * @param integer $height Height of image frame
+ */
+ public function positionImage($col_start, $row_start, $x1, $y1, $width, $height)
+ {
+ // Initialise end cell to the same as the start cell
+ $col_end = $col_start; // Col containing lower right corner of object
+ $row_end = $row_start; // Row containing bottom right corner of object
+
+ // Zero the specified offset if greater than the cell dimensions
+ if ($x1 >= PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) {
+ $x1 = 0;
+ }
+ if ($y1 >= PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_start + 1)) {
+ $y1 = 0;
+ }
+
+ $width = $width + $x1 -1;
+ $height = $height + $y1 -1;
+
+ // Subtract the underlying cell widths to find the end cell of the image
+ while ($width >= PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) {
+ $width -= PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end));
+ ++$col_end;
+ }
+
+ // Subtract the underlying cell heights to find the end cell of the image
+ while ($height >= PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1)) {
+ $height -= PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1);
+ ++$row_end;
+ }
+
+ // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
+ // with zero eight or width.
+ //
+ if (PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) {
+ return;
+ }
+ if (PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) {
+ return;
+ }
+ if (PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_start + 1) == 0) {
+ return;
+ }
+ if (PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1) == 0) {
+ return;
+ }
+
+ // Convert the pixel values to the percentage value expected by Excel
+ $x1 = $x1 / PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024;
+ $y1 = $y1 / PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_start + 1) * 256;
+ $x2 = $width / PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
+ $y2 = $height / PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object
+
+ $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2);
+ }
+
+ /**
+ * Store the OBJ record that precedes an IMDATA record. This could be generalise
+ * to support other Excel objects.
+ *
+ * @param integer $colL Column containing upper left corner of object
+ * @param integer $dxL Distance from left side of cell
+ * @param integer $rwT Row containing top left corner of object
+ * @param integer $dyT Distance from top of cell
+ * @param integer $colR Column containing lower right corner of object
+ * @param integer $dxR Distance from right of cell
+ * @param integer $rwB Row containing bottom right corner of object
+ * @param integer $dyB Distance from bottom of cell
+ */
+ private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB)
+ {
+ $record = 0x005d; // Record identifier
+ $length = 0x003c; // Bytes to follow
+
+ $cObj = 0x0001; // Count of objects in file (set to 1)
+ $OT = 0x0008; // Object type. 8 = Picture
+ $id = 0x0001; // Object ID
+ $grbit = 0x0614; // Option flags
+
+ $cbMacro = 0x0000; // Length of FMLA structure
+ $Reserved1 = 0x0000; // Reserved
+ $Reserved2 = 0x0000; // Reserved
+
+ $icvBack = 0x09; // Background colour
+ $icvFore = 0x09; // Foreground colour
+ $fls = 0x00; // Fill pattern
+ $fAuto = 0x00; // Automatic fill
+ $icv = 0x08; // Line colour
+ $lns = 0xff; // Line style
+ $lnw = 0x01; // Line weight
+ $fAutoB = 0x00; // Automatic border
+ $frs = 0x0000; // Frame style
+ $cf = 0x0009; // Image format, 9 = bitmap
+ $Reserved3 = 0x0000; // Reserved
+ $cbPictFmla = 0x0000; // Length of FMLA structure
+ $Reserved4 = 0x0000; // Reserved
+ $grbit2 = 0x0001; // Option flags
+ $Reserved5 = 0x0000; // Reserved
+
+
+ $header = pack("vv", $record, $length);
+ $data = pack("V", $cObj);
+ $data .= pack("v", $OT);
+ $data .= pack("v", $id);
+ $data .= pack("v", $grbit);
+ $data .= pack("v", $colL);
+ $data .= pack("v", $dxL);
+ $data .= pack("v", $rwT);
+ $data .= pack("v", $dyT);
+ $data .= pack("v", $colR);
+ $data .= pack("v", $dxR);
+ $data .= pack("v", $rwB);
+ $data .= pack("v", $dyB);
+ $data .= pack("v", $cbMacro);
+ $data .= pack("V", $Reserved1);
+ $data .= pack("v", $Reserved2);
+ $data .= pack("C", $icvBack);
+ $data .= pack("C", $icvFore);
+ $data .= pack("C", $fls);
+ $data .= pack("C", $fAuto);
+ $data .= pack("C", $icv);
+ $data .= pack("C", $lns);
+ $data .= pack("C", $lnw);
+ $data .= pack("C", $fAutoB);
+ $data .= pack("v", $frs);
+ $data .= pack("V", $cf);
+ $data .= pack("v", $Reserved3);
+ $data .= pack("v", $cbPictFmla);
+ $data .= pack("v", $Reserved4);
+ $data .= pack("v", $grbit2);
+ $data .= pack("V", $Reserved5);
+
+ $this->append($header . $data);
+ }
+
+ /**
+ * Convert a GD-image into the internal format.
+ *
+ * @access private
+ * @param resource $image The image to process
+ * @return array Array with data and properties of the bitmap
+ */
+ public function processBitmapGd($image)
+ {
+ $width = imagesx($image);
+ $height = imagesy($image);
+
+ $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
+ for ($j=$height; $j--;) {
+ for ($i=0; $i < $width; ++$i) {
+ $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
+ foreach (array("red", "green", "blue") as $key) {
+ $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127);
+ }
+ $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]);
+ }
+ if (3*$width % 4) {
+ $data .= str_repeat("\x00", 4 - 3*$width % 4);
+ }
+ }
+
+ return array($width, $height, strlen($data), $data);
+ }
+
+ /**
+ * Convert a 24 bit bitmap into the modified internal format used by Windows.
+ * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the
+ * MSDN library.
+ *
+ * @access private
+ * @param string $bitmap The bitmap to process
+ * @return array Array with data and properties of the bitmap
+ */
+ public function processBitmap($bitmap)
+ {
+ // Open file.
+ $bmp_fd = @fopen($bitmap, "rb");
+ if (!$bmp_fd) {
+ throw new PHPExcel_Writer_Exception("Couldn't import $bitmap");
+ }
+
+ // Slurp the file into a string.
+ $data = fread($bmp_fd, filesize($bitmap));
+
+ // Check that the file is big enough to be a bitmap.
+ if (strlen($data) <= 0x36) {
+ throw new PHPExcel_Writer_Exception("$bitmap doesn't contain enough data.\n");
+ }
+
+ // The first 2 bytes are used to identify the bitmap.
+ $identity = unpack("A2ident", $data);
+ if ($identity['ident'] != "BM") {
+ throw new PHPExcel_Writer_Exception("$bitmap doesn't appear to be a valid bitmap image.\n");
+ }
+
+ // Remove bitmap data: ID.
+ $data = substr($data, 2);
+
+ // Read and remove the bitmap size. This is more reliable than reading
+ // the data size at offset 0x22.
+ //
+ $size_array = unpack("Vsa", substr($data, 0, 4));
+ $size = $size_array['sa'];
+ $data = substr($data, 4);
+ $size -= 0x36; // Subtract size of bitmap header.
+ $size += 0x0C; // Add size of BIFF header.
+
+ // Remove bitmap data: reserved, offset, header length.
+ $data = substr($data, 12);
+
+ // Read and remove the bitmap width and height. Verify the sizes.
+ $width_and_height = unpack("V2", substr($data, 0, 8));
+ $width = $width_and_height[1];
+ $height = $width_and_height[2];
+ $data = substr($data, 8);
+ if ($width > 0xFFFF) {
+ throw new PHPExcel_Writer_Exception("$bitmap: largest image width supported is 65k.\n");
+ }
+ if ($height > 0xFFFF) {
+ throw new PHPExcel_Writer_Exception("$bitmap: largest image height supported is 65k.\n");
+ }
+
+ // Read and remove the bitmap planes and bpp data. Verify them.
+ $planes_and_bitcount = unpack("v2", substr($data, 0, 4));
+ $data = substr($data, 4);
+ if ($planes_and_bitcount[2] != 24) { // Bitcount
+ throw new PHPExcel_Writer_Exception("$bitmap isn't a 24bit true color bitmap.\n");
+ }
+ if ($planes_and_bitcount[1] != 1) {
+ throw new PHPExcel_Writer_Exception("$bitmap: only 1 plane supported in bitmap image.\n");
+ }
+
+ // Read and remove the bitmap compression. Verify compression.
+ $compression = unpack("Vcomp", substr($data, 0, 4));
+ $data = substr($data, 4);
+
+ //$compression = 0;
+ if ($compression['comp'] != 0) {
+ throw new PHPExcel_Writer_Exception("$bitmap: compression not supported in bitmap image.\n");
+ }
+
+ // Remove bitmap data: data size, hres, vres, colours, imp. colours.
+ $data = substr($data, 20);
+
+ // Add the BITMAPCOREHEADER data
+ $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18);
+ $data = $header . $data;
+
+ return (array($width, $height, $size, $data));
+ }
+
+ /**
+ * Store the window zoom factor. This should be a reduced fraction but for
+ * simplicity we will store all fractions with a numerator of 100.
+ */
+ private function writeZoom()
+ {
+ // If scale is 100 we don't need to write a record
+ if ($this->phpSheet->getSheetView()->getZoomScale() == 100) {
+ return;
+ }
+
+ $record = 0x00A0; // Record identifier
+ $length = 0x0004; // Bytes to follow
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vv", $this->phpSheet->getSheetView()->getZoomScale(), 100);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Get Escher object
+ *
+ * @return PHPExcel_Shared_Escher
+ */
+ public function getEscher()
+ {
+ return $this->escher;
+ }
+
+ /**
+ * Set Escher object
+ *
+ * @param PHPExcel_Shared_Escher $pValue
+ */
+ public function setEscher(PHPExcel_Shared_Escher $pValue = null)
+ {
+ $this->escher = $pValue;
+ }
+
+ /**
+ * Write MSODRAWING record
+ */
+ private function writeMsoDrawing()
+ {
+ // write the Escher stream if necessary
+ if (isset($this->escher)) {
+ $writer = new PHPExcel_Writer_Excel5_Escher($this->escher);
+ $data = $writer->close();
+ $spOffsets = $writer->getSpOffsets();
+ $spTypes = $writer->getSpTypes();
+ // write the neccesary MSODRAWING, OBJ records
+
+ // split the Escher stream
+ $spOffsets[0] = 0;
+ $nm = count($spOffsets) - 1; // number of shapes excluding first shape
+ for ($i = 1; $i <= $nm; ++$i) {
+ // MSODRAWING record
+ $record = 0x00EC; // Record identifier
+
+ // chunk of Escher stream for one shape
+ $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);
+
+ $length = strlen($dataChunk);
+ $header = pack("vv", $record, $length);
+
+ $this->append($header . $dataChunk);
+
+ // OBJ record
+ $record = 0x005D; // record identifier
+ $objData = '';
+
+ // ftCmo
+ if ($spTypes[$i] == 0x00C9) {
+ // Add ftCmo (common object data) subobject
+ $objData .=
+ pack(
+ 'vvvvvVVV',
+ 0x0015, // 0x0015 = ftCmo
+ 0x0012, // length of ftCmo data
+ 0x0014, // object type, 0x0014 = filter
+ $i, // object id number, Excel seems to use 1-based index, local for the sheet
+ 0x2101, // option flags, 0x2001 is what OpenOffice.org uses
+ 0, // reserved
+ 0, // reserved
+ 0 // reserved
+ );
+
+ // Add ftSbs Scroll bar subobject
+ $objData .= pack('vv', 0x00C, 0x0014);
+ $objData .= pack('H*', '0000000000000000640001000A00000010000100');
+ // Add ftLbsData (List box data) subobject
+ $objData .= pack('vv', 0x0013, 0x1FEE);
+ $objData .= pack('H*', '00000000010001030000020008005700');
+ } else {
+ // Add ftCmo (common object data) subobject
+ $objData .=
+ pack(
+ 'vvvvvVVV',
+ 0x0015, // 0x0015 = ftCmo
+ 0x0012, // length of ftCmo data
+ 0x0008, // object type, 0x0008 = picture
+ $i, // object id number, Excel seems to use 1-based index, local for the sheet
+ 0x6011, // option flags, 0x6011 is what OpenOffice.org uses
+ 0, // reserved
+ 0, // reserved
+ 0 // reserved
+ );
+ }
+
+ // ftEnd
+ $objData .=
+ pack(
+ 'vv',
+ 0x0000, // 0x0000 = ftEnd
+ 0x0000 // length of ftEnd data
+ );
+
+ $length = strlen($objData);
+ $header = pack('vv', $record, $length);
+ $this->append($header . $objData);
+ }
+ }
+ }
+
+ /**
+ * Store the DATAVALIDATIONS and DATAVALIDATION records.
+ */
+ private function writeDataValidity()
+ {
+ // Datavalidation collection
+ $dataValidationCollection = $this->phpSheet->getDataValidationCollection();
+
+ // Write data validations?
+ if (!empty($dataValidationCollection)) {
+ // DATAVALIDATIONS record
+ $record = 0x01B2; // Record identifier
+ $length = 0x0012; // Bytes to follow
+
+ $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
+ $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
+ $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
+ $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection));
+ $this->append($header.$data);
+
+ // DATAVALIDATION records
+ $record = 0x01BE; // Record identifier
+
+ foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
+ // initialize record data
+ $data = '';
+
+ // options
+ $options = 0x00000000;
+
+ // data type
+ $type = $dataValidation->getType();
+ switch ($type) {
+ case PHPExcel_Cell_DataValidation::TYPE_NONE:
+ $type = 0x00;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_WHOLE:
+ $type = 0x01;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_DECIMAL:
+ $type = 0x02;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_LIST:
+ $type = 0x03;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_DATE:
+ $type = 0x04;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_TIME:
+ $type = 0x05;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH:
+ $type = 0x06;
+ break;
+ case PHPExcel_Cell_DataValidation::TYPE_CUSTOM:
+ $type = 0x07;
+ break;
+ }
+ $options |= $type << 0;
+
+ // error style
+ $errorStyle = $dataValidation->getType();
+ switch ($errorStyle) {
+ case PHPExcel_Cell_DataValidation::STYLE_STOP:
+ $errorStyle = 0x00;
+ break;
+ case PHPExcel_Cell_DataValidation::STYLE_WARNING:
+ $errorStyle = 0x01;
+ break;
+ case PHPExcel_Cell_DataValidation::STYLE_INFORMATION:
+ $errorStyle = 0x02;
+ break;
+ }
+ $options |= $errorStyle << 4;
+
+ // explicit formula?
+ if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
+ $options |= 0x01 << 7;
+ }
+
+ // empty cells allowed
+ $options |= $dataValidation->getAllowBlank() << 8;
+
+ // show drop down
+ $options |= (!$dataValidation->getShowDropDown()) << 9;
+
+ // show input message
+ $options |= $dataValidation->getShowInputMessage() << 18;
+
+ // show error message
+ $options |= $dataValidation->getShowErrorMessage() << 19;
+
+ // condition operator
+ $operator = $dataValidation->getOperator();
+ switch ($operator) {
+ case PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN:
+ $operator = 0x00;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN:
+ $operator = 0x01;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_EQUAL:
+ $operator = 0x02;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL:
+ $operator = 0x03;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN:
+ $operator = 0x04;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN:
+ $operator = 0x05;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL:
+ $operator = 0x06;
+ break;
+ case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL:
+ $operator = 0x07;
+ break;
+ }
+ $options |= $operator << 20;
+
+ $data = pack('V', $options);
+
+ // prompt title
+ $promptTitle = $dataValidation->getPromptTitle() !== '' ?
+ $dataValidation->getPromptTitle() : chr(0);
+ $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($promptTitle);
+
+ // error title
+ $errorTitle = $dataValidation->getErrorTitle() !== '' ?
+ $dataValidation->getErrorTitle() : chr(0);
+ $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($errorTitle);
+
+ // prompt text
+ $prompt = $dataValidation->getPrompt() !== '' ?
+ $dataValidation->getPrompt() : chr(0);
+ $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($prompt);
+
+ // error text
+ $error = $dataValidation->getError() !== '' ?
+ $dataValidation->getError() : chr(0);
+ $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($error);
+
+ // formula 1
+ try {
+ $formula1 = $dataValidation->getFormula1();
+ if ($type == 0x03) { // list type
+ $formula1 = str_replace(',', chr(0), $formula1);
+ }
+ $this->parser->parse($formula1);
+ $formula1 = $this->parser->toReversePolish();
+ $sz1 = strlen($formula1);
+ } catch (PHPExcel_Exception $e) {
+ $sz1 = 0;
+ $formula1 = '';
+ }
+ $data .= pack('vv', $sz1, 0x0000);
+ $data .= $formula1;
+
+ // formula 2
+ try {
+ $formula2 = $dataValidation->getFormula2();
+ if ($formula2 === '') {
+ throw new PHPExcel_Writer_Exception('No formula2');
+ }
+ $this->parser->parse($formula2);
+ $formula2 = $this->parser->toReversePolish();
+ $sz2 = strlen($formula2);
+ } catch (PHPExcel_Exception $e) {
+ $sz2 = 0;
+ $formula2 = '';
+ }
+ $data .= pack('vv', $sz2, 0x0000);
+ $data .= $formula2;
+
+ // cell range address list
+ $data .= pack('v', 0x0001);
+ $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate);
+
+ $length = strlen($data);
+ $header = pack("vv", $record, $length);
+
+ $this->append($header . $data);
+ }
+ }
+ }
+
+ /**
+ * Map Error code
+ *
+ * @param string $errorCode
+ * @return int
+ */
+ private static function mapErrorCode($errorCode)
+ {
+ switch ($errorCode) {
+ case '#NULL!':
+ return 0x00;
+ case '#DIV/0!':
+ return 0x07;
+ case '#VALUE!':
+ return 0x0F;
+ case '#REF!':
+ return 0x17;
+ case '#NAME?':
+ return 0x1D;
+ case '#NUM!':
+ return 0x24;
+ case '#N/A':
+ return 0x2A;
+ }
+
+ return 0;
+ }
+
+ /**
+ * Write PLV Record
+ */
+ private function writePageLayoutView()
+ {
+ $record = 0x088B; // Record identifier
+ $length = 0x0010; // Bytes to follow
+
+ $rt = 0x088B; // 2
+ $grbitFrt = 0x0000; // 2
+ $reserved = 0x0000000000000000; // 8
+ $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2
+
+ // The options flags that comprise $grbit
+ if ($this->phpSheet->getSheetView()->getView() == PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT) {
+ $fPageLayoutView = 1;
+ } else {
+ $fPageLayoutView = 0;
+ }
+ $fRulerVisible = 0;
+ $fWhitespaceHidden = 0;
+
+ $grbit = $fPageLayoutView; // 2
+ $grbit |= $fRulerVisible << 1;
+ $grbit |= $fWhitespaceHidden << 3;
+
+ $header = pack("vv", $record, $length);
+ $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit);
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write CFRule Record
+ * @param PHPExcel_Style_Conditional $conditional
+ */
+ private function writeCFRule(PHPExcel_Style_Conditional $conditional)
+ {
+ $record = 0x01B1; // Record identifier
+
+ // $type : Type of the CF
+ // $operatorType : Comparison operator
+ if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) {
+ $type = 0x02;
+ $operatorType = 0x00;
+ } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS) {
+ $type = 0x01;
+
+ switch ($conditional->getOperatorType()) {
+ case PHPExcel_Style_Conditional::OPERATOR_NONE:
+ $operatorType = 0x00;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_EQUAL:
+ $operatorType = 0x03;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_GREATERTHAN:
+ $operatorType = 0x05;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_GREATERTHANOREQUAL:
+ $operatorType = 0x07;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_LESSTHAN:
+ $operatorType = 0x06;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_LESSTHANOREQUAL:
+ $operatorType = 0x08;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_NOTEQUAL:
+ $operatorType = 0x04;
+ break;
+ case PHPExcel_Style_Conditional::OPERATOR_BETWEEN:
+ $operatorType = 0x01;
+ break;
+ // not OPERATOR_NOTBETWEEN 0x02
+ }
+ }
+
+ // $szValue1 : size of the formula data for first value or formula
+ // $szValue2 : size of the formula data for second value or formula
+ $arrConditions = $conditional->getConditions();
+ $numConditions = sizeof($arrConditions);
+ if ($numConditions == 1) {
+ $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
+ $szValue2 = 0x0000;
+ $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
+ $operand2 = null;
+ } elseif ($numConditions == 2 && ($conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BETWEEN)) {
+ $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
+ $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000);
+ $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
+ $operand2 = pack('Cv', 0x1E, $arrConditions[1]);
+ } else {
+ $szValue1 = 0x0000;
+ $szValue2 = 0x0000;
+ $operand1 = null;
+ $operand2 = null;
+ }
+
+ // $flags : Option flags
+ // Alignment
+ $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0);
+ $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0);
+ $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0);
+ $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0);
+ $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0);
+ $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0);
+ if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) {
+ $bFormatAlign = 1;
+ } else {
+ $bFormatAlign = 0;
+ }
+ // Protection
+ $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0);
+ $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0);
+ if ($bProtLocked == 0 || $bProtHidden == 0) {
+ $bFormatProt = 1;
+ } else {
+ $bFormatProt = 0;
+ }
+ // Border
+ $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
+ $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
+ $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
+ $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK
+ && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0);
+ if ($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0) {
+ $bFormatBorder = 1;
+ } else {
+ $bFormatBorder = 0;
+ }
+ // Pattern
+ $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1);
+ $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1);
+ $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1);
+ if ($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0) {
+ $bFormatFill = 1;
+ } else {
+ $bFormatFill = 0;
+ }
+ // Font
+ if ($conditional->getStyle()->getFont()->getName() != null
+ || $conditional->getStyle()->getFont()->getSize() != null
+ || $conditional->getStyle()->getFont()->getBold() != null
+ || $conditional->getStyle()->getFont()->getItalic() != null
+ || $conditional->getStyle()->getFont()->getSuperScript() != null
+ || $conditional->getStyle()->getFont()->getSubScript() != null
+ || $conditional->getStyle()->getFont()->getUnderline() != null
+ || $conditional->getStyle()->getFont()->getStrikethrough() != null
+ || $conditional->getStyle()->getFont()->getColor()->getARGB() != null) {
+ $bFormatFont = 1;
+ } else {
+ $bFormatFont = 0;
+ }
+ // Alignment
+ $flags = 0;
+ $flags |= (1 == $bAlignHz ? 0x00000001 : 0);
+ $flags |= (1 == $bAlignVt ? 0x00000002 : 0);
+ $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0);
+ $flags |= (1 == $bTxRotation ? 0x00000008 : 0);
+ // Justify last line flag
+ $flags |= (1 == 1 ? 0x00000010 : 0);
+ $flags |= (1 == $bIndent ? 0x00000020 : 0);
+ $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0);
+ // Default
+ $flags |= (1 == 1 ? 0x00000080 : 0);
+ // Protection
+ $flags |= (1 == $bProtLocked ? 0x00000100 : 0);
+ $flags |= (1 == $bProtHidden ? 0x00000200 : 0);
+ // Border
+ $flags |= (1 == $bBorderLeft ? 0x00000400 : 0);
+ $flags |= (1 == $bBorderRight ? 0x00000800 : 0);
+ $flags |= (1 == $bBorderTop ? 0x00001000 : 0);
+ $flags |= (1 == $bBorderBottom ? 0x00002000 : 0);
+ $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border
+ $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border
+ // Pattern
+ $flags |= (1 == $bFillStyle ? 0x00010000 : 0);
+ $flags |= (1 == $bFillColor ? 0x00020000 : 0);
+ $flags |= (1 == $bFillColorBg ? 0x00040000 : 0);
+ $flags |= (1 == 1 ? 0x00380000 : 0);
+ // Font
+ $flags |= (1 == $bFormatFont ? 0x04000000 : 0);
+ // Alignment:
+ $flags |= (1 == $bFormatAlign ? 0x08000000 : 0);
+ // Border
+ $flags |= (1 == $bFormatBorder ? 0x10000000 : 0);
+ // Pattern
+ $flags |= (1 == $bFormatFill ? 0x20000000 : 0);
+ // Protection
+ $flags |= (1 == $bFormatProt ? 0x40000000 : 0);
+ // Text direction
+ $flags |= (1 == 0 ? 0x80000000 : 0);
+
+ // Data Blocks
+ if ($bFormatFont == 1) {
+ // Font Name
+ if ($conditional->getStyle()->getFont()->getName() == null) {
+ $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
+ $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
+ } else {
+ $dataBlockFont = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName());
+ }
+ // Font Size
+ if ($conditional->getStyle()->getFont()->getSize() == null) {
+ $dataBlockFont .= pack('V', 20 * 11);
+ } else {
+ $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize());
+ }
+ // Font Options
+ $dataBlockFont .= pack('V', 0);
+ // Font weight
+ if ($conditional->getStyle()->getFont()->getBold() == true) {
+ $dataBlockFont .= pack('v', 0x02BC);
+ } else {
+ $dataBlockFont .= pack('v', 0x0190);
+ }
+ // Escapement type
+ if ($conditional->getStyle()->getFont()->getSubScript() == true) {
+ $dataBlockFont .= pack('v', 0x02);
+ $fontEscapement = 0;
+ } elseif ($conditional->getStyle()->getFont()->getSuperScript() == true) {
+ $dataBlockFont .= pack('v', 0x01);
+ $fontEscapement = 0;
+ } else {
+ $dataBlockFont .= pack('v', 0x00);
+ $fontEscapement = 1;
+ }
+ // Underline type
+ switch ($conditional->getStyle()->getFont()->getUnderline()) {
+ case PHPExcel_Style_Font::UNDERLINE_NONE:
+ $dataBlockFont .= pack('C', 0x00);
+ $fontUnderline = 0;
+ break;
+ case PHPExcel_Style_Font::UNDERLINE_DOUBLE:
+ $dataBlockFont .= pack('C', 0x02);
+ $fontUnderline = 0;
+ break;
+ case PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING:
+ $dataBlockFont .= pack('C', 0x22);
+ $fontUnderline = 0;
+ break;
+ case PHPExcel_Style_Font::UNDERLINE_SINGLE:
+ $dataBlockFont .= pack('C', 0x01);
+ $fontUnderline = 0;
+ break;
+ case PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING:
+ $dataBlockFont .= pack('C', 0x21);
+ $fontUnderline = 0;
+ break;
+ default: $dataBlockFont .= pack('C', 0x00);
+ $fontUnderline = 1;
+ break;
+ }
+ // Not used (3)
+ $dataBlockFont .= pack('vC', 0x0000, 0x00);
+ // Font color index
+ switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) {
+ case '000000':
+ $colorIdx = 0x08;
+ break;
+ case 'FFFFFF':
+ $colorIdx = 0x09;
+ break;
+ case 'FF0000':
+ $colorIdx = 0x0A;
+ break;
+ case '00FF00':
+ $colorIdx = 0x0B;
+ break;
+ case '0000FF':
+ $colorIdx = 0x0C;
+ break;
+ case 'FFFF00':
+ $colorIdx = 0x0D;
+ break;
+ case 'FF00FF':
+ $colorIdx = 0x0E;
+ break;
+ case '00FFFF':
+ $colorIdx = 0x0F;
+ break;
+ case '800000':
+ $colorIdx = 0x10;
+ break;
+ case '008000':
+ $colorIdx = 0x11;
+ break;
+ case '000080':
+ $colorIdx = 0x12;
+ break;
+ case '808000':
+ $colorIdx = 0x13;
+ break;
+ case '800080':
+ $colorIdx = 0x14;
+ break;
+ case '008080':
+ $colorIdx = 0x15;
+ break;
+ case 'C0C0C0':
+ $colorIdx = 0x16;
+ break;
+ case '808080':
+ $colorIdx = 0x17;
+ break;
+ case '9999FF':
+ $colorIdx = 0x18;
+ break;
+ case '993366':
+ $colorIdx = 0x19;
+ break;
+ case 'FFFFCC':
+ $colorIdx = 0x1A;
+ break;
+ case 'CCFFFF':
+ $colorIdx = 0x1B;
+ break;
+ case '660066':
+ $colorIdx = 0x1C;
+ break;
+ case 'FF8080':
+ $colorIdx = 0x1D;
+ break;
+ case '0066CC':
+ $colorIdx = 0x1E;
+ break;
+ case 'CCCCFF':
+ $colorIdx = 0x1F;
+ break;
+ case '000080':
+ $colorIdx = 0x20;
+ break;
+ case 'FF00FF':
+ $colorIdx = 0x21;
+ break;
+ case 'FFFF00':
+ $colorIdx = 0x22;
+ break;
+ case '00FFFF':
+ $colorIdx = 0x23;
+ break;
+ case '800080':
+ $colorIdx = 0x24;
+ break;
+ case '800000':
+ $colorIdx = 0x25;
+ break;
+ case '008080':
+ $colorIdx = 0x26;
+ break;
+ case '0000FF':
+ $colorIdx = 0x27;
+ break;
+ case '00CCFF':
+ $colorIdx = 0x28;
+ break;
+ case 'CCFFFF':
+ $colorIdx = 0x29;
+ break;
+ case 'CCFFCC':
+ $colorIdx = 0x2A;
+ break;
+ case 'FFFF99':
+ $colorIdx = 0x2B;
+ break;
+ case '99CCFF':
+ $colorIdx = 0x2C;
+ break;
+ case 'FF99CC':
+ $colorIdx = 0x2D;
+ break;
+ case 'CC99FF':
+ $colorIdx = 0x2E;
+ break;
+ case 'FFCC99':
+ $colorIdx = 0x2F;
+ break;
+ case '3366FF':
+ $colorIdx = 0x30;
+ break;
+ case '33CCCC':
+ $colorIdx = 0x31;
+ break;
+ case '99CC00':
+ $colorIdx = 0x32;
+ break;
+ case 'FFCC00':
+ $colorIdx = 0x33;
+ break;
+ case 'FF9900':
+ $colorIdx = 0x34;
+ break;
+ case 'FF6600':
+ $colorIdx = 0x35;
+ break;
+ case '666699':
+ $colorIdx = 0x36;
+ break;
+ case '969696':
+ $colorIdx = 0x37;
+ break;
+ case '003366':
+ $colorIdx = 0x38;
+ break;
+ case '339966':
+ $colorIdx = 0x39;
+ break;
+ case '003300':
+ $colorIdx = 0x3A;
+ break;
+ case '333300':
+ $colorIdx = 0x3B;
+ break;
+ case '993300':
+ $colorIdx = 0x3C;
+ break;
+ case '993366':
+ $colorIdx = 0x3D;
+ break;
+ case '333399':
+ $colorIdx = 0x3E;
+ break;
+ case '333333':
+ $colorIdx = 0x3F;
+ break;
+ default:
+ $colorIdx = 0x00;
+ break;
+ }
+ $dataBlockFont .= pack('V', $colorIdx);
+ // Not used (4)
+ $dataBlockFont .= pack('V', 0x00000000);
+ // Options flags for modified font attributes
+ $optionsFlags = 0;
+ $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0);
+ $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0);
+ $optionsFlags |= (1 == 1 ? 0x00000008 : 0);
+ $optionsFlags |= (1 == 1 ? 0x00000010 : 0);
+ $optionsFlags |= (1 == 0 ? 0x00000020 : 0);
+ $optionsFlags |= (1 == 1 ? 0x00000080 : 0);
+ $dataBlockFont .= pack('V', $optionsFlags);
+ // Escapement type
+ $dataBlockFont .= pack('V', $fontEscapement);
+ // Underline type
+ $dataBlockFont .= pack('V', $fontUnderline);
+ // Always
+ $dataBlockFont .= pack('V', 0x00000000);
+ // Always
+ $dataBlockFont .= pack('V', 0x00000000);
+ // Not used (8)
+ $dataBlockFont .= pack('VV', 0x00000000, 0x00000000);
+ // Always
+ $dataBlockFont .= pack('v', 0x0001);
+ }
+ if ($bFormatAlign == 1) {
+ $blockAlign = 0;
+ // Alignment and text break
+ switch ($conditional->getStyle()->getAlignment()->getHorizontal()) {
+ case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL:
+ $blockAlign = 0;
+ break;
+ case PHPExcel_Style_Alignment::HORIZONTAL_LEFT:
+ $blockAlign = 1;
+ break;
+ case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT:
+ $blockAlign = 3;
+ break;
+ case PHPExcel_Style_Alignment::HORIZONTAL_CENTER:
+ $blockAlign = 2;
+ break;
+ case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS:
+ $blockAlign = 6;
+ break;
+ case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY:
+ $blockAlign = 5;
+ break;
+ }
+ if ($conditional->getStyle()->getAlignment()->getWrapText() == true) {
+ $blockAlign |= 1 << 3;
+ } else {
+ $blockAlign |= 0 << 3;
+ }
+ switch ($conditional->getStyle()->getAlignment()->getVertical()) {
+ case PHPExcel_Style_Alignment::VERTICAL_BOTTOM:
+ $blockAlign = 2 << 4;
+ break;
+ case PHPExcel_Style_Alignment::VERTICAL_TOP:
+ $blockAlign = 0 << 4;
+ break;
+ case PHPExcel_Style_Alignment::VERTICAL_CENTER:
+ $blockAlign = 1 << 4;
+ break;
+ case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY:
+ $blockAlign = 3 << 4;
+ break;
+ }
+ $blockAlign |= 0 << 7;
+
+ // Text rotation angle
+ $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation();
+
+ // Indentation
+ $blockIndent = $conditional->getStyle()->getAlignment()->getIndent();
+ if ($conditional->getStyle()->getAlignment()->getShrinkToFit() == true) {
+ $blockIndent |= 1 << 4;
+ } else {
+ $blockIndent |= 0 << 4;
+ }
+ $blockIndent |= 0 << 6;
+
+ // Relative indentation
+ $blockIndentRelative = 255;
+
+ $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000);
+ }
+ if ($bFormatBorder == 1) {
+ $blockLineStyle = 0;
+ switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()) {
+ case PHPExcel_Style_Border::BORDER_NONE:
+ $blockLineStyle |= 0x00;
+ break;
+ case PHPExcel_Style_Border::BORDER_THIN:
+ $blockLineStyle |= 0x01;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUM:
+ $blockLineStyle |= 0x02;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHED:
+ $blockLineStyle |= 0x03;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOTTED:
+ $blockLineStyle |= 0x04;
+ break;
+ case PHPExcel_Style_Border::BORDER_THICK:
+ $blockLineStyle |= 0x05;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOUBLE:
+ $blockLineStyle |= 0x06;
+ break;
+ case PHPExcel_Style_Border::BORDER_HAIR:
+ $blockLineStyle |= 0x07;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:
+ $blockLineStyle |= 0x08;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOT:
+ $blockLineStyle |= 0x09;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:
+ $blockLineStyle |= 0x0A;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOTDOT:
+ $blockLineStyle |= 0x0B;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:
+ $blockLineStyle |= 0x0C;
+ break;
+ case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:
+ $blockLineStyle |= 0x0D;
+ break;
+ }
+ switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()) {
+ case PHPExcel_Style_Border::BORDER_NONE:
+ $blockLineStyle |= 0x00 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_THIN:
+ $blockLineStyle |= 0x01 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUM:
+ $blockLineStyle |= 0x02 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHED:
+ $blockLineStyle |= 0x03 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOTTED:
+ $blockLineStyle |= 0x04 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_THICK:
+ $blockLineStyle |= 0x05 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOUBLE:
+ $blockLineStyle |= 0x06 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_HAIR:
+ $blockLineStyle |= 0x07 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:
+ $blockLineStyle |= 0x08 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOT:
+ $blockLineStyle |= 0x09 << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:
+ $blockLineStyle |= 0x0A << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOTDOT:
+ $blockLineStyle |= 0x0B << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:
+ $blockLineStyle |= 0x0C << 4;
+ break;
+ case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:
+ $blockLineStyle |= 0x0D << 4;
+ break;
+ }
+ switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()) {
+ case PHPExcel_Style_Border::BORDER_NONE:
+ $blockLineStyle |= 0x00 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_THIN:
+ $blockLineStyle |= 0x01 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUM:
+ $blockLineStyle |= 0x02 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHED:
+ $blockLineStyle |= 0x03 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOTTED:
+ $blockLineStyle |= 0x04 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_THICK:
+ $blockLineStyle |= 0x05 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOUBLE:
+ $blockLineStyle |= 0x06 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_HAIR:
+ $blockLineStyle |= 0x07 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:
+ $blockLineStyle |= 0x08 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOT:
+ $blockLineStyle |= 0x09 << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:
+ $blockLineStyle |= 0x0A << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOTDOT:
+ $blockLineStyle |= 0x0B << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:
+ $blockLineStyle |= 0x0C << 8;
+ break;
+ case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:
+ $blockLineStyle |= 0x0D << 8;
+ break;
+ }
+ switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()) {
+ case PHPExcel_Style_Border::BORDER_NONE:
+ $blockLineStyle |= 0x00 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_THIN:
+ $blockLineStyle |= 0x01 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUM:
+ $blockLineStyle |= 0x02 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHED:
+ $blockLineStyle |= 0x03 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOTTED:
+ $blockLineStyle |= 0x04 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_THICK:
+ $blockLineStyle |= 0x05 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOUBLE:
+ $blockLineStyle |= 0x06 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_HAIR:
+ $blockLineStyle |= 0x07 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:
+ $blockLineStyle |= 0x08 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOT:
+ $blockLineStyle |= 0x09 << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:
+ $blockLineStyle |= 0x0A << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOTDOT:
+ $blockLineStyle |= 0x0B << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:
+ $blockLineStyle |= 0x0C << 12;
+ break;
+ case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:
+ $blockLineStyle |= 0x0D << 12;
+ break;
+ }
+ //@todo writeCFRule() => $blockLineStyle => Index Color for left line
+ //@todo writeCFRule() => $blockLineStyle => Index Color for right line
+ //@todo writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off
+ //@todo writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off
+ $blockColor = 0;
+ //@todo writeCFRule() => $blockColor => Index Color for top line
+ //@todo writeCFRule() => $blockColor => Index Color for bottom line
+ //@todo writeCFRule() => $blockColor => Index Color for diagonal line
+ switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()) {
+ case PHPExcel_Style_Border::BORDER_NONE:
+ $blockColor |= 0x00 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_THIN:
+ $blockColor |= 0x01 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUM:
+ $blockColor |= 0x02 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHED:
+ $blockColor |= 0x03 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOTTED:
+ $blockColor |= 0x04 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_THICK:
+ $blockColor |= 0x05 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_DOUBLE:
+ $blockColor |= 0x06 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_HAIR:
+ $blockColor |= 0x07 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:
+ $blockColor |= 0x08 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOT:
+ $blockColor |= 0x09 << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:
+ $blockColor |= 0x0A << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_DASHDOTDOT:
+ $blockColor |= 0x0B << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:
+ $blockColor |= 0x0C << 21;
+ break;
+ case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:
+ $blockColor |= 0x0D << 21;
+ break;
+ }
+ $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor);
+ }
+ if ($bFormatFill == 1) {
+ // Fill Patern Style
+ $blockFillPatternStyle = 0;
+ switch ($conditional->getStyle()->getFill()->getFillType()) {
+ case PHPExcel_Style_Fill::FILL_NONE:
+ $blockFillPatternStyle = 0x00;
+ break;
+ case PHPExcel_Style_Fill::FILL_SOLID:
+ $blockFillPatternStyle = 0x01;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY:
+ $blockFillPatternStyle = 0x02;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY:
+ $blockFillPatternStyle = 0x03;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY:
+ $blockFillPatternStyle = 0x04;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL:
+ $blockFillPatternStyle = 0x05;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL:
+ $blockFillPatternStyle = 0x06;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN:
+ $blockFillPatternStyle = 0x07;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKUP:
+ $blockFillPatternStyle = 0x08;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID:
+ $blockFillPatternStyle = 0x09;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS:
+ $blockFillPatternStyle = 0x0A;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL:
+ $blockFillPatternStyle = 0x0B;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL:
+ $blockFillPatternStyle = 0x0C;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN:
+ $blockFillPatternStyle = 0x0D;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP:
+ $blockFillPatternStyle = 0x0E;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID:
+ $blockFillPatternStyle = 0x0F;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS:
+ $blockFillPatternStyle = 0x10;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_GRAY125:
+ $blockFillPatternStyle = 0x11;
+ break;
+ case PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625:
+ $blockFillPatternStyle = 0x12;
+ break;
+ case PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR:
+ $blockFillPatternStyle = 0x00;
+ break; // does not exist in BIFF8
+ case PHPExcel_Style_Fill::FILL_GRADIENT_PATH:
+ $blockFillPatternStyle = 0x00;
+ break; // does not exist in BIFF8
+ default:
+ $blockFillPatternStyle = 0x00;
+ break;
+ }
+ // Color
+ switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) {
+ case '000000':
+ $colorIdxBg = 0x08;
+ break;
+ case 'FFFFFF':
+ $colorIdxBg = 0x09;
+ break;
+ case 'FF0000':
+ $colorIdxBg = 0x0A;
+ break;
+ case '00FF00':
+ $colorIdxBg = 0x0B;
+ break;
+ case '0000FF':
+ $colorIdxBg = 0x0C;
+ break;
+ case 'FFFF00':
+ $colorIdxBg = 0x0D;
+ break;
+ case 'FF00FF':
+ $colorIdxBg = 0x0E;
+ break;
+ case '00FFFF':
+ $colorIdxBg = 0x0F;
+ break;
+ case '800000':
+ $colorIdxBg = 0x10;
+ break;
+ case '008000':
+ $colorIdxBg = 0x11;
+ break;
+ case '000080':
+ $colorIdxBg = 0x12;
+ break;
+ case '808000':
+ $colorIdxBg = 0x13;
+ break;
+ case '800080':
+ $colorIdxBg = 0x14;
+ break;
+ case '008080':
+ $colorIdxBg = 0x15;
+ break;
+ case 'C0C0C0':
+ $colorIdxBg = 0x16;
+ break;
+ case '808080':
+ $colorIdxBg = 0x17;
+ break;
+ case '9999FF':
+ $colorIdxBg = 0x18;
+ break;
+ case '993366':
+ $colorIdxBg = 0x19;
+ break;
+ case 'FFFFCC':
+ $colorIdxBg = 0x1A;
+ break;
+ case 'CCFFFF':
+ $colorIdxBg = 0x1B;
+ break;
+ case '660066':
+ $colorIdxBg = 0x1C;
+ break;
+ case 'FF8080':
+ $colorIdxBg = 0x1D;
+ break;
+ case '0066CC':
+ $colorIdxBg = 0x1E;
+ break;
+ case 'CCCCFF':
+ $colorIdxBg = 0x1F;
+ break;
+ case '000080':
+ $colorIdxBg = 0x20;
+ break;
+ case 'FF00FF':
+ $colorIdxBg = 0x21;
+ break;
+ case 'FFFF00':
+ $colorIdxBg = 0x22;
+ break;
+ case '00FFFF':
+ $colorIdxBg = 0x23;
+ break;
+ case '800080':
+ $colorIdxBg = 0x24;
+ break;
+ case '800000':
+ $colorIdxBg = 0x25;
+ break;
+ case '008080':
+ $colorIdxBg = 0x26;
+ break;
+ case '0000FF':
+ $colorIdxBg = 0x27;
+ break;
+ case '00CCFF':
+ $colorIdxBg = 0x28;
+ break;
+ case 'CCFFFF':
+ $colorIdxBg = 0x29;
+ break;
+ case 'CCFFCC':
+ $colorIdxBg = 0x2A;
+ break;
+ case 'FFFF99':
+ $colorIdxBg = 0x2B;
+ break;
+ case '99CCFF':
+ $colorIdxBg = 0x2C;
+ break;
+ case 'FF99CC':
+ $colorIdxBg = 0x2D;
+ break;
+ case 'CC99FF':
+ $colorIdxBg = 0x2E;
+ break;
+ case 'FFCC99':
+ $colorIdxBg = 0x2F;
+ break;
+ case '3366FF':
+ $colorIdxBg = 0x30;
+ break;
+ case '33CCCC':
+ $colorIdxBg = 0x31;
+ break;
+ case '99CC00':
+ $colorIdxBg = 0x32;
+ break;
+ case 'FFCC00':
+ $colorIdxBg = 0x33;
+ break;
+ case 'FF9900':
+ $colorIdxBg = 0x34;
+ break;
+ case 'FF6600':
+ $colorIdxBg = 0x35;
+ break;
+ case '666699':
+ $colorIdxBg = 0x36;
+ break;
+ case '969696':
+ $colorIdxBg = 0x37;
+ break;
+ case '003366':
+ $colorIdxBg = 0x38;
+ break;
+ case '339966':
+ $colorIdxBg = 0x39;
+ break;
+ case '003300':
+ $colorIdxBg = 0x3A;
+ break;
+ case '333300':
+ $colorIdxBg = 0x3B;
+ break;
+ case '993300':
+ $colorIdxBg = 0x3C;
+ break;
+ case '993366':
+ $colorIdxBg = 0x3D;
+ break;
+ case '333399':
+ $colorIdxBg = 0x3E;
+ break;
+ case '333333':
+ $colorIdxBg = 0x3F;
+ break;
+ default:
+ $colorIdxBg = 0x41;
+ break;
+ }
+ // Fg Color
+ switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) {
+ case '000000':
+ $colorIdxFg = 0x08;
+ break;
+ case 'FFFFFF':
+ $colorIdxFg = 0x09;
+ break;
+ case 'FF0000':
+ $colorIdxFg = 0x0A;
+ break;
+ case '00FF00':
+ $colorIdxFg = 0x0B;
+ break;
+ case '0000FF':
+ $colorIdxFg = 0x0C;
+ break;
+ case 'FFFF00':
+ $colorIdxFg = 0x0D;
+ break;
+ case 'FF00FF':
+ $colorIdxFg = 0x0E;
+ break;
+ case '00FFFF':
+ $colorIdxFg = 0x0F;
+ break;
+ case '800000':
+ $colorIdxFg = 0x10;
+ break;
+ case '008000':
+ $colorIdxFg = 0x11;
+ break;
+ case '000080':
+ $colorIdxFg = 0x12;
+ break;
+ case '808000':
+ $colorIdxFg = 0x13;
+ break;
+ case '800080':
+ $colorIdxFg = 0x14;
+ break;
+ case '008080':
+ $colorIdxFg = 0x15;
+ break;
+ case 'C0C0C0':
+ $colorIdxFg = 0x16;
+ break;
+ case '808080':
+ $colorIdxFg = 0x17;
+ break;
+ case '9999FF':
+ $colorIdxFg = 0x18;
+ break;
+ case '993366':
+ $colorIdxFg = 0x19;
+ break;
+ case 'FFFFCC':
+ $colorIdxFg = 0x1A;
+ break;
+ case 'CCFFFF':
+ $colorIdxFg = 0x1B;
+ break;
+ case '660066':
+ $colorIdxFg = 0x1C;
+ break;
+ case 'FF8080':
+ $colorIdxFg = 0x1D;
+ break;
+ case '0066CC':
+ $colorIdxFg = 0x1E;
+ break;
+ case 'CCCCFF':
+ $colorIdxFg = 0x1F;
+ break;
+ case '000080':
+ $colorIdxFg = 0x20;
+ break;
+ case 'FF00FF':
+ $colorIdxFg = 0x21;
+ break;
+ case 'FFFF00':
+ $colorIdxFg = 0x22;
+ break;
+ case '00FFFF':
+ $colorIdxFg = 0x23;
+ break;
+ case '800080':
+ $colorIdxFg = 0x24;
+ break;
+ case '800000':
+ $colorIdxFg = 0x25;
+ break;
+ case '008080':
+ $colorIdxFg = 0x26;
+ break;
+ case '0000FF':
+ $colorIdxFg = 0x27;
+ break;
+ case '00CCFF':
+ $colorIdxFg = 0x28;
+ break;
+ case 'CCFFFF':
+ $colorIdxFg = 0x29;
+ break;
+ case 'CCFFCC':
+ $colorIdxFg = 0x2A;
+ break;
+ case 'FFFF99':
+ $colorIdxFg = 0x2B;
+ break;
+ case '99CCFF':
+ $colorIdxFg = 0x2C;
+ break;
+ case 'FF99CC':
+ $colorIdxFg = 0x2D;
+ break;
+ case 'CC99FF':
+ $colorIdxFg = 0x2E;
+ break;
+ case 'FFCC99':
+ $colorIdxFg = 0x2F;
+ break;
+ case '3366FF':
+ $colorIdxFg = 0x30;
+ break;
+ case '33CCCC':
+ $colorIdxFg = 0x31;
+ break;
+ case '99CC00':
+ $colorIdxFg = 0x32;
+ break;
+ case 'FFCC00':
+ $colorIdxFg = 0x33;
+ break;
+ case 'FF9900':
+ $colorIdxFg = 0x34;
+ break;
+ case 'FF6600':
+ $colorIdxFg = 0x35;
+ break;
+ case '666699':
+ $colorIdxFg = 0x36;
+ break;
+ case '969696':
+ $colorIdxFg = 0x37;
+ break;
+ case '003366':
+ $colorIdxFg = 0x38;
+ break;
+ case '339966':
+ $colorIdxFg = 0x39;
+ break;
+ case '003300':
+ $colorIdxFg = 0x3A;
+ break;
+ case '333300':
+ $colorIdxFg = 0x3B;
+ break;
+ case '993300':
+ $colorIdxFg = 0x3C;
+ break;
+ case '993366':
+ $colorIdxFg = 0x3D;
+ break;
+ case '333399':
+ $colorIdxFg = 0x3E;
+ break;
+ case '333333':
+ $colorIdxFg = 0x3F;
+ break;
+ default:
+ $colorIdxFg = 0x40;
+ break;
+ }
+ $dataBlockFill = pack('v', $blockFillPatternStyle);
+ $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7));
+ }
+ if ($bFormatProt == 1) {
+ $dataBlockProtection = 0;
+ if ($conditional->getStyle()->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED) {
+ $dataBlockProtection = 1;
+ }
+ if ($conditional->getStyle()->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED) {
+ $dataBlockProtection = 1 << 1;
+ }
+ }
+
+ $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000);
+ if ($bFormatFont == 1) { // Block Formatting : OK
+ $data .= $dataBlockFont;
+ }
+ if ($bFormatAlign == 1) {
+ $data .= $dataBlockAlign;
+ }
+ if ($bFormatBorder == 1) {
+ $data .= $dataBlockBorder;
+ }
+ if ($bFormatFill == 1) { // Block Formatting : OK
+ $data .= $dataBlockFill;
+ }
+ if ($bFormatProt == 1) {
+ $data .= $dataBlockProtection;
+ }
+ if (!is_null($operand1)) {
+ $data .= $operand1;
+ }
+ if (!is_null($operand2)) {
+ $data .= $operand2;
+ }
+ $header = pack('vv', $record, strlen($data));
+ $this->append($header . $data);
+ }
+
+ /**
+ * Write CFHeader record
+ */
+ private function writeCFHeader()
+ {
+ $record = 0x01B0; // Record identifier
+ $length = 0x0016; // Bytes to follow
+
+ $numColumnMin = null;
+ $numColumnMax = null;
+ $numRowMin = null;
+ $numRowMax = null;
+ $arrConditional = array();
+ foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
+ foreach ($conditionalStyles as $conditional) {
+ if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION
+ || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS) {
+ if (!in_array($conditional->getHashCode(), $arrConditional)) {
+ $arrConditional[] = $conditional->getHashCode();
+ }
+ // Cells
+ $arrCoord = PHPExcel_Cell::coordinateFromString($cellCoordinate);
+ if (!is_numeric($arrCoord[0])) {
+ $arrCoord[0] = PHPExcel_Cell::columnIndexFromString($arrCoord[0]);
+ }
+ if (is_null($numColumnMin) || ($numColumnMin > $arrCoord[0])) {
+ $numColumnMin = $arrCoord[0];
+ }
+ if (is_null($numColumnMax) || ($numColumnMax < $arrCoord[0])) {
+ $numColumnMax = $arrCoord[0];
+ }
+ if (is_null($numRowMin) || ($numRowMin > $arrCoord[1])) {
+ $numRowMin = $arrCoord[1];
+ }
+ if (is_null($numRowMax) || ($numRowMax < $arrCoord[1])) {
+ $numRowMax = $arrCoord[1];
+ }
+ }
+ }
+ }
+ $needRedraw = 1;
+ $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1);
+
+ $header = pack('vv', $record, $length);
+ $data = pack('vv', count($arrConditional), $needRedraw);
+ $data .= $cellRange;
+ $data .= pack('v', 0x0001);
+ $data .= $cellRange;
+ $this->append($header . $data);
+ }
+}
diff --git a/Classes/PHPExcel/Writer/Excel5/Xf.php b/Classes/PHPExcel/Writer/Excel5/Xf.php
index 1653c7fc4..e41589a84 100644
--- a/Classes/PHPExcel/Writer/Excel5/Xf.php
+++ b/Classes/PHPExcel/Writer/Excel5/Xf.php
@@ -1,8 +1,9 @@
_isStyleXf = false;
- $this->_fontIndex = 0;
-
- $this->_numberFormatIndex = 0;
-
- $this->_text_justlast = 0;
-
- $this->_fg_color = 0x40;
- $this->_bg_color = 0x41;
-
- $this->_diag = 0;
-
- $this->_bottom_color = 0x40;
- $this->_top_color = 0x40;
- $this->_left_color = 0x40;
- $this->_right_color = 0x40;
- $this->_diag_color = 0x40;
- $this->_style = $style;
-
- }
-
-
- /**
- * Generate an Excel BIFF XF record (style or cell).
- *
- * @return string The XF record
- */
- function writeXf()
- {
- // Set the type of the XF record and some of the attributes.
- if ($this->_isStyleXf) {
- $style = 0xFFF5;
- } else {
- $style = self::_mapLocked($this->_style->getProtection()->getLocked());
- $style |= self::_mapHidden($this->_style->getProtection()->getHidden()) << 1;
- }
-
- // Flags to indicate if attributes have been set.
- $atr_num = ($this->_numberFormatIndex != 0)?1:0;
- $atr_fnt = ($this->_fontIndex != 0)?1:0;
- $atr_alc = ((int) $this->_style->getAlignment()->getWrapText())?1:0;
- $atr_bdr = (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) ||
- self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) ||
- self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) ||
- self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0;
- $atr_pat = (($this->_fg_color != 0x40) ||
- ($this->_bg_color != 0x41) ||
- self::_mapFillType($this->_style->getFill()->getFillType()))?1:0;
- $atr_prot = self::_mapLocked($this->_style->getProtection()->getLocked())
- | self::_mapHidden($this->_style->getProtection()->getHidden());
-
- // Zero the default border colour if the border has not been set.
- if (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) {
- $this->_bottom_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) {
- $this->_top_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) {
- $this->_right_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) {
- $this->_left_color = 0;
- }
- if (self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) {
- $this->_diag_color = 0;
- }
-
- $record = 0x00E0; // Record identifier
- $length = 0x0014; // Number of bytes to follow
-
- $ifnt = $this->_fontIndex; // Index to FONT record
- $ifmt = $this->_numberFormatIndex; // Index to FORMAT record
-
- $align = $this->_mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment
- $align |= (int) $this->_style->getAlignment()->getWrapText() << 3;
- $align |= self::_mapVAlign($this->_style->getAlignment()->getVertical()) << 4;
- $align |= $this->_text_justlast << 7;
-
- $used_attrib = $atr_num << 2;
- $used_attrib |= $atr_fnt << 3;
- $used_attrib |= $atr_alc << 4;
- $used_attrib |= $atr_bdr << 5;
- $used_attrib |= $atr_pat << 6;
- $used_attrib |= $atr_prot << 7;
-
- $icv = $this->_fg_color; // fg and bg pattern colors
- $icv |= $this->_bg_color << 7;
-
- $border1 = self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color
- $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4;
- $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8;
- $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12;
- $border1 |= $this->_left_color << 16;
- $border1 |= $this->_right_color << 23;
-
- $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection();
- $diag_tl_to_rb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH
- || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_DOWN;
- $diag_tr_to_lb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH
- || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_UP;
- $border1 |= $diag_tl_to_rb << 30;
- $border1 |= $diag_tr_to_lb << 31;
-
- $border2 = $this->_top_color; // Border color
- $border2 |= $this->_bottom_color << 7;
- $border2 |= $this->_diag_color << 14;
- $border2 |= self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21;
- $border2 |= self::_mapFillType($this->_style->getFill()->getFillType()) << 26;
-
- $header = pack("vv", $record, $length);
-
- //BIFF8 options: identation, shrinkToFit and text direction
- $biff8_options = $this->_style->getAlignment()->getIndent();
- $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4;
-
- $data = pack("vvvC", $ifnt, $ifmt, $style, $align);
- $data .= pack("CCC"
- , self::_mapTextRotation($this->_style->getAlignment()->getTextRotation())
- , $biff8_options
- , $used_attrib
- );
- $data .= pack("VVv", $border1, $border2, $icv);
-
- return($header . $data);
- }
-
- /**
- * Is this a style XF ?
- *
- * @param boolean $value
- */
- public function setIsStyleXf($value)
- {
- $this->_isStyleXf = $value;
- }
-
- /**
- * Sets the cell's bottom border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setBottomColor($colorIndex)
- {
- $this->_bottom_color = $colorIndex;
- }
-
- /**
- * Sets the cell's top border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setTopColor($colorIndex)
- {
- $this->_top_color = $colorIndex;
- }
-
- /**
- * Sets the cell's left border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setLeftColor($colorIndex)
- {
- $this->_left_color = $colorIndex;
- }
-
- /**
- * Sets the cell's right border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setRightColor($colorIndex)
- {
- $this->_right_color = $colorIndex;
- }
-
- /**
- * Sets the cell's diagonal border color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setDiagColor($colorIndex)
- {
- $this->_diag_color = $colorIndex;
- }
-
-
- /**
- * Sets the cell's foreground color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setFgColor($colorIndex)
- {
- $this->_fg_color = $colorIndex;
- }
-
- /**
- * Sets the cell's background color
- *
- * @access public
- * @param int $colorIndex Color index
- */
- function setBgColor($colorIndex)
- {
- $this->_bg_color = $colorIndex;
- }
-
- /**
- * Sets the index to the number format record
- * It can be date, time, currency, etc...
- *
- * @access public
- * @param integer $numberFormatIndex Index to format record
- */
- function setNumberFormatIndex($numberFormatIndex)
- {
- $this->_numberFormatIndex = $numberFormatIndex;
- }
-
- /**
- * Set the font index.
- *
- * @param int $value Font index, note that value 4 does not exist
- */
- public function setFontIndex($value)
- {
- $this->_fontIndex = $value;
- }
-
- /**
- * Map of BIFF2-BIFF8 codes for border styles
- * @static array of int
- *
- */
- private static $_mapBorderStyle = array ( PHPExcel_Style_Border::BORDER_NONE => 0x00,
- PHPExcel_Style_Border::BORDER_THIN => 0x01,
- PHPExcel_Style_Border::BORDER_MEDIUM => 0x02,
- PHPExcel_Style_Border::BORDER_DASHED => 0x03,
- PHPExcel_Style_Border::BORDER_DOTTED => 0x04,
- PHPExcel_Style_Border::BORDER_THICK => 0x05,
- PHPExcel_Style_Border::BORDER_DOUBLE => 0x06,
- PHPExcel_Style_Border::BORDER_HAIR => 0x07,
- PHPExcel_Style_Border::BORDER_MEDIUMDASHED => 0x08,
- PHPExcel_Style_Border::BORDER_DASHDOT => 0x09,
- PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT => 0x0A,
- PHPExcel_Style_Border::BORDER_DASHDOTDOT => 0x0B,
- PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT => 0x0C,
- PHPExcel_Style_Border::BORDER_SLANTDASHDOT => 0x0D,
- );
-
- /**
- * Map border style
- *
- * @param string $borderStyle
- * @return int
- */
- private static function _mapBorderStyle($borderStyle) {
- if (isset(self::$_mapBorderStyle[$borderStyle]))
- return self::$_mapBorderStyle[$borderStyle];
- return 0x00;
- }
-
- /**
- * Map of BIFF2-BIFF8 codes for fill types
- * @static array of int
- *
- */
- private static $_mapFillType = array( PHPExcel_Style_Fill::FILL_NONE => 0x00,
- PHPExcel_Style_Fill::FILL_SOLID => 0x01,
- PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY => 0x02,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY => 0x03,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY => 0x04,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL => 0x06,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN => 0x07,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKUP => 0x08,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID => 0x09,
- PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS => 0x0A,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN => 0x0D,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP => 0x0E,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID => 0x0F,
- PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10,
- PHPExcel_Style_Fill::FILL_PATTERN_GRAY125 => 0x11,
- PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625 => 0x12,
- PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8
- PHPExcel_Style_Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8
- );
- /**
- * Map fill type
- *
- * @param string $fillType
- * @return int
- */
- private static function _mapFillType($fillType) {
- if (isset(self::$_mapFillType[$fillType]))
- return self::$_mapFillType[$fillType];
- return 0x00;
- }
-
- /**
- * Map of BIFF2-BIFF8 codes for horizontal alignment
- * @static array of int
- *
- */
- private static $_mapHAlign = array( PHPExcel_Style_Alignment::HORIZONTAL_GENERAL => 0,
- PHPExcel_Style_Alignment::HORIZONTAL_LEFT => 1,
- PHPExcel_Style_Alignment::HORIZONTAL_CENTER => 2,
- PHPExcel_Style_Alignment::HORIZONTAL_RIGHT => 3,
- PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY => 5,
- PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6,
- );
- /**
- * Map to BIFF2-BIFF8 codes for horizontal alignment
- *
- * @param string $hAlign
- * @return int
- */
- private function _mapHAlign($hAlign)
- {
- if (isset(self::$_mapHAlign[$hAlign]))
- return self::$_mapHAlign[$hAlign];
- return 0;
- }
-
- /**
- * Map of BIFF2-BIFF8 codes for vertical alignment
- * @static array of int
- *
- */
- private static $_mapVAlign = array( PHPExcel_Style_Alignment::VERTICAL_TOP => 0,
- PHPExcel_Style_Alignment::VERTICAL_CENTER => 1,
- PHPExcel_Style_Alignment::VERTICAL_BOTTOM => 2,
- PHPExcel_Style_Alignment::VERTICAL_JUSTIFY => 3,
- );
- /**
- * Map to BIFF2-BIFF8 codes for vertical alignment
- *
- * @param string $vAlign
- * @return int
- */
- private static function _mapVAlign($vAlign) {
- if (isset(self::$_mapVAlign[$vAlign]))
- return self::$_mapVAlign[$vAlign];
- return 2;
- }
-
- /**
- * Map to BIFF8 codes for text rotation angle
- *
- * @param int $textRotation
- * @return int
- */
- private static function _mapTextRotation($textRotation) {
- if ($textRotation >= 0) {
- return $textRotation;
- }
- if ($textRotation == -165) {
- return 255;
- }
- if ($textRotation < 0) {
- return 90 - $textRotation;
- }
- }
-
- /**
- * Map locked
- *
- * @param string
- * @return int
- */
- private static function _mapLocked($locked) {
- switch ($locked) {
- case PHPExcel_Style_Protection::PROTECTION_INHERIT: return 1;
- case PHPExcel_Style_Protection::PROTECTION_PROTECTED: return 1;
- case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED: return 0;
- default: return 1;
- }
- }
-
- /**
- * Map hidden
- *
- * @param string
- * @return int
- */
- private static function _mapHidden($hidden) {
- switch ($hidden) {
- case PHPExcel_Style_Protection::PROTECTION_INHERIT: return 0;
- case PHPExcel_Style_Protection::PROTECTION_PROTECTED: return 1;
- case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED: return 0;
- default: return 0;
- }
- }
+ * Style XF or a cell XF ?
+ *
+ * @var boolean
+ */
+ private $isStyleXf;
+
+ /**
+ * Index to the FONT record. Index 4 does not exist
+ * @var integer
+ */
+ private $fontIndex;
+
+ /**
+ * An index (2 bytes) to a FORMAT record (number format).
+ * @var integer
+ */
+ private $numberFormatIndex;
+
+ /**
+ * 1 bit, apparently not used.
+ * @var integer
+ */
+ private $textJustLast;
+
+ /**
+ * The cell's foreground color.
+ * @var integer
+ */
+ private $foregroundColor;
+
+ /**
+ * The cell's background color.
+ * @var integer
+ */
+ private $backgroundColor;
+
+ /**
+ * Color of the bottom border of the cell.
+ * @var integer
+ */
+ private $bottomBorderColor;
+
+ /**
+ * Color of the top border of the cell.
+ * @var integer
+ */
+ private $topBorderColor;
+
+ /**
+ * Color of the left border of the cell.
+ * @var integer
+ */
+ private $leftBorderColor;
+
+ /**
+ * Color of the right border of the cell.
+ * @var integer
+ */
+ private $rightBorderColor;
+
+ /**
+ * Constructor
+ *
+ * @access public
+ * @param PHPExcel_Style The XF format
+ */
+ public function __construct(PHPExcel_Style $style = null)
+ {
+ $this->isStyleXf = false;
+ $this->fontIndex = 0;
+
+ $this->numberFormatIndex = 0;
+
+ $this->textJustLast = 0;
+
+ $this->foregroundColor = 0x40;
+ $this->backgroundColor = 0x41;
+
+ $this->_diag = 0;
+
+ $this->bottomBorderColor = 0x40;
+ $this->topBorderColor = 0x40;
+ $this->leftBorderColor = 0x40;
+ $this->rightBorderColor = 0x40;
+ $this->_diag_color = 0x40;
+ $this->_style = $style;
+
+ }
+
+
+ /**
+ * Generate an Excel BIFF XF record (style or cell).
+ *
+ * @return string The XF record
+ */
+ public function writeXf()
+ {
+ // Set the type of the XF record and some of the attributes.
+ if ($this->isStyleXf) {
+ $style = 0xFFF5;
+ } else {
+ $style = self::mapLocked($this->_style->getProtection()->getLocked());
+ $style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1;
+ }
+
+ // Flags to indicate if attributes have been set.
+ $atr_num = ($this->numberFormatIndex != 0)?1:0;
+ $atr_fnt = ($this->fontIndex != 0)?1:0;
+ $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0;
+ $atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) ||
+ self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) ||
+ self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) ||
+ self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0;
+ $atr_pat = (($this->foregroundColor != 0x40) ||
+ ($this->backgroundColor != 0x41) ||
+ self::mapFillType($this->_style->getFill()->getFillType()))?1:0;
+ $atr_prot = self::mapLocked($this->_style->getProtection()->getLocked())
+ | self::mapHidden($this->_style->getProtection()->getHidden());
+
+ // Zero the default border colour if the border has not been set.
+ if (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) {
+ $this->bottomBorderColor = 0;
+ }
+ if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) {
+ $this->topBorderColor = 0;
+ }
+ if (self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) {
+ $this->rightBorderColor = 0;
+ }
+ if (self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) {
+ $this->leftBorderColor = 0;
+ }
+ if (self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) {
+ $this->_diag_color = 0;
+ }
+
+ $record = 0x00E0; // Record identifier
+ $length = 0x0014; // Number of bytes to follow
+
+ $ifnt = $this->fontIndex; // Index to FONT record
+ $ifmt = $this->numberFormatIndex; // Index to FORMAT record
+
+ $align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment
+ $align |= (int) $this->_style->getAlignment()->getWrapText() << 3;
+ $align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4;
+ $align |= $this->textJustLast << 7;
+
+ $used_attrib = $atr_num << 2;
+ $used_attrib |= $atr_fnt << 3;
+ $used_attrib |= $atr_alc << 4;
+ $used_attrib |= $atr_bdr << 5;
+ $used_attrib |= $atr_pat << 6;
+ $used_attrib |= $atr_prot << 7;
+
+ $icv = $this->foregroundColor; // fg and bg pattern colors
+ $icv |= $this->backgroundColor << 7;
+
+ $border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color
+ $border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4;
+ $border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8;
+ $border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12;
+ $border1 |= $this->leftBorderColor << 16;
+ $border1 |= $this->rightBorderColor << 23;
+
+ $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection();
+ $diag_tl_to_rb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH
+ || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_DOWN;
+ $diag_tr_to_lb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH
+ || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_UP;
+ $border1 |= $diag_tl_to_rb << 30;
+ $border1 |= $diag_tr_to_lb << 31;
+
+ $border2 = $this->topBorderColor; // Border color
+ $border2 |= $this->bottomBorderColor << 7;
+ $border2 |= $this->_diag_color << 14;
+ $border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21;
+ $border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26;
+
+ $header = pack("vv", $record, $length);
+
+ //BIFF8 options: identation, shrinkToFit and text direction
+ $biff8_options = $this->_style->getAlignment()->getIndent();
+ $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4;
+
+ $data = pack("vvvC", $ifnt, $ifmt, $style, $align);
+ $data .= pack("CCC", self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib);
+ $data .= pack("VVv", $border1, $border2, $icv);
+
+ return($header . $data);
+ }
+
+ /**
+ * Is this a style XF ?
+ *
+ * @param boolean $value
+ */
+ public function setIsStyleXf($value)
+ {
+ $this->isStyleXf = $value;
+ }
+ /**
+ * Sets the cell's bottom border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setBottomColor($colorIndex)
+ {
+ $this->bottomBorderColor = $colorIndex;
+ }
+
+ /**
+ * Sets the cell's top border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setTopColor($colorIndex)
+ {
+ $this->topBorderColor = $colorIndex;
+ }
+
+ /**
+ * Sets the cell's left border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setLeftColor($colorIndex)
+ {
+ $this->leftBorderColor = $colorIndex;
+ }
+
+ /**
+ * Sets the cell's right border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setRightColor($colorIndex)
+ {
+ $this->rightBorderColor = $colorIndex;
+ }
+
+ /**
+ * Sets the cell's diagonal border color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setDiagColor($colorIndex)
+ {
+ $this->_diag_color = $colorIndex;
+ }
+
+
+ /**
+ * Sets the cell's foreground color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setFgColor($colorIndex)
+ {
+ $this->foregroundColor = $colorIndex;
+ }
+
+ /**
+ * Sets the cell's background color
+ *
+ * @access public
+ * @param int $colorIndex Color index
+ */
+ public function setBgColor($colorIndex)
+ {
+ $this->backgroundColor = $colorIndex;
+ }
+
+ /**
+ * Sets the index to the number format record
+ * It can be date, time, currency, etc...
+ *
+ * @access public
+ * @param integer $numberFormatIndex Index to format record
+ */
+ public function setNumberFormatIndex($numberFormatIndex)
+ {
+ $this->numberFormatIndex = $numberFormatIndex;
+ }
+
+ /**
+ * Set the font index.
+ *
+ * @param int $value Font index, note that value 4 does not exist
+ */
+ public function setFontIndex($value)
+ {
+ $this->fontIndex = $value;
+ }
+
+ /**
+ * Map of BIFF2-BIFF8 codes for border styles
+ * @static array of int
+ *
+ */
+ private static $mapBorderStyles = array(
+ PHPExcel_Style_Border::BORDER_NONE => 0x00,
+ PHPExcel_Style_Border::BORDER_THIN => 0x01,
+ PHPExcel_Style_Border::BORDER_MEDIUM => 0x02,
+ PHPExcel_Style_Border::BORDER_DASHED => 0x03,
+ PHPExcel_Style_Border::BORDER_DOTTED => 0x04,
+ PHPExcel_Style_Border::BORDER_THICK => 0x05,
+ PHPExcel_Style_Border::BORDER_DOUBLE => 0x06,
+ PHPExcel_Style_Border::BORDER_HAIR => 0x07,
+ PHPExcel_Style_Border::BORDER_MEDIUMDASHED => 0x08,
+ PHPExcel_Style_Border::BORDER_DASHDOT => 0x09,
+ PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT => 0x0A,
+ PHPExcel_Style_Border::BORDER_DASHDOTDOT => 0x0B,
+ PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT => 0x0C,
+ PHPExcel_Style_Border::BORDER_SLANTDASHDOT => 0x0D,
+ );
+
+ /**
+ * Map border style
+ *
+ * @param string $borderStyle
+ * @return int
+ */
+ private static function mapBorderStyle($borderStyle)
+ {
+ if (isset(self::$mapBorderStyles[$borderStyle])) {
+ return self::$mapBorderStyles[$borderStyle];
+ }
+ return 0x00;
+ }
+
+ /**
+ * Map of BIFF2-BIFF8 codes for fill types
+ * @static array of int
+ *
+ */
+ private static $mapFillTypes = array(
+ PHPExcel_Style_Fill::FILL_NONE => 0x00,
+ PHPExcel_Style_Fill::FILL_SOLID => 0x01,
+ PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY => 0x02,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY => 0x03,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY => 0x04,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL => 0x06,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN => 0x07,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKUP => 0x08,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID => 0x09,
+ PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS => 0x0A,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN => 0x0D,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP => 0x0E,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID => 0x0F,
+ PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10,
+ PHPExcel_Style_Fill::FILL_PATTERN_GRAY125 => 0x11,
+ PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625 => 0x12,
+ PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8
+ PHPExcel_Style_Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8
+ );
+
+ /**
+ * Map fill type
+ *
+ * @param string $fillType
+ * @return int
+ */
+ private static function mapFillType($fillType)
+ {
+ if (isset(self::$mapFillTypes[$fillType])) {
+ return self::$mapFillTypes[$fillType];
+ }
+ return 0x00;
+ }
+
+ /**
+ * Map of BIFF2-BIFF8 codes for horizontal alignment
+ * @static array of int
+ *
+ */
+ private static $mapHAlignments = array(
+ PHPExcel_Style_Alignment::HORIZONTAL_GENERAL => 0,
+ PHPExcel_Style_Alignment::HORIZONTAL_LEFT => 1,
+ PHPExcel_Style_Alignment::HORIZONTAL_CENTER => 2,
+ PHPExcel_Style_Alignment::HORIZONTAL_RIGHT => 3,
+ PHPExcel_Style_Alignment::HORIZONTAL_FILL => 4,
+ PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY => 5,
+ PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6,
+ );
+
+ /**
+ * Map to BIFF2-BIFF8 codes for horizontal alignment
+ *
+ * @param string $hAlign
+ * @return int
+ */
+ private function mapHAlign($hAlign)
+ {
+ if (isset(self::$mapHAlignments[$hAlign])) {
+ return self::$mapHAlignments[$hAlign];
+ }
+ return 0;
+ }
+
+ /**
+ * Map of BIFF2-BIFF8 codes for vertical alignment
+ * @static array of int
+ *
+ */
+ private static $mapVAlignments = array(
+ PHPExcel_Style_Alignment::VERTICAL_TOP => 0,
+ PHPExcel_Style_Alignment::VERTICAL_CENTER => 1,
+ PHPExcel_Style_Alignment::VERTICAL_BOTTOM => 2,
+ PHPExcel_Style_Alignment::VERTICAL_JUSTIFY => 3,
+ );
+
+ /**
+ * Map to BIFF2-BIFF8 codes for vertical alignment
+ *
+ * @param string $vAlign
+ * @return int
+ */
+ private static function mapVAlign($vAlign)
+ {
+ if (isset(self::$mapVAlignments[$vAlign])) {
+ return self::$mapVAlignments[$vAlign];
+ }
+ return 2;
+ }
+
+ /**
+ * Map to BIFF8 codes for text rotation angle
+ *
+ * @param int $textRotation
+ * @return int
+ */
+ private static function mapTextRotation($textRotation)
+ {
+ if ($textRotation >= 0) {
+ return $textRotation;
+ } elseif ($textRotation == -165) {
+ return 255;
+ } elseif ($textRotation < 0) {
+ return 90 - $textRotation;
+ }
+ }
+
+ /**
+ * Map locked
+ *
+ * @param string
+ * @return int
+ */
+ private static function mapLocked($locked)
+ {
+ switch ($locked) {
+ case PHPExcel_Style_Protection::PROTECTION_INHERIT:
+ return 1;
+ case PHPExcel_Style_Protection::PROTECTION_PROTECTED:
+ return 1;
+ case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED:
+ return 0;
+ default:
+ return 1;
+ }
+ }
+
+ /**
+ * Map hidden
+ *
+ * @param string
+ * @return int
+ */
+ private static function mapHidden($hidden)
+ {
+ switch ($hidden) {
+ case PHPExcel_Style_Protection::PROTECTION_INHERIT:
+ return 0;
+ case PHPExcel_Style_Protection::PROTECTION_PROTECTED:
+ return 1;
+ case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED:
+ return 0;
+ default:
+ return 0;
+ }
+ }
}
diff --git a/Classes/PHPExcel/Writer/Exception.php b/Classes/PHPExcel/Writer/Exception.php
index 70c8418ac..bfa005681 100644
--- a/Classes/PHPExcel/Writer/Exception.php
+++ b/Classes/PHPExcel/Writer/Exception.php
@@ -1,8 +1,9 @@
line = $line;
- $e->file = $file;
- throw $e;
- }
+class PHPExcel_Writer_Exception extends PHPExcel_Exception
+{
+ /**
+ * Error handler callback
+ *
+ * @param mixed $code
+ * @param mixed $string
+ * @param mixed $file
+ * @param mixed $line
+ * @param mixed $context
+ */
+ public static function errorHandlerCallback($code, $string, $file, $line, $context)
+ {
+ $e = new self($string, $code);
+ $e->line = $line;
+ $e->file = $file;
+ throw $e;
+ }
}
diff --git a/Classes/PHPExcel/Writer/HTML.php b/Classes/PHPExcel/Writer/HTML.php
index d07dbd2d1..31d7c63ac 100644
--- a/Classes/PHPExcel/Writer/HTML.php
+++ b/Classes/PHPExcel/Writer/HTML.php
@@ -1,8 +1,9 @@
_phpExcel = $phpExcel;
- $this->_defaultFont = $this->_phpExcel->getDefaultStyle()->getFont();
- }
-
- /**
- * 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()->writeDebugLog;
- PHPExcel_Calculation::getInstance()->writeDebugLog = 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()->writeDebugLog = $saveDebugLog;
- }
-
- /**
- * Map VAlign
- *
- * @param string $vAlign Vertical alignment
- * @return string
- */
- private function _mapVAlign($vAlign) {
- switch ($vAlign) {
- case PHPExcel_Style_Alignment::VERTICAL_BOTTOM: return 'bottom';
- case PHPExcel_Style_Alignment::VERTICAL_TOP: return 'top';
- case PHPExcel_Style_Alignment::VERTICAL_CENTER:
- case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY: return 'middle';
- default: return 'baseline';
- }
- }
-
- /**
- * Map HAlign
- *
- * @param string $hAlign Horizontal alignment
- * @return string|false
- */
- private function _mapHAlign($hAlign) {
- switch ($hAlign) {
- case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL: return false;
- case PHPExcel_Style_Alignment::HORIZONTAL_LEFT: return 'left';
- case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT: return 'right';
- case PHPExcel_Style_Alignment::HORIZONTAL_CENTER:
- case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: return 'center';
- case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY: return 'justify';
- default: return false;
- }
- }
-
- /**
- * Map border style
- *
- * @param int $borderStyle Sheet index
- * @return string
- */
- private function _mapBorderStyle($borderStyle) {
- switch ($borderStyle) {
- case PHPExcel_Style_Border::BORDER_NONE: return 'none';
- case PHPExcel_Style_Border::BORDER_DASHDOT: return '1px dashed';
- case PHPExcel_Style_Border::BORDER_DASHDOTDOT: return '1px dotted';
- case PHPExcel_Style_Border::BORDER_DASHED: return '1px dashed';
- case PHPExcel_Style_Border::BORDER_DOTTED: return '1px dotted';
- case PHPExcel_Style_Border::BORDER_DOUBLE: return '3px double';
- case PHPExcel_Style_Border::BORDER_HAIR: return '1px solid';
- case PHPExcel_Style_Border::BORDER_MEDIUM: return '2px solid';
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: return '2px dashed';
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: return '2px dotted';
- case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: return '2px dashed';
- case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: return '2px dashed';
- case PHPExcel_Style_Border::BORDER_THICK: return '3px solid';
- case PHPExcel_Style_Border::BORDER_THIN: return '1px solid';
- default: return '1px solid'; // map others to thin
- }
- }
-
- /**
- * Get sheet index
- *
- * @return int
- */
- public function getSheetIndex() {
- return $this->_sheetIndex;
- }
-
- /**
- * Set sheet index
- *
- * @param int $pValue Sheet index
- * @return PHPExcel_Writer_HTML
- */
- public function setSheetIndex($pValue = 0) {
- $this->_sheetIndex = $pValue;
- return $this;
- }
-
- /**
- * Get sheet index
- *
- * @return boolean
- */
- public function getGenerateSheetNavigationBlock() {
- return $this->_generateSheetNavigationBlock;
- }
-
- /**
- * Set sheet index
- *
- * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not
- * @return PHPExcel_Writer_HTML
- */
- public function setGenerateSheetNavigationBlock($pValue = true) {
- $this->_generateSheetNavigationBlock = (bool) $pValue;
- return $this;
- }
-
- /**
- * Write all sheets (resets sheetIndex to NULL)
- */
- public function writeAllSheets() {
- $this->_sheetIndex = null;
- return $this;
- }
-
- /**
- * Generate HTML header
- *
- * @param boolean $pIncludeStyles Include styles?
- * @return string
- * @throws PHPExcel_Writer_Exception
- */
- public function generateHTMLHeader($pIncludeStyles = false) {
- // PHPExcel object known?
- if (is_null($this->_phpExcel)) {
- throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
- }
-
- // Construct HTML
- $properties = $this->_phpExcel->getProperties();
- $html = '' . PHP_EOL;
- $html .= '' . PHP_EOL;
- $html .= '' . PHP_EOL;
- $html .= ' ' . PHP_EOL;
- $html .= ' ' . PHP_EOL;
- if ($properties->getTitle() > '')
- $html .= ' ';
- for ($col = 'A'; $col != $colMax; ++$col) {
- $html .= ' ';
- }
- return $html;
- }
-
-
- /**
- * Generate image tag in cell
- *
- * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
- * @param string $coordinates Cell coordinates
- * @return string
- * @throws PHPExcel_Writer_Exception
- */
- private function _writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates) {
- // Construct HTML
- $html = '';
-
- // Write images
- foreach ($pSheet->getDrawingCollection() as $drawing) {
- if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
- if ($drawing->getCoordinates() == $coordinates) {
- $filename = $drawing->getPath();
-
- // Strip off eventual '.'
- if (substr($filename, 0, 1) == '.') {
- $filename = substr($filename, 1);
- }
-
- // Prepend images root
- $filename = $this->getImagesRoot() . $filename;
-
- // Strip off eventual '.'
- if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
- $filename = substr($filename, 1);
- }
-
- // Convert UTF8 data to PCDATA
- $filename = htmlspecialchars($filename);
-
- $html .= PHP_EOL;
- if ((!$this->_embedImages) || ($this->_isPdf)) {
- $imageData = $filename;
- } else {
- $imageDetails = getimagesize($filename);
- if ($fp = fopen($filename,"rb", 0)) {
- $picture = fread($fp,filesize($filename));
- fclose($fp);
- // base64 encode the binary data, then break it
- // into chunks according to RFC 2045 semantics
- $base64 = chunk_split(base64_encode($picture));
- $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
- } else {
- $imageData = $filename;
- }
- }
-
- $html .= '';
- $html .= $this->_writeImageInCell($pSheet, $col.$row);
- if ($this->_includeCharts) {
- $html .= $this->_writeChartInCell($pSheet, $col.$row);
- }
- $html .= ' ';
- }
- ++$row;
- $html .= '' . PHP_EOL;
- $html .= '
' . PHP_EOL;
- $html .= '
' . PHP_EOL;
- } else {
- $style = isset($this->_cssStyles['table']) ?
- $this->_assembleCSS($this->_cssStyles['table']) : '';
-
- if ($this->_isPdf && $pSheet->getShowGridLines()) {
- $html .= '
' . PHP_EOL;
- } else {
- $html .= '
- $html .= $this->_generateTableFooter();
-
- // insert page break
- $html .= '';
-
- // open table again: ' . PHP_EOL;
- }
- }
-
- // Write
' . PHP_EOL;
-
- // Return
- return $html;
- }
-
- /**
- * Generate row
- *
- * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
- * @param array $pValues Array containing cells in a row
- * @param int $pRow Row number (0-based)
- * @return string
- * @throws PHPExcel_Writer_Exception
- */
- private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0) {
- if (is_array($pValues)) {
- // Construct HTML
- $html = '';
-
- // Sheet index
- $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
-
- // DomPDF and breaks
- if ($this->_isPdf && count($pSheet->getBreaks()) > 0) {
- $breaks = $pSheet->getBreaks();
-
- // check if a break is needed before this row
- if (isset($breaks['A' . $pRow])) {
- // close table: +
' . PHP_EOL;
- } else {
- $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
- ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
-
- $html .= ' ' . PHP_EOL;
- }
-
- // Write cells
- $colNum = 0;
- foreach ($pValues as $cell) {
- $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
-
- if (!$this->_useInlineCss) {
- $cssClass = '';
- $cssClass = 'column' . $colNum;
- } else {
- $cssClass = array();
- if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
- $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
- }
- }
- $colSpan = 1;
- $rowSpan = 1;
-
- // initialize
- $cellData = ' ';
-
- // PHPExcel_Cell
- if ($cell instanceof PHPExcel_Cell) {
- $cellData = '';
- if (is_null($cell->getParent())) {
- $cell->attach($pSheet);
- }
- // Value
- if ($cell->getValue() instanceof PHPExcel_RichText) {
- // Loop through rich text elements
- $elements = $cell->getValue()->getRichTextElements();
- foreach ($elements as $element) {
- // Rich text start?
- if ($element instanceof PHPExcel_RichText_Run) {
- $cellData .= '';
-
- if ($element->getFont()->getSuperScript()) {
- $cellData .= '';
- } else if ($element->getFont()->getSubScript()) {
- $cellData .= '';
- }
- }
-
- // Convert UTF8 data to PCDATA
- $cellText = $element->getText();
- $cellData .= htmlspecialchars($cellText);
-
- if ($element instanceof PHPExcel_RichText_Run) {
- if ($element->getFont()->getSuperScript()) {
- $cellData .= '';
- } else if ($element->getFont()->getSubScript()) {
- $cellData .= '';
- }
-
- $cellData .= '';
- }
- }
- } else {
- if ($this->_preCalculateFormulas) {
- $cellData = PHPExcel_Style_NumberFormat::toFormattedString(
- $cell->getCalculatedValue(),
- $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
- array($this, 'formatColor')
- );
- } else {
- $cellData = PHPExcel_Style_NumberFormat::ToFormattedString(
- $cell->getValue(),
- $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(),
- array($this, 'formatColor')
- );
- }
- $cellData = htmlspecialchars($cellData);
- if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) {
- $cellData = ''.$cellData.'';
- } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) {
- $cellData = ''.$cellData.'';
- }
- }
-
- // Converts the cell content so that spaces occuring at beginning of each new line are replaced by
- // Example: " Hello\n to the world" is converted to " Hello\n to the world"
- $cellData = preg_replace("/(?m)(?:^|\\G) /", ' ', $cellData);
-
- // convert newline "\n" to '
'
- $cellData = nl2br($cellData);
-
- // Extend CSS class?
- if (!$this->_useInlineCss) {
- $cssClass .= ' style' . $cell->getXfIndex();
- $cssClass .= ' ' . $cell->getDataType();
- } else {
- if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) {
- $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]);
- }
-
- // General horizontal alignment: Actual horizontal alignment depends on dataType
- $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() );
- if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
- && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align']))
- {
- $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align'];
- }
- }
- }
-
- // Hyperlink?
- if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
- $cellData = '' . $cellData . '';
- }
-
- // Should the cell be written or is it swallowed by a rowspan or colspan?
- $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
- && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] );
-
- // Colspan and Rowspan
- $colspan = 1;
- $rowspan = 1;
- if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
- $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
- $rowSpan = $spans['rowspan'];
- $colSpan = $spans['colspan'];
- }
-
- // Write
- if ($writeCell) {
- // Column start
- $html .= ' _useInlineCss) {
- $html .= ' class="' . $cssClass . '"';
- } else {
- //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
- // We must explicitly write the width of the element because TCPDF
- // does not recognize e.g. element because TCPDF
- // does not recognize e.g.
- if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
- $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
- $cssClass['height'] = $height;
- }
- //** end of redundant code **
-
- $html .= ' style="' . $this->_assembleCSS($cssClass) . '"';
- }
- if ($colSpan > 1) {
- $html .= ' colspan="' . $colSpan . '"';
- }
- if ($rowSpan > 1) {
- $html .= ' rowspan="' . $rowSpan . '"';
- }
- $html .= '>';
-
- // Image?
- $html .= $this->_writeImageInCell($pSheet, $coordinate);
-
- // Chart?
- if ($this->_includeCharts) {
- $html .= $this->_writeChartInCell($pSheet, $coordinate);
- }
-
- // Cell data
- $html .= $cellData;
-
- // Column end
- $html .= '' . PHP_EOL;
- }
-
- // Next column
- ++$colNum;
- }
-
- // Write row end
- $html .= ' ' . PHP_EOL;
-
- // Return
- return $html;
- } else {
- throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
- }
- }
-
- /**
- * Takes array where of CSS properties / values and converts to CSS string
- *
- * @param array
- * @return string
- */
- private function _assembleCSS($pValue = array())
- {
- $pairs = array();
- foreach ($pValue as $property => $value) {
- $pairs[] = $property . ':' . $value;
- }
- $string = implode('; ', $pairs);
-
- return $string;
- }
-
- /**
- * Get images root
- *
- * @return string
- */
- public function getImagesRoot() {
- return $this->_imagesRoot;
- }
-
- /**
- * Set images root
- *
- * @param string $pValue
- * @return PHPExcel_Writer_HTML
- */
- public function setImagesRoot($pValue = '.') {
- $this->_imagesRoot = $pValue;
- return $this;
- }
-
- /**
- * Get embed images
- *
- * @return boolean
- */
- public function getEmbedImages() {
- return $this->_embedImages;
- }
-
- /**
- * Set embed images
- *
- * @param boolean $pValue
- * @return PHPExcel_Writer_HTML
- */
- public function setEmbedImages($pValue = '.') {
- $this->_embedImages = $pValue;
- return $this;
- }
-
- /**
- * Get use inline CSS?
- *
- * @return boolean
- */
- public function getUseInlineCss() {
- return $this->_useInlineCss;
- }
-
- /**
- * Set use inline CSS?
- *
- * @param boolean $pValue
- * @return PHPExcel_Writer_HTML
- */
- public function setUseInlineCss($pValue = false) {
- $this->_useInlineCss = $pValue;
- return $this;
- }
-
- /**
- * Add color to formatted string as inline style
- *
- * @param string $pValue Plain formatted value without color
- * @param string $pFormat Format code
- * @return string
- */
- public function formatColor($pValue, $pFormat)
- {
- // Color information, e.g. [Red] is always at the beginning
- $color = null; // initialize
- $matches = array();
-
- $color_regex = '/^\\[[a-zA-Z]+\\]/';
- if (preg_match($color_regex, $pFormat, $matches)) {
- $color = str_replace('[', '', $matches[0]);
- $color = str_replace(']', '', $color);
- $color = strtolower($color);
- }
-
- // convert to PCDATA
- $value = htmlspecialchars($pValue);
-
- // color span tag
- if ($color !== null) {
- $value = '' . $value . '';
- }
-
- return $value;
- }
-
- /**
- * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
- */
- private function _calculateSpans()
- {
- // Identify all cells that should be omitted in HTML due to cell merge.
- // In HTML only the upper-left cell should be written and it should have
- // appropriate rowspan / colspan attribute
- $sheetIndexes = $this->_sheetIndex !== null ?
- array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1);
-
- foreach ($sheetIndexes as $sheetIndex) {
- $sheet = $this->_phpExcel->getSheet($sheetIndex);
-
- $candidateSpannedRow = array();
-
- // loop through all Excel merged cells
- foreach ($sheet->getMergeCells() as $cells) {
- list($cells, ) = PHPExcel_Cell::splitRange($cells);
- $first = $cells[0];
- $last = $cells[1];
-
- list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first);
- $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1;
-
- list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last);
- $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1;
-
- // loop through the individual cells in the individual merge
- $r = $fr - 1;
- while($r++ < $lr) {
- // also, flag this row as a HTML row that is candidate to be omitted
- $candidateSpannedRow[$r] = $r;
-
- $c = $fc - 1;
- while($c++ < $lc) {
- if ( !($c == $fc && $r == $fr) ) {
- // not the upper-left cell (should not be written in HTML)
- $this->_isSpannedCell[$sheetIndex][$r][$c] = array(
- 'baseCell' => array($fr, $fc),
- );
- } else {
- // upper-left is the base cell that should hold the colspan/rowspan attribute
- $this->_isBaseCell[$sheetIndex][$r][$c] = array(
- 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
- 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
- 'xlcolspan' => $lc - $fc + 1, // Excel colspan
- 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
- );
- }
- }
- }
- }
-
- // Identify which rows should be omitted in HTML. These are the rows where all the cells
- // participate in a merge and the where base cells are somewhere above.
- $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
- foreach ($candidateSpannedRow as $rowIndex) {
- if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) {
- if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
- $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
- };
- }
- }
-
- // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
- if ( isset($this->_isSpannedRow[$sheetIndex]) ) {
- foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) {
- $adjustedBaseCells = array();
- $c = -1;
- $e = $countColumns - 1;
- while($c++ < $e) {
- $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
-
- if ( !in_array($baseCell, $adjustedBaseCells) ) {
- // subtract rowspan by 1
- --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
- $adjustedBaseCells[] = $baseCell;
- }
- }
- }
- }
-
- // TODO: Same for columns
- }
-
- // We have calculated the spans
- $this->_spansAreCalculated = true;
- }
-
+class PHPExcel_Writer_HTML extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter
+{
+ /**
+ * PHPExcel object
+ *
+ * @var PHPExcel
+ */
+ protected $phpExcel;
+
+ /**
+ * Sheet index to write
+ *
+ * @var int
+ */
+ private $sheetIndex = 0;
+
+ /**
+ * Images root
+ *
+ * @var string
+ */
+ private $imagesRoot = '.';
+
+ /**
+ * embed images, or link to images
+ *
+ * @var boolean
+ */
+ private $embedImages = false;
+
+ /**
+ * Use inline CSS?
+ *
+ * @var boolean
+ */
+ private $useInlineCss = false;
+
+ /**
+ * Array of CSS styles
+ *
+ * @var array
+ */
+ private $cssStyles;
+
+ /**
+ * Array of column widths in points
+ *
+ * @var array
+ */
+ private $columnWidths;
+
+ /**
+ * Default font
+ *
+ * @var PHPExcel_Style_Font
+ */
+ private $defaultFont;
+
+ /**
+ * Flag whether spans have been calculated
+ *
+ * @var boolean
+ */
+ private $spansAreCalculated = false;
+
+ /**
+ * Excel cells that should not be written as HTML cells
+ *
+ * @var array
+ */
+ private $isSpannedCell = array();
+
+ /**
+ * Excel cells that are upper-left corner in a cell merge
+ *
+ * @var array
+ */
+ private $isBaseCell = array();
+
+ /**
+ * Excel rows that should not be written as HTML rows
+ *
+ * @var array
+ */
+ private $isSpannedRow = array();
+
+ /**
+ * Is the current writer creating PDF?
+ *
+ * @var boolean
+ */
+ protected $isPdf = false;
+
+ /**
+ * Generate the Navigation block
+ *
+ * @var boolean
+ */
+ private $generateSheetNavigationBlock = true;
+
+ /**
+ * Create a new PHPExcel_Writer_HTML
+ *
+ * @param PHPExcel $phpExcel PHPExcel object
+ */
+ public function __construct(PHPExcel $phpExcel)
+ {
+ $this->phpExcel = $phpExcel;
+ $this->defaultFont = $this->phpExcel->getDefaultStyle()->getFont();
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * Map VAlign
+ *
+ * @param string $vAlign Vertical alignment
+ * @return string
+ */
+ private function mapVAlign($vAlign)
+ {
+ switch ($vAlign) {
+ case PHPExcel_Style_Alignment::VERTICAL_BOTTOM:
+ return 'bottom';
+ case PHPExcel_Style_Alignment::VERTICAL_TOP:
+ return 'top';
+ case PHPExcel_Style_Alignment::VERTICAL_CENTER:
+ case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY:
+ return 'middle';
+ default:
+ return 'baseline';
+ }
+ }
+
+ /**
+ * Map HAlign
+ *
+ * @param string $hAlign Horizontal alignment
+ * @return string|false
+ */
+ private function mapHAlign($hAlign)
+ {
+ switch ($hAlign) {
+ case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL:
+ return false;
+ case PHPExcel_Style_Alignment::HORIZONTAL_LEFT:
+ return 'left';
+ case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT:
+ return 'right';
+ case PHPExcel_Style_Alignment::HORIZONTAL_CENTER:
+ case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS:
+ return 'center';
+ case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY:
+ return 'justify';
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Map border style
+ *
+ * @param int $borderStyle Sheet index
+ * @return string
+ */
+ private function mapBorderStyle($borderStyle)
+ {
+ switch ($borderStyle) {
+ case PHPExcel_Style_Border::BORDER_NONE:
+ return 'none';
+ case PHPExcel_Style_Border::BORDER_DASHDOT:
+ return '1px dashed';
+ case PHPExcel_Style_Border::BORDER_DASHDOTDOT:
+ return '1px dotted';
+ case PHPExcel_Style_Border::BORDER_DASHED:
+ return '1px dashed';
+ case PHPExcel_Style_Border::BORDER_DOTTED:
+ return '1px dotted';
+ case PHPExcel_Style_Border::BORDER_DOUBLE:
+ return '3px double';
+ case PHPExcel_Style_Border::BORDER_HAIR:
+ return '1px solid';
+ case PHPExcel_Style_Border::BORDER_MEDIUM:
+ return '2px solid';
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT:
+ return '2px dashed';
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT:
+ return '2px dotted';
+ case PHPExcel_Style_Border::BORDER_MEDIUMDASHED:
+ return '2px dashed';
+ case PHPExcel_Style_Border::BORDER_SLANTDASHDOT:
+ return '2px dashed';
+ case PHPExcel_Style_Border::BORDER_THICK:
+ return '3px solid';
+ case PHPExcel_Style_Border::BORDER_THIN:
+ return '1px solid';
+ default:
+ // map others to thin
+ return '1px solid';
+ }
+ }
+
+ /**
+ * Get sheet index
+ *
+ * @return int
+ */
+ public function getSheetIndex()
+ {
+ return $this->sheetIndex;
+ }
+
+ /**
+ * Set sheet index
+ *
+ * @param int $pValue Sheet index
+ * @return PHPExcel_Writer_HTML
+ */
+ public function setSheetIndex($pValue = 0)
+ {
+ $this->sheetIndex = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get sheet index
+ *
+ * @return boolean
+ */
+ public function getGenerateSheetNavigationBlock()
+ {
+ return $this->generateSheetNavigationBlock;
+ }
+
+ /**
+ * Set sheet index
+ *
+ * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not
+ * @return PHPExcel_Writer_HTML
+ */
+ public function setGenerateSheetNavigationBlock($pValue = true)
+ {
+ $this->generateSheetNavigationBlock = (bool) $pValue;
+ return $this;
+ }
+
+ /**
+ * Write all sheets (resets sheetIndex to NULL)
+ */
+ public function writeAllSheets()
+ {
+ $this->sheetIndex = null;
+ return $this;
+ }
+
+ /**
+ * Generate HTML header
+ *
+ * @param boolean $pIncludeStyles Include styles?
+ * @return string
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function generateHTMLHeader($pIncludeStyles = false)
+ {
+ // PHPExcel object known?
+ if (is_null($this->phpExcel)) {
+ throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');
+ }
+
+ // Construct HTML
+ $properties = $this->phpExcel->getProperties();
+ $html = '' . PHP_EOL;
+ $html .= '' . PHP_EOL;
+ $html .= '' . PHP_EOL;
+ $html .= ' ' . PHP_EOL;
+ $html .= ' ' . PHP_EOL;
+ if ($properties->getTitle() > '') {
+ $html .= ' ';
+ for ($col = 'A'; $col != $colMax; ++$col) {
+ $html .= ' ';
+ }
+ return $html;
+ }
+
+
+ /**
+ * Generate image tag in cell
+ *
+ * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
+ * @param string $coordinates Cell coordinates
+ * @return string
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates)
+ {
+ // Construct HTML
+ $html = '';
+
+ // Write images
+ foreach ($pSheet->getDrawingCollection() as $drawing) {
+ if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
+ if ($drawing->getCoordinates() == $coordinates) {
+ $filename = $drawing->getPath();
+
+ // Strip off eventual '.'
+ if (substr($filename, 0, 1) == '.') {
+ $filename = substr($filename, 1);
+ }
+
+ // Prepend images root
+ $filename = $this->getImagesRoot() . $filename;
+
+ // Strip off eventual '.'
+ if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
+ $filename = substr($filename, 1);
+ }
+
+ // Convert UTF8 data to PCDATA
+ $filename = htmlspecialchars($filename);
+
+ $html .= PHP_EOL;
+ if ((!$this->embedImages) || ($this->isPdf)) {
+ $imageData = $filename;
+ } else {
+ $imageDetails = getimagesize($filename);
+ if ($fp = fopen($filename, "rb", 0)) {
+ $picture = fread($fp, filesize($filename));
+ fclose($fp);
+ // base64 encode the binary data, then break it
+ // into chunks according to RFC 2045 semantics
+ $base64 = chunk_split(base64_encode($picture));
+ $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
+ } else {
+ $imageData = $filename;
+ }
+ }
+
+ $html .= '';
+ $html .= $this->writeImageInCell($pSheet, $col.$row);
+ if ($this->includeCharts) {
+ $html .= $this->writeChartInCell($pSheet, $col.$row);
+ }
+ $html .= ' ';
+ }
+ ++$row;
+ $html .= '';
+ $html .= '
';
+ }
+ }
+
+ return $html;
+ }
+
+ /**
+ * Generate chart tag in cell
+ *
+ * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
+ * @param string $coordinates Cell coordinates
+ * @return string
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeChartInCell(PHPExcel_Worksheet $pSheet, $coordinates)
+ {
+ // Construct HTML
+ $html = '';
+
+ // Write charts
+ foreach ($pSheet->getChartCollection() as $chart) {
+ if ($chart instanceof PHPExcel_Chart) {
+ $chartCoordinates = $chart->getTopLeftPosition();
+ if ($chartCoordinates['cell'] == $coordinates) {
+ $chartFileName = PHPExcel_Shared_File::sys_get_temp_dir().'/'.uniqid().'.png';
+ if (!$chart->render($chartFileName)) {
+ return;
+ }
+
+ $html .= PHP_EOL;
+ $imageDetails = getimagesize($chartFileName);
+ if ($fp = fopen($chartFileName, "rb", 0)) {
+ $picture = fread($fp, filesize($chartFileName));
+ fclose($fp);
+ // base64 encode the binary data, then break it
+ // into chunks according to RFC 2045 semantics
+ $base64 = chunk_split(base64_encode($picture));
+ $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64;
+
+ $html .= '
' . PHP_EOL;
+ $html .= '
' . PHP_EOL;
+ } else {
+ $style = isset($this->cssStyles['table']) ?
+ $this->assembleCSS($this->cssStyles['table']) : '';
+
+ if ($this->isPdf && $pSheet->getShowGridlines()) {
+ $html .= '
' . PHP_EOL;
+ } else {
+ $html .= '
+ $html .= $this->generateTableFooter();
+
+ // insert page break
+ $html .= '';
+
+ // open table again: ' . PHP_EOL;
+ }
+ }
+
+ // Write
' . PHP_EOL;
+
+ return $html;
+ }
+
+ /**
+ * Generate row
+ *
+ * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet
+ * @param array $pValues Array containing cells in a row
+ * @param int $pRow Row number (0-based)
+ * @return string
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0, $cellType = 'td')
+ {
+ if (is_array($pValues)) {
+ // Construct HTML
+ $html = '';
+
+ // Sheet index
+ $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
+
+ // DomPDF and breaks
+ if ($this->isPdf && count($pSheet->getBreaks()) > 0) {
+ $breaks = $pSheet->getBreaks();
+
+ // check if a break is needed before this row
+ if (isset($breaks['A' . $pRow])) {
+ // close table: +
' . PHP_EOL;
+ } else {
+ $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
+ ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
+
+ $html .= ' ' . PHP_EOL;
+ }
+
+ // Write cells
+ $colNum = 0;
+ foreach ($pValues as $cellAddress) {
+ $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : '';
+ $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1);
+ if (!$this->useInlineCss) {
+ $cssClass = '';
+ $cssClass = 'column' . $colNum;
+ } else {
+ $cssClass = array();
+ if ($cellType == 'th') {
+ if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum])) {
+ $this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum];
+ }
+ } else {
+ if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
+ $this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
+ }
+ }
+ }
+ $colSpan = 1;
+ $rowSpan = 1;
+
+ // initialize
+ $cellData = ' ';
+
+ // PHPExcel_Cell
+ if ($cell instanceof PHPExcel_Cell) {
+ $cellData = '';
+ if (is_null($cell->getParent())) {
+ $cell->attach($pSheet);
+ }
+ // Value
+ if ($cell->getValue() instanceof PHPExcel_RichText) {
+ // Loop through rich text elements
+ $elements = $cell->getValue()->getRichTextElements();
+ foreach ($elements as $element) {
+ // Rich text start?
+ if ($element instanceof PHPExcel_RichText_Run) {
+ $cellData .= '';
+
+ if ($element->getFont()->getSuperScript()) {
+ $cellData .= '';
+ } elseif ($element->getFont()->getSubScript()) {
+ $cellData .= '';
+ }
+ }
+
+ // Convert UTF8 data to PCDATA
+ $cellText = $element->getText();
+ $cellData .= htmlspecialchars($cellText);
+
+ if ($element instanceof PHPExcel_RichText_Run) {
+ if ($element->getFont()->getSuperScript()) {
+ $cellData .= '';
+ } elseif ($element->getFont()->getSubScript()) {
+ $cellData .= '';
+ }
+
+ $cellData .= '';
+ }
+ }
+ } else {
+ if ($this->preCalculateFormulas) {
+ $cellData = PHPExcel_Style_NumberFormat::toFormattedString(
+ $cell->getCalculatedValue(),
+ $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(),
+ array($this, 'formatColor')
+ );
+ } else {
+ $cellData = PHPExcel_Style_NumberFormat::toFormattedString(
+ $cell->getValue(),
+ $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(),
+ array($this, 'formatColor')
+ );
+ }
+ $cellData = htmlspecialchars($cellData);
+ if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperScript()) {
+ $cellData = ''.$cellData.'';
+ } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubScript()) {
+ $cellData = ''.$cellData.'';
+ }
+ }
+
+ // Converts the cell content so that spaces occuring at beginning of each new line are replaced by
+ // Example: " Hello\n to the world" is converted to " Hello\n to the world"
+ $cellData = preg_replace("/(?m)(?:^|\\G) /", ' ', $cellData);
+
+ // convert newline "\n" to '
'
+ $cellData = nl2br($cellData);
+
+ // Extend CSS class?
+ if (!$this->useInlineCss) {
+ $cssClass .= ' style' . $cell->getXfIndex();
+ $cssClass .= ' ' . $cell->getDataType();
+ } else {
+ if ($cellType == 'th') {
+ if (isset($this->cssStyles['th.style' . $cell->getXfIndex()])) {
+ $cssClass = array_merge($cssClass, $this->cssStyles['th.style' . $cell->getXfIndex()]);
+ }
+ } else {
+ if (isset($this->cssStyles['td.style' . $cell->getXfIndex()])) {
+ $cssClass = array_merge($cssClass, $this->cssStyles['td.style' . $cell->getXfIndex()]);
+ }
+ }
+
+ // General horizontal alignment: Actual horizontal alignment depends on dataType
+ $sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex());
+ if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
+ && isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])) {
+ $cssClass['text-align'] = $this->cssStyles['.' . $cell->getDataType()]['text-align'];
+ }
+ }
+ }
+
+ // Hyperlink?
+ if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
+ $cellData = '' . $cellData . '';
+ }
+
+ // Should the cell be written or is it swallowed by a rowspan or colspan?
+ $writeCell = !(isset($this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
+ && $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]);
+
+ // Colspan and Rowspan
+ $colspan = 1;
+ $rowspan = 1;
+ if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
+ $spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
+ $rowSpan = $spans['rowspan'];
+ $colSpan = $spans['colspan'];
+
+ // Also apply style from last cell in merge to fix borders -
+ // relies on !important for non-none border declarations in createCSSStyleBorder
+ $endCellCoord = PHPExcel_Cell::stringFromColumnIndex($colNum + $colSpan - 1) . ($pRow + $rowSpan);
+ if (!$this->useInlineCss) {
+ $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex();
+ }
+ }
+
+ // Write
+ if ($writeCell) {
+ // Column start
+ $html .= ' <' . $cellType;
+ if (!$this->useInlineCss) {
+ $html .= ' class="' . $cssClass . '"';
+ } else {
+ //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
+ // We must explicitly write the width of the element because TCPDF
+ // does not recognize e.g. element because TCPDF
+ // does not recognize e.g.
+ if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
+ $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
+ $cssClass['height'] = $height;
+ }
+ //** end of redundant code **
+
+ $html .= ' style="' . $this->assembleCSS($cssClass) . '"';
+ }
+ if ($colSpan > 1) {
+ $html .= ' colspan="' . $colSpan . '"';
+ }
+ if ($rowSpan > 1) {
+ $html .= ' rowspan="' . $rowSpan . '"';
+ }
+ $html .= '>';
+
+ // Image?
+ $html .= $this->writeImageInCell($pSheet, $coordinate);
+
+ // Chart?
+ if ($this->includeCharts) {
+ $html .= $this->writeChartInCell($pSheet, $coordinate);
+ }
+
+ // Cell data
+ $html .= $cellData;
+
+ // Column end
+ $html .= ''.$cellType.'>' . PHP_EOL;
+ }
+
+ // Next column
+ ++$colNum;
+ }
+
+ // Write row end
+ $html .= ' ' . PHP_EOL;
+
+ // Return
+ return $html;
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Takes array where of CSS properties / values and converts to CSS string
+ *
+ * @param array
+ * @return string
+ */
+ private function assembleCSS($pValue = array())
+ {
+ $pairs = array();
+ foreach ($pValue as $property => $value) {
+ $pairs[] = $property . ':' . $value;
+ }
+ $string = implode('; ', $pairs);
+
+ return $string;
+ }
+
+ /**
+ * Get images root
+ *
+ * @return string
+ */
+ public function getImagesRoot()
+ {
+ return $this->imagesRoot;
+ }
+
+ /**
+ * Set images root
+ *
+ * @param string $pValue
+ * @return PHPExcel_Writer_HTML
+ */
+ public function setImagesRoot($pValue = '.')
+ {
+ $this->imagesRoot = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get embed images
+ *
+ * @return boolean
+ */
+ public function getEmbedImages()
+ {
+ return $this->embedImages;
+ }
+
+ /**
+ * Set embed images
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Writer_HTML
+ */
+ public function setEmbedImages($pValue = '.')
+ {
+ $this->embedImages = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get use inline CSS?
+ *
+ * @return boolean
+ */
+ public function getUseInlineCss()
+ {
+ return $this->useInlineCss;
+ }
+
+ /**
+ * Set use inline CSS?
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Writer_HTML
+ */
+ public function setUseInlineCss($pValue = false)
+ {
+ $this->useInlineCss = $pValue;
+ return $this;
+ }
+
+ /**
+ * Add color to formatted string as inline style
+ *
+ * @param string $pValue Plain formatted value without color
+ * @param string $pFormat Format code
+ * @return string
+ */
+ public function formatColor($pValue, $pFormat)
+ {
+ // Color information, e.g. [Red] is always at the beginning
+ $color = null; // initialize
+ $matches = array();
+
+ $color_regex = '/^\\[[a-zA-Z]+\\]/';
+ if (preg_match($color_regex, $pFormat, $matches)) {
+ $color = str_replace('[', '', $matches[0]);
+ $color = str_replace(']', '', $color);
+ $color = strtolower($color);
+ }
+
+ // convert to PCDATA
+ $value = htmlspecialchars($pValue);
+
+ // color span tag
+ if ($color !== null) {
+ $value = '' . $value . '';
+ }
+
+ return $value;
+ }
+
+ /**
+ * Calculate information about HTML colspan and rowspan which is not always the same as Excel's
+ */
+ private function calculateSpans()
+ {
+ // Identify all cells that should be omitted in HTML due to cell merge.
+ // In HTML only the upper-left cell should be written and it should have
+ // appropriate rowspan / colspan attribute
+ $sheetIndexes = $this->sheetIndex !== null ?
+ array($this->sheetIndex) : range(0, $this->phpExcel->getSheetCount() - 1);
+
+ foreach ($sheetIndexes as $sheetIndex) {
+ $sheet = $this->phpExcel->getSheet($sheetIndex);
+
+ $candidateSpannedRow = array();
+
+ // loop through all Excel merged cells
+ foreach ($sheet->getMergeCells() as $cells) {
+ list($cells,) = PHPExcel_Cell::splitRange($cells);
+ $first = $cells[0];
+ $last = $cells[1];
+
+ list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first);
+ $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1;
+
+ list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last);
+ $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1;
+
+ // loop through the individual cells in the individual merge
+ $r = $fr - 1;
+ while ($r++ < $lr) {
+ // also, flag this row as a HTML row that is candidate to be omitted
+ $candidateSpannedRow[$r] = $r;
+
+ $c = $fc - 1;
+ while ($c++ < $lc) {
+ if (!($c == $fc && $r == $fr)) {
+ // not the upper-left cell (should not be written in HTML)
+ $this->isSpannedCell[$sheetIndex][$r][$c] = array(
+ 'baseCell' => array($fr, $fc),
+ );
+ } else {
+ // upper-left is the base cell that should hold the colspan/rowspan attribute
+ $this->isBaseCell[$sheetIndex][$r][$c] = array(
+ 'xlrowspan' => $lr - $fr + 1, // Excel rowspan
+ 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
+ 'xlcolspan' => $lc - $fc + 1, // Excel colspan
+ 'colspan' => $lc - $fc + 1, // HTML colspan, value may change
+ );
+ }
+ }
+ }
+ }
+
+ // Identify which rows should be omitted in HTML. These are the rows where all the cells
+ // participate in a merge and the where base cells are somewhere above.
+ $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
+ foreach ($candidateSpannedRow as $rowIndex) {
+ if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) {
+ if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
+ $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
+ };
+ }
+ }
+
+ // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
+ if (isset($this->isSpannedRow[$sheetIndex])) {
+ foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) {
+ $adjustedBaseCells = array();
+ $c = -1;
+ $e = $countColumns - 1;
+ while ($c++ < $e) {
+ $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
+
+ if (!in_array($baseCell, $adjustedBaseCells)) {
+ // subtract rowspan by 1
+ --$this->isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan'];
+ $adjustedBaseCells[] = $baseCell;
+ }
+ }
+ }
+ }
+
+ // TODO: Same for columns
+ }
+
+ // We have calculated the spans
+ $this->spansAreCalculated = true;
+ }
+
+ private function setMargins(PHPExcel_Worksheet $pSheet)
+ {
+ $htmlPage = '@page { ';
+ $htmlBody = 'body { ';
+
+ $left = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
+ $htmlPage .= 'margin-left: ' . $left;
+ $htmlBody .= 'margin-left: ' . $left;
+ $right = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
+ $htmlPage .= 'margin-right: ' . $right;
+ $htmlBody .= 'margin-right: ' . $right;
+ $top = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
+ $htmlPage .= 'margin-top: ' . $top;
+ $htmlBody .= 'margin-top: ' . $top;
+ $bottom = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
+ $htmlPage .= 'margin-bottom: ' . $bottom;
+ $htmlBody .= 'margin-bottom: ' . $bottom;
+
+ $htmlPage .= "}\n";
+ $htmlBody .= "}\n";
+
+ return "\n";
+ }
}
diff --git a/Classes/PHPExcel/Writer/IWriter.php b/Classes/PHPExcel/Writer/IWriter.php
index 908e45f69..c7cfe7405 100644
--- a/Classes/PHPExcel/Writer/IWriter.php
+++ b/Classes/PHPExcel/Writer/IWriter.php
@@ -1,8 +1,9 @@
setPHPExcel($pPHPExcel);
+
+ $writerPartsArray = array(
+ 'content' => 'PHPExcel_Writer_OpenDocument_Content',
+ 'meta' => 'PHPExcel_Writer_OpenDocument_Meta',
+ 'meta_inf' => 'PHPExcel_Writer_OpenDocument_MetaInf',
+ 'mimetype' => 'PHPExcel_Writer_OpenDocument_Mimetype',
+ 'settings' => 'PHPExcel_Writer_OpenDocument_Settings',
+ 'styles' => 'PHPExcel_Writer_OpenDocument_Styles',
+ 'thumbnails' => 'PHPExcel_Writer_OpenDocument_Thumbnails'
+ );
+
+ foreach ($writerPartsArray as $writer => $class) {
+ $this->writerParts[$writer] = new $class($this);
+ }
+ }
+
+ /**
+ * Get writer part
+ *
+ * @param string $pPartName Writer part name
+ * @return PHPExcel_Writer_Excel2007_WriterPart
+ */
+ public function getWriterPart($pPartName = '')
+ {
+ if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
+ return $this->writerParts[strtolower($pPartName)];
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Save PHPExcel to file
+ *
+ * @param string $pFilename
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function save($pFilename = null)
+ {
+ if (!$this->spreadSheet) {
+ throw new PHPExcel_Writer_Exception('PHPExcel object unassigned.');
+ }
+
+ // garbage collect
+ $this->spreadSheet->garbageCollect();
+
+ // If $pFilename is php://output or php://stdout, make it a temporary file...
+ $originalFilename = $pFilename;
+ if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
+ $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp');
+ if ($pFilename == '') {
+ $pFilename = $originalFilename;
+ }
+ }
+
+ $objZip = $this->createZip($pFilename);
+
+ $objZip->addFromString('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest());
+ $objZip->addFromString('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail());
+ $objZip->addFromString('content.xml', $this->getWriterPart('content')->write());
+ $objZip->addFromString('meta.xml', $this->getWriterPart('meta')->write());
+ $objZip->addFromString('mimetype', $this->getWriterPart('mimetype')->write());
+ $objZip->addFromString('settings.xml', $this->getWriterPart('settings')->write());
+ $objZip->addFromString('styles.xml', $this->getWriterPart('styles')->write());
+
+ // Close file
+ if ($objZip->close() === false) {
+ throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename.");
+ }
+
+ // If a temporary file was used, copy it to the correct file stream
+ if ($originalFilename != $pFilename) {
+ if (copy($pFilename, $originalFilename) === false) {
+ throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
+ }
+ @unlink($pFilename);
+ }
+ }
+
+ /**
+ * Create zip object
+ *
+ * @param string $pFilename
+ * @throws PHPExcel_Writer_Exception
+ * @return ZipArchive
+ */
+ private function createZip($pFilename)
+ {
+ // 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.");
+ }
+ }
+
+ return $objZip;
+ }
+
+ /**
+ * Get PHPExcel object
+ *
+ * @return PHPExcel
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function getPHPExcel()
+ {
+ if ($this->spreadSheet !== null) {
+ return $this->spreadSheet;
+ } else {
+ throw new PHPExcel_Writer_Exception('No PHPExcel assigned.');
+ }
+ }
+
+ /**
+ * Set PHPExcel object
+ *
+ * @param PHPExcel $pPHPExcel PHPExcel object
+ * @throws PHPExcel_Writer_Exception
+ * @return PHPExcel_Writer_Excel2007
+ */
+ public function setPHPExcel(PHPExcel $pPHPExcel = null)
+ {
+ $this->spreadSheet = $pPHPExcel;
+ return $this;
+ }
+}
diff --git a/Classes/PHPExcel/Writer/OpenDocument/Cell/Comment.php b/Classes/PHPExcel/Writer/OpenDocument/Cell/Comment.php
new file mode 100644
index 000000000..f1e98a16e
--- /dev/null
+++ b/Classes/PHPExcel/Writer/OpenDocument/Cell/Comment.php
@@ -0,0 +1,63 @@
+
+ */
+class PHPExcel_Writer_OpenDocument_Cell_Comment
+{
+ public static function write(PHPExcel_Shared_XMLWriter $objWriter, PHPExcel_Cell $cell)
+ {
+ $comments = $cell->getWorksheet()->getComments();
+ if (!isset($comments[$cell->getCoordinate()])) {
+ return;
+ }
+ $comment = $comments[$cell->getCoordinate()];
+
+ $objWriter->startElement('office:annotation');
+ //$objWriter->writeAttribute('draw:style-name', 'gr1');
+ //$objWriter->writeAttribute('draw:text-style-name', 'P1');
+ $objWriter->writeAttribute('svg:width', $comment->getWidth());
+ $objWriter->writeAttribute('svg:height', $comment->getHeight());
+ $objWriter->writeAttribute('svg:x', $comment->getMarginLeft());
+ $objWriter->writeAttribute('svg:y', $comment->getMarginTop());
+ //$objWriter->writeAttribute('draw:caption-point-x', $comment->getMarginLeft());
+ //$objWriter->writeAttribute('draw:caption-point-y', $comment->getMarginTop());
+ $objWriter->writeElement('dc:creator', $comment->getAuthor());
+ // TODO: Not realized in PHPExcel_Comment yet.
+ //$objWriter->writeElement('dc:date', $comment->getDate());
+ $objWriter->writeElement('text:p', $comment->getText()->getPlainText());
+ //$objWriter->writeAttribute('draw:text-style-name', 'P1');
+ $objWriter->endElement();
+ }
+}
diff --git a/Classes/PHPExcel/Writer/OpenDocument/Content.php b/Classes/PHPExcel/Writer/OpenDocument/Content.php
new file mode 100644
index 000000000..a34b1670c
--- /dev/null
+++ b/Classes/PHPExcel/Writer/OpenDocument/Content.php
@@ -0,0 +1,272 @@
+
+ */
+class PHPExcel_Writer_OpenDocument_Content extends PHPExcel_Writer_OpenDocument_WriterPart
+{
+ const NUMBER_COLS_REPEATED_MAX = 1024;
+ const NUMBER_ROWS_REPEATED_MAX = 1048576;
+
+ /**
+ * Write content.xml to XML format
+ *
+ * @param PHPExcel $pPHPExcel
+ * @return string XML Output
+ * @throws PHPExcel_Writer_Exception
+ */
+ public function write(PHPExcel $pPHPExcel = null)
+ {
+ if (!$pPHPExcel) {
+ $pPHPExcel = $this->getParentWriter()->getPHPExcel(); /* @var $pPHPExcel PHPExcel */
+ }
+
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8');
+
+ // Content
+ $objWriter->startElement('office:document-content');
+ $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
+ $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0');
+ $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0');
+ $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0');
+ $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0');
+ $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0');
+ $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
+ $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
+ $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0');
+ $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0');
+ $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0');
+ $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0');
+ $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0');
+ $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0');
+ $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML');
+ $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0');
+ $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0');
+ $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
+ $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer');
+ $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc');
+ $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events');
+ $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms');
+ $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
+ $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
+ $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report');
+ $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2');
+ $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
+ $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#');
+ $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table');
+ $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0');
+ $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0');
+ $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/');
+ $objWriter->writeAttribute('office:version', '1.2');
+
+ $objWriter->writeElement('office:scripts');
+ $objWriter->writeElement('office:font-face-decls');
+ $objWriter->writeElement('office:automatic-styles');
+
+ $objWriter->startElement('office:body');
+ $objWriter->startElement('office:spreadsheet');
+ $objWriter->writeElement('table:calculation-settings');
+ $this->writeSheets($objWriter);
+ $objWriter->writeElement('table:named-expressions');
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
+ /**
+ * Write sheets
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter
+ */
+ private function writeSheets(PHPExcel_Shared_XMLWriter $objWriter)
+ {
+ $pPHPExcel = $this->getParentWriter()->getPHPExcel(); /* @var $pPHPExcel PHPExcel */
+
+ $sheet_count = $pPHPExcel->getSheetCount();
+ for ($i = 0; $i < $sheet_count; $i++) {
+ //$this->getWriterPart('Worksheet')->writeWorksheet());
+ $objWriter->startElement('table:table');
+ $objWriter->writeAttribute('table:name', $pPHPExcel->getSheet($i)->getTitle());
+ $objWriter->writeElement('office:forms');
+ $objWriter->startElement('table:table-column');
+ $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX);
+ $objWriter->endElement();
+ $this->writeRows($objWriter, $pPHPExcel->getSheet($i));
+ $objWriter->endElement();
+ }
+ }
+
+ /**
+ * Write rows of the specified sheet
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter
+ * @param PHPExcel_Worksheet $sheet
+ */
+ private function writeRows(PHPExcel_Shared_XMLWriter $objWriter, PHPExcel_Worksheet $sheet)
+ {
+ $number_rows_repeated = self::NUMBER_ROWS_REPEATED_MAX;
+ $span_row = 0;
+ $rows = $sheet->getRowIterator();
+ while ($rows->valid()) {
+ $number_rows_repeated--;
+ $row = $rows->current();
+ if ($row->getCellIterator()->valid()) {
+ if ($span_row) {
+ $objWriter->startElement('table:table-row');
+ if ($span_row > 1) {
+ $objWriter->writeAttribute('table:number-rows-repeated', $span_row);
+ }
+ $objWriter->startElement('table:table-cell');
+ $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ $span_row = 0;
+ }
+ $objWriter->startElement('table:table-row');
+ $this->writeCells($objWriter, $row);
+ $objWriter->endElement();
+ } else {
+ $span_row++;
+ }
+ $rows->next();
+ }
+ }
+
+ /**
+ * Write cells of the specified row
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter
+ * @param PHPExcel_Worksheet_Row $row
+ * @throws PHPExcel_Writer_Exception
+ */
+ private function writeCells(PHPExcel_Shared_XMLWriter $objWriter, PHPExcel_Worksheet_Row $row)
+ {
+ $number_cols_repeated = self::NUMBER_COLS_REPEATED_MAX;
+ $prev_column = -1;
+ $cells = $row->getCellIterator();
+ while ($cells->valid()) {
+ $cell = $cells->current();
+ $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
+
+ $this->writeCellSpan($objWriter, $column, $prev_column);
+ $objWriter->startElement('table:table-cell');
+
+ switch ($cell->getDataType()) {
+ case PHPExcel_Cell_DataType::TYPE_BOOL:
+ $objWriter->writeAttribute('office:value-type', 'boolean');
+ $objWriter->writeAttribute('office:value', $cell->getValue());
+ $objWriter->writeElement('text:p', $cell->getValue());
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_ERROR:
+ throw new PHPExcel_Writer_Exception('Writing of error not implemented yet.');
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_FORMULA:
+ try {
+ $formula_value = $cell->getCalculatedValue();
+ } catch (Exception $e) {
+ $formula_value = $cell->getValue();
+ }
+ $objWriter->writeAttribute('table:formula', 'of:' . $cell->getValue());
+ if (is_numeric($formula_value)) {
+ $objWriter->writeAttribute('office:value-type', 'float');
+ } else {
+ $objWriter->writeAttribute('office:value-type', 'string');
+ }
+ $objWriter->writeAttribute('office:value', $formula_value);
+ $objWriter->writeElement('text:p', $formula_value);
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_INLINE:
+ throw new PHPExcel_Writer_Exception('Writing of inline not implemented yet.');
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_NUMERIC:
+ $objWriter->writeAttribute('office:value-type', 'float');
+ $objWriter->writeAttribute('office:value', $cell->getValue());
+ $objWriter->writeElement('text:p', $cell->getValue());
+ break;
+
+ case PHPExcel_Cell_DataType::TYPE_STRING:
+ $objWriter->writeAttribute('office:value-type', 'string');
+ $objWriter->writeElement('text:p', $cell->getValue());
+ break;
+ }
+ PHPExcel_Writer_OpenDocument_Cell_Comment::write($objWriter, $cell);
+ $objWriter->endElement();
+ $prev_column = $column;
+ $cells->next();
+ }
+ $number_cols_repeated = $number_cols_repeated - $prev_column - 1;
+ if ($number_cols_repeated > 0) {
+ if ($number_cols_repeated > 1) {
+ $objWriter->startElement('table:table-cell');
+ $objWriter->writeAttribute('table:number-columns-repeated', $number_cols_repeated);
+ $objWriter->endElement();
+ } else {
+ $objWriter->writeElement('table:table-cell');
+ }
+ }
+ }
+
+ /**
+ * Write span
+ *
+ * @param PHPExcel_Shared_XMLWriter $objWriter
+ * @param integer $curColumn
+ * @param integer $prevColumn
+ */
+ private function writeCellSpan(PHPExcel_Shared_XMLWriter $objWriter, $curColumn, $prevColumn)
+ {
+ $diff = $curColumn - $prevColumn - 1;
+ if (1 === $diff) {
+ $objWriter->writeElement('table:table-cell');
+ } elseif ($diff > 1) {
+ $objWriter->startElement('table:table-cell');
+ $objWriter->writeAttribute('table:number-columns-repeated', $diff);
+ $objWriter->endElement();
+ }
+ }
+}
diff --git a/Classes/PHPExcel/Writer/OpenDocument/Meta.php b/Classes/PHPExcel/Writer/OpenDocument/Meta.php
new file mode 100644
index 000000000..1a5c5fd0b
--- /dev/null
+++ b/Classes/PHPExcel/Writer/OpenDocument/Meta.php
@@ -0,0 +1,95 @@
+getParentWriter()->getPHPExcel();
+ }
+
+ $objWriter = null;
+ if ($this->getParentWriter()->getUseDiskCaching()) {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
+ } else {
+ $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
+ }
+
+ // XML header
+ $objWriter->startDocument('1.0', 'UTF-8');
+
+ // Meta
+ $objWriter->startElement('office:document-meta');
+
+ $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
+ $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
+ $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
+ $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0');
+ $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
+ $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#');
+ $objWriter->writeAttribute('office:version', '1.2');
+
+ $objWriter->startElement('office:meta');
+
+ $objWriter->writeElement('meta:initial-creator', $pPHPExcel->getProperties()->getCreator());
+ $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator());
+ $objWriter->writeElement('meta:creation-date', date(DATE_W3C, $pPHPExcel->getProperties()->getCreated()));
+ $objWriter->writeElement('dc:date', date(DATE_W3C, $pPHPExcel->getProperties()->getCreated()));
+ $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle());
+ $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription());
+ $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject());
+ $keywords = explode(' ', $pPHPExcel->getProperties()->getKeywords());
+ foreach ($keywords as $keyword) {
+ $objWriter->writeElement('meta:keyword', $keyword);
+ }
+
+ //PHPExcel Reader Example #18
+Reading list of WorkSheets without loading entire file
+';
+
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+$worksheetNames = $objReader->listWorksheetNames($inputFileName);
+
+echo 'Worksheet Names
';
+echo '';
+foreach ($worksheetNames as $worksheetName) {
+ echo '
';
+
+?>
+
+
\ No newline at end of file
diff --git a/Documentation/Examples/Reader/exampleReader19.php b/Documentation/Examples/Reader/exampleReader19.php
new file mode 100644
index 000000000..2f3eaaf28
--- /dev/null
+++ b/Documentation/Examples/Reader/exampleReader19.php
@@ -0,0 +1,53 @@
+
+
+
+
+
+PHPExcel Reader Example #19
+Reading WorkSheet information without loading entire file
+';
+
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+$worksheetData = $objReader->listWorksheetInfo($inputFileName);
+
+echo 'Worksheet Information
';
+echo '';
+foreach ($worksheetData as $worksheet) {
+ echo '
';
+
+?>
+
+
\ No newline at end of file
diff --git a/Documentation/FunctionListByCategory.txt b/Documentation/FunctionListByCategory.txt
index a5423eb66..b23d9a11c 100644
--- a/Documentation/FunctionListByCategory.txt
+++ b/Documentation/FunctionListByCategory.txt
@@ -177,7 +177,7 @@ CATEGORY_LOOKUP_AND_REFERENCE
COLUMN PHPExcel_Calculation_LookupRef::COLUMN
COLUMNS PHPExcel_Calculation_LookupRef::COLUMNS
GETPIVOTDATA *** Not yet Implemented
- HLOOKUP *** Not yet Implemented
+ HLOOKUP PHPExcel_Calculation_LookupRef::HLOOKUP
HYPERLINK PHPExcel_Calculation_LookupRef::HYPERLINK
INDEX PHPExcel_Calculation_LookupRef::INDEX
INDIRECT PHPExcel_Calculation_LookupRef::INDIRECT
@@ -374,4 +374,4 @@ CATEGORY_TEXT_AND_DATA
TEXT PHPExcel_Calculation_TextData::TEXTFORMAT
TRIM PHPExcel_Calculation_TextData::TRIMSPACES
UPPER PHPExcel_Calculation_TextData::UPPERCASE
- VALUE *** Not yet Implemented
+ VALUE PHPExcel_Calculation_TextData::VALUE
diff --git a/Documentation/FunctionListByName.txt b/Documentation/FunctionListByName.txt
index 082c83af0..45a9daf73 100644
--- a/Documentation/FunctionListByName.txt
+++ b/Documentation/FunctionListByName.txt
@@ -146,7 +146,7 @@ HARMEAN CATEGORY_STATISTICAL PHPExcel_Calculation_Sta
HEX2BIN CATEGORY_ENGINEERING PHPExcel_Calculation_Engineering::HEXTOBIN
HEX2DEC CATEGORY_ENGINEERING PHPExcel_Calculation_Engineering::HEXTODEC
HEX2OCT CATEGORY_ENGINEERING PHPExcel_Calculation_Engineering::HEXTOOCT
-HLOOKUP CATEGORY_LOOKUP_AND_REFERENCE *** Not yet Implemented
+HLOOKUP CATEGORY_LOOKUP_AND_REFERENCE PHPExcel_Calculation_LookupRef::HLOOKUP
HOUR CATEGORY_DATE_AND_TIME PHPExcel_Calculation_DateTime::HOUROFDAY
HYPERLINK CATEGORY_LOOKUP_AND_REFERENCE PHPExcel_Calculation_LookupRef::HYPERLINK
HYPGEOMDIST CATEGORY_STATISTICAL PHPExcel_Calculation_Statistical::HYPGEOMDIST
@@ -355,7 +355,7 @@ TYPE CATEGORY_INFORMATION PHPExcel_Calculation_Fun
UPPER CATEGORY_TEXT_AND_DATA PHPExcel_Calculation_TextData::UPPERCASE
USDOLLAR CATEGORY_FINANCIAL *** Not yet Implemented
-VALUE CATEGORY_TEXT_AND_DATA *** Not yet Implemented
+VALUE CATEGORY_TEXT_AND_DATA PHPExcel_Calculation_TextData::VALUE
VAR CATEGORY_STATISTICAL PHPExcel_Calculation_Statistical::VARFunc
VARA CATEGORY_STATISTICAL PHPExcel_Calculation_Statistical::VARA
VARP CATEGORY_STATISTICAL PHPExcel_Calculation_Statistical::VARP
diff --git a/Documentation/Functionality Cross-Reference.xls b/Documentation/Functionality Cross-Reference.xls
index 905f94430..227fd612f 100644
Binary files a/Documentation/Functionality Cross-Reference.xls and b/Documentation/Functionality Cross-Reference.xls differ
diff --git a/Documentation/PHPExcel AutoFilter Reference developer documentation.doc b/Documentation/PHPExcel AutoFilter Reference developer documentation.doc
index 2024f77c2..208b20205 100644
Binary files a/Documentation/PHPExcel AutoFilter Reference developer documentation.doc and b/Documentation/PHPExcel AutoFilter Reference developer documentation.doc differ
diff --git a/Documentation/PHPExcel Function Reference developer documentation.doc b/Documentation/PHPExcel Function Reference developer documentation.doc
index 1ab93b253..57d218c7c 100644
Binary files a/Documentation/PHPExcel Function Reference developer documentation.doc and b/Documentation/PHPExcel Function Reference developer documentation.doc differ
diff --git a/Documentation/PHPExcel User Documentation - Reading Spreadsheet Files.doc b/Documentation/PHPExcel User Documentation - Reading Spreadsheet Files.doc
index 810937e74..ef3954d3b 100644
Binary files a/Documentation/PHPExcel User Documentation - Reading Spreadsheet Files.doc and b/Documentation/PHPExcel User Documentation - Reading Spreadsheet Files.doc differ
diff --git a/Documentation/PHPExcel developer documentation.doc b/Documentation/PHPExcel developer documentation.doc
index 401951507..52cc9647d 100644
Binary files a/Documentation/PHPExcel developer documentation.doc and b/Documentation/PHPExcel developer documentation.doc differ
diff --git a/Documentation/markdown/CalculationEngine/FunctionReference/01-Introduction.md b/Documentation/markdown/CalculationEngine/FunctionReference/01-Introduction.md
new file mode 100644
index 000000000..2ea3a5057
--- /dev/null
+++ b/Documentation/markdown/CalculationEngine/FunctionReference/01-Introduction.md
@@ -0,0 +1,11 @@
+# Calculation Engine - Formula Function Reference
+
+## Frequently asked questions
+
+The up-to-date F.A.Q. page for PHPExcel can be found on [http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements][1].
+
+### Formulas don’t seem to be calculated in Excel2003 using compatibility pack?
+
+This is normal behaviour of the compatibility pack, Excel2007 displays this correctly. Use PHPExcel_Writer_Excel5 if you really need calculated values, or force recalculation in Excel2003.
+
+ [1]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements
diff --git a/Documentation/markdown/CalculationEngine/FunctionReference/02-01-Date-and-Time-Handling.md b/Documentation/markdown/CalculationEngine/FunctionReference/02-01-Date-and-Time-Handling.md
new file mode 100644
index 000000000..82993bbcc
--- /dev/null
+++ b/Documentation/markdown/CalculationEngine/FunctionReference/02-01-Date-and-Time-Handling.md
@@ -0,0 +1,123 @@
+# Calculation Engine - Formula Function Reference
+
+## Function Reference
+
+### Handling Date and Time Values
+
+#### Excel functions that return a Date and Time value
+
+Any of the Date and Time functions that return a date value in Excel can return either an Excel timestamp or a PHP timestamp or date object.
+
+It is possible for scripts to change the data type used for returning date values by calling the PHPExcel_Calculation_Functions::setReturnDateType() method:
+
+```php
+PHPExcel_Calculation_Functions::setReturnDateType($returnDateType);
+```
+
+where the following constants can be used for $returnDateType
+
+ - PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC
+ - PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT
+ - PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+
+The method will return a Boolean True on success, False on failure (e.g. if an invalid value is passed in for the return date type).
+
+The PHPExcel_Calculation_Functions::getReturnDateType() method can be used to determine the current value of this setting:
+
+```php
+$returnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
+```
+
+The default is RETURNDATE_PHP_NUMERIC.
+
+##### PHP Timestamps
+
+If RETURNDATE_PHP_NUMERIC is set for the Return Date Type, then any date value returned to the calling script by any access to the Date and Time functions in Excel will be an integer value that represents the number of seconds from the PHP/Unix base date. The PHP/Unix base date (0) is 00:00 UST on 1st January 1970. This value can be positive or negative: so a value of -3600 would be 23:00 hrs on 31st December 1969; while a value of +3600 would be 01:00 hrs on 1st January 1970. This gives PHP a date range of between 14th December 1901 and 19th January 2038.
+
+##### PHP DateTime Objects
+
+If the Return Date Type is set for RETURNDATE_PHP_NUMERIC, then any date value returned to the calling script by any access to the Date and Time functions in Excel will be a PHP date/time object.
+
+##### Excel Timestamps
+
+If RETURNDATE_EXCEL is set for the Return Date Type, then the returned date value by any access to the Date and Time functions in Excel will be a floating point value that represents a number of days from the Excel base date. The Excel base date is determined by which calendar Excel uses: the Windows 1900 or the Mac 1904 calendar. 1st January 1900 is the base date for the Windows 1900 calendar while 1st January 1904 is the base date for the Mac 1904 calendar.
+
+It is possible for scripts to change the calendar used for calculating Excel date values by calling the PHPExcel_Shared_Date::setExcelCalendar() method:
+
+```php
+PHPExcel_Shared_Date::setExcelCalendar($baseDate);
+```
+
+where the following constants can be used for $baseDate
+
+ - PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
+ - PHPExcel_Shared_Date::CALENDAR_MAC_1904
+
+The method will return a Boolean True on success, False on failure (e.g. if an invalid value is passed in).
+
+The PHPExcel_Shared_Date::getExcelCalendar() method can be used to determine the current value of this setting:
+
+```php
+$baseDate = PHPExcel_Shared_Date::getExcelCalendar();
+```
+The default is CALENDAR_WINDOWS_1900.
+
+##### Functions that return a Date/Time Value
+
+ - DATE
+ - DATEVALUE
+ - EDATE
+ - EOMONTH
+ - NOW
+ - TIME
+ - TIMEVALUE
+ - TODAY
+
+#### Excel functions that accept Date and Time values as parameters
+
+Date values passed in as parameters to a function can be an Excel timestamp or a PHP timestamp; or date object; or a string containing a date value (e.g. '1-Jan-2009'). PHPExcel will attempt to identify their type based on the PHP datatype:
+
+An integer numeric value will be treated as a PHP/Unix timestamp. A real (floating point) numeric value will be treated as an Excel date/timestamp. Any PHP DateTime object will be treated as a DateTime object. Any string value (even one containing straight numeric data) will be converted to a date/time object for validation as a date value based on the server locale settings, so passing through an ambiguous value of '07/08/2008' will be treated as 7th August 2008 if your server settings are UK, but as 8th July 2008 if your server settings are US. However, if you pass through a value such as '31/12/2008' that would be considered an error by a US-based server, but which is not ambiguous, then PHPExcel will attempt to correct this to 31st December 2008. If the content of the string doesn’t match any of the formats recognised by the php date/time object implementation of strtotime() (which can handle a wider range of formats than the normal strtotime() function), then the function will return a '#VALUE' error. However, Excel recommends that you should always use date/timestamps for your date functions, and the recommendation for PHPExcel is the same: avoid strings because the result is not predictable.
+
+The same principle applies when data is being written to Excel. Cells containing date actual values (rather than Excel functions that return a date value) are always written as Excel dates, converting where necessary. If a cell formatted as a date contains an integer or date/time object value, then it is converted to an Excel value for writing: if a cell formatted as a date contains a real value, then no conversion is required. Note that string values are written as strings rather than converted to Excel date timestamp values.
+
+##### Functions that expect a Date/Time Value
+
+ - DATEDIF
+ - DAY
+ - DAYS360
+ - EDATE
+ - EOMONTH
+ - HOUR
+ - MINUTE
+ - MONTH
+ - NETWORKDAYS
+ - SECOND
+ - WEEKDAY
+ - WEEKNUM
+ - WORKDAY
+ - YEAR
+ - YEARFRAC
+
+#### Helper Methods
+
+In addition to the setExcelCalendar() and getExcelCalendar() methods, a number of other methods are available in the PHPExcel_Shared_Date class that can help when working with dates:
+
+##### PHPExcel_Shared_Date::ExcelToPHP($excelDate)
+
+Converts a date/time from an Excel date timestamp to return a PHP serialized date/timestamp.
+
+Note that this method does not trap for Excel dates that fall outside of the valid range for a PHP date timestamp.
+
+##### PHPExcel_Shared_Date::ExcelToPHPObject($excelDate)
+
+Converts a date from an Excel date/timestamp to return a PHP DateTime object.
+
+##### PHPExcel_Shared_Date::PHPToExcel($PHPDate)
+
+Converts a PHP serialized date/timestamp or a PHP DateTime object to return an Excel date timestamp.
+
+##### PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0)
+
+Takes year, month and day values (and optional hour, minute and second values) and returns an Excel date timestamp value.
+
diff --git a/Documentation/markdown/CalculationEngine/FunctionReference/02-General-Introduction.md b/Documentation/markdown/CalculationEngine/FunctionReference/02-General-Introduction.md
new file mode 100644
index 000000000..b714d5118
--- /dev/null
+++ b/Documentation/markdown/CalculationEngine/FunctionReference/02-General-Introduction.md
@@ -0,0 +1,36 @@
+# Calculation Engine - Formula Function Reference
+
+## General Introduction
+
+### Function that are not Supported in Excel5
+
+Not all functions are supported by the Excel 5 Writer. Use of these functions within your workbooks will result in an error when trying to write to Excel5.
+
+The following is the list of those functions that are implemented within PHPExcel, but that cannot currently be written to Excel 5.
+
+#### Cube Functions
+
+ Excel Function | Notes
+ --------------------|---------
+ CUBEKPIMEMBER | Not yet Implemented
+ CUBEMEMBER | Not yet Implemented
+ CUBEMEMBERPROPERTY | Not yet Implemented
+ CUBERANKEDMEMBER | Not yet Implemented
+ CUBESET | Not yet Implemented
+ CUBESETCOUNT | Not yet Implemented
+ CUBEVALUE | Not yet Implemented
+
+
+#### Database Functions
+
+ Excel Function | Notes
+ ---------------|---------
+
+
+#### Date and Time Functions
+
+ Excel Function | Notes
+ ---------------|---------
+ EDATE | Not a standard function within Excel 5, but an add-in from the Analysis ToolPak.
+ EOMONTH | Not a standard function within Excel 5, but an add-in from the Analysis ToolPak.
+
diff --git a/Documentation/markdown/CalculationEngine/FunctionReference/03-01-Cube-Functions.md b/Documentation/markdown/CalculationEngine/FunctionReference/03-01-Cube-Functions.md
new file mode 100644
index 000000000..8c946321d
--- /dev/null
+++ b/Documentation/markdown/CalculationEngine/FunctionReference/03-01-Cube-Functions.md
@@ -0,0 +1,34 @@
+# Calculation Engine - Formula Function Reference
+
+## Function Reference
+
+### Cube Functions
+
+#### CUBEKPIMEMBER
+
+Not yet implemented.
+
+#### CUBEMEMBER
+
+Not yet implemented.
+
+#### CUBEMEMBERPROPERTY
+
+Not yet implemented.
+
+#### CUBERANKEDMEMBER
+
+Not yet implemented.
+
+#### CUBESET
+
+Not yet implemented.
+
+#### CUBESETCOUNT
+
+Not yet implemented.
+
+#### CUBEVALUE
+
+Not yet implemented.
+
diff --git a/Documentation/markdown/CalculationEngine/FunctionReference/03-02-Database-Functions.md b/Documentation/markdown/CalculationEngine/FunctionReference/03-02-Database-Functions.md
new file mode 100644
index 000000000..a50e1c853
--- /dev/null
+++ b/Documentation/markdown/CalculationEngine/FunctionReference/03-02-Database-Functions.md
@@ -0,0 +1,618 @@
+# Calculation Engine - Formula Function Reference
+
+## Function Reference
+
+### Database Functions
+
+#### DAVERAGE
+
+The DAVERAGE function returns the average value of the cells in a column of a list or database that match conditions you specify.
+
+##### Syntax
+
+```
+DAVERAGE (database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The average value of the matching cells.
+
+This is the statistical mean.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DAVERAGE(A4:E10,"Yield",A1:B2)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 12
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DCOUNT
+
+The DCOUNT function returns the count of cells that contain a number in a column of a list or database matching conditions that you specify.
+
+##### Syntax
+
+```
+DCOUNT(database, [field], criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The count of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DCOUNT(A4:E10,"Height",A1:B3)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+
+// $retVal = 3
+```
+
+##### Notes
+
+In MS Excel, The field argument is optional. If field is omitted, DCOUNT counts all records in the database that match the criteria. This logic has not yet been implemented in PHPExcel.
+
+#### DCOUNTA
+
+The DCOUNT function returns the count of cells that aren’t blank in a column of a list or database and that match conditions that you specify.
+
+##### Syntax
+
+```
+DCOUNTA(database, [field], criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The count of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DCOUNTA(A4:E10,"Yield",A1:A3)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+
+// $retVal = 5
+```
+
+##### Notes
+
+In MS Excel, The field argument is optional. If field is omitted, DCOUNTA counts all records in the database that match the criteria. This logic has not yet been implemented in PHPExcel.
+
+#### DGET
+
+The DGET function extracts a single value from a column of a list or database that matches conditions that you specify.
+
+##### Syntax
+
+```
+DGET(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**mixed** The value from the selected column of the matching row.
+
+#### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=GET(A4:E10,"Age",A1:F2)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 14
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DMAX
+
+The DMAX function returns the largest number in a column of a list or database that matches conditions you specify.
+
+##### Syntax
+
+```
+DMAX(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The maximum value of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DMAX(A4:E10,"Profit",A1:B2)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 105
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DMIN
+
+The DMIN function returns the smallest number in a column of a list or database that matches conditions you specify.
+
+##### Syntax
+
+```
+DMIN(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The minimum value of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DMIN(A4:E10,"Yield",A1:A3)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 6
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DPRODUCT
+
+The DPRODUCT function multiplies the values in a column of a list or database that match conditions that you specify.
+
+##### Syntax
+
+```
+DPRODUCT(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The product of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DPRODUCT(A4:E10,"Yield",A1:B2)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 140
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DSTDEV
+
+The DSTDEV function estimates the standard deviation of a population based on a sample by using the numbers in a column of a list or database that match conditions that you specify.
+
+##### Syntax
+
+```
+DSTDEV(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The estimated standard deviation of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DSTDEV(A4:E10,"Yield",A1:A3)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 2.97
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DSTDEVP
+
+The DSTDEVP function calculates the standard deviation of a population based on the entire population by using the numbers in a column of a list or database that match conditions that you specify.
+
+##### Syntax
+
+```
+DSTDEVP(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The estimated standard deviation of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DSTDEVP(A4:E10,"Yield",A1:A3)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 2.65
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DSUM
+
+The DSUM function adds the numbers in a column of a list or database that matches conditions you specify.
+
+##### Syntax
+
+```
+DSUM(database, field, criteria)
+```
+
+##### Parameters
+
+**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.
+
+**field** Indicates which column of the database is used in the function.
+
+Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on.
+
+**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 Value
+
+**float** The total value of the matching cells.
+
+##### Examples
+
+```php
+$database = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
+ array( 'Apple', 18, 20, 14, 105.00 ),
+ array( 'Pear', 12, 12, 10, 96.00 ),
+ array( 'Cherry', 13, 14, 9, 105.00 ),
+ array( 'Apple', 14, 15, 10, 75.00 ),
+ array( 'Pear', 9, 8, 8, 76.80 ),
+ array( 'Apple', 8, 9, 6, 45.00 ),
+);
+
+$criteria = array(
+ array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
+ array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
+ array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
+);
+
+$worksheet->fromArray( $criteria, NULL, 'A1' )
+ ->fromArray( $database, NULL, 'A4' );
+
+$worksheet->setCellValue('A12', '=DMIN(A4:E10,"Profit",A1:A2)');
+
+$retVal = $worksheet->getCell('A12')->getCalculatedValue();
+// $retVal = 225
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DVAR
+
+Not yet documented.
+
+#### DVARP
+
+Not yet documented.
+
diff --git a/Documentation/markdown/CalculationEngine/FunctionReference/03-03-Date-and-Time-Functions.md b/Documentation/markdown/CalculationEngine/FunctionReference/03-03-Date-and-Time-Functions.md
new file mode 100644
index 000000000..d0cc56817
--- /dev/null
+++ b/Documentation/markdown/CalculationEngine/FunctionReference/03-03-Date-and-Time-Functions.md
@@ -0,0 +1,1000 @@
+# Calculation Engine - Formula Function Reference
+
+## Function Reference
+
+### Date and Time Functions
+
+Excel provides a number of functions for the manipulation of dates and times, and calculations based on date/time values. it is worth spending some time reading the section titled "Date and Time Values" on passing date parameters and returning date values to understand how PHPExcel reconciles the differences between dates and times in Excel and in PHP.
+
+#### DATE
+
+The DATE function returns an Excel timestamp or a PHP timestamp or date object representing the date that is referenced by the parameters.
+
+##### Syntax
+
+```
+DATE(year, month, day)
+```
+
+##### Parameters
+
+**year** The year number.
+
+If this value is between 0 (zero) and 1899 inclusive (for the Windows 1900 calendar), or between 4 and 1903 inclusive (for the Mac 1904), then PHPExcel adds it to the Calendar base year, so a value of 108 will interpret the year as 2008 when using the Windows 1900 calendar, or 2012 when using the Mac 1904 calendar.
+
+**month** The month number.
+
+If this value is greater than 12, the DATE function adds that number of months to the first month in the year specified. For example, DATE(2008,14,2) returns a value representing February 2, 2009.
+
+If the value of __month__ is less than 1, then that value will be adjusted by -1, and that will then be subtracted from the first month of the year specified. For example, DATE(2008,0,2) returns a value representing December 2, 2007; while DATE(2008,-1,2) returns a value representing November 2, 2007.
+
+**day** The day number.
+
+If this value is greater than the number of days in the month (and year) specified, the DATE function adds that number of days to the first day in the month. For example, DATE(2008,1,35) returns a value representing February 4, 2008.
+
+If the value of __day__ is less than 1, then that value will be adjusted by -1, and that will then be subtracted from the first month of the year specified. For example, DATE(2008,3,0) returns a value representing February 29, 2008; while DATE(2008,3,-2) returns a value representing February 27, 2008.
+
+##### Return Value
+
+**mixed** A date/time stamp that corresponds to the given date.
+
+This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of PHPExcel_Calculation_Functions::getReturnDateType().
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Year')
+ ->setCellValue('A2', 'Month')
+ ->setCellValue('A3', 'Day');
+
+$worksheet->setCellValue('B1', 2008)
+ ->setCellValue('B2', 12)
+ ->setCellValue('B3', 31);
+
+$worksheet->setCellValue('D1', '=DATE(B1,B2,B3)');
+
+$retVal = $worksheet->getCell('D1')->getCalculatedValue();
+// $retVal = 1230681600
+```
+
+```php
+// We're going to be calling the same cell calculation multiple times,
+// and expecting different return values, so disable calculation cacheing
+PHPExcel_Calculation::getInstance()->setCalculationCacheEnabled(FALSE);
+
+$saveFormat = PHPExcel_Calculation_Functions::getReturnDateType();
+
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+);
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATE'),
+ array(2008, 12, 31)
+);
+// $retVal = 39813.0
+
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC
+);
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATE'),
+ array(2008, 12, 31)
+);
+// $retVal = 1230681600
+
+PHPExcel_Calculation_Functions::setReturnDateType($saveFormat);
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### DATEDIF
+
+The DATEDIF function computes the difference between two dates in a variety of different intervals, such number of years, months, or days.
+
+##### Syntax
+
+```
+DATEDIF(date1, date2 [, unit])
+```
+
+##### Parameters
+
+**date1** First Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**date2** Second Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**unit** The interval type to use for the calculation
+
+This is a string, comprising one of the values listed below:
+
+Unit | Meaning | Description
+-----|---------------------------------|--------------------------------
+m | Months | Complete calendar months between the dates.
+d | Days | Number of days between the dates.
+y | Years | Complete calendar years between the dates.
+ym | Months Excluding Years | Complete calendar months between the dates as if they were of the same year.
+yd | Days Excluding Years | Complete calendar days between the dates as if they were of the same year.
+md | Days Excluding Years And Months | Complete calendar days between the dates as if they were of the same month and same year.
+
+The unit value is not case sensitive, and defaults to "d".
+
+##### Return Value
+
+**integer** An integer value that reflects the difference between the two dates.
+
+This could be the number of full days, months or years between the two dates, depending on the interval unit value passed into the function as the third parameter.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Year')
+ ->setCellValue('A2', 'Month')
+ ->setCellValue('A3', 'Day');
+
+$worksheet->setCellValue('B1', 2001)
+ ->setCellValue('C1', 2009)
+ ->setCellValue('B2', 7)
+ ->setCellValue('C2', 12)
+ ->setCellValue('B3', 1)
+ ->setCellValue('C3', 31);
+
+$worksheet->setCellValue('D1', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"d")')
+ ->setCellValue('D2', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"m")')
+ ->setCellValue('D3', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"y")')
+ ->setCellValue('D4', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"ym")')
+ ->setCellValue('D5', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"yd")')
+ ->setCellValue('D6', '=DATEDIF(DATE(B1,B2,B3),DATE(C1,C2,C3),"md")');
+
+$retVal = $worksheet->getCell('D1')->getCalculatedValue();
+// $retVal = 3105
+
+$retVal = $worksheet->getCell('D2')->getCalculatedValue();
+// $retVal = 101
+
+$retVal = $worksheet->getCell('D3')->getCalculatedValue();
+// $retVal = 8
+
+$retVal = $worksheet->getCell('D4')->getCalculatedValue();
+// $retVal = 5
+
+$retVal = $worksheet->getCell('D5')->getCalculatedValue();
+// $retVal = 183
+
+$retVal = $worksheet->getCell('D6')->getCalculatedValue();
+// $retVal = 30
+```
+
+```php
+$date1 = 1193317015; // PHP timestamp for 25-Oct-2007
+$date2 = 1449579415; // PHP timestamp for 8-Dec-2015
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEDIF'),
+ array($date1, $date2, 'd')
+);
+// $retVal = 2966
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEDIF'),
+ array($date1, $date2, 'm')
+);
+// $retVal = 97
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEDIF'),
+ array($date1, $date2, 'y')
+);
+// $retVal = 8
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEDIF'),
+ array($date1, $date2, 'ym')
+);
+// $retVal = 1
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEDIF'),
+ array($date1, $date2, 'yd')
+);
+// $retVal = 44
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEDIF'),
+ array($date1, $date2, 'md')
+);
+// $retVal = 13
+```
+
+##### Notes
+
+If Date1 is later than Date2, DATEDIF will return a #NUM! error.
+
+#### DATEVALUE
+
+The DATEVALUE function returns the date represented by a date formatted as a text string. Use DATEVALUE to convert a date represented by text to a serial number.
+
+##### Syntax
+
+```
+DATEVALUE(dateString)
+```
+
+##### Parameters
+
+**date** Date String.
+
+A string, representing a date value.
+
+##### Return Value
+
+**mixed** A date/time stamp that corresponds to the given date.
+
+This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of PHPExcel_Calculation_Functions::getReturnDateType().
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String');
+ ->setCellValue('A2', '31-Dec-2008')
+ ->setCellValue('A3', '31/12/2008')
+ ->setCellValue('A4', '12-31-2008');
+
+$worksheet->setCellValue('B2', '=DATEVALUE(A2)')
+ ->setCellValue('B3', '=DATEVALUE(A3)')
+ ->setCellValue('B4', '=DATEVALUE(A4)');
+
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+);
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+
+$retVal = $worksheet->getCell('B4')->getCalculatedValue();
+// $retVal = 39813.0 for all cases
+```
+
+```php
+// We're going to be calling the same cell calculation multiple times,
+// and expecting different return values, so disable calculation cacheing
+PHPExcel_Calculation::getInstance()->setCalculationCacheEnabled(FALSE);
+
+$saveFormat = PHPExcel_Calculation_Functions::getReturnDateType();
+
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+);
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEVALUE'),
+ array('31-Dec-2008')
+);
+// $retVal = 39813.0
+
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC
+);
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DATEVALUE'),
+ array('31-Dec-2008')
+);
+// $retVal = 1230681600
+
+PHPExcel_Calculation_Functions::setReturnDateType($saveFormat);
+```
+
+##### Notes
+
+DATEVALUE uses the php date/time object implementation of strtotime() (which can handle a wider range of formats than the normal strtotime() function), and it is also called for any date parameter passed to other date functions (such as DATEDIF) when the parameter value is a string.
+
+__WARNING:-__ PHPExcel accepts a wider range of date formats than MS Excel, so it is entirely possible that Excel will return a #VALUE! error when passed a date string that it can’t interpret, while PHPExcel is able to translate that same string into a correct date value.
+
+Care should be taken in workbooks that use string formatted dates in calculations when writing to Excel5 or Excel2007.
+
+#### DAY
+
+The DAY function returns the day of a date. The day is given as an integer ranging from 1 to 31.
+
+##### Syntax
+
+```
+DAY(datetime)
+```
+
+##### Parameters
+
+**datetime** Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+##### Return Value
+
+**integer** An integer value that reflects the day of the month.
+
+This is an integer ranging from 1 to 31.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String')
+ ->setCellValue('A2', '31-Dec-2008')
+ ->setCellValue('A3', '14-Feb-2008');
+
+$worksheet->setCellValue('B2', '=DAY(A2)')
+ ->setCellValue('B3', '=DAY(A3)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 31
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 14
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DAYOFMONTH'),
+ array('25-Dec-2008')
+);
+// $retVal = 25
+```
+
+##### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::DAYOFMONTH() when the method is called statically.
+
+#### DAYS360
+
+The DAYS360 function computes the difference between two dates based on a 360 day year (12 equal periods of 30 days each) used by some accounting systems.
+
+##### Syntax
+
+```
+DAYS360(date1, date2 [, method])
+```
+
+#### Parameters
+
+**date1** First Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**date2** Second Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**method** A boolean flag (TRUE or FALSE)
+
+This is a flag that determines which method to use in the calculation, based on the values listed below:
+
+ method | Description
+ -------|------------
+ FALSE | U.S. (NASD) method. If the starting date is the last day of a month, it becomes equal to the 30th of the same month. If the ending date is the last day of a month and the starting date is earlier than the 30th of a month, the ending date becomes equal to the 1st of the next month; otherwise the ending date becomes equal to the 30th of the same month.
+ TRUE | European method. Starting dates and ending dates that occur on the 31st of a month become equal to the 30th of the same month.
+
+The method value defaults to FALSE.
+
+##### Return Value
+
+**integer** An integer value that reflects the difference between the two dates.
+
+This is the number of full days between the two dates, based on a 360 day year.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('B1', 'Start Date')
+ ->setCellValue('C1', 'End Date')
+ ->setCellValue('A2', 'Year')
+ ->setCellValue('A3', 'Month')
+ ->setCellValue('A4', 'Day');
+
+$worksheet->setCellValue('B2', 2003)
+ ->setCellValue('B3', 2)
+ ->setCellValue('B4', 3);
+
+$worksheet->setCellValue('C2', 2007)
+ ->setCellValue('C3', 5)
+ ->setCellValue('C4', 31);
+
+$worksheet->setCellValue('E2', '=DAYS360(DATE(B2,B3,B4),DATE(C2,C3,C4))')
+ ->setCellValue('E4', '=DAYS360(DATE(B2,B3,B4),DATE(C2,C3,C4),FALSE)');
+
+$retVal = $worksheet->getCell('E2')->getCalculatedValue();
+// $retVal = 1558
+
+$retVal = $worksheet->getCell('E4')->getCalculatedValue();
+// $retVal = 1557
+```
+
+```php
+$date1 = 37655.0; // Excel timestamp for 25-Oct-2007
+$date2 = 39233.0; // Excel timestamp for 8-Dec-2015
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DAYS360'),
+ array($date1, $date2)
+);
+// $retVal = 1558
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DAYS360'),
+ array($date1, $date2, TRUE)
+);
+// $retVal = 1557
+```
+
+##### Notes
+
+__WARNING:-__ This function does not currently work with the Excel5 Writer when a PHP Boolean is used for the third (optional) parameter (as shown in the example above), and the writer will generate and error. It will work if a numeric 0 or 1 is used for the method parameter; or if the Excel TRUE() and FALSE() functions are used instead.
+
+#### EDATE
+
+The EDATE function returns an Excel timestamp or a PHP timestamp or date object representing the date that is the indicated number of months before or after a specified date (the start_date). Use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue.
+
+##### Syntax
+
+```
+EDATE(baseDate, months)
+```
+
+##### Parameters
+
+**baseDate** Start Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**months** Number of months to add.
+
+An integer value indicating the number of months before or after baseDate. A positive value for months yields a future date; a negative value yields a past date.
+
+##### Return Value
+
+**mixed** A date/time stamp that corresponds to the basedate + months.
+
+This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of PHPExcel_Calculation_Functions::getReturnDateType().
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String')
+ ->setCellValue('A2', '1-Jan-2008')
+ ->setCellValue('A3', '29-Feb-2008');
+
+$worksheet->setCellValue('B2', '=EDATE(A2,5)')
+ ->setCellValue('B3', '=EDATE(A3,-12)');
+
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+);
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 39600.0 (1-Jun-2008)
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 39141.0 (28-Feb-2007)
+```
+
+```php
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+);
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'EDATE'),
+ array('31-Oct-2008',25)
+);
+// $retVal = 40512.0 (30-Nov-2010)
+```
+
+###### Notes
+
+__WARNING:-__ This function is currently not supported by the Excel5 Writer because it is not a standard function within Excel 5, but an add-in from the Analysis ToolPak.
+
+#### EOMONTH
+
+The EOMONTH function returns an Excel timestamp or a PHP timestamp or date object representing the date of the last day of the month that is the indicated number of months before or after a specified date (the start_date). Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
+
+##### Syntax
+
+```
+EOMONTH(baseDate, months)
+```
+
+##### Parameters
+
+**baseDate** Start Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**months** Number of months to add.
+
+An integer value indicating the number of months before or after baseDate. A positive value for months yields a future date; a negative value yields a past date.
+
+##### Return Value
+
+**mixed** A date/time stamp that corresponds to the last day of basedate + months.
+
+This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of PHPExcel_Calculation_Functions::getReturnDateType().
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String')
+ ->setCellValue('A2', '1-Jan-2000')
+ ->setCellValue('A3', '14-Feb-2009');
+
+$worksheet->setCellValue('B2', '=EOMONTH(A2,5)')
+ ->setCellValue('B3', '=EOMONTH(A3,-12)');
+
+PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 39629.0 (30-Jun-2008)
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 39507.0 (29-Feb-2008)
+```
+
+```php
+PHPExcel_Calculation_Functions::setReturnDateType(
+ PHPExcel_Calculation_Functions::RETURNDATE_EXCEL
+);
+
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'EOMONTH'),
+ array('31-Oct-2008',13)
+);
+// $retVal = 40147.0 (30-Nov-2010)
+```
+
+##### Notes
+
+__WARNING:-__ This function is currently not supported by the Excel5 Writer because it is not a standard function within Excel 5, but an add-in from the Analysis ToolPak.
+
+#### HOUR
+
+The HOUR function returns the hour of a time value. The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
+
+##### Syntax
+
+```
+HOUR(datetime)
+```
+
+##### Parameters
+
+**datetime** Time.
+
+An Excel date/time value, PHP date timestamp, PHP date object, or a date/time represented as a string.
+
+##### Return Value
+
+**integer** An integer value that reflects the hour of the day.
+
+This is an integer ranging from 0 to 23.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Time String')
+ ->setCellValue('A2', '31-Dec-2008 17:30')
+ ->setCellValue('A3', '14-Feb-2008 4:20 AM')
+ ->setCellValue('A4', '14-Feb-2008 4:20 PM');
+
+$worksheet->setCellValue('B2', '=HOUR(A2)')
+ ->setCellValue('B3', '=HOUR(A3)')
+ ->setCellValue('B4', '=HOUR(A4)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 17
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 4
+
+$retVal = $worksheet->getCell('B4')->getCalculatedValue();
+// $retVal = 16
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'HOUROFDAY'),
+ array('09:30')
+);
+// $retVal = 9
+```
+
+##### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::HOUROFDAY() when the method is called statically.
+
+#### MINUTE
+
+The MINUTE function returns the minutes of a time value. The minute is given as an integer, ranging from 0 to 59.
+
+##### Syntax
+
+```
+MINUTE(datetime)
+```
+
+##### Parameters
+
+**datetime** Time.
+
+An Excel date/time value, PHP date timestamp, PHP date object, or a date/time represented as a string.
+
+##### Return Value
+
+**integer** An integer value that reflects the minutes within the hour.
+
+This is an integer ranging from 0 to 59.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Time String')
+ ->setCellValue('A2', '31-Dec-2008 17:30')
+ ->setCellValue('A3', '14-Feb-2008 4:20 AM')
+ ->setCellValue('A4', '14-Feb-2008 4:45 PM');
+
+$worksheet->setCellValue('B2', '=MINUTE(A2)')
+ ->setCellValue('B3', '=MINUTE(A3)')
+ ->setCellValue('B4', '=MINUTE(A4)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 30
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 20
+
+$retVal = $worksheet->getCell('B4')->getCalculatedValue();
+// $retVal = 45
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'MINUTEOFHOUR'),
+ array('09:30')
+);
+// $retVal = 30
+```
+
+##### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::MINUTEOFHOUR() when the method is called statically.
+
+#### MONTH
+
+The MONTH function returns the month of a date. The month is given as an integer ranging from 1 to 12.
+
+##### Syntax
+
+```
+MONTH(datetime)
+```
+
+##### Parameters
+
+**datetime** Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+##### Return Value
+
+**integer** An integer value that reflects the month of the year.
+
+This is an integer ranging from 1 to 12.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String');
+$worksheet->setCellValue('A2', '31-Dec-2008');
+$worksheet->setCellValue('A3', '14-Feb-2008');
+
+$worksheet->setCellValue('B2', '=MONTH(A2)');
+$worksheet->setCellValue('B3', '=MONTH(A3)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 12
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 2
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'MONTHOFYEAR'),
+ array('14-July-2008')
+);
+// $retVal = 7
+```
+
+#### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::MONTHOFYEAR() when the method is called statically.
+
+#### NETWORKDAYS
+
+The NETWORKDAYS function returns the number of whole working days between a *start date* and an *end date*. Working days exclude weekends and any dates identified in *holidays*. Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days worked during a specific term.
+
+##### Syntax
+
+```
+NETWORKDAYS(startDate, endDate [, holidays])
+```
+
+##### Parameters
+
+**startDate** Start Date of the period.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**endDate** End Date of the period.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**holidays** Optional array of Holiday dates.
+
+An optional range of one or more dates to exclude from the working calendar, such as state and federal holidays and floating holidays.
+
+The list can be either a range of cells that contains the dates or an array constant of Excel date values, PHP date timestamps, PHP date objects, or dates represented as strings.
+
+##### Return Value
+
+**integer** Number of working days.
+
+The number of working days between startDate and endDate.
+
+##### Examples
+
+```php
+```
+
+```php
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+#### NOW
+
+The NOW function returns the current date and time.
+
+##### Syntax
+
+```
+NOW()
+```
+
+##### Parameters
+
+There are now parameters for the NOW() function.
+
+##### Return Value
+
+**mixed** A date/time stamp that corresponds to the current date and time.
+
+This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of PHPExcel_Calculation_Functions::getReturnDateType().
+
+##### Examples
+
+```php
+```
+
+```php
+```
+
+##### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::DATETIMENOW() when the method is called statically.
+
+#### SECOND
+
+The SECOND function returns the seconds of a time value. The second is given as an integer, ranging from 0 to 59.
+
+##### Syntax
+
+```
+SECOND(datetime)
+```
+
+##### Parameters
+
+**datetime** Time.
+
+An Excel date/time value, PHP date timestamp, PHP date object, or a date/time represented as a string.
+
+##### Return Value
+
+**integer** An integer value that reflects the seconds within the minute.
+
+This is an integer ranging from 0 to 59.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Time String')
+ ->setCellValue('A2', '31-Dec-2008 17:30:20')
+ ->setCellValue('A3', '14-Feb-2008 4:20 AM')
+ ->setCellValue('A4', '14-Feb-2008 4:45:59 PM');
+
+$worksheet->setCellValue('B2', '=SECOND(A2)')
+ ->setCellValue('B3', '=SECOND(A3)');
+ ->setCellValue('B4', '=SECOND(A4)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 20
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 0
+
+$retVal = $worksheet->getCell('B4')->getCalculatedValue();
+// $retVal = 59
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'SECONDOFMINUTE'),
+ array('09:30:17')
+);
+// $retVal = 17
+```
+
+##### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::SECONDOFMINUTE() when the method is called statically.
+
+#### TIME
+
+Not yet documented.
+
+#### TIMEVALUE
+
+Not yet documented.
+
+#### TODAY
+
+Not yet documented.
+
+#### WEEKDAY
+
+The WEEKDAY function returns the day of the week for a given date. The day is given as an integer ranging from 1 to 7, although this can be modified to return a value between 0 and 6.
+
+##### Syntax
+
+```
+WEEKDAY(datetime [, method])
+```
+
+##### Parameters
+
+**datetime** Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+**method** An integer flag (values 0, 1 or 2)
+
+This is a flag that determines which method to use in the calculation, based on the values listed below:
+
+ method | Description
+ :-----:|------------------------------------------
+ 0 | Returns 1 (Sunday) through 7 (Saturday).
+ 1 | Returns 1 (Monday) through 7 (Sunday).
+ 2 | Returns 0 (Monday) through 6 (Sunday).
+
+The method value defaults to 1.
+
+##### Return Value
+
+**integer** An integer value that reflects the day of the week.
+
+This is an integer ranging from 1 to 7, or 0 to 6, depending on the value of method.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String')
+ ->setCellValue('A2', '31-Dec-2008')
+ ->setCellValue('A3', '14-Feb-2008');
+
+$worksheet->setCellValue('B2', '=WEEKDAY(A2)')
+ ->setCellValue('B3', '=WEEKDAY(A3,0)')
+ ->setCellValue('B4', '=WEEKDAY(A3,2)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 12
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 2
+
+$retVal = $worksheet->getCell('B4')->getCalculatedValue();
+// $retVal = 2
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'DAYOFWEEK'),
+ array('14-July-2008')
+);
+// $retVal = 7
+```
+
+##### Notes
+
+Note that the PHPExcel function is PHPExcel_Calculation_Functions::DAYOFWEEK() when the method is called statically.
+
+#### WEEKNUM
+
+Not yet documented.
+
+#### WORKDAY
+
+Not yet documented.
+
+#### YEAR
+
+The YEAR function returns the year of a date.
+
+##### Syntax
+
+```
+YEAR(datetime)
+```
+
+##### Parameters
+
+**datetime** Date.
+
+An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string.
+
+##### Return Value
+
+**integer** An integer value that reflects the month of the year.
+
+This is an integer year value.
+
+##### Examples
+
+```php
+$worksheet->setCellValue('A1', 'Date String')
+ ->setCellValue('A2', '17-Jul-1982')
+ ->setCellValue('A3', '16-Apr-2009');
+
+$worksheet->setCellValue('B2', '=YEAR(A2)')
+ ->setCellValue('B3', '=YEAR(A3)');
+
+$retVal = $worksheet->getCell('B2')->getCalculatedValue();
+// $retVal = 1982
+
+$retVal = $worksheet->getCell('B3')->getCalculatedValue();
+// $retVal = 2009
+```
+
+```php
+$retVal = call_user_func_array(
+ array('PHPExcel_Calculation_Functions', 'YEAR'),
+ array('14-July-2001')
+);
+// $retVal = 2001
+```
+
+##### Notes
+
+There are no additional notes on this function
+
+### YEARFRAC
+
+Not yet documented.
+
diff --git a/Documentation/markdown/Features/Autofilters/01-Autofilters.md b/Documentation/markdown/Features/Autofilters/01-Autofilters.md
new file mode 100644
index 000000000..c2fbd2fa8
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/01-Autofilters.md
@@ -0,0 +1,19 @@
+# PHPExcel AutoFilter Reference
+
+
+## AutoFilters
+
+Each worksheet in an Excel Workbook can contain a single autoFilter range. Filtered data displays only the rows that meet criteria that you specify and hides rows that you do not want displayed. You can filter by more than one column: filters are additive, which means that each additional filter is based on the current filter and further reduces the subset of data.
+
+
+
+When an AutoFilter is applied to a range of cells, the first row in an autofilter range will be the heading row, which displays the autoFilter dropdown icons. It is not part of the actual autoFiltered data. All subsequent rows are the autoFiltered data. So an AutoFilter range should always contain the heading row and one or more data rows (one data row is pretty meaningless), but PHPExcel won't actually stop you specifying a meaningless range: it's up to you as the developer to avoid such errors.
+
+To determine if a filter is applied, note the icon in the column heading. A drop-down arrow () means that filtering is enabled but not applied. In MS Excel, when you hover over the heading of a column with filtering enabled but not applied, a screen tip displays the cell text for the first row in that column, and the message "(Showing All)".
+
+
+
+
+A Filter button () means that a filter is applied. When you hover over the heading of a filtered column, a screen tip displays the filter that has been applied to that column, such as "Equals a red cell color" or "Larger than 150".
+
+
diff --git a/Documentation/markdown/Features/Autofilters/02-Setting-an-Autofilter.md b/Documentation/markdown/Features/Autofilters/02-Setting-an-Autofilter.md
new file mode 100644
index 000000000..49c8fa4c1
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/02-Setting-an-Autofilter.md
@@ -0,0 +1,24 @@
+# PHPExcel AutoFilter Reference
+
+
+## Setting an AutoFilter area on a worksheet
+
+To set an autoFilter on a range of cells.
+
+```php
+$objPHPExcel->getActiveSheet()->setAutoFilter('A1:E20');
+```
+
+The first row in an autofilter range will be the heading row, which displays the autoFilter dropdown icons. It is not part of the actual autoFiltered data. All subsequent rows are the autoFiltered data. So an AutoFilter range should always contain the heading row and one or more data rows (one data row is pretty meaningless, but PHPExcel won't actually stop you specifying a meaningless range: it's up to you as the developer to avoid such errors.
+
+If you want to set the whole worksheet as an autofilter region
+
+```php
+$objPHPExcel->getActiveSheet()->setAutoFilter(
+ $objPHPExcel->getActiveSheet()
+ ->calculateWorksheetDimension()
+);
+```
+
+This enables filtering, but does not actually apply any filters.
+
diff --git a/Documentation/markdown/Features/Autofilters/03-Autofilter-Expressions.md b/Documentation/markdown/Features/Autofilters/03-Autofilter-Expressions.md
new file mode 100644
index 000000000..fd6590175
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/03-Autofilter-Expressions.md
@@ -0,0 +1,27 @@
+# PHPExcel AutoFilter Reference
+
+
+## Autofilter Expressions
+
+PHPEXcel 1.7.8 introduced the ability to actually create, read and write filter expressions; initially only for Excel2007 files, but later releases will extend this to other formats.
+
+To apply a filter expression to an autoFilter range, you first need to identify which column you're going to be applying this filter to.
+
+```php
+$autoFilter = $objPHPExcel->getActiveSheet()->getAutoFilter();
+$columnFilter = $autoFilter->getColumn('C');
+```
+
+This returns an autoFilter column object, and you can then apply filter expressions to that column.
+
+There are a number of different types of autofilter expressions. The most commonly used are:
+
+ - Simple Filters
+ - DateGroup Filters
+ - Custom filters
+ - Dynamic Filters
+ - Top Ten Filters
+
+These different types are mutually exclusive within any single column. You should not mix the different types of filter in the same column. PHPExcel will not actively prevent you from doing this, but the results are unpredictable.
+
+Other filter expression types (such as cell colour filters) are not yet supported.
diff --git a/Documentation/markdown/Features/Autofilters/04-01-Autofilter-Expressions-Simple.md b/Documentation/markdown/Features/Autofilters/04-01-Autofilter-Expressions-Simple.md
new file mode 100644
index 000000000..ca229b892
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/04-01-Autofilter-Expressions-Simple.md
@@ -0,0 +1,52 @@
+# PHPExcel AutoFilter Reference
+
+
+## Autofilter Expressions
+
+### Simple filters
+
+In MS Excel, Simple Filters are a dropdown list of all values used in that column, and the user can select which ones they want to display and which ones they want to hide by ticking and unticking the checkboxes alongside each option. When the filter is applied, rows containing the checked entries will be displayed, rows that don't contain those values will be hidden.
+
+
+
+To create a filter expression, we need to start by identifying the filter type. In this case, we're just going to specify that this filter is a standard filter.
+
+```php
+$columnFilter->setFilterType(
+ PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER
+);
+```
+
+Now we've identified the filter type, we can create a filter rule and set the filter values:
+
+When creating a simple filter in PHPExcel, you only need to specify the values for "checked" columns: you do this by creating a filter rule for each value.
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ 'France'
+ );
+
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ 'Germany'
+ );
+```
+
+This creates two filter rules: the column will be filtered by values that match “France” OR “Germany”. For Simple Filters, you can create as many rules as you want
+
+Simple filters are always a comparison match of EQUALS, and multiple standard filters are always treated as being joined by an OR condition.
+
+#### Matching Blanks
+
+If you want to create a filter to select blank cells, you would use:
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ ''
+ );
+```
diff --git a/Documentation/markdown/Features/Autofilters/04-02-Autofilter-Expressions-Dategroup.md b/Documentation/markdown/Features/Autofilters/04-02-Autofilter-Expressions-Dategroup.md
new file mode 100644
index 000000000..2b9015ff4
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/04-02-Autofilter-Expressions-Dategroup.md
@@ -0,0 +1,48 @@
+# PHPExcel AutoFilter Reference
+
+
+## Autofilter Expressions
+
+### DateGroup Filters
+
+In MS Excel, DateGroup filters provide a series of dropdown filter selectors for date values, so you can specify entire years, or months within a year, or individual days within each month.
+
+
+
+DateGroup filters are still applied as a Standard Filter type.
+
+```php
+$columnFilter->setFilterType(
+ PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER
+);
+```
+
+Creating a dateGroup filter in PHPExcel, you specify the values for "checked" columns as an associative array of year. month, day, hour minute and second. To select a year and month, you need to create a DateGroup rule identifying the selected year and month:
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ array(
+ 'year' => 2012,
+ 'month' => 1
+ )
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP
+ );
+```
+
+The key values for the associative array are:
+
+ - year
+ - month
+ - day
+ - hour
+ - minute
+ - second
+
+Like Standard filters, DateGroup filters are always a match of EQUALS, and multiple standard filters are always treated as being joined by an OR condition.
+
+Note that we alse specify a ruleType: to differentiate this from a standard filter, we explicitly set the Rule's Type to AUTOFILTER_RULETYPE_DATEGROUP. As with standard filters, we can create any number of DateGroup Filters.
+
diff --git a/Documentation/markdown/Features/Autofilters/04-03-Autofilter-Expressions-Custom.md b/Documentation/markdown/Features/Autofilters/04-03-Autofilter-Expressions-Custom.md
new file mode 100644
index 000000000..9ca3bd49d
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/04-03-Autofilter-Expressions-Custom.md
@@ -0,0 +1,84 @@
+# PHPExcel AutoFilter Reference
+
+
+## Autofilter Expressions
+
+### Custom filters
+
+In MS Excel, Custom filters allow us to select more complex conditions using an operator as well as a value. Typical examples might be values that fall within a range (e.g. between -20 and +20), or text values with wildcards (e.g. beginning with the letter U). To handle this, they
+
+
+
+
+
+Custom filters are limited to 2 rules, and these can be joined using either an AND or an OR.
+
+We start by specifying a Filter type, this time a CUSTOMFILTER.
+
+```php
+$columnFilter->setFilterType(
+ PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER
+);
+```
+
+And then define our rules.
+
+The following shows a simple wildcard filter to show all column entries beginning with the letter 'U'.
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ 'U*'
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
+ );
+```
+
+MS Excel uses \* as a wildcard to match any number of characters, and ? as a wildcard to match a single character. 'U\*' equates to "begins with a 'U'"; '\*U' equates to "ends with a 'U'"; and '\*U\*' equates to "contains a 'U'"
+
+If you want to match explicitly against a \* or a ? character, you can escape it with a tilde (~), so ?~\*\* would explicitly match for a \* character as the second character in the cell value, followed by any number of other characters. The only other character that needs escaping is the ~ itself.
+
+To create a "between" condition, we need to define two rules:
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
+ -20
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
+ );
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL,
+ 20
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
+ );
+```
+
+We also set the rule type to CUSTOMFILTER.
+
+This defined two rules, filtering numbers that are >= -20 OR <= 20, so we also need to modify the join condition to reflect AND rather than OR.
+
+```php
+$columnFilter->setAndOr(
+ PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_ANDOR_AND
+);
+```
+
+The valid set of operators for Custom Filters are defined in the PHPExcel_Worksheet_AutoFilter_Column_Rule class, and comprise:
+
+ Operator Constant | Value |
+ ------------------------------------------|----------------------|
+ AUTOFILTER_COLUMN_RULE_EQUAL | 'equal' |
+ AUTOFILTER_COLUMN_RULE_NOTEQUAL | 'notEqual' |
+ AUTOFILTER_COLUMN_RULE_GREATERTHAN | 'greaterThan' |
+ AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL | 'greaterThanOrEqual' |
+ AUTOFILTER_COLUMN_RULE_LESSTHAN | 'lessThan' |
+ AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL | 'lessThanOrEqual' |
+
diff --git a/Documentation/markdown/Features/Autofilters/04-04-Autofilter-Expressions-Dynamic.md b/Documentation/markdown/Features/Autofilters/04-04-Autofilter-Expressions-Dynamic.md
new file mode 100644
index 000000000..f285e573e
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/04-04-Autofilter-Expressions-Dynamic.md
@@ -0,0 +1,88 @@
+# PHPExcel AutoFilter Reference
+
+
+## Autofilter Expressions
+
+### Dynamic Filters
+
+Dynamic Filters are based on a dynamic comparison condition, where the value we're comparing against the cell values is variable, such as 'today'; or when we're testing against an aggregate of the cell data (e.g. 'aboveAverage'). Only a single dynamic filter can be applied to a column at a time.
+
+
+
+Again, we start by specifying a Filter type, this time a DYNAMICFILTER.
+
+```php
+$columnFilter->setFilterType(
+ PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER
+);
+```
+
+When defining the rule for a dynamic filter, we don't define a value (we can simply set that to NULL) but we do specify the dynamic filter category.
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ NULL,
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER
+ );
+```
+
+We also set the rule type to DYNAMICFILTER.
+
+The valid set of dynamic filter categories is defined in the PHPExcel_Worksheet_AutoFilter_Column_Rule class, and comprises:
+
+ Operator Constant | Value |
+ -----------------------------------------|----------------|
+ AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY | 'yesterday' |
+ AUTOFILTER_RULETYPE_DYNAMIC_TODAY | 'today' |
+ AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW | 'tomorrow' |
+ AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE | 'yearToDate' |
+ AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR | 'thisYear' |
+ AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER | 'thisQuarter' |
+ AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH | 'thisMonth' |
+ AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK | 'thisWeek' |
+ AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR | 'lastYear' |
+ AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER | 'lastQuarter' |
+ AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH | 'lastMonth' |
+ AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK | 'lastWeek' |
+ AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR | 'nextYear' |
+ AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER | 'nextQuarter' |
+ AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH | 'nextMonth' |
+ AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK | 'nextWeek' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 | 'M1' |
+ AUTOFILTER_RULETYPE_DYNAMIC_JANUARY | 'M1' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 | 'M2' |
+ AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY | 'M2' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 | 'M3' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MARCH | 'M3' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 | 'M4' |
+ AUTOFILTER_RULETYPE_DYNAMIC_APRIL | 'M4' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 | 'M5' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MAY | 'M5' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 | 'M6' |
+ AUTOFILTER_RULETYPE_DYNAMIC_JUNE | 'M6' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 | 'M7' |
+ AUTOFILTER_RULETYPE_DYNAMIC_JULY | 'M7' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 | 'M8' |
+ AUTOFILTER_RULETYPE_DYNAMIC_AUGUST | 'M8' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 | 'M9' |
+ AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER | 'M9' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 | 'M10' |
+ AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER | 'M10' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 | 'M11' |
+ AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER | 'M11' |
+ AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 | 'M12' |
+ AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER | 'M12' |
+ AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 | 'Q1' |
+ AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 | 'Q2' |
+ AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 | 'Q3' |
+ AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 | 'Q4' |
+ AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE | 'aboveAverage' |
+ AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE | 'belowAverage' |
+
+We can only apply a single Dynamic Filter rule to a column at a time.
+
diff --git a/Documentation/markdown/Features/Autofilters/04-05-Autofilter-Expressions-Topten.md b/Documentation/markdown/Features/Autofilters/04-05-Autofilter-Expressions-Topten.md
new file mode 100644
index 000000000..ff36b0a8a
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/04-05-Autofilter-Expressions-Topten.md
@@ -0,0 +1,69 @@
+# PHPExcel AutoFilter Reference
+
+
+## Autofilter Expressions
+
+### Top Ten Filters
+
+Top Ten Filters are similar to Dynamic Filters in that they are based on a summarisation of the actual data values in the cells. However, unlike Dynamic Filters where you can only select a single option, Top Ten Filters allow you to select based on a number of criteria:
+
+
+
+
+
+You can identify whether you want the top (highest) or bottom (lowest) values.You can identify how many values you wish to select in the filterYou can identify whether this should be a percentage or a number of items.
+
+Like Dynamic Filters, only a single Top Ten filter can be applied to a column at a time.
+
+We start by specifying a Filter type, this time a DYNAMICFILTER.
+
+```php
+$columnFilter->setFilterType(
+ PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER
+);
+```
+
+Then we create the rule:
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT,
+ 5,
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER
+ );
+```
+
+This will filter the Top 5 percent of values in the column.
+
+To specify the lowest (bottom 2 values), we would specify a rule of:
+
+```php
+$columnFilter->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE,
+ 5,
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
+ )
+ ->setRuleType(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER
+ );
+```
+
+The option values for TopTen Filters top/bottom value/percent are all defined in the PHPExcel_Worksheet_AutoFilter_Column_Rule class, and comprise:
+
+ Operator Constant | Value |
+ ---------------------------------------|-------------|
+ AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE | 'byValue' |
+ AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT | 'byPercent' |
+
+and
+
+ Operator Constant | Value |
+ -------------------------------------|----------|
+ AUTOFILTER_COLUMN_RULE_TOPTEN_TOP | 'top' |
+ AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM | 'bottom' |
+
diff --git a/Documentation/markdown/Features/Autofilters/05-Executing-Autofilters.md b/Documentation/markdown/Features/Autofilters/05-Executing-Autofilters.md
new file mode 100644
index 000000000..852e1f41f
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/05-Executing-Autofilters.md
@@ -0,0 +1,42 @@
+# PHPExcel AutoFilter Reference
+
+
+## Executing an AutoFilter
+
+When an autofilter is applied in MS Excel, it sets the row hidden/visible flags for each row of the autofilter area based on the selected criteria, so that only those rows that match the filter criteria are displayed.
+
+PHPExcel will not execute the equivalent function automatically when you set or change a filter expression, but only when the file is saved.
+
+### Applying the Filter
+
+If you wish to execute your filter from within a script, you need to do this manually. You can do this using the autofilters showHideRows() method.
+
+```php
+$autoFilter = $objPHPExcel->getActiveSheet()->getAutoFilter();
+$autoFilter->showHideRows();
+```
+
+This will set all rows that match the filter criteria to visible, while hiding all other rows within the autofilter area.
+
+### Displaying Filtered Rows
+
+Simply looping through the rows in an autofilter area will still access ever row, whether it matches the filter criteria or not. To selectively access only the filtered rows, you need to test each row’s visibility settings.
+
+```php
+foreach ($objPHPExcel->getActiveSheet()->getRowIterator() as $row) {
+ if ($objPHPExcel->getActiveSheet()
+ ->getRowDimension($row->getRowIndex())->getVisible()) {
+ echo ' Row number - ' , $row->getRowIndex() , ' ';
+ echo $objPHPExcel->getActiveSheet()
+ ->getCell(
+ 'C'.$row->getRowIndex()
+ )
+ ->getValue(), ' ';
+ echo $objPHPExcel->getActiveSheet()
+ ->getCell(
+ 'D'.$row->getRowIndex()
+ )->getFormattedValue(), ' ';
+ echo EOL;
+ }
+}
+```
diff --git a/Documentation/markdown/Features/Autofilters/06-Autofilter-Sorting.md b/Documentation/markdown/Features/Autofilters/06-Autofilter-Sorting.md
new file mode 100644
index 000000000..23133b8f4
--- /dev/null
+++ b/Documentation/markdown/Features/Autofilters/06-Autofilter-Sorting.md
@@ -0,0 +1,7 @@
+# PHPExcel AutoFilter Reference
+
+
+## AutoFilter Sorting
+
+In MS Excel, Autofiltering also allows the rows to be sorted. This feature is ***not*** supported by PHPExcel.
+
diff --git a/Documentation/markdown/Features/Autofilters/images/01-01-autofilter.png b/Documentation/markdown/Features/Autofilters/images/01-01-autofilter.png
new file mode 100644
index 000000000..8b5c4fad6
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/01-01-autofilter.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/01-02-autofilter.png b/Documentation/markdown/Features/Autofilters/images/01-02-autofilter.png
new file mode 100644
index 000000000..a2d6c9b9e
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/01-02-autofilter.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/01-03-filter-icon-1.png b/Documentation/markdown/Features/Autofilters/images/01-03-filter-icon-1.png
new file mode 100644
index 000000000..e5a7e7dc0
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/01-03-filter-icon-1.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/01-03-filter-icon-2.png b/Documentation/markdown/Features/Autofilters/images/01-03-filter-icon-2.png
new file mode 100644
index 000000000..1567245f3
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/01-03-filter-icon-2.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/01-04-autofilter.png b/Documentation/markdown/Features/Autofilters/images/01-04-autofilter.png
new file mode 100644
index 000000000..b88f4c4fb
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/01-04-autofilter.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-01-simple-autofilter.png b/Documentation/markdown/Features/Autofilters/images/04-01-simple-autofilter.png
new file mode 100644
index 000000000..5dcc6a47c
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-01-simple-autofilter.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-02-dategroup-autofilter.png b/Documentation/markdown/Features/Autofilters/images/04-02-dategroup-autofilter.png
new file mode 100644
index 000000000..da1f089be
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-02-dategroup-autofilter.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-03-custom-autofilter-1.png b/Documentation/markdown/Features/Autofilters/images/04-03-custom-autofilter-1.png
new file mode 100644
index 000000000..0098d98a4
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-03-custom-autofilter-1.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-03-custom-autofilter-2.png b/Documentation/markdown/Features/Autofilters/images/04-03-custom-autofilter-2.png
new file mode 100644
index 000000000..96ff2cf0f
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-03-custom-autofilter-2.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-04-dynamic-autofilter.png b/Documentation/markdown/Features/Autofilters/images/04-04-dynamic-autofilter.png
new file mode 100644
index 000000000..6cb905d97
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-04-dynamic-autofilter.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-05-topten-autofilter-1.png b/Documentation/markdown/Features/Autofilters/images/04-05-topten-autofilter-1.png
new file mode 100644
index 000000000..207e64575
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-05-topten-autofilter-1.png differ
diff --git a/Documentation/markdown/Features/Autofilters/images/04-05-topten-autofilter-2.png b/Documentation/markdown/Features/Autofilters/images/04-05-topten-autofilter-2.png
new file mode 100644
index 000000000..4db512521
Binary files /dev/null and b/Documentation/markdown/Features/Autofilters/images/04-05-topten-autofilter-2.png differ
diff --git a/Documentation/markdown/Functions/FunctionListByCategory.md b/Documentation/markdown/Functions/FunctionListByCategory.md
new file mode 100644
index 000000000..4ceb1e476
--- /dev/null
+++ b/Documentation/markdown/Functions/FunctionListByCategory.md
@@ -0,0 +1,411 @@
+## CATEGORY_CUBE
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ CUBEKPIMEMBER | **\*\*\* Not yet Implemented**
+ CUBEMEMBER | **\*\*\* Not yet Implemented**
+ CUBEMEMBERPROPERTY | **\*\*\* Not yet Implemented**
+ CUBERANKEDMEMBER | **\*\*\* Not yet Implemented**
+ CUBESET | **\*\*\* Not yet Implemented**
+ CUBESETCOUNT | **\*\*\* Not yet Implemented**
+ CUBEVALUE | **\*\*\* Not yet Implemented**
+
+## CATEGORY_DATABASE
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ DAVERAGE | PHPExcel_Calculation_Database::DAVERAGE
+ DCOUNT | PHPExcel_Calculation_Database::DCOUNT
+ DCOUNTA | PHPExcel_Calculation_Database::DCOUNTA
+ DGET | PHPExcel_Calculation_Database::DGET
+ DMAX | PHPExcel_Calculation_Database::DMAX
+ DMIN | PHPExcel_Calculation_Database::DMIN
+ DPRODUCT | PHPExcel_Calculation_Database::DPRODUCT
+ DSTDEV | PHPExcel_Calculation_Database::DSTDEV
+ DSTDEVP | PHPExcel_Calculation_Database::DSTDEVP
+ DSUM | PHPExcel_Calculation_Database::DSUM
+ DVAR | PHPExcel_Calculation_Database::DVAR
+ DVARP | PHPExcel_Calculation_Database::DVARP
+
+## CATEGORY_DATE_AND_TIME
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ DATE | PHPExcel_Calculation_DateTime::DATE
+ DATEDIF | PHPExcel_Calculation_DateTime::DATEDIF
+ DATEVALUE | PHPExcel_Calculation_DateTime::DATEVALUE
+ DAY | PHPExcel_Calculation_DateTime::DAYOFMONTH
+ DAYS360 | PHPExcel_Calculation_DateTime::DAYS360
+ EDATE | PHPExcel_Calculation_DateTime::EDATE
+ EOMONTH | PHPExcel_Calculation_DateTime::EOMONTH
+ HOUR | PHPExcel_Calculation_DateTime::HOUROFDAY
+ MINUTE | PHPExcel_Calculation_DateTime::MINUTEOFHOUR
+ MONTH | PHPExcel_Calculation_DateTime::MONTHOFYEAR
+ NETWORKDAYS | PHPExcel_Calculation_DateTime::NETWORKDAYS
+ NOW | PHPExcel_Calculation_DateTime::DATETIMENOW
+ SECOND | PHPExcel_Calculation_DateTime::SECONDOFMINUTE
+ TIME | PHPExcel_Calculation_DateTime::TIME
+ TIMEVALUE | PHPExcel_Calculation_DateTime::TIMEVALUE
+ TODAY | PHPExcel_Calculation_DateTime::DATENOW
+ WEEKDAY | PHPExcel_Calculation_DateTime::DAYOFWEEK
+ WEEKNUM | PHPExcel_Calculation_DateTime::WEEKOFYEAR
+ WORKDAY | PHPExcel_Calculation_DateTime::WORKDAY
+ YEAR | PHPExcel_Calculation_DateTime::YEAR
+ YEARFRAC | PHPExcel_Calculation_DateTime::YEARFRAC
+
+## CATEGORY_ENGINEERING
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ BESSELI | PHPExcel_Calculation_Engineering::BESSELI
+ BESSELJ | PHPExcel_Calculation_Engineering::BESSELJ
+ BESSELK | PHPExcel_Calculation_Engineering::BESSELK
+ BESSELY | PHPExcel_Calculation_Engineering::BESSELY
+ BIN2DEC | PHPExcel_Calculation_Engineering::BINTODEC
+ BIN2HEX | PHPExcel_Calculation_Engineering::BINTOHEX
+ BIN2OCT | PHPExcel_Calculation_Engineering::BINTOOCT
+ COMPLEX | PHPExcel_Calculation_Engineering::COMPLEX
+ CONVERT | PHPExcel_Calculation_Engineering::CONVERTUOM
+ DEC2BIN | PHPExcel_Calculation_Engineering::DECTOBIN
+ DEC2HEX | PHPExcel_Calculation_Engineering::DECTOHEX
+ DEC2OCT | PHPExcel_Calculation_Engineering::DECTOOCT
+ DELTA | PHPExcel_Calculation_Engineering::DELTA
+ ERF | PHPExcel_Calculation_Engineering::ERF
+ ERFC | PHPExcel_Calculation_Engineering::ERFC
+ GESTEP | PHPExcel_Calculation_Engineering::GESTEP
+ HEX2BIN | PHPExcel_Calculation_Engineering::HEXTOBIN
+ HEX2DEC | PHPExcel_Calculation_Engineering::HEXTODEC
+ HEX2OCT | PHPExcel_Calculation_Engineering::HEXTOOCT
+ IMABS | PHPExcel_Calculation_Engineering::IMABS
+ IMAGINARY | PHPExcel_Calculation_Engineering::IMAGINARY
+ IMARGUMENT | PHPExcel_Calculation_Engineering::IMARGUMENT
+ IMCONJUGATE | PHPExcel_Calculation_Engineering::IMCONJUGATE
+ IMCOS | PHPExcel_Calculation_Engineering::IMCOS
+ IMDIV | PHPExcel_Calculation_Engineering::IMDIV
+ IMEXP | PHPExcel_Calculation_Engineering::IMEXP
+ IMLN | PHPExcel_Calculation_Engineering::IMLN
+ IMLOG10 | PHPExcel_Calculation_Engineering::IMLOG10
+ IMLOG2 | PHPExcel_Calculation_Engineering::IMLOG2
+ IMPOWER | PHPExcel_Calculation_Engineering::IMPOWER
+ IMPRODUCT | PHPExcel_Calculation_Engineering::IMPRODUCT
+ IMREAL | PHPExcel_Calculation_Engineering::IMREAL
+ IMSIN | PHPExcel_Calculation_Engineering::IMSIN
+ IMSQRT | PHPExcel_Calculation_Engineering::IMSQRT
+ IMSUB | PHPExcel_Calculation_Engineering::IMSUB
+ IMSUM | PHPExcel_Calculation_Engineering::IMSUM
+ OCT2BIN | PHPExcel_Calculation_Engineering::OCTTOBIN
+ OCT2DEC | PHPExcel_Calculation_Engineering::OCTTODEC
+ OCT2HEX | PHPExcel_Calculation_Engineering::OCTTOHEX
+
+## CATEGORY_FINANCIAL
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ ACCRINT | PHPExcel_Calculation_Financial::ACCRINT
+ ACCRINTM | PHPExcel_Calculation_Financial::ACCRINTM
+ AMORDEGRC | PHPExcel_Calculation_Financial::AMORDEGRC
+ AMORLINC | PHPExcel_Calculation_Financial::AMORLINC
+ COUPDAYBS | PHPExcel_Calculation_Financial::COUPDAYBS
+ COUPDAYS | PHPExcel_Calculation_Financial::COUPDAYS
+ COUPDAYSNC | PHPExcel_Calculation_Financial::COUPDAYSNC
+ COUPNCD | PHPExcel_Calculation_Financial::COUPNCD
+ COUPNUM | PHPExcel_Calculation_Financial::COUPNUM
+ COUPPCD | PHPExcel_Calculation_Financial::COUPPCD
+ CUMIPMT | PHPExcel_Calculation_Financial::CUMIPMT
+ CUMPRINC | PHPExcel_Calculation_Financial::CUMPRINC
+ DB | PHPExcel_Calculation_Financial::DB
+ DDB | PHPExcel_Calculation_Financial::DDB
+ DISC | PHPExcel_Calculation_Financial::DISC
+ DOLLARDE | PHPExcel_Calculation_Financial::DOLLARDE
+ DOLLARFR | PHPExcel_Calculation_Financial::DOLLARFR
+ DURATION | **\*\*\* Not yet Implemented**
+ EFFECT | PHPExcel_Calculation_Financial::EFFECT
+ FV | PHPExcel_Calculation_Financial::FV
+ FVSCHEDULE | PHPExcel_Calculation_Financial::FVSCHEDULE
+ INTRATE | PHPExcel_Calculation_Financial::INTRATE
+ IPMT | PHPExcel_Calculation_Financial::IPMT
+ IRR | PHPExcel_Calculation_Financial::IRR
+ ISPMT | PHPExcel_Calculation_Financial::ISPMT
+ MDURATION | **\*\*\* Not yet Implemented**
+ MIRR | PHPExcel_Calculation_Financial::MIRR
+ NOMINAL | PHPExcel_Calculation_Financial::NOMINAL
+ NPER | PHPExcel_Calculation_Financial::NPER
+ NPV | PHPExcel_Calculation_Financial::NPV
+ ODDFPRICE | **\*\*\* Not yet Implemented**
+ ODDFYIELD | **\*\*\* Not yet Implemented**
+ ODDLPRICE | **\*\*\* Not yet Implemented**
+ ODDLYIELD | **\*\*\* Not yet Implemented**
+ PMT | PHPExcel_Calculation_Financial::PMT
+ PPMT | PHPExcel_Calculation_Financial::PPMT
+ PRICE | PHPExcel_Calculation_Financial::PRICE
+ PRICEDISC | PHPExcel_Calculation_Financial::PRICEDISC
+ PRICEMAT | PHPExcel_Calculation_Financial::PRICEMAT
+ PV | PHPExcel_Calculation_Financial::PV
+ RATE | PHPExcel_Calculation_Financial::RATE
+ RECEIVED | PHPExcel_Calculation_Financial::RECEIVED
+ SLN | PHPExcel_Calculation_Financial::SLN
+ SYD | PHPExcel_Calculation_Financial::SYD
+ TBILLEQ | PHPExcel_Calculation_Financial::TBILLEQ
+ TBILLPRICE | PHPExcel_Calculation_Financial::TBILLPRICE
+ TBILLYIELD | PHPExcel_Calculation_Financial::TBILLYIELD
+ USDOLLAR | **\*\*\* Not yet Implemented**
+ VDB | **\*\*\* Not yet Implemented**
+ XIRR | PHPExcel_Calculation_Financial::XIRR
+ XNPV | PHPExcel_Calculation_Financial::XNPV
+ YIELD | **\*\*\* Not yet Implemented**
+ YIELDDISC | PHPExcel_Calculation_Financial::YIELDDISC
+ YIELDMAT | PHPExcel_Calculation_Financial::YIELDMAT
+
+## CATEGORY_INFORMATION
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ CELL | **\*\*\* Not yet Implemented**
+ ERROR.TYPE | PHPExcel_Calculation_Functions::ERROR_TYPE
+ INFO | **\*\*\* Not yet Implemented**
+ ISBLANK | PHPExcel_Calculation_Functions::IS_BLANK
+ ISERR | PHPExcel_Calculation_Functions::IS_ERR
+ ISERROR | PHPExcel_Calculation_Functions::IS_ERROR
+ ISEVEN | PHPExcel_Calculation_Functions::IS_EVEN
+ ISLOGICAL | PHPExcel_Calculation_Functions::IS_LOGICAL
+ ISNA | PHPExcel_Calculation_Functions::IS_NA
+ ISNONTEXT | PHPExcel_Calculation_Functions::IS_NONTEXT
+ ISNUMBER | PHPExcel_Calculation_Functions::IS_NUMBER
+ ISODD | PHPExcel_Calculation_Functions::IS_ODD
+ ISREF | **\*\*\* Not yet Implemented**
+ ISTEXT | PHPExcel_Calculation_Functions::IS_TEXT
+ N | PHPExcel_Calculation_Functions::N
+ NA | PHPExcel_Calculation_Functions::NA
+ TYPE | PHPExcel_Calculation_Functions::TYPE
+ VERSION | PHPExcel_Calculation_Functions::VERSION
+
+## CATEGORY_LOGICAL
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ AND | PHPExcel_Calculation_Logical::LOGICAL_AND
+ FALSE | PHPExcel_Calculation_Logical::FALSE
+ IF | PHPExcel_Calculation_Logical::STATEMENT_IF
+ IFERROR | PHPExcel_Calculation_Logical::IFERROR
+ NOT | PHPExcel_Calculation_Logical::NOT
+ OR | PHPExcel_Calculation_Logical::LOGICAL_OR
+ TRUE | PHPExcel_Calculation_Logical::TRUE
+
+## CATEGORY_LOOKUP_AND_REFERENCE
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ ADDRESS | PHPExcel_Calculation_LookupRef::CELL_ADDRESS
+ AREAS | **\*\*\* Not yet Implemented**
+ CHOOSE | PHPExcel_Calculation_LookupRef::CHOOSE
+ COLUMN | PHPExcel_Calculation_LookupRef::COLUMN
+ COLUMNS | PHPExcel_Calculation_LookupRef::COLUMNS
+ GETPIVOTDATA | **\*\*\* Not yet Implemented**
+ HLOOKUP | **\*\*\* Not yet Implemented**
+ HYPERLINK | PHPExcel_Calculation_LookupRef::HYPERLINK
+ INDEX | PHPExcel_Calculation_LookupRef::INDEX
+ INDIRECT | PHPExcel_Calculation_LookupRef::INDIRECT
+ LOOKUP | PHPExcel_Calculation_LookupRef::LOOKUP
+ MATCH | PHPExcel_Calculation_LookupRef::MATCH
+ OFFSET | PHPExcel_Calculation_LookupRef::OFFSET
+ ROW | PHPExcel_Calculation_LookupRef::ROW
+ ROWS | PHPExcel_Calculation_LookupRef::ROWS
+ RTD | **\*\*\* Not yet Implemented**
+ TRANSPOSE | PHPExcel_Calculation_LookupRef::TRANSPOSE
+ VLOOKUP | PHPExcel_Calculation_LookupRef::VLOOKUP
+
+## CATEGORY_MATH_AND_TRIG
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ ABS | abs
+ ACOS | acos
+ ACOSH | acosh
+ ASIN | asin
+ ASINH | asinh
+ ATAN | atan
+ ATAN2 | PHPExcel_Calculation_MathTrig::REVERSE_ATAN2
+ ATANH | atanh
+ CEILING | PHPExcel_Calculation_MathTrig::CEILING
+ COMBIN | PHPExcel_Calculation_MathTrig::COMBIN
+ COS | cos
+ COSH | cosh
+ DEGREES | rad2deg
+ EVEN | PHPExcel_Calculation_MathTrig::EVEN
+ EXP | exp
+ FACT | PHPExcel_Calculation_MathTrig::FACT
+ FACTDOUBLE | PHPExcel_Calculation_MathTrig::FACTDOUBLE
+ FLOOR | PHPExcel_Calculation_MathTrig::FLOOR
+ GCD | PHPExcel_Calculation_MathTrig::GCD
+ INT | PHPExcel_Calculation_MathTrig::INT
+ LCM | PHPExcel_Calculation_MathTrig::LCM
+ LN | log
+ LOG | PHPExcel_Calculation_MathTrig::LOG_BASE
+ LOG10 | log10
+ MDETERM | PHPExcel_Calculation_MathTrig::MDETERM
+ MINVERSE | PHPExcel_Calculation_MathTrig::MINVERSE
+ MMULT | PHPExcel_Calculation_MathTrig::MMULT
+ MOD | PHPExcel_Calculation_MathTrig::MOD
+ MROUND | PHPExcel_Calculation_MathTrig::MROUND
+ MULTINOMIAL | PHPExcel_Calculation_MathTrig::MULTINOMIAL
+ ODD | PHPExcel_Calculation_MathTrig::ODD
+ PI | pi
+ POWER | PHPExcel_Calculation_MathTrig::POWER
+ PRODUCT | PHPExcel_Calculation_MathTrig::PRODUCT
+ QUOTIENT | PHPExcel_Calculation_MathTrig::QUOTIENT
+ RADIANS | deg2rad
+ RAND | PHPExcel_Calculation_MathTrig::RAND
+ RANDBETWEEN | PHPExcel_Calculation_MathTrig::RAND
+ ROMAN | PHPExcel_Calculation_MathTrig::ROMAN
+ ROUND | round
+ ROUNDDOWN | PHPExcel_Calculation_MathTrig::ROUNDDOWN
+ ROUNDUP | PHPExcel_Calculation_MathTrig::ROUNDUP
+ SERIESSUM | PHPExcel_Calculation_MathTrig::SERIESSUM
+ SIGN | PHPExcel_Calculation_MathTrig::SIGN
+ SIN | sin
+ SINH | sinh
+ SQRT | sqrt
+ SQRTPI | PHPExcel_Calculation_MathTrig::SQRTPI
+ SUBTOTAL | PHPExcel_Calculation_MathTrig::SUBTOTAL
+ SUM | PHPExcel_Calculation_MathTrig::SUM
+ SUMIF | PHPExcel_Calculation_MathTrig::SUMIF
+ SUMIFS | **\*\*\* Not yet Implemented**
+ SUMPRODUCT | PHPExcel_Calculation_MathTrig::SUMPRODUCT
+ SUMSQ | PHPExcel_Calculation_MathTrig::SUMSQ
+ SUMX2MY2 | PHPExcel_Calculation_MathTrig::SUMX2MY2
+ SUMX2PY2 | PHPExcel_Calculation_MathTrig::SUMX2PY2
+ SUMXMY2 | PHPExcel_Calculation_MathTrig::SUMXMY2
+ TAN | tan
+ TANH | tanh
+ TRUNC | PHPExcel_Calculation_MathTrig::TRUNC
+
+## CATEGORY_STATISTICAL
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ AVEDEV | PHPExcel_Calculation_Statistical::AVEDEV
+ AVERAGE | PHPExcel_Calculation_Statistical::AVERAGE
+ AVERAGEA | PHPExcel_Calculation_Statistical::AVERAGEA
+ AVERAGEIF | PHPExcel_Calculation_Statistical::AVERAGEIF
+ AVERAGEIFS | **\*\*\* Not yet Implemented**
+ BETADIST | PHPExcel_Calculation_Statistical::BETADIST
+ BETAINV | PHPExcel_Calculation_Statistical::BETAINV
+ BINOMDIST | PHPExcel_Calculation_Statistical::BINOMDIST
+ CHIDIST | PHPExcel_Calculation_Statistical::CHIDIST
+ CHIINV | PHPExcel_Calculation_Statistical::CHIINV
+ CHITEST | **\*\*\* Not yet Implemented**
+ CONFIDENCE | PHPExcel_Calculation_Statistical::CONFIDENCE
+ CORREL | PHPExcel_Calculation_Statistical::CORREL
+ COUNT | PHPExcel_Calculation_Statistical::COUNT
+ COUNTA | PHPExcel_Calculation_Statistical::COUNTA
+ COUNTBLANK | PHPExcel_Calculation_Statistical::COUNTBLANK
+ COUNTIF | PHPExcel_Calculation_Statistical::COUNTIF
+ COUNTIFS | **\*\*\* Not yet Implemented**
+ COVAR | PHPExcel_Calculation_Statistical::COVAR
+ CRITBINOM | PHPExcel_Calculation_Statistical::CRITBINOM
+ DEVSQ | PHPExcel_Calculation_Statistical::DEVSQ
+ EXPONDIST | PHPExcel_Calculation_Statistical::EXPONDIST
+ FDIST | **\*\*\* Not yet Implemented**
+ FINV | **\*\*\* Not yet Implemented**
+ FISHER | PHPExcel_Calculation_Statistical::FISHER
+ FISHERINV | PHPExcel_Calculation_Statistical::FISHERINV
+ FORECAST | PHPExcel_Calculation_Statistical::FORECAST
+ FREQUENCY | **\*\*\* Not yet Implemented**
+ FTEST | **\*\*\* Not yet Implemented**
+ GAMMADIST | PHPExcel_Calculation_Statistical::GAMMADIST
+ GAMMAINV | PHPExcel_Calculation_Statistical::GAMMAINV
+ GAMMALN | PHPExcel_Calculation_Statistical::GAMMALN
+ GEOMEAN | PHPExcel_Calculation_Statistical::GEOMEAN
+ GROWTH | PHPExcel_Calculation_Statistical::GROWTH
+ HARMEAN | PHPExcel_Calculation_Statistical::HARMEAN
+ HYPGEOMDIST | PHPExcel_Calculation_Statistical::HYPGEOMDIST
+ INTERCEPT | PHPExcel_Calculation_Statistical::INTERCEPT
+ KURT | PHPExcel_Calculation_Statistical::KURT
+ LARGE | PHPExcel_Calculation_Statistical::LARGE
+ LINEST | PHPExcel_Calculation_Statistical::LINEST
+ LOGEST | PHPExcel_Calculation_Statistical::LOGEST
+ LOGINV | PHPExcel_Calculation_Statistical::LOGINV
+ LOGNORMDIST | PHPExcel_Calculation_Statistical::LOGNORMDIST
+ MAX | PHPExcel_Calculation_Statistical::MAX
+ MAXA | PHPExcel_Calculation_Statistical::MAXA
+ MAXIF | PHPExcel_Calculation_Statistical::MAXIF
+ MEDIAN | PHPExcel_Calculation_Statistical::MEDIAN
+ MEDIANIF | **\*\*\* Not yet Implemented**
+ MIN | PHPExcel_Calculation_Statistical::MIN
+ MINA | PHPExcel_Calculation_Statistical::MINA
+ MINIF | PHPExcel_Calculation_Statistical::MINIF
+ MODE | PHPExcel_Calculation_Statistical::MODE
+ NEGBINOMDIST | PHPExcel_Calculation_Statistical::NEGBINOMDIST
+ NORMDIST | PHPExcel_Calculation_Statistical::NORMDIST
+ NORMINV | PHPExcel_Calculation_Statistical::NORMINV
+ NORMSDIST | PHPExcel_Calculation_Statistical::NORMSDIST
+ NORMSINV | PHPExcel_Calculation_Statistical::NORMSINV
+ PEARSON | PHPExcel_Calculation_Statistical::CORREL
+ PERCENTILE | PHPExcel_Calculation_Statistical::PERCENTILE
+ PERCENTRANK | PHPExcel_Calculation_Statistical::PERCENTRANK
+ PERMUT | PHPExcel_Calculation_Statistical::PERMUT
+ POISSON | PHPExcel_Calculation_Statistical::POISSON
+ PROB | **\*\*\* Not yet Implemented**
+ QUARTILE | PHPExcel_Calculation_Statistical::QUARTILE
+ RANK | PHPExcel_Calculation_Statistical::RANK
+ RSQ | PHPExcel_Calculation_Statistical::RSQ
+ SKEW | PHPExcel_Calculation_Statistical::SKEW
+ SLOPE | PHPExcel_Calculation_Statistical::SLOPE
+ SMALL | PHPExcel_Calculation_Statistical::SMALL
+ STANDARDIZE | PHPExcel_Calculation_Statistical::STANDARDIZE
+ STDEV | PHPExcel_Calculation_Statistical::STDEV
+ STDEVA | PHPExcel_Calculation_Statistical::STDEVA
+ STDEVP | PHPExcel_Calculation_Statistical::STDEVP
+ STDEVPA | PHPExcel_Calculation_Statistical::STDEVPA
+ STEYX | PHPExcel_Calculation_Statistical::STEYX
+ TDIST | PHPExcel_Calculation_Statistical::TDIST
+ TINV | PHPExcel_Calculation_Statistical::TINV
+ TREND | PHPExcel_Calculation_Statistical::TREND
+ TRIMMEAN | PHPExcel_Calculation_Statistical::TRIMMEAN
+ TTEST | **\*\*\* Not yet Implemented**
+ VAR | PHPExcel_Calculation_Statistical::VARFunc
+ VARA | PHPExcel_Calculation_Statistical::VARA
+ VARP | PHPExcel_Calculation_Statistical::VARP
+ VARPA | PHPExcel_Calculation_Statistical::VARPA
+ WEIBULL | PHPExcel_Calculation_Statistical::WEIBULL
+ ZTEST | PHPExcel_Calculation_Statistical::ZTEST
+
+## CATEGORY_TEXT_AND_DATA
+
+ Excel Function | PHPExcel Function
+ --------------------|-------------------------------------------
+ ASC | **\*\*\* Not yet Implemented**
+ BAHTTEXT | **\*\*\* Not yet Implemented**
+ CHAR | PHPExcel_Calculation_TextData::CHARACTER
+ CLEAN | PHPExcel_Calculation_TextData::TRIMNONPRINTABLE
+ CODE | PHPExcel_Calculation_TextData::ASCIICODE
+ CONCATENATE | PHPExcel_Calculation_TextData::CONCATENATE
+ DOLLAR | PHPExcel_Calculation_TextData::DOLLAR
+ EXACT | **\*\*\* Not yet Implemented**
+ FIND | PHPExcel_Calculation_TextData::SEARCHSENSITIVE
+ FINDB | PHPExcel_Calculation_TextData::SEARCHSENSITIVE
+ FIXED | PHPExcel_Calculation_TextData::FIXEDFORMAT
+ JIS | **\*\*\* Not yet Implemented**
+ LEFT | PHPExcel_Calculation_TextData::LEFT
+ LEFTB | PHPExcel_Calculation_TextData::LEFT
+ LEN | PHPExcel_Calculation_TextData::STRINGLENGTH
+ LENB | PHPExcel_Calculation_TextData::STRINGLENGTH
+ LOWER | PHPExcel_Calculation_TextData::LOWERCASE
+ MID | PHPExcel_Calculation_TextData::MID
+ MIDB | PHPExcel_Calculation_TextData::MID
+ PHONETIC | **\*\*\* Not yet Implemented**
+ PROPER | PHPExcel_Calculation_TextData::PROPERCASE
+ REPLACE | PHPExcel_Calculation_TextData::REPLACE
+ REPLACEB | PHPExcel_Calculation_TextData::REPLACE
+ REPT | str_repeat
+ RIGHT | PHPExcel_Calculation_TextData::RIGHT
+ RIGHTB | PHPExcel_Calculation_TextData::RIGHT
+ SEARCH | PHPExcel_Calculation_TextData::SEARCHINSENSITIVE
+ SEARCHB | PHPExcel_Calculation_TextData::SEARCHINSENSITIVE
+ SUBSTITUTE | PHPExcel_Calculation_TextData::SUBSTITUTE
+ T | PHPExcel_Calculation_TextData::RETURNSTRING
+ TEXT | PHPExcel_Calculation_TextData::TEXTFORMAT
+ TRIM | PHPExcel_Calculation_TextData::TRIMSPACES
+ UPPER | PHPExcel_Calculation_TextData::UPPERCASE
+ VALUE | **\*\*\* Not yet Implemented**
+
diff --git a/Documentation/markdown/Functions/FunctionListByName.md b/Documentation/markdown/Functions/FunctionListByName.md
new file mode 100644
index 000000000..b69e45469
--- /dev/null
+++ b/Documentation/markdown/Functions/FunctionListByName.md
@@ -0,0 +1,485 @@
+#A
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ ABS | CATEGORY_MATH_AND_TRIG | abs
+ ACCRINT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::ACCRINT
+ ACCRINTM | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::ACCRINTM
+ ACOS | CATEGORY_MATH_AND_TRIG | acos
+ ACOSH | CATEGORY_MATH_AND_TRIG | acosh
+ ADDRESS | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::CELL_ADDRESS
+ AMORDEGRC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::AMORDEGRC
+ AMORLINC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::AMORLINC
+ AND | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::LOGICAL_AND
+ AREAS | CATEGORY_LOOKUP_AND_REFERENCE | **\*\*\* Not yet Implemented**
+ ASC | CATEGORY_TEXT_AND_DATA | **\*\*\* Not yet Implemented**
+ ASIN | CATEGORY_MATH_AND_TRIG | asin
+ ASINH | CATEGORY_MATH_AND_TRIG | asinh
+ ATAN | CATEGORY_MATH_AND_TRIG | atan
+ ATAN2 | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::REVERSE_ATAN2
+ ATANH | CATEGORY_MATH_AND_TRIG | atanh
+ AVEDEV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::AVEDEV
+ AVERAGE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::AVERAGE
+ AVERAGEA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::AVERAGEA
+ AVERAGEIF | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::AVERAGEIF
+ AVERAGEIFS | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+
+#B
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ BAHTTEXT | CATEGORY_TEXT_AND_DATA | **\*\*\* Not yet Implemented**
+ BESSELI | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BESSELI
+ BESSELJ | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BESSELJ
+ BESSELK | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BESSELK
+ BESSELY | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BESSELY
+ BETADIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::BETADIST
+ BETAINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::BETAINV
+ BIN2DEC | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BINTODEC
+ BIN2HEX | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BINTOHEX
+ BIN2OCT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::BINTOOCT
+ BINOMDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::BINOMDIST
+
+#C
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ CEILING | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::CEILING
+ CELL | CATEGORY_INFORMATION | **\*\*\* Not yet Implemented**
+ CHAR | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::CHARACTER
+ CHIDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::CHIDIST
+ CHIINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::CHIINV
+ CHITEST | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ CHOOSE | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::CHOOSE
+ CLEAN | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::TRIMNONPRINTABLE
+ CODE | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::ASCIICODE
+ COLUMN | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::COLUMN
+ COLUMNS | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::COLUMNS
+ COMBIN | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::COMBIN
+ COMPLEX | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::COMPLEX
+ CONCATENATE | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::CONCATENATE
+ CONFIDENCE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::CONFIDENCE
+ CONVERT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::CONVERTUOM
+ CORREL | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::CORREL
+ COS | CATEGORY_MATH_AND_TRIG | cos
+ COSH | CATEGORY_MATH_AND_TRIG | cosh
+ COUNT | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::COUNT
+ COUNTA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::COUNTA
+ COUNTBLANK | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::COUNTBLANK
+ COUNTIF | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::COUNTIF
+ COUNTIFS | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ COUPDAYBS | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::COUPDAYBS
+ COUPDAYS | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::COUPDAYS
+ COUPDAYSNC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::COUPDAYSNC
+ COUPNCD | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::COUPNCD
+ COUPNUM | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::COUPNUM
+ COUPPCD | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::COUPPCD
+ COVAR | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::COVAR
+ CRITBINOM | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::CRITBINOM
+ CUBEKPIMEMBER | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUBEMEMBER | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUBEMEMBERPROPERTY | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUBERANKEDMEMBER | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUBESET | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUBESETCOUNT | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUBEVALUE | CATEGORY_CUBE | **\*\*\* Not yet Implemented**
+ CUMIPMT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::CUMIPMT
+ CUMPRINC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::CUMPRINC
+
+#D
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ DATE | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DATE
+ DATEDIF | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DATEDIF
+ DATEVALUE | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DATEVALUE
+ DAVERAGE | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DAVERAGE
+ DAY | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DAYOFMONTH
+ DAYS360 | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DAYS360
+ DB | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::DB
+ DCOUNT | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DCOUNT
+ DCOUNTA | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DCOUNTA
+ DDB | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::DDB
+ DEC2BIN | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::DECTOBIN
+ DEC2HEX | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::DECTOHEX
+ DEC2OCT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::DECTOOCT
+ DEGREES | CATEGORY_MATH_AND_TRIG | rad2deg
+ DELTA | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::DELTA
+ DEVSQ | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::DEVSQ
+ DGET | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DGET
+ DISC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::DISC
+ DMAX | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DMAX
+ DMIN | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DMIN
+ DOLLAR | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::DOLLAR
+ DOLLARDE | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::DOLLARDE
+ DOLLARFR | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::DOLLARFR
+ DPRODUCT | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DPRODUCT
+ DSTDEV | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DSTDEV
+ DSTDEVP | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DSTDEVP
+ DSUM | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DSUM
+ DURATION | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ DVAR | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DVAR
+ DVARP | CATEGORY_DATABASE | PHPExcel_Calculation_Database::DVARP
+
+#E
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ EDATE | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::EDATE
+ EFFECT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::EFFECT
+ EOMONTH | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::EOMONTH
+ ERF | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::ERF
+ ERFC | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::ERFC
+ ERROR.TYPE | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::ERROR_TYPE
+ EVEN | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::EVEN
+ EXACT | CATEGORY_TEXT_AND_DATA | **\*\*\* Not yet Implemented**
+ EXP | CATEGORY_MATH_AND_TRIG | exp
+ EXPONDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::EXPONDIST
+
+#F
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ FACT | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::FACT
+ FACTDOUBLE | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::FACTDOUBLE
+ FALSE | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::FALSE
+ FDIST | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ FIND | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::SEARCHSENSITIVE
+ FINDB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::SEARCHSENSITIVE
+ FINV | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ FISHER | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::FISHER
+ FISHERINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::FISHERINV
+ FIXED | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::FIXEDFORMAT
+ FLOOR | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::FLOOR
+ FORECAST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::FORECAST
+ FREQUENCY | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ FTEST | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ FV | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::FV
+ FVSCHEDULE | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::FVSCHEDULE
+
+#G
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ GAMMADIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::GAMMADIST
+ GAMMAINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::GAMMAINV
+ GAMMALN | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::GAMMALN
+ GCD | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::GCD
+ GEOMEAN | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::GEOMEAN
+ GESTEP | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::GESTEP
+ GETPIVOTDATA | CATEGORY_LOOKUP_AND_REFERENCE | **\*\*\* Not yet Implemented**
+ GROWTH | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::GROWTH
+
+#H
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ HARMEAN | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::HARMEAN
+ HEX2BIN | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::HEXTOBIN
+ HEX2DEC | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::HEXTODEC
+ HEX2OCT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::HEXTOOCT
+ HLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | **\*\*\* Not yet Implemented**
+ HOUR | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::HOUROFDAY
+ HYPERLINK | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::HYPERLINK
+ HYPGEOMDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::HYPGEOMDIST
+
+#I
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ IF | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::STATEMENT_IF
+ IFERROR | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::IFERROR
+ IMABS | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMABS
+ IMAGINARY | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMAGINARY
+ IMARGUMENT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMARGUMENT
+ IMCONJUGATE | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMCONJUGATE
+ IMCOS | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMCOS
+ IMDIV | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMDIV
+ IMEXP | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMEXP
+ IMLN | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMLN
+ IMLOG10 | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMLOG10
+ IMLOG2 | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMLOG2
+ IMPOWER | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMPOWER
+ IMPRODUCT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMPRODUCT
+ IMREAL | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMREAL
+ IMSIN | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMSIN
+ IMSQRT | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMSQRT
+ IMSUB | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMSUB
+ IMSUM | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::IMSUM
+ INDEX | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::INDEX
+ INDIRECT | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::INDIRECT
+ INFO | CATEGORY_INFORMATION | **\*\*\* Not yet Implemented**
+ INT | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::INT
+ INTERCEPT | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::INTERCEPT
+ INTRATE | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::INTRATE
+ IPMT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::IPMT
+ IRR | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::IRR
+ ISBLANK | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_BLANK
+ ISERR | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_ERR
+ ISERROR | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_ERROR
+ ISEVEN | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_EVEN
+ ISLOGICAL | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_LOGICAL
+ ISNA | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_NA
+ ISNONTEXT | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_NONTEXT
+ ISNUMBER | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_NUMBER
+ ISODD | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_ODD
+ ISPMT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::ISPMT
+ ISREF | CATEGORY_INFORMATION | **\*\*\* Not yet Implemented**
+ ISTEXT | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::IS_TEXT
+
+#J
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ JIS | CATEGORY_TEXT_AND_DATA | **\*\*\* Not yet Implemented**
+
+#K
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ KURT | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::KURT
+
+#L
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ LARGE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::LARGE
+ LCM | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::LCM
+ LEFT | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::LEFT
+ LEFTB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::LEFT
+ LEN | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::STRINGLENGTH
+ LENB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::STRINGLENGTH
+ LINEST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::LINEST
+ LN | CATEGORY_MATH_AND_TRIG | log
+ LOG | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::LOG_BASE
+ LOG10 | CATEGORY_MATH_AND_TRIG | log10
+ LOGEST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::LOGEST
+ LOGINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::LOGINV
+ LOGNORMDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::LOGNORMDIST
+ LOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::LOOKUP
+ LOWER | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::LOWERCASE
+
+#M
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ MATCH | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::MATCH
+ MAX | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MAX
+ MAXA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MAXA
+ MAXIF | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MAXIF
+ MDETERM | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::MDETERM
+ MDURATION | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ MEDIAN | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MEDIAN
+ MEDIANIF | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ MID | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::MID
+ MIDB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::MID
+ MIN | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MIN
+ MINA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MINA
+ MINIF | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MINIF
+ MINUTE | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::MINUTEOFHOUR
+ MINVERSE | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::MINVERSE
+ MIRR | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::MIRR
+ MMULT | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::MMULT
+ MOD | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::MOD
+ MODE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::MODE
+ MONTH | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::MONTHOFYEAR
+ MROUND | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::MROUND
+ MULTINOMIAL | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::MULTINOMIAL
+
+#N
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ N | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::N
+ NA | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::NA
+ NEGBINOMDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::NEGBINOMDIST
+ NETWORKDAYS | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::NETWORKDAYS
+ NOMINAL | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::NOMINAL
+ NORMDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::NORMDIST
+ NORMINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::NORMINV
+ NORMSDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::NORMSDIST
+ NORMSINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::NORMSINV
+ NOT | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::NOT
+ NOW | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DATETIMENOW
+ NPER | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::NPER
+ NPV | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::NPV
+
+#O
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ OCT2BIN | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::OCTTOBIN
+ OCT2DEC | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::OCTTODEC
+ OCT2HEX | CATEGORY_ENGINEERING | PHPExcel_Calculation_Engineering::OCTTOHEX
+ ODD | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::ODD
+ ODDFPRICE | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ ODDFYIELD | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ ODDLPRICE | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ ODDLYIELD | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ OFFSET | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::OFFSET
+ OR | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::LOGICAL_OR
+
+#P
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ PEARSON | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::CORREL
+ PERCENTILE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::PERCENTILE
+ PERCENTRANK | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::PERCENTRANK
+ PERMUT | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::PERMUT
+ PHONETIC | CATEGORY_TEXT_AND_DATA | **\*\*\* Not yet Implemented**
+ PI | CATEGORY_MATH_AND_TRIG | pi
+ PMT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::PMT
+ POISSON | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::POISSON
+ POWER | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::POWER
+ PPMT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::PPMT
+ PRICE | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::PRICE
+ PRICEDISC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::PRICEDISC
+ PRICEMAT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::PRICEMAT
+ PROB | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ PRODUCT | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::PRODUCT
+ PROPER | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::PROPERCASE
+ PV | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::PV
+
+#Q
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ QUARTILE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::QUARTILE
+ QUOTIENT | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::QUOTIENT
+
+#R
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ RADIANS | CATEGORY_MATH_AND_TRIG | deg2rad
+ RAND | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::RAND
+ RANDBETWEEN | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::RAND
+ RANK | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::RANK
+ RATE | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::RATE
+ RECEIVED | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::RECEIVED
+ REPLACE | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::REPLACE
+ REPLACEB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::REPLACE
+ REPT | CATEGORY_TEXT_AND_DATA | str_repeat
+ RIGHT | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::RIGHT
+ RIGHTB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::RIGHT
+ ROMAN | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::ROMAN
+ ROUND | CATEGORY_MATH_AND_TRIG | round
+ ROUNDDOWN | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::ROUNDDOWN
+ ROUNDUP | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::ROUNDUP
+ ROW | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::ROW
+ ROWS | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::ROWS
+ RSQ | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::RSQ
+ RTD | CATEGORY_LOOKUP_AND_REFERENCE | **\*\*\* Not yet Implemented**
+
+#S
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ SEARCH | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::SEARCHINSENSITIVE
+ SEARCHB | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::SEARCHINSENSITIVE
+ SECOND | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::SECONDOFMINUTE
+ SERIESSUM | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SERIESSUM
+ SIGN | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SIGN
+ SIN | CATEGORY_MATH_AND_TRIG | sin
+ SINH | CATEGORY_MATH_AND_TRIG | sinh
+ SKEW | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::SKEW
+ SLN | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::SLN
+ SLOPE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::SLOPE
+ SMALL | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::SMALL
+ SQRT | CATEGORY_MATH_AND_TRIG | sqrt
+ SQRTPI | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SQRTPI
+ STANDARDIZE | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::STANDARDIZE
+ STDEV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::STDEV
+ STDEVA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::STDEVA
+ STDEVP | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::STDEVP
+ STDEVPA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::STDEVPA
+ STEYX | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::STEYX
+ SUBSTITUTE | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::SUBSTITUTE
+ SUBTOTAL | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUBTOTAL
+ SUM | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUM
+ SUMIF | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUMIF
+ SUMIFS | CATEGORY_MATH_AND_TRIG | **\*\*\* Not yet Implemented**
+ SUMPRODUCT | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUMPRODUCT
+ SUMSQ | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUMSQ
+ SUMX2MY2 | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUMX2MY2
+ SUMX2PY2 | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUMX2PY2
+ SUMXMY2 | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::SUMXMY2
+ SYD | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::SYD
+
+#T
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ T | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::RETURNSTRING
+ TAN | CATEGORY_MATH_AND_TRIG | tan
+ TANH | CATEGORY_MATH_AND_TRIG | tanh
+ TBILLEQ | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::TBILLEQ
+ TBILLPRICE | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::TBILLPRICE
+ TBILLYIELD | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::TBILLYIELD
+ TDIST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::TDIST
+ TEXT | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::TEXTFORMAT
+ TIME | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::TIME
+ TIMEVALUE | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::TIMEVALUE
+ TINV | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::TINV
+ TODAY | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DATENOW
+ TRANSPOSE | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::TRANSPOSE
+ TREND | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::TREND
+ TRIM | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::TRIMSPACES
+ TRIMMEAN | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::TRIMMEAN
+ TRUE | CATEGORY_LOGICAL | PHPExcel_Calculation_Logical::TRUE
+ TRUNC | CATEGORY_MATH_AND_TRIG | PHPExcel_Calculation_MathTrig::TRUNC
+ TTEST | CATEGORY_STATISTICAL | **\*\*\* Not yet Implemented**
+ TYPE | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::TYPE
+
+#U
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ UPPER | CATEGORY_TEXT_AND_DATA | PHPExcel_Calculation_TextData::UPPERCASE
+ USDOLLAR | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+
+#V
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ VALUE | CATEGORY_TEXT_AND_DATA | **\*\*\* Not yet Implemented**
+ VAR | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::VARFunc
+ VARA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::VARA
+ VARP | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::VARP
+ VARPA | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::VARPA
+ VDB | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ VERSION | CATEGORY_INFORMATION | PHPExcel_Calculation_Functions::VERSION
+ VLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | PHPExcel_Calculation_LookupRef::VLOOKUP
+
+#W
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ WEEKDAY | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::DAYOFWEEK
+ WEEKNUM | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::WEEKOFYEAR
+ WEIBULL | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::WEIBULL
+ WORKDAY | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::WORKDAY
+
+#X
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ XIRR | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::XIRR
+ XNPV | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::XNPV
+
+#Y
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ YEAR | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::YEAR
+ YEARFRAC | CATEGORY_DATE_AND_TIME | PHPExcel_Calculation_DateTime::YEARFRAC
+ YIELD | CATEGORY_FINANCIAL | **\*\*\* Not yet Implemented**
+ YIELDDISC | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::YIELDDISC
+ YIELDMAT | CATEGORY_FINANCIAL | PHPExcel_Calculation_Financial::YIELDMAT
+
+#Z
+
+ Excel Function | Category | PHPExcel Function
+ --------------------|--------------------------------|-------------------------------------------
+ ZTEST | CATEGORY_STATISTICAL | PHPExcel_Calculation_Statistical::ZTEST
diff --git a/Documentation/markdown/Overview/01-Getting-Started.md b/Documentation/markdown/Overview/01-Getting-Started.md
new file mode 100644
index 000000000..262f1eaf8
--- /dev/null
+++ b/Documentation/markdown/Overview/01-Getting-Started.md
@@ -0,0 +1,179 @@
+# PHPExcel Developer Documentation
+
+
+## Prerequisites, Installation, FAQ and Links
+
+### Software requirements
+
+The following software is required to develop using PHPExcel:
+
+ - PHP version 5.2.0 or newer
+ - PHP extension php_zip enabled [^phpzip_footnote]
+ - PHP extension php_xml enabled
+ - PHP extension php_gd2 enabled (if not compiled in)
+
+
+### Installation instructions
+
+Installation is quite easy: copy the contents of the Classes folder to any location within your application source directories.
+
+*Example:*
+
+If your web root folder is /var/www/ you may want to create a subfolder called /var/www/Classes/ and copy the files into that folder so you end up with files:
+
+ /var/www/Classes/PHPExcel.php
+ /var/www/Classes/PHPExcel/Calculation.php
+ /var/www/Classes/PHPExcel/Cell.php
+ ...
+
+
+### Getting started
+
+A good way to get started is to run some of the tests included in the download.
+Copy the "Examples" folder next to your "Classes" folder from above so you end up with:
+
+ /var/www/Examples/01simple.php
+ /var/www/Examples/02types.php
+ ...
+
+Start running the tests by pointing your browser to the test scripts:
+
+http://example.com/Tests/01simple.php
+http://example.com/Tests/02types.php
+...
+
+**Note:** It may be necessary to modify the include/require statements at the beginning of each of the test scripts if your "Classes" folder from above is named differently.
+
+
+### Useful links and tools
+
+There are some links and tools which are very useful when developing using PHPExcel. Please refer to the [PHPExcel CodePlex pages][2] for an update version of the list below.
+
+#### OpenXML / SpreadsheetML
+
+ - __File format documentation__
+[http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm][3]
+ - __OpenXML Explained e-book__
+[http://openxmldeveloper.org/articles/1970.aspx][4]
+ - __Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats__
+[http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en][5]
+ - __OpenXML Package Explorer__
+[http://www.codeplex.com/PackageExplorer/][6]
+
+
+### Frequently asked questions
+
+The up-to-date F.A.Q. page for PHPExcel can be found on [http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements][7].
+
+##### There seems to be a problem with character encoding...
+
+It is necessary to use UTF-8 encoding for all texts in PHPExcel. If the script uses different encoding then you can convert those texts with PHP's iconv() or mb_convert_encoding() functions.
+
+##### PHP complains about ZipArchive not being found
+
+Make sure you meet all requirements, especially php_zip extension should be enabled.
+
+The ZipArchive class is only required when reading or writing formats that use Zip compression (Excel2007 and OOCalc). Since version 1.7.6 the PCLZip library has been bundled with PHPExcel as an alternative to the ZipArchive class.
+
+This can be enabled by calling:
+```php
+PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
+```
+*before* calling the save method of the Excel2007 Writer.
+
+You can revert to using ZipArchive by calling:
+```php
+PHPExcel_Settings::setZipClass(PHPExcel_Settings::ZIPARCHIVE);
+```
+At present, this only allows you to write Excel2007 files without the need for ZipArchive (not to read Excel2007 or OOCalc)
+
+##### Excel 2007 cannot open the file generated by PHPExcel_Writer_2007 on Windows
+
+"Excel found unreadable content in '*.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes."
+
+Some older versions of the 5.2.x php_zip extension on Windows contain an error when creating ZIP files. The version that can be found on [http://snaps.php.net/win32/php5.2-win32-latest.zip][8] should work at all times.
+
+Alternatively, upgrading to at least PHP 5.2.9 should solve the problem.
+
+If you can't locate a clean copy of ZipArchive, then you can use the PCLZip library as an alternative when writing Excel2007 files, as described above.
+
+##### Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate yyy bytes) in zzz on line aaa
+
+PHPExcel holds an "in memory" representation of a spreadsheet, so it is susceptible to PHP's memory limitations. The memory made available to PHP can be increased by editing the value of the memory_limit directive in your php.ini file, or by using ini_set('memory_limit', '128M') within your code (ISP permitting).
+
+Some Readers and Writers are faster than others, and they also use differing amounts of memory. You can find some indication of the relative performance and memory usage for the different Readers and Writers, over the different versions of PHPExcel, on the [discussion board][9].
+
+If you've already increased memory to a maximum, or can't change your memory limit, then [this discussion][10] on the board describes some of the methods that can be applied to reduce the memory usage of your scripts using PHPExcel.
+
+##### Protection on my worksheet is not working?
+
+When you make use of any of the worksheet protection features (e.g. cell range protection, prohibiting deleting rows, ...), make sure you enable worksheet security. This can for example be done like this:
+```php
+$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
+```
+
+##### Feature X is not working with PHPExcel_Reader_Y / PHPExcel_Writer_Z
+
+Not all features of PHPExcel are implemented in all of the Reader / Writer classes. This is mostly due to underlying libraries not supporting a specific feature or not having implemented a specific feature.
+
+For example autofilter is not implemented in PEAR Spreadsheet_Excel_writer, which is the base of our Excel5 writer.
+
+We are slowly building up a list of features, together with the different readers and writers that support them, in the "Functionality Cross-Reference.xls" file in the /Documentation folder.
+
+##### Formulas don't seem to be calculated in Excel2003 using compatibility pack?
+
+This is normal behaviour of the compatibility pack, Excel2007 displays this correctly. Use PHPExcel_Writer_Excel5 if you really need calculated values, or force recalculation in Excel2003.
+
+##### Setting column width is not 100% accurate
+
+Trying to set column width, I experience one problem. When I open the file in Excel, the actual width is 0.71 less than it should be.
+
+The short answer is that PHPExcel uses a measure where padding is included. See section: "Setting a column's width" for more details.
+
+##### How do I use PHPExcel with my framework
+
+ - There are some instructions for using PHPExcel with Joomla on the [Joomla message board][11]
+ - A page of advice on using [PHPExcel in the Yii framework][12]
+ - [The Bakery][13] has some helper classes for reading and writing with PHPExcel within CakePHP
+ - Integrating [PHPExcel into Kohana 3][14] and [?????????? PHPExcel ? Kohana Framework][15]
+ - Using [PHPExcel with Typo3][16]
+
+##### Joomla Autoloader interferes with PHPExcel Autoloader
+
+Thanks to peterrlynch for the following advice on resolving issues between the [PHPExcel autoloader and Joomla Autoloader][17]
+
+
+#### Tutorials
+
+ - __English PHPExcel tutorial__
+ [http://openxmldeveloper.org][18]
+ - __French PHPExcel tutorial__
+ [http://g-ernaelsten.developpez.com/tutoriels/excel2007/][19]
+ - __A Japanese-language introduction to PHPExcel__
+ [http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html][21]
+
+
+ [2]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Documents&referringTitle=Home
+ [3]: http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm
+ [4]: http://openxmldeveloper.org/articles/1970.aspx
+ [5]: http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en
+ [6]: http://www.codeplex.com/PackageExplorer/
+ [7]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements
+ [8]: http://snaps.php.net/win32/php5.2-win32-latest.zip
+ [9]: http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=234150
+ [10]: http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=242712
+ [11]: http://http:/forum.joomla.org/viewtopic.php?f=304&t=433060
+ [12]: http://www.yiiframework.com/wiki/101/how-to-use-phpexcel-external-library-with-yii/
+ [13]: http://bakery.cakephp.org/articles/melgior/2010/01/26/simple-excel-spreadsheet-helper
+ [14]: http://www.flynsarmy.com/2010/07/phpexcel-module-for-kohana-3/
+ [15]: http://szpargalki.blogspot.com/2011/02/phpexcel-kohana-framework.html
+ [16]: http://typo3.org/documentation/document-library/extension-manuals/phpexcel_library/1.1.1/view/toc/0/
+ [17]: http://phpexcel.codeplex.com/discussions/211925
+ [18]: http://openxmldeveloper.org
+ [19]: http://g-ernaelsten.developpez.com/tutoriels/excel2007/
+ [20]: http://www.web-junior.net/sozdanie-excel-fajjlov-s-pomoshhyu-phpexcel/
+ [21]: http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html
+
+
+[^phpzip_footnote]: __php_zip__ is only needed by __PHPExcel_Reader_Excel2007__, __PHPExcel_Writer_Excel2007__ and __PHPExcel_Reader_OOCalc__. In other words, if you need PHPExcel to handle .xlsx or .ods files you will need the zip extension, but otherwise not.
';
+ echo 'Rows: ', $worksheet['totalRows'], ' Columns: ', $worksheet['totalColumns'], '
';
+ echo 'Cell Range: A1:', $worksheet['lastColumnLetter'], $worksheet['totalRows'];
+ echo '
You can remove this dependency for writing Excel2007 files (though not yet for reading) by using the PCLZip library that is bundled with PHPExcel. See the FAQ section of this document for details about this. PCLZip does have a dependency on PHP's zlib extension being enabled.
+
diff --git a/Documentation/markdown/Overview/02-Architecture.md b/Documentation/markdown/Overview/02-Architecture.md
new file mode 100644
index 000000000..8ddb43e2c
--- /dev/null
+++ b/Documentation/markdown/Overview/02-Architecture.md
@@ -0,0 +1,76 @@
+# PHPExcel Developer Documentation
+
+
+## Architecture
+
+### Schematical
+
+
+
+
+### Lazy Loader
+
+PHPExcel implements an autoloader or "lazy loader", which means that it is not necessary to include every file within PHPExcel. It is only necessary to include the initial PHPExcel class file, then the autoloader will include other class files as and when required, so only those files that are actually required by your script will be loaded into PHP memory. The main benefit of this is that it reduces the memory footprint of PHPExcel itself, so that it uses less PHP memory.
+
+If your own scripts already define an autoload function, then this may be overwritten by the PHPExcel autoload function. For example, if you have:
+```php
+function __autoload($class) {
+ ...
+}
+```
+Do this instead:
+```php
+function myAutoload($class) {
+ ...
+}
+
+spl_autoload_register('myAutoload');
+```
+Your autoloader will then co-exist with the autoloader of PHPExcel.
+
+
+### Spreadsheet in memory
+
+PHPExcel's architecture is built in a way that it can serve as an in-memory spreadsheet. This means that, if one would want to create a web based view of a spreadsheet which communicates with PHPExcel's object model, he would only have to write the front-end code.
+
+Just like desktop spreadsheet software, PHPExcel represents a spreadsheet containing one or more worksheets, which contain cells with data, formulas, images, ...
+
+
+### Readers and writers
+
+On its own, PHPExcel does not provide the functionality to read from or write to a persisted spreadsheet (on disk or in a database). To provide that functionality, readers and writers can be used.
+
+By default, the PHPExcel package provides some readers and writers, including one for the Open XML spreadsheet format (a.k.a. Excel 2007 file format). You are not limited to the default readers and writers, as you are free to implement the PHPExcel_Reader_IReader and PHPExcel_Writer_IWriter interface in a custom class.
+
+
+
+### Fluent interfaces
+
+PHPExcel supports fluent interfaces in most locations. This means that you can easily "chain" calls to specific methods without requiring a new PHP statement. For example, take the following code:
+
+```php
+$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
+$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
+$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
+$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
+$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
+$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");
+$objPHPExcel->getProperties()->setCategory("Test result file");
+```
+
+This can be rewritten as:
+
+```php
+$objPHPExcel->getProperties()
+ ->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
+```
+
+ > __Using fluent interfaces is not required__
+ > Fluent interfaces have been implemented to provide a convenient programming API. Use of them is not required, but can make your code easier to read and maintain.
+ > It can also improve performance, as you are reducing the overall number of calls to PHPExcel methods: in the above example, the `getProperties()` method is being called only once rather than 7 times in the non-fluent version.
diff --git a/Documentation/markdown/Overview/03-Creating-a-Spreadsheet.md b/Documentation/markdown/Overview/03-Creating-a-Spreadsheet.md
new file mode 100644
index 000000000..b65000bf5
--- /dev/null
+++ b/Documentation/markdown/Overview/03-Creating-a-Spreadsheet.md
@@ -0,0 +1,34 @@
+# PHPExcel Developer Documentation
+
+
+## Creating a spreadsheet
+
+### The PHPExcel class
+
+The PHPExcel class is the core of PHPExcel. It contains references to the contained worksheets, document security settings and document meta data.
+
+To simplify the PHPExcel concept: the PHPExcel class represents your workbook.
+
+Typically, you will create a workbook in one of two ways, either by loading it from a spreadsheet file, or creating it manually. A third option, though less commonly used, is cloning an existing workbook that has been created using one of the previous two methods.
+
+#### Loading a Workbook from a file
+
+Details of the different spreadsheet formats supported, and the options available to read them into a PHPExcel object are described fully in the PHPExcel User Documentation - Reading Spreadsheet Files document.
+
+```php
+$inputFileName = './sampleData/example1.xls';
+
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
+```
+
+#### Creating a new workbook
+
+If you want to create a new workbook, rather than load one from file, then you simply need to instantiate it as a new PHPExcel object.
+
+```php
+/** Create a new PHPExcel Object **/
+$objPHPExcel = new PHPExcel();
+```
+
+A new workbook will always be created with a single worksheet.
diff --git a/Documentation/markdown/Overview/04-Configuration-Settings.md b/Documentation/markdown/Overview/04-Configuration-Settings.md
new file mode 100644
index 000000000..2024e801e
--- /dev/null
+++ b/Documentation/markdown/Overview/04-Configuration-Settings.md
@@ -0,0 +1,140 @@
+# PHPExcel Developer Documentation
+
+
+## Configuration Settings
+
+Once you have included the PHPExcel files in your script, but before instantiating a PHPExcel object or loading a workbook file, there are a number of configuration options that can be set which will affect the subsequent behaviour of the script.
+
+### Cell Caching
+
+PHPExcel uses an average of about 1k/cell in your worksheets, so large workbooks can quickly use up available memory. Cell caching provides a mechanism that allows PHPExcel to maintain the cell objects in a smaller size of memory, on disk, or in APC, memcache or Wincache, rather than in PHP memory. This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data.
+
+By default, PHPExcel still holds all cell objects in memory, but you can specify alternatives. To enable cell caching, you must call the PHPExcel_Settings::setCacheStorageMethod() method, passing in the caching method that you wish to use.
+
+```php
+$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
+
+PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
+```
+
+setCacheStorageMethod() will return a boolean true on success, false on failure (for example if trying to cache to APC when APC is not enabled).
+
+A separate cache is maintained for each individual worksheet, and is automatically created when the worksheet is instantiated based on the caching method and settings that you have configured. You cannot change the configuration settings once you have started to read a workbook, or have created your first worksheet.
+
+Currently, the following caching methods are available.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_in_memory
+
+The default. If you don't initialise any caching method, then this is the method that PHPExcel will use. Cell objects are maintained in PHP memory as at present.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized
+
+Using this caching method, cells are held in PHP memory as an array of serialized objects, which reduces the memory footprint with minimal performance overhead.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip
+
+Like cache_in_memory_serialized, this method holds cells in PHP memory as an array of serialized objects, but gzipped to reduce the memory usage still further, although access to read or write a cell is slightly slower.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_igbinary
+
+Uses PHPs igbinary extension (if its available) to serialize cell objects in memory. This is normally faster and uses less memory than standard PHP serialization, but isnt available in most hosting environments.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_discISAM
+
+When using cache_to_discISAM all cells are held in a temporary disk file, with only an index to their location in that file maintained in PHP memory. This is slower than any of the cache_in_memory methods, but significantly reduces the memory footprint. By default, PHPExcel will use PHP's temp directory for the cache file, but you can specify a different directory when initialising cache_to_discISAM.
+
+```php
+$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
+$cacheSettings = array(
+ 'dir' => '/usr/local/tmp'
+);
+PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
+```
+
+The temporary disk file is automatically deleted when your script terminates.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp
+
+Like cache_to_discISAM, when using cache_to_phpTemp all cells are held in the php://temp I/O stream, with only an index to their location maintained in PHP memory. In PHP, the php://memory wrapper stores data in the memory: php://temp behaves similarly, but uses a temporary file for storing the data when a certain memory limit is reached. The default is 1 MB, but you can change this when initialising cache_to_phpTemp.
+
+```php
+$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
+$cacheSettings = array(
+ 'memoryCacheSize' => '8MB'
+);
+PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
+```
+
+The php://temp file is automatically deleted when your script terminates.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_apc
+
+When using cache_to_apc, cell objects are maintained in APC with only an index maintained in PHP memory to identify that the cell exists. By default, an APC cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising cache_to_APC.
+
+```php
+$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_APC;
+$cacheSettings = array(
+ 'cacheTime' => 600
+);
+PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
+```
+
+When your script terminates all entries will be cleared from APC, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_memcache
+
+When using cache_to_memcache, cell objects are maintained in memcache with only an index maintained in PHP memory to identify that the cell exists.
+
+By default, PHPExcel looks for a memcache server on localhost at port 11211. It also sets a memcache timeout limit of 600 seconds. If you are running memcache on a different server or port, then you can change these defaults when you initialise cache_to_memcache:
+
+```php
+$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache;
+$cacheSettings = array(
+ 'memcacheServer' => 'localhost',
+ 'memcachePort' => 11211,
+ 'cacheTime' => 600
+);
+PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
+```
+
+When your script terminates all entries will be cleared from memcache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_wincache
+
+When using cache_to_wincache, cell objects are maintained in Wincache with only an index maintained in PHP memory to identify that the cell exists. By default, a Wincache cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising cache_to_wincache.
+
+```php
+$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_wincache;
+$cacheSettings = array(
+ 'cacheTime' => 600
+);
+PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
+```
+
+When your script terminates all entries will be cleared from Wincache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_sqlite
+
+Uses an SQLite 2 "in-memory" database for caching cell data. Unlike other caching methods, neither cells nor an index are held in PHP memory - an indexed database table makes it unnecessary to hold any index in PHP memory, which makes this the most memory-efficient of the cell caching methods.
+
+#### PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3;
+
+Uses an SQLite 3 "in-memory" database for caching cell data. Unlike other caching methods, neither cells nor an index are held in PHP memory - an indexed database table makes it unnecessary to hold any index in PHP memory, which makes this the most memory-efficient of the cell caching methods.
+
+
+### Language/Locale
+
+Some localisation elements have been included in PHPExcel. You can set a locale by changing the settings. To set the locale to Brazilian Portuguese you would use:
+
+```php
+$locale = 'pt_br';
+$validLocale = PHPExcel_Settings::setLocale($locale);
+if (!$validLocale) {
+ echo 'Unable to set locale to ' . $locale . " - reverting to en_us" . PHP_EOL;
+}
+```
+
+If Brazilian Portuguese language files aren't available, then Portuguese will be enabled instead: if Portuguese language files aren't available, then the setLocale() method will return an error, and American English (en_us) settings will be used throughout.
+
+More details of the features available once a locale has been set, including a list of the languages and locales currently supported, can be found in the section of this document entitled "Locale Settings for Formulae".
+
diff --git a/Documentation/markdown/Overview/05-Deleting-a-Workbook.md b/Documentation/markdown/Overview/05-Deleting-a-Workbook.md
new file mode 100644
index 000000000..0ea91712f
--- /dev/null
+++ b/Documentation/markdown/Overview/05-Deleting-a-Workbook.md
@@ -0,0 +1,13 @@
+# PHPExcel Developer Documentation
+
+## Clearing a Workbook from memory
+
+The PHPExcel object contains cyclic references (e.g. the workbook is linked to the worksheets, and the worksheets are linked to their parent workbook) which cause problems when PHP tries to clear the objects from memory when they are unset(), or at the end of a function when they are in local scope. The result of this is "memory leaks", which can easily use a large amount of PHP's limited memory.
+
+This can only be resolved manually: if you need to unset a workbook, then you also need to "break" these cyclic references before doing so. PHPExcel provides the disconnectWorksheets() method for this purpose.
+
+```php
+$objPHPExcel->disconnectWorksheets();
+
+unset($objPHPExcel);
+```
diff --git a/Documentation/markdown/Overview/06-Worksheets.md b/Documentation/markdown/Overview/06-Worksheets.md
new file mode 100644
index 000000000..a6a231ccf
--- /dev/null
+++ b/Documentation/markdown/Overview/06-Worksheets.md
@@ -0,0 +1,94 @@
+# PHPExcel Developer Documentation
+
+## Worksheets
+
+A worksheet is a collection of cells, formulae, images, graphs, etc. It holds all data necessary to represent a spreadsheet worksheet.
+
+When you load a workbook from a spreadsheet file, it will be loaded with all its existing worksheets (unless you specified that only certain sheets should be loaded). When you load from non-spreadsheet files (such as a CSV or HTML file) or from spreadsheet formats that don't identify worksheets by name (such as SYLK), then a single worksheet called "WorkSheet1" will be created containing the data from that file.
+
+When you instantiate a new workbook, PHPExcel will create it with a single worksheet called "WorkSheet1"�.
+
+The `getSheetCount()` method will tell you the number of worksheets in the workbook; while the `getSheetNames()` method will return a list of all worksheets in the workbook, indexed by the order in which their "tabs" would appear when opened in MS Excel (or other appropriate Spreadsheet program).
+
+Individual worksheets can be accessed by name, or by their index position in the workbook. The index position represents the order that each worksheet "tab" is shown when the workbook is opened in MS Excel (or other appropriate Spreadsheet program). To access a sheet by its index, use the `getSheet()` method.
+
+```php
+// Get the second sheet in the workbook
+// Note that sheets are indexed from 0
+$objPHPExcel->getSheet(1);
+```
+
+If you don't specify a sheet index, then the first worksheet will be returned.
+
+Methods also exist allowing you to reorder the worksheets in the workbook.
+
+To access a sheet by name, use the `getSheetByName()` method, specifying the name of the worksheet that you want to access.
+
+```php
+// Retrieve the worksheet called 'Worksheet 1'
+$objPHPExcel->getSheetByName('Worksheet 1');
+```
+
+Alternatively, one worksheet is always the currently active worksheet, and you can access that directly. The currently active worksheet is the one that will be active when the workbook is opened in MS Excel (or other appropriate Spreadsheet program).
+
+```php
+// Retrieve the current active worksheet
+$objPHPExcel->getActiveSheet();
+```
+
+You can change the currently active sheet by index or by name using the `setActiveSheetIndex()` and `setActiveSheetIndexByName()` methods.
+
+### Adding a new Worksheet
+
+You can add a new worksheet to the workbook using the `createSheet()` method of the PHPExcel object. By default, this will be created as a new "last�" sheet; but you can also specify an index position as an argument, and the worksheet will be inserted at that position, shuffling all subsequent worksheets in the collection down a place.
+
+```php
+$objPHPExcel->createSheet();
+```
+
+A new worksheet created using this method will be called "Worksheet\' . PHP_EOL;
+foreach ($objWorksheet->getRowIterator() as $row) {
+ echo '
' . PHP_EOL;
+```
+
+Note that we have set the cell iterator's `setIterateOnlyExistingCells()` to FALSE. This makes the iterator loop all cells within the worksheet range, even if they have not been set.
+
+The cell iterator will return a __NULL__ as the cell value if it is not set in the worksheet.
+Setting the cell iterator's setIterateOnlyExistingCells() to FALSE will loop all cells in the worksheet that can be available at that moment. This will create new cells if required and increase memory usage! Only use it if it is intended to loop all cells that are possibly available.
+
+#### Looping through cells using indexes
+
+One can use the possibility to access cell values by column and row index like (0,1) instead of 'A1' for reading and writing cell values in loops.
+
+Note: In PHPExcel column index is 0-based while row index is 1-based. That means 'A1' ~ (0,1)
+
+Below is an example where we read all the values in a worksheet and display them in a table.
+
+```php
+$objReader = PHPExcel_IOFactory::createReader('Excel2007');
+$objReader->setReadDataOnly(TRUE);
+$objPHPExcel = $objReader->load("test.xlsx");
+
+$objWorksheet = $objPHPExcel->getActiveSheet();
+// Get the highest row and column numbers referenced in the worksheet
+$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
+$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
+$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
+
+echo '' . PHP_EOL;
+ $cellIterator = $row->getCellIterator();
+ $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
+ // even if a cell value is not set.
+ // By default, only cells that have a value
+ // set will be iterated.
+ foreach ($cellIterator as $cell) {
+ echo ' ' . PHP_EOL;
+}
+echo '' .
+ $cell->getValue() .
+ ' ' . PHP_EOL;
+ }
+ echo '' . "\n";
+for ($row = 1; $row <= $highestRow; ++$row) {
+ echo '
' . PHP_EOL;
+```
+
+Alternatively, you can take advantage of PHP's "Perl-style" character incrementors to loop through the cells by coordinate:
+
+```php
+$objReader = PHPExcel_IOFactory::createReader('Excel2007');
+$objReader->setReadDataOnly(TRUE);
+$objPHPExcel = $objReader->load("test.xlsx");
+
+$objWorksheet = $objPHPExcel->getActiveSheet();
+// Get the highest row number and column letter referenced in the worksheet
+$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
+$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
+// Increment the highest column letter
+$highestColumn++;
+
+echo '' . PHP_EOL;
+ for ($col = 0; $col <= $highestColumnIndex; ++$col) {
+ echo ' ' . PHP_EOL;
+}
+echo '' .
+ $objWorksheet->getCellByColumnAndRow($col, $row)
+ ->getValue() .
+ ' ' . PHP_EOL;
+ }
+ echo '' . "\n";
+for ($row = 1; $row <= $highestRow; ++$row) {
+ echo '
' . PHP_EOL;
+```
+
+Note that we can't use a <= comparison here, because 'AA' would match as <= 'B', so we increment the highest column letter and then loop while $col != the incremented highest column.
+
+### Using value binders to facilitate data entry
+
+Internally, PHPExcel uses a default PHPExcel_Cell_IValueBinder implementation (PHPExcel_Cell_DefaultValueBinder) to determine data types of entered data using a cell's `setValue()` method (the `setValueExplicit()` method bypasses this check).
+
+Optionally, the default behaviour of PHPExcel can be modified, allowing easier data entry. For example, a PHPExcel_Cell_AdvancedValueBinder class is available. It automatically converts percentages, number in scientific format, and dates entered as strings to the correct format, also setting the cell's style information. The following example demonstrates how to set the value binder in PHPExcel:
+
+```php
+/** PHPExcel */
+require_once 'PHPExcel.php';
+
+// Set value binder
+PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
+
+// Create new PHPExcel object
+$objPHPExcel = new PHPExcel();
+
+// ...
+// Add some data, resembling some different data types
+$objPHPExcel->getActiveSheet()->setCellValue('A4', 'Percentage value:');
+// Converts the string value to 0.1 and sets percentage cell style
+$objPHPExcel->getActiveSheet()->setCellValue('B4', '10%');
+
+$objPHPExcel->getActiveSheet()->setCellValue('A5', 'Date/time value:');
+// Converts the string value to an Excel datestamp and sets the date format cell style
+$objPHPExcel->getActiveSheet()->setCellValue('B5', '21 December 1983');
+```
+
+__Creating your own value binder is easy.__
+When advanced value binding is required, you can implement the PHPExcel_Cell_IValueBinder interface or extend the PHPExcel_Cell_DefaultValueBinder or PHPExcel_Cell_AdvancedValueBinder classes.
+
diff --git a/Documentation/markdown/Overview/08-Recipes.md b/Documentation/markdown/Overview/08-Recipes.md
new file mode 100644
index 000000000..b8930a44c
--- /dev/null
+++ b/Documentation/markdown/Overview/08-Recipes.md
@@ -0,0 +1,1214 @@
+# PHPExcel Developer Documentation
+
+## PHPExcel recipes
+
+The following pages offer you some widely-used PHPExcel recipes. Please note that these do NOT offer complete documentation on specific PHPExcel API functions, but just a bump to get you started. If you need specific API functions, please refer to the API documentation.
+
+For example, REF _Ref191885321 \w \h 4.4.7 REF _Ref191885321 \h Setting a worksheet's page orientation and size covers setting a page orientation to A4. Other paper formats, like US Letter, are not covered in this document, but in the PHPExcel API documentation.
+
+### Setting a spreadsheet's metadata
+
+PHPExcel allows an easy way to set a spreadsheet's metadata, using document property accessors. Spreadsheet metadata can be useful for finding a specific document in a file repository or a document management system. For example Microsoft Sharepoint uses document metadata to search for a specific document in its document lists.
+
+Setting spreadsheet metadata is done as follows:
+
+```php
+$objPHPExcel->getProperties()
+ ->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw");
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription(
+ "Test document for Office 2007 XLSX, generated using PHP classes."
+ )
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
+```
+
+### Setting a spreadsheet's active sheet
+
+The following line of code sets the active sheet index to the first sheet:
+
+```php
+$objPHPExcel->setActiveSheetIndex(0);
+```
+
+You can also set the active sheet by its name/title
+
+```php
+$objPHPExcel->setActiveSheetIndexByName('DataSheet')
+```
+
+will change the currently active sheet to the worksheet called "DataSheet".
+
+### Write a date or time into a cell
+
+In Excel, dates and Times are stored as numeric values counting the number of days elapsed since 1900-01-01. For example, the date '2008-12-31' is represented as 39813. You can verify this in Microsoft Office Excel by entering that date in a cell and afterwards changing the number format to 'General' so the true numeric value is revealed. Likewise, '3:15 AM' is represented as 0.135417.
+
+PHPExcel works with UST (Universal Standard Time) date and Time values, but does no internal conversions; so it is up to the developer to ensure that values passed to the date/time conversion functions are UST.
+
+Writing a date value in a cell consists of 2 lines of code. Select the method that suits you the best. Here are some examples:
+
+```php
+/* PHPExcel_Cell_AdvanceValueBinder required for this sample */
+require_once 'PHPExcel/Cell/AdvancedValueBinder.php';
+
+// MySQL-like timestamp '2008-12-31' or date string
+PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
+
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('D1', '2008-12-31');
+
+$objPHPExcel->getActiveSheet()->getStyle('D1')
+ ->getNumberFormat()
+ ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
+
+// PHP-time (Unix time)
+$time = gmmktime(0,0,0,12,31,2008); // int(1230681600)
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('D1', PHPExcel_Shared_Date::PHPToExcel($time));
+$objPHPExcel->getActiveSheet()->getStyle('D1')
+ ->getNumberFormat()
+ ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
+
+// Excel-date/time
+$objPHPExcel->getActiveSheet()->setCellValue('D1', 39813)
+$objPHPExcel->getActiveSheet()->getStyle('D1')
+ ->getNumberFormat()
+ ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
+```
+
+The above methods for entering a date all yield the same result. PHPExcel_Style_NumberFormat provides a lot of pre-defined date formats.
+
+The PHPExcel_Shared_Date::PHPToExcel() method will also work with a PHP DateTime object.
+
+Similarly, times (or date and time values) can be entered in the same fashion: just remember to use an appropriate format code.
+
+__Notes:__
+
+See section "Using value binders to facilitate data entry" to learn more about the AdvancedValueBinder used in the first example.
+In previous versions of PHPExcel up to and including 1.6.6, when a cell had a date-like number format code, it was possible to enter a date directly using an integer PHP-time without converting to Excel date format. Starting with PHPExcel 1.6.7 this is no longer supported.
+Excel can also operate in a 1904-based calendar (default for workbooks saved on Mac). Normally, you do not have to worry about this when using PHPExcel.
+
+### Write a formula into a cell
+
+Inside the Excel file, formulas are always stored as they would appear in an English version of Microsoft Office Excel, and PHPExcel handles all formulae internally in this format. This means that the following rules hold:
+
+ - Decimal separator is '.' (period)
+ - Function argument separator is ',' (comma)
+ - Matrix row separator is ';' (semicolon)
+ - English function names must be used
+
+This is regardless of which language version of Microsoft Office Excel may have been used to create the Excel file.
+
+When the final workbook is opened by the user, Microsoft Office Excel will take care of displaying the formula according the applications language. Translation is taken care of by the application!
+
+The following line of code writes the formula '=IF(C4>500,"profit","loss")' into the cell B8. Note that the formula must start with "=" to make PHPExcel recognise this as a formula.
+
+```php
+$objPHPExcel->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")');
+```
+
+If you want to write a string beginning with an "=" character to a cell, then you should use the setCellValueExplicit() method.
+
+```php
+$objPHPExcel->getActiveSheet()
+ ->setCellValueExplicit(
+ 'B8',
+ '=IF(C4>500,"profit","loss")',
+ PHPExcel_Cell_DataType::TYPE_STRING
+ );
+```
+
+A cell's formula can be read again using the following line of code:
+
+```php
+$formula = $objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
+```
+
+If you need the calculated value of a cell, use the following code. This is further explained in REF _Ref191885372 \w \h \* MERGEFORMAT 4.4.35.
+
+```php
+$value = $objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
+```
+
+### Locale Settings for Formulae
+
+Some localisation elements have been included in PHPExcel. You can set a locale by changing the settings. To set the locale to Russian you would use:
+
+```php
+$locale = 'ru';
+$validLocale = PHPExcel_Settings::setLocale($locale);
+if (!$validLocale) {
+ echo 'Unable to set locale to '.$locale." - reverting to en_us' . PHP_EOL;
+ for ($col = 'A'; $col != $highestColumn; ++$col) {
+ echo ' ' . PHP_EOL;
+}
+echo '' .
+ $objWorksheet->getCell($col . $row)
+ ->getValue() .
+ ' ' . PHP_EOL;
+ }
+ echo '
\n";
+}
+```
+
+If Russian language files aren't available, the `setLocale()` method will return an error, and English settings will be used throughout.
+
+Once you have set a locale, you can translate a formula from its internal English coding.
+
+```php
+$formula = $objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
+$translatedFormula = PHPExcel_Calculation::getInstance()->_translateFormulaToLocale($formula);
+```
+
+You can also create a formula using the function names and argument separators appropriate to the defined locale; then translate it to English before setting the cell value:
+
+```php
+$formula = '=????360(????(2010;2;5);????(2010;12;31);??????)';
+$internalFormula = PHPExcel_Calculation::getInstance()->translateFormulaToEnglish($formula);
+$objPHPExcel->getActiveSheet()->setCellValue('B8',$internalFormula);
+```
+
+Currently, formula translation only translates the function names, the constants TRUE and FALSE, and the function argument separators.
+
+At present, the following locale settings are supported:
+
+ Language | | Locale Code
+ ---------------------|----------------------|-------------
+ Czech | Ceština | cs
+ Danish | Dansk | da
+ German | Deutsch | de
+ Spanish | Español | es
+ Finnish | Suomi | fi
+ French | Français | fr
+ Hungarian | Magyar | hu
+ Italian | Italiano | it
+ Dutch | Nederlands | nl
+ Norwegian | Norsk | no
+ Polish | Jezyk polski | pl
+ Portuguese | Português | pt
+ Brazilian Portuguese | Português Brasileiro | pt_br
+ Russian | ??????? ???? | ru
+ Swedish | Svenska | sv
+ Turkish | Türkçe | tr
+
+### Write a newline character "\n" in a cell (ALT+"Enter")
+
+In Microsoft Office Excel you get a line break in a cell by hitting ALT+"Enter". When you do that, it automatically turns on "wrap text" for the cell.
+
+Here is how to achieve this in PHPExcel:
+
+```php
+$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
+$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
+```
+
+__Tip__
+
+Read more about formatting cells using getStyle() elsewhere.
+
+__Tip__
+
+AdvancedValuebinder.php automatically turns on "wrap text" for the cell when it sees a newline character in a string that you are inserting in a cell. Just like Microsoft Office Excel. Try this:
+
+```php
+require_once 'PHPExcel/Cell/AdvancedValueBinder.php';
+PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
+
+$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
+```
+
+Read more about AdvancedValueBinder.php elsewhere.
+
+### Explicitly set a cell's datatype
+
+You can set a cell's datatype explicitly by using the cell's setValueExplicit method, or the setCellValueExplicit method of a worksheet. Here's an example:
+
+```php
+$objPHPExcel->getActiveSheet()->getCell('A1')
+ ->setValueExplicit(
+ '25',
+ PHPExcel_Cell_DataType::TYPE_NUMERIC
+ );
+```
+
+### Change a cell into a clickable URL
+
+You can make a cell a clickable URL by setting its hyperlink property:
+
+```php
+$objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
+$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('http://www.phpexcel.net/');
+```
+
+If you want to make a hyperlink to another worksheet/cell, use the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
+$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");
+```
+
+### Setting Printer Options for Excel files
+
+#### Setting a worksheet's page orientation and size
+
+Setting a worksheet's page orientation and size can be done using the following lines of code:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageSetup()
+ ->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
+$objPHPExcel->getActiveSheet()->getPageSetup()
+ ->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
+```
+
+Note that there are additional page settings available. Please refer to the API documentation for all possible options.
+
+#### Page Setup: Scaling options
+
+The page setup scaling options in PHPExcel relate directly to the scaling options in the "Page Setup" dialog as shown in the illustration.
+
+Default values in PHPExcel correspond to default values in MS Office Excel as shown in illustration
+
+
+
+ method | initial value | calling method will trigger | Note
+ --------------------|:-------------:|-----------------------------|------
+ setFitToPage(...) | FALSE | - |
+ setScale(...) | 100 | setFitToPage(FALSE) |
+ setFitToWidth(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-width
+ setFitToHeight(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-height
+
+##### Example
+
+Here is how to fit to 1 page wide by infinite pages tall:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageSetup()->setFitToWidth(1);
+$objPHPExcel->getActiveSheet()->getPageSetup()->setFitToHeight(0);
+```
+
+As you can see, it is not necessary to call setFitToPage(TRUE) since setFitToWidth(...) and setFitToHeight(...) triggers this.
+
+If you use setFitToWidth() you should in general also specify setFitToHeight() explicitly like in the example. Be careful relying on the initial values. This is especially true if you are upgrading from PHPExcel 1.7.0 to 1.7.1 where the default values for fit-to-height and fit-to-width changed from 0 to 1.
+
+#### Page margins
+
+To set page margins for a worksheet, use this code:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageMargins()->setTop(1);
+$objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0.75);
+$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0.75);
+$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(1);
+```
+
+Note that the margin values are specified in inches.
+
+
+
+#### Center a page horizontally/vertically
+
+To center a page horizontally/vertically, you can use the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
+$objPHPExcel->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
+```
+
+#### Setting the print header and footer of a worksheet
+
+Setting a worksheet's print header and footer can be done using the following lines of code:
+
+```php
+$objPHPExcel->getActiveSheet()->getHeaderFooter()
+ ->setOddHeader('&C&HPlease treat this document as confidential!');
+$objPHPExcel->getActiveSheet()->getHeaderFooter()
+ ->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');
+```
+
+Substitution and formatting codes (starting with &) can be used inside headers and footers. There is no required order in which these codes must appear.
+
+The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again:
+
+ - Strikethrough
+ - Superscript
+ - Subscript
+
+Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, while the first is ON.
+
+The following codes are supported by Excel2007:
+
+Code | Meaning
+-----------------------|-----------
+&L | Code for "left section" (there are three header / footer locations, "left", "center", and "right"). When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the left section.
+&P | Code for "current page #"
+&N | Code for "total pages"
+&font size | Code for "text font size", where font size is a font size in points.
+&K | Code for "text font color" - RGB Color is specified as RRGGBB Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade value, NN is the tint/shade value.
+&S | Code for "text strikethrough" on / off
+&X | Code for "text super script" on / off
+&Y | Code for "text subscript" on / off
+&C | Code for "center section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the center section.
+&D | Code for "date"
+&T | Code for "time"
+&G | Code for "picture as background" - Please make sure to add the image to the header/footer[^print-footer-image-footnote]
+&U | Code for "text single underline"
+&E | Code for "double underline"
+&R | Code for "right section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the right section.
+&Z | Code for "this workbook's file path"
+&F | Code for "this workbook's file name"
+&A | Code for "sheet tab name"
+&+ | Code for add to page #
+&- | Code for subtract from page #
+&"font name,font type" | Code for "text font name" and "text font type", where font name and font type are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font name, it means "none specified". Both of font name and font type can be localized values.
+&"-,Bold" | Code for "bold font style"
+&B | Code for "bold font style"
+&"-,Regular" | Code for "regular font style"
+&"-,Italic" | Code for "italic font style"
+&I | Code for "italic font style"
+&"-,Bold Italic" | Code for "bold italic font style"
+&O | Code for "outline style"
+&H | Code for "shadow style"
+
+ [^print-footer-image-footnote]: z
+```php
+$objDrawing = new PHPExcel_Worksheet_HeaderFooterDrawing();
+$objDrawing->setName('PHPExcel logo');
+$objDrawing->setPath('./images/phpexcel_logo.gif');
+$objDrawing->setHeight(36);
+$objPHPExcel->getActiveSheet()->getHeaderFooter()->addImage($objDrawing, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);
+```
+
+__Tip__
+
+The above table of codes may seem overwhelming first time you are trying to figure out how to write some header or footer. Luckily, there is an easier way. Let Microsoft Office Excel do the work for you.For example, create in Microsoft Office Excel an xlsx file where you insert the header and footer as desired using the programs own interface. Save file as test.xlsx. Now, take that file and read off the values using PHPExcel as follows:
+
+```php
+$objPHPexcel = PHPExcel_IOFactory::load('test.xlsx');
+$objWorksheet = $objPHPexcel->getActiveSheet();
+
+var_dump($objWorksheet->getHeaderFooter()->getOddFooter());
+var_dump($objWorksheet->getHeaderFooter()->getEvenFooter());
+var_dump($objWorksheet->getHeaderFooter()->getOddHeader());
+var_dump($objWorksheet->getHeaderFooter()->getEvenHeader());
+```
+
+That reveals the codes for the even/odd header and footer. Experienced users may find it easier to rename test.xlsx to test.zip, unzip it, and inspect directly the contents of the relevant xl/worksheets/sheetX.xml to find the codes for header/footer.
+
+#### Setting printing breaks on a row or column
+
+To set a print break, use the following code, which sets a row break on row 10.
+
+```php
+$objPHPExcel->getActiveSheet()->setBreak( 'A10' , PHPExcel_Worksheet::BREAK_ROW );
+```
+
+The following line of code sets a print break on column D:
+
+```php
+$objPHPExcel->getActiveSheet()->setBreak( 'D10' , PHPExcel_Worksheet::BREAK_COLUMN );
+```
+
+#### Show/hide gridlines when printing
+
+To show/hide gridlines when printing, use the following code:
+
+$objPHPExcel->getActiveSheet()->setShowGridlines(true);
+
+#### Setting rows/columns to repeat at top/left
+
+PHPExcel can repeat specific rows/cells at top/left of a page. The following code is an example of how to repeat row 1 to 5 on each printed page of a specific worksheet:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
+```
+
+#### Specify printing area
+
+To specify a worksheet's printing area, use the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5');
+```
+
+There can also be multiple printing areas in a single worksheet:
+
+```php
+$objPHPExcel->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20');
+```
+
+### Styles
+
+#### Formatting cells
+
+A cell can be formatted with font, border, fill, ... style information. For example, one can set the foreground colour of a cell to red, aligned to the right, and the border to black and thick border style. Let's do that on cell B2:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
+$objPHPExcel->getActiveSheet()->getStyle('B2')
+ ->getFill()->getStartColor()->setARGB('FFFF0000');
+```
+
+Starting with PHPExcel 1.7.0 getStyle() also accepts a cell range as a parameter. For example, you can set a red background color on a range of cells:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
+ ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
+ ->getStartColor()->setARGB('FFFF0000');
+```
+
+__Tip__
+It is recommended to style many cells at once, using e.g. getStyle('A1:M500'), rather than styling the cells individually in a loop. This is much faster compared to looping through cells and styling them individually.
+
+There is also an alternative manner to set styles. The following code sets a cell's style to font bold, alignment right, top border thin and a gradient fill:
+
+```php
+$styleArray = array(
+ 'font' => array(
+ 'bold' => true,
+ ),
+ 'alignment' => array(
+ 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
+ ),
+ 'borders' => array(
+ 'top' => array(
+ 'style' => PHPExcel_Style_Border::BORDER_THIN,
+ ),
+ ),
+ 'fill' => array(
+ 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
+ 'rotation' => 90,
+ 'startcolor' => array(
+ 'argb' => 'FFA0A0A0',
+ ),
+ 'endcolor' => array(
+ 'argb' => 'FFFFFFFF',
+ ),
+ ),
+);
+
+$objPHPExcel->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
+```
+
+Or with a range of cells:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('B3:B7')->applyFromArray($styleArray);
+```
+
+This alternative method using arrays should be faster in terms of execution whenever you are setting more than one style property. But the difference may barely be measurable unless you have many different styles in your workbook.
+
+Prior to PHPExcel 1.7.0 duplicateStyleArray() was the recommended method for styling a cell range, but this method has now been deprecated since getStyle() has started to accept a cell range.
+
+#### Number formats
+
+You often want to format numbers in Excel. For example you may want a thousands separator plus a fixed number of decimals after the decimal separator. Or perhaps you want some numbers to be zero-padded.
+
+In Microsoft Office Excel you may be familiar with selecting a number format from the "Format Cells" dialog. Here there are some predefined number formats available including some for dates. The dialog is designed in a way so you don't have to interact with the underlying raw number format code unless you need a custom number format.
+
+In PHPExcel, you can also apply various predefined number formats. Example:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
+ ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
+```
+
+This will format a number e.g. 1587.2 so it shows up as 1,587.20 when you open the workbook in MS Office Excel. (Depending on settings for decimal and thousands separators in Microsoft Office Excel it may show up as 1.587,20)
+
+You can achieve exactly the same as the above by using this:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
+ ->setFormatCode('#,##0.00');
+```
+
+In Microsoft Office Excel, as well as in PHPExcel, you will have to interact with raw number format codes whenever you need some special custom number format. Example:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
+ ->setFormatCode('[Blue][>=3000]$#,##0;[Red][<0]$#,##0;$#,##0');
+```
+
+Another example is when you want numbers zero-padded with leading zeros to a fixed length:
+
+```php
+$objPHPExcel->getActiveSheet()->getCell('A1')->setValue(19);
+$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
+ ->setFormatCode('0000'); // will show as 0019 in Excel
+```
+
+__Tip__
+The rules for composing a number format code in Excel can be rather complicated. Sometimes you know how to create some number format in Microsoft Office Excel, but don't know what the underlying number format code looks like. How do you find it?
+
+The readers shipped with PHPExcel come to the rescue. Load your template workbook using e.g. Excel2007 reader to reveal the number format code. Example how read a number format code for cell A1:
+
+```php
+$objReader = PHPExcel_IOFactory::createReader('Excel2007');
+$objPHPExcel = $objReader->load('template.xlsx');
+var_dump($objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->getFormatCode());
+```
+
+Advanced users may find it faster to inspect the number format code directly by renaming template.xlsx to template.zip, unzipping, and looking for the relevant piece of XML code holding the number format code in *xl/styles.xml*.
+
+#### Alignment and wrap text
+
+Let's set vertical alignment to the top for cells A1:D4
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('A1:D4')
+ ->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP);
+```
+
+Here is how to achieve wrap text:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('A1:D4')
+ ->getAlignment()->setWrapText(true);
+```
+
+#### Setting the default style of a workbook
+
+It is possible to set the default style of a workbook. Let's set the default font to Arial size 8:
+
+```php
+$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
+$objPHPExcel->getDefaultStyle()->getFont()->setSize(8);
+```
+
+#### Styling cell borders
+
+In PHPExcel it is easy to apply various borders on a rectangular selection. Here is how to apply a thick red border outline around cells B2:G8.
+
+```php
+$styleArray = array(
+ 'borders' => array(
+ 'outline' => array(
+ 'style' => PHPExcel_Style_Border::BORDER_THICK,
+ 'color' => array('argb' => 'FFFF0000'),
+ ),
+ ),
+);
+
+$objWorksheet->getStyle('B2:G8')->applyFromArray($styleArray);
+```
+
+In Microsoft Office Excel, the above operation would correspond to selecting the cells B2:G8, launching the style dialog, choosing a thick red border, and clicking on the "Outline" border component.
+
+Note that the border outline is applied to the rectangular selection B2:G8 as a whole, not on each cell individually.
+
+You can achieve any border effect by using just the 5 basic borders and operating on a single cell at a time:
+
+ Array key | Maps to property
+ ----------|------------------
+ left | getLeft()
+ right | getRight()
+ top | getTop()
+ bottom | getBottom()
+ diagonal | getDiagonal()
+
+Additional shortcut borders come in handy like in the example above. These are the shortcut borders available:
+
+ Array key | Maps to property
+ -----------|------------------
+ allborders | getAllBorders()
+ outline | getOutline()
+ inside | getInside()
+ vertical | getVertical()
+ horizontal | getHorizontal()
+
+
+
+An overview of all border shortcuts can be seen in the following image:
+
+
+
+If you simultaneously set e.g. allborders and vertical, then we have "overlapping" borders, and one of the components has to win over the other where there is border overlap. In PHPExcel, from weakest to strongest borders, the list is as follows: allborders, outline/inside, vertical/horizontal, left/right/top/bottom/diagonal.
+
+This border hierarchy can be utilized to achieve various effects in an easy manner.
+
+### Conditional formatting a cell
+
+A cell can be formatted conditionally, based on a specific rule. For example, one can set the foreground colour of a cell to red if its value is below zero, and to green if its value is zero or more.
+
+One can set a conditional style ruleset to a cell using the following code:
+
+```php
+$objConditional1 = new PHPExcel_Style_Conditional();
+$objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
+$objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN);
+$objConditional1->addCondition('0');
+$objConditional1->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);
+$objConditional1->getStyle()->getFont()->setBold(true);
+
+$objConditional2 = new PHPExcel_Style_Conditional();
+$objConditional2->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
+$objConditional2->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_GREATERTHANOREQUAL);
+$objConditional2->addCondition('0');
+$objConditional2->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_GREEN);
+$objConditional2->getStyle()->getFont()->setBold(true);
+
+$conditionalStyles = $objPHPExcel->getActiveSheet()->getStyle('B2')->getConditionalStyles();
+array_push($conditionalStyles, $objConditional1);
+array_push($conditionalStyles, $objConditional2);
+
+$objPHPExcel->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles);
+```
+
+If you want to copy the ruleset to other cells, you can duplicate the style object:
+
+```php
+$objPHPExcel->getActiveSheet()
+ ->duplicateStyle(
+ $objPHPExcel->getActiveSheet()->getStyle('B2'),
+ 'B3:B7'
+ );
+```
+
+### Add a comment to a cell
+
+To add a comment to a cell, use the following code. The example below adds a comment to cell E11:
+
+```php
+$objPHPExcel->getActiveSheet()
+ ->getComment('E11')
+ ->setAuthor('Mark Baker');
+$objCommentRichText = $objPHPExcel->getActiveSheet()
+ ->getComment('E11')
+ ->getText()->createTextRun('PHPExcel:');
+$objCommentRichText->getFont()->setBold(true);
+$objPHPExcel->getActiveSheet()
+ ->getComment('E11')
+ ->getText()->createTextRun("\r\n");
+$objPHPExcel->getActiveSheet()
+ ->getComment('E11')
+ ->getText()->createTextRun('Total amount on the current invoice, excluding VAT.');
+```
+
+
+
+### Apply autofilter to a range of cells
+
+To apply an autofilter to a range of cells, use the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->setAutoFilter('A1:C9');
+```
+
+__Make sure that you always include the complete filter range!__
+Excel does support setting only the captionrow, but that's __not__ a best practice...
+
+### Setting security on a spreadsheet
+
+Excel offers 3 levels of "protection": document security, sheet security and cell security.
+
+Document security allows you to set a password on a complete spreadsheet, allowing changes to be made only when that password is entered.Worksheet security offers other security options: you can disallow inserting rows on a specific sheet, disallow sorting, ... Cell security offers the option to lock/unlock a cell as well as show/hide the internal formulaAn example on setting document security:
+
+```php
+$objPHPExcel->getSecurity()->setLockWindows(true);
+$objPHPExcel->getSecurity()->setLockStructure(true);
+$objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel");
+```
+
+An example on setting worksheet security:
+
+```php
+$objPHPExcel->getActiveSheet()
+ ->getProtection()->setPassword('PHPExcel');
+$objPHPExcel->getActiveSheet()
+ ->getProtection()->setSheet(true);
+$objPHPExcel->getActiveSheet()
+ ->getProtection()->setSort(true);
+$objPHPExcel->getActiveSheet()
+ ->getProtection()->setInsertRows(true);
+$objPHPExcel->getActiveSheet()
+ ->getProtection()->setFormatCells(true);
+```
+
+An example on setting cell security:
+
+```php
+$objPHPExcel->getActiveSheet()->getStyle('B1')
+ ->getProtection()
+ ->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
+```
+
+__Make sure you enable worksheet protection if you need any of the worksheet protection features!__ This can be done using the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
+```
+
+### Setting data validation on a cell
+
+Data validation is a powerful feature of Excel2007. It allows to specify an input filter on the data that can be inserted in a specific cell. This filter can be a range (i.e. value must be between 0 and 10), a list (i.e. value must be picked from a list), ...
+
+The following piece of code only allows numbers between 10 and 20 to be entered in cell B3:
+
+```php
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B3')
+ ->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
+$objValidation->setAllowBlank(true);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Number is not allowed!');
+$objValidation->setPromptTitle('Allowed input');
+$objValidation->setPrompt('Only numbers between 10 and 20 are allowed.');
+$objValidation->setFormula1(10);
+$objValidation->setFormula2(20);
+```
+
+This validation will limit the length of text that can be entered in a cell to 6 characters.
+
+```
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B9')->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
+$objValidation->setAllowBlank(true);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Text exceeds maximum length');
+$objValidation->setPromptTitle('Allowed input');
+$objValidation->setPrompt('Maximum text length is 6 characters.');
+$objValidation->setFormula1(6);
+```
+
+The following piece of code only allows an item picked from a list of data to be entered in cell B3:
+
+```php
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B5')
+ ->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
+$objValidation->setAllowBlank(false);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setShowDropDown(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Value is not in list.');
+$objValidation->setPromptTitle('Pick from list');
+$objValidation->setPrompt('Please pick a value from the drop-down list.');
+$objValidation->setFormula1('"Item A,Item B,Item C"');
+```
+
+When using a data validation list like above, make sure you put the list between " and " and that you split the items with a comma (,).
+
+It is important to remember that any string participating in an Excel formula is allowed to be maximum 255 characters (not bytes). This sets a limit on how many items you can have in the string "Item A,Item B,Item C". Therefore it is normally a better idea to type the item values directly in some cell range, say A1:A3, and instead use, say, $objValidation->setFormula1('Sheet!$A$1:$A$3');. Another benefit is that the item values themselves can contain the comma "," character itself.
+
+If you need data validation on multiple cells, one can clone the ruleset:
+
+```php
+$objPHPExcel->getActiveSheet()->getCell('B8')->setDataValidation(clone $objValidation);
+```
+
+### Setting a column's width
+
+A column's width can be set using the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
+```
+
+If you want PHPExcel to perform an automatic width calculation, use the following code. PHPExcel will approximate the column with to the width of the widest column value.
+
+```php
+$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
+```
+
+
+
+The measure for column width in PHPExcel does __not__ correspond exactly to the measure you may be used to in Microsoft Office Excel. Column widths are difficult to deal with in Excel, and there are several measures for the column width.1) __Inner width in character units__ (e.g. 8.43 this is probably what you are familiar with in Excel)2) __Full width in pixels__ (e.g. 64 pixels)3) __Full width in character units__ (e.g. 9.140625, value -1 indicates unset width)__PHPExcel always operates with 3) "Full width in character units"__ which is in fact the only value that is stored in any Excel file, hence the most reliable measure. Unfortunately, __Microsoft ____Office ____Excel does not present you with this ____measure__. Instead measures 1) and 2) are computed by the application when the file is opened and these values are presented in various dialogues and tool tips.The character width unit is the width of a '0' (zero) glyph in the workbooks default font. Therefore column widths measured in character units in two different workbooks can only be compared if they have the same default workbook font.If you have some Excel file and need to know the column widths in measure 3), you can read the Excel file with PHPExcel and echo the retrieved values.
+
+### Show/hide a column
+
+To set a worksheet's column visibility, you can use the following code. The first line explicitly shows the column C, the second line hides column D.
+
+```php
+$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setVisible(true);
+$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(false);
+```
+
+### Group/outline a column
+
+To group/outline a column, you can use the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1);
+```
+
+You can also collapse the column. Note that you should also set the column invisible, otherwise the collapse will not be visible in Excel 2007.
+
+```php
+$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setCollapsed(true);
+$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setVisible(false);
+```
+
+Please refer to the section "group/outline a row" for a complete example on collapsing.
+
+You can instruct PHPExcel to add a summary to the right (default), or to the left. The following code adds the summary to the left:
+
+```php
+$objPHPExcel->getActiveSheet()->setShowSummaryRight(false);
+```
+
+### Setting a row's height
+
+A row's height can be set using the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getRowDimension('10')->setRowHeight(100);
+```
+
+Excel measures row height in points, where 1 pt is 1/72 of an inch (or about 0.35mm). The default value is 12.75 pts; and the permitted range of values is between 0 and 409 pts, where 0 pts is a hidden row.
+
+### Show/hide a row
+
+To set a worksheet''s row visibility, you can use the following code. The following example hides row number 10.
+
+```php
+$objPHPExcel->getActiveSheet()->getRowDimension('10')->setVisible(false);
+```
+
+Note that if you apply active filters using an AutoFilter, then this will override any rows that you hide or unhide manually within that AutoFilter range if you save the file.
+
+### Group/outline a row
+
+To group/outline a row, you can use the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1);
+```
+
+You can also collapse the row. Note that you should also set the row invisible, otherwise the collapse will not be visible in Excel 2007.
+
+```php
+$objPHPExcel->getActiveSheet()->getRowDimension('5')->setCollapsed(true);
+$objPHPExcel->getActiveSheet()->getRowDimension('5')->setVisible(false);
+```
+
+Here's an example which collapses rows 50 to 80:
+
+```php
+for ($i = 51; $i <= 80; $i++) {
+ $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, "FName $i");
+ $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, "LName $i");
+ $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, "PhoneNo $i");
+ $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, "FaxNo $i");
+ $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, true);
+ $objPHPExcel->getActiveSheet()->getRowDimension($i)->setOutlineLevel(1);
+ $objPHPExcel->getActiveSheet()->getRowDimension($i)->setVisible(false);
+}
+
+$objPHPExcel->getActiveSheet()->getRowDimension(81)->setCollapsed(true);
+```
+
+You can instruct PHPExcel to add a summary below the collapsible rows (default), or above. The following code adds the summary above:
+
+```php
+$objPHPExcel->getActiveSheet()->setShowSummaryBelow(false);
+```
+
+### Merge/unmerge cells
+
+If you have a big piece of data you want to display in a worksheet, you can merge two or more cells together, to become one cell. This can be done using the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->mergeCells('A18:E22');
+```
+
+Removing a merge can be done using the unmergeCells method:
+
+```php
+$objPHPExcel->getActiveSheet()->unmergeCells('A18:E22');
+```
+
+### Inserting rows/columns
+
+You can insert/remove rows/columns at a specific position. The following code inserts 2 new rows, right before row 7:
+
+```php
+$objPHPExcel->getActiveSheet()->insertNewRowBefore(7, 2);
+```
+
+### Add a drawing to a worksheet
+
+A drawing is always represented as a separate object, which can be added to a worksheet. Therefore, you must first instantiate a new PHPExcel_Worksheet_Drawing, and assign its properties a meaningful value:
+
+```php
+$objDrawing = new PHPExcel_Worksheet_Drawing();
+$objDrawing->setName('Logo');
+$objDrawing->setDescription('Logo');
+$objDrawing->setPath('./images/officelogo.jpg');
+$objDrawing->setHeight(36);
+```
+
+To add the above drawing to the worksheet, use the following snippet of code. PHPExcel creates the link between the drawing and the worksheet:
+
+```php
+$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
+```
+
+You can set numerous properties on a drawing, here are some examples:
+
+```php
+$objDrawing->setName('Paid');
+$objDrawing->setDescription('Paid');
+$objDrawing->setPath('./images/paid.png');
+$objDrawing->setCoordinates('B15');
+$objDrawing->setOffsetX(110);
+$objDrawing->setRotation(25);
+$objDrawing->getShadow()->setVisible(true);
+$objDrawing->getShadow()->setDirection(45);
+```
+
+You can also add images created using GD functions without needing to save them to disk first as In-Memory drawings.
+
+```php
+// Use GD to create an in-memory image
+$gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
+$textColor = imagecolorallocate($gdImage, 255, 255, 255);
+imagestring($gdImage, 1, 5, 5, 'Created with PHPExcel', $textColor);
+
+// Add the In-Memory image to a worksheet
+$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
+$objDrawing->setName('In-Memory image 1');
+$objDrawing->setDescription('In-Memory image 1');
+$objDrawing->setCoordinates('A1');
+$objDrawing->setImageResource($gdImage);
+$objDrawing->setRenderingFunction(
+ PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG
+);
+$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
+$objDrawing->setHeight(36);
+$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
+```
+
+### Reading Images from a worksheet
+
+A commonly asked question is how to retrieve the images from a workbook that has been loaded, and save them as individual image files to disk.
+
+The following code extracts images from the current active worksheet, and writes each as a separate file.
+
+```php
+$i = 0;
+foreach ($objPHPExcel->getActiveSheet()->getDrawingCollection() as $drawing) {
+ if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
+ ob_start();
+ call_user_func(
+ $drawing->getRenderingFunction(),
+ $drawing->getImageResource()
+ );
+ $imageContents = ob_get_contents();
+ ob_end_clean();
+ switch ($drawing->getMimeType()) {
+ case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
+ $extension = 'png';
+ break;
+ case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
+ $extension = 'gif';
+ break;
+ case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
+ $extension = 'jpg';
+ break;
+ }
+ } else {
+ $zipReader = fopen($drawing->getPath(),'r');
+ $imageContents = '';
+ while (!feof($zipReader)) {
+ $imageContents .= fread($zipReader,1024);
+ }
+ fclose($zipReader);
+ $extension = $drawing->getExtension();
+ }
+ $myFileName = '00_Image_'.++$i.'.'.$extension;
+ file_put_contents($myFileName,$imageContents);
+}
+```
+
+### Add rich text to a cell
+
+Adding rich text to a cell can be done using PHPExcel_RichText instances. Here''s an example, which creates the following rich text string:
+
+ > This invoice is *__payable within thirty days after the end of the month__* unless specified otherwise on the invoice.
+
+```php
+$objRichText = new PHPExcel_RichText();
+$objRichText->createText('This invoice is ');
+$objPayable = $objRichText->createTextRun('payable within thirty days after the end of the month');
+$objPayable->getFont()->setBold(true);
+$objPayable->getFont()->setItalic(true);
+$objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );
+$objRichText->createText(', unless specified otherwise on the invoice.');
+$objPHPExcel->getActiveSheet()->getCell('A18')->setValue($objRichText);
+```
+
+### Define a named range
+
+PHPExcel supports the definition of named ranges. These can be defined using the following code:
+
+```php
+// Add some data
+$objPHPExcel->setActiveSheetIndex(0);
+$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Firstname:');
+$objPHPExcel->getActiveSheet()->setCellValue('A2', 'Lastname:');
+$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Maarten');
+$objPHPExcel->getActiveSheet()->setCellValue('B2', 'Balliauw');
+
+// Define named ranges
+$objPHPExcel->addNamedRange( new PHPExcel_NamedRange('PersonFN', $objPHPExcel->getActiveSheet(), 'B1') );
+$objPHPExcel->addNamedRange( new PHPExcel_NamedRange('PersonLN', $objPHPExcel->getActiveSheet(), 'B2') );
+```
+
+Optionally, a fourth parameter can be passed defining the named range local (i.e. only usable on the current worksheet). Named ranges are global by default.
+
+### Redirect output to a client's web browser
+
+Sometimes, one really wants to output a file to a client''s browser, especially when creating spreadsheets on-the-fly. There are some easy steps that can be followed to do this:
+
+ 1. Create your PHPExcel spreadsheet
+ 2. Output HTTP headers for the type of document you wish to output
+ 3. Use the PHPExcel_Writer_* of your choice, and save to "php://output"
+
+PHPExcel_Writer_Excel2007 uses temporary storage when writing to php://output. By default, temporary files are stored in the script's working directory. When there is no access, it falls back to the operating system's temporary files location.
+
+__This may not be safe for unauthorized viewing!__
+Depending on the configuration of your operating system, temporary storage can be read by anyone using the same temporary storage folder. When confidentiality of your document is needed, it is recommended not to use php://output.
+
+#### HTTP headers
+
+Example of a script redirecting an Excel 2007 file to the client's browser:
+
+```php
+/* Here there will be some code where you create $objPHPExcel */
+
+// redirect output to client browser
+header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+header('Content-Disposition: attachment;filename="myfile.xlsx"');
+header('Cache-Control: max-age=0');
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save('php://output');
+```
+
+Example of a script redirecting an Excel5 file to the client's browser:
+
+```php
+/* Here there will be some code where you create $objPHPExcel */
+
+// redirect output to client browser
+header('Content-Type: application/vnd.ms-excel');
+header('Content-Disposition: attachment;filename="myfile.xls"');
+header('Cache-Control: max-age=0');
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
+$objWriter->save('php://output');
+```
+
+**Caution:**
+
+Make sure not to include any echo statements or output any other contents than the Excel file. There should be no whitespace before the opening tag (which can also be omitted to avoid problems). Make sure that your script is saved without a BOM (Byte-order mark) because this counts as echoing output. The same things apply to all included files.
+Failing to follow the above guidelines may result in corrupt Excel files arriving at the client browser, and/or that headers cannot be set by PHP (resulting in warning messages).
+
+### Setting the default column width
+
+Default column width can be set using the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
+```
+
+### Setting the default row height
+
+Default row height can be set using the following code:
+
+```php
+$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
+```
+
+### Add a GD drawing to a worksheet
+
+There might be a situation where you want to generate an in-memory image using GD and add it to a PHPExcel worksheet without first having to save this file to a temporary location.
+
+Here''s an example which generates an image in memory and adds it to the active worksheet:
+
+```php
+// Generate an image
+$gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
+$textColor = imagecolorallocate($gdImage, 255, 255, 255);
+imagestring($gdImage, 1, 5, 5, 'Created with PHPExcel', $textColor);
+
+// Add a drawing to the worksheet
+$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
+$objDrawing->setName('Sample image');
+$objDrawing->setDescription('Sample image');
+$objDrawing->setImageResource($gdImage);
+$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
+$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
+$objDrawing->setHeight(36);
+$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
+```
+
+### Setting worksheet zoom level
+
+To set a worksheet's zoom level, the following code can be used:
+
+```php
+$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScale(75);
+```
+
+Note that zoom level should be in range 10 – 400.
+
+### Sheet tab color
+
+Sometimes you want to set a color for sheet tab. For example you can have a red sheet tab:
+
+```php
+$objWorksheet->getTabColor()->setRGB('FF0000');
+```
+
+### Creating worksheets in a workbook
+
+If you need to create more worksheets in the workbook, here is how:
+
+```php
+$objWorksheet1 = $objPHPExcel->createSheet();
+$objWorksheet1->setTitle('Another sheet');
+```
+
+Think of createSheet() as the "Insert sheet" button in Excel. When you hit that button a new sheet is appended to the existing collection of worksheets in the workbook.
+
+### Hidden worksheets (Sheet states)
+
+Set a worksheet to be __hidden__ using this code:
+
+```php
+$objPHPExcel->getActiveSheet()
+ ->setSheetState(PHPExcel_Worksheet::SHEETSTATE_HIDDEN);
+```
+
+Sometimes you may even want the worksheet to be __"very hidden"__. The available sheet states are :
+
+ - PHPExcel_Worksheet::SHEETSTATE_VISIBLE
+ - PHPExcel_Worksheet::SHEETSTATE_HIDDEN
+ - PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN
+
+In Excel the sheet state "very hidden" can only be set programmatically, e.g. with Visual Basic Macro. It is not possible to make such a sheet visible via the user interface.
+
+### Right-to-left worksheet
+
+Worksheets can be set individually whether column "A" should start at left or right side. Default is left. Here is how to set columns from right-to-left.
+
+```php
+// right-to-left worksheet
+$objPHPExcel->getActiveSheet()
+ ->setRightToLeft(true);
+```
+
diff --git a/Documentation/markdown/Overview/09-Calculation-Engine.md b/Documentation/markdown/Overview/09-Calculation-Engine.md
new file mode 100644
index 000000000..c13a18c6c
--- /dev/null
+++ b/Documentation/markdown/Overview/09-Calculation-Engine.md
@@ -0,0 +1,52 @@
+# PHPExcel Developer Documentation
+
+## Using the PHPExcel calculation engine
+
+### Performing formula calculations
+
+As PHPExcel represents an in-memory spreadsheet, it also offers formula calculation capabilities. A cell can be of a value type (containing a number or text), or a formula type (containing a formula which can be evaluated). For example, the formula "=SUM(A1:A10)" evaluates to the sum of values in A1, A2, ..., A10.
+
+To calculate a formula, you can call the cell containing the formula’s method getCalculatedValue(), for example:
+
+```php
+$objPHPExcel->getActiveSheet()->getCell('E11')->getCalculatedValue();
+```
+If you write the following line of code in the invoice demo included with PHPExcel, it evaluates to the value "64":
+
+
+
+Another nice feature of PHPExcel's formula parser, is that it can automatically adjust a formula when inserting/removing rows/columns. Here's an example:
+
+
+
+You see that the formula contained in cell E11 is "SUM(E4:E9)". Now, when I write the following line of code, two new product lines are added:
+
+```php
+$objPHPExcel->getActiveSheet()->insertNewRowBefore(7, 2);
+```
+
+
+
+Did you notice? The formula in the former cell E11 (now E13, as I inserted 2 new rows), changed to "SUM(E4:E11)". Also, the inserted cells duplicate style information of the previous cell, just like Excel's behaviour. Note that you can both insert rows and columns.
+
+### Known limitations
+
+There are some known limitations to the PHPExcel calculation engine. Most of them are due to the fact that an Excel formula is converted into PHP code before being executed. This means that Excel formula calculation is subject to PHP's language characteristics.
+
+#### Operator precedence
+
+In Excel '+' wins over '&', just like '*' wins over '+' in ordinary algebra. The former rule is not what one finds using the calculation engine shipped with PHPExcel.
+
+Reference for operator precedence in Excel: [http://support.microsoft.com/kb/25189][18]
+
+Reference for operator precedence in PHP: [http://www.php.net/operators][19]
+
+#### Formulas involving numbers and text
+
+Formulas involving numbers and text may produce unexpected results or even unreadable file contents. For example, the formula '=3+"Hello "' is expected to produce an error in Excel (#VALUE!). Due to the fact that PHP converts “Hello” to a numeric value (zero), the result of this formula is evaluated as 3 instead of evaluating as an error. This also causes the Excel document being generated as containing unreadable content.
+
+Reference for this behaviour in PHP: [http://be.php.net/manual/en/language.types.string.php#language.types.string.conversion][20]
+
+ [18]: http://support.microsoft.com/kb/25189
+ [19]: http://www.php.net/operators
+ [20]: http://be.php.net/manual/en/language.types.string.php#language.types.string.conversion
diff --git a/Documentation/markdown/Overview/10-Reading-and-Writing.md b/Documentation/markdown/Overview/10-Reading-and-Writing.md
new file mode 100644
index 000000000..1468abc7e
--- /dev/null
+++ b/Documentation/markdown/Overview/10-Reading-and-Writing.md
@@ -0,0 +1,714 @@
+# PHPExcel Developer Documentation
+
+## Reading and writing to file
+
+As you already know from part REF _Ref191885438 \w \h 3.3 REF _Ref191885438 \h Readers and writers, reading and writing to a persisted storage is not possible using the base PHPExcel classes. For this purpose, PHPExcel provides readers and writers, which are implementations of PHPExcel_Writer_IReader and PHPExcel_Writer_IWriter.
+
+### PHPExcel_IOFactory
+
+The PHPExcel API offers multiple methods to create a PHPExcel_Writer_IReader or PHPExcel_Writer_IWriter instance:
+
+Direct creation via PHPExcel_IOFactory. All examples underneath demonstrate the direct creation method. Note that you can also use the PHPExcel_IOFactory class to do this.
+
+#### Creating PHPExcel_Reader_IReader using PHPExcel_IOFactory
+
+There are 2 methods for reading in a file into PHPExcel: using automatic file type resolving or explicitly.
+
+Automatic file type resolving checks the different PHPExcel_Reader_IReader distributed with PHPExcel. If one of them can load the specified file name, the file is loaded using that PHPExcel_Reader_IReader. Explicit mode requires you to specify which PHPExcel_Reader_IReader should be used.
+
+You can create a PHPExcel_Reader_IReader instance using PHPExcel_IOFactory in automatic file type resolving mode using the following code sample:
+
+```php
+$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");
+```
+
+A typical use of this feature is when you need to read files uploaded by your users, and you don’t know whether they are uploading xls or xlsx files.
+
+If you need to set some properties on the reader, (e.g. to only read data, see more about this later), then you may instead want to use this variant:
+
+```php
+$objReader = PHPExcel_IOFactory::createReaderForFile("05featuredemo.xlsx");
+$objReader->setReadDataOnly(true);
+$objReader->load("05featuredemo.xlsx");
+```
+
+You can create a PHPExcel_Reader_IReader instance using PHPExcel_IOFactory in explicit mode using the following code sample:
+
+```php
+$objReader = PHPExcel_IOFactory::createReader("Excel2007");
+$objPHPExcel = $objReader->load("05featuredemo.xlsx");
+```
+
+Note that automatic type resolving mode is slightly slower than explicit mode.
+
+#### Creating PHPExcel_Writer_IWriter using PHPExcel_IOFactory
+
+You can create a PHPExcel_Writer_Iwriter instance using PHPExcel_IOFactory:
+
+```php
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
+$objWriter->save("05featuredemo.xlsx");
+```
+
+### Excel 2007 (SpreadsheetML) file format
+
+Excel2007 file format is the main file format of PHPExcel. It allows outputting the in-memory spreadsheet to a .xlsx file.
+
+#### PHPExcel_Reader_Excel2007
+
+##### Reading a spreadsheet
+
+You can read an .xlsx file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_Excel2007();
+$objPHPExcel = $objReader->load("05featuredemo.xlsx");
+```
+
+##### Read data only
+
+You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:
+
+```php
+$objReader = new PHPExcel_Reader_Excel2007();
+$objReader->setReadDataOnly(true);
+$objPHPExcel = $objReader->load("05featuredemo.xlsx");
+```
+
+##### Read specific sheets only
+
+You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:
+
+```php
+$objReader = new PHPExcel_Reader_Excel2007();
+$objReader->setLoadSheetsOnly( array("Sheet 1", "My special sheet") );
+$objPHPExcel = $objReader->load("05featuredemo.xlsx");
+```
+
+##### Read specific cells only
+
+You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PHPExcel_Reader_IReadFilter. By default, all cells are read using the PHPExcel_Reader_DefaultReadFilter.
+
+The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
+
+```php
+class MyReadFilter implements PHPExcel_Reader_IReadFilter {
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Read title row and rows 20 - 30
+ if ($row == 1 || ($row >= 20 && $row <= 30)) {
+ return true;
+ }
+ return false;
+ }
+}
+
+$objReader = new PHPExcel_Reader_Excel2007();
+$objReader->setReadFilter( new MyReadFilter() );
+$objPHPExcel = $objReader->load("06largescale.xlsx");
+```
+
+#### PHPExcel_Writer_Excel2007
+
+##### Writing a spreadsheet
+
+You can write an .xlsx file using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
+$objWriter->save("05featuredemo.xlsx");
+```
+
+##### Formula pre-calculation
+
+By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
+
+```php
+$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
+$objWriter->setPreCalculateFormulas(false);
+$objWriter->save("05featuredemo.xlsx");
+```
+
+##### Office 2003 compatibility pack
+
+Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Excel2007 spreadsheets (mostly related to formula calculation). You can enable Office2003 compatibility with the following code:
+
+```
+$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
+$objWriter->setOffice2003Compatibility(true);
+$objWriter->save("05featuredemo.xlsx");
+```
+
+__Office2003 compatibility should only be used when needed__
+Office2003 compatibility option should only be used when needed. This option disables several Office2007 file format options, resulting in a lower-featured Office2007 spreadsheet when this option is used.
+
+### Excel 5 (BIFF) file format
+
+Excel5 file format is the old Excel file format, implemented in PHPExcel to provide a uniform manner to create both .xlsx and .xls files. It is basically a modified version of [PEAR Spreadsheet_Excel_Writer][21], although it has been extended and has fewer limitations and more features than the old PEAR library. This can read all BIFF versions that use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot read earlier versions.
+
+Excel5 file format will not be developed any further, it just provides an additional file format for PHPExcel.
+
+__Excel5 (BIFF) limitations__
+Please note that BIFF file format has some limits regarding to styling cells and handling large spreadsheets via PHP.
+
+#### PHPExcel_Reader_Excel5
+
+##### Reading a spreadsheet
+
+You can read an .xls file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_Excel5();
+$objPHPExcel = $objReader->load("05featuredemo.xls");
+```
+
+##### Read data only
+
+You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:
+
+```php
+$objReader = new PHPExcel_Reader_Excel5();
+$objReader->setReadDataOnly(true);
+$objPHPExcel = $objReader->load("05featuredemo.xls");
+```
+
+##### Read specific sheets only
+
+You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:
+
+```php
+$objReader = new PHPExcel_Reader_Excel5();
+$objReader->setLoadSheetsOnly( array("Sheet 1", "My special sheet") );
+$objPHPExcel = $objReader->load("05featuredemo.xls");
+```
+
+##### Read specific cells only
+
+You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PHPExcel_Reader_IReadFilter. By default, all cells are read using the PHPExcel_Reader_DefaultReadFilter.
+
+The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:
+
+```php
+class MyReadFilter implements PHPExcel_Reader_IReadFilter {
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Read title row and rows 20 - 30
+ if ($row == 1 || ($row >= 20 && $row <= 30)) {
+ return true;
+ }
+ return false;
+ }
+}
+
+$objReader = new PHPExcel_Reader_Excel5();
+$objReader->setReadFilter( new MyReadFilter() );
+$objPHPExcel = $objReader->load("06largescale.xls");
+```
+
+#### PHPExcel_Writer_Excel5
+
+##### Writing a spreadsheet
+
+You can write an .xls file using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
+$objWriter->save("05featuredemo.xls");
+```
+
+### Excel 2003 XML file format
+
+Excel 2003 XML file format is a file format which can be used in older versions of Microsoft Excel.
+
+__Excel 2003 XML limitations__
+Please note that Excel 2003 XML format has some limits regarding to styling cells and handling large spreadsheets via PHP.
+
+#### PHPExcel_Reader_Excel2003XML
+
+##### Reading a spreadsheet
+
+You can read an Excel 2003 .xml file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_Excel2003XML();
+$objPHPExcel = $objReader->load("05featuredemo.xml");
+```
+
+##### Read specific cells only
+
+You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PHPExcel_Reader_IReadFilter. By default, all cells are read using the PHPExcel_Reader_DefaultReadFilter.
+
+The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:
+
+```php
+class MyReadFilter implements PHPExcel_Reader_IReadFilter {
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Read title row and rows 20 - 30
+ if ($row == 1 || ($row >= 20 && $row <= 30)) {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+$objReader = new PHPExcel_Reader_Excel2003XML();
+$objReader->setReadFilter( new MyReadFilter() );
+$objPHPExcel = $objReader->load("06largescale.xml");
+```
+
+### Symbolic LinK (SYLK)
+
+Symbolic Link (SYLK) is a Microsoft file format typically used to exchange data between applications, specifically spreadsheets. SYLK files conventionally have a .slk suffix. Composed of only displayable ANSI characters, it can be easily created and processed by other applications, such as databases.
+
+__SYLK limitations__
+Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets via PHP.
+
+#### PHPExcel_Reader_SYLK
+
+##### Reading a spreadsheet
+
+You can read an .slk file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_SYLK();
+$objPHPExcel = $objReader->load("05featuredemo.slk");
+```
+
+##### Read specific cells only
+
+You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PHPExcel_Reader_IReadFilter. By default, all cells are read using the PHPExcel_Reader_DefaultReadFilter.
+
+The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file:
+
+```php
+class MyReadFilter implements PHPExcel_Reader_IReadFilter {
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Read title row and rows 20 - 30
+ if ($row == 1 || ($row >= 20 && $row <= 30)) {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+$objReader = new PHPExcel_Reader_SYLK();
+$objReader->setReadFilter( new MyReadFilter() );
+$objPHPExcel = $objReader->load("06largescale.slk");
+```
+
+### Open/Libre Office (.ods)
+
+Open Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files.
+
+#### PHPExcel_Reader_OOCalc
+
+##### Reading a spreadsheet
+
+You can read an .ods file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_OOCalc();
+$objPHPExcel = $objReader->load("05featuredemo.ods");
+```
+
+##### Read specific cells only
+
+You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PHPExcel_Reader_IReadFilter. By default, all cells are read using the PHPExcel_Reader_DefaultReadFilter.
+
+The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file:
+
+```php
+class MyReadFilter implements PHPExcel_Reader_IReadFilter {
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Read title row and rows 20 - 30
+ if ($row == 1 || ($row >= 20 && $row <= 30)) {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+$objReader = new PHPExcel_Reader_OOcalc();
+$objReader->setReadFilter( new MyReadFilter() );
+$objPHPExcel = $objReader->load("06largescale.ods");
+```
+
+### CSV (Comma Separated Values)
+
+CSV (Comma Separated Values) are often used as an import/export file format with other systems. PHPExcel allows reading and writing to CSV files.
+
+__CSV limitations__
+Please note that CSV file format has some limits regarding to styling cells, number formatting, ...
+
+#### PHPExcel_Reader_CSV
+
+##### Reading a CSV file
+
+You can read a .csv file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_CSV();
+$objPHPExcel = $objReader->load("sample.csv");
+```
+
+##### Setting CSV options
+
+Often, CSV files are not really “comma separated”, or use semicolon (;) as a separator. You can instruct PHPExcel_Reader_CSV some options before reading a CSV file.
+
+Note that PHPExcel_Reader_CSV by default assumes that the loaded CSV file is UTF-8 encoded. If you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately.
+
+```php
+$objReader = new PHPExcel_Reader_CSV();
+$objReader->setInputEncoding('CP1252');
+$objReader->setDelimiter(';');
+$objReader->setEnclosure('');
+$objReader->setLineEnding("\r\n");
+$objReader->setSheetIndex(0);
+
+$objPHPExcel = $objReader->load("sample.csv");
+```
+
+##### Read a specific worksheet
+
+CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV:
+
+```php
+$objReader->setSheetIndex(0);
+```
+
+##### Read into existing spreadsheet
+
+When working with CSV files, it might occur that you want to import CSV data into an existing PHPExcel object. The following code loads a CSV file into an existing $objPHPExcel containing some sheets, and imports onto the 6th sheet:
+
+```php
+$objReader = new PHPExcel_Reader_CSV();
+$objReader->setDelimiter(';');
+$objReader->setEnclosure('');
+$objReader->setLineEnding("\r\n");
+$objReader->setSheetIndex(5);
+
+$objReader->loadIntoExisting("05featuredemo.csv", $objPHPExcel);
+```
+
+#### PHPExcel_Writer_CSV
+
+##### Writing a CSV file
+
+You can write a .csv file using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
+$objWriter->save("05featuredemo.csv");
+```
+
+##### Setting CSV options
+
+Often, CSV files are not really “comma separated”, or use semicolon (;) as a separator. You can instruct PHPExcel_Writer_CSV some options before writing a CSV file:
+
+```php
+$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
+$objWriter->setDelimiter(';');
+$objWriter->setEnclosure('');
+$objWriter->setLineEnding("\r\n");
+$objWriter->setSheetIndex(0);
+
+$objWriter->save("05featuredemo.csv");
+```
+
+##### Write a specific worksheet
+
+CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV:
+
+```php
+$objWriter->setSheetIndex(0);
+```
+
+##### Formula pre-calculation
+
+By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
+
+```php
+$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
+$objWriter->setPreCalculateFormulas(false);
+$objWriter->save("05featuredemo.csv");
+```
+
+##### Writing UTF-8 CSV files
+
+A CSV file can be marked as UTF-8 by writing a BOM file header. This can be enabled by using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
+$objWriter->setUseBOM(true);
+$objWriter->save("05featuredemo.csv");
+```
+
+##### Decimal and thousands separators
+
+If the worksheet you are exporting contains numbers with decimal or thousands separators then you should think about what characters you want to use for those before doing the export.
+
+By default PHPExcel looks up in the server's locale settings to decide what characters to use. But to avoid problems it is recommended to set the characters explicitly as shown below.
+
+English users will want to use this before doing the export:
+
+```php
+PHPExcel_Shared_String::setDecimalSeparator('.');
+PHPExcel_Shared_String::setThousandsSeparator(',');
+```
+
+German users will want to use the opposite values.
+
+```php
+PHPExcel_Shared_String::setDecimalSeparator(',');
+PHPExcel_Shared_String::setThousandsSeparator('.');
+```
+
+Note that the above code sets decimal and thousand separators as global options. This also affects how HTML and PDF is exported.
+
+### HTML
+
+PHPExcel allows you to read or write a spreadsheet as HTML format, for quick representation of the data in it to anyone who does not have a spreadsheet application on their PC, or loading files saved by other scripts that simply create HTML markup and give it a .xls file extension.
+
+__HTML limitations__
+Please note that HTML file format has some limits regarding to styling cells, number formatting, ...
+
+#### PHPExcel_Reader_HTML
+
+##### Reading a spreadsheet
+
+You can read an .html or .htm file using the following code:
+
+```php
+$objReader = new PHPExcel_Reader_HTML();
+
+$objPHPExcel = $objReader->load("05featuredemo.html");
+```
+
+__HTML limitations__
+Please note that HTML reader is still experimental and does not yet support merged cells or nested tables cleanly
+
+#### PHPExcel_Writer_HTML
+
+Please note that PHPExcel_Writer_HTML only outputs the first worksheet by default.
+
+##### Writing a spreadsheet
+
+You can write a .htm file using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
+
+$objWriter->save("05featuredemo.htm");
+```
+
+##### Write all worksheets
+
+HTML files can contain one or more worksheets. If you want to write all sheets into a single HTML file, use the following code:
+
+```php
+$objWriter->writeAllSheets();
+```
+
+##### Write a specific worksheet
+
+HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML:
+
+```php
+$objWriter->setSheetIndex(0);
+```
+
+##### Setting the images root of the HTML file
+
+There might be situations where you want to explicitly set the included images root. For example, one might want to see
+```html
+
+```
+
+instead of
+
+```html
+
.
+```
+
+You can use the following code to achieve this result:
+
+```php
+$objWriter->setImagesRoot('http://www.example.com/');
+```
+
+##### Formula pre-calculation
+
+By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
+
+```php
+$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
+$objWriter->setPreCalculateFormulas(false);
+
+$objWriter->save("05featuredemo.htm");
+```
+
+##### Embedding generated HTML in a web page
+
+There might be a situation where you want to embed the generated HTML in an existing website. PHPExcel_Writer_HTML provides support to generate only specific parts of the HTML code, which allows you to use these parts in your website.
+
+Supported methods:
+
+ - generateHTMLHeader()
+ - generateStyles()
+ - generateSheetData()
+ - generateHTMLFooter()
+
+Here's an example which retrieves all parts independently and merges them into a resulting HTML page:
+
+```php
+generateHTMLHeader();
+?>
+
+
+?>
+
+-->
+
+
+generateSheetData();
+echo $objWriter->generateHTMLFooter();
+?>
+```
+
+##### Writing UTF-8 HTML files
+
+A HTML file can be marked as UTF-8 by writing a BOM file header. This can be enabled by using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
+$objWriter->setUseBOM(true);
+
+$objWriter->save("05featuredemo.htm");
+```
+
+##### Decimal and thousands separators
+
+See section PHPExcel_Writer_CSV how to control the appearance of these.
+
+### PDF
+
+PHPExcel allows you to write a spreadsheet into PDF format, for fast distribution of represented data.
+
+__PDF limitations__
+Please note that PDF file format has some limits regarding to styling cells, number formatting, ...
+
+#### PHPExcel_Writer_PDF
+
+PHPExcel’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as tcPDF, mPDF or DomPDF. Prior to version 1.7.8 of PHPExcel, the tcPDF library was bundled with PHPExcel; but from version 1.7.8 this was removed. Instead, you must now install a PDF Rendering library yourself; but PHPExcel will work with a number of different libraries.
+
+Currently, the following libraries are supported:
+
+Library | Version used for testing | Downloadable from | PHPExcel Internal Constant
+--------|--------------------------|----------------------------------|----------------------------
+tcPDF | 5.9 | http://www.tcpdf.org/ | PDF_RENDERER_TCPDF
+mPDF | 5.4 | http://www.mpdf1.com/mpdf/ | PDF_RENDERER_MPDF
+domPDF | 0.6.0 beta 3 | http://code.google.com/p/dompdf/ | PDF_RENDERER_DOMPDF
+
+The different libraries have different strengths and weaknesses. Some generate better formatted output than others, some are faster or use less memory than others, while some generate smaller .pdf files. It is the developers choice which one they wish to use, appropriate to their own circumstances.
+
+Before instantiating a Writer to generate PDF output, you will need to indicate which Rendering library you are using, and where it is located.
+
+```php
+$rendererName = PHPExcel_Settings::PDF_RENDERER_MPDF;
+$rendererLibrary = 'mPDF5.4';
+$rendererLibraryPath = dirname(__FILE__).'/../../../libraries/PDF/' . $rendererLibrary;
+
+if (!PHPExcel_Settings::setPdfRenderer(
+ $rendererName,
+ $rendererLibraryPath
+ )) {
+ die(
+ 'Please set the $rendererName and $rendererLibraryPath values' .
+ PHP_EOL .
+ ' as appropriate for your directory structure'
+ );
+}
+```
+
+##### Writing a spreadsheet
+
+Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code:
+
+```php
+$objWriter = new PHPExcel_Writer_PDF($objPHPExcel);
+$objWriter->save("05featuredemo.pdf");
+```
+
+Please note that PHPExcel_Writer_PDF only outputs the first worksheet by default.
+
+##### Write all worksheets
+
+PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code:
+
+```php
+$objWriter->writeAllSheets();
+```
+
+##### Write a specific worksheet
+
+PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF:
+
+```php
+$objWriter->setSheetIndex(0);
+```
+
+##### Formula pre-calculation
+
+By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
+
+```php
+$objWriter = new PHPExcel_Writer_PDF($objPHPExcel);
+$objWriter->setPreCalculateFormulas(false);
+
+$objWriter->save("05featuredemo.pdf");
+```
+
+##### Decimal and thousands separators
+
+See section PHPExcel_Writer_CSV how to control the appearance of these.
+
+### Generating Excel files from templates (read, modify, write)
+
+Readers and writers are the tools that allow you to generate Excel files from templates. This requires less coding effort than generating the Excel file from scratch, especially if your template has many styles, page setup properties, headers etc.
+
+Here is an example how to open a template file, fill in a couple of fields and save it again:
+
+```php
+$objPHPexcel = PHPExcel_IOFactory::load('template.xlsx');
+
+$objWorksheet = $objPHPexcel->getActiveSheet();
+
+$objWorksheet->getCell('A1')->setValue('John');
+$objWorksheet->getCell('A2')->setValue('Smith');
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPexcel, 'Excel5');
+$objWriter->save('write.xls');
+```
+
+Notice that it is ok to load an xlsx file and generate an xls file.
+
+ [21]: http://pear.php.net/package/Spreadsheet_Excel_Writer
+ [22]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Credits&referringTitle=Home
diff --git a/Documentation/markdown/Overview/11-Appendices.md b/Documentation/markdown/Overview/11-Appendices.md
new file mode 100644
index 000000000..1302feb3f
--- /dev/null
+++ b/Documentation/markdown/Overview/11-Appendices.md
@@ -0,0 +1,100 @@
+# PHPExcel Developer Documentation
+
+## Credits
+
+Please refer to the internet page [http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Credits&referringTitle=Home][22] for up-to-date credits.
+
+## Valid array keys for style applyFromArray()
+
+The following table lists the valid array keys for PHPExcel_Style applyFromArray() classes. If the "Maps to property"� column maps a key to a setter, the value provided for that key will be applied directly. If the "Maps to property" column maps a key to a getter, the value provided for that key will be applied as another style array.
+
+__PHPExcel_Style__
+
+ Array key | Maps to property
+ -------------|-------------------
+ fill | getFill()
+ font | getFont()
+ borders | getBorders()
+ alignment | getAlignment()
+ numberformat | getNumberFormat()
+ protection | getProtection()
+
+
+__PHPExcel_Style_Fill__
+
+ Array key | Maps to property
+ -----------|-------------------
+ type | setFillType()
+ rotation | setRotation()
+ startcolor | getStartColor()
+ endcolor | getEndColor()
+ color | getStartColor()
+
+
+__PHPExcel_Style_Font__
+
+ Array key | Maps to property
+ ------------|-------------------
+ name | setName()
+ bold | setBold()
+ italic | setItalic()
+ underline | setUnderline()
+ strike | setStrikethrough()
+ color | getColor()
+ size | setSize()
+ superScript | setSuperScript()
+ subScript | setSubScript()
+
+
+__PHPExcel_Style_Borders__
+
+ Array key | Maps to property
+ ------------------|-------------------
+ allborders | getLeft(); getRight(); getTop(); getBottom()
+ left | getLeft()
+ right | getRight()
+ top | getTop()
+ bottom | getBottom()
+ diagonal | getDiagonal()
+ vertical | getVertical()
+ horizontal | getHorizontal()
+ diagonaldirection | setDiagonalDirection()
+ outline | setOutline()
+
+
+__PHPExcel_Style_Border__
+
+ Array key | Maps to property
+ ----------|-------------------
+ style | setBorderStyle()
+ color | getColor()
+
+
+__PHPExcel_Style_Alignment__
+
+ Array key | Maps to property
+ ------------|-------------------
+ horizontal | setHorizontal()
+ vertical | setVertical()
+ rotation | setTextRotation()
+ wrap | setWrapText()
+ shrinkToFit | setShrinkToFit()
+ indent | setIndent()
+
+
+__PHPExcel_Style_NumberFormat__
+
+ Array key | Maps to property
+ ----------|-------------------
+ code | setFormatCode()
+
+
+__PHPExcel_Style_Protection__
+
+ Array key | Maps to property
+ ----------|-------------------
+ locked | setLocked()
+ hidden | setHidden()
+
+
+ [22]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Credits&referringTitle=Home
diff --git a/Documentation/markdown/Overview/images/01-schematic.png b/Documentation/markdown/Overview/images/01-schematic.png
new file mode 100644
index 000000000..8b6779204
Binary files /dev/null and b/Documentation/markdown/Overview/images/01-schematic.png differ
diff --git a/Documentation/markdown/Overview/images/02-readers-writers.png b/Documentation/markdown/Overview/images/02-readers-writers.png
new file mode 100644
index 000000000..0600788ae
Binary files /dev/null and b/Documentation/markdown/Overview/images/02-readers-writers.png differ
diff --git a/Documentation/markdown/Overview/images/07-simple-example-1.png b/Documentation/markdown/Overview/images/07-simple-example-1.png
new file mode 100644
index 000000000..30d193683
Binary files /dev/null and b/Documentation/markdown/Overview/images/07-simple-example-1.png differ
diff --git a/Documentation/markdown/Overview/images/07-simple-example-2.png b/Documentation/markdown/Overview/images/07-simple-example-2.png
new file mode 100644
index 000000000..e2b68506c
Binary files /dev/null and b/Documentation/markdown/Overview/images/07-simple-example-2.png differ
diff --git a/Documentation/markdown/Overview/images/07-simple-example-3.png b/Documentation/markdown/Overview/images/07-simple-example-3.png
new file mode 100644
index 000000000..459261f33
Binary files /dev/null and b/Documentation/markdown/Overview/images/07-simple-example-3.png differ
diff --git a/Documentation/markdown/Overview/images/07-simple-example-4.png b/Documentation/markdown/Overview/images/07-simple-example-4.png
new file mode 100644
index 000000000..70725452f
Binary files /dev/null and b/Documentation/markdown/Overview/images/07-simple-example-4.png differ
diff --git a/Documentation/markdown/Overview/images/08-cell-comment.png b/Documentation/markdown/Overview/images/08-cell-comment.png
new file mode 100644
index 000000000..bd8f8e66e
Binary files /dev/null and b/Documentation/markdown/Overview/images/08-cell-comment.png differ
diff --git a/Documentation/markdown/Overview/images/08-column-width.png b/Documentation/markdown/Overview/images/08-column-width.png
new file mode 100644
index 000000000..141994341
Binary files /dev/null and b/Documentation/markdown/Overview/images/08-column-width.png differ
diff --git a/Documentation/markdown/Overview/images/08-page-setup-margins.png b/Documentation/markdown/Overview/images/08-page-setup-margins.png
new file mode 100644
index 000000000..36e07a9b6
Binary files /dev/null and b/Documentation/markdown/Overview/images/08-page-setup-margins.png differ
diff --git a/Documentation/markdown/Overview/images/08-page-setup-scaling-options.png b/Documentation/markdown/Overview/images/08-page-setup-scaling-options.png
new file mode 100644
index 000000000..80fb5f00c
Binary files /dev/null and b/Documentation/markdown/Overview/images/08-page-setup-scaling-options.png differ
diff --git a/Documentation/markdown/Overview/images/08-styling-border-options.png b/Documentation/markdown/Overview/images/08-styling-border-options.png
new file mode 100644
index 000000000..4ef597070
Binary files /dev/null and b/Documentation/markdown/Overview/images/08-styling-border-options.png differ
diff --git a/Documentation/markdown/Overview/images/09-command-line-calculation.png b/Documentation/markdown/Overview/images/09-command-line-calculation.png
new file mode 100644
index 000000000..ceb2b3091
Binary files /dev/null and b/Documentation/markdown/Overview/images/09-command-line-calculation.png differ
diff --git a/Documentation/markdown/Overview/images/09-formula-in-cell-1.png b/Documentation/markdown/Overview/images/09-formula-in-cell-1.png
new file mode 100644
index 000000000..e50c6cc84
Binary files /dev/null and b/Documentation/markdown/Overview/images/09-formula-in-cell-1.png differ
diff --git a/Documentation/markdown/Overview/images/09-formula-in-cell-2.png b/Documentation/markdown/Overview/images/09-formula-in-cell-2.png
new file mode 100644
index 000000000..46daf090d
Binary files /dev/null and b/Documentation/markdown/Overview/images/09-formula-in-cell-2.png differ
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/01-File-Formats.md b/Documentation/markdown/ReadingSpreadsheetFiles/01-File-Formats.md
new file mode 100644
index 000000000..d89166437
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/01-File-Formats.md
@@ -0,0 +1,60 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+
+## Spreadsheet File Formats
+
+PHPExcel can read a number of different spreadsheet and file formats, although not all features are supported by all of the readers. Check the Functionality Cross-Reference document (Functionality Cross-Reference.xls) for a list that identifies which features are supported by which readers.
+
+Currently, PHPExcel supports the following File Types for Reading:
+
+### Excel5
+
+The Microsoft Excel™ Binary file format (BIFF5 and BIFF8) is a binary file format that was used by Microsoft Excel™ between versions 95 and 2003. The format is supported (to various extents) by most spreadsheet programs. BIFF files normally have an extension of .xls. Documentation describing the format can be found online at [http://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx][1] or from [http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/[MS-XLS].pdf][2] (as a downloadable PDF).
+
+### Excel2003XML
+
+Microsoft Excel™ 2003 included options for a file format called SpreadsheetML. This file is a zipped XML document. It is not very common, but its core features are supported. Documentation for the format can be found at [http://msdn.microsoft.com/en-us/library/aa140066%28office.10%29.aspx][3] though it’s sadly rather sparse in its detail.
+
+### Excel2007
+
+Microsoft Excel™ 2007 shipped with a new file format, namely Microsoft Office Open XML SpreadsheetML, and Excel 2010 extended this still further with its new features such as sparklines. These files typically have an extension of .xlsx. This format is based around a zipped collection of eXtensible Markup Language (XML) files. Microsoft Office Open XML SpreadsheetML is mostly standardized in ECMA 376 ([http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm][4]) and ISO 29500.
+
+### OOCalc
+
+aka Open Document Format (ODF) or OASIS, this is the OpenOffice.org XML File Format for spreadsheets. It comprises a zip archive including several components all of which are text files, most of these with markup in the eXtensible Markup Language (XML). It is the standard file format for OpenOffice.org Calc and StarCalc, and files typically have an extension of .ods. The published specification for the file format is available from the OASIS Open Office XML Format Technical Committee web page ([http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office#technical][5]). Other information is available from the OpenOffice.org XML File Format web page ([http://xml.openoffice.org/general.html][6]), part of the OpenOffice.org project.
+
+### SYLK
+
+This is the Microsoft Multiplan Symbolic Link Interchange (SYLK) file format. Multiplan was a predecessor to Microsoft Excel™. Files normally have an extension of .slk. While not common, there are still a few applications that generate SYLK files as a cross-platform option, because (despite being limited to a single worksheet) it is a simple format to implement, and supports some basic data and cell formatting options (unlike CSV files).
+
+### Gnumeric
+
+The Gnumeric file format is used by the Gnome Gnumeric spreadsheet application, and typically files have an extension of .gnumeric. The file contents are stored using eXtensible Markup Language (XML) markup, and the file is then compressed using the GNU project's gzip compression library. [http://projects.gnome.org/gnumeric/doc/file-format-gnumeric.shtml][7]
+
+### CSV
+
+Comma Separated Value (CSV) file format is a common structuring strategy for text format files. In CSV flies, each line in the file represents a row of data and (within each line of the file) the different data fields (or columns) are separated from one another using a comma (","). If a data field contains a comma, then it should be enclosed (typically in quotation marks ("). Sometimes tabs "\t", or the pipe symbol ("|"), or a semi-colon (";") are used as separators instead of a comma, although other symbols can be used. Because CSV is a text-only format, it doesn't support any data formatting options.
+
+"CSV" is not a single, well-defined format (although see RFC 4180 for one definition that is commonly used). Rather, in practice the term "CSV" refers to any file that:
+ - is plain text using a character set such as ASCII, Unicode, EBCDIC, or Shift JIS,
+ - consists of records (typically one record per line),
+ - with the records divided into fields separated by delimiters (typically a single reserved character such as comma, semicolon, or tab,
+ - where every record has the same sequence of fields.
+
+Within these general constraints, many variations are in use. Therefore "CSV" files are not entirely portable. Nevertheless, the variations are fairly small, and many implementations allow users to glance at the file (which is feasible because it is plain text), and then specify the delimiter character(s), quoting rules, etc.
+
+**Warning:** Microsoft Excel™ will open .csv files, but depending on the system's regional settings, it may expect a semicolon as a separator instead of a comma, since in some languages the comma is used as the decimal separator. Also, many regional versions of Excel will not be able to deal with Unicode characters in a CSV file.
+
+### HTML
+
+HyperText Markup Language (HTML) is the main markup language for creating web pages and other information that can be displayed in a web browser. Files typically have an extension of .html or .htm. HTML markup provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. Since 1996, the HTML specifications have been maintained, with input from commercial software vendors, by the World Wide Web Consortium (W3C). However, in 2000, HTML also became an international standard (ISO/IEC 15445:2000). HTML 4.01 was published in late 1999, with further errata published through 2001. In 2004 development began on HTML5 in the Web Hypertext Application Technology Working Group (WHATWG), which became a joint deliverable with the W3C in 2008.
+
+
+
+ [1]: http://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx
+ [2]: http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/%5bMS-XLS%5d.pdf
+ [3]: http://msdn.microsoft.com/en-us/library/aa140066%28office.10%29.aspx
+ [4]: http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm
+ [5]: http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office
+ [6]: http://xml.openoffice.org/general.html
+ [7]: http://projects.gnome.org/gnumeric/doc/file-format-gnumeric.shtml
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/02-Security.md b/Documentation/markdown/ReadingSpreadsheetFiles/02-Security.md
new file mode 100644
index 000000000..12da958ff
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/02-Security.md
@@ -0,0 +1,13 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+
+## Security
+
+XML-based formats such as OfficeOpen XML, Excel2003 XML, OASIS and Gnumeric are susceptible to XML External Entity Processing (XXE) injection attacks (for an explanation of XXE injection see http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html) when reading spreadsheet files. This can lead to:
+
+ - Disclosure whether a file is existent
+ - Server Side Request Forgery
+ - Command Execution (depending on the installed PHP wrappers)
+
+
+To prevent this, PHPExcel sets `libxml_disable_entity_loader` to `true` for the XML-based Readers by default.
\ No newline at end of file
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/03-Loading-a-Spreadsheet.md b/Documentation/markdown/ReadingSpreadsheetFiles/03-Loading-a-Spreadsheet.md
new file mode 100644
index 000000000..afa674d1b
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/03-Loading-a-Spreadsheet.md
@@ -0,0 +1,21 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+
+## Loading a Spreadsheet File
+
+The simplest way to load a workbook file is to let PHPExcel's IO Factory identify the file type and load it, calling the static load() method of the PHPExcel_IOFactory class.
+
+```php
+$inputFileName = './sampleData/example1.xls';
+
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
+```
+ > See Examples/Reader/exampleReader01.php for a working example of this code.
+
+The load() method will attempt to identify the file type, and instantiate a loader for that file type; using it to load the file and store the data and any formatting in a PHPExcel object.
+
+The method makes an initial guess at the loader to instantiate based on the file extension; but will test the file before actually executing the load: so if (for example) the file is actually a CSV file or contains HTML markup, but that has been given a .xls extension (quite a common practise), it will reject the Excel5 loader that it would normally use for a .xls file; and test the file using the other loaders until it finds the appropriate loader, and then use that to read the file.
+
+While easy to implement in your code, and you don't need to worry about the file type; this isn't the most efficient method to load a file; and it lacks the flexibility to configure the loader in any way before actually reading the file into a PHPExcel object.
+
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/04-Loading-with-a-Reader.md b/Documentation/markdown/ReadingSpreadsheetFiles/04-Loading-with-a-Reader.md
new file mode 100644
index 000000000..94d07aaa3
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/04-Loading-with-a-Reader.md
@@ -0,0 +1,56 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+
+## Creating a Reader and Loading a Spreadsheet File
+
+If you know the file type of the spreadsheet file that you need to load, you can instantiate a new reader object for that file type, then use the reader's load() method to read the file to a PHPExcel object. It is possible to instantiate the reader objects for each of the different supported filetype by name. However, you may get unpredictable results if the file isn't of the right type (e.g. it is a CSV with an extension of .xls), although this type of exception should normally be trapped.
+
+```php
+$inputFileName = './sampleData/example1.xls';
+
+/** Create a new Excel5 Reader **/
+$objReader = new PHPExcel_Reader_Excel5();
+// $objReader = new PHPExcel_Reader_Excel2007();
+// $objReader = new PHPExcel_Reader_Excel2003XML();
+// $objReader = new PHPExcel_Reader_OOCalc();
+// $objReader = new PHPExcel_Reader_SYLK();
+// $objReader = new PHPExcel_Reader_Gnumeric();
+// $objReader = new PHPExcel_Reader_CSV();
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader02.php for a working example of this code.
+
+Alternatively, you can use the IO Factory's createReader() method to instantiate the reader object for you, simply telling it the file type of the reader that you want instantiating.
+
+```php
+$inputFileType = 'Excel5';
+// $inputFileType = 'Excel2007';
+// $inputFileType = 'Excel2003XML';
+// $inputFileType = 'OOCalc';
+// $inputFileType = 'SYLK';
+// $inputFileType = 'Gnumeric';
+// $inputFileType = 'CSV';
+$inputFileName = './sampleData/example1.xls';
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader03.php for a working example of this code.
+
+If you're uncertain of the filetype, you can use the IO Factory's identify() method to identify the reader that you need, before using the createReader() method to instantiate the reader object.
+
+```php
+$inputFileName = './sampleData/example1.xls';
+
+/** Identify the type of $inputFileName **/
+$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
+/** Create a new Reader of the type that has been identified **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader04.php for a working example of this code.
+
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/05-Reader-Options.md b/Documentation/markdown/ReadingSpreadsheetFiles/05-Reader-Options.md
new file mode 100644
index 000000000..137fd1e8f
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/05-Reader-Options.md
@@ -0,0 +1,392 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+## Spreadsheet Reader Options
+
+Once you have created a reader object for the workbook that you want to load, you have the opportunity to set additional options before executing the load() method.
+
+### Reading Only Data from a Spreadsheet File
+
+If you're only interested in the cell values in a workbook, but don't need any of the cell formatting information, then you can set the reader to read only the data values and any formulae from each cell using the setReadDataOnly() method.
+
+```php
+$inputFileType = 'Excel5';
+$inputFileName = './sampleData/example1.xls';
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Advise the Reader that we only want to load cell data **/
+$objReader->setReadDataOnly(true);
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader05.php for a working example of this code.
+
+It is important to note that Workbooks (and PHPExcel) store dates and times as simple numeric values: they can only be distinguished from other numeric values by the format mask that is applied to that cell. When setting read data only to true, PHPExcel doesn't read the cell format masks, so it is not possible to differentiate between dates/times and numbers.
+
+The Gnumeric loader has been written to read the format masks for date values even when read data only has been set to true, so it can differentiate between dates/times and numbers; but this change hasn't yet been implemented for the other readers.
+
+Reading Only Data from a Spreadsheet File applies to Readers:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | YES | Excel5 | YES | Excel2003XML | YES |
+OOCalc | YES | SYLK | NO | Gnumeric | YES |
+CSV | NO | HTML | NO
+
+### Reading Only Named WorkSheets from a File
+
+If your workbook contains a number of worksheets, but you are only interested in reading some of those, then you can use the setLoadSheetsOnly() method to identify those sheets you are interested in reading.
+
+To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method.
+
+```php
+$inputFileType = 'Excel5';
+$inputFileName = './sampleData/example1.xls';
+$sheetname = 'Data Sheet #2';
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Advise the Reader of which WorkSheets we want to load **/
+$objReader->setLoadSheetsOnly($sheetname);
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader07.php for a working example of this code.
+
+If you want to read more than just a single sheet, you can pass a list of sheet names as an array parameter to the setLoadSheetsOnly() method.
+
+```php
+$inputFileType = 'Excel5';
+$inputFileName = './sampleData/example1.xls';
+$sheetnames = array('Data Sheet #1','Data Sheet #3');
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Advise the Reader of which WorkSheets we want to load **/
+$objReader->setLoadSheetsOnly($sheetnames);
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader08.php for a working example of this code.
+
+To reset this option to the default, you can call the setLoadAllSheets() method.
+
+```php
+$inputFileType = 'Excel5';
+$inputFileName = './sampleData/example1.xls';
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Advise the Reader to load all Worksheets **/
+$objReader->setLoadAllSheets();
+/** Load $inputFileName to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader06.php for a working example of this code.
+
+Reading Only Named WorkSheets from a File applies to Readers:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | YES | Excel5 | YES | Excel2003XML | YES |
+OOCalc | YES | SYLK | NO | Gnumeric | YES |
+CSV | NO | HTML | NO
+
+### Reading Only Specific Columns and Rows from a File (Read Filters)
+
+If you are only interested in reading part of a worksheet, then you can write a filter class that identifies whether or not individual cells should be read by the loader. A read filter must implement the PHPExcel_Reader_IReadFilter interface, and contain a readCell() method that accepts arguments of $column, $row and $worksheetName, and return a boolean true or false that indicates whether a workbook cell identified by those arguments should be read or not.
+
+```php
+$inputFileType = 'Excel5';
+$inputFileName = './sampleData/example1.xls';
+$sheetname = 'Data Sheet #3';
+
+
+/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
+class MyReadFilter implements PHPExcel_Reader_IReadFilter
+{
+ public function readCell($column, $row, $worksheetName = '') {
+ // Read rows 1 to 7 and columns A to E only
+ if ($row >= 1 && $row <= 7) {
+ if (in_array($column,range('A','E'))) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
+
+/** Create an Instance of our Read Filter **/
+$filterSubset = new MyReadFilter();
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Tell the Reader that we want to use the Read Filter **/
+$objReader->setReadFilter($filterSubset);
+/** Load only the rows and columns that match our filter to PHPExcel **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader09.php for a working example of this code.
+
+This example is not particularly useful, because it can only be used in a very specific circumstance (when you only want cells in the range A1:E7 from your worksheet. A generic Read Filter would probably be more useful:
+
+```php
+/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
+class MyReadFilter implements PHPExcel_Reader_IReadFilter
+{
+ private $_startRow = 0;
+ private $_endRow = 0;
+ private $_columns = array();
+
+ /** Get the list of rows and columns to read */
+ public function __construct($startRow, $endRow, $columns) {
+ $this->_startRow = $startRow;
+ $this->_endRow = $endRow;
+ $this->_columns = $columns;
+ }
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Only read the rows and columns that were configured
+ if ($row >= $this->_startRow && $row <= $this->_endRow) {
+ if (in_array($column,$this->_columns)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
+
+/** Create an Instance of our Read Filter, passing in the cell range **/
+$filterSubset = new MyReadFilter(9,15,range('G','K'));
+```
+ > See Examples/Reader/exampleReader10.php for a working example of this code.
+
+This can be particularly useful for conserving memory, by allowing you to read and process a large workbook in “chunks”: an example of this usage might be when transferring data from an Excel worksheet to a database.
+
+```php
+$inputFileType = 'Excel5';
+$inputFileName = './sampleData/example2.xls';
+
+
+/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
+class chunkReadFilter implements PHPExcel_Reader_IReadFilter
+{
+ private $_startRow = 0;
+ private $_endRow = 0;
+
+ /** Set the list of rows that we want to read */
+ public function setRows($startRow, $chunkSize) {
+ $this->_startRow = $startRow;
+ $this->_endRow = $startRow + $chunkSize;
+ }
+
+ public function readCell($column, $row, $worksheetName = '') {
+ // Only read the heading row, and the configured rows
+ if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {
+ return true;
+ }
+ return false;
+ }
+}
+
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+
+
+/** Define how many rows we want to read for each "chunk" **/
+$chunkSize = 2048;
+/** Create a new Instance of our Read Filter **/
+$chunkFilter = new chunkReadFilter();
+
+/** Tell the Reader that we want to use the Read Filter **/
+$objReader->setReadFilter($chunkFilter);
+
+/** Loop to read our worksheet in "chunk size" blocks **/
+for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
+ /** Tell the Read Filter which rows we want this iteration **/
+ $chunkFilter->setRows($startRow,$chunkSize);
+ /** Load only the rows that match our filter **/
+ $objPHPExcel = $objReader->load($inputFileName);
+ // Do some processing here
+}
+```
+ > See Examples/Reader/exampleReader12.php for a working example of this code.
+
+Using Read Filters applies to:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | YES | Excel5 | YES | Excel2003XML | YES |
+OOCalc | YES | SYLK | NO | Gnumeric | YES |
+CSV | YES | HTML | NO
+
+### Combining Multiple Files into a Single PHPExcel Object
+
+While you can limit the number of worksheets that are read from a workbook file using the setLoadSheetsOnly() method, certain readers also allow you to combine several individual "sheets" from different files into a single PHPExcel object, where each individual file is a single worksheet within that workbook. For each file that you read, you need to indicate which worksheet index it should be loaded into using the setSheetIndex() method of the $objReader, then use the loadIntoExisting() method rather than the load() method to actually read the file into that worksheet.
+
+```php
+$inputFileType = 'CSV';
+$inputFileNames = array('./sampleData/example1.csv',
+ './sampleData/example2.csv'
+ './sampleData/example3.csv'
+);
+
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+
+
+/** Extract the first named file from the array list **/
+$inputFileName = array_shift($inputFileNames);
+/** Load the initial file to the first worksheet in a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+/** Set the worksheet title (to the filename that we've loaded) **/
+$objPHPExcel->getActiveSheet()
+ ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
+
+
+/** Loop through all the remaining files in the list **/
+foreach($inputFileNames as $sheet => $inputFileName) {
+ /** Increment the worksheet index pointer for the Reader **/
+ $objReader->setSheetIndex($sheet+1);
+ /** Load the current file into a new worksheet in PHPExcel **/
+ $objReader->loadIntoExisting($inputFileName,$objPHPExcel);
+ /** Set the worksheet title (to the filename that we've loaded) **/
+ $objPHPExcel->getActiveSheet()
+ ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
+}
+```
+ > See Examples/Reader/exampleReader13.php for a working example of this code.
+
+Note that using the same sheet index for multiple sheets won't append files into the same sheet, but overwrite the results of the previous load. You cannot load multiple CSV files into the same worksheet.
+
+Combining Multiple Files into a Single PHPExcel Object applies to:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | NO | Excel5 | NO | Excel2003XML | NO |
+OOCalc | NO | SYLK | YES | Gnumeric | NO |
+CSV | YES | HTML | NO
+
+### Combining Read Filters with the setSheetIndex() method to split a large CSV file across multiple Worksheets
+
+An Excel5 BIFF .xls file is limited to 65536 rows in a worksheet, while the Excel2007 Microsoft Office Open XML SpreadsheetML .xlsx file is limited to 1,048,576 rows in a worksheet; but a CSV file is not limited other than by available disk space. This means that we wouldn’t ordinarily be able to read all the rows from a very large CSV file that exceeded those limits, and save it as an Excel5 or Excel2007 file. However, by using Read Filters to read the CSV file in “chunks” (using the chunkReadFilter Class that we defined in section REF _Ref275604563 \r \p 5.3 above), and the setSheetIndex() method of the $objReader, we can split the CSV file across several individual worksheets.
+
+```php
+$inputFileType = 'CSV';
+$inputFileName = './sampleData/example2.csv';
+
+
+echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'
';
+/** Create a new Reader of the type defined in $inputFileType **/
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+
+
+/** Define how many rows we want to read for each "chunk" **/
+$chunkSize = 65530;
+/** Create a new Instance of our Read Filter **/
+$chunkFilter = new chunkReadFilter();
+
+/** Tell the Reader that we want to use the Read Filter **/
+/** and that we want to store it in contiguous rows/columns **/
+
+$objReader->setReadFilter($chunkFilter)
+ ->setContiguous(true);
+
+/** Instantiate a new PHPExcel object manually **/
+$objPHPExcel = new PHPExcel();
+
+/** Set a sheet index **/
+$sheet = 0;
+/** Loop to read our worksheet in "chunk size" blocks **/
+/** $startRow is set to 2 initially because we always read the headings in row #1 **/
+for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) {
+ /** Tell the Read Filter which rows we want to read this loop **/
+ $chunkFilter->setRows($startRow,$chunkSize);
+
+ /** Increment the worksheet index pointer for the Reader **/
+ $objReader->setSheetIndex($sheet);
+ /** Load only the rows that match our filter into a new worksheet **/
+ $objReader->loadIntoExisting($inputFileName,$objPHPExcel);
+ /** Set the worksheet title for the sheet that we've justloaded) **/
+ /** and increment the sheet index as well **/
+ $objPHPExcel->getActiveSheet()->setTitle('Country Data #'.(++$sheet));
+}
+```
+ > See Examples/Reader/exampleReader14.php for a working example of this code.
+
+This code will read 65,530 rows at a time from the CSV file that we’re loading, and store each "chunk" in a new worksheet.
+
+The setContiguous() method for the Reader is important here. It is applicable only when working with a Read Filter, and identifies whether or not the cells should be stored by their position within the CSV file, or their position relative to the filter.
+
+For example, if the filter returned true for cells in the range B2:C3, then with setContiguous set to false (the default) these would be loaded as B2:C3 in the PHPExcel object; but with setContiguous set to true, they would be loaded as A1:B2.
+
+Splitting a single loaded file across multiple worksheets applies to:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | NO | Excel5 | NO | Excel2003XML | NO |
+OOCalc | NO | SYLK | NO | Gnumeric | NO |
+CSV | YES | HTML | NO
+
+### Pipe or Tab Separated Value Files
+
+The CSV loader defaults to loading a file where comma is used as the separator, but you can modify this to load tab- or pipe-separated value files using the setDelimiter() method.
+
+```php
+$inputFileType = 'CSV';
+$inputFileName = './sampleData/example1.tsv';
+
+/** Create a new Reader of the type defined in $inputFileType **/ $objReader = PHPExcel_IOFactory::createReader($inputFileType);
+/** Set the delimiter to a TAB character **/
+$objReader->setDelimiter("\t");
+// $objReader->setDelimiter('|');
+
+/** Load the file to a PHPExcel Object **/
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader15.php for a working example of this code.
+
+In addition to the delimiter, you can also use the following methods to set other attributes for the data load:
+
+setEnclosure() | default is "
+setLineEnding() | default is PHP_EOL
+setInputEncoding() | default is UTF-8
+
+Setting CSV delimiter applies to:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | NO | Excel5 | NO | Excel2003XML | NO |
+OOCalc | NO | SYLK | NO | Gnumeric | NO |
+CSV | YES | HTML | NO
+
+### A Brief Word about the Advanced Value Binder
+
+When loading data from a file that contains no formatting information, such as a CSV file, then data is read either as strings or numbers (float or integer). This means that PHPExcel does not automatically recognise dates/times (such as "16-Apr-2009" or "13:30"), booleans ("TRUE" or "FALSE"), percentages ("75%"), hyperlinks ("http://www.phpexcel.net/"), etc as anything other than simple strings. However, you can apply additional processing that is executed against these values during the load process within a Value Binder.
+
+A Value Binder is a class that implement the PHPExcel_Cell_IValueBinder interface. It must contain a bindValue() method that accepts a PHPExcel_Cell and a value as arguments, and return a boolean true or false that indicates whether the workbook cell has been populated with the value or not. The Advanced Value Binder implements such a class: amongst other tests, it identifies a string comprising "TRUE" or "FALSE" (based on locale settings) and sets it to a boolean; or a number in scientific format (e.g. "1.234e-5") and converts it to a float; or dates and times, converting them to their Excel timestamp value – before storing the value in the cell object. It also sets formatting for strings that are identified as dates, times or percentages. It could easily be extended to provide additional handling (including text or cell formatting) when it encountered a hyperlink, or HTML markup within a CSV file.
+
+So using a Value Binder allows a great deal more flexibility in the loader logic when reading unformatted text files.
+
+```php
+/** Tell PHPExcel that we want to use the Advanced Value Binder **/
+PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
+
+$inputFileType = 'CSV';
+$inputFileName = './sampleData/example1.tsv';
+
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+$objReader->setDelimiter("\t");
+$objPHPExcel = $objReader->load($inputFileName);
+```
+ > See Examples/Reader/exampleReader15.php for a working example of this code.
+
+Loading using a Value Binder applies to:
+
+Reader | Y/N |Reader | Y/N |Reader | Y/N |
+----------|:---:|--------|:---:|--------------|:---:|
+Excel2007 | NO | Excel5 | NO | Excel2003XML | NO |
+OOCalc | NO | SYLK | NO | Gnumeric | NO |
+CSV | YES | HTML | YES
+
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/06-Error-Handling.md b/Documentation/markdown/ReadingSpreadsheetFiles/06-Error-Handling.md
new file mode 100644
index 000000000..d3e064f9b
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/06-Error-Handling.md
@@ -0,0 +1,20 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+## Error Handling
+
+Of course, you should always apply some error handling to your scripts as well. PHPExcel throws exceptions, so you can wrap all your code that accesses the library methods within Try/Catch blocks to trap for any problems that are encountered, and deal with them in an appropriate manner.
+
+The PHPExcel Readers throw a PHPExcel_Reader_Exception.
+
+```php
+$inputFileName = './sampleData/example-1.xls';
+
+try {
+ /** Load $inputFileName to a PHPExcel Object **/
+ $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
+} catch(PHPExcel_Reader_Exception $e) {
+ die('Error loading file: '.$e->getMessage());
+}
+```
+ > See Examples/Reader/exampleReader16.php for a working example of this code.
+
diff --git a/Documentation/markdown/ReadingSpreadsheetFiles/07-Helper-Methods.md b/Documentation/markdown/ReadingSpreadsheetFiles/07-Helper-Methods.md
new file mode 100644
index 000000000..57dbec7a7
--- /dev/null
+++ b/Documentation/markdown/ReadingSpreadsheetFiles/07-Helper-Methods.md
@@ -0,0 +1,47 @@
+# PHPExcel User Documentation – Reading Spreadsheet Files
+
+
+## Helper Methods
+
+You can retrieve a list of worksheet names contained in a file without loading the whole file by using the Reader’s `listWorksheetNames()` method; similarly, a `listWorksheetInfo()` method will retrieve the dimensions of worksheet in a file without needing to load and parse the whole file.
+
+### listWorksheetNames
+
+The `listWorksheetNames()` method returns a simple array listing each worksheet name within the workbook:
+
+```php
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+
+$worksheetNames = $objReader->listWorksheetNames($inputFileName);
+
+echo 'Worksheet Names
';
+echo '';
+foreach ($worksheetNames as $worksheetName) {
+ echo '
';
+```
+ > See Examples/Reader/exampleReader18.php for a working example of this code.
+
+### listWorksheetInfo
+
+The `listWorksheetInfo()` method returns a nested array, with each entry listing the name and dimensions for a worksheet:
+
+```php
+$objReader = PHPExcel_IOFactory::createReader($inputFileType);
+
+$worksheetData = $objReader->listWorksheetInfo($inputFileName);
+
+echo 'Worksheet Information
';
+echo '';
+foreach ($worksheetData as $worksheet) {
+ echo '
';
+```
+ > See Examples/Reader/exampleReader19.php for a working example of this code.
diff --git a/Examples/.gitignore b/Examples/.gitignore
index 1888a98fa..d53fd7fab 100644
--- a/Examples/.gitignore
+++ b/Examples/.gitignore
@@ -1,3 +1,5 @@
-
*.xls
-*.xlsx
\ No newline at end of file
+*.xlsx
+*.csv
+*.jpg
+*.pdf
diff --git a/Examples/01pharSimple.php b/Examples/01pharSimple.php
index 8e15ea0e4..84b86cc5e 100644
--- a/Examples/01pharSimple.php
+++ b/Examples/01pharSimple.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
diff --git a/Examples/01simple-download-ods.php b/Examples/01simple-download-ods.php
new file mode 100644
index 000000000..30dbd7e35
--- /dev/null
+++ b/Examples/01simple-download-ods.php
@@ -0,0 +1,89 @@
+getProperties()->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
+
+
+// Add some data
+$objPHPExcel->setActiveSheetIndex(0)
+ ->setCellValue('A1', 'Hello')
+ ->setCellValue('B2', 'world!')
+ ->setCellValue('C1', 'Hello')
+ ->setCellValue('D2', 'world!');
+
+// Miscellaneous glyphs, UTF-8
+$objPHPExcel->setActiveSheetIndex(0)
+ ->setCellValue('A4', 'Miscellaneous glyphs')
+ ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
+
+// Rename worksheet
+$objPHPExcel->getActiveSheet()->setTitle('Simple');
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Redirect output to a client’s web browser (OpenDocument)
+header('Content-Type: application/vnd.oasis.opendocument.spreadsheet');
+header('Content-Disposition: attachment;filename="01simple.ods"');
+header('Cache-Control: max-age=0');
+// If you're serving to IE 9, then the following may be needed
+header('Cache-Control: max-age=1');
+
+// If you're serving to IE over SSL, then the following may be needed
+header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
+header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
+header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
+header ('Pragma: public'); // HTTP/1.0
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'OpenDocument');
+$objWriter->save('php://output');
+exit;
diff --git a/Examples/01simple-download-pdf.php b/Examples/01simple-download-pdf.php
index 5fe4a847c..133af3a69 100644
--- a/Examples/01simple-download-pdf.php
+++ b/Examples/01simple-download-pdf.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Change these values to select the Rendering library that you wish to use
diff --git a/Examples/01simple-download-xls.php b/Examples/01simple-download-xls.php
index c1d670dc3..96bb780b5 100644
--- a/Examples/01simple-download-xls.php
+++ b/Examples/01simple-download-xls.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -75,6 +75,14 @@
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
+// If you're serving to IE 9, then the following may be needed
+header('Cache-Control: max-age=1');
+
+// If you're serving to IE over SSL, then the following may be needed
+header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
+header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
+header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
+header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
diff --git a/Examples/01simple-download-xlsx.php b/Examples/01simple-download-xlsx.php
index fd98a9fbb..d441f4191 100644
--- a/Examples/01simple-download-xlsx.php
+++ b/Examples/01simple-download-xlsx.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -75,6 +75,14 @@
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
+// If you're serving to IE 9, then the following may be needed
+header('Cache-Control: max-age=1');
+
+// If you're serving to IE over SSL, then the following may be needed
+header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
+header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
+header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
+header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
diff --git a/Examples/01simple.php b/Examples/01simple.php
index a547a49ab..13f802759 100644
--- a/Examples/01simple.php
+++ b/Examples/01simple.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,8 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
';
+ echo 'Rows: ', $worksheet['totalRows'],
+ ' Columns: ', $worksheet['totalColumns'], '
';
+ echo 'Cell Range: A1:',
+ $worksheet['lastColumnLetter'], $worksheet['totalRows'];
+ echo '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
-
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
echo date('H:i:s') , " Create new PHPExcel object" , EOL;
@@ -71,6 +70,14 @@
$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
+$value = "-ValueA\n-Value B\n-Value C";
+$objPHPExcel->getActiveSheet()->setCellValue('A10', $value);
+$objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(-1);
+$objPHPExcel->getActiveSheet()->getStyle('A10')->getAlignment()->setWrapText(true);
+$objPHPExcel->getActiveSheet()->getStyle('A10')->setQuotePrefix(true);
+
+
+
// Rename worksheet
echo date('H:i:s') , " Rename worksheet" , EOL;
$objPHPExcel->getActiveSheet()->setTitle('Simple');
diff --git a/Examples/01simplePCLZip.php b/Examples/01simplePCLZip.php
new file mode 100644
index 000000000..0af4cbdd8
--- /dev/null
+++ b/Examples/01simplePCLZip.php
@@ -0,0 +1,106 @@
+');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set document properties" , EOL;
+$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("PHPExcel Test Document")
+ ->setSubject("PHPExcel Test Document")
+ ->setDescription("Test document for PHPExcel, generated using PHP classes.")
+ ->setKeywords("office PHPExcel php")
+ ->setCategory("Test result file");
+
+
+// Add some data
+echo date('H:i:s') , " Add some data" , EOL;
+$objPHPExcel->setActiveSheetIndex(0)
+ ->setCellValue('A1', 'Hello')
+ ->setCellValue('B2', 'world!')
+ ->setCellValue('C1', 'Hello')
+ ->setCellValue('D2', 'world!');
+
+// Miscellaneous glyphs, UTF-8
+$objPHPExcel->setActiveSheetIndex(0)
+ ->setCellValue('A4', 'Miscellaneous glyphs')
+ ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
+
+
+$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
+$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
+$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
+
+
+// Rename worksheet
+echo date('H:i:s') , " Rename worksheet" , EOL;
+$objPHPExcel->getActiveSheet()->setTitle('Simple');
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+// Use PCLZip rather than ZipArchive to create the Excel2007 OfficeOpenXML file
+PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing files" , EOL;
+echo 'Files have been created in ' , getcwd() , EOL;
diff --git a/Examples/02types-xls.php b/Examples/02types-xls.php
index 905dc9d11..93ce17e59 100644
--- a/Examples/02types-xls.php
+++ b/Examples/02types-xls.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -109,6 +109,28 @@
$objPHPExcel->getActiveSheet()->setCellValue('A12', 'NULL')
->setCellValue('C12', NULL);
+$objRichText = new PHPExcel_RichText();
+$objRichText->createText('你好 ');
+$objPayable = $objRichText->createTextRun('你 好 吗?');
+$objPayable->getFont()->setBold(true);
+$objPayable->getFont()->setItalic(true);
+$objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );
+
+$objRichText->createText(', unless specified otherwise on the invoice.');
+
+$objPHPExcel->getActiveSheet()->setCellValue('A13', 'Rich Text')
+ ->setCellValue('C13', $objRichText);
+
+
+$objRichText2 = new PHPExcel_RichText();
+$objRichText2->createText("black text\n");
+
+$objRed = $objRichText2->createTextRun("red text");
+$objRed->getFont()->setColor( new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_RED ) );
+
+$objPHPExcel->getActiveSheet()->getCell("C14")->setValue($objRichText2);
+$objPHPExcel->getActiveSheet()->getStyle("C14")->getAlignment()->setWrapText(true);
+
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
diff --git a/Examples/02types.php b/Examples/02types.php
index a66af9053..394a73dd4 100644
--- a/Examples/02types.php
+++ b/Examples/02types.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -109,10 +109,54 @@
$objPHPExcel->getActiveSheet()->setCellValue('A12', 'NULL')
->setCellValue('C12', NULL);
+$objRichText = new PHPExcel_RichText();
+$objRichText->createText('你好 ');
+
+$objPayable = $objRichText->createTextRun('你 好 吗?');
+$objPayable->getFont()->setBold(true);
+$objPayable->getFont()->setItalic(true);
+$objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );
+
+$objRichText->createText(', unless specified otherwise on the invoice.');
+
+$objPHPExcel->getActiveSheet()->setCellValue('A13', 'Rich Text')
+ ->setCellValue('C13', $objRichText);
+
+
+$objRichText2 = new PHPExcel_RichText();
+$objRichText2->createText("black text\n");
+
+$objRed = $objRichText2->createTextRun("red text");
+$objRed->getFont()->setColor( new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_RED ) );
+
+$objPHPExcel->getActiveSheet()->getCell("C14")->setValue($objRichText2);
+$objPHPExcel->getActiveSheet()->getStyle("C14")->getAlignment()->setWrapText(true);
+
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
+$objRichText3 = new PHPExcel_RichText();
+$objRichText3->createText("Hello ");
+
+$objUnderlined = $objRichText3->createTextRun("underlined");
+$objUnderlined->getFont()->setUnderline(true);
+$objRichText3->createText(' World.');
+
+$objPHPExcel->getActiveSheet()
+ ->getCell("C15")
+ ->setValue($objRichText3);
+
+
+$objPHPExcel->getActiveSheet()->setCellValue('A17', 'Hyperlink');
+
+$objPHPExcel->getActiveSheet()->setCellValue('C17', 'www.phpexcel.net');
+$objPHPExcel->getActiveSheet()->getCell('C17')->getHyperlink()->setUrl('http://www.phpexcel.net/');
+$objPHPExcel->getActiveSheet()->getCell('C17')->getHyperlink()->setTooltip('Navigate to website');
+
+$objPHPExcel->getActiveSheet()->setCellValue('C18', '=HYPERLINK("mailto:abc@def.com","abc@def.com")');
+
+
// Rename worksheet
echo date('H:i:s') , " Rename worksheet" , EOL;
$objPHPExcel->getActiveSheet()->setTitle('Datatypes');
diff --git a/Examples/03formulas.php b/Examples/03formulas.php
index 7670908fb..6c5d1ddc9 100644
--- a/Examples/03formulas.php
+++ b/Examples/03formulas.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -107,6 +107,15 @@
$callStartTime = microtime(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+
+//
+// If we set Pre Calculated Formulas to true then PHPExcel will calculate all formulae in the
+// workbook before saving. This adds time and memory overhead, and can cause some problems with formulae
+// using functions or features (such as array formulae) that aren't yet supported by the calculation engine
+// If the value is false (the default) for the Excel2007 Writer, then MS Excel (or the application used to
+// open the file) will need to recalculate values itself to guarantee that the correct results are available.
+//
+//$objWriter->setPreCalculateFormulas(true);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
diff --git a/Examples/04printing.php b/Examples/04printing.php
index 0147bffc1..58d5f6a8e 100644
--- a/Examples/04printing.php
+++ b/Examples/04printing.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/05featuredemo.inc.php b/Examples/05featuredemo.inc.php
index 9fd0a6178..003379cce 100644
--- a/Examples/05featuredemo.inc.php
+++ b/Examples/05featuredemo.inc.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -267,12 +267,13 @@
$objPHPExcel->getActiveSheet()->getStyle('B1')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
// Add a hyperlink to the sheet
-echo date('H:i:s') , " Add a hyperlink to the sheet" , EOL;
+echo date('H:i:s') , " Add a hyperlink to an external website" , EOL;
$objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('http://www.phpexcel.net/');
$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setTooltip('Navigate to website');
$objPHPExcel->getActiveSheet()->getStyle('E26')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
+echo date('H:i:s') , " Add a hyperlink to another cell on a different worksheet within the workbook" , EOL;
$objPHPExcel->getActiveSheet()->setCellValue('E27', 'Terms and conditions');
$objPHPExcel->getActiveSheet()->getCell('E27')->getHyperlink()->setUrl("sheet://'Terms and conditions'!A1");
$objPHPExcel->getActiveSheet()->getCell('E27')->getHyperlink()->setTooltip('Review terms and conditions');
diff --git a/Examples/05featuredemo.php b/Examples/05featuredemo.php
index f902e251e..9e502acb6 100644
--- a/Examples/05featuredemo.php
+++ b/Examples/05featuredemo.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -37,7 +37,7 @@
include "05featuredemo.inc.php";
/** Include PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
// Save Excel 2007 file
diff --git a/Examples/06largescale-with-cellcaching-sqlite.php b/Examples/06largescale-with-cellcaching-sqlite.php
new file mode 100644
index 000000000..8baa7431a
--- /dev/null
+++ b/Examples/06largescale-with-cellcaching-sqlite.php
@@ -0,0 +1,129 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_sqlite;
+if (PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
+ echo date('H:i:s') , " Enable Cell Caching using " , $cacheMethod , " method" , EOL;
+} else {
+ echo date('H:i:s') , " Unable to set Cell Caching using " , $cacheMethod , " method, reverting to memory" , EOL;
+}
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set properties" , EOL;
+$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
+
+
+// Create a first sheet
+echo date('H:i:s') , " Add data" , EOL;
+$objPHPExcel->setActiveSheetIndex(0);
+$objPHPExcel->getActiveSheet()->setCellValue('A1', "Firstname");
+$objPHPExcel->getActiveSheet()->setCellValue('B1', "Lastname");
+$objPHPExcel->getActiveSheet()->setCellValue('C1', "Phone");
+$objPHPExcel->getActiveSheet()->setCellValue('D1', "Fax");
+$objPHPExcel->getActiveSheet()->setCellValue('E1', "Is Client ?");
+
+
+// Hide "Phone" and "fax" column
+echo date('H:i:s') , " Hide 'Phone' and 'fax' columns" , EOL;
+$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setVisible(false);
+$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(false);
+
+
+// Set outline levels
+echo date('H:i:s') , " Set outline levels" , EOL;
+$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1)
+ ->setVisible(false)
+ ->setCollapsed(true);
+
+// Freeze panes
+echo date('H:i:s') , " Freeze panes" , EOL;
+$objPHPExcel->getActiveSheet()->freezePane('A2');
+
+
+// Rows to repeat at top
+echo date('H:i:s') , " Rows to repeat at top" , EOL;
+$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
+
+
+// Add data
+for ($i = 2; $i <= 5000; $i++) {
+ $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, "FName $i")
+ ->setCellValue('B' . $i, "LName $i")
+ ->setCellValue('C' . $i, "PhoneNo $i")
+ ->setCellValue('D' . $i, "FaxNo $i")
+ ->setCellValue('E' . $i, true);
+}
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/06largescale-with-cellcaching-sqlite3.php b/Examples/06largescale-with-cellcaching-sqlite3.php
new file mode 100644
index 000000000..1f480d1d2
--- /dev/null
+++ b/Examples/06largescale-with-cellcaching-sqlite3.php
@@ -0,0 +1,129 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3;
+if (PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
+ echo date('H:i:s') , " Enable Cell Caching using " , $cacheMethod , " method" , EOL;
+} else {
+ echo date('H:i:s') , " Unable to set Cell Caching using " , $cacheMethod , " method, reverting to memory" , EOL;
+}
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set properties" , EOL;
+$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
+
+
+// Create a first sheet
+echo date('H:i:s') , " Add data" , EOL;
+$objPHPExcel->setActiveSheetIndex(0);
+$objPHPExcel->getActiveSheet()->setCellValue('A1', "Firstname");
+$objPHPExcel->getActiveSheet()->setCellValue('B1', "Lastname");
+$objPHPExcel->getActiveSheet()->setCellValue('C1', "Phone");
+$objPHPExcel->getActiveSheet()->setCellValue('D1', "Fax");
+$objPHPExcel->getActiveSheet()->setCellValue('E1', "Is Client ?");
+
+
+// Hide "Phone" and "fax" column
+echo date('H:i:s') , " Hide 'Phone' and 'fax' columns" , EOL;
+$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setVisible(false);
+$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(false);
+
+
+// Set outline levels
+echo date('H:i:s') , " Set outline levels" , EOL;
+$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1)
+ ->setVisible(false)
+ ->setCollapsed(true);
+
+// Freeze panes
+echo date('H:i:s') , " Freeze panes" , EOL;
+$objPHPExcel->getActiveSheet()->freezePane('A2');
+
+
+// Rows to repeat at top
+echo date('H:i:s') , " Rows to repeat at top" , EOL;
+$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
+
+
+// Add data
+for ($i = 2; $i <= 5000; $i++) {
+ $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, "FName $i")
+ ->setCellValue('B' . $i, "LName $i")
+ ->setCellValue('C' . $i, "PhoneNo $i")
+ ->setCellValue('D' . $i, "FaxNo $i")
+ ->setCellValue('E' . $i, true);
+}
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/06largescale-with-cellcaching.php b/Examples/06largescale-with-cellcaching.php
index fd42c6e95..d20b29f24 100644
--- a/Examples/06largescale-with-cellcaching.php
+++ b/Examples/06largescale-with-cellcaching.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,10 +35,12 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
-PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
+if (!PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
+ die($cacheMethod . " caching method is not available" . EOL);
+}
echo date('H:i:s') , " Enable Cell Caching using " , $cacheMethod , " method" , EOL;
diff --git a/Examples/06largescale-xls.php b/Examples/06largescale-xls.php
index 49b9746ba..5adc3d259 100644
--- a/Examples/06largescale-xls.php
+++ b/Examples/06largescale-xls.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
/*
diff --git a/Examples/06largescale.php b/Examples/06largescale.php
index f524aa47b..cb21caf50 100644
--- a/Examples/06largescale.php
+++ b/Examples/06largescale.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
/*
diff --git a/Examples/07reader.php b/Examples/07reader.php
index cf1ead2a6..318ba1891 100644
--- a/Examples/07reader.php
+++ b/Examples/07reader.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
if (!file_exists("05featuredemo.xlsx")) {
diff --git a/Examples/07readerPCLZip.php b/Examples/07readerPCLZip.php
new file mode 100644
index 000000000..f1da9c574
--- /dev/null
+++ b/Examples/07readerPCLZip.php
@@ -0,0 +1,79 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/** Include PHPExcel_IOFactory */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
+
+
+if (!file_exists("05featuredemo.xlsx")) {
+ exit("Please run 05featuredemo.php first." . EOL);
+}
+
+// Use PCLZip rather than ZipArchive to read the Excel2007 OfficeOpenXML file
+PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
+
+echo date('H:i:s') , " Load from Excel2007 file" , EOL;
+$callStartTime = microtime(true);
+
+$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");
+
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/08conditionalformatting.php b/Examples/08conditionalformatting.php
index 24e62c4bf..514a8bb63 100644
--- a/Examples/08conditionalformatting.php
+++ b/Examples/08conditionalformatting.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/08conditionalformatting2.php b/Examples/08conditionalformatting2.php
index 1040b315f..aeb2a3136 100644
--- a/Examples/08conditionalformatting2.php
+++ b/Examples/08conditionalformatting2.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/09pagebreaks.php b/Examples/09pagebreaks.php
index 85bd8329c..36e21ae4b 100644
--- a/Examples/09pagebreaks.php
+++ b/Examples/09pagebreaks.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -78,9 +78,22 @@
}
}
-
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
+$objPHPExcel->getActiveSheet()->setTitle('Printing Options');
+
+// Set print headers
+$objPHPExcel->getActiveSheet()
+ ->getHeaderFooter()->setOddHeader('&C&24&K0000FF&B&U&A');
+$objPHPExcel->getActiveSheet()
+ ->getHeaderFooter()->setEvenHeader('&C&24&K0000FF&B&U&A');
+
+// Set print footers
+$objPHPExcel->getActiveSheet()
+ ->getHeaderFooter()->setOddFooter('&R&D &T&C&F&LPage &P / &N');
+$objPHPExcel->getActiveSheet()
+ ->getHeaderFooter()->setEvenFooter('&L&D &T&C&F&RPage &P / &N');
+
// Save Excel 2007 file
diff --git a/Examples/10autofilter-selection-1.php b/Examples/10autofilter-selection-1.php
index 188a3c225..8cdc0def4 100644
--- a/Examples/10autofilter-selection-1.php
+++ b/Examples/10autofilter-selection-1.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/10autofilter-selection-2.php b/Examples/10autofilter-selection-2.php
index a55bc2e56..e2aea748d 100644
--- a/Examples/10autofilter-selection-2.php
+++ b/Examples/10autofilter-selection-2.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/10autofilter-selection-display.php b/Examples/10autofilter-selection-display.php
new file mode 100644
index 000000000..ba3fed9e0
--- /dev/null
+++ b/Examples/10autofilter-selection-display.php
@@ -0,0 +1,198 @@
+');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// Create new PHPExcel object
+echo date('H:i:s').' Create new PHPExcel object'.EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s').' Set document properties'.EOL;
+$objPHPExcel->getProperties()->setCreator('Maarten Balliauw')
+ ->setLastModifiedBy('Maarten Balliauw')
+ ->setTitle('PHPExcel Test Document')
+ ->setSubject('PHPExcel Test Document')
+ ->setDescription('Test document for PHPExcel, generated using PHP classes.')
+ ->setKeywords('office PHPExcel php')
+ ->setCategory('Test result file');
+
+// Create the worksheet
+echo date('H:i:s').' Add data'.EOL;
+$objPHPExcel->setActiveSheetIndex(0);
+$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Financial Year')
+ ->setCellValue('B1', 'Financial Period')
+ ->setCellValue('C1', 'Country')
+ ->setCellValue('D1', 'Date')
+ ->setCellValue('E1', 'Sales Value')
+ ->setCellValue('F1', 'Expenditure')
+ ;
+$startYear = $endYear = $currentYear = date('Y');
+$startYear--;
+$endYear++;
+
+$years = range($startYear,$endYear);
+$periods = range(1,12);
+$countries = array( 'United States', 'UK', 'France', 'Germany',
+ 'Italy', 'Spain', 'Portugal', 'Japan'
+ );
+
+$row = 2;
+foreach($years as $year) {
+ foreach($periods as $period) {
+ foreach($countries as $country) {
+ $endDays = date('t',mktime(0,0,0,$period,1,$year));
+ for($i = 1; $i <= $endDays; ++$i) {
+ $eDate = PHPExcel_Shared_Date::FormattedPHPToExcel(
+ $year,
+ $period,
+ $i
+ );
+ $value = rand(500,1000) * (1 + rand(-0.25,+0.25));
+ $salesValue = $invoiceValue = NULL;
+ $incomeOrExpenditure = rand(-1,1);
+ if ($incomeOrExpenditure == -1) {
+ $expenditure = rand(-500,-1000) * (1 + rand(-0.25,+0.25));
+ $income = NULL;
+ } elseif ($incomeOrExpenditure == 1) {
+ $expenditure = rand(-500,-1000) * (1 + rand(-0.25,+0.25));
+ $income = rand(500,1000) * (1 + rand(-0.25,+0.25));;
+ } else {
+ $expenditure = NULL;
+ $income = rand(500,1000) * (1 + rand(-0.25,+0.25));;
+ }
+ $dataArray = array( $year,
+ $period,
+ $country,
+ $eDate,
+ $income,
+ $expenditure,
+ );
+ $objPHPExcel->getActiveSheet()->fromArray($dataArray, NULL, 'A'.$row++);
+ }
+ }
+ }
+}
+$row--;
+
+
+// Set styling
+echo date('H:i:s').' Set styling'.EOL;
+$objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true);
+$objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getAlignment()->setWrapText(TRUE);
+$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12.5);
+$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10.5);
+$objPHPExcel->getActiveSheet()->getStyle('D2:D'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
+$objPHPExcel->getActiveSheet()->getStyle('E2:F'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
+$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(14);
+$objPHPExcel->getActiveSheet()->freezePane('A2');
+
+
+
+// Set autofilter range
+echo date('H:i:s').' Set autofilter range'.EOL;
+// Always include the complete filter range!
+// Excel does support setting only the caption
+// row, but that's not a best practise...
+$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());
+
+// Set active filters
+$autoFilter = $objPHPExcel->getActiveSheet()->getAutoFilter();
+echo date('H:i:s').' Set active filters'.EOL;
+// Filter the Country column on a filter value of countries beginning with the letter U (or Japan)
+// We use * as a wildcard, so specify as U* and using a wildcard requires customFilter
+$autoFilter->getColumn('C')
+ ->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER)
+ ->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ 'u*'
+ )
+ ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
+$autoFilter->getColumn('C')
+ ->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ 'japan'
+ )
+ ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
+// Filter the Date column on a filter value of the first day of every period of the current year
+// We us a dateGroup ruletype for this, although it is still a standard filter
+foreach($periods as $period) {
+ $endDate = date('t',mktime(0,0,0,$period,1,$currentYear));
+
+ $autoFilter->getColumn('D')
+ ->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER)
+ ->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ array(
+ 'year' => $currentYear,
+ 'month' => $period,
+ 'day' => $endDate
+ )
+ )
+ ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP);
+}
+// Display only sales values that are blank
+// Standard filter, operator equals, and value of NULL
+$autoFilter->getColumn('E')
+ ->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER)
+ ->createRule()
+ ->setRule(
+ PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
+ ''
+ );
+
+// Execute filtering
+echo date('H:i:s').' Execute filtering'.EOL;
+$autoFilter->showHideRows();
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Display Results of filtering
+echo date('H:i:s').' Display filtered rows'.EOL;
+foreach ($objPHPExcel->getActiveSheet()->getRowIterator() as $row) {
+ if ($objPHPExcel->getActiveSheet()->getRowDimension($row->getRowIndex())->getVisible()) {
+ echo ' Row number - ' , $row->getRowIndex() , ' ';
+ echo $objPHPExcel->getActiveSheet()->getCell('C'.$row->getRowIndex())->getValue(), ' ';
+ echo $objPHPExcel->getActiveSheet()->getCell('D'.$row->getRowIndex())->getFormattedValue(), ' ';
+ echo EOL;
+ }
+}
diff --git a/Examples/10autofilter.php b/Examples/10autofilter.php
index 682248bbe..015e9cfe3 100644
--- a/Examples/10autofilter.php
+++ b/Examples/10autofilter.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
echo date('H:i:s').' Create new PHPExcel object'.EOL;
diff --git a/Examples/11documentsecurity-xls.php b/Examples/11documentsecurity-xls.php
index 0ccc7d7d6..2348ce959 100644
--- a/Examples/11documentsecurity-xls.php
+++ b/Examples/11documentsecurity-xls.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/11documentsecurity.php b/Examples/11documentsecurity.php
index a1ac2e25d..9fd4fb2a4 100644
--- a/Examples/11documentsecurity.php
+++ b/Examples/11documentsecurity.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/12cellProtection.php b/Examples/12cellProtection.php
new file mode 100644
index 000000000..e12c9ae47
--- /dev/null
+++ b/Examples/12cellProtection.php
@@ -0,0 +1,107 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set document properties" , EOL;
+$objPHPExcel->getProperties()->setCreator("Mark Baker")
+ ->setLastModifiedBy("Mark Baker")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
+
+
+// Add some data
+echo date('H:i:s') , " Add some data" , EOL;
+$objPHPExcel->setActiveSheetIndex(0);
+$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Crouching');
+$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Tiger');
+$objPHPExcel->getActiveSheet()->setCellValue('A2', 'Hidden');
+$objPHPExcel->getActiveSheet()->setCellValue('B2', 'Dragon');
+
+// Rename worksheet
+echo date('H:i:s') , " Rename worksheet" , EOL;
+$objPHPExcel->getActiveSheet()->setTitle('Simple');
+
+
+// Set document security
+echo date('H:i:s') , " Set cell protection" , EOL;
+
+
+// Set sheet security
+echo date('H:i:s') , " Set sheet security" , EOL;
+$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
+$objPHPExcel->getActiveSheet()
+ ->getStyle('A2:B2')
+ ->getProtection()->setLocked(
+ PHPExcel_Style_Protection::PROTECTION_UNPROTECTED
+ );
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/13calculation.php b/Examples/13calculation.php
index 36db08826..e255d115f 100644
--- a/Examples/13calculation.php
+++ b/Examples/13calculation.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,9 +34,10 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
date_default_timezone_set('Europe/London');
+mt_srand(1234567890);
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// List functions
@@ -207,6 +208,15 @@
$callStartTime = microtime(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+
+//
+// If we set Pre Calculated Formulas to true then PHPExcel will calculate all formulae in the
+// workbook before saving. This adds time and memory overhead, and can cause some problems with formulae
+// using functions or features (such as array formulae) that aren't yet supported by the calculation engine
+// If the value is false (the default) for the Excel2007 Writer, then MS Excel (or the application used to
+// open the file) will need to recalculate values itself to guarantee that the correct results are available.
+//
+//$objWriter->setPreCalculateFormulas(true);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
diff --git a/Examples/13calculationCyclicFormulae.php b/Examples/13calculationCyclicFormulae.php
new file mode 100644
index 000000000..8512a3e85
--- /dev/null
+++ b/Examples/13calculationCyclicFormulae.php
@@ -0,0 +1,97 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// 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('A1', '=B1')
+ ->setCellValue('A2', '=B2+1')
+ ->setCellValue('B1', '=A1+1')
+ ->setCellValue('B2', '=A2');
+
+PHPExcel_Calculation::getInstance($objPHPExcel)->cyclicFormulaCount = 100;
+
+// Calculated data
+echo date('H:i:s') , " Calculated data" , EOL;
+for($row = 1; $row <= 2; ++$row) {
+ for ($col = 'A'; $col != 'C'; ++$col) {
+ if ((!is_null($formula = $objPHPExcel->getActiveSheet()->getCell($col.$row)->getValue())) &&
+ ($formula[0] == '=')) {
+ echo 'Value of ' , $col , $row , ' [' , $formula , ']: ' ,
+ $objPHPExcel->getActiveSheet()->getCell($col.$row)->getCalculatedValue() . EOL;
+ }
+ }
+}
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+
+//
+// If we set Pre Calculated Formulas to true then PHPExcel will calculate all formulae in the
+// workbook before saving. This adds time and memory overhead, and can cause some problems with formulae
+// using functions or features (such as array formulae) that aren't yet supported by the calculation engine
+// If the value is false (the default) for the Excel2007 Writer, then MS Excel (or the application used to
+// open the file) will need to recalculate values itself to guarantee that the correct results are available.
+//
+//$objWriter->setPreCalculateFormulas(true);
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/14excel5.php b/Examples/14excel5.php
index b35308b3b..7a9f6856f 100644
--- a/Examples/14excel5.php
+++ b/Examples/14excel5.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -37,7 +37,7 @@
include "05featuredemo.inc.php";
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
// Save Excel 95 file
diff --git a/Examples/15datavalidation-xls.php b/Examples/15datavalidation-xls.php
index 2cb893dfe..3f0afde53 100644
--- a/Examples/15datavalidation-xls.php
+++ b/Examples/15datavalidation-xls.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -47,22 +47,31 @@
// Set document properties
echo date('H:i:s') , " Set document properties" , EOL;
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
- ->setLastModifiedBy("Maarten Balliauw")
- ->setTitle("Office 2007 XLSX Test Document")
- ->setSubject("Office 2007 XLSX Test Document")
- ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
- ->setKeywords("office 2007 openxml php")
- ->setCategory("Test result file");
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
// Create a first sheet
echo date('H:i:s') , " Add data" , EOL;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', "Cell B3 and B5 contain data validation...")
- ->setCellValue('A3', "Number:")
- ->setCellValue('B3', "10")
- ->setCellValue('A5', "List:")
- ->setCellValue('B5', "Item A");
+ ->setCellValue('A3', "Number:")
+ ->setCellValue('B3', "10")
+ ->setCellValue('A5', "List:")
+ ->setCellValue('B5', "Item A")
+ ->setCellValue('A7', "List #2:")
+ ->setCellValue('B7', "Item #2")
+ ->setCellValue('D2', "Item #1")
+ ->setCellValue('D3', "Item #2")
+ ->setCellValue('D4', "Item #3")
+ ->setCellValue('D5', "Item #4")
+ ->setCellValue('D6', "Item #5")
+ ->setCellValue('A9', 'Text:')
+ ;
// Set data validation
@@ -93,6 +102,31 @@
$objValidation->setPrompt('Please pick a value from the drop-down list.');
$objValidation->setFormula1('"Item A,Item B,Item C"'); // Make sure to put the list items between " and " !!!
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B7')->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
+$objValidation->setAllowBlank(false);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setShowDropDown(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Value is not in list.');
+$objValidation->setPromptTitle('Pick from list');
+$objValidation->setPrompt('Please pick a value from the drop-down list.');
+$objValidation->setFormula1('$D$2:$D$6'); // Make sure NOT to put a range of cells or a formula between " and " !!!
+
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B9')->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
+$objValidation->setAllowBlank(true);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Text exceeds maximum length');
+$objValidation->setPromptTitle('Allowed input');
+$objValidation->setPrompt('Maximum text length is 6 characters.');
+$objValidation->setFormula1(6);
+
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
diff --git a/Examples/15datavalidation.php b/Examples/15datavalidation.php
index 373150d87..132063d8e 100644
--- a/Examples/15datavalidation.php
+++ b/Examples/15datavalidation.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -47,22 +47,31 @@
// Set document properties
echo date('H:i:s') , " Set document properties" , EOL;
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
- ->setLastModifiedBy("Maarten Balliauw")
- ->setTitle("Office 2007 XLSX Test Document")
- ->setSubject("Office 2007 XLSX Test Document")
- ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
- ->setKeywords("office 2007 openxml php")
- ->setCategory("Test result file");
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("Office 2007 XLSX Test Document")
+ ->setSubject("Office 2007 XLSX Test Document")
+ ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
+ ->setKeywords("office 2007 openxml php")
+ ->setCategory("Test result file");
// Create a first sheet
echo date('H:i:s') , " Add data" , EOL;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', "Cell B3 and B5 contain data validation...")
- ->setCellValue('A3', "Number:")
- ->setCellValue('B3', "10")
- ->setCellValue('A5', "List:")
- ->setCellValue('B5', "Item A");
+ ->setCellValue('A3', "Number:")
+ ->setCellValue('B3', "10")
+ ->setCellValue('A5', "List:")
+ ->setCellValue('B5', "Item A")
+ ->setCellValue('A7', "List #2:")
+ ->setCellValue('B7', "Item #2")
+ ->setCellValue('D2', "Item #1")
+ ->setCellValue('D3', "Item #2")
+ ->setCellValue('D4', "Item #3")
+ ->setCellValue('D5', "Item #4")
+ ->setCellValue('D6', "Item #5")
+ ->setCellValue('A9', 'Text:')
+ ;
// Set data validation
@@ -91,7 +100,33 @@
$objValidation->setError('Value is not in list.');
$objValidation->setPromptTitle('Pick from list');
$objValidation->setPrompt('Please pick a value from the drop-down list.');
-$objValidation->setFormula1('"Item A,Item B,Item C"'); // Make sure to put the list items between " and " !!!
+$objValidation->setFormula1('"Item A,Item B,Item C"'); // Make sure to put the list items between " and " if your list is simply a comma-separated list of values !!!
+
+
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B7')->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
+$objValidation->setAllowBlank(false);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setShowDropDown(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Value is not in list.');
+$objValidation->setPromptTitle('Pick from list');
+$objValidation->setPrompt('Please pick a value from the drop-down list.');
+$objValidation->setFormula1('$D$2:$D$6'); // Make sure NOT to put a range of cells or a formula between " and " !!!
+
+$objValidation = $objPHPExcel->getActiveSheet()->getCell('B9')->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH );
+$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
+$objValidation->setAllowBlank(true);
+$objValidation->setShowInputMessage(true);
+$objValidation->setShowErrorMessage(true);
+$objValidation->setErrorTitle('Input error');
+$objValidation->setError('Text exceeds maximum length');
+$objValidation->setPromptTitle('Allowed input');
+$objValidation->setPrompt('Maximum text length is 6 characters.');
+$objValidation->setFormula1(6);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
diff --git a/Examples/16csv.php b/Examples/16csv.php
index b4070e655..8d42fcbba 100644
--- a/Examples/16csv.php
+++ b/Examples/16csv.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -46,7 +46,6 @@
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')->setDelimiter(',')
->setEnclosure('"')
- ->setLineEnding("\r\n")
->setSheetIndex(0)
->save(str_replace('.php', '.csv', __FILE__));
$callEndTime = microtime(true);
@@ -61,7 +60,6 @@
$callStartTime = microtime(true);
$objReader = PHPExcel_IOFactory::createReader('CSV')->setDelimiter(',')
->setEnclosure('"')
- ->setLineEnding("\r\n")
->setSheetIndex(0);
$objPHPExcelFromCSV = $objReader->load(str_replace('.php', '.csv', __FILE__));
@@ -85,6 +83,20 @@
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+echo date('H:i:s') , " Write to CSV format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriterCSV = PHPExcel_IOFactory::createWriter($objPHPExcelFromCSV, 'CSV');
+$objWriterCSV->setExcelCompatibility(true);
+$objWriterCSV->save(str_replace('.php', '_excel.csv', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+echo date('H:i:s') , " File written to " , str_replace('.php', '_excel.csv', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
diff --git a/Examples/17html.php b/Examples/17html.php
index 222197d2f..b84f8d4ed 100644
--- a/Examples/17html.php
+++ b/Examples/17html.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -38,7 +38,7 @@
include "05featuredemo.inc.php";
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
echo date('H:i:s') , " Write to HTML format" , EOL;
diff --git a/Examples/18extendedcalculation.php b/Examples/18extendedcalculation.php
index 2cc8137b6..59aeb3005 100644
--- a/Examples/18extendedcalculation.php
+++ b/Examples/18extendedcalculation.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// List functions
diff --git a/Examples/19namedrange.php b/Examples/19namedrange.php
index ed0ab283e..7876ea58b 100644
--- a/Examples/19namedrange.php
+++ b/Examples/19namedrange.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/20readexcel5.php b/Examples/20readexcel5.php
index 37f1a1e8a..7625c7b81 100644
--- a/Examples/20readexcel5.php
+++ b/Examples/20readexcel5.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
if (!file_exists("14excel5.xls")) {
diff --git a/Examples/21pdf.php b/Examples/21pdf.php
index a85a240fe..b26ddb8b1 100644
--- a/Examples/21pdf.php
+++ b/Examples/21pdf.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -38,7 +38,7 @@
include "05featuredemo.inc.php";
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
// Change these values to select the Rendering library that you wish to use
diff --git a/Examples/22heavilyformatted.php b/Examples/22heavilyformatted.php
index 14e231048..98c7d184e 100644
--- a/Examples/22heavilyformatted.php
+++ b/Examples/22heavilyformatted.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/23sharedstyles.php b/Examples/23sharedstyles.php
index 7e71d6e0e..22eadba1c 100644
--- a/Examples/23sharedstyles.php
+++ b/Examples/23sharedstyles.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -36,7 +36,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/24readfilter.php b/Examples/24readfilter.php
index 386f40d78..000d180a4 100644
--- a/Examples/24readfilter.php
+++ b/Examples/24readfilter.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
date_default_timezone_set('Europe/London');
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
// Check prerequisites
diff --git a/Examples/25inmemoryimage.php b/Examples/25inmemoryimage.php
index 0ed15085d..6c3b0b845 100644
--- a/Examples/25inmemoryimage.php
+++ b/Examples/25inmemoryimage.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
@@ -75,9 +75,15 @@
echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo date('H:i:s') , " Write to HTML format" , EOL;
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
+$objWriter->save(str_replace('.php', '.html', __FILE__));
+echo date('H:i:s') , " File written to " , str_replace('.php', '.html', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+
+
// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
-echo 'File has been created in ' , getcwd() , EOL;
+echo 'Files have been created in ' , getcwd() , EOL;
diff --git a/Examples/26utf8.php b/Examples/26utf8.php
index a760d27f4..112c5c73f 100644
--- a/Examples/26utf8.php
+++ b/Examples/26utf8.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Change these values to select the PDF Rendering library that you wish to use
diff --git a/Examples/27imagesexcel5.php b/Examples/27imagesexcel5.php
index 462ec6e73..a4f6a9d7d 100644
--- a/Examples/27imagesexcel5.php
+++ b/Examples/27imagesexcel5.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Read from Excel5 (.xls) template
diff --git a/Examples/28iterator.php b/Examples/28iterator.php
index 1c6e6d856..1ba9cbee0 100644
--- a/Examples/28iterator.php
+++ b/Examples/28iterator.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,18 +35,14 @@
date_default_timezone_set('Europe/London');
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
-if (!file_exists("05featuredemo.xlsx")) {
- exit("Please run 05featuredemo.php first." . EOL);
-}
-
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
-$objPHPExcel = $objReader->load("05featuredemo.xlsx");
+$objPHPExcel = $objReader->load("./templates/28iterators.xlsx");
-echo date('H:i:s') , " Iterate worksheets" , EOL;
+echo date('H:i:s') , " Iterate worksheets by Row" , EOL;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle() , EOL;
@@ -64,5 +60,23 @@
}
+echo date('H:i:s') , " Iterate worksheets by Column" , EOL;
+foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
+ echo 'Worksheet - ' , $worksheet->getTitle() , EOL;
+
+ foreach ($worksheet->getColumnIterator() as $column) {
+ echo ' Column index - ' , $column->getColumnIndex() , EOL;
+
+ $cellIterator = $column->getCellIterator();
+ $cellIterator->setIterateOnlyExistingCells(true); // Loop all cells, even if it is not set
+ foreach ($cellIterator as $cell) {
+ if (!is_null($cell)) {
+ echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue() , EOL;
+ }
+ }
+ }
+}
+
+
// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
diff --git a/Examples/29advancedvaluebinder.php b/Examples/29advancedvaluebinder.php
index 71307e692..a172c6cde 100644
--- a/Examples/29advancedvaluebinder.php
+++ b/Examples/29advancedvaluebinder.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -33,7 +33,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Set timezone
diff --git a/Examples/30template.php b/Examples/30template.php
index 6367de07f..db9cbb451 100644
--- a/Examples/30template.php
+++ b/Examples/30template.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
diff --git a/Examples/31docproperties_write-xls.php b/Examples/31docproperties_write-xls.php
index 6c1368177..e9a5e876a 100644
--- a/Examples/31docproperties_write-xls.php
+++ b/Examples/31docproperties_write-xls.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
$inputFileType = 'Excel5';
diff --git a/Examples/31docproperties_write.php b/Examples/31docproperties_write.php
index 7e4749794..4cd477956 100644
--- a/Examples/31docproperties_write.php
+++ b/Examples/31docproperties_write.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,7 +35,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
$inputFileType = 'Excel2007';
diff --git a/Examples/32chartreadwrite.php b/Examples/32chartreadwrite.php
index 797612e9e..5aeedcaeb 100644
--- a/Examples/32chartreadwrite.php
+++ b/Examples/32chartreadwrite.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,13 +31,13 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
+set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
diff --git a/Examples/33chartcreate-area.php b/Examples/33chartcreate-area.php
index 1e53b6041..fac8ce93f 100644
--- a/Examples/33chartcreate-area.php
+++ b/Examples/33chartcreate-area.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -61,7 +59,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -94,13 +92,13 @@
PHPExcel_Chart_DataSeries::TYPE_AREACHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_PERCENT_STACKED, // plotGrouping
range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
+ $dataSeriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, NULL, false);
@@ -113,7 +111,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-bar-stacked.php b/Examples/33chartcreate-bar-stacked.php
index f6465ee76..af9493f7a 100644
--- a/Examples/33chartcreate-bar-stacked.php
+++ b/Examples/33chartcreate-bar-stacked.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -61,7 +59,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -94,7 +92,7 @@
PHPExcel_Chart_DataSeries::TYPE_BARCHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_STACKED, // plotGrouping
range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
+ $dataSeriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
@@ -103,7 +101,7 @@
$series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_BAR);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -116,7 +114,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-bar.php b/Examples/33chartcreate-bar.php
index 764942f09..653675d69 100644
--- a/Examples/33chartcreate-bar.php
+++ b/Examples/33chartcreate-bar.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -61,7 +59,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -94,7 +92,7 @@
PHPExcel_Chart_DataSeries::TYPE_BARCHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_CLUSTERED, // plotGrouping
range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
+ $dataSeriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
@@ -103,7 +101,7 @@
$series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_BAR);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -116,7 +114,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-column-2.php b/Examples/33chartcreate-column-2.php
index 921049922..0ade332c9 100644
--- a/Examples/33chartcreate-column-2.php
+++ b/Examples/33chartcreate-column-2.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -69,7 +67,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 'Budget'
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 'Forecast'
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$E$1', NULL, 1), // 'Actual'
@@ -102,7 +100,7 @@
PHPExcel_Chart_DataSeries::TYPE_BARCHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_CLUSTERED, // plotGrouping
range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
+ $dataSeriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
@@ -111,7 +109,7 @@
$series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_BOTTOM, NULL, false);
@@ -125,7 +123,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
$xAxisLabel, // xAxisLabel
diff --git a/Examples/33chartcreate-column.php b/Examples/33chartcreate-column.php
index 6feacf9ad..67f417847 100644
--- a/Examples/33chartcreate-column.php
+++ b/Examples/33chartcreate-column.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -61,7 +59,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -94,7 +92,7 @@
PHPExcel_Chart_DataSeries::TYPE_BARCHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping
range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
+ $dataSeriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
@@ -103,7 +101,7 @@
$series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -116,7 +114,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-composite-chart.php b/Examples/33chartcreate-composite.php
similarity index 92%
rename from Examples/33chartcreate-composite-chart.php
rename to Examples/33chartcreate-composite.php
index 14496f1c9..be7ad94a7 100644
--- a/Examples/33chartcreate-composite-chart.php
+++ b/Examples/33chartcreate-composite.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -70,13 +68,13 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels1 = array(
+$dataSeriesLabels1 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // Temperature
);
-$dataseriesLabels2 = array(
+$dataSeriesLabels2 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // Rainfall
);
-$dataseriesLabels3 = array(
+$dataSeriesLabels3 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // Humidity
);
@@ -108,7 +106,7 @@
PHPExcel_Chart_DataSeries::TYPE_BARCHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_CLUSTERED, // plotGrouping
range(0, count($dataSeriesValues1)-1), // plotOrder
- $dataseriesLabels1, // plotLabel
+ $dataSeriesLabels1, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues1 // plotValues
);
@@ -133,7 +131,7 @@
PHPExcel_Chart_DataSeries::TYPE_LINECHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping
range(0, count($dataSeriesValues2)-1), // plotOrder
- $dataseriesLabels2, // plotLabel
+ $dataSeriesLabels2, // plotLabel
NULL, // plotCategory
$dataSeriesValues2 // plotValues
);
@@ -155,14 +153,14 @@
PHPExcel_Chart_DataSeries::TYPE_AREACHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping
range(0, count($dataSeriesValues2)-1), // plotOrder
- $dataseriesLabels3, // plotLabel
+ $dataSeriesLabels3, // plotLabel
NULL, // plotCategory
$dataSeriesValues3 // plotValues
);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series1, $series2, $series3));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series1, $series2, $series3));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -174,7 +172,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-line.php b/Examples/33chartcreate-line.php
index 8fc9714e7..90c2e60c0 100644
--- a/Examples/33chartcreate-line.php
+++ b/Examples/33chartcreate-line.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -61,7 +59,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -94,13 +92,13 @@
PHPExcel_Chart_DataSeries::TYPE_LINECHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_STACKED, // plotGrouping
range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
+ $dataSeriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues // plotValues
);
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, NULL, false);
@@ -113,7 +111,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-multiple-charts.php b/Examples/33chartcreate-multiple-charts.php
index a8943eec1..0e5ac60e2 100644
--- a/Examples/33chartcreate-multiple-charts.php
+++ b/Examples/33chartcreate-multiple-charts.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -62,7 +60,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels1 = array(
+$dataSeriesLabels1 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -95,13 +93,13 @@
PHPExcel_Chart_DataSeries::TYPE_AREACHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_PERCENT_STACKED, // plotGrouping
range(0, count($dataSeriesValues1)-1), // plotOrder
- $dataseriesLabels1, // plotLabel
+ $dataSeriesLabels1, // plotLabel
$xAxisTickValues1, // plotCategory
$dataSeriesValues1 // plotValues
);
// Set the series in the plot area
-$plotarea1 = new PHPExcel_Chart_PlotArea(NULL, array($series1));
+$plotArea1 = new PHPExcel_Chart_PlotArea(NULL, array($series1));
// Set the chart legend
$legend1 = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, NULL, false);
@@ -114,7 +112,7 @@
'chart1', // name
$title1, // title
$legend1, // legend
- $plotarea1, // plotArea
+ $plotArea1, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
@@ -136,7 +134,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels2 = array(
+$dataSeriesLabels2 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
@@ -169,7 +167,7 @@
PHPExcel_Chart_DataSeries::TYPE_BARCHART, // plotType
PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping
range(0, count($dataSeriesValues2)-1), // plotOrder
- $dataseriesLabels2, // plotLabel
+ $dataSeriesLabels2, // plotLabel
$xAxisTickValues2, // plotCategory
$dataSeriesValues2 // plotValues
);
@@ -178,7 +176,7 @@
$series2->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);
// Set the series in the plot area
-$plotarea2 = new PHPExcel_Chart_PlotArea(NULL, array($series2));
+$plotArea2 = new PHPExcel_Chart_PlotArea(NULL, array($series2));
// Set the chart legend
$legend2 = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -191,7 +189,7 @@
'chart2', // name
$title2, // title
$legend2, // legend
- $plotarea2, // plotArea
+ $plotArea2, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-pie.php b/Examples/33chartcreate-pie.php
index fe68ba2c3..78b6293f8 100644
--- a/Examples/33chartcreate-pie.php
+++ b/Examples/33chartcreate-pie.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -62,7 +60,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels1 = array(
+$dataSeriesLabels1 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
);
// Set the X-Axis Labels
@@ -89,9 +87,9 @@
// Build the dataseries
$series1 = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_PIECHART, // plotType
- PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping
+ NULL, // plotGrouping (Pie charts don't have any grouping)
range(0, count($dataSeriesValues1)-1), // plotOrder
- $dataseriesLabels1, // plotLabel
+ $dataSeriesLabels1, // plotLabel
$xAxisTickValues1, // plotCategory
$dataSeriesValues1 // plotValues
);
@@ -102,7 +100,7 @@
$layout1->setShowPercent(TRUE);
// Set the series in the plot area
-$plotarea1 = new PHPExcel_Chart_PlotArea($layout1, array($series1));
+$plotArea1 = new PHPExcel_Chart_PlotArea($layout1, array($series1));
// Set the chart legend
$legend1 = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -114,7 +112,7 @@
'chart1', // name
$title1, // title
$legend1, // legend
- $plotarea1, // plotArea
+ $plotArea1, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
@@ -136,7 +134,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels2 = array(
+$dataSeriesLabels2 = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
);
// Set the X-Axis Labels
@@ -163,9 +161,9 @@
// Build the dataseries
$series2 = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_DONUTCHART, // plotType
- PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping
+ NULL, // plotGrouping (Donut charts don't have any grouping)
range(0, count($dataSeriesValues2)-1), // plotOrder
- $dataseriesLabels2, // plotLabel
+ $dataSeriesLabels2, // plotLabel
$xAxisTickValues2, // plotCategory
$dataSeriesValues2 // plotValues
);
@@ -176,7 +174,7 @@
$layout2->setShowCatName(TRUE);
// Set the series in the plot area
-$plotarea2 = new PHPExcel_Chart_PlotArea($layout2, array($series2));
+$plotArea2 = new PHPExcel_Chart_PlotArea($layout2, array($series2));
$title2 = new PHPExcel_Chart_Title('Test Donut Chart');
@@ -186,7 +184,7 @@
'chart2', // name
$title2, // title
NULL, // legend
- $plotarea2, // plotArea
+ $plotArea2, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-radar.php b/Examples/33chartcreate-radar.php
index a1bb413ac..7d1047a42 100644
--- a/Examples/33chartcreate-radar.php
+++ b/Examples/33chartcreate-radar.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,14 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
@@ -70,7 +68,7 @@
// Number of datapoints in series
// Data values
// Data Marker
-$dataseriesLabels = array(
+$dataSeriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
);
@@ -99,21 +97,22 @@
// Build the dataseries
$series = new PHPExcel_Chart_DataSeries(
- PHPExcel_Chart_DataSeries::TYPE_RADARCHART, // plotType
- NULL, // plotGrouping
- range(0, count($dataSeriesValues)-1), // plotOrder
- $dataseriesLabels, // plotLabel
- $xAxisTickValues, // plotCategory
- $dataSeriesValues, // plotValues
- NULL, // smooth line
- PHPExcel_Chart_DataSeries::STYLE_MARKER // plotStyle
+ PHPExcel_Chart_DataSeries::TYPE_RADARCHART, // plotType
+ NULL, // plotGrouping (Radar charts don't have any grouping)
+ range(0, count($dataSeriesValues)-1), // plotOrder
+ $dataSeriesLabels, // plotLabel
+ $xAxisTickValues, // plotCategory
+ $dataSeriesValues, // plotValues
+ NULL, // plotDirection
+ NULL, // smooth line
+ PHPExcel_Chart_DataSeries::STYLE_MARKER // plotStyle
);
// Set up a layout object for the Pie chart
$layout = new PHPExcel_Chart_Layout();
// Set the series in the plot area
-$plotarea = new PHPExcel_Chart_PlotArea($layout, array($series));
+$plotArea = new PHPExcel_Chart_PlotArea($layout, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
@@ -125,7 +124,7 @@
'chart1', // name
$title, // title
$legend, // legend
- $plotarea, // plotArea
+ $plotArea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
NULL, // xAxisLabel
diff --git a/Examples/33chartcreate-scatter.php b/Examples/33chartcreate-scatter.php
new file mode 100644
index 000000000..a5fab8272
--- /dev/null
+++ b/Examples/33chartcreate-scatter.php
@@ -0,0 +1,139 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/**
+ * PHPExcel
+ *
+ * Copyright (c) 2006 - 2015 PHPExcel
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category PHPExcel
+ * @package PHPExcel
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @version ##VERSION##, ##DATE##
+ */
+
+/** PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+$objPHPExcel = new PHPExcel();
+$objWorksheet = $objPHPExcel->getActiveSheet();
+$objWorksheet->fromArray(
+ array(
+ array('', 2010, 2011, 2012),
+ array('Q1', 12, 15, 21),
+ array('Q2', 56, 73, 86),
+ array('Q3', 52, 61, 69),
+ array('Q4', 30, 32, 0),
+ )
+);
+
+// Set the Labels for each data series we want to plot
+// Datatype
+// Cell reference for data
+// Format Code
+// Number of datapoints in series
+// Data values
+// Data Marker
+$dataSeriesLabels = array(
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), // 2010
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), // 2012
+);
+// Set the X-Axis Labels
+$xAxisTickValues = array(
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$5', NULL, 4), // Q1 to Q4
+);
+// Set the Data values for each data series we want to plot
+// Datatype
+// Cell reference for data
+// Format Code
+// Number of datapoints in series
+// Data values
+// Data Marker
+$dataSeriesValues = array(
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$5', NULL, 4),
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$5', NULL, 4),
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$D$2:$D$5', NULL, 4),
+);
+
+// Build the dataseries
+$series = new PHPExcel_Chart_DataSeries(
+ PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART, // plotType
+ NULL, // plotGrouping (Scatter charts don't have any grouping)
+ range(0, count($dataSeriesValues)-1), // plotOrder
+ $dataSeriesLabels, // plotLabel
+ $xAxisTickValues, // plotCategory
+ $dataSeriesValues, // plotValues
+ NULL, // plotDirection
+ NULL, // smooth line
+ PHPExcel_Chart_DataSeries::STYLE_LINEMARKER // plotStyle
+);
+
+// Set the series in the plot area
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+// Set the chart legend
+$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_TOPRIGHT, NULL, false);
+
+$title = new PHPExcel_Chart_Title('Test Scatter Chart');
+$yAxisLabel = new PHPExcel_Chart_Title('Value ($k)');
+
+
+// Create the chart
+$chart = new PHPExcel_Chart(
+ 'chart1', // name
+ $title, // title
+ $legend, // legend
+ $plotArea, // plotArea
+ true, // plotVisibleOnly
+ 0, // displayBlanksAs
+ NULL, // xAxisLabel
+ $yAxisLabel // yAxisLabel
+);
+
+// Set the position where the chart should appear in the worksheet
+$chart->setTopLeftPosition('A7');
+$chart->setBottomRightPosition('H20');
+
+// Add the chart to the worksheet
+$objWorksheet->addChart($chart);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->setIncludeCharts(TRUE);
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/33chartcreate-stock.php b/Examples/33chartcreate-stock.php
new file mode 100644
index 000000000..465107b3a
--- /dev/null
+++ b/Examples/33chartcreate-stock.php
@@ -0,0 +1,151 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+/**
+ * PHPExcel
+ *
+ * Copyright (c) 2006 - 2015 PHPExcel
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category PHPExcel
+ * @package PHPExcel
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
+ * @version ##VERSION##, ##DATE##
+ */
+
+/** PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+$objPHPExcel = new PHPExcel();
+$objWorksheet = $objPHPExcel->getActiveSheet();
+$objWorksheet->fromArray(
+ array(
+ array('Counts', 'Max', 'Min', 'Min Threshold', 'Max Threshold' ),
+ array(10, 10, 5, 0, 50 ),
+ array(30, 20, 10, 0, 50 ),
+ array(20, 30, 15, 0, 50 ),
+ array(40, 10, 0, 0, 50 ),
+ array(100, 40, 5, 0, 50 ),
+ ), null, 'A1', true
+);
+$objWorksheet->getStyle('B2:E6')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);
+
+
+// Set the Labels for each data series we want to plot
+// Datatype
+// Cell reference for data
+// Format Code
+// Number of datapoints in series
+// Data values
+// Data Marker
+$dataSeriesLabels = array(
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1), //Max / Open
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), //Min / Close
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$D$1', NULL, 1), //Min Threshold / Min
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$E$1', NULL, 1), //Max Threshold / Max
+);
+// Set the X-Axis Labels
+// Datatype
+// Cell reference for data
+// Format Code
+// Number of datapoints in series
+// Data values
+// Data Marker
+$xAxisTickValues = array(
+ new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$6', NULL, 5), // Counts
+);
+// Set the Data values for each data series we want to plot
+// Datatype
+// Cell reference for data
+// Format Code
+// Number of datapoints in series
+// Data values
+// Data Marker
+$dataSeriesValues = array(
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$6', NULL, 5),
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$6', NULL, 5),
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$D$2:$D$6', NULL, 5),
+ new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$E$2:$E$6', NULL, 5),
+);
+
+// Build the dataseries
+$series = new PHPExcel_Chart_DataSeries(
+ PHPExcel_Chart_DataSeries::TYPE_STOCKCHART, // plotType
+ null, // plotGrouping - if we set this to not null, then xlsx throws error
+ range(0, count($dataSeriesValues)-1), // plotOrder
+ $dataSeriesLabels, // plotLabel
+ $xAxisTickValues, // plotCategory
+ $dataSeriesValues // plotValues
+);
+
+// Set the series in the plot area
+$plotArea = new PHPExcel_Chart_PlotArea(NULL, array($series));
+// Set the chart legend
+$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
+
+$title = new PHPExcel_Chart_Title('Test Stock Chart');
+$xAxisLabel = new PHPExcel_Chart_Title('Counts');
+$yAxisLabel = new PHPExcel_Chart_Title('Values');
+
+// Create the chart
+$chart = new PHPExcel_Chart(
+ 'stock-chart', // name
+ $title, // title
+ $legend, // legend
+ $plotArea, // plotArea
+ true, // plotVisibleOnly
+ 0, // displayBlanksAs
+ $xAxisLabel, // xAxisLabel
+ $yAxisLabel // yAxisLabel
+);
+
+// Set the position where the chart should appear in the worksheet
+$chart->setTopLeftPosition('A7');
+$chart->setBottomRightPosition('H20');
+
+// Add the chart to the worksheet
+$objWorksheet->addChart($chart);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->setIncludeCharts(TRUE);
+$filename = str_replace('.php', '.xlsx', __FILE__);
+if(file_exists($filename)) {
+ unlink($filename);
+}
+$objWriter->save($filename);
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing file" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/34chartupdate.php b/Examples/34chartupdate.php
index c60217235..f4b36c6bf 100644
--- a/Examples/34chartupdate.php
+++ b/Examples/34chartupdate.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,16 +31,13 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
-/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
-
/** PHPExcel */
-include 'PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
if (!file_exists("33chartcreate-bar.xlsx")) {
exit("Please run 33chartcreate-bar.php first." . EOL);
diff --git a/Examples/35chartrender.php b/Examples/35chartrender.php
index 601fb4c89..62719e51d 100644
--- a/Examples/35chartrender.php
+++ b/Examples/35chartrender.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,13 +31,13 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
+set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
@@ -46,7 +46,7 @@
// Change these values to select the Rendering library that you wish to use
// and its directory location on your server
$rendererName = PHPExcel_Settings::CHART_RENDERER_JPGRAPH;
-$rendererLibrary = 'jpgraph3.5.0b1/src';
+$rendererLibrary = 'jpgraph3.5.0b1/src/';
$rendererLibraryPath = '/php/libraries/Charts/' . $rendererLibrary;
diff --git a/Examples/36chartreadwriteHTML.php b/Examples/36chartreadwriteHTML.php
index 3998378cf..7fc26fdee 100644
--- a/Examples/36chartreadwriteHTML.php
+++ b/Examples/36chartreadwriteHTML.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,13 +31,13 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
+set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
@@ -46,7 +46,7 @@
// Change these values to select the Rendering library that you wish to use
// and its directory location on your server
$rendererName = PHPExcel_Settings::CHART_RENDERER_JPGRAPH;
-$rendererLibrary = 'jpgraph3.5.0b1/src';
+$rendererLibrary = 'jpgraph3.5.0b1/src/';
$rendererLibraryPath = '/php/libraries/Charts/' . $rendererLibrary;
diff --git a/Examples/36chartreadwritePDF.php b/Examples/36chartreadwritePDF.php
index bdac4713c..24d1c857b 100644
--- a/Examples/36chartreadwritePDF.php
+++ b/Examples/36chartreadwritePDF.php
@@ -13,7 +13,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -31,13 +31,13 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
+set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
@@ -69,7 +69,7 @@
// Change these values to select the Rendering library that you wish to use
// for Chart images, and its directory location on your server
$rendererName = PHPExcel_Settings::CHART_RENDERER_JPGRAPH;
-$rendererLibrary = 'jpgraph3.5.0b1/src';
+$rendererLibrary = 'jpgraph3.5.0b1/src/';
$rendererLibraryPath = '/php/libraries/Charts/' . $rendererLibrary;
diff --git a/Examples/37page_layout_view.php b/Examples/37page_layout_view.php
index e25dafb1a..810ca3d21 100644
--- a/Examples/37page_layout_view.php
+++ b/Examples/37page_layout_view.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -34,7 +34,7 @@
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '
');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
diff --git a/Examples/38cloneWorksheet.php b/Examples/38cloneWorksheet.php
new file mode 100644
index 000000000..245f7da43
--- /dev/null
+++ b/Examples/38cloneWorksheet.php
@@ -0,0 +1,118 @@
+');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set document properties" , EOL;
+$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("PHPExcel Test Document")
+ ->setSubject("PHPExcel Test Document")
+ ->setDescription("Test document for PHPExcel, generated using PHP classes.")
+ ->setKeywords("office PHPExcel php")
+ ->setCategory("Test result file");
+
+
+// Add some data
+echo date('H:i:s') , " Add some data" , EOL;
+$objPHPExcel->setActiveSheetIndex(0)
+ ->setCellValue('A1', 'Hello')
+ ->setCellValue('B2', 'world!')
+ ->setCellValue('C1', 'Hello')
+ ->setCellValue('D2', 'world!');
+
+// Miscellaneous glyphs, UTF-8
+$objPHPExcel->setActiveSheetIndex(0)
+ ->setCellValue('A4', 'Miscellaneous glyphs')
+ ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
+
+
+$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
+$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
+$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
+
+
+// Rename worksheet
+echo date('H:i:s') , " Rename worksheet" , EOL;
+$objPHPExcel->getActiveSheet()->setTitle('Simple');
+
+
+// Clone worksheet
+echo date('H:i:s') , " Clone worksheet" , EOL;
+$clonedSheet = clone $objPHPExcel->getActiveSheet();
+$clonedSheet
+ ->setCellValue('A1', 'Goodbye')
+ ->setCellValue('A2', 'cruel')
+ ->setCellValue('C1', 'Goodbye')
+ ->setCellValue('C2', 'cruel');
+
+// Rename cloned worksheet
+echo date('H:i:s') , " Rename cloned worksheet" , EOL;
+$clonedSheet->setTitle('Simple Clone');
+$objPHPExcel->addSheet($clonedSheet);
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing files" , EOL;
+echo 'File has been created in ' , getcwd() , EOL;
diff --git a/Examples/39dropdown.php b/Examples/39dropdown.php
new file mode 100644
index 000000000..c8dcff67c
--- /dev/null
+++ b/Examples/39dropdown.php
@@ -0,0 +1,175 @@
+');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set document properties" , EOL;
+$objPHPExcel->getProperties()
+ ->setCreator("PHPOffice")
+ ->setLastModifiedBy("PHPOffice")
+ ->setTitle("PHPExcel Test Document")
+ ->setSubject("PHPExcel Test Document")
+ ->setDescription("Test document for PHPExcel, generated using PHP classes.")
+ ->setKeywords("Office PHPExcel php")
+ ->setCategory("Test result file");
+
+
+function transpose($value) {
+ return array($value);
+}
+
+// Add some data
+$continentColumn = 'D';
+$column = 'F';
+
+// Set data for dropdowns
+foreach(glob('./data/continents/*') as $key => $filename) {
+ $continent = pathinfo($filename, PATHINFO_FILENAME);
+ echo "Loading $continent", EOL;
+ $continent = str_replace(' ','_',$continent);
+ $countries = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+ $countryCount = count($countries);
+
+ // Transpose $countries from a row to a column array
+ $countries = array_map('transpose', $countries);
+ $objPHPExcel->getActiveSheet()
+ ->fromArray($countries, null, $column . '1');
+ $objPHPExcel->addNamedRange(
+ new PHPExcel_NamedRange(
+ $continent,
+ $objPHPExcel->getActiveSheet(), $column . '1:' . $column . $countryCount
+ )
+ );
+ $objPHPExcel->getActiveSheet()
+ ->getColumnDimension($column)
+ ->setVisible(false);
+
+ $objPHPExcel->getActiveSheet()
+ ->setCellValue($continentColumn . ($key+1), $continent);
+
+ ++$column;
+}
+
+// Hide the dropdown data
+$objPHPExcel->getActiveSheet()
+ ->getColumnDimension($continentColumn)
+ ->setVisible(false);
+
+$objPHPExcel->addNamedRange(
+ new PHPExcel_NamedRange(
+ 'Continents',
+ $objPHPExcel->getActiveSheet(), $continentColumn . '1:' . $continentColumn . ($key+1)
+ )
+);
+
+
+// Set selection cells
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('A1', 'Continent:');
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('B1', 'Select continent');
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('B3', '=' . $column . 1);
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('B3', 'Select country');
+$objPHPExcel->getActiveSheet()
+ ->getStyle('A1:A3')
+ ->getFont()->setBold(true);
+
+// Set linked validators
+$objValidation = $objPHPExcel->getActiveSheet()
+ ->getCell('B1')
+ ->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST )
+ ->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION )
+ ->setAllowBlank(false)
+ ->setShowInputMessage(true)
+ ->setShowErrorMessage(true)
+ ->setShowDropDown(true)
+ ->setErrorTitle('Input error')
+ ->setError('Continent is not in the list.')
+ ->setPromptTitle('Pick from the list')
+ ->setPrompt('Please pick a continent from the drop-down list.')
+ ->setFormula1('=Continents');
+
+$objPHPExcel->getActiveSheet()
+ ->setCellValue('A3', 'Country:');
+$objPHPExcel->getActiveSheet()
+ ->getStyle('A3')
+ ->getFont()->setBold(true);
+
+$objValidation = $objPHPExcel->getActiveSheet()
+ ->getCell('B3')
+ ->getDataValidation();
+$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST )
+ ->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION )
+ ->setAllowBlank(false)
+ ->setShowInputMessage(true)
+ ->setShowErrorMessage(true)
+ ->setShowDropDown(true)
+ ->setErrorTitle('Input error')
+ ->setError('Country is not in the list.')
+ ->setPromptTitle('Pick from the list')
+ ->setPrompt('Please pick a country from the drop-down list.')
+ ->setFormula1('=INDIRECT($B$1)');
+
+
+$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
+$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
+
+
+// Set active sheet index to the first sheet, so Excel opens this as the first sheet
+$objPHPExcel->setActiveSheetIndex(0);
+
+// Save Excel 2007 file
+// This linked validation list method only seems to work for Excel2007, not for Excel5
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing files" , EOL;
+echo 'Files have been created in ' , getcwd() , EOL;
diff --git a/Examples/40duplicateStyle.php b/Examples/40duplicateStyle.php
index 52891ad4c..be31951a4 100644
--- a/Examples/40duplicateStyle.php
+++ b/Examples/40duplicateStyle.php
@@ -10,7 +10,7 @@
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
-require_once '../Classes/PHPExcel.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
echo date('H:i:s') , " Create new PHPExcel object" , EOL;
$objPHPExcel = new PHPExcel();
diff --git a/Examples/41password.php b/Examples/41password.php
new file mode 100644
index 000000000..15aea7ba0
--- /dev/null
+++ b/Examples/41password.php
@@ -0,0 +1,84 @@
+');
+
+date_default_timezone_set('Europe/London');
+
+include "05featuredemo.inc.php";
+
+/** Include PHPExcel_IOFactory */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
+
+
+// Set password against the spreadsheet file
+$objPHPExcel->getSecurity()->setLockWindows(true);
+$objPHPExcel->getSecurity()->setLockStructure(true);
+$objPHPExcel->getSecurity()->setWorkbookPassword('secret');
+
+
+// Save Excel 2007 file
+echo date('H:i:s') , " Write to Excel2007 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
+$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Save Excel 95 file
+echo date('H:i:s') , " Write to Excel5 format" , EOL;
+$callStartTime = microtime(true);
+
+$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
+$objWriter->save(str_replace('.php', '.xls', __FILE__));
+$callEndTime = microtime(true);
+$callTime = $callEndTime - $callStartTime;
+
+echo date('H:i:s') , " File written to " , str_replace('.php', '.xls', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
+echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
+// Echo memory usage
+echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+
+// Echo memory peak usage
+echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
+
+// Echo done
+echo date('H:i:s') , " Done writing files" , EOL;
+echo 'Files have been created in ' , getcwd() , EOL;
diff --git a/Examples/42richText.php b/Examples/42richText.php
new file mode 100644
index 000000000..32bc401fd
--- /dev/null
+++ b/Examples/42richText.php
@@ -0,0 +1,164 @@
+');
+
+/** Include PHPExcel */
+require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
+
+
+// Create new PHPExcel object
+echo date('H:i:s') , " Create new PHPExcel object" , EOL;
+$objPHPExcel = new PHPExcel();
+
+// Set document properties
+echo date('H:i:s') , " Set document properties" , EOL;
+$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
+ ->setLastModifiedBy("Maarten Balliauw")
+ ->setTitle("PHPExcel Test Document")
+ ->setSubject("PHPExcel Test Document")
+ ->setDescription("Test document for PHPExcel, generated using PHP classes.")
+ ->setKeywords("office PHPExcel php")
+ ->setCategory("Test result file");
+
+
+// Add some data
+echo date('H:i:s') , " Add some data" , EOL;
+
+$html1 = '
+My very first example of rich text
+
generated from html markuphealthy food pizza.
+
+';
+
+$html2 = '
+
+ 10°F is cold
+
+Quadratic Equation Solver
diff --git a/Examples/Quadratic2.php b/Examples/Quadratic2.php
index 93f285996..5f6013eab 100644
--- a/Examples/Quadratic2.php
+++ b/Examples/Quadratic2.php
@@ -9,7 +9,7 @@
error_reporting(E_ALL);
/** Include path **/
-set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
+set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../Classes/');
?>
Quadratic Equation Solver
diff --git a/Examples/SylkReader.php b/Examples/SylkReader.php
index a59ee0f3d..a16a4f057 100644
--- a/Examples/SylkReader.php
+++ b/Examples/SylkReader.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,7 +31,7 @@
date_default_timezone_set('Europe/London');
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
echo date('H:i:s') , " Load from SYLK file" , PHP_EOL;
diff --git a/Examples/XMLReader.php b/Examples/XMLReader.php
index 5f8884108..836f6b2df 100644
--- a/Examples/XMLReader.php
+++ b/Examples/XMLReader.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -31,7 +31,7 @@
date_default_timezone_set('Europe/London');
/** PHPExcel_IOFactory */
-require_once '../Classes/PHPExcel/IOFactory.php';
+require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
echo date('H:i:s') , " Load from XML file" , PHP_EOL;
diff --git a/Examples/data/continents/Africa.txt b/Examples/data/continents/Africa.txt
new file mode 100644
index 000000000..407fa769a
--- /dev/null
+++ b/Examples/data/continents/Africa.txt
@@ -0,0 +1,54 @@
+Algeria
+Angola
+Benin
+Botswana
+Burkina
+Burundi
+Cameroon
+Cape Verde
+Central African Republic
+Chad
+Comoros
+Congo
+Congo, Democratic Republic of
+Djibouti
+Egypt
+Equatorial Guinea
+Eritrea
+Ethiopia
+Gabon
+Gambia
+Ghana
+Guinea
+Guinea-Bissau
+Ivory Coast
+Kenya
+Lesotho
+Liberia
+Libya
+Madagascar
+Malawi
+Mali
+Mauritania
+Mauritius
+Morocco
+Mozambique
+Namibia
+Niger
+Nigeria
+Rwanda
+Sao Tome and Principe
+Senegal
+Seychelles
+Sierra Leone
+Somalia
+South Africa
+South Sudan
+Sudan
+Swaziland
+Tanzania
+Togo
+Tunisia
+Uganda
+Zambia
+Zimbabwe
diff --git a/Examples/data/continents/Asia.txt b/Examples/data/continents/Asia.txt
new file mode 100644
index 000000000..9ce006c53
--- /dev/null
+++ b/Examples/data/continents/Asia.txt
@@ -0,0 +1,44 @@
+Afghanistan
+Bahrain
+Bangladesh
+Bhutan
+Brunei
+Burma (Myanmar)
+Cambodia
+China
+East Timor
+India
+Indonesia
+Iran
+Iraq
+Israel
+Japan
+Jordan
+Kazakhstan
+Korea, North
+Korea, South
+Kuwait
+Kyrgyzstan
+Laos
+Lebanon
+Malaysia
+Maldives
+Mongolia
+Nepal
+Oman
+Pakistan
+Philippines
+Qatar
+Russian Federation
+Saudi Arabia
+Singapore
+Sri Lanka
+Syria
+Tajikistan
+Thailand
+Turkey
+Turkmenistan
+United Arab Emirates
+Uzbekistan
+Vietnam
+Yemen
diff --git a/Examples/data/continents/Europe.txt b/Examples/data/continents/Europe.txt
new file mode 100644
index 000000000..70c11607a
--- /dev/null
+++ b/Examples/data/continents/Europe.txt
@@ -0,0 +1,47 @@
+Albania
+Andorra
+Armenia
+Austria
+Azerbaijan
+Belarus
+Belgium
+Bosnia and Herzegovina
+Bulgaria
+Croatia
+Cyprus
+Czech Republic
+Denmark
+Estonia
+Finland
+France
+Georgia
+Germany
+Greece
+Hungary
+Iceland
+Ireland
+Italy
+Latvia
+Liechtenstein
+Lithuania
+Luxembourg
+Macedonia
+Malta
+Moldova
+Monaco
+Montenegro
+Netherlands
+Norway
+Poland
+Portugal
+Romania
+San Marino
+Serbia
+Slovakia
+Slovenia
+Spain
+Sweden
+Switzerland
+Ukraine
+United Kingdom
+Vatican City
diff --git a/Examples/data/continents/North America.txt b/Examples/data/continents/North America.txt
new file mode 100644
index 000000000..5881ae132
--- /dev/null
+++ b/Examples/data/continents/North America.txt
@@ -0,0 +1,23 @@
+Antigua and Barbuda
+Bahamas
+Barbados
+Belize
+Canada
+Costa Rica
+Cuba
+Dominica
+Dominican Republic
+El Salvador
+Grenada
+Guatemala
+Haiti
+Honduras
+Jamaica
+Mexico
+Nicaragua
+Panama
+Saint Kitts and Nevis
+Saint Lucia
+Saint Vincent and the Grenadines
+Trinidad and Tobago
+United States
diff --git a/Examples/data/continents/Oceania.txt b/Examples/data/continents/Oceania.txt
new file mode 100644
index 000000000..cbdc896c1
--- /dev/null
+++ b/Examples/data/continents/Oceania.txt
@@ -0,0 +1,14 @@
+Australia
+Fiji
+Kiribati
+Marshall Islands
+Micronesia
+Nauru
+New Zealand
+Palau
+Papua New Guinea
+Samoa
+Solomon Islands
+Tonga
+Tuvalu
+Vanuatu
diff --git a/Examples/data/continents/South America.txt b/Examples/data/continents/South America.txt
new file mode 100644
index 000000000..777ffbfb9
--- /dev/null
+++ b/Examples/data/continents/South America.txt
@@ -0,0 +1,12 @@
+Argentina
+Bolivia
+Brazil
+Chile
+Colombia
+Ecuador
+Guyana
+Paraguay
+Peru
+Suriname
+Uruguay
+Venezuela
diff --git a/Examples/runall.php b/Examples/runall.php
index ad37f3397..153cb7657 100644
--- a/Examples/runall.php
+++ b/Examples/runall.php
@@ -2,7 +2,7 @@
/**
* PHPExcel
*
- * Copyright (C) 2006 - 2012 PHPExcel
+ * Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
*
* @category PHPExcel
* @package PHPExcel
- * @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
@@ -35,6 +35,7 @@
// List of tests
$aTests = array(
'01simple.php'
+ , '01simplePCLZip.php'
, '02types.php'
, '02types-xls.php'
, '03formulas.php'
@@ -42,17 +43,23 @@
, '05featuredemo.php'
, '06largescale.php'
, '06largescale-with-cellcaching.php'
+ , '06largescale-with-cellcaching-sqlite.php'
+ , '06largescale-with-cellcaching-sqlite3.php'
, '06largescale-xls.php'
, '07reader.php'
+ , '07readerPCLZip.php'
, '08conditionalformatting.php'
, '08conditionalformatting2.php'
, '09pagebreaks.php'
, '10autofilter.php'
, '10autofilter-selection-1.php'
, '10autofilter-selection-2.php'
+ , '10autofilter-selection-display.php'
, '11documentsecurity.php'
, '11documentsecurity-xls.php'
+ , '12cellProtection.php'
, '13calculation.php'
+ , '13calculationCyclicFormulae.php'
, '14excel5.php'
, '15datavalidation.php'
, '15datavalidation-xls.php'
@@ -82,21 +89,30 @@
, '33chartcreate-line.php'
, '33chartcreate-pie.php'
, '33chartcreate-radar.php'
+ , '33chartcreate-stock.php'
, '33chartcreate-multiple-charts.php'
, '33chartcreate-composite.php'
, '34chartupdate.php'
, '35chartrender.php'
, '36chartreadwriteHTML.php'
+ , '36chartreadwritePDF.php'
, '37page_layout_view.php'
+ , '38cloneWorksheet.php'
+ , '39dropdown.php'
, '40duplicateStyle.php'
+ , '41password.php'
+ , '42richText.php'
+ , '43mergeWorkbooks.php'
+ , '44worksheetInfo.php'
, 'OOCalcReader.php'
+ , 'OOCalcReaderPCLZip.php'
, 'SylkReader.php'
, 'Excel2003XMLReader.php'
, 'XMLReader.php'
, 'GnumericReader.php'
);
-// First, clear all results
+// First, clear all previous run results
foreach ($aTests as $sTest) {
@unlink( str_replace('.php', '.xls', $sTest) );
@unlink( str_replace('.php', '.xlsx', $sTest) );
@@ -113,4 +129,4 @@
echo shell_exec('php ' . $sTest);
echo "\r\n";
echo "\r\n";
-}
+}
\ No newline at end of file
diff --git a/Examples/templates/43mergeBook1.xlsx b/Examples/templates/43mergeBook1.xlsx
new file mode 100644
index 000000000..6efc05a5d
Binary files /dev/null and b/Examples/templates/43mergeBook1.xlsx differ
diff --git a/Examples/templates/43mergeBook2.xlsx b/Examples/templates/43mergeBook2.xlsx
new file mode 100644
index 000000000..1eb6035d4
Binary files /dev/null and b/Examples/templates/43mergeBook2.xlsx differ
diff --git a/README.md b/README.md
index 52b63b2e6..b0dd57aff 100644
--- a/README.md
+++ b/README.md
@@ -5,6 +5,8 @@ Master: [](http://travis-ci.org/PHPOffice/PHPExcel)
+[](https://gitter.im/PHPOffice/PHPExcel)
+
## File Formats supported
### Reading
@@ -33,7 +35,15 @@ Develop: [
+ - [Helpful article about pull requests](https://help.github.com/articles/using-pull-requests/ "Pull Requests")
+
## License
PHPExcel is licensed under [LGPL (GNU LESSER GENERAL PUBLIC LICENSE)](https://github.com/PHPOffice/PHPExcel/blob/master/license.md)
diff --git a/changelog.txt b/changelog.txt
index 552cb9e43..d92923215 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -1,7 +1,7 @@
**************************************************************************************
* PHPExcel
*
-* Copyright (c) 2006 - 2012 PHPExcel
+* Copyright (c) 2006 - 2014 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -17,15 +17,115 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
-* @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+* @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 ##VERSION##, ##DATE##
**************************************************************************************
-Fixed in develop branch:
+2018-11-22 (v1.8.2):
+- Security (MBaker) - Fix and improve XXE security scanning for XML-based Readers
+- Bugfix: (MBaker) - Fix to getCell() method when cell reference includes a worksheet reference
+- Bugfix: (ncrypthic) Work Item GH-570 - Ignore inlineStr type if formula element exists
+- Bugfix: (hernst42) Work Item GH-709 - Fixed missing renames of writeRelationShip (from _writeRelationShip)
+- General: (umpirsky) Work Item GH-548 - Optimize vlookup() sort
+- Bugfix: (MBaker) Work Item GH-554 - Whitespace after toRichTextObject()
+- Feature: (MBaker) - Initial implementation of SUMIFS() function
+- Feature: (MBaker) - Additional codepages
+- Feature: (Tomino2112) Work Item GH-808 - MemoryDrawing not working in HTML writer
+- General: (rentalhost) Work Item GH-575 - Excel 2007 Reader freezes because of conditional formatting
+- Bugfix: (vitalyrepin) Pull Request 869 - c:max and c:min elements shall NOT be inside c:orientation elements
+- General: (sim642) Pull Request 489 - Implement actual timezone adjustment into PHPExcel_Shared_Date::PHPToExcel
+
+
+2015-04-30 (v1.8.1):
+- Bugfix: (goncons) Work Item GH-397 - Fix for Writing an Open Document cell with non-numeric formula
+- Bugfix: (sarciszewski) Work Item GH-329 - Avoid potential divide by zero in basedrawing
+- Bugfix: (ymaerschalck) Work Item GH-405 - XML External Entity (XXE) Processing, different behaviour between simplexml_load_string() and simplexml_load_file().
+- Bugfix: (MBaker) - Fix to ensure that current cell is maintained when executing formula calculations
+- Bugfix: (MBaker) Work Item GH-350 - Keep/set the value on Reader _loadSheetsOnly as NULL, courtesy of Restless-ET
+- Bugfix: (MBaker) Work Item CP18105 - Loading an Excel 2007 spreadsheet throws an "Autofilter must be set on a range of cells" exception
+- Bugfix: (MBaker) Work Item GH-388 - Fix to autoloader registration for backward compatibility with PHP 5.2.0 not accepting the prepend flag
+- Bugfix: (MBaker) Work Item GH-384 - DOM loadHTMLFile() failing with options flags when using PHP < 5.4.0
+- Bugfix: (MBaker) - Fix for percentage operator in formulae for BIFF Writer
+- Bugfix: (MBaker) - Fix to getStyle() call for cell object
+- Bugfix: (MBaker) - Discard Autofilters in Excel2007 Reader when filter range isn't a valid range
+- Bugfix: (frozenstupidity) Work Item GH-423 - Fix invalid NA return in VLOOKUP
+- Bugfix: (wiseloren) Work Item CP21454 - "No Impact" conditional formatting fix for NumberFormat
+- Bugfix: (bobwitlox) Work Item GH-467 - Bug in Excel2003XML reader, parsing merged cells
+- Bugfix: (MBaker) Work Item GH-302 - Fix for CEIL() and FLOOR() when number argument is zero
+- Bugfix: (MBaker) - Remove cells cleanly when calling RemoveRow() or RemoveColumn()
+- General: (MBaker) - Small performance improvement for autosize columns
+- General: (frost-nzcr4) Work Item GH-379 - Change the getter/setter for zeroHeight to camel case
+- General: (MBaker) Work Item GH-394 - DefaultValueBinder is too much aggressive when converting string to numeric
+- General: (MBaker) - Default precalculate formulas to false for writers
+- General: (MBaker) - Set default Cyclic Reference behaviour to 1 to eliminate exception when using a single cyclic iteration in formulae
+- General: (MBaker) Work Item GH-396 - Some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE
+- Feature: (WiktrzGE) Work Item GH-404 - Methods to manage most of the existing options for Chart Axis, Major Grid-lines and Minor Grid-lines
+- Feature: (frost-nzcr4) Work Item GH-403 - ODS read/write comments in the cell
+- Feature: (CQD) Work Item GH-389 - Additional Mac CJK codepage definitions
+- Feature: (bolovincev) Work Item GH-269 - Update Worksheet.php getStyleByColumnAndRow() to allow a range of cells rather than just a single cell
+- Feature: (MBaker) - New methods added for testing cell status within merge groups
+- Feature: (cifren/MBaker) Work Item GH-205 - Handling merge cells in HTML Reader
+- Feature: (MBaker) - Helper to convert basic HTML markup to a Rich Text object
+- Feature: (MBaker) - Improved Iterators
+ New Column Iterator
+ Support for row and column ranges
+ Improved handling for next/prev
+- Security: (MBaker) - XML filescan in XML-based Readers to prevent XML Entity Expansion (XEE)
+ (see http://projects.webappsec.org/w/page/13247002/XML%20Entity%20Expansion for an explanation of XEE injection) attacks
+ Reference CVE-2015-3542 - Identification of problem courtesy of Dawid Golunski (Pentest Ltd.)
+
+2014-03-02 (v1.8.0):
+- Bugfix: (MBaker) Work item CP19830 - Undefined variable: fileHandle in CSV Reader
+- Bugfix: (MBaker) Work item CP19968 - Out of memory in style/supervisor.php
+- Bugfix: (MBaker) - Style error with merged cells in PDF Writer
+- Bugfix: (MBaker) - Problem with cloning worksheets
+- Bugfix: (tavoarcila) Work Item GH-259 - Bug fix reading Open Office files
+- Bugfix: (MBaker) Work item CP20397 - Serious bug in absolute cell reference used in shared formula
+ Would also have affected insert/delete column/row
+- Bugfix: (RomanSyroeshko) Work Item GH-267 - CHOOSE() returns "#VALUE!" if the 1st entry is chosen
+- Bugfix: (Gemorroj) Work Item GH-268 - When duplicating styles, styles shifted by one column to the right
+ Fix also applied to duplicating conditional styles
+- Bugfix: (IndrekHaav) Work Item GH-212 - Fix for formulae that reference a sheet whose name begins with a digit:
+ these were erroneously identified as numeric values, causing the parser to throw an undefined variable error.
+- Bugfix: (IndrekHaav) Work Item CP16208 - Fixed undefined variable error due to $styleArray being used before it's initialised
+- Bugfix: (PowerKiKi) Work Item GH-273 - ISTEXT() return wrong result if referencing an empty but formatted cell
+- Bugfix: (PowerKiKi) Work Item GH-270/GH-31 - Binary comparison of strings are case insensitive
+- Bugfix: (MBaker) Work Item GH-275 - Insert New Row/Column Before is not correctly updating formula references
+- Bugfix: (MBaker) Work Item GH-257 - Passing an array of cells to _generateRow() in the HTML/PDF Writer causes caching problems with last cell in the range
+- Bugfix: (MBaker) Work Item GH-193 - Fix to empty worksheet garbage collection when using cell caching
+- Bugfix: (Jazzo) Work Item GH-248 - Excel2007 does not correctly mark rows as hidden
+- Bugfix: (Roy Shahbazian) Work Item GH-299 - Fixed typo in Chart/Layout set/getYMode()
+- Bugfix: (EliuFlorez) Work item GH-279 - Fatal error: Call to a member function cellExists() line: 3327 in calculation.php if referenced worksheet doesn't exist
+- Bugfix: (MBaker) Work Item GH-290 - AdvancedValueBinder "Division by zero"-error
+- Bugfix: (MBaker) Work Item CP20604 - Adding Sheet to Workbook Bug
+- Bugfix: (MBaker) Work item CP20703 - Calculation engine incorrectly evaluates empty cells as #VALUE
+- Bugfix: (MBaker) Work item CP20760 - Formula references to cell on another sheet in ODS files
+- Bugfix: (MBaker) Work item GH321,GH158,CP17824 - LibreOffice created XLSX files results in an empty file.
+- Feature: (amerov) - Implementation of the Excel HLOOKUP() function
+- Feature: (MBaker) - Added "Quote Prefix" to style settings (Excel2007 Reader and Writer only)
+- Feature: (MBaker) - Added Horizontal FILL alignment for Excel5 and Excel2007 Readers/Writers, and Horizontal DISTRIBUTED alignment for Excel2007 Reader/Writer
+- Feature: (trvrnrth) Work Item GH-261 - Add support for reading protected (RC4 encrypted) .xls files
+- Feature: (LWol) Work Item GH-252 - Adding support for macros, Ribbon in Excel 2007
+- General: (cdhutch) Work item CP20055 - Remove array_shift in ReferenceHelper::insertNewBefore improves column or row delete speed
+- General: (MBaker) - Improve stock chart handling and rendering, with help from Swashata Ghosh
+- General: (MBaker) - Fix to calculation properties for Excel2007 so that the opening application will only recalculate on load if it's actually required
+- General: (MBaker) - Modified Excel2007 Writer to default preCalculateFormulas to false
+ Note that autosize columns will still recalculate affected formulae internally
+- General: (dresenhista) Work Item GH-242 - Functionality to getHighestRow() for a specified column, and getHighestColumn() for a specified row
+- General: (adamriyadi) Work Item GH-247 - Modify PHPExcel_Reader_Excel2007 to use zipClass from PHPExcel_Settings::getZipClass()
+ This allows the use of PCLZip when reading for people that don't have access to ZipArchive
+- General: (infojunkie) Work Item GH-276 - Convert properties to string in OOCalc reader
+- Security: (maartenba) Work Item GH-322 - Disable libxml external entity loading by default.
+ This is to prevent XML External Entity Processing (XXE) injection attacks (see http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html for an explanation of XXE injection).
+ Reference CVE-2014-2054
+
+
+2013-06-02 (v1.7.9):
- Feature: (MBaker) Include charts option for HTML Writer
- Feature: (MBaker) Added composer file
+- Feature: (MBaker) Added getStyle() method to Cell object
- Bugfix: (Asker) Work item 18777 - Error in PHPEXCEL/Calculation.php script on line 2976 (stack pop check)
- Bugfix: (MBaker) Work item 18794 - CSV files without a file extension being identified as HTML
- Bugfix: (AndreKR) Work item GH-66 - Wrong check for maximum number of rows in Excel5 Writer
@@ -41,6 +141,9 @@ Fixed in develop branch:
- General: (cfhay) Work item 18958 - Memory and Speed improvements in PHPExcel_Reader_Excel5
- General: (MBaker) Work item GH-78 - Modify listWorksheetNames() and listWorksheetInfo to use XMLReader with streamed XML rather than SimpleXML
- General: (dbonsch) Restructuring of PHPExcel Exceptions
+- General: (MBaker) Work items 16926 and 15145 - Refactor Calculation Engine from singleton to a Multiton
+ Ensures that calculation cache is maintained independently for different workbooks
+- General: (MBaker) Modify cell's getCalculatedValue() method to return the content of RichText objects rather than the RichText object itself
- Bugfix: (techhead) Work item GH-70 - Fixed formula/formatting bug when removing rows
- Bugfix: (alexgann) Work item GH-63 - Fix to cellExists for non-existent namedRanges
- Bugfix: (MBaker) Work item 18844 - cache_in_memory_gzip "eats" last worksheet line, cache_in_memory doesn't
@@ -50,54 +153,12 @@ Fixed in develop branch:
- Bugfix: (MBaker) Work item GH-104 - echo statements in HTML.php
- Feature: (Progi1984) Work item GH-8/CP11704 : Conditional formatting in Excel 5 Writer
- Bugfix: (MBaker) Work item GH-113 - canRead() Error for GoogleDocs ODS files: in ODS files from Google Docs there is no mimetype file
-
-
---------------------------------------------------------------------------------
-BREAKING CHANGE! As part of the planned changes for handling array formulae in
-workbooks, there are some changes that will affect the PHPExcel_Cell object
-methods.
-
-The following methods are now deprecated, and will be removed in version 1.7.9:
- getCalculatedValue() The getValue() method will return calculated
- values for cells containing formulae instead.
- setCalculatedValue() The cell value will always contain the result of a
- any formula calculation.
- setFormulaAttributes() Will now be determined by the arguments to the
- setFormula() method.
- getFormulaAttributes() This will be replaced by the getArrayFormulaRange()
- method.
-
-The following methods will be added in version 1.7.9
- getFormula() Use to retrieve a cell formula, will return the cell
- value if the cell doesn't contain a formula, or
- is not part of an array formula range.
- setFormula() Use to set a cell formula. It will still be possible
- to set formulae using the setValue() and
- setValueExplicit() methods.
- calculate() Use to execute a formula calculation to update the
- cell value.
- isFormula() Use to determine if a cell contains a formula, or is
- part of an array formula range or not.
- isArrayFormula() Use to determine if a cell contains an array formula,
- or is part of an array formula range or not.
- getArrayFormulaRange() Use to retrieve an array formula range.
-
-The following methods will be changed in version 1.7.9
- setValue() The logic behind this will be modified to store
- formula values in the new cell property structure,
- but it will still perform the same function.
- setValueExplicit() The logic behind this will be modified to store
- formula values in the new cell property structure,
- but it will still perform the same function.
- getValue() Will no longer return a formula if the cell contains
- a formula, but will return the calculated value
- instead. For cells that don't contain a formula,
- it will still return the stored value.
- getDataType() Will return the datatype of the calculated value for
- cells that contain formulae.
- setDataType() Error handling will be added to prevent setting a
- cell datatype to an inappropriate value.
---------------------------------------------------------------------------------
+- Bugfix: (MBaker) Work item GH-80 - "Sheet index is out of bounds." Exception
+- Bugfix: (ccorliss) Work item GH-105 - Fixed number format fatal error
+- Bugfix: (MBaker) - Add DROP TABLE in destructor for SQLite and SQLite3 cache controllers
+- Bugfix: (alexgann) Work item GH-154 - Fix merged-cell borders on HTML/PDF output
+- Bugfix: (Shanto) Work item GH-161 - Fix: Hyperlinks break when removing rows
+- Bugfix: (neclimdul) Work item GH-166 - Fix Extra Table Row From Images and Charts
2012-10-12 (v1.7.8):
@@ -169,7 +230,7 @@ The following methods will be changed in version 1.7.9
- General: (MBaker) Reduce cell caching overhead using dirty flag to ensure that cells are only rewritten to the cache if they have actually been changed
- General: (MBaker) Improved memory usage in CSV Writer
- General: (MBaker) Improved speed and memory usage in Excel5 Writer
-- General: (MBaker) Experimental -
+- General: (MBaker) Experimental -
Added getHighestDataColumn(), getHighestDataRow(), getHighestRowAndColumn() and calculateWorksheetDataDimension() methods for the worksheet that return the highest row and column that have cell records
- General: (MBaker) Change iterators to implement Iterator rather than extend CachingIterator, as a fix for PHP 5.4. changes in SPL
- Bugfix: (MBaker) Work item 15459 - Invalid cell coordinate in Autofilter for Excel2007 Writer
diff --git a/composer.json b/composer.json
index f0bd60e1c..8aa448025 100644
--- a/composer.json
+++ b/composer.json
@@ -2,32 +2,38 @@
"name": "phpoffice/phpexcel",
"description": "PHPExcel - OpenXML - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine",
"keywords": ["PHP","Excel","OpenXML","xlsx","xls","spreadsheet"],
- "homepage": "http://phpexcel.codeplex.com/",
+ "homepage": "https://github.com/PHPOffice/PHPExcel",
"type": "library",
- "license": "LGPL",
+ "license": "LGPL-2.1",
"authors": [
{
"name": "Maarten Balliauw",
"homepage": "http://blog.maartenballiauw.be/"
},
{
- "name": "Mark Baker"
+ "name": "Mark Baker",
+ "homepage": "http://markbakeruk.net/"
},
{
"name": "Franck Lefevre",
- "homepage": "http://blog.rootslabs.net/"
+ "homepage": "http://rootslabs.net/"
},
{
"name": "Erik Tilt"
}
],
"require": {
- "php": ">=5.2.0",
- "ext-xml": "*"
+ "php": "^5.2|^7.0",
+ "ext-mbstring": "*",
+ "ext-xml": "*",
+ "ext-xmlwriter": "*"
+ },
+ "require-dev": {
+ "squizlabs/php_codesniffer": "2.*"
},
"recommend": {
"ext-zip": "*",
- "ext-gd2": "*"
+ "ext-gd": "*"
},
"autoload": {
"psr-0": {
diff --git a/install.txt b/install.txt
index 6fb880383..1a999d258 100644
--- a/install.txt
+++ b/install.txt
@@ -7,17 +7,17 @@
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
-*
+*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
-*
+*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
-* @copyright Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
+* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
**************************************************************************************
diff --git a/unitTests/Classes/PHPExcel/AutoloaderTest.php b/unitTests/Classes/PHPExcel/AutoloaderTest.php
index 286ef627c..842d1797d 100644
--- a/unitTests/Classes/PHPExcel/AutoloaderTest.php
+++ b/unitTests/Classes/PHPExcel/AutoloaderTest.php
@@ -6,8 +6,7 @@ class AutoloaderTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
@@ -46,11 +45,10 @@ public function testAutoloadValidPHPExcelClass()
public function testAutoloadInstantiateSuccess()
{
- $result = new PHPExcel_Calculation_Function(1,2,3);
+ $result = new PHPExcel_Calculation_Function(1, 2, 3);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'PHPExcel_Calculation_Function'));
+ $this->assertTrue(is_a($result, 'PHPExcel_Calculation_Function'));
}
-
-}
\ No newline at end of file
+}
diff --git a/unitTests/Classes/PHPExcel/Calculation/DateTimeTest.php b/unitTests/Classes/PHPExcel/Calculation/DateTimeTest.php
index 57692a341..d42ae44d8 100644
--- a/unitTests/Classes/PHPExcel/Calculation/DateTimeTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/DateTimeTest.php
@@ -8,457 +8,457 @@ class DateTimeTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
/**
* @dataProvider providerDATE
*/
- public function testDATE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','DATE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDATE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'DATE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDATE()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/DATE.data');
- }
-
- public function testDATEtoPHP()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $result = PHPExcel_Calculation_DateTime::DATE(2012,1,31);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
- $this->assertEquals(1327968000, $result, NULL, 1E-8);
- }
-
- public function testDATEtoPHPObject()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
- $result = PHPExcel_Calculation_DateTime::DATE(2012,1,31);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/DATE.data');
+ }
+
+ public function testDATEtoPHP()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $result = PHPExcel_Calculation_DateTime::DATE(2012, 1, 31);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $this->assertEquals(1327968000, $result, null, 1E-8);
+ }
+
+ public function testDATEtoPHPObject()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
+ $result = PHPExcel_Calculation_DateTime::DATE(2012, 1, 31);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'DateTime'));
+ $this->assertTrue(is_a($result, 'DateTime'));
// ... with the correct value
- $this->assertEquals($result->format('d-M-Y'),'31-Jan-2012');
- }
-
- public function testDATEwith1904Calendar()
- {
- PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
- $result = PHPExcel_Calculation_DateTime::DATE(1918,11,11);
- PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
- $this->assertEquals($result,5428);
- }
-
- public function testDATEwith1904CalendarError()
- {
- PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
- $result = PHPExcel_Calculation_DateTime::DATE(1901,1,31);
- PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
- $this->assertEquals($result,'#NUM!');
- }
+ $this->assertEquals($result->format('d-M-Y'), '31-Jan-2012');
+ }
+
+ public function testDATEwith1904Calendar()
+ {
+ PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
+ $result = PHPExcel_Calculation_DateTime::DATE(1918, 11, 11);
+ PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
+ $this->assertEquals($result, 5428);
+ }
+
+ public function testDATEwith1904CalendarError()
+ {
+ PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904);
+ $result = PHPExcel_Calculation_DateTime::DATE(1901, 1, 31);
+ PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900);
+ $this->assertEquals($result, '#NUM!');
+ }
/**
* @dataProvider providerDATEVALUE
*/
- public function testDATEVALUE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','DATEVALUE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDATEVALUE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'DATEVALUE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDATEVALUE()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/DATEVALUE.data');
- }
-
- public function testDATEVALUEtoPHP()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $result = PHPExcel_Calculation_DateTime::DATEVALUE('2012-1-31');
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
- $this->assertEquals(1327968000, $result, NULL, 1E-8);
- }
-
- public function testDATEVALUEtoPHPObject()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
- $result = PHPExcel_Calculation_DateTime::DATEVALUE('2012-1-31');
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/DATEVALUE.data');
+ }
+
+ public function testDATEVALUEtoPHP()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $result = PHPExcel_Calculation_DateTime::DATEVALUE('2012-1-31');
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $this->assertEquals(1327968000, $result, null, 1E-8);
+ }
+
+ public function testDATEVALUEtoPHPObject()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
+ $result = PHPExcel_Calculation_DateTime::DATEVALUE('2012-1-31');
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'DateTime'));
+ $this->assertTrue(is_a($result, 'DateTime'));
// ... with the correct value
- $this->assertEquals($result->format('d-M-Y'),'31-Jan-2012');
- }
+ $this->assertEquals($result->format('d-M-Y'), '31-Jan-2012');
+ }
/**
* @dataProvider providerYEAR
*/
- public function testYEAR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','YEAR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testYEAR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'YEAR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerYEAR()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/YEAR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/YEAR.data');
+ }
/**
* @dataProvider providerMONTH
*/
- public function testMONTH()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','MONTHOFYEAR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testMONTH()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'MONTHOFYEAR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerMONTH()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/MONTH.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/MONTH.data');
+ }
/**
* @dataProvider providerWEEKNUM
*/
- public function testWEEKNUM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','WEEKOFYEAR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testWEEKNUM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'WEEKOFYEAR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerWEEKNUM()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/WEEKNUM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/WEEKNUM.data');
+ }
/**
* @dataProvider providerWEEKDAY
*/
- public function testWEEKDAY()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','DAYOFWEEK'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testWEEKDAY()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'DAYOFWEEK'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerWEEKDAY()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/WEEKDAY.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/WEEKDAY.data');
+ }
/**
* @dataProvider providerDAY
*/
- public function testDAY()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','DAYOFMONTH'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDAY()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'DAYOFMONTH'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDAY()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/DAY.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/DAY.data');
+ }
/**
* @dataProvider providerTIME
*/
- public function testTIME()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','TIME'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testTIME()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'TIME'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerTIME()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/TIME.data');
- }
-
- public function testTIMEtoPHP()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $result = PHPExcel_Calculation_DateTime::TIME(7,30,20);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
- $this->assertEquals(27020, $result, NULL, 1E-8);
- }
-
- public function testTIMEtoPHPObject()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
- $result = PHPExcel_Calculation_DateTime::TIME(7,30,20);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/TIME.data');
+ }
+
+ public function testTIMEtoPHP()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $result = PHPExcel_Calculation_DateTime::TIME(7, 30, 20);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $this->assertEquals(27020, $result, null, 1E-8);
+ }
+
+ public function testTIMEtoPHPObject()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
+ $result = PHPExcel_Calculation_DateTime::TIME(7, 30, 20);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'DateTime'));
+ $this->assertTrue(is_a($result, 'DateTime'));
// ... with the correct value
- $this->assertEquals($result->format('H:i:s'),'07:30:20');
- }
+ $this->assertEquals($result->format('H:i:s'), '07:30:20');
+ }
/**
* @dataProvider providerTIMEVALUE
*/
- public function testTIMEVALUE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','TIMEVALUE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testTIMEVALUE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'TIMEVALUE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerTIMEVALUE()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/TIMEVALUE.data');
- }
-
- public function testTIMEVALUEtoPHP()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $result = PHPExcel_Calculation_DateTime::TIMEVALUE('7:30:20');
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
- $this->assertEquals(23420, $result, NULL, 1E-8);
- }
-
- public function testTIMEVALUEtoPHPObject()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
- $result = PHPExcel_Calculation_DateTime::TIMEVALUE('7:30:20');
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/TIMEVALUE.data');
+ }
+
+ public function testTIMEVALUEtoPHP()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $result = PHPExcel_Calculation_DateTime::TIMEVALUE('7:30:20');
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $this->assertEquals(23420, $result, null, 1E-8);
+ }
+
+ public function testTIMEVALUEtoPHPObject()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
+ $result = PHPExcel_Calculation_DateTime::TIMEVALUE('7:30:20');
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'DateTime'));
+ $this->assertTrue(is_a($result, 'DateTime'));
// ... with the correct value
- $this->assertEquals($result->format('H:i:s'),'07:30:20');
- }
+ $this->assertEquals($result->format('H:i:s'), '07:30:20');
+ }
/**
* @dataProvider providerHOUR
*/
- public function testHOUR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','HOUROFDAY'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testHOUR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'HOUROFDAY'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerHOUR()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/HOUR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/HOUR.data');
+ }
/**
* @dataProvider providerMINUTE
*/
- public function testMINUTE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','MINUTEOFHOUR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testMINUTE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'MINUTEOFHOUR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerMINUTE()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/MINUTE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/MINUTE.data');
+ }
/**
* @dataProvider providerSECOND
*/
- public function testSECOND()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','SECONDOFMINUTE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testSECOND()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'SECONDOFMINUTE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerSECOND()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/SECOND.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/SECOND.data');
+ }
/**
* @dataProvider providerNETWORKDAYS
*/
- public function testNETWORKDAYS()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','NETWORKDAYS'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testNETWORKDAYS()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'NETWORKDAYS'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerNETWORKDAYS()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/NETWORKDAYS.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/NETWORKDAYS.data');
+ }
/**
* @dataProvider providerWORKDAY
*/
- public function testWORKDAY()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','WORKDAY'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testWORKDAY()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'WORKDAY'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerWORKDAY()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/WORKDAY.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/WORKDAY.data');
+ }
/**
* @dataProvider providerEDATE
*/
- public function testEDATE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','EDATE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testEDATE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'EDATE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerEDATE()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/EDATE.data');
- }
-
- public function testEDATEtoPHP()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $result = PHPExcel_Calculation_DateTime::EDATE('2012-1-26',-1);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
- $this->assertEquals(1324857600, $result, NULL, 1E-8);
- }
-
- public function testEDATEtoPHPObject()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
- $result = PHPExcel_Calculation_DateTime::EDATE('2012-1-26',-1);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/EDATE.data');
+ }
+
+ public function testEDATEtoPHP()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $result = PHPExcel_Calculation_DateTime::EDATE('2012-1-26', -1);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $this->assertEquals(1324857600, $result, null, 1E-8);
+ }
+
+ public function testEDATEtoPHPObject()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
+ $result = PHPExcel_Calculation_DateTime::EDATE('2012-1-26', -1);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'DateTime'));
+ $this->assertTrue(is_a($result, 'DateTime'));
// ... with the correct value
- $this->assertEquals($result->format('d-M-Y'),'26-Dec-2011');
- }
+ $this->assertEquals($result->format('d-M-Y'), '26-Dec-2011');
+ }
/**
* @dataProvider providerEOMONTH
*/
- public function testEOMONTH()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','EOMONTH'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testEOMONTH()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'EOMONTH'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerEOMONTH()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/EOMONTH.data');
- }
-
- public function testEOMONTHtoPHP()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
- $result = PHPExcel_Calculation_DateTime::EOMONTH('2012-1-26',-1);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
- $this->assertEquals(1325289600, $result, NULL, 1E-8);
- }
-
- public function testEOMONTHtoPHPObject()
- {
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
- $result = PHPExcel_Calculation_DateTime::EOMONTH('2012-1-26',-1);
- PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/EOMONTH.data');
+ }
+
+ public function testEOMONTHtoPHP()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC);
+ $result = PHPExcel_Calculation_DateTime::EOMONTH('2012-1-26', -1);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+ $this->assertEquals(1325289600, $result, null, 1E-8);
+ }
+
+ public function testEOMONTHtoPHPObject()
+ {
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT);
+ $result = PHPExcel_Calculation_DateTime::EOMONTH('2012-1-26', -1);
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
// Must return an object...
$this->assertTrue(is_object($result));
// ... of the correct type
- $this->assertTrue(is_a($result,'DateTime'));
+ $this->assertTrue(is_a($result, 'DateTime'));
// ... with the correct value
- $this->assertEquals($result->format('d-M-Y'),'31-Dec-2011');
- }
+ $this->assertEquals($result->format('d-M-Y'), '31-Dec-2011');
+ }
/**
* @dataProvider providerDATEDIF
*/
- public function testDATEDIF()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','DATEDIF'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDATEDIF()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'DATEDIF'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDATEDIF()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/DATEDIF.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/DATEDIF.data');
+ }
/**
* @dataProvider providerDAYS360
*/
- public function testDAYS360()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','DAYS360'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDAYS360()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'DAYS360'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDAYS360()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/DAYS360.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/DAYS360.data');
+ }
/**
* @dataProvider providerYEARFRAC
*/
- public function testYEARFRAC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_DateTime','YEARFRAC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testYEARFRAC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_DateTime', 'YEARFRAC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerYEARFRAC()
{
- return new testDataFileIterator('rawTestData/Calculation/DateTime/YEARFRAC.data');
- }
-
+ return new testDataFileIterator('rawTestData/Calculation/DateTime/YEARFRAC.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Calculation/EngineeringTest.php b/unitTests/Classes/PHPExcel/Calculation/EngineeringTest.php
index 647da09f4..08448f558 100644
--- a/unitTests/Classes/PHPExcel/Calculation/EngineeringTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/EngineeringTest.php
@@ -12,685 +12,672 @@ class EngineeringTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
/**
* @dataProvider providerBESSELI
*/
- public function testBESSELI()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELI'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testBESSELI()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELI'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerBESSELI()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELI.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELI.data');
+ }
/**
* @dataProvider providerBESSELJ
*/
- public function testBESSELJ()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELJ'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testBESSELJ()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELJ'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerBESSELJ()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELJ.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELJ.data');
+ }
/**
* @dataProvider providerBESSELK
*/
- public function testBESSELK()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELK'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testBESSELK()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELK'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerBESSELK()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELK.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELK.data');
+ }
/**
* @dataProvider providerBESSELY
*/
- public function testBESSELY()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELY'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testBESSELY()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BESSELY'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerBESSELY()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELY.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BESSELY.data');
+ }
/**
* @dataProvider providerCOMPLEX
*/
- public function testCOMPLEX()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','COMPLEX'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCOMPLEX()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','COMPLEX'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCOMPLEX()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/COMPLEX.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/COMPLEX.data');
+ }
/**
* @dataProvider providerIMAGINARY
*/
- public function testIMAGINARY()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMAGINARY'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIMAGINARY()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMAGINARY'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIMAGINARY()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMAGINARY.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMAGINARY.data');
+ }
/**
* @dataProvider providerIMREAL
*/
- public function testIMREAL()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMREAL'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIMREAL()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMREAL'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIMREAL()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMREAL.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMREAL.data');
+ }
/**
* @dataProvider providerIMABS
*/
- public function testIMABS()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMABS'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIMABS()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMABS'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIMABS()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMABS.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMABS.data');
+ }
/**
* @dataProvider providerIMARGUMENT
*/
- public function testIMARGUMENT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMARGUMENT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIMARGUMENT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMARGUMENT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIMARGUMENT()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMARGUMENT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMARGUMENT.data');
+ }
/**
* @dataProvider providerIMCONJUGATE
*/
- public function testIMCONJUGATE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMCONJUGATE'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMCONJUGATE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMCONJUGATE'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMCONJUGATE()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMCONJUGATE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMCONJUGATE.data');
+ }
/**
* @dataProvider providerIMCOS
*/
- public function testIMCOS()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMCOS'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMCOS()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMCOS'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMCOS()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMCOS.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMCOS.data');
+ }
/**
* @dataProvider providerIMDIV
*/
- public function testIMDIV()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMDIV'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMDIV()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMDIV'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMDIV()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMDIV.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMDIV.data');
+ }
/**
* @dataProvider providerIMEXP
*/
- public function testIMEXP()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMEXP'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMEXP()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMEXP'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMEXP()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMEXP.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMEXP.data');
+ }
/**
* @dataProvider providerIMLN
*/
- public function testIMLN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMLN'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMLN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMLN'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMLN()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMLN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMLN.data');
+ }
/**
* @dataProvider providerIMLOG2
*/
- public function testIMLOG2()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMLOG2'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMLOG2()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMLOG2'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMLOG2()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMLOG2.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMLOG2.data');
+ }
/**
* @dataProvider providerIMLOG10
*/
- public function testIMLOG10()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMLOG10'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMLOG10()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMLOG10'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMLOG10()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMLOG10.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMLOG10.data');
+ }
/**
* @dataProvider providerIMPOWER
*/
- public function testIMPOWER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMPOWER'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMPOWER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMPOWER'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMPOWER()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMPOWER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMPOWER.data');
+ }
/**
* @dataProvider providerIMPRODUCT
*/
- public function testIMPRODUCT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMPRODUCT'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMPRODUCT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMPRODUCT'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMPRODUCT()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMPRODUCT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMPRODUCT.data');
+ }
/**
* @dataProvider providerIMSIN
*/
- public function testIMSIN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSIN'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMSIN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSIN'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMSIN()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSIN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSIN.data');
+ }
/**
* @dataProvider providerIMSQRT
*/
- public function testIMSQRT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSQRT'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMSQRT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSQRT'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMSQRT()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSQRT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSQRT.data');
+ }
/**
* @dataProvider providerIMSUB
*/
- public function testIMSUB()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUB'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMSUB()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUB'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMSUB()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUB.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUB.data');
+ }
/**
* @dataProvider providerIMSUM
*/
- public function testIMSUM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUM'),$args);
- $complexAssert = new complexAssert();
- $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
- $complexAssert->getErrorMessage());
- }
+ public function testIMSUM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUM'), $args);
+ $complexAssert = new complexAssert();
+ $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8), $complexAssert->getErrorMessage());
+ }
public function providerIMSUM()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUM.data');
+ }
/**
* @dataProvider providerERF
*/
- public function testERF()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','ERF'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testERF()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','ERF'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerERF()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/ERF.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/ERF.data');
+ }
/**
* @dataProvider providerERFC
*/
- public function testERFC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','ERFC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testERFC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','ERFC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerERFC()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/ERFC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/ERFC.data');
+ }
/**
* @dataProvider providerBIN2DEC
*/
- public function testBIN2DEC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BINTODEC'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testBIN2DEC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BINTODEC'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerBIN2DEC()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BIN2DEC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BIN2DEC.data');
+ }
/**
* @dataProvider providerBIN2HEX
*/
- public function testBIN2HEX()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BINTOHEX'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testBIN2HEX()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BINTOHEX'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerBIN2HEX()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BIN2HEX.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BIN2HEX.data');
+ }
/**
* @dataProvider providerBIN2OCT
*/
- public function testBIN2OCT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BINTOOCT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testBIN2OCT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','BINTOOCT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerBIN2OCT()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/BIN2OCT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/BIN2OCT.data');
+ }
/**
* @dataProvider providerDEC2BIN
*/
- public function testDEC2BIN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DECTOBIN'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testDEC2BIN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DECTOBIN'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerDEC2BIN()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/DEC2BIN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/DEC2BIN.data');
+ }
/**
* @dataProvider providerDEC2HEX
*/
- public function testDEC2HEX()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DECTOHEX'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testDEC2HEX()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DECTOHEX'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerDEC2HEX()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/DEC2HEX.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/DEC2HEX.data');
+ }
/**
* @dataProvider providerDEC2OCT
*/
- public function testDEC2OCT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DECTOOCT'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testDEC2OCT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DECTOOCT'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerDEC2OCT()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/DEC2OCT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/DEC2OCT.data');
+ }
/**
* @dataProvider providerHEX2BIN
*/
- public function testHEX2BIN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','HEXTOBIN'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testHEX2BIN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','HEXTOBIN'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerHEX2BIN()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/HEX2BIN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/HEX2BIN.data');
+ }
/**
* @dataProvider providerHEX2DEC
*/
- public function testHEX2DEC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','HEXTODEC'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testHEX2DEC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','HEXTODEC'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerHEX2DEC()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/HEX2DEC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/HEX2DEC.data');
+ }
/**
* @dataProvider providerHEX2OCT
*/
- public function testHEX2OCT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','HEXTOOCT'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testHEX2OCT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','HEXTOOCT'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerHEX2OCT()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/HEX2OCT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/HEX2OCT.data');
+ }
/**
* @dataProvider providerOCT2BIN
*/
- public function testOCT2BIN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','OCTTOBIN'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testOCT2BIN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','OCTTOBIN'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerOCT2BIN()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/OCT2BIN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/OCT2BIN.data');
+ }
/**
* @dataProvider providerOCT2DEC
*/
- public function testOCT2DEC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','OCTTODEC'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testOCT2DEC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','OCTTODEC'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerOCT2DEC()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/OCT2DEC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/OCT2DEC.data');
+ }
/**
* @dataProvider providerOCT2HEX
*/
- public function testOCT2HEX()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','OCTTOHEX'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testOCT2HEX()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','OCTTOHEX'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerOCT2HEX()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/OCT2HEX.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/OCT2HEX.data');
+ }
/**
* @dataProvider providerDELTA
*/
- public function testDELTA()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DELTA'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testDELTA()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','DELTA'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerDELTA()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/DELTA.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/DELTA.data');
+ }
/**
* @dataProvider providerGESTEP
*/
- public function testGESTEP()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','GESTEP'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testGESTEP()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','GESTEP'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerGESTEP()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/GESTEP.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/GESTEP.data');
+ }
- public function testGetConversionGroups()
- {
- $result = PHPExcel_Calculation_Engineering::getConversionGroups();
- $this->assertInternalType('array', $result);
- }
+ public function testGetConversionGroups()
+ {
+ $result = PHPExcel_Calculation_Engineering::getConversionGroups();
+ $this->assertInternalType('array', $result);
+ }
- public function testGetConversionGroupUnits()
- {
- $result = PHPExcel_Calculation_Engineering::getConversionGroupUnits();
- $this->assertInternalType('array', $result);
- }
+ public function testGetConversionGroupUnits()
+ {
+ $result = PHPExcel_Calculation_Engineering::getConversionGroupUnits();
+ $this->assertInternalType('array', $result);
+ }
- public function testGetConversionGroupUnitDetails()
- {
- $result = PHPExcel_Calculation_Engineering::getConversionGroupUnitDetails();
- $this->assertInternalType('array', $result);
- }
+ public function testGetConversionGroupUnitDetails()
+ {
+ $result = PHPExcel_Calculation_Engineering::getConversionGroupUnitDetails();
+ $this->assertInternalType('array', $result);
+ }
- public function testGetConversionMultipliers()
- {
- $result = PHPExcel_Calculation_Engineering::getConversionMultipliers();
- $this->assertInternalType('array', $result);
- }
+ public function testGetConversionMultipliers()
+ {
+ $result = PHPExcel_Calculation_Engineering::getConversionMultipliers();
+ $this->assertInternalType('array', $result);
+ }
/**
* @dataProvider providerCONVERTUOM
*/
- public function testCONVERTUOM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','CONVERTUOM'),$args);
- $this->assertEquals($expectedResult, $result, NULL);
- }
+ public function testCONVERTUOM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','CONVERTUOM'), $args);
+ $this->assertEquals($expectedResult, $result, null);
+ }
public function providerCONVERTUOM()
{
- return new testDataFileIterator('rawTestData/Calculation/Engineering/CONVERTUOM.data');
- }
-
+ return new testDataFileIterator('rawTestData/Calculation/Engineering/CONVERTUOM.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Calculation/FinancialTest.php b/unitTests/Classes/PHPExcel/Calculation/FinancialTest.php
index b27a6a7df..f6e39814c 100644
--- a/unitTests/Classes/PHPExcel/Calculation/FinancialTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/FinancialTest.php
@@ -8,507 +8,507 @@ class FinancialTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
/**
* @dataProvider providerACCRINT
*/
- public function testACCRINT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','ACCRINT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testACCRINT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','ACCRINT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerACCRINT()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/ACCRINT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/ACCRINT.data');
+ }
/**
* @dataProvider providerACCRINTM
*/
- public function testACCRINTM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','ACCRINTM'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testACCRINTM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','ACCRINTM'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerACCRINTM()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/ACCRINTM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/ACCRINTM.data');
+ }
/**
* @dataProvider providerAMORDEGRC
*/
- public function testAMORDEGRC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','AMORDEGRC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testAMORDEGRC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','AMORDEGRC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerAMORDEGRC()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/AMORDEGRC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/AMORDEGRC.data');
+ }
/**
* @dataProvider providerAMORLINC
*/
- public function testAMORLINC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','AMORLINC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testAMORLINC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','AMORLINC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerAMORLINC()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/AMORLINC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/AMORLINC.data');
+ }
/**
* @dataProvider providerCOUPDAYBS
*/
- public function testCOUPDAYBS()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPDAYBS'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCOUPDAYBS()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPDAYBS'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCOUPDAYBS()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/COUPDAYBS.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/COUPDAYBS.data');
+ }
/**
* @dataProvider providerCOUPDAYS
*/
- public function testCOUPDAYS()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPDAYS'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCOUPDAYS()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPDAYS'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCOUPDAYS()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/COUPDAYS.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/COUPDAYS.data');
+ }
/**
* @dataProvider providerCOUPDAYSNC
*/
- public function testCOUPDAYSNC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPDAYSNC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCOUPDAYSNC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPDAYSNC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCOUPDAYSNC()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/COUPDAYSNC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/COUPDAYSNC.data');
+ }
/**
* @dataProvider providerCOUPNCD
*/
- public function testCOUPNCD()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPNCD'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCOUPNCD()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPNCD'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCOUPNCD()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/COUPNCD.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/COUPNCD.data');
+ }
/**
* @dataProvider providerCOUPNUM
*/
- public function testCOUPNUM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPNUM'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCOUPNUM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPNUM'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCOUPNUM()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/COUPNUM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/COUPNUM.data');
+ }
/**
* @dataProvider providerCOUPPCD
*/
- public function testCOUPPCD()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPPCD'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCOUPPCD()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','COUPPCD'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCOUPPCD()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/COUPPCD.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/COUPPCD.data');
+ }
/**
* @dataProvider providerCUMIPMT
*/
- public function testCUMIPMT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','CUMIPMT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCUMIPMT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','CUMIPMT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCUMIPMT()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/CUMIPMT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/CUMIPMT.data');
+ }
/**
* @dataProvider providerCUMPRINC
*/
- public function testCUMPRINC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','CUMPRINC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testCUMPRINC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','CUMPRINC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerCUMPRINC()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/CUMPRINC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/CUMPRINC.data');
+ }
/**
* @dataProvider providerDB
*/
- public function testDB()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DB'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDB()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DB'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDB()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/DB.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/DB.data');
+ }
/**
* @dataProvider providerDDB
*/
- public function testDDB()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DDB'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDDB()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DDB'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDDB()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/DDB.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/DDB.data');
+ }
/**
* @dataProvider providerDISC
*/
- public function testDISC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DISC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDISC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DISC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDISC()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/DISC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/DISC.data');
+ }
/**
* @dataProvider providerDOLLARDE
*/
- public function testDOLLARDE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DOLLARDE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDOLLARDE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DOLLARDE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDOLLARDE()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/DOLLARDE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/DOLLARDE.data');
+ }
/**
* @dataProvider providerDOLLARFR
*/
- public function testDOLLARFR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DOLLARFR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testDOLLARFR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','DOLLARFR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerDOLLARFR()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/DOLLARFR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/DOLLARFR.data');
+ }
/**
* @dataProvider providerEFFECT
*/
- public function testEFFECT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','EFFECT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testEFFECT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','EFFECT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerEFFECT()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/EFFECT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/EFFECT.data');
+ }
/**
* @dataProvider providerFV
*/
- public function testFV()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','FV'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testFV()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','FV'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerFV()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/FV.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/FV.data');
+ }
/**
* @dataProvider providerFVSCHEDULE
*/
- public function testFVSCHEDULE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','FVSCHEDULE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testFVSCHEDULE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','FVSCHEDULE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerFVSCHEDULE()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/FVSCHEDULE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/FVSCHEDULE.data');
+ }
/**
* @dataProvider providerINTRATE
*/
- public function testINTRATE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','INTRATE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testINTRATE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','INTRATE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerINTRATE()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/INTRATE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/INTRATE.data');
+ }
/**
* @dataProvider providerIPMT
*/
- public function testIPMT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','IPMT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIPMT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','IPMT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIPMT()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/IPMT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/IPMT.data');
+ }
/**
* @dataProvider providerIRR
*/
- public function testIRR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','IRR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIRR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','IRR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIRR()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/IRR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/IRR.data');
+ }
/**
* @dataProvider providerISPMT
*/
- public function testISPMT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','ISPMT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testISPMT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','ISPMT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerISPMT()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/ISPMT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/ISPMT.data');
+ }
/**
* @dataProvider providerMIRR
*/
- public function testMIRR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','MIRR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testMIRR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','MIRR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerMIRR()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/MIRR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/MIRR.data');
+ }
/**
* @dataProvider providerNOMINAL
*/
- public function testNOMINAL()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','NOMINAL'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testNOMINAL()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','NOMINAL'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerNOMINAL()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/NOMINAL.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/NOMINAL.data');
+ }
/**
* @dataProvider providerNPER
*/
- public function testNPER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','NPER'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testNPER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','NPER'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerNPER()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/NPER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/NPER.data');
+ }
/**
* @dataProvider providerNPV
*/
- public function testNPV()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','NPV'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testNPV()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','NPV'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerNPV()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/NPV.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/NPV.data');
+ }
/**
* @dataProvider providerPRICE
*/
- public function testPRICE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','PRICE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testPRICE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','PRICE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerPRICE()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/PRICE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/PRICE.data');
+ }
/**
* @dataProvider providerRATE
*/
- public function testRATE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','RATE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testRATE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','RATE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerRATE()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/RATE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Financial/RATE.data');
+ }
/**
* @dataProvider providerXIRR
*/
- public function testXIRR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Financial','XIRR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testXIRR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Financial','XIRR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerXIRR()
{
- return new testDataFileIterator('rawTestData/Calculation/Financial/XIRR.data');
- }
-
+ return new testDataFileIterator('rawTestData/Calculation/Financial/XIRR.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Calculation/FunctionsTest.php b/unitTests/Classes/PHPExcel/Calculation/FunctionsTest.php
index 5e6ef962a..61c48205a 100644
--- a/unitTests/Classes/PHPExcel/Calculation/FunctionsTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/FunctionsTest.php
@@ -8,267 +8,267 @@ class FunctionsTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
-
- public function testDUMMY()
- {
- $result = PHPExcel_Calculation_Functions::DUMMY();
- $this->assertEquals('#Not Yet Implemented', $result);
- }
-
- public function testDIV0()
- {
- $result = PHPExcel_Calculation_Functions::DIV0();
- $this->assertEquals('#DIV/0!', $result);
- }
-
- public function testNA()
- {
- $result = PHPExcel_Calculation_Functions::NA();
- $this->assertEquals('#N/A', $result);
- }
-
- public function testNaN()
- {
- $result = PHPExcel_Calculation_Functions::NaN();
- $this->assertEquals('#NUM!', $result);
- }
-
- public function testNAME()
- {
- $result = PHPExcel_Calculation_Functions::NAME();
- $this->assertEquals('#NAME?', $result);
- }
-
- public function testREF()
- {
- $result = PHPExcel_Calculation_Functions::REF();
- $this->assertEquals('#REF!', $result);
- }
-
- public function testNULL()
- {
- $result = PHPExcel_Calculation_Functions::NULL();
- $this->assertEquals('#NULL!', $result);
- }
-
- public function testVALUE()
- {
- $result = PHPExcel_Calculation_Functions::VALUE();
- $this->assertEquals('#VALUE!', $result);
- }
+
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
+
+ public function testDUMMY()
+ {
+ $result = PHPExcel_Calculation_Functions::DUMMY();
+ $this->assertEquals('#Not Yet Implemented', $result);
+ }
+
+ public function testDIV0()
+ {
+ $result = PHPExcel_Calculation_Functions::DIV0();
+ $this->assertEquals('#DIV/0!', $result);
+ }
+
+ public function testNA()
+ {
+ $result = PHPExcel_Calculation_Functions::NA();
+ $this->assertEquals('#N/A', $result);
+ }
+
+ public function testNaN()
+ {
+ $result = PHPExcel_Calculation_Functions::NaN();
+ $this->assertEquals('#NUM!', $result);
+ }
+
+ public function testNAME()
+ {
+ $result = PHPExcel_Calculation_Functions::NAME();
+ $this->assertEquals('#NAME?', $result);
+ }
+
+ public function testREF()
+ {
+ $result = PHPExcel_Calculation_Functions::REF();
+ $this->assertEquals('#REF!', $result);
+ }
+
+ public function testNULL()
+ {
+ $result = PHPExcel_Calculation_Functions::null();
+ $this->assertEquals('#NULL!', $result);
+ }
+
+ public function testVALUE()
+ {
+ $result = PHPExcel_Calculation_Functions::VALUE();
+ $this->assertEquals('#VALUE!', $result);
+ }
/**
* @dataProvider providerIS_BLANK
*/
- public function testIS_BLANK()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_BLANK'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_BLANK()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_BLANK'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_BLANK()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_BLANK.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_BLANK.data');
+ }
/**
* @dataProvider providerIS_ERR
*/
- public function testIS_ERR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_ERR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_ERR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_ERR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_ERR()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_ERR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_ERR.data');
+ }
/**
* @dataProvider providerIS_ERROR
*/
- public function testIS_ERROR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_ERROR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_ERROR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_ERROR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_ERROR()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_ERROR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_ERROR.data');
+ }
/**
* @dataProvider providerERROR_TYPE
*/
- public function testERROR_TYPE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','ERROR_TYPE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testERROR_TYPE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','ERROR_TYPE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerERROR_TYPE()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/ERROR_TYPE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/ERROR_TYPE.data');
+ }
/**
* @dataProvider providerIS_LOGICAL
*/
- public function testIS_LOGICAL()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_LOGICAL'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_LOGICAL()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_LOGICAL'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_LOGICAL()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_LOGICAL.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_LOGICAL.data');
+ }
/**
* @dataProvider providerIS_NA
*/
- public function testIS_NA()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_NA'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_NA()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_NA'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_NA()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_NA.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_NA.data');
+ }
/**
* @dataProvider providerIS_NUMBER
*/
- public function testIS_NUMBER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_NUMBER'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_NUMBER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_NUMBER'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_NUMBER()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_NUMBER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_NUMBER.data');
+ }
/**
* @dataProvider providerIS_TEXT
*/
- public function testIS_TEXT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_TEXT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_TEXT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_TEXT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_TEXT()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_TEXT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_TEXT.data');
+ }
/**
* @dataProvider providerIS_NONTEXT
*/
- public function testIS_NONTEXT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_NONTEXT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_NONTEXT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_NONTEXT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_NONTEXT()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_NONTEXT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_NONTEXT.data');
+ }
/**
* @dataProvider providerIS_EVEN
*/
- public function testIS_EVEN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_EVEN'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_EVEN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_EVEN'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_EVEN()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_EVEN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_EVEN.data');
+ }
/**
* @dataProvider providerIS_ODD
*/
- public function testIS_ODD()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_ODD'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testIS_ODD()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','IS_ODD'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerIS_ODD()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/IS_ODD.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/IS_ODD.data');
+ }
/**
* @dataProvider providerTYPE
*/
- public function testTYPE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','TYPE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testTYPE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','TYPE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerTYPE()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/TYPE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Functions/TYPE.data');
+ }
/**
* @dataProvider providerN
*/
- public function testN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Functions','N'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-8);
- }
+ public function testN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Functions','N'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
public function providerN()
{
- return new testDataFileIterator('rawTestData/Calculation/Functions/N.data');
- }
-
+ return new testDataFileIterator('rawTestData/Calculation/Functions/N.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Calculation/LogicalTest.php b/unitTests/Classes/PHPExcel/Calculation/LogicalTest.php
index 46749d12c..e475c30fb 100644
--- a/unitTests/Classes/PHPExcel/Calculation/LogicalTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/LogicalTest.php
@@ -8,103 +8,103 @@ class LogicalTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
- public function testTRUE()
- {
- $result = PHPExcel_Calculation_Logical::TRUE();
- $this->assertEquals(TRUE, $result);
- }
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
+
+ public function testTRUE()
+ {
+ $result = PHPExcel_Calculation_Logical::TRUE();
+ $this->assertEquals(true, $result);
+ }
- public function testFALSE()
- {
- $result = PHPExcel_Calculation_Logical::FALSE();
- $this->assertEquals(FALSE, $result);
- }
+ public function testFALSE()
+ {
+ $result = PHPExcel_Calculation_Logical::FALSE();
+ $this->assertEquals(false, $result);
+ }
/**
* @dataProvider providerAND
*/
- public function testAND()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Logical','LOGICAL_AND'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testAND()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Logical','LOGICAL_AND'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerAND()
{
- return new testDataFileIterator('rawTestData/Calculation/Logical/AND.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Logical/AND.data');
+ }
/**
* @dataProvider providerOR
*/
- public function testOR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Logical','LOGICAL_OR'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testOR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Logical','LOGICAL_OR'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerOR()
{
- return new testDataFileIterator('rawTestData/Calculation/Logical/OR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Logical/OR.data');
+ }
/**
* @dataProvider providerNOT
*/
public function testNOT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Logical','NOT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Logical','NOT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerNOT()
{
- return new testDataFileIterator('rawTestData/Calculation/Logical/NOT.data');
+ return new testDataFileIterator('rawTestData/Calculation/Logical/NOT.data');
}
/**
* @dataProvider providerIF
*/
public function testIF()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Logical','STATEMENT_IF'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Logical','STATEMENT_IF'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerIF()
{
- return new testDataFileIterator('rawTestData/Calculation/Logical/IF.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/Logical/IF.data');
+ }
/**
* @dataProvider providerIFERROR
*/
public function testIFERROR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_Logical','IFERROR'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_Logical','IFERROR'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerIFERROR()
{
return new testDataFileIterator('rawTestData/Calculation/Logical/IFERROR.data');
- }
-
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Calculation/LookupRefTest.php b/unitTests/Classes/PHPExcel/Calculation/LookupRefTest.php
new file mode 100644
index 000000000..1408b73b8
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Calculation/LookupRefTest.php
@@ -0,0 +1,50 @@
+assertEquals($expectedResult, $result);
+ }
+
+ public function providerHLOOKUP()
+ {
+ return new testDataFileIterator('rawTestData/Calculation/LookupRef/HLOOKUP.data');
+ }
+
+ /**
+ * @dataProvider providerVLOOKUP
+ */
+ public function testVLOOKUP()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_LookupRef','VLOOKUP'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function providerVLOOKUP()
+ {
+ return new testDataFileIterator('rawTestData/Calculation/LookupRef/VLOOKUP.data');
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Calculation/MathTrigTest.php b/unitTests/Classes/PHPExcel/Calculation/MathTrigTest.php
index ce448d6ab..2f2bc2b54 100644
--- a/unitTests/Classes/PHPExcel/Calculation/MathTrigTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/MathTrigTest.php
@@ -8,477 +8,567 @@ class MathTrigTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
/**
* @dataProvider providerATAN2
*/
- public function testATAN2()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ATAN2'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testATAN2()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ATAN2'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerATAN2()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/ATAN2.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/ATAN2.data');
+ }
/**
* @dataProvider providerCEILING
*/
- public function testCEILING()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','CEILING'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testCEILING()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','CEILING'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerCEILING()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/CEILING.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/CEILING.data');
+ }
/**
* @dataProvider providerCOMBIN
*/
- public function testCOMBIN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','COMBIN'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testCOMBIN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','COMBIN'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerCOMBIN()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/COMBIN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/COMBIN.data');
+ }
/**
* @dataProvider providerEVEN
*/
- public function testEVEN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','EVEN'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testEVEN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','EVEN'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerEVEN()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/EVEN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/EVEN.data');
+ }
/**
* @dataProvider providerODD
*/
- public function testODD()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ODD'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testODD()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ODD'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerODD()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/ODD.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/ODD.data');
+ }
/**
* @dataProvider providerFACT
*/
- public function testFACT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','FACT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testFACT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','FACT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerFACT()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/FACT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/FACT.data');
+ }
/**
* @dataProvider providerFACTDOUBLE
*/
- public function testFACTDOUBLE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','FACTDOUBLE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testFACTDOUBLE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','FACTDOUBLE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerFACTDOUBLE()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/FACTDOUBLE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/FACTDOUBLE.data');
+ }
/**
* @dataProvider providerFLOOR
*/
- public function testFLOOR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','FLOOR'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testFLOOR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','FLOOR'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerFLOOR()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/FLOOR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/FLOOR.data');
+ }
/**
* @dataProvider providerGCD
*/
- public function testGCD()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','GCD'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testGCD()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','GCD'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerGCD()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/GCD.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/GCD.data');
+ }
/**
* @dataProvider providerLCM
*/
- public function testLCM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','LCM'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testLCM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','LCM'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerLCM()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/LCM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/LCM.data');
+ }
/**
* @dataProvider providerINT
*/
- public function testINT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','INT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testINT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','INT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerINT()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/INT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/INT.data');
+ }
/**
* @dataProvider providerSIGN
*/
- public function testSIGN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SIGN'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testSIGN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SIGN'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerSIGN()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/SIGN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/SIGN.data');
+ }
/**
* @dataProvider providerPOWER
*/
- public function testPOWER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','POWER'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testPOWER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','POWER'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerPOWER()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/POWER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/POWER.data');
+ }
/**
* @dataProvider providerLOG
*/
- public function testLOG()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','LOG_BASE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testLOG()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','LOG_BASE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerLOG()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/LOG.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/LOG.data');
+ }
/**
* @dataProvider providerMOD
*/
- public function testMOD()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MOD'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testMOD()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MOD'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerMOD()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/MOD.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/MOD.data');
+ }
/**
* @dataProvider providerMDETERM
*/
- public function testMDETERM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MDETERM'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testMDETERM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MDETERM'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerMDETERM()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/MDETERM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/MDETERM.data');
+ }
/**
* @dataProvider providerMINVERSE
*/
- public function testMINVERSE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MINVERSE'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testMINVERSE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MINVERSE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerMINVERSE()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/MINVERSE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/MINVERSE.data');
+ }
/**
* @dataProvider providerMMULT
*/
- public function testMMULT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MMULT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testMMULT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MMULT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerMMULT()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/MMULT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/MMULT.data');
+ }
/**
* @dataProvider providerMULTINOMIAL
*/
- public function testMULTINOMIAL()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MULTINOMIAL'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testMULTINOMIAL()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MULTINOMIAL'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerMULTINOMIAL()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/MULTINOMIAL.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/MULTINOMIAL.data');
+ }
/**
* @dataProvider providerMROUND
*/
- public function testMROUND()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MROUND'),$args);
- PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_ARRAY);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testMROUND()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','MROUND'), $args);
+ PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_ARRAY);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerMROUND()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/MROUND.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/MROUND.data');
+ }
/**
* @dataProvider providerPRODUCT
*/
- public function testPRODUCT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','PRODUCT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testPRODUCT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','PRODUCT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerPRODUCT()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/PRODUCT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/PRODUCT.data');
+ }
/**
* @dataProvider providerQUOTIENT
*/
- public function testQUOTIENT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','QUOTIENT'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testQUOTIENT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','QUOTIENT'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerQUOTIENT()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/QUOTIENT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/QUOTIENT.data');
+ }
/**
* @dataProvider providerROUNDUP
*/
- public function testROUNDUP()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ROUNDUP'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testROUNDUP()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ROUNDUP'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerROUNDUP()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/ROUNDUP.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/ROUNDUP.data');
+ }
/**
* @dataProvider providerROUNDDOWN
*/
- public function testROUNDDOWN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ROUNDDOWN'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testROUNDDOWN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ROUNDDOWN'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerROUNDDOWN()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/ROUNDDOWN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/ROUNDDOWN.data');
+ }
/**
* @dataProvider providerSERIESSUM
*/
- public function testSERIESSUM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SERIESSUM'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testSERIESSUM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SERIESSUM'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerSERIESSUM()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/SERIESSUM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/SERIESSUM.data');
+ }
+
+ /**
+ * @dataProvider providerSUMIFS
+ */
+ public function testSUMIFS()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SUMIFS'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
+
+ public function providerSUMIFS()
+ {
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/SUMIFS.data');
+ }
/**
* @dataProvider providerSUMSQ
*/
- public function testSUMSQ()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SUMSQ'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testSUMSQ()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SUMSQ'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerSUMSQ()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/SUMSQ.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/SUMSQ.data');
+ }
/**
* @dataProvider providerTRUNC
*/
- public function testTRUNC()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','TRUNC'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testTRUNC()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','TRUNC'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerTRUNC()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/TRUNC.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/TRUNC.data');
+ }
/**
* @dataProvider providerROMAN
*/
- public function testROMAN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ROMAN'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testROMAN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','ROMAN'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerROMAN()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/ROMAN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/ROMAN.data');
+ }
/**
* @dataProvider providerSQRTPI
*/
- public function testSQRTPI()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SQRTPI'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-12);
- }
+ public function testSQRTPI()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig','SQRTPI'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
public function providerSQRTPI()
{
- return new testDataFileIterator('rawTestData/Calculation/MathTrig/SQRTPI.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/MathTrig/SQRTPI.data');
+ }
+ /**
+ * @dataProvider providerSUMIF
+ */
+ public function testSUMIF()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_MathTrig', 'SUMIF'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-12);
+ }
+
+ public function providerSUMIF()
+ {
+ return array(
+ array(
+ array(
+ array(1),
+ array(5),
+ array(10),
+ ),
+ '>=5',
+ 15,
+ ),
+ array(
+ array(
+ array('text'),
+ array(2),
+ ),
+ '=text',
+ array(
+ array(10),
+ array(100),
+ ),
+ 10,
+ ),
+ array(
+ array(
+ array('"text with quotes"'),
+ array(2),
+ ),
+ '="text with quotes"',
+ array(
+ array(10),
+ array(100),
+ ),
+ 10,
+ ),
+ array(
+ array(
+ array('"text with quotes"'),
+ array(''),
+ ),
+ '>"', // Compare to the single characater " (double quote)
+ array(
+ array(10),
+ array(100),
+ ),
+ 10
+ ),
+ array(
+ array(
+ array(''),
+ array('anything'),
+ ),
+ '>"', // Compare to the single characater " (double quote)
+ array(
+ array(10),
+ array(100),
+ ),
+ 100
+ ),
+ );
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Calculation/TextDataTest.php b/unitTests/Classes/PHPExcel/Calculation/TextDataTest.php
index 717e8fefb..135d4b092 100644
--- a/unitTests/Classes/PHPExcel/Calculation/TextDataTest.php
+++ b/unitTests/Classes/PHPExcel/Calculation/TextDataTest.php
@@ -8,336 +8,356 @@ class TextDataTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+
+ PHPExcel_Calculation_Functions::setCompatibilityMode(PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL);
+ }
/**
* @dataProvider providerCHAR
*/
- public function testCHAR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','CHARACTER'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCHAR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','CHARACTER'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCHAR()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/CHAR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/CHAR.data');
+ }
/**
* @dataProvider providerCODE
*/
- public function testCODE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','ASCIICODE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCODE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','ASCIICODE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCODE()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/CODE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/CODE.data');
+ }
/**
* @dataProvider providerCONCATENATE
*/
- public function testCONCATENATE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','CONCATENATE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCONCATENATE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','CONCATENATE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCONCATENATE()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/CONCATENATE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/CONCATENATE.data');
+ }
/**
* @dataProvider providerLEFT
*/
- public function testLEFT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','LEFT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testLEFT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','LEFT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerLEFT()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/LEFT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/LEFT.data');
+ }
/**
* @dataProvider providerMID
*/
- public function testMID()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','MID'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testMID()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','MID'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerMID()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/MID.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/MID.data');
+ }
/**
* @dataProvider providerRIGHT
*/
- public function testRIGHT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','RIGHT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testRIGHT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','RIGHT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerRIGHT()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/RIGHT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/RIGHT.data');
+ }
/**
* @dataProvider providerLOWER
*/
- public function testLOWER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','LOWERCASE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testLOWER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','LOWERCASE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerLOWER()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/LOWER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/LOWER.data');
+ }
/**
* @dataProvider providerUPPER
*/
- public function testUPPER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','UPPERCASE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testUPPER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','UPPERCASE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerUPPER()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/UPPER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/UPPER.data');
+ }
/**
* @dataProvider providerPROPER
*/
- public function testPROPER()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','PROPERCASE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testPROPER()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','PROPERCASE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerPROPER()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/PROPER.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/PROPER.data');
+ }
/**
* @dataProvider providerLEN
*/
- public function testLEN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','STRINGLENGTH'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testLEN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','STRINGLENGTH'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerLEN()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/LEN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/LEN.data');
+ }
/**
* @dataProvider providerSEARCH
*/
- public function testSEARCH()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','SEARCHINSENSITIVE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testSEARCH()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','SEARCHINSENSITIVE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerSEARCH()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/SEARCH.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/SEARCH.data');
+ }
/**
* @dataProvider providerFIND
*/
- public function testFIND()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','SEARCHSENSITIVE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testFIND()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','SEARCHSENSITIVE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerFIND()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/FIND.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/FIND.data');
+ }
/**
* @dataProvider providerREPLACE
*/
- public function testREPLACE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','REPLACE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testREPLACE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','REPLACE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerREPLACE()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/REPLACE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/REPLACE.data');
+ }
/**
* @dataProvider providerSUBSTITUTE
*/
- public function testSUBSTITUTE()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','SUBSTITUTE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testSUBSTITUTE()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','SUBSTITUTE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerSUBSTITUTE()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/SUBSTITUTE.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/SUBSTITUTE.data');
+ }
/**
* @dataProvider providerTRIM
*/
- public function testTRIM()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','TRIMSPACES'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testTRIM()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','TRIMSPACES'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerTRIM()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/TRIM.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/TRIM.data');
+ }
/**
* @dataProvider providerCLEAN
*/
- public function testCLEAN()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','TRIMNONPRINTABLE'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCLEAN()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','TRIMNONPRINTABLE'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCLEAN()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/CLEAN.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/CLEAN.data');
+ }
/**
* @dataProvider providerDOLLAR
*/
- public function testDOLLAR()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','DOLLAR'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testDOLLAR()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','DOLLAR'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerDOLLAR()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/DOLLAR.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/DOLLAR.data');
+ }
/**
* @dataProvider providerFIXED
*/
- public function testFIXED()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','FIXEDFORMAT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testFIXED()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','FIXEDFORMAT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerFIXED()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/FIXED.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/FIXED.data');
+ }
/**
* @dataProvider providerT
*/
- public function testT()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','RETURNSTRING'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testT()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData','RETURNSTRING'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerT()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/T.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/T.data');
+ }
/**
* @dataProvider providerTEXT
*/
- public function testTEXT()
- {
- // Enforce decimal and thousands separator values to UK/US, and currency code to USD
- call_user_func(array('PHPExcel_Shared_String','setDecimalSeparator'),'.');
- call_user_func(array('PHPExcel_Shared_String','setThousandsSeparator'),',');
- call_user_func(array('PHPExcel_Shared_String','setCurrencyCode'),'$');
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Calculation_TextData','TEXTFORMAT'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testTEXT()
+ {
+ // Enforce decimal and thousands separator values to UK/US, and currency code to USD
+ call_user_func(array('PHPExcel_Shared_String', 'setDecimalSeparator'), '.');
+ call_user_func(array('PHPExcel_Shared_String', 'setThousandsSeparator'), ',');
+ call_user_func(array('PHPExcel_Shared_String', 'setCurrencyCode'), '$');
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData', 'TEXTFORMAT'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerTEXT()
{
- return new testDataFileIterator('rawTestData/Calculation/TextData/TEXT.data');
- }
+ return new testDataFileIterator('rawTestData/Calculation/TextData/TEXT.data');
+ }
+ /**
+ * @dataProvider providerVALUE
+ */
+ public function testVALUE()
+ {
+ call_user_func(array('PHPExcel_Shared_String', 'setDecimalSeparator'), '.');
+ call_user_func(array('PHPExcel_Shared_String', 'setThousandsSeparator'), ' ');
+ call_user_func(array('PHPExcel_Shared_String', 'setCurrencyCode'), '$');
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Calculation_TextData', 'VALUE'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-8);
+ }
+
+ public function providerVALUE()
+ {
+ return new testDataFileIterator('rawTestData/Calculation/TextData/VALUE.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/CalculationTest.php b/unitTests/Classes/PHPExcel/CalculationTest.php
new file mode 100644
index 000000000..bc221ce2a
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/CalculationTest.php
@@ -0,0 +1,35 @@
+_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');
+ }
+
+ public function providerBinaryComparisonOperation()
+ {
+ return new testDataFileIterator('rawTestData/CalculationBinaryComparisonOperation.data');
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Cell/AdvancedValueBinderTest.php b/unitTests/Classes/PHPExcel/Cell/AdvancedValueBinderTest.php
index a76a2b25a..0a55ba730 100644
--- a/unitTests/Classes/PHPExcel/Cell/AdvancedValueBinderTest.php
+++ b/unitTests/Classes/PHPExcel/Cell/AdvancedValueBinderTest.php
@@ -13,20 +13,20 @@ public function setUp()
public function provider()
{
if (!class_exists('PHPExcel_Style_NumberFormat')) {
- $this->setUp();
+ $this->setUp();
}
$currencyUSD = PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
$currencyEURO = str_replace('$', '€', PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
return array(
- array('10%', 0.1, PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00, ',', '.', '$'),
- array('$10.11', 10.11, $currencyUSD, ',', '.', '$'),
- array('$1,010.12', 1010.12, $currencyUSD, ',', '.', '$'),
- array('$20,20', 20.2, $currencyUSD, '.', ',', '$'),
- array('$2.020,20', 2020.2, $currencyUSD, '.', ',', '$'),
- array('€2.020,20', 2020.2, $currencyEURO, '.', ',', '€'),
- array('€ 2.020,20', 2020.2, $currencyEURO, '.', ',', '€'),
- array('€2,020.22', 2020.22, $currencyEURO, ',', '.', '€'),
+ array('10%', 0.1, PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00, ',', '.', '$'),
+ array('$10.11', 10.11, $currencyUSD, ',', '.', '$'),
+ array('$1,010.12', 1010.12, $currencyUSD, ',', '.', '$'),
+ array('$20,20', 20.2, $currencyUSD, '.', ',', '$'),
+ array('$2.020,20', 2020.2, $currencyUSD, '.', ',', '$'),
+ array('€2.020,20', 2020.2, $currencyEURO, '.', ',', '€'),
+ array('€ 2.020,20', 2020.2, $currencyEURO, '.', ',', '€'),
+ array('€2,020.22', 2020.22, $currencyEURO, ',', '.', '€'),
);
}
@@ -35,7 +35,16 @@ public function provider()
*/
public function testCurrency($value, $valueBinded, $format, $thousandsSeparator, $decimalSeparator, $currencyCode)
{
- $sheet = $this->getMock('PHPExcel_Worksheet', array('getStyle', 'getNumberFormat', 'setFormatCode'));
+ $sheet = $this->getMock(
+ 'PHPExcel_Worksheet',
+ array('getStyle', 'getNumberFormat', 'setFormatCode','getCellCacheController')
+ );
+ $cache = $this->getMockBuilder('PHPExcel_CachedObjectStorage_Memory')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $cache->expects($this->any())
+ ->method('getParent')
+ ->will($this->returnValue($sheet));
$sheet->expects($this->once())
->method('getStyle')
@@ -47,15 +56,18 @@ public function testCurrency($value, $valueBinded, $format, $thousandsSeparator,
->method('setFormatCode')
->with($format)
->will($this->returnSelf());
+ $sheet->expects($this->any())
+ ->method('getCellCacheController')
+ ->will($this->returnValue($cache));
PHPExcel_Shared_String::setCurrencyCode($currencyCode);
PHPExcel_Shared_String::setDecimalSeparator($decimalSeparator);
PHPExcel_Shared_String::setThousandsSeparator($thousandsSeparator);
- $cell = new PHPExcel_Cell('A', 1, null, PHPExcel_Cell_DataType::TYPE_STRING, $sheet);
+ $cell = new PHPExcel_Cell(null, PHPExcel_Cell_DataType::TYPE_STRING, $sheet);
$binder = new PHPExcel_Cell_AdvancedValueBinder();
$binder->bindValue($cell, $value);
$this->assertEquals($valueBinded, $cell->getValue());
}
-}
\ No newline at end of file
+}
diff --git a/unitTests/Classes/PHPExcel/Cell/DataTypeTest.php b/unitTests/Classes/PHPExcel/Cell/DataTypeTest.php
index c17c5d0fc..1180c9d6f 100644
--- a/unitTests/Classes/PHPExcel/Cell/DataTypeTest.php
+++ b/unitTests/Classes/PHPExcel/Cell/DataTypeTest.php
@@ -6,19 +6,17 @@ class DataTypeTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
-
- public function testGetErrorCodes()
- {
- $result = call_user_func(array('PHPExcel_Cell_DataType','getErrorCodes'));
- $this->assertInternalType('array', $result);
- $this->assertGreaterThan(0, count($result));
- $this->assertArrayHasKey('#NULL!', $result);
- }
+ }
+ public function testGetErrorCodes()
+ {
+ $result = call_user_func(array('PHPExcel_Cell_DataType','getErrorCodes'));
+ $this->assertInternalType('array', $result);
+ $this->assertGreaterThan(0, count($result));
+ $this->assertArrayHasKey('#NULL!', $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Cell/DefaultValueBinderTest.php b/unitTests/Classes/PHPExcel/Cell/DefaultValueBinderTest.php
new file mode 100644
index 000000000..37287b1fe
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Cell/DefaultValueBinderTest.php
@@ -0,0 +1,84 @@
+cellStub = $this->getMockBuilder('PHPExcel_Cell')
+ ->disableOriginalConstructor()
+ ->getMock();
+ // Configure the stub.
+ $this->cellStub->expects($this->any())
+ ->method('setValueExplicit')
+ ->will($this->returnValue(true));
+
+ }
+
+ /**
+ * @dataProvider binderProvider
+ */
+ public function testBindValue($value)
+ {
+ $this->createCellStub();
+ $binder = new PHPExcel_Cell_DefaultValueBinder();
+ $result = $binder->bindValue($this->cellStub, $value);
+ $this->assertTrue($result);
+ }
+
+ public function binderProvider()
+ {
+ return array(
+ array(null),
+ array(''),
+ array('ABC'),
+ array('=SUM(A1:B2)'),
+ array(true),
+ array(false),
+ array(123),
+ array(-123.456),
+ array('123'),
+ array('-123.456'),
+ array('#REF!'),
+ array(new DateTime()),
+ );
+ }
+
+ /**
+ * @dataProvider providerDataTypeForValue
+ */
+ public function testDataTypeForValue()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell_DefaultValueBinder','dataTypeForValue'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function providerDataTypeForValue()
+ {
+ return new testDataFileIterator('rawTestData/Cell/DefaultValueBinder.data');
+ }
+
+ public function testDataTypeForRichTextObject()
+ {
+ $objRichText = new PHPExcel_RichText();
+ $objRichText->createText('Hello World');
+
+ $expectedResult = PHPExcel_Cell_DataType::TYPE_INLINE;
+ $result = call_user_func(array('PHPExcel_Cell_DefaultValueBinder','dataTypeForValue'), $objRichText);
+ $this->assertEquals($expectedResult, $result);
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Cell/HyperlinkTest.php b/unitTests/Classes/PHPExcel/Cell/HyperlinkTest.php
index 54910cfd5..42dff6a56 100644
--- a/unitTests/Classes/PHPExcel/Cell/HyperlinkTest.php
+++ b/unitTests/Classes/PHPExcel/Cell/HyperlinkTest.php
@@ -6,83 +6,81 @@ class HyperlinkTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
- public function testGetUrl()
- {
- $urlValue = 'http://www.phpexcel.net/';
-
- $testInstance = new PHPExcel_Cell_Hyperlink($urlValue);
+ public function testGetUrl()
+ {
+ $urlValue = 'http://www.phpexcel.net/';
- $result = $testInstance->getUrl();
- $this->assertEquals($urlValue,$result);
- }
+ $testInstance = new PHPExcel_Cell_Hyperlink($urlValue);
- public function testSetUrl()
- {
- $initialUrlValue = 'http://www.phpexcel.net/';
- $newUrlValue = 'http://github.com/PHPOffice/PHPExcel';
+ $result = $testInstance->getUrl();
+ $this->assertEquals($urlValue, $result);
+ }
- $testInstance = new PHPExcel_Cell_Hyperlink($initialUrlValue);
- $result = $testInstance->setUrl($newUrlValue);
- $this->assertTrue($result instanceof PHPExcel_Cell_Hyperlink);
+ public function testSetUrl()
+ {
+ $initialUrlValue = 'http://www.phpexcel.net/';
+ $newUrlValue = 'http://github.com/PHPOffice/PHPExcel';
- $result = $testInstance->getUrl();
- $this->assertEquals($newUrlValue,$result);
- }
+ $testInstance = new PHPExcel_Cell_Hyperlink($initialUrlValue);
+ $result = $testInstance->setUrl($newUrlValue);
+ $this->assertTrue($result instanceof PHPExcel_Cell_Hyperlink);
- public function testGetTooltip()
- {
- $tooltipValue = 'PHPExcel Web Site';
+ $result = $testInstance->getUrl();
+ $this->assertEquals($newUrlValue, $result);
+ }
- $testInstance = new PHPExcel_Cell_Hyperlink(NULL, $tooltipValue);
+ public function testGetTooltip()
+ {
+ $tooltipValue = 'PHPExcel Web Site';
- $result = $testInstance->getTooltip();
- $this->assertEquals($tooltipValue,$result);
- }
+ $testInstance = new PHPExcel_Cell_Hyperlink(null, $tooltipValue);
- public function testSetTooltip()
- {
- $initialTooltipValue = 'PHPExcel Web Site';
- $newTooltipValue = 'PHPExcel Repository on Github';
+ $result = $testInstance->getTooltip();
+ $this->assertEquals($tooltipValue, $result);
+ }
- $testInstance = new PHPExcel_Cell_Hyperlink(NULL, $initialTooltipValue);
- $result = $testInstance->setTooltip($newTooltipValue);
- $this->assertTrue($result instanceof PHPExcel_Cell_Hyperlink);
+ public function testSetTooltip()
+ {
+ $initialTooltipValue = 'PHPExcel Web Site';
+ $newTooltipValue = 'PHPExcel Repository on Github';
- $result = $testInstance->getTooltip();
- $this->assertEquals($newTooltipValue,$result);
- }
+ $testInstance = new PHPExcel_Cell_Hyperlink(null, $initialTooltipValue);
+ $result = $testInstance->setTooltip($newTooltipValue);
+ $this->assertTrue($result instanceof PHPExcel_Cell_Hyperlink);
- public function testIsInternal()
- {
- $initialUrlValue = 'http://www.phpexcel.net/';
- $newUrlValue = 'sheet://Worksheet1!A1';
+ $result = $testInstance->getTooltip();
+ $this->assertEquals($newTooltipValue, $result);
+ }
- $testInstance = new PHPExcel_Cell_Hyperlink($initialUrlValue);
- $result = $testInstance->isInternal();
- $this->assertFalse($result);
+ public function testIsInternal()
+ {
+ $initialUrlValue = 'http://www.phpexcel.net/';
+ $newUrlValue = 'sheet://Worksheet1!A1';
- $testInstance->setUrl($newUrlValue);
- $result = $testInstance->isInternal();
- $this->assertTrue($result);
- }
+ $testInstance = new PHPExcel_Cell_Hyperlink($initialUrlValue);
+ $result = $testInstance->isInternal();
+ $this->assertFalse($result);
- public function testGetHashCode()
- {
- $urlValue = 'http://www.phpexcel.net/';
- $tooltipValue = 'PHPExcel Web Site';
- $initialExpectedHash = 'd84d713aed1dbbc8a7c5af183d6c7dbb';
+ $testInstance->setUrl($newUrlValue);
+ $result = $testInstance->isInternal();
+ $this->assertTrue($result);
+ }
- $testInstance = new PHPExcel_Cell_Hyperlink($urlValue, $tooltipValue);
+ public function testGetHashCode()
+ {
+ $urlValue = 'http://www.phpexcel.net/';
+ $tooltipValue = 'PHPExcel Web Site';
+ $initialExpectedHash = 'd84d713aed1dbbc8a7c5af183d6c7dbb';
- $result = $testInstance->getHashCode();
- $this->assertEquals($initialExpectedHash,$result);
- }
+ $testInstance = new PHPExcel_Cell_Hyperlink($urlValue, $tooltipValue);
+ $result = $testInstance->getHashCode();
+ $this->assertEquals($initialExpectedHash, $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/CellTest.php b/unitTests/Classes/PHPExcel/CellTest.php
index 11df404ce..9680294a5 100644
--- a/unitTests/Classes/PHPExcel/CellTest.php
+++ b/unitTests/Classes/PHPExcel/CellTest.php
@@ -12,284 +12,283 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
/**
* @dataProvider providerColumnString
*/
- public function testColumnIndexFromString()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','columnIndexFromString'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testColumnIndexFromString()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','columnIndexFromString'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerColumnString()
{
- return new testDataFileIterator('rawTestData/ColumnString.data');
- }
+ return new testDataFileIterator('rawTestData/ColumnString.data');
+ }
public function testColumnIndexFromStringTooLong()
- {
- $cellAddress = 'ABCD';
- try {
- $result = call_user_func(array('PHPExcel_Cell','columnIndexFromString'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Column string index can not be longer than 3 characters');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = 'ABCD';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','columnIndexFromString'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Column string index can not be longer than 3 characters');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
public function testColumnIndexFromStringTooShort()
- {
- $cellAddress = '';
- try {
- $result = call_user_func(array('PHPExcel_Cell','columnIndexFromString'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Column string index can not be empty');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = '';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','columnIndexFromString'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Column string index can not be empty');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
/**
* @dataProvider providerColumnIndex
*/
- public function testStringFromColumnIndex()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','stringFromColumnIndex'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testStringFromColumnIndex()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','stringFromColumnIndex'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerColumnIndex()
{
- return new testDataFileIterator('rawTestData/ColumnIndex.data');
- }
+ return new testDataFileIterator('rawTestData/ColumnIndex.data');
+ }
/**
* @dataProvider providerCoordinates
*/
- public function testCoordinateFromString()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','coordinateFromString'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCoordinateFromString()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','coordinateFromString'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCoordinates()
{
- return new testDataFileIterator('rawTestData/CellCoordinates.data');
- }
+ return new testDataFileIterator('rawTestData/CellCoordinates.data');
+ }
public function testCoordinateFromStringWithRangeAddress()
- {
- $cellAddress = 'A1:AI2012';
- try {
- $result = call_user_func(array('PHPExcel_Cell','coordinateFromString'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = 'A1:AI2012';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','coordinateFromString'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
public function testCoordinateFromStringWithEmptyAddress()
- {
- $cellAddress = '';
- try {
- $result = call_user_func(array('PHPExcel_Cell','coordinateFromString'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Cell coordinate can not be zero-length string');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = '';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','coordinateFromString'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Cell coordinate can not be zero-length string');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
public function testCoordinateFromStringWithInvalidAddress()
- {
- $cellAddress = 'AI';
- try {
- $result = call_user_func(array('PHPExcel_Cell','coordinateFromString'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Invalid cell coordinate '.$cellAddress);
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = 'AI';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','coordinateFromString'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Invalid cell coordinate '.$cellAddress);
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
/**
* @dataProvider providerAbsoluteCoordinates
*/
- public function testAbsoluteCoordinateFromString()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','absoluteCoordinate'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testAbsoluteCoordinateFromString()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','absoluteCoordinate'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerAbsoluteCoordinates()
{
- return new testDataFileIterator('rawTestData/CellAbsoluteCoordinate.data');
- }
+ return new testDataFileIterator('rawTestData/CellAbsoluteCoordinate.data');
+ }
public function testAbsoluteCoordinateFromStringWithRangeAddress()
- {
- $cellAddress = 'A1:AI2012';
- try {
- $result = call_user_func(array('PHPExcel_Cell','absoluteCoordinate'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = 'A1:AI2012';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','absoluteCoordinate'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
/**
* @dataProvider providerAbsoluteReferences
*/
- public function testAbsoluteReferenceFromString()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','absoluteReference'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testAbsoluteReferenceFromString()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','absoluteReference'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerAbsoluteReferences()
{
- return new testDataFileIterator('rawTestData/CellAbsoluteReference.data');
- }
+ return new testDataFileIterator('rawTestData/CellAbsoluteReference.data');
+ }
public function testAbsoluteReferenceFromStringWithRangeAddress()
- {
- $cellAddress = 'A1:AI2012';
- try {
- $result = call_user_func(array('PHPExcel_Cell','absoluteReference'),$cellAddress);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellAddress = 'A1:AI2012';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','absoluteReference'), $cellAddress);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Cell coordinate string can not be a range of cells');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
/**
* @dataProvider providerSplitRange
*/
- public function testSplitRange()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','splitRange'),$args);
- foreach($result as $key => $split) {
- if (!is_array($expectedResult[$key])) {
- $this->assertEquals($expectedResult[$key], $split[0]);
- } else {
- $this->assertEquals($expectedResult[$key], $split);
- }
- }
- }
+ public function testSplitRange()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','splitRange'), $args);
+ foreach ($result as $key => $split) {
+ if (!is_array($expectedResult[$key])) {
+ $this->assertEquals($expectedResult[$key], $split[0]);
+ } else {
+ $this->assertEquals($expectedResult[$key], $split);
+ }
+ }
+ }
public function providerSplitRange()
{
- return new testDataFileIterator('rawTestData/CellSplitRange.data');
- }
+ return new testDataFileIterator('rawTestData/CellSplitRange.data');
+ }
/**
* @dataProvider providerBuildRange
*/
- public function testBuildRange()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','buildRange'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testBuildRange()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','buildRange'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerBuildRange()
{
- return new testDataFileIterator('rawTestData/CellBuildRange.data');
- }
+ return new testDataFileIterator('rawTestData/CellBuildRange.data');
+ }
public function testBuildRangeInvalid()
- {
- $cellRange = '';
- try {
- $result = call_user_func(array('PHPExcel_Cell','buildRange'),$cellRange);
- } catch (PHPExcel_Exception $e) {
- $this->assertEquals($e->getMessage(), 'Range does not contain any information');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $cellRange = '';
+ try {
+ $result = call_user_func(array('PHPExcel_Cell','buildRange'), $cellRange);
+ } catch (PHPExcel_Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Range does not contain any information');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
/**
* @dataProvider providerRangeBoundaries
*/
- public function testRangeBoundaries()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','rangeBoundaries'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testRangeBoundaries()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','rangeBoundaries'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerRangeBoundaries()
{
- return new testDataFileIterator('rawTestData/CellRangeBoundaries.data');
- }
+ return new testDataFileIterator('rawTestData/CellRangeBoundaries.data');
+ }
/**
* @dataProvider providerRangeDimension
*/
- public function testRangeDimension()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','rangeDimension'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testRangeDimension()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','rangeDimension'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerRangeDimension()
{
- return new testDataFileIterator('rawTestData/CellRangeDimension.data');
- }
+ return new testDataFileIterator('rawTestData/CellRangeDimension.data');
+ }
/**
* @dataProvider providerGetRangeBoundaries
*/
- public function testGetRangeBoundaries()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','getRangeBoundaries'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testGetRangeBoundaries()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','getRangeBoundaries'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerGetRangeBoundaries()
{
- return new testDataFileIterator('rawTestData/CellGetRangeBoundaries.data');
- }
+ return new testDataFileIterator('rawTestData/CellGetRangeBoundaries.data');
+ }
/**
* @dataProvider providerExtractAllCellReferencesInRange
*/
- public function testExtractAllCellReferencesInRange()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Cell','extractAllCellReferencesInRange'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testExtractAllCellReferencesInRange()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Cell','extractAllCellReferencesInRange'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerExtractAllCellReferencesInRange()
{
- return new testDataFileIterator('rawTestData/CellExtractAllCellReferencesInRange.data');
- }
-
+ return new testDataFileIterator('rawTestData/CellExtractAllCellReferencesInRange.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Chart/DataSeriesValuesTest.php b/unitTests/Classes/PHPExcel/Chart/DataSeriesValuesTest.php
index 38284de9a..5bb527cd5 100644
--- a/unitTests/Classes/PHPExcel/Chart/DataSeriesValuesTest.php
+++ b/unitTests/Classes/PHPExcel/Chart/DataSeriesValuesTest.php
@@ -6,50 +6,48 @@ class DataSeriesValuesTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
-
- public function testSetDataType()
- {
- $dataTypeValues = array(
- 'Number',
- 'String'
- );
-
- $testInstance = new PHPExcel_Chart_DataSeriesValues;
-
- foreach($dataTypeValues as $dataTypeValue) {
- $result = $testInstance->setDataType($dataTypeValue);
- $this->assertTrue($result instanceof PHPExcel_Chart_DataSeriesValues);
- }
- }
-
- public function testSetInvalidDataTypeThrowsException()
- {
- $testInstance = new PHPExcel_Chart_DataSeriesValues;
-
- try {
- $result = $testInstance->setDataType('BOOLEAN');
- } catch (Exception $e) {
- $this->assertEquals($e->getMessage(), 'Invalid datatype for chart data series values');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
-
- public function testGetDataType()
- {
- $dataTypeValue = 'String';
-
- $testInstance = new PHPExcel_Chart_DataSeriesValues;
- $setValue = $testInstance->setDataType($dataTypeValue);
-
- $result = $testInstance->getDataType();
- $this->assertEquals($dataTypeValue,$result);
- }
+ }
+ public function testSetDataType()
+ {
+ $dataTypeValues = array(
+ 'Number',
+ 'String'
+ );
+
+ $testInstance = new PHPExcel_Chart_DataSeriesValues;
+
+ foreach ($dataTypeValues as $dataTypeValue) {
+ $result = $testInstance->setDataType($dataTypeValue);
+ $this->assertTrue($result instanceof PHPExcel_Chart_DataSeriesValues);
+ }
+ }
+
+ public function testSetInvalidDataTypeThrowsException()
+ {
+ $testInstance = new PHPExcel_Chart_DataSeriesValues;
+
+ try {
+ $result = $testInstance->setDataType('BOOLEAN');
+ } catch (Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Invalid datatype for chart data series values');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
+
+ public function testGetDataType()
+ {
+ $dataTypeValue = 'String';
+
+ $testInstance = new PHPExcel_Chart_DataSeriesValues;
+ $setValue = $testInstance->setDataType($dataTypeValue);
+
+ $result = $testInstance->getDataType();
+ $this->assertEquals($dataTypeValue, $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Chart/LayoutTest.php b/unitTests/Classes/PHPExcel/Chart/LayoutTest.php
index f24e01c31..a06b09b48 100644
--- a/unitTests/Classes/PHPExcel/Chart/LayoutTest.php
+++ b/unitTests/Classes/PHPExcel/Chart/LayoutTest.php
@@ -6,32 +6,30 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
- public function testSetLayoutTarget()
- {
- $LayoutTargetValue = 'String';
-
- $testInstance = new PHPExcel_Chart_Layout;
+ public function testSetLayoutTarget()
+ {
+ $LayoutTargetValue = 'String';
- $result = $testInstance->setLayoutTarget($LayoutTargetValue);
- $this->assertTrue($result instanceof PHPExcel_Chart_Layout);
- }
+ $testInstance = new PHPExcel_Chart_Layout;
- public function testGetLayoutTarget()
- {
- $LayoutTargetValue = 'String';
+ $result = $testInstance->setLayoutTarget($LayoutTargetValue);
+ $this->assertTrue($result instanceof PHPExcel_Chart_Layout);
+ }
- $testInstance = new PHPExcel_Chart_Layout;
- $setValue = $testInstance->setLayoutTarget($LayoutTargetValue);
+ public function testGetLayoutTarget()
+ {
+ $LayoutTargetValue = 'String';
- $result = $testInstance->getLayoutTarget();
- $this->assertEquals($LayoutTargetValue,$result);
- }
+ $testInstance = new PHPExcel_Chart_Layout;
+ $setValue = $testInstance->setLayoutTarget($LayoutTargetValue);
+ $result = $testInstance->getLayoutTarget();
+ $this->assertEquals($LayoutTargetValue, $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Chart/LegendTest.php b/unitTests/Classes/PHPExcel/Chart/LegendTest.php
index 4c4f8df81..b4df4119a 100644
--- a/unitTests/Classes/PHPExcel/Chart/LegendTest.php
+++ b/unitTests/Classes/PHPExcel/Chart/LegendTest.php
@@ -6,129 +6,127 @@ class LegendTest extends PHPUnit_Framework_TestCase
public function setUp()
{
- if (!defined('PHPEXCEL_ROOT'))
- {
+ if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
-
- public function testSetPosition()
- {
- $positionValues = array(
- PHPExcel_Chart_Legend::POSITION_RIGHT,
- PHPExcel_Chart_Legend::POSITION_LEFT,
- PHPExcel_Chart_Legend::POSITION_TOP,
- PHPExcel_Chart_Legend::POSITION_BOTTOM,
- PHPExcel_Chart_Legend::POSITION_TOPRIGHT,
- );
-
- $testInstance = new PHPExcel_Chart_Legend;
-
- foreach($positionValues as $positionValue) {
- $result = $testInstance->setPosition($positionValue);
- $this->assertTrue($result);
- }
- }
-
- public function testSetInvalidPositionReturnsFalse()
- {
- $testInstance = new PHPExcel_Chart_Legend;
-
- $result = $testInstance->setPosition('BottomLeft');
- $this->assertFalse($result);
- // Ensure that value is unchanged
- $result = $testInstance->getPosition();
- $this->assertEquals(PHPExcel_Chart_Legend::POSITION_RIGHT,$result);
- }
-
- public function testGetPosition()
- {
- $PositionValue = PHPExcel_Chart_Legend::POSITION_BOTTOM;
-
- $testInstance = new PHPExcel_Chart_Legend;
- $setValue = $testInstance->setPosition($PositionValue);
-
- $result = $testInstance->getPosition();
- $this->assertEquals($PositionValue,$result);
- }
-
- public function testSetPositionXL()
- {
- $positionValues = array(
- PHPExcel_Chart_Legend::xlLegendPositionBottom,
- PHPExcel_Chart_Legend::xlLegendPositionCorner,
- PHPExcel_Chart_Legend::xlLegendPositionCustom,
- PHPExcel_Chart_Legend::xlLegendPositionLeft,
- PHPExcel_Chart_Legend::xlLegendPositionRight,
- PHPExcel_Chart_Legend::xlLegendPositionTop,
- );
-
- $testInstance = new PHPExcel_Chart_Legend;
-
- foreach($positionValues as $positionValue) {
- $result = $testInstance->setPositionXL($positionValue);
- $this->assertTrue($result);
- }
- }
-
- public function testSetInvalidXLPositionReturnsFalse()
- {
- $testInstance = new PHPExcel_Chart_Legend;
-
- $result = $testInstance->setPositionXL(999);
- $this->assertFalse($result);
- // Ensure that value is unchanged
- $result = $testInstance->getPositionXL();
- $this->assertEquals(PHPExcel_Chart_Legend::xlLegendPositionRight,$result);
- }
-
- public function testGetPositionXL()
- {
- $PositionValue = PHPExcel_Chart_Legend::xlLegendPositionCorner;
-
- $testInstance = new PHPExcel_Chart_Legend;
- $setValue = $testInstance->setPositionXL($PositionValue);
-
- $result = $testInstance->getPositionXL();
- $this->assertEquals($PositionValue,$result);
- }
-
- public function testSetOverlay()
- {
- $overlayValues = array(
- TRUE,
- FALSE,
- );
-
- $testInstance = new PHPExcel_Chart_Legend;
-
- foreach($overlayValues as $overlayValue) {
- $result = $testInstance->setOverlay($overlayValue);
- $this->assertTrue($result);
- }
- }
-
- public function testSetInvalidOverlayReturnsFalse()
- {
- $testInstance = new PHPExcel_Chart_Legend;
-
- $result = $testInstance->setOverlay('INVALID');
- $this->assertFalse($result);
-
- $result = $testInstance->getOverlay();
- $this->assertFalse($result);
- }
-
- public function testGetOverlay()
- {
- $OverlayValue = TRUE;
-
- $testInstance = new PHPExcel_Chart_Legend;
- $setValue = $testInstance->setOverlay($OverlayValue);
-
- $result = $testInstance->getOverlay();
- $this->assertEquals($OverlayValue,$result);
- }
+ }
+ public function testSetPosition()
+ {
+ $positionValues = array(
+ PHPExcel_Chart_Legend::POSITION_RIGHT,
+ PHPExcel_Chart_Legend::POSITION_LEFT,
+ PHPExcel_Chart_Legend::POSITION_TOP,
+ PHPExcel_Chart_Legend::POSITION_BOTTOM,
+ PHPExcel_Chart_Legend::POSITION_TOPRIGHT,
+ );
+
+ $testInstance = new PHPExcel_Chart_Legend;
+
+ foreach ($positionValues as $positionValue) {
+ $result = $testInstance->setPosition($positionValue);
+ $this->assertTrue($result);
+ }
+ }
+
+ public function testSetInvalidPositionReturnsFalse()
+ {
+ $testInstance = new PHPExcel_Chart_Legend;
+
+ $result = $testInstance->setPosition('BottomLeft');
+ $this->assertFalse($result);
+ // Ensure that value is unchanged
+ $result = $testInstance->getPosition();
+ $this->assertEquals(PHPExcel_Chart_Legend::POSITION_RIGHT, $result);
+ }
+
+ public function testGetPosition()
+ {
+ $PositionValue = PHPExcel_Chart_Legend::POSITION_BOTTOM;
+
+ $testInstance = new PHPExcel_Chart_Legend;
+ $setValue = $testInstance->setPosition($PositionValue);
+
+ $result = $testInstance->getPosition();
+ $this->assertEquals($PositionValue, $result);
+ }
+
+ public function testSetPositionXL()
+ {
+ $positionValues = array(
+ PHPExcel_Chart_Legend::xlLegendPositionBottom,
+ PHPExcel_Chart_Legend::xlLegendPositionCorner,
+ PHPExcel_Chart_Legend::xlLegendPositionCustom,
+ PHPExcel_Chart_Legend::xlLegendPositionLeft,
+ PHPExcel_Chart_Legend::xlLegendPositionRight,
+ PHPExcel_Chart_Legend::xlLegendPositionTop,
+ );
+
+ $testInstance = new PHPExcel_Chart_Legend;
+
+ foreach ($positionValues as $positionValue) {
+ $result = $testInstance->setPositionXL($positionValue);
+ $this->assertTrue($result);
+ }
+ }
+
+ public function testSetInvalidXLPositionReturnsFalse()
+ {
+ $testInstance = new PHPExcel_Chart_Legend;
+
+ $result = $testInstance->setPositionXL(999);
+ $this->assertFalse($result);
+ // Ensure that value is unchanged
+ $result = $testInstance->getPositionXL();
+ $this->assertEquals(PHPExcel_Chart_Legend::xlLegendPositionRight, $result);
+ }
+
+ public function testGetPositionXL()
+ {
+ $PositionValue = PHPExcel_Chart_Legend::xlLegendPositionCorner;
+
+ $testInstance = new PHPExcel_Chart_Legend;
+ $setValue = $testInstance->setPositionXL($PositionValue);
+
+ $result = $testInstance->getPositionXL();
+ $this->assertEquals($PositionValue, $result);
+ }
+
+ public function testSetOverlay()
+ {
+ $overlayValues = array(
+ true,
+ false,
+ );
+
+ $testInstance = new PHPExcel_Chart_Legend;
+
+ foreach ($overlayValues as $overlayValue) {
+ $result = $testInstance->setOverlay($overlayValue);
+ $this->assertTrue($result);
+ }
+ }
+
+ public function testSetInvalidOverlayReturnsFalse()
+ {
+ $testInstance = new PHPExcel_Chart_Legend;
+
+ $result = $testInstance->setOverlay('INVALID');
+ $this->assertFalse($result);
+
+ $result = $testInstance->getOverlay();
+ $this->assertFalse($result);
+ }
+
+ public function testGetOverlay()
+ {
+ $OverlayValue = true;
+
+ $testInstance = new PHPExcel_Chart_Legend;
+ $setValue = $testInstance->setOverlay($OverlayValue);
+
+ $result = $testInstance->getOverlay();
+ $this->assertEquals($OverlayValue, $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Reader/XEEValidatorTest.php b/unitTests/Classes/PHPExcel/Reader/XEEValidatorTest.php
new file mode 100644
index 000000000..c2c411fe5
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Reader/XEEValidatorTest.php
@@ -0,0 +1,54 @@
+getMockForAbstractClass('PHPExcel_Reader_Abstract');
+ $expectedResult = 'FAILURE: Should throw an Exception rather than return a value';
+ $result = $reader->securityScanFile($filename);
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function providerInvalidXML()
+ {
+ $tests = array();
+ foreach (glob('rawTestData/Reader/XEETestInvalid*.xml') as $file) {
+ $tests[] = [realpath($file), true];
+ }
+ return $tests;
+ }
+
+ /**
+ * @dataProvider providerValidXML
+ */
+ public function testValidXML($filename, $expectedResult)
+ {
+ $reader = $this->getMockForAbstractClass('PHPExcel_Reader_Abstract');
+ $result = $reader->securityScanFile($filename);
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function providerValidXML()
+ {
+ $tests = array();
+ foreach (glob('rawTestData/Reader/XEETestValid*.xml') as $file) {
+ $tests[] = [realpath($file), file_get_contents($file)];
+ }
+ return $tests;
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/ReferenceHelperTest.php b/unitTests/Classes/PHPExcel/ReferenceHelperTest.php
new file mode 100644
index 000000000..cf40f73aa
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/ReferenceHelperTest.php
@@ -0,0 +1,57 @@
+ $value) {
+ $this->assertEquals($columnExpectedResult[$key], $value);
+ }
+ }
+
+ public function testColumnReverseSort()
+ {
+ $columnBase = $columnExpectedResult = array(
+ 'A','B','Z',
+ 'AA','AB','AZ',
+ 'BA','BB','BZ',
+ 'ZA','ZB','ZZ',
+ 'AAA','AAB','AAZ',
+ 'ABA','ABB','ABZ',
+ 'AZA','AZB','AZZ',
+ 'BAA','BAB','BAZ',
+ 'BBA','BBB','BBZ',
+ 'BZA','BZB','BZZ'
+ );
+ shuffle($columnBase);
+ $columnExpectedResult = array_reverse($columnExpectedResult);
+ usort($columnBase, array('PHPExcel_ReferenceHelper','columnReverseSort'));
+ foreach ($columnBase as $key => $value) {
+ $this->assertEquals($columnExpectedResult[$key], $value);
+ }
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/SettingsTest.php b/unitTests/Classes/PHPExcel/SettingsTest.php
new file mode 100644
index 000000000..0618c7822
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/SettingsTest.php
@@ -0,0 +1,32 @@
+assertTrue((bool) ((LIBXML_DTDLOAD | LIBXML_DTDATTR) & $result));
+ }
+
+ /**
+ */
+ public function testSetXMLSettings()
+ {
+ call_user_func_array(array('PHPExcel_Settings','setLibXmlLoaderOptions'), [LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID]);
+ $result = call_user_func(array('PHPExcel_Settings','getLibXmlLoaderOptions'));
+ $this->assertTrue((bool) ((LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID) & $result));
+ }
+
+}
diff --git a/unitTests/Classes/PHPExcel/Shared/CodePageTest.php b/unitTests/Classes/PHPExcel/Shared/CodePageTest.php
index ae4aeecc5..d434694e0 100644
--- a/unitTests/Classes/PHPExcel/Shared/CodePageTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/CodePageTest.php
@@ -12,46 +12,45 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
/**
* @dataProvider providerCodePage
*/
- public function testCodePageNumberToName()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_CodePage','NumberToName'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCodePageNumberToName()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_CodePage','NumberToName'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCodePage()
{
- return new testDataFileIterator('rawTestData/Shared/CodePage.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/CodePage.data');
+ }
public function testNumberToNameWithInvalidCodePage()
- {
- $invalidCodePage = 12345;
- try {
- $result = call_user_func(array('PHPExcel_Shared_CodePage','NumberToName'),$invalidCodePage);
- } catch (Exception $e) {
- $this->assertEquals($e->getMessage(), 'Unknown codepage: 12345');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
+ {
+ $invalidCodePage = 12345;
+ try {
+ $result = call_user_func(array('PHPExcel_Shared_CodePage','NumberToName'), $invalidCodePage);
+ } catch (Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Unknown codepage: 12345');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
public function testNumberToNameWithUnsupportedCodePage()
- {
- $unsupportedCodePage = 720;
- try {
- $result = call_user_func(array('PHPExcel_Shared_CodePage','NumberToName'),$unsupportedCodePage);
- } catch (Exception $e) {
- $this->assertEquals($e->getMessage(), 'Code page 720 not supported.');
- return;
- }
- $this->fail('An expected exception has not been raised.');
- }
-
+ {
+ $unsupportedCodePage = 720;
+ try {
+ $result = call_user_func(array('PHPExcel_Shared_CodePage','NumberToName'), $unsupportedCodePage);
+ } catch (Exception $e) {
+ $this->assertEquals($e->getMessage(), 'Code page 720 not supported.');
+ return;
+ }
+ $this->fail('An expected exception has not been raised.');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Shared/DateTest.php b/unitTests/Classes/PHPExcel/Shared/DateTest.php
index 80b77d3c6..f0bf91983 100644
--- a/unitTests/Classes/PHPExcel/Shared/DateTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/DateTest.php
@@ -12,177 +12,176 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
- public function testSetExcelCalendar()
- {
- $calendarValues = array(
- PHPExcel_Shared_Date::CALENDAR_MAC_1904,
- PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900,
- );
-
- foreach($calendarValues as $calendarValue) {
- $result = call_user_func(array('PHPExcel_Shared_Date','setExcelCalendar'),$calendarValue);
- $this->assertTrue($result);
- }
- }
+ public function testSetExcelCalendar()
+ {
+ $calendarValues = array(
+ PHPExcel_Shared_Date::CALENDAR_MAC_1904,
+ PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900,
+ );
+
+ foreach ($calendarValues as $calendarValue) {
+ $result = call_user_func(array('PHPExcel_Shared_Date','setExcelCalendar'), $calendarValue);
+ $this->assertTrue($result);
+ }
+ }
public function testSetExcelCalendarWithInvalidValue()
- {
- $unsupportedCalendar = '2012';
- $result = call_user_func(array('PHPExcel_Shared_Date','setExcelCalendar'),$unsupportedCalendar);
- $this->assertFalse($result);
- }
+ {
+ $unsupportedCalendar = '2012';
+ $result = call_user_func(array('PHPExcel_Shared_Date','setExcelCalendar'), $unsupportedCalendar);
+ $this->assertFalse($result);
+ }
/**
* @dataProvider providerDateTimeExcelToPHP1900
*/
- public function testDateTimeExcelToPHP1900()
- {
- $result = call_user_func(
- array('PHPExcel_Shared_Date','setExcelCalendar'),
- PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
- );
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- if ($args[0] < 1) {
- $expectedResult += gmmktime(0,0,0);
- }
- $result = call_user_func_array(array('PHPExcel_Shared_Date','ExcelToPHP'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testDateTimeExcelToPHP1900()
+ {
+ $result = call_user_func(
+ array('PHPExcel_Shared_Date','setExcelCalendar'),
+ PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
+ );
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ if ($args[0] < 1) {
+ $expectedResult += gmmktime(0, 0, 0);
+ }
+ $result = call_user_func_array(array('PHPExcel_Shared_Date', 'ExcelToPHP'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerDateTimeExcelToPHP1900()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimeExcelToPHP1900.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/DateTimeExcelToPHP1900.data');
+ }
/**
* @dataProvider providerDateTimePHPToExcel1900
*/
- public function testDateTimePHPToExcel1900()
- {
- $result = call_user_func(
- array('PHPExcel_Shared_Date','setExcelCalendar'),
- PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
- );
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Date','PHPToExcel'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-5);
- }
+ public function testDateTimePHPToExcel1900()
+ {
+ $result = call_user_func(
+ array('PHPExcel_Shared_Date','setExcelCalendar'),
+ PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
+ );
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Date','PHPToExcel'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-5);
+ }
public function providerDateTimePHPToExcel1900()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimePHPToExcel1900.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/DateTimePHPToExcel1900.data');
+ }
/**
* @dataProvider providerDateTimeFormattedPHPToExcel1900
*/
- public function testDateTimeFormattedPHPToExcel1900()
- {
- $result = call_user_func(
- array('PHPExcel_Shared_Date','setExcelCalendar'),
- PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
- );
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Date','FormattedPHPToExcel'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-5);
- }
+ public function testDateTimeFormattedPHPToExcel1900()
+ {
+ $result = call_user_func(
+ array('PHPExcel_Shared_Date','setExcelCalendar'),
+ PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
+ );
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Date','FormattedPHPToExcel'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-5);
+ }
public function providerDateTimeFormattedPHPToExcel1900()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimeFormattedPHPToExcel1900.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/DateTimeFormattedPHPToExcel1900.data');
+ }
/**
* @dataProvider providerDateTimeExcelToPHP1904
*/
- public function testDateTimeExcelToPHP1904()
- {
- $result = call_user_func(
- array('PHPExcel_Shared_Date','setExcelCalendar'),
- PHPExcel_Shared_Date::CALENDAR_MAC_1904
- );
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- if ($args[0] < 1) {
- $expectedResult += gmmktime(0,0,0);
- }
- $result = call_user_func_array(array('PHPExcel_Shared_Date','ExcelToPHP'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testDateTimeExcelToPHP1904()
+ {
+ $result = call_user_func(
+ array('PHPExcel_Shared_Date','setExcelCalendar'),
+ PHPExcel_Shared_Date::CALENDAR_MAC_1904
+ );
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ if ($args[0] < 1) {
+ $expectedResult += gmmktime(0, 0, 0);
+ }
+ $result = call_user_func_array(array('PHPExcel_Shared_Date','ExcelToPHP'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerDateTimeExcelToPHP1904()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimeExcelToPHP1904.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/DateTimeExcelToPHP1904.data');
+ }
/**
* @dataProvider providerDateTimePHPToExcel1904
*/
- public function testDateTimePHPToExcel1904()
- {
- $result = call_user_func(
- array('PHPExcel_Shared_Date','setExcelCalendar'),
- PHPExcel_Shared_Date::CALENDAR_MAC_1904
- );
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Date','PHPToExcel'),$args);
- $this->assertEquals($expectedResult, $result, NULL, 1E-5);
- }
+ public function testDateTimePHPToExcel1904()
+ {
+ $result = call_user_func(
+ array('PHPExcel_Shared_Date','setExcelCalendar'),
+ PHPExcel_Shared_Date::CALENDAR_MAC_1904
+ );
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Date','PHPToExcel'), $args);
+ $this->assertEquals($expectedResult, $result, null, 1E-5);
+ }
public function providerDateTimePHPToExcel1904()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimePHPToExcel1904.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/DateTimePHPToExcel1904.data');
+ }
/**
* @dataProvider providerIsDateTimeFormatCode
*/
- public function testIsDateTimeFormatCode()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Date','isDateTimeFormatCode'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testIsDateTimeFormatCode()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Date','isDateTimeFormatCode'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerIsDateTimeFormatCode()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimeFormatCodes.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/DateTimeFormatCodes.data');
+ }
/**
* @dataProvider providerDateTimeExcelToPHP1900Timezone
*/
- public function testDateTimeExcelToPHP1900Timezone()
- {
- $result = call_user_func(
- array('PHPExcel_Shared_Date','setExcelCalendar'),
- PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
- );
-
- $args = func_get_args();
- $expectedResult = array_pop($args);
- if ($args[0] < 1) {
- $expectedResult += gmmktime(0,0,0);
- }
- $result = call_user_func_array(array('PHPExcel_Shared_Date','ExcelToPHP'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testDateTimeExcelToPHP1900Timezone()
+ {
+ $result = call_user_func(
+ array('PHPExcel_Shared_Date','setExcelCalendar'),
+ PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900
+ );
+
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ if ($args[0] < 1) {
+ $expectedResult += gmmktime(0, 0, 0);
+ }
+ $result = call_user_func_array(array('PHPExcel_Shared_Date','ExcelToPHP'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerDateTimeExcelToPHP1900Timezone()
{
- return new testDataFileIterator('rawTestData/Shared/DateTimeExcelToPHP1900Timezone.data');
- }
-
+ return new testDataFileIterator('rawTestData/Shared/DateTimeExcelToPHP1900Timezone.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Shared/FileTest.php b/unitTests/Classes/PHPExcel/Shared/FileTest.php
index 9deb401d9..6f6696c51 100644
--- a/unitTests/Classes/PHPExcel/Shared/FileTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/FileTest.php
@@ -12,28 +12,28 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
-
- public function testGetUseUploadTempDirectory()
- {
- $expectedResult = FALSE;
-
- $result = call_user_func(array('PHPExcel_Shared_File','getUseUploadTempDirectory'));
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetUseUploadTempDirectory()
- {
- $useUploadTempDirectoryValues = array(
- TRUE,
- FALSE,
- );
-
- foreach($useUploadTempDirectoryValues as $useUploadTempDirectoryValue) {
- call_user_func(array('PHPExcel_Shared_File','setUseUploadTempDirectory'),$useUploadTempDirectoryValue);
-
- $result = call_user_func(array('PHPExcel_Shared_File','getUseUploadTempDirectory'));
- $this->assertEquals($useUploadTempDirectoryValue, $result);
- }
- }
+ }
+
+ public function testGetUseUploadTempDirectory()
+ {
+ $expectedResult = false;
+
+ $result = call_user_func(array('PHPExcel_Shared_File','getUseUploadTempDirectory'));
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testSetUseUploadTempDirectory()
+ {
+ $useUploadTempDirectoryValues = array(
+ true,
+ false,
+ );
+
+ foreach ($useUploadTempDirectoryValues as $useUploadTempDirectoryValue) {
+ call_user_func(array('PHPExcel_Shared_File','setUseUploadTempDirectory'), $useUploadTempDirectoryValue);
+
+ $result = call_user_func(array('PHPExcel_Shared_File','getUseUploadTempDirectory'));
+ $this->assertEquals($useUploadTempDirectoryValue, $result);
+ }
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Shared/FontTest.php b/unitTests/Classes/PHPExcel/Shared/FontTest.php
index 6ce5a0261..eecd69de9 100644
--- a/unitTests/Classes/PHPExcel/Shared/FontTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/FontTest.php
@@ -12,83 +12,82 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
- public function testGetAutoSizeMethod()
- {
- $expectedResult = PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX;
-
- $result = call_user_func(array('PHPExcel_Shared_Font','getAutoSizeMethod'));
- $this->assertEquals($expectedResult, $result);
- }
+ public function testGetAutoSizeMethod()
+ {
+ $expectedResult = PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX;
- public function testSetAutoSizeMethod()
- {
- $autosizeMethodValues = array(
- PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT,
- PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX,
- );
+ $result = call_user_func(array('PHPExcel_Shared_Font','getAutoSizeMethod'));
+ $this->assertEquals($expectedResult, $result);
+ }
- foreach($autosizeMethodValues as $autosizeMethodValue) {
- $result = call_user_func(array('PHPExcel_Shared_Font','setAutoSizeMethod'),$autosizeMethodValue);
- $this->assertTrue($result);
- }
- }
+ public function testSetAutoSizeMethod()
+ {
+ $autosizeMethodValues = array(
+ PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT,
+ PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX,
+ );
+
+ foreach ($autosizeMethodValues as $autosizeMethodValue) {
+ $result = call_user_func(array('PHPExcel_Shared_Font','setAutoSizeMethod'), $autosizeMethodValue);
+ $this->assertTrue($result);
+ }
+ }
public function testSetAutoSizeMethodWithInvalidValue()
- {
- $unsupportedAutosizeMethod = 'guess';
+ {
+ $unsupportedAutosizeMethod = 'guess';
- $result = call_user_func(array('PHPExcel_Shared_Font','setAutoSizeMethod'),$unsupportedAutosizeMethod);
- $this->assertFalse($result);
- }
+ $result = call_user_func(array('PHPExcel_Shared_Font','setAutoSizeMethod'), $unsupportedAutosizeMethod);
+ $this->assertFalse($result);
+ }
/**
* @dataProvider providerFontSizeToPixels
*/
- public function testFontSizeToPixels()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Font','fontSizeToPixels'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testFontSizeToPixels()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Font','fontSizeToPixels'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerFontSizeToPixels()
{
- return new testDataFileIterator('rawTestData/Shared/FontSizeToPixels.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/FontSizeToPixels.data');
+ }
/**
* @dataProvider providerInchSizeToPixels
*/
- public function testInchSizeToPixels()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Font','inchSizeToPixels'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testInchSizeToPixels()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Font','inchSizeToPixels'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerInchSizeToPixels()
{
- return new testDataFileIterator('rawTestData/Shared/InchSizeToPixels.data');
- }
+ return new testDataFileIterator('rawTestData/Shared/InchSizeToPixels.data');
+ }
/**
* @dataProvider providerCentimeterSizeToPixels
*/
- public function testCentimeterSizeToPixels()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_Font','centimeterSizeToPixels'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testCentimeterSizeToPixels()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_Font','centimeterSizeToPixels'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerCentimeterSizeToPixels()
{
- return new testDataFileIterator('rawTestData/Shared/CentimeterSizeToPixels.data');
- }
-
+ return new testDataFileIterator('rawTestData/Shared/CentimeterSizeToPixels.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Shared/PasswordHasherTest.php b/unitTests/Classes/PHPExcel/Shared/PasswordHasherTest.php
index 24a26178a..620acb983 100644
--- a/unitTests/Classes/PHPExcel/Shared/PasswordHasherTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/PasswordHasherTest.php
@@ -12,22 +12,21 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
/**
* @dataProvider providerHashPassword
*/
- public function testHashPassword()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Shared_PasswordHasher','hashPassword'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testHashPassword()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Shared_PasswordHasher','hashPassword'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerHashPassword()
{
- return new testDataFileIterator('rawTestData/Shared/PasswordHashes.data');
- }
-
+ return new testDataFileIterator('rawTestData/Shared/PasswordHashes.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Shared/StringTest.php b/unitTests/Classes/PHPExcel/Shared/StringTest.php
index 9a34729d6..9955d8165 100644
--- a/unitTests/Classes/PHPExcel/Shared/StringTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/StringTest.php
@@ -12,72 +12,71 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
-
- public function testGetIsMbStringEnabled()
- {
- $result = call_user_func(array('PHPExcel_Shared_String','getIsMbstringEnabled'));
- $this->assertTrue($result);
- }
-
- public function testGetIsIconvEnabled()
- {
- $result = call_user_func(array('PHPExcel_Shared_String','getIsIconvEnabled'));
- $this->assertTrue($result);
- }
-
- public function testGetDecimalSeparator()
- {
- $localeconv = localeconv();
-
- $expectedResult = (!empty($localeconv['decimal_point'])) ? $localeconv['decimal_point'] : ',';
- $result = call_user_func(array('PHPExcel_Shared_String','getDecimalSeparator'));
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetDecimalSeparator()
- {
- $expectedResult = ',';
- $result = call_user_func(array('PHPExcel_Shared_String','setDecimalSeparator'),$expectedResult);
-
- $result = call_user_func(array('PHPExcel_Shared_String','getDecimalSeparator'));
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testGetThousandsSeparator()
- {
- $localeconv = localeconv();
-
- $expectedResult = (!empty($localeconv['thousands_sep'])) ? $localeconv['thousands_sep'] : ',';
- $result = call_user_func(array('PHPExcel_Shared_String','getThousandsSeparator'));
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetThousandsSeparator()
- {
- $expectedResult = ' ';
- $result = call_user_func(array('PHPExcel_Shared_String','setThousandsSeparator'),$expectedResult);
-
- $result = call_user_func(array('PHPExcel_Shared_String','getThousandsSeparator'));
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testGetCurrencyCode()
- {
- $localeconv = localeconv();
-
- $expectedResult = (!empty($localeconv['currency_symbol'])) ? $localeconv['currency_symbol'] : '$';
- $result = call_user_func(array('PHPExcel_Shared_String','getCurrencyCode'));
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetCurrencyCode()
- {
- $expectedResult = '£';
- $result = call_user_func(array('PHPExcel_Shared_String','setCurrencyCode'),$expectedResult);
-
- $result = call_user_func(array('PHPExcel_Shared_String','getCurrencyCode'));
- $this->assertEquals($expectedResult, $result);
- }
+ }
+ public function testGetIsMbStringEnabled()
+ {
+ $result = call_user_func(array('PHPExcel_Shared_String','getIsMbstringEnabled'));
+ $this->assertTrue($result);
+ }
+
+ public function testGetIsIconvEnabled()
+ {
+ $result = call_user_func(array('PHPExcel_Shared_String','getIsIconvEnabled'));
+ $this->assertTrue($result);
+ }
+
+ public function testGetDecimalSeparator()
+ {
+ $localeconv = localeconv();
+
+ $expectedResult = (!empty($localeconv['decimal_point'])) ? $localeconv['decimal_point'] : ',';
+ $result = call_user_func(array('PHPExcel_Shared_String','getDecimalSeparator'));
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testSetDecimalSeparator()
+ {
+ $expectedResult = ',';
+ $result = call_user_func(array('PHPExcel_Shared_String','setDecimalSeparator'), $expectedResult);
+
+ $result = call_user_func(array('PHPExcel_Shared_String','getDecimalSeparator'));
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testGetThousandsSeparator()
+ {
+ $localeconv = localeconv();
+
+ $expectedResult = (!empty($localeconv['thousands_sep'])) ? $localeconv['thousands_sep'] : ',';
+ $result = call_user_func(array('PHPExcel_Shared_String','getThousandsSeparator'));
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testSetThousandsSeparator()
+ {
+ $expectedResult = ' ';
+ $result = call_user_func(array('PHPExcel_Shared_String','setThousandsSeparator'), $expectedResult);
+
+ $result = call_user_func(array('PHPExcel_Shared_String','getThousandsSeparator'));
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testGetCurrencyCode()
+ {
+ $localeconv = localeconv();
+
+ $expectedResult = (!empty($localeconv['currency_symbol'])) ? $localeconv['currency_symbol'] : '$';
+ $result = call_user_func(array('PHPExcel_Shared_String','getCurrencyCode'));
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testSetCurrencyCode()
+ {
+ $expectedResult = '£';
+ $result = call_user_func(array('PHPExcel_Shared_String','setCurrencyCode'), $expectedResult);
+
+ $result = call_user_func(array('PHPExcel_Shared_String','getCurrencyCode'));
+ $this->assertEquals($expectedResult, $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Shared/TimeZoneTest.php b/unitTests/Classes/PHPExcel/Shared/TimeZoneTest.php
index 0e44ceb62..254842673 100644
--- a/unitTests/Classes/PHPExcel/Shared/TimeZoneTest.php
+++ b/unitTests/Classes/PHPExcel/Shared/TimeZoneTest.php
@@ -10,30 +10,29 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
- public function testSetTimezone()
- {
- $timezoneValues = array(
- 'Europe/Prague',
- 'Asia/Tokyo',
- 'America/Indiana/Indianapolis',
- 'Pacific/Honolulu',
- 'Atlantic/St_Helena',
- );
-
- foreach($timezoneValues as $timezoneValue) {
- $result = call_user_func(array('PHPExcel_Shared_TimeZone','setTimezone'),$timezoneValue);
- $this->assertTrue($result);
- }
+ public function testSetTimezone()
+ {
+ $timezoneValues = array(
+ 'Europe/Prague',
+ 'Asia/Tokyo',
+ 'America/Indiana/Indianapolis',
+ 'Pacific/Honolulu',
+ 'Atlantic/St_Helena',
+ );
+
+ foreach ($timezoneValues as $timezoneValue) {
+ $result = call_user_func(array('PHPExcel_Shared_TimeZone','setTimezone'), $timezoneValue);
+ $this->assertTrue($result);
+ }
- }
+ }
public function testSetTimezoneWithInvalidValue()
- {
- $unsupportedTimezone = 'Etc/GMT+10';
- $result = call_user_func(array('PHPExcel_Shared_TimeZone','setTimezone'),$unsupportedTimezone);
- $this->assertFalse($result);
- }
-
+ {
+ $unsupportedTimezone = 'Etc/GMT+10';
+ $result = call_user_func(array('PHPExcel_Shared_TimeZone','setTimezone'), $unsupportedTimezone);
+ $this->assertFalse($result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Style/ColorTest.php b/unitTests/Classes/PHPExcel/Style/ColorTest.php
index f157b1a34..2d9188ef3 100644
--- a/unitTests/Classes/PHPExcel/Style/ColorTest.php
+++ b/unitTests/Classes/PHPExcel/Style/ColorTest.php
@@ -12,70 +12,69 @@ public function setUp()
define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
}
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ }
/**
* @dataProvider providerColorGetRed
*/
- public function testGetRed()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Style_Color','getRed'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testGetRed()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Style_Color','getRed'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerColorGetRed()
{
- return new testDataFileIterator('rawTestData/Style/ColorGetRed.data');
- }
+ return new testDataFileIterator('rawTestData/Style/ColorGetRed.data');
+ }
/**
* @dataProvider providerColorGetGreen
*/
- public function testGetGreen()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Style_Color','getGreen'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testGetGreen()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Style_Color','getGreen'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerColorGetGreen()
{
- return new testDataFileIterator('rawTestData/Style/ColorGetGreen.data');
- }
+ return new testDataFileIterator('rawTestData/Style/ColorGetGreen.data');
+ }
/**
* @dataProvider providerColorGetBlue
*/
- public function testGetBlue()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Style_Color','getBlue'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testGetBlue()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Style_Color','getBlue'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerColorGetBlue()
{
- return new testDataFileIterator('rawTestData/Style/ColorGetBlue.data');
- }
+ return new testDataFileIterator('rawTestData/Style/ColorGetBlue.data');
+ }
/**
* @dataProvider providerColorChangeBrightness
*/
- public function testChangeBrightness()
- {
- $args = func_get_args();
- $expectedResult = array_pop($args);
- $result = call_user_func_array(array('PHPExcel_Style_Color','changeBrightness'),$args);
- $this->assertEquals($expectedResult, $result);
- }
+ public function testChangeBrightness()
+ {
+ $args = func_get_args();
+ $expectedResult = array_pop($args);
+ $result = call_user_func_array(array('PHPExcel_Style_Color','changeBrightness'), $args);
+ $this->assertEquals($expectedResult, $result);
+ }
public function providerColorChangeBrightness()
{
- return new testDataFileIterator('rawTestData/Style/ColorChangeBrightness.data');
- }
-
+ return new testDataFileIterator('rawTestData/Style/ColorChangeBrightness.data');
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Style/NumberFormatDateTest.php b/unitTests/Classes/PHPExcel/Style/NumberFormatDateTest.php
new file mode 100644
index 000000000..8ba828f73
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Style/NumberFormatDateTest.php
@@ -0,0 +1,35 @@
+assertEquals($expectedResult, $result);
+ }
+
+ public function providerNumberFormat()
+ {
+ return new testDataFileIterator('rawTestData/Style/NumberFormatDates.data');
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Style/NumberFormatTest.php b/unitTests/Classes/PHPExcel/Style/NumberFormatTest.php
new file mode 100644
index 000000000..08c2f0240
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Style/NumberFormatTest.php
@@ -0,0 +1,35 @@
+assertEquals($expectedResult, $result);
+ }
+
+ public function providerNumberFormat()
+ {
+ return new testDataFileIterator('rawTestData/Style/NumberFormat.data');
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/Column/RuleTest.php b/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/Column/RuleTest.php
index 65d0a85c6..0c39c683a 100644
--- a/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/Column/RuleTest.php
+++ b/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/Column/RuleTest.php
@@ -3,9 +3,9 @@
class RuleTest extends PHPUnit_Framework_TestCase
{
- private $_testAutoFilterRuleObject;
+ private $_testAutoFilterRuleObject;
- private $_mockAutoFilterColumnObject;
+ private $_mockAutoFilterColumnObject;
public function setUp()
{
@@ -15,95 +15,94 @@ public function setUp()
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
$this->_mockAutoFilterColumnObject = $this->getMockBuilder('PHPExcel_Worksheet_AutoFilter_Column')
- ->disableOriginalConstructor()
- ->getMock();
+ ->disableOriginalConstructor()
+ ->getMock();
$this->_mockAutoFilterColumnObject->expects($this->any())
- ->method('testColumnInRange')
- ->will($this->returnValue(3));
+ ->method('testColumnInRange')
+ ->will($this->returnValue(3));
- $this->_testAutoFilterRuleObject = new PHPExcel_Worksheet_AutoFilter_Column_Rule(
- $this->_mockAutoFilterColumnObject
- );
+ $this->_testAutoFilterRuleObject = new PHPExcel_Worksheet_AutoFilter_Column_Rule(
+ $this->_mockAutoFilterColumnObject
+ );
}
- public function testGetRuleType()
- {
- $result = $this->_testAutoFilterRuleObject->getRuleType();
- $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER, $result);
- }
-
- public function testSetRuleType()
- {
- $expectedResult = PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP;
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterRuleObject->setRuleType($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
-
- $result = $this->_testAutoFilterRuleObject->getRuleType();
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetValue()
- {
- $expectedResult = 100;
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterRuleObject->setValue($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
-
- $result = $this->_testAutoFilterRuleObject->getValue();
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testGetOperator()
- {
- $result = $this->_testAutoFilterRuleObject->getOperator();
- $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL, $result);
- }
-
- public function testSetOperator()
- {
- $expectedResult = PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterRuleObject->setOperator($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
-
- $result = $this->_testAutoFilterRuleObject->getOperator();
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetGrouping()
- {
- $expectedResult = PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH;
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterRuleObject->setGrouping($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
-
- $result = $this->_testAutoFilterRuleObject->getGrouping();
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testGetParent()
- {
- $result = $this->_testAutoFilterRuleObject->getParent();
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
-
- public function testSetParent()
- {
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterRuleObject->setParent($this->_mockAutoFilterColumnObject);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
- }
-
- public function testClone()
- {
- $result = clone $this->_testAutoFilterRuleObject;
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
- }
+ public function testGetRuleType()
+ {
+ $result = $this->_testAutoFilterRuleObject->getRuleType();
+ $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER, $result);
+ }
+
+ public function testSetRuleType()
+ {
+ $expectedResult = PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP;
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterRuleObject->setRuleType($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
+
+ $result = $this->_testAutoFilterRuleObject->getRuleType();
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testSetValue()
+ {
+ $expectedResult = 100;
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterRuleObject->setValue($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
+
+ $result = $this->_testAutoFilterRuleObject->getValue();
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testGetOperator()
+ {
+ $result = $this->_testAutoFilterRuleObject->getOperator();
+ $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL, $result);
+ }
+
+ public function testSetOperator()
+ {
+ $expectedResult = PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterRuleObject->setOperator($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
+
+ $result = $this->_testAutoFilterRuleObject->getOperator();
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testSetGrouping()
+ {
+ $expectedResult = PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH;
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterRuleObject->setGrouping($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
+
+ $result = $this->_testAutoFilterRuleObject->getGrouping();
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testGetParent()
+ {
+ $result = $this->_testAutoFilterRuleObject->getParent();
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
+
+ public function testSetParent()
+ {
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterRuleObject->setParent($this->_mockAutoFilterColumnObject);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
+ }
+
+ public function testClone()
+ {
+ $result = clone $this->_testAutoFilterRuleObject;
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column_Rule', $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/ColumnTest.php b/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/ColumnTest.php
index c8411f5e3..da6eef53c 100644
--- a/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/ColumnTest.php
+++ b/unitTests/Classes/PHPExcel/Worksheet/AutoFilter/ColumnTest.php
@@ -1,13 +1,13 @@
_mockAutoFilterObject = $this->getMockBuilder('PHPExcel_Worksheet_AutoFilter')
- ->disableOriginalConstructor()
- ->getMock();
+ ->disableOriginalConstructor()
+ ->getMock();
$this->_mockAutoFilterObject->expects($this->any())
- ->method('testColumnInRange')
- ->will($this->returnValue(3));
-
- $this->_testAutoFilterColumnObject = new PHPExcel_Worksheet_AutoFilter_Column(
- $this->_testInitialColumn,
- $this->_mockAutoFilterObject
- );
- }
-
- public function testGetColumnIndex()
- {
- $result = $this->_testAutoFilterColumnObject->getColumnIndex();
- $this->assertEquals($this->_testInitialColumn, $result);
- }
-
- public function testSetColumnIndex()
- {
- $expectedResult = 'L';
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterColumnObject->setColumnIndex($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
-
- $result = $this->_testAutoFilterColumnObject->getColumnIndex();
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testGetParent()
- {
- $result = $this->_testAutoFilterColumnObject->getParent();
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
- }
-
- public function testSetParent()
- {
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterColumnObject->setParent($this->_mockAutoFilterObject);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
-
- public function testGetFilterType()
- {
- $result = $this->_testAutoFilterColumnObject->getFilterType();
- $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER, $result);
- }
-
- public function testSetFilterType()
- {
- $result = $this->_testAutoFilterColumnObject->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
-
- $result = $this->_testAutoFilterColumnObject->getFilterType();
- $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, $result);
- }
+ ->method('testColumnInRange')
+ ->will($this->returnValue(3));
+
+ $this->_testAutoFilterColumnObject = new PHPExcel_Worksheet_AutoFilter_Column(
+ $this->_testInitialColumn,
+ $this->_mockAutoFilterObject
+ );
+ }
+
+ public function testGetColumnIndex()
+ {
+ $result = $this->_testAutoFilterColumnObject->getColumnIndex();
+ $this->assertEquals($this->_testInitialColumn, $result);
+ }
+
+ public function testSetColumnIndex()
+ {
+ $expectedResult = 'L';
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterColumnObject->setColumnIndex($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+
+ $result = $this->_testAutoFilterColumnObject->getColumnIndex();
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testGetParent()
+ {
+ $result = $this->_testAutoFilterColumnObject->getParent();
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+ }
+
+ public function testSetParent()
+ {
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterColumnObject->setParent($this->_mockAutoFilterObject);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
+
+ public function testGetFilterType()
+ {
+ $result = $this->_testAutoFilterColumnObject->getFilterType();
+ $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER, $result);
+ }
+
+ public function testSetFilterType()
+ {
+ $result = $this->_testAutoFilterColumnObject->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+
+ $result = $this->_testAutoFilterColumnObject->getFilterType();
+ $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, $result);
+ }
/**
* @expectedException PHPExcel_Exception
*/
- public function testSetInvalidFilterTypeThrowsException()
- {
- $expectedResult = 'Unfiltered';
+ public function testSetInvalidFilterTypeThrowsException()
+ {
+ $expectedResult = 'Unfiltered';
- $result = $this->_testAutoFilterColumnObject->setFilterType($expectedResult);
- }
+ $result = $this->_testAutoFilterColumnObject->setFilterType($expectedResult);
+ }
- public function testGetJoin()
- {
- $result = $this->_testAutoFilterColumnObject->getJoin();
- $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR, $result);
- }
+ public function testGetJoin()
+ {
+ $result = $this->_testAutoFilterColumnObject->getJoin();
+ $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR, $result);
+ }
- public function testSetJoin()
- {
- $result = $this->_testAutoFilterColumnObject->setJoin(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ public function testSetJoin()
+ {
+ $result = $this->_testAutoFilterColumnObject->setJoin(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- $result = $this->_testAutoFilterColumnObject->getJoin();
- $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND, $result);
- }
+ $result = $this->_testAutoFilterColumnObject->getJoin();
+ $this->assertEquals(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND, $result);
+ }
/**
* @expectedException PHPExcel_Exception
*/
- public function testSetInvalidJoinThrowsException()
- {
- $expectedResult = 'Neither';
-
- $result = $this->_testAutoFilterColumnObject->setJoin($expectedResult);
- }
-
- public function testSetAttributes()
- {
- $attributeSet = array( 'val' => 100,
- 'maxVal' => 200
- );
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterColumnObject->setAttributes($attributeSet);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
-
- public function testGetAttributes()
- {
- $attributeSet = array( 'val' => 100,
- 'maxVal' => 200
- );
-
- $this->_testAutoFilterColumnObject->setAttributes($attributeSet);
-
- $result = $this->_testAutoFilterColumnObject->getAttributes();
- $this->assertTrue(is_array($result));
- $this->assertEquals(count($attributeSet), count($result));
- }
-
- public function testSetAttribute()
- {
- $attributeSet = array( 'val' => 100,
- 'maxVal' => 200
- );
-
- foreach($attributeSet as $attributeName => $attributeValue) {
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterColumnObject->setAttribute($attributeName,$attributeValue);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
- }
-
- public function testGetAttribute()
- {
- $attributeSet = array( 'val' => 100,
- 'maxVal' => 200
- );
-
- $this->_testAutoFilterColumnObject->setAttributes($attributeSet);
-
- foreach($attributeSet as $attributeName => $attributeValue) {
- $result = $this->_testAutoFilterColumnObject->getAttribute($attributeName);
- $this->assertEquals($attributeValue, $result);
- }
- $result = $this->_testAutoFilterColumnObject->getAttribute('nonExistentAttribute');
- $this->assertNull($result);
- }
-
- public function testClone()
- {
- $result = clone $this->_testAutoFilterColumnObject;
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
+ public function testSetInvalidJoinThrowsException()
+ {
+ $expectedResult = 'Neither';
+
+ $result = $this->_testAutoFilterColumnObject->setJoin($expectedResult);
+ }
+
+ public function testSetAttributes()
+ {
+ $attributeSet = array( 'val' => 100,
+ 'maxVal' => 200
+ );
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterColumnObject->setAttributes($attributeSet);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
+
+ public function testGetAttributes()
+ {
+ $attributeSet = array( 'val' => 100,
+ 'maxVal' => 200
+ );
+
+ $this->_testAutoFilterColumnObject->setAttributes($attributeSet);
+
+ $result = $this->_testAutoFilterColumnObject->getAttributes();
+ $this->assertTrue(is_array($result));
+ $this->assertEquals(count($attributeSet), count($result));
+ }
+
+ public function testSetAttribute()
+ {
+ $attributeSet = array( 'val' => 100,
+ 'maxVal' => 200
+ );
+
+ foreach ($attributeSet as $attributeName => $attributeValue) {
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterColumnObject->setAttribute($attributeName, $attributeValue);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
+ }
+
+ public function testGetAttribute()
+ {
+ $attributeSet = array( 'val' => 100,
+ 'maxVal' => 200
+ );
+ $this->_testAutoFilterColumnObject->setAttributes($attributeSet);
+
+ foreach ($attributeSet as $attributeName => $attributeValue) {
+ $result = $this->_testAutoFilterColumnObject->getAttribute($attributeName);
+ $this->assertEquals($attributeValue, $result);
+ }
+ $result = $this->_testAutoFilterColumnObject->getAttribute('nonExistentAttribute');
+ $this->assertNull($result);
+ }
+
+ public function testClone()
+ {
+ $result = clone $this->_testAutoFilterColumnObject;
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/AutoFilterTest.php b/unitTests/Classes/PHPExcel/Worksheet/AutoFilterTest.php
index 6a6d5ae8d..519810d3d 100644
--- a/unitTests/Classes/PHPExcel/Worksheet/AutoFilterTest.php
+++ b/unitTests/Classes/PHPExcel/Worksheet/AutoFilterTest.php
@@ -3,9 +3,9 @@
class AutoFilterTest extends PHPUnit_Framework_TestCase
{
- private $_testInitialRange = 'H2:O256';
+ private $_testInitialRange = 'H2:O256';
- private $_testAutoFilterObject;
+ private $_testAutoFilterObject;
public function setUp()
@@ -16,319 +16,324 @@ public function setUp()
require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
$this->_mockWorksheetObject = $this->getMockBuilder('PHPExcel_Worksheet')
- ->disableOriginalConstructor()
- ->getMock();
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->_mockCacheController = $this->getMockBuilder('PHPExcel_CachedObjectStorage_Memory')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->_mockWorksheetObject->expects($this->any())
+ ->method('getCellCacheController')
+ ->will($this->returnValue($this->_mockCacheController));
+
+ $this->_testAutoFilterObject = new PHPExcel_Worksheet_AutoFilter(
+ $this->_testInitialRange,
+ $this->_mockWorksheetObject
+ );
+ }
+
+ public function testToString()
+ {
+ $expectedResult = $this->_testInitialRange;
+
+ // magic __toString should return the active autofilter range
+ $result = $this->_testAutoFilterObject;
+ $this->assertEquals($expectedResult, $result);
+ }
+
+ public function testGetParent()
+ {
+ $result = $this->_testAutoFilterObject->getParent();
+ $this->assertInstanceOf('PHPExcel_Worksheet', $result);
+ }
+
+ public function testSetParent()
+ {
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setParent($this->_mockWorksheetObject);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+ }
+
+ public function testGetRange()
+ {
+ $expectedResult = $this->_testInitialRange;
+
+ // Result should be the active autofilter range
+ $result = $this->_testAutoFilterObject->getRange();
+ $this->assertEquals($expectedResult, $result);
+ }
- $this->_testAutoFilterObject = new PHPExcel_Worksheet_AutoFilter(
- $this->_testInitialRange,
- $this->_mockWorksheetObject
- );
+ public function testSetRange()
+ {
+ $ranges = array('G1:J512' => 'Worksheet1!G1:J512',
+ 'K1:N20' => 'K1:N20'
+ );
+
+ foreach ($ranges as $actualRange => $fullRange) {
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setRange($fullRange);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+
+ // Result should be the new autofilter range
+ $result = $this->_testAutoFilterObject->getRange();
+ $this->assertEquals($actualRange, $result);
+ }
}
- public function testToString()
- {
- $expectedResult = $this->_testInitialRange;
-
- // magic __toString should return the active autofilter range
- $result = $this->_testAutoFilterObject;
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testGetParent()
- {
- $result = $this->_testAutoFilterObject->getParent();
- $this->assertInstanceOf('PHPExcel_Worksheet', $result);
- }
-
- public function testSetParent()
- {
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setParent($this->_mockWorksheetObject);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
- }
-
- public function testGetRange()
- {
- $expectedResult = $this->_testInitialRange;
-
- // Result should be the active autofilter range
- $result = $this->_testAutoFilterObject->getRange();
- $this->assertEquals($expectedResult, $result);
- }
-
- public function testSetRange()
- {
- $ranges = array('G1:J512' => 'Worksheet1!G1:J512',
- 'K1:N20' => 'K1:N20'
- );
-
- foreach($ranges as $actualRange => $fullRange) {
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setRange($fullRange);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
-
- // Result should be the new autofilter range
- $result = $this->_testAutoFilterObject->getRange();
- $this->assertEquals($actualRange, $result);
- }
- }
-
- public function testClearRange()
- {
- $expectedResult = '';
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setRange();
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
-
- // Result should be a clear range
- $result = $this->_testAutoFilterObject->getRange();
- $this->assertEquals($expectedResult, $result);
- }
+ public function testClearRange()
+ {
+ $expectedResult = '';
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setRange();
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+
+ // Result should be a clear range
+ $result = $this->_testAutoFilterObject->getRange();
+ $this->assertEquals($expectedResult, $result);
+ }
/**
* @expectedException PHPExcel_Exception
*/
- public function testSetRangeInvalidRange()
- {
- $expectedResult = 'A1';
-
- $result = $this->_testAutoFilterObject->setRange($expectedResult);
- }
-
- public function testGetColumnsEmpty()
- {
- // There should be no columns yet defined
- $result = $this->_testAutoFilterObject->getColumns();
- $this->assertInternalType('array', $result);
- $this->assertEquals(0, count($result));
- }
-
- public function testGetColumnOffset()
- {
- $columnIndexes = array( 'H' => 0,
- 'K' => 3,
- 'M' => 5
- );
-
- // If we request a specific column by its column ID, we should get an
- // integer returned representing the column offset within the range
- foreach($columnIndexes as $columnIndex => $columnOffset) {
- $result = $this->_testAutoFilterObject->getColumnOffset($columnIndex);
- $this->assertEquals($columnOffset, $result);
- }
- }
+ public function testSetRangeInvalidRange()
+ {
+ $expectedResult = 'A1';
+
+ $result = $this->_testAutoFilterObject->setRange($expectedResult);
+ }
+
+ public function testGetColumnsEmpty()
+ {
+ // There should be no columns yet defined
+ $result = $this->_testAutoFilterObject->getColumns();
+ $this->assertInternalType('array', $result);
+ $this->assertEquals(0, count($result));
+ }
+
+ public function testGetColumnOffset()
+ {
+ $columnIndexes = array( 'H' => 0,
+ 'K' => 3,
+ 'M' => 5
+ );
+
+ // If we request a specific column by its column ID, we should get an
+ // integer returned representing the column offset within the range
+ foreach ($columnIndexes as $columnIndex => $columnOffset) {
+ $result = $this->_testAutoFilterObject->getColumnOffset($columnIndex);
+ $this->assertEquals($columnOffset, $result);
+ }
+ }
/**
* @expectedException PHPExcel_Exception
*/
public function testGetInvalidColumnOffset()
- {
- $invalidColumn = 'G';
-
- $result = $this->_testAutoFilterObject->getColumnOffset($invalidColumn);
- }
-
- public function testSetColumnWithString()
- {
- $expectedResult = 'L';
+ {
+ $invalidColumn = 'G';
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setColumn($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+ $result = $this->_testAutoFilterObject->getColumnOffset($invalidColumn);
+ }
- $result = $this->_testAutoFilterObject->getColumns();
- // Result should be an array of PHPExcel_Worksheet_AutoFilter_Column
- // objects for each column we set indexed by the column ID
- $this->assertInternalType('array', $result);
- $this->assertEquals(1, count($result));
- $this->assertArrayHasKey($expectedResult,$result);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result[$expectedResult]);
- }
+ public function testSetColumnWithString()
+ {
+ $expectedResult = 'L';
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setColumn($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+
+ $result = $this->_testAutoFilterObject->getColumns();
+ // Result should be an array of PHPExcel_Worksheet_AutoFilter_Column
+ // objects for each column we set indexed by the column ID
+ $this->assertInternalType('array', $result);
+ $this->assertEquals(1, count($result));
+ $this->assertArrayHasKey($expectedResult, $result);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result[$expectedResult]);
+ }
/**
* @expectedException PHPExcel_Exception
*/
public function testSetInvalidColumnWithString()
- {
- $invalidColumn = 'A';
-
- $result = $this->_testAutoFilterObject->setColumn($invalidColumn);
- }
-
- public function testSetColumnWithColumnObject()
- {
- $expectedResult = 'M';
- $columnObject = new PHPExcel_Worksheet_AutoFilter_Column($expectedResult);
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setColumn($columnObject);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
-
- $result = $this->_testAutoFilterObject->getColumns();
- // Result should be an array of PHPExcel_Worksheet_AutoFilter_Column
- // objects for each column we set indexed by the column ID
- $this->assertInternalType('array', $result);
- $this->assertEquals(1, count($result));
- $this->assertArrayHasKey($expectedResult,$result);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result[$expectedResult]);
- }
+ {
+ $invalidColumn = 'A';
+
+ $result = $this->_testAutoFilterObject->setColumn($invalidColumn);
+ }
+
+ public function testSetColumnWithColumnObject()
+ {
+ $expectedResult = 'M';
+ $columnObject = new PHPExcel_Worksheet_AutoFilter_Column($expectedResult);
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setColumn($columnObject);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+
+ $result = $this->_testAutoFilterObject->getColumns();
+ // Result should be an array of PHPExcel_Worksheet_AutoFilter_Column
+ // objects for each column we set indexed by the column ID
+ $this->assertInternalType('array', $result);
+ $this->assertEquals(1, count($result));
+ $this->assertArrayHasKey($expectedResult, $result);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result[$expectedResult]);
+ }
/**
* @expectedException PHPExcel_Exception
*/
public function testSetInvalidColumnWithObject()
- {
- $invalidColumn = 'E';
- $columnObject = new PHPExcel_Worksheet_AutoFilter_Column($invalidColumn);
+ {
+ $invalidColumn = 'E';
+ $columnObject = new PHPExcel_Worksheet_AutoFilter_Column($invalidColumn);
- $result = $this->_testAutoFilterObject->setColumn($invalidColumn);
- }
+ $result = $this->_testAutoFilterObject->setColumn($invalidColumn);
+ }
/**
* @expectedException PHPExcel_Exception
*/
public function testSetColumnWithInvalidDataType()
- {
- $invalidColumn = 123.456;
- $columnObject = new PHPExcel_Worksheet_AutoFilter_Column($invalidColumn);
-
- $result = $this->_testAutoFilterObject->setColumn($invalidColumn);
- }
-
- public function testGetColumns()
- {
- $columnIndexes = array('L','M');
-
- foreach($columnIndexes as $columnIndex) {
- $this->_testAutoFilterObject->setColumn($columnIndex);
- }
-
- $result = $this->_testAutoFilterObject->getColumns();
- // Result should be an array of PHPExcel_Worksheet_AutoFilter_Column
- // objects for each column we set indexed by the column ID
- $this->assertInternalType('array', $result);
- $this->assertEquals(count($columnIndexes), count($result));
- foreach($columnIndexes as $columnIndex) {
- $this->assertArrayHasKey($columnIndex,$result);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result[$columnIndex]);
- }
- }
-
- public function testGetColumn()
- {
- $columnIndexes = array('L','M');
-
- foreach($columnIndexes as $columnIndex) {
- $this->_testAutoFilterObject->setColumn($columnIndex);
- }
-
- // If we request a specific column by its column ID, we should
- // get a PHPExcel_Worksheet_AutoFilter_Column object returned
- foreach($columnIndexes as $columnIndex) {
- $result = $this->_testAutoFilterObject->getColumn($columnIndex);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
- }
-
- public function testGetColumnByOffset()
- {
- $columnIndexes = array( 0 => 'H',
- 3 => 'K',
- 5 => 'M'
- );
-
- // If we request a specific column by its offset, we should
- // get a PHPExcel_Worksheet_AutoFilter_Column object returned
- foreach($columnIndexes as $columnIndex => $columnID) {
- $result = $this->_testAutoFilterObject->getColumnByOffset($columnIndex);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- $this->assertEquals($result->getColumnIndex(),$columnID);
- }
- }
-
- public function testGetColumnIfNotSet()
- {
- // If we request a specific column by its column ID, we should
- // get a PHPExcel_Worksheet_AutoFilter_Column object returned
- $result = $this->_testAutoFilterObject->getColumn('K');
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
- }
+ {
+ $invalidColumn = 123.456;
+ $columnObject = new PHPExcel_Worksheet_AutoFilter_Column($invalidColumn);
+
+ $result = $this->_testAutoFilterObject->setColumn($invalidColumn);
+ }
+
+ public function testGetColumns()
+ {
+ $columnIndexes = array('L','M');
+
+ foreach ($columnIndexes as $columnIndex) {
+ $this->_testAutoFilterObject->setColumn($columnIndex);
+ }
+
+ $result = $this->_testAutoFilterObject->getColumns();
+ // Result should be an array of PHPExcel_Worksheet_AutoFilter_Column
+ // objects for each column we set indexed by the column ID
+ $this->assertInternalType('array', $result);
+ $this->assertEquals(count($columnIndexes), count($result));
+ foreach ($columnIndexes as $columnIndex) {
+ $this->assertArrayHasKey($columnIndex, $result);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result[$columnIndex]);
+ }
+ }
+
+ public function testGetColumn()
+ {
+ $columnIndexes = array('L','M');
+
+ foreach ($columnIndexes as $columnIndex) {
+ $this->_testAutoFilterObject->setColumn($columnIndex);
+ }
+
+ // If we request a specific column by its column ID, we should
+ // get a PHPExcel_Worksheet_AutoFilter_Column object returned
+ foreach ($columnIndexes as $columnIndex) {
+ $result = $this->_testAutoFilterObject->getColumn($columnIndex);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
+ }
+
+ public function testGetColumnByOffset()
+ {
+ $columnIndexes = array( 0 => 'H',
+ 3 => 'K',
+ 5 => 'M'
+ );
+
+ // If we request a specific column by its offset, we should
+ // get a PHPExcel_Worksheet_AutoFilter_Column object returned
+ foreach ($columnIndexes as $columnIndex => $columnID) {
+ $result = $this->_testAutoFilterObject->getColumnByOffset($columnIndex);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ $this->assertEquals($result->getColumnIndex(), $columnID);
+ }
+ }
+
+ public function testGetColumnIfNotSet()
+ {
+ // If we request a specific column by its column ID, we should
+ // get a PHPExcel_Worksheet_AutoFilter_Column object returned
+ $result = $this->_testAutoFilterObject->getColumn('K');
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter_Column', $result);
+ }
/**
* @expectedException PHPExcel_Exception
*/
- public function testGetColumnWithoutRangeSet()
- {
- // Clear the range
- $result = $this->_testAutoFilterObject->setRange();
-
- $result = $this->_testAutoFilterObject->getColumn('A');
- }
-
- public function testClearRangeWithExistingColumns()
- {
- $expectedResult = '';
-
- $columnIndexes = array('L','M','N');
- foreach($columnIndexes as $columnIndex) {
- $this->_testAutoFilterObject->setColumn($columnIndex);
- }
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setRange();
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
-
- // Range should be cleared
- $result = $this->_testAutoFilterObject->getRange();
- $this->assertEquals($expectedResult, $result);
-
- // Column array should be cleared
- $result = $this->_testAutoFilterObject->getColumns();
- $this->assertInternalType('array', $result);
- $this->assertEquals(0, count($result));
- }
-
- public function testSetRangeWithExistingColumns()
- {
- $expectedResult = 'G1:J512';
-
- // These columns should be retained
- $columnIndexes1 = array('I','J');
- foreach($columnIndexes1 as $columnIndex) {
- $this->_testAutoFilterObject->setColumn($columnIndex);
- }
- // These columns should be discarded
- $columnIndexes2 = array('K','L','M');
- foreach($columnIndexes2 as $columnIndex) {
- $this->_testAutoFilterObject->setColumn($columnIndex);
- }
-
- // Setters return the instance to implement the fluent interface
- $result = $this->_testAutoFilterObject->setRange($expectedResult);
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
-
- // Range should be correctly set
- $result = $this->_testAutoFilterObject->getRange();
- $this->assertEquals($expectedResult, $result);
-
- // Only columns that existed in the original range and that
- // still fall within the new range should be retained
- $result = $this->_testAutoFilterObject->getColumns();
- $this->assertInternalType('array', $result);
- $this->assertEquals(count($columnIndexes1), count($result));
- }
-
- public function testClone()
- {
- $columnIndexes = array('L','M');
-
- foreach($columnIndexes as $columnIndex) {
- $this->_testAutoFilterObject->setColumn($columnIndex);
- }
-
- $result = clone $this->_testAutoFilterObject;
- $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
- }
+ public function testGetColumnWithoutRangeSet()
+ {
+ // Clear the range
+ $result = $this->_testAutoFilterObject->setRange();
+ $result = $this->_testAutoFilterObject->getColumn('A');
+ }
+
+ public function testClearRangeWithExistingColumns()
+ {
+ $expectedResult = '';
+
+ $columnIndexes = array('L','M','N');
+ foreach ($columnIndexes as $columnIndex) {
+ $this->_testAutoFilterObject->setColumn($columnIndex);
+ }
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setRange();
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+
+ // Range should be cleared
+ $result = $this->_testAutoFilterObject->getRange();
+ $this->assertEquals($expectedResult, $result);
+
+ // Column array should be cleared
+ $result = $this->_testAutoFilterObject->getColumns();
+ $this->assertInternalType('array', $result);
+ $this->assertEquals(0, count($result));
+ }
+
+ public function testSetRangeWithExistingColumns()
+ {
+ $expectedResult = 'G1:J512';
+
+ // These columns should be retained
+ $columnIndexes1 = array('I','J');
+ foreach ($columnIndexes1 as $columnIndex) {
+ $this->_testAutoFilterObject->setColumn($columnIndex);
+ }
+ // These columns should be discarded
+ $columnIndexes2 = array('K','L','M');
+ foreach ($columnIndexes2 as $columnIndex) {
+ $this->_testAutoFilterObject->setColumn($columnIndex);
+ }
+
+ // Setters return the instance to implement the fluent interface
+ $result = $this->_testAutoFilterObject->setRange($expectedResult);
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+
+ // Range should be correctly set
+ $result = $this->_testAutoFilterObject->getRange();
+ $this->assertEquals($expectedResult, $result);
+
+ // Only columns that existed in the original range and that
+ // still fall within the new range should be retained
+ $result = $this->_testAutoFilterObject->getColumns();
+ $this->assertInternalType('array', $result);
+ $this->assertEquals(count($columnIndexes1), count($result));
+ }
+
+ public function testClone()
+ {
+ $columnIndexes = array('L','M');
+
+ foreach ($columnIndexes as $columnIndex) {
+ $this->_testAutoFilterObject->setColumn($columnIndex);
+ }
+
+ $result = clone $this->_testAutoFilterObject;
+ $this->assertInstanceOf('PHPExcel_Worksheet_AutoFilter', $result);
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/CellCollectionTest.php b/unitTests/Classes/PHPExcel/Worksheet/CellCollectionTest.php
index c2c130d7a..95dd2cec4 100644
--- a/unitTests/Classes/PHPExcel/Worksheet/CellCollectionTest.php
+++ b/unitTests/Classes/PHPExcel/Worksheet/CellCollectionTest.php
@@ -3,29 +3,27 @@
class CellCollectionTest extends PHPUnit_Framework_TestCase
{
- public function setUp()
- {
- if (!defined('PHPEXCEL_ROOT'))
- {
- define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
- }
- require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
- }
+ public function setUp()
+ {
+ if (!defined('PHPEXCEL_ROOT')) {
+ define('PHPEXCEL_ROOT', APPLICATION_PATH . '/');
+ }
+ require_once(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
+ }
- public function testCacheLastCell()
- {
- $methods = PHPExcel_CachedObjectStorageFactory::getCacheStorageMethods();
- foreach ($methods as $method) {
- PHPExcel_CachedObjectStorageFactory::initialize($method);
- $workbook = new PHPExcel();
- $cells = array('A1', 'A2');
- $worksheet = $workbook->getActiveSheet();
- $worksheet->setCellValue('A1', 1);
- $worksheet->setCellValue('A2', 2);
- $this->assertEquals($cells, $worksheet->getCellCollection(), "Cache method \"$method\".");
- PHPExcel_CachedObjectStorageFactory::finalize();
- }
- }
-
+ public function testCacheLastCell()
+ {
+ $methods = PHPExcel_CachedObjectStorageFactory::getCacheStorageMethods();
+ foreach ($methods as $method) {
+ PHPExcel_CachedObjectStorageFactory::initialize($method);
+ $workbook = new PHPExcel();
+ $cells = array('A1', 'A2');
+ $worksheet = $workbook->getActiveSheet();
+ $worksheet->setCellValue('A1', 1);
+ $worksheet->setCellValue('A2', 2);
+ $this->assertEquals($cells, $worksheet->getCellCollection(), "Cache method \"$method\".");
+ PHPExcel_CachedObjectStorageFactory::finalize();
+ }
+ }
}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/ColumnCellIteratorTest.php b/unitTests/Classes/PHPExcel/Worksheet/ColumnCellIteratorTest.php
new file mode 100644
index 000000000..869d086eb
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Worksheet/ColumnCellIteratorTest.php
@@ -0,0 +1,86 @@
+mockCell = $this->getMockBuilder('PHPExcel_Cell')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet = $this->getMockBuilder('PHPExcel_Worksheet')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet->expects($this->any())
+ ->method('getHighestRow')
+ ->will($this->returnValue(5));
+ $this->mockWorksheet->expects($this->any())
+ ->method('getCellByColumnAndRow')
+ ->will($this->returnValue($this->mockCell));
+ }
+
+
+ public function testIteratorFullRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnCellIterator($this->mockWorksheet, 'A');
+ $ColumnCellIndexResult = 1;
+ $this->assertEquals($ColumnCellIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $ColumnCell) {
+ $this->assertEquals($ColumnCellIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Cell', $ColumnCell);
+ }
+ }
+
+ public function testIteratorStartEndRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnCellIterator($this->mockWorksheet, 'A', 2, 4);
+ $ColumnCellIndexResult = 2;
+ $this->assertEquals($ColumnCellIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $ColumnCell) {
+ $this->assertEquals($ColumnCellIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Cell', $ColumnCell);
+ }
+ }
+
+ public function testIteratorSeekAndPrev()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnCellIterator($this->mockWorksheet, 'A', 2, 4);
+ $columnIndexResult = 4;
+ $iterator->seek(4);
+ $this->assertEquals($columnIndexResult, $iterator->key());
+
+ for ($i = 1; $i < $columnIndexResult-1; $i++) {
+ $iterator->prev();
+ $this->assertEquals($columnIndexResult - $i, $iterator->key());
+ }
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testSeekOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnCellIterator($this->mockWorksheet, 'A', 2, 4);
+ $iterator->seek(1);
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testPrevOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnCellIterator($this->mockWorksheet, 'A', 2, 4);
+ $iterator->prev();
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/ColumnIteratorTest.php b/unitTests/Classes/PHPExcel/Worksheet/ColumnIteratorTest.php
new file mode 100644
index 000000000..20108e850
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Worksheet/ColumnIteratorTest.php
@@ -0,0 +1,96 @@
+mockColumn = $this->getMockBuilder('PHPExcel_Worksheet_Column')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet = $this->getMockBuilder('PHPExcel_Worksheet')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet->expects($this->any())
+ ->method('getHighestColumn')
+ ->will($this->returnValue('E'));
+ $this->mockWorksheet->expects($this->any())
+ ->method('current')
+ ->will($this->returnValue($this->mockColumn));
+ }
+
+
+ public function testIteratorFullRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnIterator($this->mockWorksheet);
+ $columnIndexResult = 'A';
+ $this->assertEquals($columnIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $column) {
+ $this->assertEquals($columnIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Column', $column);
+ }
+ }
+
+ public function testIteratorStartEndRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnIterator($this->mockWorksheet, 'B', 'D');
+ $columnIndexResult = 'B';
+ $this->assertEquals($columnIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $column) {
+ $this->assertEquals($columnIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Column', $column);
+ }
+ }
+
+ public function testIteratorSeekAndPrev()
+ {
+ $ranges = range('A', 'E');
+ $iterator = new PHPExcel_Worksheet_ColumnIterator($this->mockWorksheet, 'B', 'D');
+ $columnIndexResult = 'D';
+ $iterator->seek('D');
+ $this->assertEquals($columnIndexResult, $iterator->key());
+
+ for ($i = 1; $i < array_search($columnIndexResult, $ranges); $i++) {
+ $iterator->prev();
+ $expectedResult = $ranges[array_search($columnIndexResult, $ranges) - $i];
+ $this->assertEquals($expectedResult, $iterator->key());
+ }
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testStartOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnIterator($this->mockWorksheet, 'IA', 'IV');
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testSeekOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnIterator($this->mockWorksheet, 'B', 'D');
+ $iterator->seek('A');
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testPrevOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_ColumnIterator($this->mockWorksheet, 'B', 'D');
+ $iterator->prev();
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/RowCellIteratorTest.php b/unitTests/Classes/PHPExcel/Worksheet/RowCellIteratorTest.php
new file mode 100644
index 000000000..ec60e90bb
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Worksheet/RowCellIteratorTest.php
@@ -0,0 +1,88 @@
+mockCell = $this->getMockBuilder('PHPExcel_Cell')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet = $this->getMockBuilder('PHPExcel_Worksheet')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet->expects($this->any())
+ ->method('getHighestColumn')
+ ->will($this->returnValue('E'));
+ $this->mockWorksheet->expects($this->any())
+ ->method('getCellByColumnAndRow')
+ ->will($this->returnValue($this->mockCell));
+ }
+
+
+ public function testIteratorFullRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowCellIterator($this->mockWorksheet);
+ $RowCellIndexResult = 'A';
+ $this->assertEquals($RowCellIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $RowCell) {
+ $this->assertEquals($RowCellIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Cell', $RowCell);
+ }
+ }
+
+ public function testIteratorStartEndRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowCellIterator($this->mockWorksheet, 2, 'B', 'D');
+ $RowCellIndexResult = 'B';
+ $this->assertEquals($RowCellIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $RowCell) {
+ $this->assertEquals($RowCellIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Cell', $RowCell);
+ }
+ }
+
+ public function testIteratorSeekAndPrev()
+ {
+ $ranges = range('A', 'E');
+ $iterator = new PHPExcel_Worksheet_RowCellIterator($this->mockWorksheet, 2, 'B', 'D');
+ $RowCellIndexResult = 'D';
+ $iterator->seek('D');
+ $this->assertEquals($RowCellIndexResult, $iterator->key());
+
+ for ($i = 1; $i < array_search($RowCellIndexResult, $ranges); $i++) {
+ $iterator->prev();
+ $expectedResult = $ranges[array_search($RowCellIndexResult, $ranges) - $i];
+ $this->assertEquals($expectedResult, $iterator->key());
+ }
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testSeekOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowCellIterator($this->mockWorksheet, 2, 'B', 'D');
+ $iterator->seek(1);
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testPrevOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowCellIterator($this->mockWorksheet, 2, 'B', 'D');
+ $iterator->prev();
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/RowIteratorTest.php b/unitTests/Classes/PHPExcel/Worksheet/RowIteratorTest.php
new file mode 100644
index 000000000..346941c37
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Worksheet/RowIteratorTest.php
@@ -0,0 +1,94 @@
+mockRow = $this->getMockBuilder('PHPExcel_Worksheet_Row')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet = $this->getMockBuilder('PHPExcel_Worksheet')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockWorksheet->expects($this->any())
+ ->method('getHighestRow')
+ ->will($this->returnValue(5));
+ $this->mockWorksheet->expects($this->any())
+ ->method('current')
+ ->will($this->returnValue($this->mockRow));
+ }
+
+
+ public function testIteratorFullRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowIterator($this->mockWorksheet);
+ $rowIndexResult = 1;
+ $this->assertEquals($rowIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $row) {
+ $this->assertEquals($rowIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Row', $row);
+ }
+ }
+
+ public function testIteratorStartEndRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowIterator($this->mockWorksheet, 2, 4);
+ $rowIndexResult = 2;
+ $this->assertEquals($rowIndexResult, $iterator->key());
+
+ foreach ($iterator as $key => $row) {
+ $this->assertEquals($rowIndexResult++, $key);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Row', $row);
+ }
+ }
+
+ public function testIteratorSeekAndPrev()
+ {
+ $iterator = new PHPExcel_Worksheet_RowIterator($this->mockWorksheet, 2, 4);
+ $rowIndexResult = 4;
+ $iterator->seek($rowIndexResult);
+ $this->assertEquals($rowIndexResult, $iterator->key());
+
+ for ($i = 1; $i < $rowIndexResult-1; $i++) {
+ $iterator->prev();
+ $this->assertEquals($rowIndexResult - $i, $iterator->key());
+ }
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testStartOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowIterator($this->mockWorksheet, 256, 512);
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testSeekOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowIterator($this->mockWorksheet, 2, 4);
+ $iterator->seek(1);
+ }
+
+ /**
+ * @expectedException PHPExcel_Exception
+ */
+ public function testPrevOutOfRange()
+ {
+ $iterator = new PHPExcel_Worksheet_RowIterator($this->mockWorksheet, 2, 4);
+ $iterator->prev();
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/WorksheetColumnTest.php b/unitTests/Classes/PHPExcel/Worksheet/WorksheetColumnTest.php
new file mode 100644
index 000000000..9e880fb9f
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Worksheet/WorksheetColumnTest.php
@@ -0,0 +1,46 @@
+mockWorksheet = $this->getMockBuilder('PHPExcel_Worksheet')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->mockWorksheet->expects($this->any())
+ ->method('getHighestRow')
+ ->will($this->returnValue(5));
+ }
+
+
+ public function testInstantiateColumnDefault()
+ {
+ $column = new PHPExcel_Worksheet_Column($this->mockWorksheet);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Column', $column);
+ $columnIndex = $column->getColumnIndex();
+ $this->assertEquals('A', $columnIndex);
+ }
+
+ public function testInstantiateColumnSpecified()
+ {
+ $column = new PHPExcel_Worksheet_Column($this->mockWorksheet, 'E');
+ $this->assertInstanceOf('PHPExcel_Worksheet_Column', $column);
+ $columnIndex = $column->getColumnIndex();
+ $this->assertEquals('E', $columnIndex);
+ }
+
+ public function testGetCellIterator()
+ {
+ $column = new PHPExcel_Worksheet_Column($this->mockWorksheet);
+ $cellIterator = $column->getCellIterator();
+ $this->assertInstanceOf('PHPExcel_Worksheet_ColumnCellIterator', $cellIterator);
+ }
+}
diff --git a/unitTests/Classes/PHPExcel/Worksheet/WorksheetRowTest.php b/unitTests/Classes/PHPExcel/Worksheet/WorksheetRowTest.php
new file mode 100644
index 000000000..059d8b202
--- /dev/null
+++ b/unitTests/Classes/PHPExcel/Worksheet/WorksheetRowTest.php
@@ -0,0 +1,46 @@
+mockWorksheet = $this->getMockBuilder('PHPExcel_Worksheet')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->mockWorksheet->expects($this->any())
+ ->method('getHighestColumn')
+ ->will($this->returnValue('E'));
+ }
+
+
+ public function testInstantiateRowDefault()
+ {
+ $row = new PHPExcel_Worksheet_Row($this->mockWorksheet);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Row', $row);
+ $rowIndex = $row->getRowIndex();
+ $this->assertEquals(1, $rowIndex);
+ }
+
+ public function testInstantiateRowSpecified()
+ {
+ $row = new PHPExcel_Worksheet_Row($this->mockWorksheet, 5);
+ $this->assertInstanceOf('PHPExcel_Worksheet_Row', $row);
+ $rowIndex = $row->getRowIndex();
+ $this->assertEquals(5, $rowIndex);
+ }
+
+ public function testGetCellIterator()
+ {
+ $row = new PHPExcel_Worksheet_Row($this->mockWorksheet);
+ $cellIterator = $row->getCellIterator();
+ $this->assertInstanceOf('PHPExcel_Worksheet_RowCellIterator', $cellIterator);
+ }
+}
diff --git a/unitTests/bootstrap.php b/unitTests/bootstrap.php
index 8293b9304..d212d58a1 100644
--- a/unitTests/bootstrap.php
+++ b/unitTests/bootstrap.php
@@ -2,7 +2,7 @@
/**
* $Id: bootstrap.php 2892 2011-08-14 15:11:50Z markbaker@phpexcel.net $
*
- * @copyright Copyright (C) 2011-2012 PHPExcel. All rights reserved.
+ * @copyright Copyright (C) 2011-2014 PHPExcel. All rights reserved.
* @package PHPExcel
* @subpackage PHPExcel Unit Tests
* @author Mark Baker
@@ -17,20 +17,21 @@
// Define path to application directory
defined('APPLICATION_PATH')
- || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../Classes'));
+ || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../Classes'));
// Define path to application tests directory
defined('APPLICATION_TESTS_PATH')
- || define('APPLICATION_TESTS_PATH', realpath(dirname(__FILE__) ));
+ || define('APPLICATION_TESTS_PATH', realpath(dirname(__FILE__)));
// Define application environment
defined('APPLICATION_ENV') || define('APPLICATION_ENV', 'ci');
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
- realpath(APPLICATION_PATH . '/../Classes'),
- './',
- get_include_path(),
+ realpath(APPLICATION_PATH . '/../Classes'),
+ './',
+ dirname(__FILE__),
+ get_include_path(),
)));
@@ -40,9 +41,9 @@
*/
echo "PHPExcel tests beginning\n";
-if(extension_loaded('xdebug')) {
- echo "Xdebug extension loaded and running\n";
- xdebug_enable();
+if (extension_loaded('xdebug')) {
+ echo "Xdebug extension loaded and running\n";
+ xdebug_enable();
} else {
- echo 'Xdebug not found, you should run the following at the command line: echo "zend_extension=/usr/lib64/php/modules/xdebug.so" > /etc/php.d/xdebug.ini' . "\n";
+ echo 'Xdebug not found, you should run the following at the command line: echo "zend_extension=/usr/lib64/php/modules/xdebug.so" > /etc/php.d/xdebug.ini' . "\n";
}
diff --git a/unitTests/custom/Complex.php b/unitTests/custom/Complex.php
index c827baebd..0b22ddfdd 100644
--- a/unitTests/custom/Complex.php
+++ b/unitTests/custom/Complex.php
@@ -1,114 +1,117 @@
-realPart = (float) $realPart;
- $this->imaginaryPart = (float) $imaginaryPart;
- $this->suffix = strtolower($suffix);
- }
-
- public function getReal()
- {
- return $this->realPart;
- }
-
- public function getImaginary()
- {
- return $this->imaginaryPart;
- }
-
- public function getSuffix()
- {
- return $this->suffix;
- }
-
- public function __toString() {
- $str = "";
- if ($this->imaginaryPart != 0.0) {
- if (abs($this->imaginaryPart) != 1.0) {
- $str .= $this->imaginaryPart . $this->suffix;
- } else {
- $str .= (($this->imaginaryPart < 0.0) ? '-' : ''). $this->suffix;
- }
- }
- if ($this->realPart != 0.0) {
- if (($str) && ($this->imaginaryPart > 0.0))
- $str = "+" . $str;
- $str = $this->realPart . $str;
- }
- if (!$str)
- $str = "0.0";
- return $str;
- }
-
-}
+realPart = (float) $realPart;
+ $this->imaginaryPart = (float) $imaginaryPart;
+ $this->suffix = strtolower($suffix);
+ }
+
+ public function getReal()
+ {
+ return $this->realPart;
+ }
+
+ public function getImaginary()
+ {
+ return $this->imaginaryPart;
+ }
+
+ public function getSuffix()
+ {
+ return $this->suffix;
+ }
+
+ public function __toString()
+ {
+ $str = "";
+ if ($this->imaginaryPart != 0.0) {
+ if (abs($this->imaginaryPart) != 1.0) {
+ $str .= $this->imaginaryPart . $this->suffix;
+ } else {
+ $str .= (($this->imaginaryPart < 0.0) ? '-' : ''). $this->suffix;
+ }
+ }
+ if ($this->realPart != 0.0) {
+ if (($str) && ($this->imaginaryPart > 0.0)) {
+ $str = "+" . $str;
+ }
+ $str = $this->realPart . $str;
+ }
+ if (!$str) {
+ $str = "0.0";
+ }
+ return $str;
+ }
+}
diff --git a/unitTests/custom/complexAssert.php b/unitTests/custom/complexAssert.php
index 5b813d257..f95ca28c0 100644
--- a/unitTests/custom/complexAssert.php
+++ b/unitTests/custom/complexAssert.php
@@ -1,62 +1,55 @@
-_errorMessage = 'Expected Error: ' .
- $actual . ' !== ' . $expected;
- return FALSE;
- }
-
- $expectedComplex = new Complex($expected);
- $actualComplex = new Complex($actual);
-
- if (!is_numeric($actualComplex->getReal()) || !is_numeric($expectedComplex->getReal())) {
- if ($actualComplex->getReal() !== $expectedComplex->getReal()) {
- $this->_errorMessage = 'Mismatched String: ' .
- $actualComplex->getReal() . ' !== ' . $expectedComplex->getReal();
- return FALSE;
- }
- return TRUE;
- }
-
- if ($actualComplex->getReal() < ($expectedComplex->getReal() - $delta) ||
- $actualComplex->getReal() > ($expectedComplex->getReal() + $delta)) {
- $this->_errorMessage = 'Mismatched Real part: ' .
- $actualComplex->getReal() . ' != ' . $expectedComplex->getReal();
- return FALSE;
- }
-
- if ($actualComplex->getImaginary() < ($expectedComplex->getImaginary() - $delta) ||
- $actualComplex->getImaginary() > ($expectedComplex->getImaginary() + $delta)) {
- $this->_errorMessage = 'Mismatched Imaginary part: ' .
- $actualComplex->getImaginary() . ' != ' . $expectedComplex->getImaginary();
- return FALSE;
- }
-
- if ($actualComplex->getSuffix() !== $actualComplex->getSuffix()) {
- $this->_errorMessage = 'Mismatched Suffix: ' .
- $actualComplex->getSuffix() . ' != ' . $expectedComplex->getSuffix();
- return FALSE;
- }
-
- return TRUE;
- }
-
-
- public function getErrorMessage() {
- return $this->_errorMessage;
- }
-
-}
+_errorMessage = 'Expected Error: ' . $actual . ' !== ' . $expected;
+ return false;
+ }
+
+ $expectedComplex = new Complex($expected);
+ $actualComplex = new Complex($actual);
+
+ if (!is_numeric($actualComplex->getReal()) || !is_numeric($expectedComplex->getReal())) {
+ if ($actualComplex->getReal() !== $expectedComplex->getReal()) {
+ $this->_errorMessage = 'Mismatched String: ' . $actualComplex->getReal() . ' !== ' . $expectedComplex->getReal();
+ return false;
+ }
+ return true;
+ }
+
+ if ($actualComplex->getReal() < ($expectedComplex->getReal() - $delta) ||
+ $actualComplex->getReal() > ($expectedComplex->getReal() + $delta)) {
+ $this->_errorMessage = 'Mismatched Real part: ' . $actualComplex->getReal() . ' != ' . $expectedComplex->getReal();
+ return false;
+ }
+
+ if ($actualComplex->getImaginary() < ($expectedComplex->getImaginary() - $delta) ||
+ $actualComplex->getImaginary() > ($expectedComplex->getImaginary() + $delta)) {
+ $this->_errorMessage = 'Mismatched Imaginary part: ' . $actualComplex->getImaginary() . ' != ' . $expectedComplex->getImaginary();
+ return false;
+ }
+
+ if ($actualComplex->getSuffix() !== $actualComplex->getSuffix()) {
+ $this->_errorMessage = 'Mismatched Suffix: ' . $actualComplex->getSuffix() . ' != ' . $expectedComplex->getSuffix();
+ return false;
+ }
+
+ return true;
+ }
+
+ public function getErrorMessage()
+ {
+ return $this->_errorMessage;
+ }
+}
diff --git a/unitTests/phpunit.xml b/unitTests/phpunit.xml
index d18d14610..d024c28f9 100644
--- a/unitTests/phpunit.xml
+++ b/unitTests/phpunit.xml
@@ -13,6 +13,9 @@
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false">
+