commit 88184503025873928a54b7993391aee00685c51d
Author: Dave Umrysh
+ * References:
+ *
';
+ $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']]) &&
+ @(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;
+ } // 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 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;
+ } // function _processTokenStack()
+
+
+ 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;
+ } // 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->_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 '=':
+ $result = ($operand1 == $operand2);
+ break;
+ // Greater than or equal
+ case '>=':
+ if ($useLowercaseFirstComparison) {
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0;
+ } else {
+ $result = ($operand1 >= $operand2);
+ }
+ break;
+ // Less than or equal
+ case '<=':
+ if ($useLowercaseFirstComparison) {
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0;
+ } else {
+ $result = ($operand1 <= $operand2);
+ }
+ break;
+ // Inequality
+ case '<>':
+ $result = ($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;
+ } // function _executeBinaryComparisonOperation()
+
+ /**
+ * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters
+ * @param string $str1
+ * @param string $str2
+ * @return integer
+ */
+ private function strcmpLowercaseFirst($str1, $str2)
+ {
+ $from = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+ $to = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ $inversedStr1 = strtr($str1, $from, $to);
+ $inversedStr2 = strtr($str2, $from, $to);
+
+ 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;
+ } // function _executeNumericBinaryOperation()
+
+
+ // 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);
+ } // function _raiseFormulaError()
+
+
+ /**
+ * 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
+ 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.
+ * @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
+ 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/PHPExcel/Calculation/Database.php b/PHPExcel/Calculation/Database.php
new file mode 100644
index 0000000..c3e86d7
--- /dev/null
+++ b/PHPExcel/Calculation/Database.php
@@ -0,0 +1,725 @@
+ $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/PHPExcel/Calculation/DateTime.php b/PHPExcel/Calculation/DateTime.php
new file mode 100644
index 0000000..debd131
--- /dev/null
+++ b/PHPExcel/Calculation/DateTime.php
@@ -0,0 +1,1475 @@
+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))) {
+ $month = PHPExcel_Shared_Date::monthStringToNumber($month);
+ }
+
+ 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
+
diff --git a/PHPExcel/Calculation/Engineering.php b/PHPExcel/Calculation/Engineering.php
new file mode 100644
index 0000000..7e32aa8
--- /dev/null
+++ b/PHPExcel/Calculation/Engineering.php
@@ -0,0 +1,2505 @@
+ 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()
+
+
+ /**
+ * 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);
+ } // 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 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));
+ } // 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
+ *
+ * @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;
+ } // 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/PHPExcel/Calculation/Exception.php b/PHPExcel/Calculation/Exception.php
new file mode 100644
index 0000000..037f788
--- /dev/null
+++ b/PHPExcel/Calculation/Exception.php
@@ -0,0 +1,52 @@
+line = $line;
+ $e->file = $file;
+ throw $e;
+ }
+}
diff --git a/PHPExcel/Calculation/ExceptionHandler.php b/PHPExcel/Calculation/ExceptionHandler.php
new file mode 100644
index 0000000..389f647
--- /dev/null
+++ b/PHPExcel/Calculation/ExceptionHandler.php
@@ -0,0 +1,49 @@
+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)) {
+ 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
+ *
+ * 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;
+ } // 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.
+ *
+ * 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];
+ } // function IPMT()
+
+ /**
+ * 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();
+ } // 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()
+
+
+ /**
+ * 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());
+ } // 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.
+ *
+ * @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
diff --git a/PHPExcel/Calculation/FormulaParser.php b/PHPExcel/Calculation/FormulaParser.php
new file mode 100644
index 0000000..754a638
--- /dev/null
+++ b/PHPExcel/Calculation/FormulaParser.php
@@ -0,0 +1,614 @@
+<";
+ const OPERATORS_POSTFIX = "%";
+
+ /**
+ * Formula
+ *
+ * @var string
+ */
+ private $_formula;
+
+ /**
+ * Tokens
+ *
+ * @var PHPExcel_Calculation_FormulaToken[]
+ */
+ private $_tokens = array();
+
+ /**
+ * Create a new PHPExcel_Calculation_FormulaParser
+ *
+ * @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();
+ }
+
+ /**
+ * Get Formula
+ *
+ * @return string
+ */
+ public function getFormula() {
+ return $this->_formula;
+ }
+
+ /**
+ * Get Token
+ *
+ * @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.");
+ }
+ }
+
+ /**
+ * Get Token count
+ *
+ * @return string
+ */
+ public function getTokenCount() {
+ return count($this->_tokens);
+ }
+
+ /**
+ * Get Tokens
+ *
+ * @return PHPExcel_Calculation_FormulaToken[]
+ */
+ 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;
+ }
+ }
+}
diff --git a/PHPExcel/Calculation/FormulaToken.php b/PHPExcel/Calculation/FormulaToken.php
new file mode 100644
index 0000000..fd5e2e5
--- /dev/null
+++ b/PHPExcel/Calculation/FormulaToken.php
@@ -0,0 +1,176 @@
+_value = $pValue;
+ $this->_tokenType = $pTokenType;
+ $this->_tokenSubType = $pTokenSubType;
+ }
+
+ /**
+ * Get Value
+ *
+ * @return string
+ */
+ public function getValue() {
+ return $this->_value;
+ }
+
+ /**
+ * Set Value
+ *
+ * @param string $value
+ */
+ public function setValue($value) {
+ $this->_value = $value;
+ }
+
+ /**
+ * Get Token Type (represented by TOKEN_TYPE_*)
+ *
+ * @return string
+ */
+ public function getTokenType() {
+ return $this->_tokenType;
+ }
+
+ /**
+ * Set Token Type
+ *
+ * @param string $value
+ */
+ public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN) {
+ $this->_tokenType = $value;
+ }
+
+ /**
+ * Get Token SubType (represented by TOKEN_SUBTYPE_*)
+ *
+ * @return string
+ */
+ public function getTokenSubType() {
+ return $this->_tokenSubType;
+ }
+
+ /**
+ * Set Token SubType
+ *
+ * @param string $value
+ */
+ public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
+ $this->_tokenSubType = $value;
+ }
+}
diff --git a/PHPExcel/Calculation/Function.php b/PHPExcel/Calculation/Function.php
new file mode 100644
index 0000000..7299834
--- /dev/null
+++ b/PHPExcel/Calculation/Function.php
@@ -0,0 +1,149 @@
+_category = $pCategory;
+ $this->_excelName = $pExcelName;
+ $this->_phpExcelName = $pPHPExcelName;
+ } else {
+ throw new PHPExcel_Calculation_Exception("Invalid parameters passed.");
+ }
+ }
+
+ /**
+ * Get Category (represented by CATEGORY_*)
+ *
+ * @return string
+ */
+ public function getCategory() {
+ return $this->_category;
+ }
+
+ /**
+ * Set Category (represented by CATEGORY_*)
+ *
+ * @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.");
+ }
+ }
+
+ /**
+ * Get Excel name
+ *
+ * @return string
+ */
+ public function getExcelName() {
+ return $this->_excelName;
+ }
+
+ /**
+ * Set Excel name
+ *
+ * @param string $value
+ */
+ public function setExcelName($value) {
+ $this->_excelName = $value;
+ }
+
+ /**
+ * Get PHPExcel name
+ *
+ * @return string
+ */
+ public function getPHPExcelName() {
+ return $this->_phpExcelName;
+ }
+
+ /**
+ * Set PHPExcel name
+ *
+ * @param string $value
+ */
+ public function setPHPExcelName($value) {
+ $this->_phpExcelName = $value;
+ }
+}
diff --git a/PHPExcel/Calculation/Functions.php b/PHPExcel/Calculation/Functions.php
new file mode 100644
index 0000000..59dd75d
--- /dev/null
+++ b/PHPExcel/Calculation/Functions.php
@@ -0,0 +1,725 @@
+ '#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 #NULL!
+ */
+ 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 (!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;
+ }
+ } // 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 1.8.0, 2014-03-02';
+ } // 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;
+ } 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
+
+
+//
+// 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()
+}
+
+if (!function_exists('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()
+}
+
+
+//
+// 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;
+ }
+}
diff --git a/PHPExcel/Calculation/Logical.php b/PHPExcel/Calculation/Logical.php
new file mode 100644
index 0000000..bb206a1
--- /dev/null
+++ b/PHPExcel/Calculation/Logical.php
@@ -0,0 +1,288 @@
+ $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()
+
+
+ /**
+ * 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);
+ }
+ }
+
+ // Return
+ if ($argCount < 0) {
+ return PHPExcel_Calculation_Functions::VALUE();
+ }
+ return $returnValue;
+ } // function LOGICAL_OR()
+
+
+ /**
+ * 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()
+
+ /**
+ * 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()
+
+
+ /**
+ * 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
diff --git a/PHPExcel/Calculation/LookupRef.php b/PHPExcel/Calculation/LookupRef.php
new file mode 100644
index 0000000..e1285d9
--- /dev/null
+++ b/PHPExcel/Calculation/LookupRef.php
@@ -0,0 +1,881 @@
+ '') {
+ 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
+ * @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);
+
+ 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 $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);
+ } // 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);
+ $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);
+ } // 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 ((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
+ $result = $lookup_array[$rowNumber][$returnColumn];
+ if ((is_numeric($lookup_value) && is_numeric($result)) ||
+ (!is_numeric($lookup_value) && !is_numeric($result))) {
+ return $result;
+ }
+ }
+ }
+
+ return PHPExcel_Calculation_Functions::NA();
+ } // function VLOOKUP()
+
+
+/**
+ * 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
+ $result = $lookup_array[$returnColumn][$rowNumber];
+ return $result;
+ }
+ }
+
+ return PHPExcel_Calculation_Functions::NA();
+ } // function HLOOKUP()
+
+
+ /**
+ * 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/PHPExcel/Calculation/MathTrig.php b/PHPExcel/Calculation/MathTrig.php
new file mode 100644
index 0000000..1093055
--- /dev/null
+++ b/PHPExcel/Calculation/MathTrig.php
@@ -0,0 +1,1373 @@
+ 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
+ */
+ 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 $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);
+ } // 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 = 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
+ 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() {
+ $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);
+ }
+ }
+
+ // Return
+ return $returnValue;
+ } // function SUMSQ()
+
+
+ /**
+ * 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);
+ $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[] $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);
+ $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[] $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);
+ $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
diff --git a/PHPExcel/Calculation/Statistical.php b/PHPExcel/Calculation/Statistical.php
new file mode 100644
index 0000000..32b9c78
--- /dev/null
+++ b/PHPExcel/Calculation/Statistical.php
@@ -0,0 +1,3651 @@
+ $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
+ *
+ *
+ *
+ * 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.
+ *
'; +// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); +// 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
diff --git a/PHPExcel/Shared/JAMA/utils/Error.php b/PHPExcel/Shared/JAMA/utils/Error.php
new file mode 100644
index 0000000..e73252b
--- /dev/null
+++ b/PHPExcel/Shared/JAMA/utils/Error.php
@@ -0,0 +1,82 @@
+ 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.
+ *
+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);
+}
+*/
diff --git a/PHPExcel/Shared/OLE.php b/PHPExcel/Shared/OLE.php
new file mode 100644
index 0000000..9796282
--- /dev/null
+++ b/PHPExcel/Shared/OLE.php
@@ -0,0 +1,531 @@
+ |
+// | Based on OLE::Storage_Lite by Kawai, Takanori |
+// +----------------------------------------------------------------------+
+//
+// $Id: OLE.php,v 1.13 2007/03/07 14:38:25 schmidt Exp $
+
+
+/**
+* Array for storing OLE instances that are accessed from
+* OLE_ChainedBlockStream::stream_open().
+* @var array
+*/
+$GLOBALS['_OLE_INSTANCES'] = array();
+
+/**
+* OLE package base class.
+*
+* @author Xavier Noguer
';
+ $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/PHPExcel/Shared/PCLZip/gnu-lgpl.txt b/PHPExcel/Shared/PCLZip/gnu-lgpl.txt
new file mode 100644
index 0000000..cbee875
--- /dev/null
+++ b/PHPExcel/Shared/PCLZip/gnu-lgpl.txt
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(
+ * array(
+ * 'font' => array(
+ * 'name' => 'Arial',
+ * 'bold' => true,
+ * 'italic' => false,
+ * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE,
+ * 'strike' => false,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * ),
+ * 'borders' => 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'
+ * )
+ * )
+ * ),
+ * 'quotePrefix' => true
+ * )
+ * );
+ *
+ *
+ * @param array $pStyles Array containing style information
+ * @param boolean $pAdvanced Advanced mode for setting borders.
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style
+ */
+ public function applyFromArray($pStyles = null, $pAdvanced = true)
+ {
+ if (is_array($pStyles)) {
+ if ($this->_isSupervisor) {
+
+ $pRange = $this->getSelectedCells();
+
+ // Uppercase coordinate
+ $pRange = strtoupper($pRange);
+
+ // Is it a cell range or a single cell?
+ 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;
+
+ // Make sure we can loop upwards on rows and columns
+ if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
+ $tmp = $rangeStart;
+ $rangeStart = $rangeEnd;
+ $rangeEnd = $tmp;
+ }
+
+ // ADVANCED MODE:
+
+ if ($pAdvanced && isset($pStyles['borders'])) {
+
+ // 'allborders' is a shorthand property for 'outline' and 'inside' and
+ // it applies to components that have not been set explicitly
+ if (isset($pStyles['borders']['allborders'])) {
+ foreach (array('outline', 'inside') as $component) {
+ if (!isset($pStyles['borders'][$component])) {
+ $pStyles['borders'][$component] = $pStyles['borders']['allborders'];
+ }
+ }
+ unset($pStyles['borders']['allborders']); // not needed any more
+ }
+
+ // 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left'
+ // it applies to components that have not been set explicitly
+ if (isset($pStyles['borders']['outline'])) {
+ foreach (array('top', 'right', 'bottom', 'left') as $component) {
+ if (!isset($pStyles['borders'][$component])) {
+ $pStyles['borders'][$component] = $pStyles['borders']['outline'];
+ }
+ }
+ unset($pStyles['borders']['outline']); // not needed any more
+ }
+
+ // 'inside' is a shorthand property for 'vertical' and 'horizontal'
+ // it applies to components that have not been set explicitly
+ if (isset($pStyles['borders']['inside'])) {
+ foreach (array('vertical', 'horizontal') as $component) {
+ if (!isset($pStyles['borders'][$component])) {
+ $pStyles['borders'][$component] = $pStyles['borders']['inside'];
+ }
+ }
+ unset($pStyles['borders']['inside']); // not needed any more
+ }
+
+ // width and height characteristics of selection, 1, 2, or 3 (for 3 or more)
+ $xMax = min($rangeEnd[0] - $rangeStart[0] + 1, 3);
+ $yMax = min($rangeEnd[1] - $rangeStart[1] + 1, 3);
+
+ // loop through up to 3 x 3 = 9 regions
+ for ($x = 1; $x <= $xMax; ++$x) {
+ // start column index for region
+ $colStart = ($x == 3) ?
+ PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0])
+ : PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $x - 1);
+
+ // end column index for region
+ $colEnd = ($x == 1) ?
+ PHPExcel_Cell::stringFromColumnIndex($rangeStart[0])
+ : PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] - $xMax + $x);
+
+ for ($y = 1; $y <= $yMax; ++$y) {
+
+ // which edges are touching the region
+ $edges = array();
+
+ // are we at left edge
+ if ($x == 1) {
+ $edges[] = 'left';
+ }
+
+ // are we at right edge
+ if ($x == $xMax) {
+ $edges[] = 'right';
+ }
+
+ // are we at top edge?
+ if ($y == 1) {
+ $edges[] = 'top';
+ }
+
+ // are we at bottom edge?
+ if ($y == $yMax) {
+ $edges[] = 'bottom';
+ }
+
+ // start row index for region
+ $rowStart = ($y == 3) ?
+ $rangeEnd[1] : $rangeStart[1] + $y - 1;
+
+ // end row index for region
+ $rowEnd = ($y == 1) ?
+ $rangeStart[1] : $rangeEnd[1] - $yMax + $y;
+
+ // build range for region
+ $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd;
+
+ // retrieve relevant style array for region
+ $regionStyles = $pStyles;
+ unset($regionStyles['borders']['inside']);
+
+ // what are the inner edges of the region when looking at the selection
+ $innerEdges = array_diff( array('top', 'right', 'bottom', 'left'), $edges );
+
+ // inner edges that are not touching the region should take the 'inside' border properties if they have been set
+ foreach ($innerEdges as $innerEdge) {
+ switch ($innerEdge) {
+ case 'top':
+ case 'bottom':
+ // should pick up 'horizontal' border property if set
+ if (isset($pStyles['borders']['horizontal'])) {
+ $regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal'];
+ } else {
+ unset($regionStyles['borders'][$innerEdge]);
+ }
+ break;
+ case 'left':
+ case 'right':
+ // should pick up 'vertical' border property if set
+ if (isset($pStyles['borders']['vertical'])) {
+ $regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical'];
+ } else {
+ unset($regionStyles['borders'][$innerEdge]);
+ }
+ break;
+ }
+ }
+
+ // apply region style to region by calling applyFromArray() in simple mode
+ $this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false);
+ }
+ }
+ return $this;
+ }
+
+ // SIMPLE MODE:
+
+ // Selection type, inspect
+ if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) {
+ $selectionType = 'COLUMN';
+ } else if (preg_match('/^A[0-9]+:XFD[0-9]+$/', $pRange)) {
+ $selectionType = 'ROW';
+ } else {
+ $selectionType = 'CELL';
+ }
+
+ // First loop through columns, rows, or cells to find out which styles are affected by this operation
+ switch ($selectionType) {
+ case 'COLUMN':
+ $oldXfIndexes = array();
+ for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true;
+ }
+ break;
+
+ case 'ROW':
+ $oldXfIndexes = array();
+ for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) {
+ $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style
+ } else {
+ $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true;
+ }
+ }
+ break;
+
+ case 'CELL':
+ $oldXfIndexes = array();
+ for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true;
+ }
+ }
+ break;
+ }
+
+ // clone each of the affected styles, apply the style array, and add the new styles to the workbook
+ $workbook = $this->getActiveSheet()->getParent();
+ foreach ($oldXfIndexes as $oldXfIndex => $dummy) {
+ $style = $workbook->getCellXfByIndex($oldXfIndex);
+ $newStyle = clone $style;
+ $newStyle->applyFromArray($pStyles);
+
+ if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) {
+ // there is already such cell Xf in our collection
+ $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex();
+ } else {
+ // we don't have such a cell Xf, need to add
+ $workbook->addCellXf($newStyle);
+ $newXfIndexes[$oldXfIndex] = $newStyle->getIndex();
+ }
+ }
+
+ // Loop through columns, rows, or cells again and update the XF index
+ switch ($selectionType) {
+ case 'COLUMN':
+ for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ $columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col);
+ $oldXfIndex = $columnDimension->getXfIndex();
+ $columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]);
+ }
+ break;
+
+ case 'ROW':
+ for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ $rowDimension = $this->getActiveSheet()->getRowDimension($row);
+ $oldXfIndex = $rowDimension->getXfIndex() === null ?
+ 0 : $rowDimension->getXfIndex(); // row without explicit style should be formatted based on default style
+ $rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]);
+ }
+ break;
+
+ case 'CELL':
+ for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ $cell = $this->getActiveSheet()->getCellByColumnAndRow($col, $row);
+ $oldXfIndex = $cell->getXfIndex();
+ $cell->setXfIndex($newXfIndexes[$oldXfIndex]);
+ }
+ }
+ break;
+ }
+
+ } else {
+ // not a supervisor, just apply the style array directly on style object
+ if (array_key_exists('fill', $pStyles)) {
+ $this->getFill()->applyFromArray($pStyles['fill']);
+ }
+ if (array_key_exists('font', $pStyles)) {
+ $this->getFont()->applyFromArray($pStyles['font']);
+ }
+ if (array_key_exists('borders', $pStyles)) {
+ $this->getBorders()->applyFromArray($pStyles['borders']);
+ }
+ if (array_key_exists('alignment', $pStyles)) {
+ $this->getAlignment()->applyFromArray($pStyles['alignment']);
+ }
+ if (array_key_exists('numberformat', $pStyles)) {
+ $this->getNumberFormat()->applyFromArray($pStyles['numberformat']);
+ }
+ if (array_key_exists('protection', $pStyles)) {
+ $this->getProtection()->applyFromArray($pStyles['protection']);
+ }
+ if (array_key_exists('quotePrefix', $pStyles)) {
+ $this->_quotePrefix = $pStyles['quotePrefix'];
+ }
+ }
+ } else {
+ throw new PHPExcel_Exception("Invalid style array passed.");
+ }
+ return $this;
+ }
+
+ /**
+ * Get Fill
+ *
+ * @return PHPExcel_Style_Fill
+ */
+ public function getFill()
+ {
+ return $this->_fill;
+ }
+
+ /**
+ * Get Font
+ *
+ * @return PHPExcel_Style_Font
+ */
+ public function getFont()
+ {
+ return $this->_font;
+ }
+
+ /**
+ * Set font
+ *
+ * @param PHPExcel_Style_Font $font
+ * @return PHPExcel_Style
+ */
+ public function setFont(PHPExcel_Style_Font $font)
+ {
+ $this->_font = $font;
+ return $this;
+ }
+
+ /**
+ * Get Borders
+ *
+ * @return PHPExcel_Style_Borders
+ */
+ public function getBorders()
+ {
+ return $this->_borders;
+ }
+
+ /**
+ * Get Alignment
+ *
+ * @return PHPExcel_Style_Alignment
+ */
+ public function getAlignment()
+ {
+ return $this->_alignment;
+ }
+
+ /**
+ * Get Number Format
+ *
+ * @return PHPExcel_Style_NumberFormat
+ */
+ public function getNumberFormat()
+ {
+ return $this->_numberFormat;
+ }
+
+ /**
+ * Get Conditional Styles. Only used on supervisor.
+ *
+ * @return PHPExcel_Style_Conditional[]
+ */
+ public function getConditionalStyles()
+ {
+ return $this->getActiveSheet()->getConditionalStyles($this->getActiveCell());
+ }
+
+ /**
+ * Set Conditional Styles. Only used on supervisor.
+ *
+ * @param PHPExcel_Style_Conditional[] $pValue Array of condtional styles
+ * @return PHPExcel_Style
+ */
+ public function setConditionalStyles($pValue = null)
+ {
+ if (is_array($pValue)) {
+ $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue);
+ }
+ return $this;
+ }
+
+ /**
+ * Get Protection
+ *
+ * @return PHPExcel_Style_Protection
+ */
+ public function getProtection()
+ {
+ return $this->_protection;
+ }
+
+ /**
+ * Get quote prefix
+ *
+ * @return boolean
+ */
+ public function getQuotePrefix()
+ {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getQuotePrefix();
+ }
+ return $this->_quotePrefix;
+ }
+
+ /**
+ * Set quote prefix
+ *
+ * @param boolean $pValue
+ */
+ public function setQuotePrefix($pValue)
+ {
+ if ($pValue == '') {
+ $pValue = false;
+ }
+ if ($this->_isSupervisor) {
+ $styleArray = array('quotePrefix' => $pValue);
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_quotePrefix = (boolean) $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode()
+ {
+ $hashConditionals = '';
+ foreach ($this->_conditionalStyles as $conditional) {
+ $hashConditionals .= $conditional->getHashCode();
+ }
+
+ return md5(
+ $this->_fill->getHashCode()
+ . $this->_font->getHashCode()
+ . $this->_borders->getHashCode()
+ . $this->_alignment->getHashCode()
+ . $this->_numberFormat->getHashCode()
+ . $hashConditionals
+ . $this->_protection->getHashCode()
+ . ($this->_quotePrefix ? 't' : 'f')
+ . __CLASS__
+ );
+ }
+
+ /**
+ * Get own index in style collection
+ *
+ * @return int
+ */
+ public function getIndex()
+ {
+ return $this->_index;
+ }
+
+ /**
+ * Set own index in style collection
+ *
+ * @param int $pValue
+ */
+ public function setIndex($pValue)
+ {
+ $this->_index = $pValue;
+ }
+
+}
diff --git a/PHPExcel/Style/Alignment.php b/PHPExcel/Style/Alignment.php
new file mode 100644
index 0000000..0d9e076
--- /dev/null
+++ b/PHPExcel/Style/Alignment.php
@@ -0,0 +1,412 @@
+_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']);
+ }
+ }
+ } 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__
+ );
+ }
+
+}
diff --git a/PHPExcel/Style/Border.php b/PHPExcel/Style/Border.php
new file mode 100644
index 0000000..3b7eba9
--- /dev/null
+++ b/PHPExcel/Style/Border.php
@@ -0,0 +1,294 @@
+_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');
+ }
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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;
+
+ }
+ }
+
+ /**
+ * 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));
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Get Border style
+ *
+ * @return string
+ */
+ public function getBorderStyle() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getBorderStyle();
+ }
+ return $this->_borderStyle;
+ }
+
+ /**
+ * 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) {
+
+ 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;
+ }
+
+ /**
+ * Get Border Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getColor() {
+ return $this->_color;
+ }
+
+ /**
+ * 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;
+
+ 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/PHPExcel/Style/Borders.php b/PHPExcel/Style/Borders.php
new file mode 100644
index 0000000..b90838a
--- /dev/null
+++ b/PHPExcel/Style/Borders.php
@@ -0,0 +1,424 @@
+_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);
+ }
+
+ /**
+ * 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'
+ * )
+ * )
+ * )
+ * );
+ *
+ *
+ * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
+ * array(
+ * 'allborders' => array(
+ * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
+ * 'color' => array(
+ * 'rgb' => '808080'
+ * )
+ * )
+ * )
+ * );
+ *
+ *
+ * @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;
+ }
+
+ /**
+ * Get Left
+ *
+ * @return PHPExcel_Style_Border
+ */
+ public function getLeft() {
+ return $this->_left;
+ }
+
+ /**
+ * Get Right
+ *
+ * @return PHPExcel_Style_Border
+ */
+ public function getRight() {
+ return $this->_right;
+ }
+
+ /**
+ * Get Top
+ *
+ * @return PHPExcel_Style_Border
+ */
+ public function getTop() {
+ return $this->_top;
+ }
+
+ /**
+ * Get Bottom
+ *
+ * @return PHPExcel_Style_Border
+ */
+ public function getBottom() {
+ return $this->_bottom;
+ }
+
+ /**
+ * Get Diagonal
+ *
+ * @return PHPExcel_Style_Border
+ */
+ public function getDiagonal() {
+ return $this->_diagonal;
+ }
+
+ /**
+ * Get AllBorders (pseudo-border). Only applies to supervisor.
+ *
+ * @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;
+ }
+
+ /**
+ * Get Outline (pseudo-border). Only applies to supervisor.
+ *
+ * @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;
+ }
+
+ /**
+ * Get Inside (pseudo-border). Only applies to supervisor.
+ *
+ * @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;
+ }
+
+ /**
+ * Get Vertical (pseudo-border). Only applies to supervisor.
+ *
+ * @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;
+ }
+
+ /**
+ * Get Horizontal (pseudo-border). Only applies to supervisor.
+ *
+ * @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;
+ }
+
+ /**
+ * Get DiagonalDirection
+ *
+ * @return int
+ */
+ public function getDiagonalDirection() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getDiagonalDirection();
+ }
+ return $this->_diagonalDirection;
+ }
+
+ /**
+ * Set DiagonalDirection
+ *
+ * @param int $pValue
+ * @return PHPExcel_Style_Borders
+ */
+ 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;
+ }
+
+ /**
+ * 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/PHPExcel/Style/Color.php b/PHPExcel/Style/Color.php
new file mode 100644
index 0000000..4d34504
--- /dev/null
+++ b/PHPExcel/Style/Color.php
@@ -0,0 +1,429 @@
+_argb = $pARGB;
+ }
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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;
+ }
+ }
+
+ /**
+ * 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;
+
+ }
+ return $this->_parent->getStyleArray(array($key => $array));
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Get ARGB
+ *
+ * @return string
+ */
+ public function getARGB() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getARGB();
+ }
+ return $this->_argb;
+ }
+
+ /**
+ * 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 RGB
+ *
+ * @return string
+ */
+ public function getRGB() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getRGB();
+ }
+ return substr($this->_argb, 2);
+ }
+
+ /**
+ * 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 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 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 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 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);
+ }
+
+ /**
+ * 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);
+
+ $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;
+ }
+
+ 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;
+
+ $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;
+ }
+
+ /**
+ * 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);
+
+ // 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 (array_key_exists($pIndex, self::$_indexedColors)) {
+ return new PHPExcel_Style_Color(self::$_indexedColors[$pIndex]);
+ }
+
+ if ($background) {
+ return new PHPExcel_Style_Color('FFFFFFFF');
+ }
+ return new PHPExcel_Style_Color('FF000000');
+ }
+
+ /**
+ * 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/PHPExcel/Style/Conditional.php b/PHPExcel/Style/Conditional.php
new file mode 100644
index 0000000..ffd7a9f
--- /dev/null
+++ b/PHPExcel/Style/Conditional.php
@@ -0,0 +1,277 @@
+_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);
+ }
+
+ /**
+ * Get Condition type
+ *
+ * @return string
+ */
+ public function getConditionType() {
+ return $this->_conditionType;
+ }
+
+ /**
+ * Set 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;
+ }
+
+ /**
+ * Get Operator type
+ *
+ * @return string
+ */
+ public function getOperatorType() {
+ return $this->_operatorType;
+ }
+
+ /**
+ * Set 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;
+ }
+
+ /**
+ * Get text
+ *
+ * @return string
+ */
+ public function getText() {
+ return $this->_text;
+ }
+
+ /**
+ * Set text
+ *
+ * @param string $value
+ * @return PHPExcel_Style_Conditional
+ */
+ public function setText($value = null) {
+ $this->_text = $value;
+ return $this;
+ }
+
+ /**
+ * Get Condition
+ *
+ * @deprecated Deprecated, use getConditions instead
+ * @return string
+ */
+ public function getCondition() {
+ if (isset($this->_condition[0])) {
+ return $this->_condition[0];
+ }
+
+ return '';
+ }
+
+ /**
+ * Set Condition
+ *
+ * @deprecated Deprecated, use setConditions instead
+ * @param string $pValue Condition
+ * @return PHPExcel_Style_Conditional
+ */
+ public function setCondition($pValue = '') {
+ if (!is_array($pValue))
+ $pValue = array($pValue);
+
+ return $this->setConditions($pValue);
+ }
+
+ /**
+ * Get Conditions
+ *
+ * @return string[]
+ */
+ public function getConditions() {
+ return $this->_condition;
+ }
+
+ /**
+ * Set Conditions
+ *
+ * @param string[] $pValue Condition
+ * @return PHPExcel_Style_Conditional
+ */
+ public function setConditions($pValue) {
+ if (!is_array($pValue))
+ $pValue = array($pValue);
+
+ $this->_condition = $pValue;
+ return $this;
+ }
+
+ /**
+ * Add Condition
+ *
+ * @param string $pValue Condition
+ * @return PHPExcel_Style_Conditional
+ */
+ public function addCondition($pValue = '') {
+ $this->_condition[] = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Style
+ *
+ * @return PHPExcel_Style
+ */
+ public function getStyle() {
+ return $this->_style;
+ }
+
+ /**
+ * Set Style
+ *
+ * @param PHPExcel_Style $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Style_Conditional
+ */
+ 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__
+ );
+ }
+
+ /**
+ * 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/PHPExcel/Style/Fill.php b/PHPExcel/Style/Fill.php
new file mode 100644
index 0000000..1b4d0ad
--- /dev/null
+++ b/PHPExcel/Style/Fill.php
@@ -0,0 +1,321 @@
+_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);
+
+ // bind parent if we are a supervisor
+ if ($isSupervisor) {
+ $this->_startColor->bindParent($this, '_startColor');
+ $this->_endColor->bindParent($this, '_endColor');
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ /**
+ * Build style array from subcomponents
+ *
+ * @param array $array
+ * @return array
+ */
+ public function getStyleArray($array)
+ {
+ return array('fill' => $array);
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Get Fill Type
+ *
+ * @return string
+ */
+ public function getFillType() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getFillType();
+ }
+ return $this->_fillType;
+ }
+
+ /**
+ * 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 Rotation
+ *
+ * @return double
+ */
+ public function getRotation() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getRotation();
+ }
+ return $this->_rotation;
+ }
+
+ /**
+ * 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 Start Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getStartColor() {
+ return $this->_startColor;
+ }
+
+ /**
+ * 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;
+
+ if ($this->_isSupervisor) {
+ $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB()));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
+ } else {
+ $this->_startColor = $color;
+ }
+ return $this;
+ }
+
+ /**
+ * Get End Color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getEndColor() {
+ return $this->_endColor;
+ }
+
+ /**
+ * 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;
+
+ 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/PHPExcel/Style/Font.php b/PHPExcel/Style/Font.php
new file mode 100644
index 0000000..e89488c
--- /dev/null
+++ b/PHPExcel/Style/Font.php
@@ -0,0 +1,532 @@
+_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/PHPExcel/Style/NumberFormat.php b/PHPExcel/Style/NumberFormat.php
new file mode 100644
index 0000000..e8a978f
--- /dev/null
+++ b/PHPExcel/Style/NumberFormat.php
@@ -0,0 +1,711 @@
+_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'
+ );
+
+ private static function _formatAsDate(&$value, &$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) {
+ 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);
+ }
+ }
+ }
+
+ // Additional formatting provided by callback function
+ if ($callBack !== null) {
+ list($writerInstance, $function) = $callBack;
+ $value = $writerInstance->$function($value, $formatColor);
+ }
+
+ return $value;
+ }
+
+}
diff --git a/PHPExcel/Style/Protection.php b/PHPExcel/Style/Protection.php
new file mode 100644
index 0000000..8dc1f31
--- /dev/null
+++ b/PHPExcel/Style/Protection.php
@@ -0,0 +1,207 @@
+_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();
+ }
+
+ /**
+ * 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
+ * )
+ * );
+ *
+ *
+ * @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;
+ }
+
+ /**
+ * Get locked
+ *
+ * @return string
+ */
+ public function getLocked() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getLocked();
+ }
+ return $this->_locked;
+ }
+
+ /**
+ * Set locked
+ *
+ * @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;
+ }
+
+ /**
+ * Get hidden
+ *
+ * @return string
+ */
+ public function getHidden() {
+ if ($this->_isSupervisor) {
+ return $this->getSharedComponent()->getHidden();
+ }
+ return $this->_hidden;
+ }
+
+ /**
+ * Set hidden
+ *
+ * @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;
+ }
+
+ /**
+ * 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/PHPExcel/Style/Supervisor.php b/PHPExcel/Style/Supervisor.php
new file mode 100644
index 0000000..c2ce9c0
--- /dev/null
+++ b/PHPExcel/Style/Supervisor.php
@@ -0,0 +1,132 @@
+_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;
+ }
+
+ /**
+ * 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 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();
+ }
+
+ /**
+ * 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/PHPExcel/Worksheet.php b/PHPExcel/Worksheet.php
new file mode 100644
index 0000000..682ad98
--- /dev/null
+++ b/PHPExcel/Worksheet.php
@@ -0,0 +1,2909 @@
+_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);
+
+ // Set page setup
+ $this->_pageSetup = new PHPExcel_Worksheet_PageSetup();
+
+ // Set page margins
+ $this->_pageMargins = new PHPExcel_Worksheet_PageMargins();
+
+ // Set page header/footer
+ $this->_headerFooter = new PHPExcel_Worksheet_HeaderFooter();
+
+ // Set sheet view
+ $this->_sheetView = new PHPExcel_Worksheet_SheetView();
+
+ // Drawing collection
+ $this->_drawingCollection = new ArrayObject();
+
+ // Chart collection
+ $this->_chartCollection = new ArrayObject();
+
+ // Protection
+ $this->_protection = new PHPExcel_Worksheet_Protection();
+
+ // Default row dimension
+ $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);
+ }
+
+
+ /**
+ * Disconnect all cells from this PHPExcel_Worksheet object,
+ * typically so that the worksheet object can be unset
+ *
+ */
+ public function disconnectCells() {
+ 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;
+ }
+
+ /**
+ * Code to execute when this worksheet is unset()
+ *
+ */
+ function __destruct() {
+ PHPExcel_Calculation::getInstance($this->_parent)
+ ->clearCalculationCacheForWorksheet($this->_title);
+
+ $this->disconnectCells();
+ }
+
+ /**
+ * Return the cache controller for the cell collection
+ *
+ * @return PHPExcel_CachedObjectStorage_xxx
+ */
+ public function getCellCacheController() {
+ return $this->_cellCollection;
+ } // function getCellCacheController()
+
+
+ /**
+ * Get array of invalid characters for sheet title
+ *
+ * @return array
+ */
+ public static function getInvalidCharacters()
+ {
+ 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)
+ {
+ // Some of the printable ASCII characters are invalid: * : / \ ? [ ]
+ if (str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) {
+ throw new PHPExcel_Exception('Invalid character found in sheet title');
+ }
+
+ // Maximum 31 characters allowed for sheet title
+ if (PHPExcel_Shared_String::CountCharacters($pValue) > 31) {
+ throw new PHPExcel_Exception('Maximum 31 characters allowed in sheet title.');
+ }
+
+ return $pValue;
+ }
+
+ /**
+ * Get collection of cells
+ *
+ * @param boolean $pSorted Also sort the cell collection?
+ * @return PHPExcel_Cell[]
+ */
+ public function getCellCollection($pSorted = true)
+ {
+ if ($pSorted) {
+ // Re-order cell collection
+ return $this->sortCellCollection();
+ }
+ if ($this->_cellCollection !== NULL) {
+ return $this->_cellCollection->getCellList();
+ }
+ return array();
+ }
+
+ /**
+ * Sort collection of cells
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function sortCellCollection()
+ {
+ if ($this->_cellCollection !== NULL) {
+ return $this->_cellCollection->getSortedCellList();
+ }
+ return array();
+ }
+
+ /**
+ * Get collection of row dimensions
+ *
+ * @return PHPExcel_Worksheet_RowDimension[]
+ */
+ public function getRowDimensions()
+ {
+ return $this->_rowDimensions;
+ }
+
+ /**
+ * Get default row dimension
+ *
+ * @return PHPExcel_Worksheet_RowDimension
+ */
+ public function getDefaultRowDimension()
+ {
+ return $this->_defaultRowDimension;
+ }
+
+ /**
+ * Get collection of column dimensions
+ *
+ * @return PHPExcel_Worksheet_ColumnDimension[]
+ */
+ public function getColumnDimensions()
+ {
+ return $this->_columnDimensions;
+ }
+
+ /**
+ * Get default column dimension
+ *
+ * @return PHPExcel_Worksheet_ColumnDimension
+ */
+ public function getDefaultColumnDimension()
+ {
+ return $this->_defaultColumnDimension;
+ }
+
+ /**
+ * Get collection of drawings
+ *
+ * @return PHPExcel_Worksheet_BaseDrawing[]
+ */
+ public function getDrawingCollection()
+ {
+ return $this->_drawingCollection;
+ }
+
+ /**
+ * Get collection of charts
+ *
+ * @return PHPExcel_Chart[]
+ */
+ public function getChartCollection()
+ {
+ return $this->_chartCollection;
+ }
+
+ /**
+ * Add chart
+ *
+ * @param PHPExcel_Chart $pChart
+ * @param int|null $iChartIndex Index where chart should go (0,1,..., or null for last)
+ * @return PHPExcel_Chart
+ */
+ public function addChart(PHPExcel_Chart $pChart = null, $iChartIndex = null)
+ {
+ $pChart->setWorksheet($this);
+ if (is_null($iChartIndex)) {
+ $this->_chartCollection[] = $pChart;
+ } else {
+ // Insert the chart at the requested index
+ array_splice($this->_chartCollection, $iChartIndex, 0, array($pChart));
+ }
+
+ return $pChart;
+ }
+
+ /**
+ * Return the count of charts on this worksheet
+ *
+ * @return int The number of charts
+ */
+ public function getChartCount()
+ {
+ return count($this->_chartCollection);
+ }
+
+ /**
+ * Get a chart by its index position
+ *
+ * @param string $index Chart index position
+ * @return false|PHPExcel_Chart
+ * @throws PHPExcel_Exception
+ */
+ public function getChartByIndex($index = null)
+ {
+ $chartCount = count($this->_chartCollection);
+ if ($chartCount == 0) {
+ return false;
+ }
+ if (is_null($index)) {
+ $index = --$chartCount;
+ }
+ if (!isset($this->_chartCollection[$index])) {
+ return false;
+ }
+
+ return $this->_chartCollection[$index];
+ }
+
+ /**
+ * Return an array of the names of charts on this worksheet
+ *
+ * @return string[] The names of charts
+ * @throws PHPExcel_Exception
+ */
+ public function getChartNames()
+ {
+ $chartNames = array();
+ foreach($this->_chartCollection as $chart) {
+ $chartNames[] = $chart->getName();
+ }
+ return $chartNames;
+ }
+
+ /**
+ * Get a chart by name
+ *
+ * @param string $chartName Chart name
+ * @return false|PHPExcel_Chart
+ * @throws PHPExcel_Exception
+ */
+ public function getChartByName($chartName = '')
+ {
+ $chartCount = count($this->_chartCollection);
+ if ($chartCount == 0) {
+ return false;
+ }
+ foreach($this->_chartCollection as $index => $chart) {
+ if ($chart->getName() == $chartName) {
+ return $this->_chartCollection[$index];
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Refresh column dimensions
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function refreshColumnDimensions()
+ {
+ $currentColumnDimensions = $this->getColumnDimensions();
+ $newColumnDimensions = array();
+
+ foreach ($currentColumnDimensions as $objColumnDimension) {
+ $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
+ }
+
+ $this->_columnDimensions = $newColumnDimensions;
+
+ return $this;
+ }
+
+ /**
+ * Refresh row dimensions
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function refreshRowDimensions()
+ {
+ $currentRowDimensions = $this->getRowDimensions();
+ $newRowDimensions = array();
+
+ foreach ($currentRowDimensions as $objRowDimension) {
+ $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
+ }
+
+ $this->_rowDimensions = $newRowDimensions;
+
+ return $this;
+ }
+
+ /**
+ * Calculate worksheet dimension
+ *
+ * @return string String containing the dimension of this worksheet
+ */
+ public function calculateWorksheetDimension()
+ {
+ // Return
+ return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow();
+ }
+
+ /**
+ * Calculate worksheet data dimension
+ *
+ * @return string String containing the dimension of this worksheet that actually contain data
+ */
+ public function calculateWorksheetDataDimension()
+ {
+ // Return
+ return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow();
+ }
+
+ /**
+ * Calculate widths for auto-size columns
+ *
+ * @param boolean $calculateMergeCells Calculate merge cell width
+ * @return PHPExcel_Worksheet;
+ */
+ public function calculateColumnWidths($calculateMergeCells = false)
+ {
+ // initialize $autoSizes array
+ $autoSizes = array();
+ foreach ($this->getColumnDimensions() as $colDimension) {
+ if ($colDimension->getAutoSize()) {
+ $autoSizes[$colDimension->getColumnIndex()] = -1;
+ }
+ }
+
+ // There is only something to do if there are some auto-size columns
+ if (!empty($autoSizes)) {
+
+ // build list of cells references that participate in a merge
+ $isMergeCell = array();
+ foreach ($this->getMergeCells() as $cells) {
+ foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
+ $isMergeCell[$cellReference] = true;
+ }
+ }
+
+ // loop through all cells in the worksheet
+ foreach ($this->getCellCollection(false) as $cellID) {
+ $cell = $this->getCell($cellID);
+ if (isset($autoSizes[$this->_cellCollection->getCurrentColumn()])) {
+ // Determine width if cell does not participate in a merge
+ if (!isset($isMergeCell[$this->_cellCollection->getCurrentAddress()])) {
+ // Calculated value
+ // To formatted string
+ $cellValue = PHPExcel_Style_NumberFormat::toFormattedString(
+ $cell->getCalculatedValue(),
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
+ );
+
+ $autoSizes[$this->_cellCollection->getCurrentColumn()] = max(
+ (float) $autoSizes[$this->_cellCollection->getCurrentColumn()],
+ (float)PHPExcel_Shared_Font::calculateColumnWidth(
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
+ $cellValue,
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
+ $this->getDefaultStyle()->getFont()
+ )
+ );
+ }
+ }
+ }
+
+ // adjust column widths
+ foreach ($autoSizes as $columnIndex => $width) {
+ if ($width == -1) $width = $this->getDefaultColumnDimension()->getWidth();
+ $this->getColumnDimension($columnIndex)->setWidth($width);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get parent
+ *
+ * @return PHPExcel
+ */
+ public function getParent() {
+ return $this->_parent;
+ }
+
+ /**
+ * Re-bind parent
+ *
+ * @param PHPExcel $parent
+ * @return PHPExcel_Worksheet
+ */
+ public function rebindParent(PHPExcel $parent) {
+ 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;
+
+ return $this;
+ }
+
+ /**
+ * Get title
+ *
+ * @return string
+ */
+ public function getTitle()
+ {
+ return $this->_title;
+ }
+
+ /**
+ * Set title
+ *
+ * @param string $pValue String containing the dimension of this worksheet
+ * @param string $updateFormulaCellReferences boolean Flag indicating whether cell references in formulae should
+ * be updated to reflect the new sheet name.
+ * This should be left as the default true, unless you are
+ * certain that no formula cells on any worksheet contain
+ * references to this worksheet
+ * @return PHPExcel_Worksheet
+ */
+ public function setTitle($pValue = 'Worksheet', $updateFormulaCellReferences = true)
+ {
+ // Is this a 'rename' or not?
+ if ($this->getTitle() == $pValue) {
+ return $this;
+ }
+
+ // Syntax check
+ self::_checkSheetTitle($pValue);
+
+ // Old title
+ $oldTitle = $this->getTitle();
+
+ if ($this->_parent) {
+ // Is there already such sheet name?
+ if ($this->_parent->sheetNameExists($pValue)) {
+ // Use name, but append with lowest possible integer
+
+ if (PHPExcel_Shared_String::CountCharacters($pValue) > 29) {
+ $pValue = PHPExcel_Shared_String::Substring($pValue,0,29);
+ }
+ $i = 1;
+ while ($this->_parent->sheetNameExists($pValue . ' ' . $i)) {
+ ++$i;
+ if ($i == 10) {
+ if (PHPExcel_Shared_String::CountCharacters($pValue) > 28) {
+ $pValue = PHPExcel_Shared_String::Substring($pValue,0,28);
+ }
+ } elseif ($i == 100) {
+ if (PHPExcel_Shared_String::CountCharacters($pValue) > 27) {
+ $pValue = PHPExcel_Shared_String::Substring($pValue,0,27);
+ }
+ }
+ }
+
+ $altTitle = $pValue . ' ' . $i;
+ return $this->setTitle($altTitle,$updateFormulaCellReferences);
+ }
+ }
+
+ // Set title
+ $this->_title = $pValue;
+ $this->_dirty = true;
+
+ if ($this->_parent) {
+ // New title
+ $newTitle = $this->getTitle();
+ PHPExcel_Calculation::getInstance($this->_parent)
+ ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
+ if ($updateFormulaCellReferences)
+ PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->_parent, $oldTitle, $newTitle);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get sheet state
+ *
+ * @return string Sheet state (visible, hidden, veryHidden)
+ */
+ public function getSheetState() {
+ return $this->_sheetState;
+ }
+
+ /**
+ * Set sheet state
+ *
+ * @param string $value Sheet state (visible, hidden, veryHidden)
+ * @return PHPExcel_Worksheet
+ */
+ public function setSheetState($value = PHPExcel_Worksheet::SHEETSTATE_VISIBLE) {
+ $this->_sheetState = $value;
+ return $this;
+ }
+
+ /**
+ * Get page setup
+ *
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function getPageSetup()
+ {
+ return $this->_pageSetup;
+ }
+
+ /**
+ * Set page setup
+ *
+ * @param PHPExcel_Worksheet_PageSetup $pValue
+ * @return PHPExcel_Worksheet
+ */
+ public function setPageSetup(PHPExcel_Worksheet_PageSetup $pValue)
+ {
+ $this->_pageSetup = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get page margins
+ *
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ public function getPageMargins()
+ {
+ return $this->_pageMargins;
+ }
+
+ /**
+ * Set page margins
+ *
+ * @param PHPExcel_Worksheet_PageMargins $pValue
+ * @return PHPExcel_Worksheet
+ */
+ public function setPageMargins(PHPExcel_Worksheet_PageMargins $pValue)
+ {
+ $this->_pageMargins = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get page header/footer
+ *
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function getHeaderFooter()
+ {
+ return $this->_headerFooter;
+ }
+
+ /**
+ * Set page header/footer
+ *
+ * @param PHPExcel_Worksheet_HeaderFooter $pValue
+ * @return PHPExcel_Worksheet
+ */
+ public function setHeaderFooter(PHPExcel_Worksheet_HeaderFooter $pValue)
+ {
+ $this->_headerFooter = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get sheet view
+ *
+ * @return PHPExcel_Worksheet_SheetView
+ */
+ public function getSheetView()
+ {
+ return $this->_sheetView;
+ }
+
+ /**
+ * Set sheet view
+ *
+ * @param PHPExcel_Worksheet_SheetView $pValue
+ * @return PHPExcel_Worksheet
+ */
+ public function setSheetView(PHPExcel_Worksheet_SheetView $pValue)
+ {
+ $this->_sheetView = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Protection
+ *
+ * @return PHPExcel_Worksheet_Protection
+ */
+ public function getProtection()
+ {
+ return $this->_protection;
+ }
+
+ /**
+ * Set Protection
+ *
+ * @param PHPExcel_Worksheet_Protection $pValue
+ * @return PHPExcel_Worksheet
+ */
+ public function setProtection(PHPExcel_Worksheet_Protection $pValue)
+ {
+ $this->_protection = $pValue;
+ $this->_dirty = true;
+
+ return $this;
+ }
+
+ /**
+ * 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($row = null)
+ {
+ 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($row = null)
+ {
+ 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($column = null)
+ {
+ 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($column = null)
+ {
+ return $this->_cellCollection->getHighestRow($column);
+ }
+
+ /**
+ * Get highest worksheet column and highest row that have cell records
+ *
+ * @return array Highest column name and highest row number
+ */
+ public function getHighestRowAndColumn()
+ {
+ return $this->_cellCollection->getHighestRowAndColumn();
+ }
+
+ /**
+ * Set a cell value
+ *
+ * @param string $pCoordinate Coordinate of the cell
+ * @param mixed $pValue Value of the cell
+ * @param bool $returnCell Return the worksheet (false, default) or the cell (true)
+ * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified
+ */
+ public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell = false)
+ {
+ $cell = $this->getCell($pCoordinate)->setValue($pValue);
+ return ($returnCell) ? $cell : $this;
+ }
+
+ /**
+ * Set a cell value by using numeric cell coordinates
+ *
+ * @param string $pColumn Numeric column coordinate of the cell (A = 0)
+ * @param string $pRow Numeric row coordinate of the cell
+ * @param mixed $pValue Value of the cell
+ * @param bool $returnCell Return the worksheet (false, default) or the cell (true)
+ * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified
+ */
+ public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $returnCell = false)
+ {
+ $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValue($pValue);
+ return ($returnCell) ? $cell : $this;
+ }
+
+ /**
+ * Set a cell value
+ *
+ * @param string $pCoordinate Coordinate of the cell
+ * @param mixed $pValue Value of the cell
+ * @param string $pDataType Explicit data type
+ * @param bool $returnCell Return the worksheet (false, default) or the cell (true)
+ * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified
+ */
+ public function setCellValueExplicit($pCoordinate = 'A1', $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false)
+ {
+ // Set value
+ $cell = $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
+ return ($returnCell) ? $cell : $this;
+ }
+
+ /**
+ * Set a cell value by using numeric cell coordinates
+ *
+ * @param string $pColumn Numeric column coordinate of the cell
+ * @param string $pRow Numeric row coordinate of the cell
+ * @param mixed $pValue Value of the cell
+ * @param string $pDataType Explicit data type
+ * @param bool $returnCell Return the worksheet (false, default) or the cell (true)
+ * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified
+ */
+ public function setCellValueExplicitByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false)
+ {
+ $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValueExplicit($pValue, $pDataType);
+ return ($returnCell) ? $cell : $this;
+ }
+
+ /**
+ * Get cell at a specific coordinate
+ *
+ * @param string $pCoordinate Coordinate of the cell
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Cell Cell that was found
+ */
+ public function getCell($pCoordinate = 'A1')
+ {
+ // Check cell collection
+ if ($this->_cellCollection->isDataSet($pCoordinate)) {
+ return $this->_cellCollection->getCacheData($pCoordinate);
+ }
+
+ // Worksheet reference?
+ if (strpos($pCoordinate, '!') !== false) {
+ $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true);
+ return $this->_parent->getSheetByName($worksheetReference[0])->getCell($worksheetReference[1]);
+ }
+
+ // Named range?
+ if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) &&
+ (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) {
+ $namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this);
+ if ($namedRange !== NULL) {
+ $pCoordinate = $namedRange->getRange();
+ return $namedRange->getWorksheet()->getCell($pCoordinate);
+ }
+ }
+
+ // Uppercase coordinate
+ $pCoordinate = strtoupper($pCoordinate);
+
+ if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) {
+ throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.');
+ } elseif (strpos($pCoordinate, '$') !== false) {
+ throw new PHPExcel_Exception('Cell coordinate must not be absolute.');
+ }
+
+ // Create new cell object
+ return $this->_createNewCell($pCoordinate);
+ }
+
+ /**
+ * Get cell at a specific coordinate by using numeric cell coordinates
+ *
+ * @param string $pColumn Numeric column coordinate of the cell
+ * @param string $pRow Numeric row coordinate of the cell
+ * @return PHPExcel_Cell Cell that was found
+ */
+ public function getCellByColumnAndRow($pColumn = 0, $pRow = 1)
+ {
+ $columnLetter = PHPExcel_Cell::stringFromColumnIndex($pColumn);
+ $coordinate = $columnLetter . $pRow;
+
+ if ($this->_cellCollection->isDataSet($coordinate)) {
+ return $this->_cellCollection->getCacheData($coordinate);
+ }
+
+ return $this->_createNewCell($coordinate);
+ }
+
+ /**
+ * 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;
+
+ // 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]);
+
+ // 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;
+ }
+
+ /**
+ * Does the cell at a specific coordinate exist?
+ *
+ * @param string $pCoordinate Coordinate of the cell
+ * @throws PHPExcel_Exception
+ * @return boolean
+ */
+ public function cellExists($pCoordinate = 'A1')
+ {
+ // Worksheet reference?
+ if (strpos($pCoordinate, '!') !== false) {
+ $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true);
+ return $this->_parent->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]);
+ }
+
+ // Named range?
+ if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) &&
+ (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) {
+ $namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this);
+ if ($namedRange !== NULL) {
+ $pCoordinate = $namedRange->getRange();
+ if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {
+ if (!$namedRange->getLocalOnly()) {
+ return $namedRange->getWorksheet()->cellExists($pCoordinate);
+ } else {
+ throw new PHPExcel_Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());
+ }
+ }
+ }
+ else { return false; }
+ }
+
+ // Uppercase coordinate
+ $pCoordinate = strtoupper($pCoordinate);
+
+ if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
+ throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.');
+ } 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);
+ }
+ }
+
+ /**
+ * Cell at a specific coordinate by using numeric cell coordinates exists?
+ *
+ * @param string $pColumn Numeric column coordinate of the cell
+ * @param string $pRow Numeric row coordinate of the cell
+ * @return boolean
+ */
+ public function cellExistsByColumnAndRow($pColumn = 0, $pRow = 1)
+ {
+ return $this->cellExists(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow);
+ }
+
+ /**
+ * Get row dimension at a specific row
+ *
+ * @param int $pRow Numeric index of the row
+ * @return PHPExcel_Worksheet_RowDimension
+ */
+ public function getRowDimension($pRow = 1, $create = TRUE)
+ {
+ // Found
+ $found = null;
+
+ // Get row dimension
+ if (!isset($this->_rowDimensions[$pRow])) {
+ if (!$create)
+ return NULL;
+ $this->_rowDimensions[$pRow] = new PHPExcel_Worksheet_RowDimension($pRow);
+
+ $this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow);
+ }
+ return $this->_rowDimensions[$pRow];
+ }
+
+ /**
+ * Get column dimension at a specific column
+ *
+ * @param string $pColumn String index of the column
+ * @return PHPExcel_Worksheet_ColumnDimension
+ */
+ public function getColumnDimension($pColumn = 'A', $create = TRUE)
+ {
+ // Uppercase coordinate
+ $pColumn = strtoupper($pColumn);
+
+ // Fetch dimensions
+ 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;
+ }
+ return $this->_columnDimensions[$pColumn];
+ }
+
+ /**
+ * Get column dimension at a specific column by using numeric cell coordinates
+ *
+ * @param string $pColumn Numeric column coordinate of the cell
+ * @return PHPExcel_Worksheet_ColumnDimension
+ */
+ public function getColumnDimensionByColumn($pColumn = 0)
+ {
+ return $this->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($pColumn));
+ }
+
+ /**
+ * Get styles
+ *
+ * @return PHPExcel_Style[]
+ */
+ public function getStyles()
+ {
+ return $this->_styles;
+ }
+
+ /**
+ * Get default style of workbook.
+ *
+ * @deprecated
+ * @return PHPExcel_Style
+ * @throws PHPExcel_Exception
+ */
+ public function getDefaultStyle()
+ {
+ return $this->_parent->getDefaultStyle();
+ }
+
+ /**
+ * Set default style - should only be used by PHPExcel_IReader implementations!
+ *
+ * @deprecated
+ * @param PHPExcel_Style $pValue
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function setDefaultStyle(PHPExcel_Style $pValue)
+ {
+ $this->_parent->getDefaultStyle()->applyFromArray(array(
+ 'font' => array(
+ 'name' => $pValue->getFont()->getName(),
+ 'size' => $pValue->getFont()->getSize(),
+ ),
+ ));
+ return $this;
+ }
+
+ /**
+ * Get style for cell
+ *
+ * @param string $pCellCoordinate Cell coordinate 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));
+
+ // set cell coordinate as active
+ $this->setSelectedCells($pCellCoordinate);
+
+ return $this->_parent->getCellXfSupervisor();
+ }
+
+ /**
+ * Get conditional styles for a cell
+ *
+ * @param string $pCoordinate
+ * @return PHPExcel_Style_Conditional[]
+ */
+ public function getConditionalStyles($pCoordinate = 'A1')
+ {
+ if (!isset($this->_conditionalStylesCollection[$pCoordinate])) {
+ $this->_conditionalStylesCollection[$pCoordinate] = array();
+ }
+ return $this->_conditionalStylesCollection[$pCoordinate];
+ }
+
+ /**
+ * Do conditional styles exist for this cell?
+ *
+ * @param string $pCoordinate
+ * @return boolean
+ */
+ public function conditionalStylesExists($pCoordinate = 'A1')
+ {
+ if (isset($this->_conditionalStylesCollection[$pCoordinate])) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Removes conditional styles for a cell
+ *
+ * @param string $pCoordinate
+ * @return PHPExcel_Worksheet
+ */
+ public function removeConditionalStyles($pCoordinate = 'A1')
+ {
+ unset($this->_conditionalStylesCollection[$pCoordinate]);
+ return $this;
+ }
+
+ /**
+ * Get collection of conditional styles
+ *
+ * @return array
+ */
+ public function getConditionalStylesCollection()
+ {
+ return $this->_conditionalStylesCollection;
+ }
+
+ /**
+ * Set conditional styles
+ *
+ * @param $pCoordinate string E.g. 'A1'
+ * @param $pValue PHPExcel_Style_Conditional[]
+ * @return PHPExcel_Worksheet
+ */
+ public function setConditionalStyles($pCoordinate = 'A1', $pValue)
+ {
+ $this->_conditionalStylesCollection[$pCoordinate] = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get style for cell by using numeric cell coordinates
+ *
+ * @param int $pColumn Numeric column coordinate of the cell
+ * @param int $pRow Numeric row coordinate of the cell
+ * @return PHPExcel_Style
+ */
+ public function getStyleByColumnAndRow($pColumn = 0, $pRow = 1)
+ {
+ return $this->getStyle(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow);
+ }
+
+ /**
+ * Set shared cell style to a range of cells
+ *
+ * Please note that this will overwrite existing cell styles for cells in range!
+ *
+ * @deprecated
+ * @param PHPExcel_Style $pSharedCellStyle Cell style to share
+ * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function setSharedStyle(PHPExcel_Style $pSharedCellStyle = null, $pRange = '')
+ {
+ $this->duplicateStyle($pSharedCellStyle, $pRange);
+ return $this;
+ }
+
+ /**
+ * Duplicate cell style to a range of cells
+ *
+ * Please note that this will overwrite existing cell styles for cells in range!
+ *
+ * @param PHPExcel_Style $pCellStyle Cell style to duplicate
+ * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '')
+ {
+ // make sure we have a real style and not supervisor
+ $style = $pCellStyle->getIsSupervisor() ? $pCellStyle->getSharedComponent() : $pCellStyle;
+
+ // Add the style to the workbook if necessary
+ $workbook = $this->_parent;
+ if ($existingStyle = $this->_parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
+ // there is already such cell Xf in our collection
+ $xfIndex = $existingStyle->getIndex();
+ } else {
+ // we don't have such a cell Xf, need to add
+ $workbook->addCellXf($pCellStyle);
+ $xfIndex = $pCellStyle->getIndex();
+ }
+
+ // Calculate range outer borders
+ 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]) {
+ $tmp = $rangeStart;
+ $rangeStart = $rangeEnd;
+ $rangeEnd = $tmp;
+ }
+
+ // 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 - 1) . $row)->setXfIndex($xfIndex);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Duplicate conditional style to a range of cells
+ *
+ * Please note that this will overwrite existing cell styles for cells in range!
+ *
+ * @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) {
+ if (!($cellStyle instanceof PHPExcel_Style_Conditional)) {
+ throw new PHPExcel_Exception('Style is not a conditional style');
+ }
+ }
+
+ // Calculate range outer borders
+ 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]) {
+ $tmp = $rangeStart;
+ $rangeStart = $rangeEnd;
+ $rangeEnd = $tmp;
+ }
+
+ // 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 - 1) . $row, $pCellStyle);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Duplicate cell style array to a range of cells
+ *
+ * Please note that this will overwrite existing cell styles for cells in range,
+ * if they are in the styles array. For example, if you decide to set a range of
+ * cells to font bold, only include font bold in the styles array.
+ *
+ * @deprecated
+ * @param array $pStyles Array containing style information
+ * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @param boolean $pAdvanced Advanced mode for setting borders.
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function duplicateStyleArray($pStyles = null, $pRange = '', $pAdvanced = true)
+ {
+ $this->getStyle($pRange)->applyFromArray($pStyles, $pAdvanced);
+ return $this;
+ }
+
+ /**
+ * Set break on a cell
+ *
+ * @param string $pCell Cell coordinate (e.g. A1)
+ * @param int $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function setBreak($pCell = 'A1', $pBreak = PHPExcel_Worksheet::BREAK_NONE)
+ {
+ // Uppercase coordinate
+ $pCell = strtoupper($pCell);
+
+ if ($pCell != '') {
+ 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.');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Set break on a cell by using numeric cell coordinates
+ *
+ * @param integer $pColumn Numeric column coordinate of the cell
+ * @param integer $pRow Numeric row coordinate of the cell
+ * @param integer $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*)
+ * @return PHPExcel_Worksheet
+ */
+ public function setBreakByColumnAndRow($pColumn = 0, $pRow = 1, $pBreak = PHPExcel_Worksheet::BREAK_NONE)
+ {
+ return $this->setBreak(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow, $pBreak);
+ }
+
+ /**
+ * Get breaks
+ *
+ * @return array[]
+ */
+ public function getBreaks()
+ {
+ return $this->_breaks;
+ }
+
+ /**
+ * Set merge on a cell range
+ *
+ * @param string $pRange Cell range (e.g. A1:E1)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function mergeCells($pRange = 'A1:A1')
+ {
+ // Uppercase coordinate
+ $pRange = strtoupper($pRange);
+
+ if (strpos($pRange,':') !== false) {
+ $this->_mergeCells[$pRange] = $pRange;
+
+ // make sure cells are created
+
+ // get the cells in the range
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
+
+ // create upper left cell if it does not already exist
+ $upperLeft = $aReferences[0];
+ if (!$this->cellExists($upperLeft)) {
+ $this->getCell($upperLeft)->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL);
+ }
+
+ // create or blank out the rest of the cells in the range
+ $count = count($aReferences);
+ for ($i = 1; $i < $count; $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.');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Set merge on a cell range by using numeric cell coordinates
+ *
+ * @param int $pColumn1 Numeric column coordinate of the first cell
+ * @param int $pRow1 Numeric row coordinate of the first cell
+ * @param int $pColumn2 Numeric column coordinate of the last cell
+ * @param int $pRow2 Numeric row coordinate of the last cell
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function mergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1)
+ {
+ $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2;
+ return $this->mergeCells($cellRange);
+ }
+
+ /**
+ * Remove merge on a cell range
+ *
+ * @param string $pRange Cell range (e.g. A1:E1)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function unmergeCells($pRange = 'A1:A1')
+ {
+ // Uppercase coordinate
+ $pRange = strtoupper($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.');
+ }
+ } else {
+ throw new PHPExcel_Exception('Merge can only be removed from a range of cells.');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Remove merge on a cell range by using numeric cell coordinates
+ *
+ * @param int $pColumn1 Numeric column coordinate of the first cell
+ * @param int $pRow1 Numeric row coordinate of the first cell
+ * @param int $pColumn2 Numeric column coordinate of the last cell
+ * @param int $pRow2 Numeric row coordinate of the last cell
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function unmergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1)
+ {
+ $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2;
+ return $this->unmergeCells($cellRange);
+ }
+
+ /**
+ * Get merge cells array.
+ *
+ * @return array[]
+ */
+ public function getMergeCells()
+ {
+ return $this->_mergeCells;
+ }
+
+ /**
+ * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
+ * a single cell range.
+ *
+ * @param array
+ */
+ public function setMergeCells($pValue = array())
+ {
+ $this->_mergeCells = $pValue;
+
+ return $this;
+ }
+
+ /**
+ * Set protection on a cell range
+ *
+ * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
+ * @param string $pPassword Password to unlock the protection
+ * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function protectCells($pRange = 'A1', $pPassword = '', $pAlreadyHashed = false)
+ {
+ // Uppercase coordinate
+ $pRange = strtoupper($pRange);
+
+ if (!$pAlreadyHashed) {
+ $pPassword = PHPExcel_Shared_PasswordHasher::hashPassword($pPassword);
+ }
+ $this->_protectedCells[$pRange] = $pPassword;
+
+ return $this;
+ }
+
+ /**
+ * Set protection on a cell range by using numeric cell coordinates
+ *
+ * @param int $pColumn1 Numeric column coordinate of the first cell
+ * @param int $pRow1 Numeric row coordinate of the first cell
+ * @param int $pColumn2 Numeric column coordinate of the last cell
+ * @param int $pRow2 Numeric row coordinate of the last cell
+ * @param string $pPassword Password to unlock the protection
+ * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function protectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false)
+ {
+ $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2;
+ return $this->protectCells($cellRange, $pPassword, $pAlreadyHashed);
+ }
+
+ /**
+ * Remove protection on a cell range
+ *
+ * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function unprotectCells($pRange = 'A1')
+ {
+ // Uppercase coordinate
+ $pRange = strtoupper($pRange);
+
+ if (isset($this->_protectedCells[$pRange])) {
+ unset($this->_protectedCells[$pRange]);
+ } else {
+ throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as protected.');
+ }
+ return $this;
+ }
+
+ /**
+ * Remove protection on a cell range by using numeric cell coordinates
+ *
+ * @param int $pColumn1 Numeric column coordinate of the first cell
+ * @param int $pRow1 Numeric row coordinate of the first cell
+ * @param int $pColumn2 Numeric column coordinate of the last cell
+ * @param int $pRow2 Numeric row coordinate of the last cell
+ * @param string $pPassword Password to unlock the protection
+ * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false)
+ {
+ $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2;
+ return $this->unprotectCells($cellRange, $pPassword, $pAlreadyHashed);
+ }
+
+ /**
+ * Get protected cells
+ *
+ * @return array[]
+ */
+ public function getProtectedCells()
+ {
+ return $this->_protectedCells;
+ }
+
+ /**
+ * Get Autofilter
+ *
+ * @return PHPExcel_Worksheet_AutoFilter
+ */
+ public function getAutoFilter()
+ {
+ return $this->_autoFilter;
+ }
+
+ /**
+ * Set AutoFilter
+ *
+ * @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)
+ {
+ if (is_string($pValue)) {
+ $this->_autoFilter->setRange($pValue);
+ } elseif(is_object($pValue) && ($pValue instanceof PHPExcel_Worksheet_AutoFilter)) {
+ $this->_autoFilter = $pValue;
+ }
+ return $this;
+ }
+
+ /**
+ * Set Autofilter Range by using numeric cell coordinates
+ *
+ * @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
+ */
+ public function setAutoFilterByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1)
+ {
+ return $this->setAutoFilter(
+ PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1
+ . ':' .
+ PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2
+ );
+ }
+
+ /**
+ * Remove autofilter
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function removeAutoFilter()
+ {
+ $this->_autoFilter->setRange(NULL);
+ return $this;
+ }
+
+ /**
+ * Get Freeze Pane
+ *
+ * @return string
+ */
+ public function getFreezePane()
+ {
+ return $this->_freezePane;
+ }
+
+ /**
+ * Freeze Pane
+ *
+ * @param string $pCell Cell (i.e. A2)
+ * Examples:
+ * A2 will freeze the rows above cell A2 (i.e row 1)
+ * B1 will freeze the columns to the left of cell B1 (i.e column A)
+ * B2 will freeze the rows above and to the left of cell A2
+ * (i.e row 1 and column A)
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function freezePane($pCell = '')
+ {
+ // Uppercase coordinate
+ $pCell = strtoupper($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.');
+ }
+ return $this;
+ }
+
+ /**
+ * Freeze Pane by using numeric cell coordinates
+ *
+ * @param int $pColumn Numeric column coordinate of the cell
+ * @param int $pRow Numeric row coordinate of the cell
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function freezePaneByColumnAndRow($pColumn = 0, $pRow = 1)
+ {
+ return $this->freezePane(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow);
+ }
+
+ /**
+ * Unfreeze Pane
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function unfreezePane()
+ {
+ return $this->freezePane('');
+ }
+
+ /**
+ * Insert a new row, updating all possible related data
+ *
+ * @param int $pBefore Insert before this one
+ * @param int $pNumRows Number of rows to insert
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function insertNewRowBefore($pBefore = 1, $pNumRows = 1) {
+ if ($pBefore >= 1) {
+ $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
+ $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
+ } else {
+ throw new PHPExcel_Exception("Rows can only be inserted before at least row 1.");
+ }
+ return $this;
+ }
+
+ /**
+ * Insert a new column, updating all possible related data
+ *
+ * @param int $pBefore Insert before this one
+ * @param int $pNumCols Number of columns to insert
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1) {
+ if (!is_numeric($pBefore)) {
+ $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
+ $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
+ } else {
+ throw new PHPExcel_Exception("Column references should not be numeric.");
+ }
+ return $this;
+ }
+
+ /**
+ * Insert a new column, updating all possible related data
+ *
+ * @param int $pBefore Insert before this one (numeric column coordinate of the cell)
+ * @param int $pNumCols Number of columns to insert
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1) {
+ if ($pBefore >= 0) {
+ return $this->insertNewColumnBefore(PHPExcel_Cell::stringFromColumnIndex($pBefore), $pNumCols);
+ } else {
+ throw new PHPExcel_Exception("Columns can only be inserted before at least column A (0).");
+ }
+ }
+
+ /**
+ * Delete a row, updating all possible related data
+ *
+ * @param int $pRow Remove starting with this one
+ * @param int $pNumRows Number of rows to remove
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function removeRow($pRow = 1, $pNumRows = 1) {
+ if ($pRow >= 1) {
+ $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
+ $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this);
+ } else {
+ throw new PHPExcel_Exception("Rows to be deleted should at least start from row 1.");
+ }
+ return $this;
+ }
+
+ /**
+ * Remove a column, updating all possible related data
+ *
+ * @param int $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) {
+ if (!is_numeric($pColumn)) {
+ $pColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($pColumn) - 1 + $pNumCols);
+ $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance();
+ $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this);
+ } else {
+ throw new PHPExcel_Exception("Column references should not be numeric.");
+ }
+ return $this;
+ }
+
+ /**
+ * Remove a column, updating all possible related data
+ *
+ * @param int $pColumn Remove starting with this one (numeric column coordinate of the cell)
+ * @param int $pNumCols Number of columns to remove
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function removeColumnByIndex($pColumn = 0, $pNumCols = 1) {
+ if ($pColumn >= 0) {
+ return $this->removeColumn(PHPExcel_Cell::stringFromColumnIndex($pColumn), $pNumCols);
+ } else {
+ throw new PHPExcel_Exception("Columns to be deleted should at least start from column 0");
+ }
+ }
+
+ /**
+ * Show gridlines?
+ *
+ * @return boolean
+ */
+ public function getShowGridlines() {
+ return $this->_showGridlines;
+ }
+
+ /**
+ * Set show gridlines
+ *
+ * @param boolean $pValue Show gridlines (true/false)
+ * @return PHPExcel_Worksheet
+ */
+ public function setShowGridlines($pValue = false) {
+ $this->_showGridlines = $pValue;
+ return $this;
+ }
+
+ /**
+ * Print gridlines?
+ *
+ * @return boolean
+ */
+ public function getPrintGridlines() {
+ return $this->_printGridlines;
+ }
+
+ /**
+ * Set print gridlines
+ *
+ * @param boolean $pValue Print gridlines (true/false)
+ * @return PHPExcel_Worksheet
+ */
+ public function setPrintGridlines($pValue = false) {
+ $this->_printGridlines = $pValue;
+ return $this;
+ }
+
+ /**
+ * Show row and column headers?
+ *
+ * @return boolean
+ */
+ public function getShowRowColHeaders() {
+ return $this->_showRowColHeaders;
+ }
+
+ /**
+ * Set show row and column headers
+ *
+ * @param boolean $pValue Show row and column headers (true/false)
+ * @return PHPExcel_Worksheet
+ */
+ public function setShowRowColHeaders($pValue = false) {
+ $this->_showRowColHeaders = $pValue;
+ return $this;
+ }
+
+ /**
+ * Show summary below? (Row/Column outlining)
+ *
+ * @return boolean
+ */
+ public function getShowSummaryBelow() {
+ return $this->_showSummaryBelow;
+ }
+
+ /**
+ * Set show summary below
+ *
+ * @param boolean $pValue Show summary below (true/false)
+ * @return PHPExcel_Worksheet
+ */
+ public function setShowSummaryBelow($pValue = true) {
+ $this->_showSummaryBelow = $pValue;
+ return $this;
+ }
+
+ /**
+ * Show summary right? (Row/Column outlining)
+ *
+ * @return boolean
+ */
+ public function getShowSummaryRight() {
+ return $this->_showSummaryRight;
+ }
+
+ /**
+ * Set show summary right
+ *
+ * @param boolean $pValue Show summary right (true/false)
+ * @return PHPExcel_Worksheet
+ */
+ public function setShowSummaryRight($pValue = true) {
+ $this->_showSummaryRight = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get comments
+ *
+ * @return PHPExcel_Comment[]
+ */
+ public function getComments()
+ {
+ return $this->_comments;
+ }
+
+ /**
+ * Set comments array for the entire sheet.
+ *
+ * @param array of PHPExcel_Comment
+ * @return PHPExcel_Worksheet
+ */
+ public function setComments($pValue = array())
+ {
+ $this->_comments = $pValue;
+
+ return $this;
+ }
+
+ /**
+ * Get comment for cell
+ *
+ * @param string $pCellCoordinate Cell coordinate to get comment for
+ * @return PHPExcel_Comment
+ * @throws PHPExcel_Exception
+ */
+ public function getComment($pCellCoordinate = 'A1')
+ {
+ // Uppercase coordinate
+ $pCellCoordinate = strtoupper($pCellCoordinate);
+
+ 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) {
+ throw new PHPExcel_Exception('Cell coordinate string must not be absolute.');
+ } else if ($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];
+ } else {
+ $newComment = new PHPExcel_Comment();
+ $this->_comments[$pCellCoordinate] = $newComment;
+ return $newComment;
+ }
+ }
+ }
+
+ /**
+ * Get comment for cell by using numeric cell coordinates
+ *
+ * @param int $pColumn Numeric column coordinate of the cell
+ * @param int $pRow Numeric row coordinate of the cell
+ * @return PHPExcel_Comment
+ */
+ public function getCommentByColumnAndRow($pColumn = 0, $pRow = 1)
+ {
+ return $this->getComment(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow);
+ }
+
+ /**
+ * Get selected cell
+ *
+ * @deprecated
+ * @return string
+ */
+ public function getSelectedCell()
+ {
+ return $this->getSelectedCells();
+ }
+
+ /**
+ * Get active cell
+ *
+ * @return string Example: 'A1'
+ */
+ public function getActiveCell()
+ {
+ return $this->_activeCell;
+ }
+
+ /**
+ * Get selected cells
+ *
+ * @return string
+ */
+ public function getSelectedCells()
+ {
+ return $this->_selectedCells;
+ }
+
+ /**
+ * Selected cell
+ *
+ * @param string $pCoordinate Cell (i.e. A1)
+ * @return PHPExcel_Worksheet
+ */
+ public function setSelectedCell($pCoordinate = 'A1')
+ {
+ return $this->setSelectedCells($pCoordinate);
+ }
+
+ /**
+ * Select a range of cells.
+ *
+ * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function setSelectedCells($pCoordinate = 'A1')
+ {
+ // Uppercase coordinate
+ $pCoordinate = strtoupper($pCoordinate);
+
+ // Convert 'A' to 'A:A'
+ $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate);
+
+ // Convert '1' to '1:1'
+ $pCoordinate = preg_replace('/^([0-9]+)$/', '${1}:${1}', $pCoordinate);
+
+ // Convert 'A:C' to 'A1:C1048576'
+ $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate);
+
+ // Convert '1:3' to 'A1:XFD3'
+ $pCoordinate = preg_replace('/^([0-9]+):([0-9]+)$/', 'A${1}:XFD${2}', $pCoordinate);
+
+ if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {
+ list($first, ) = PHPExcel_Cell::splitRange($pCoordinate);
+ $this->_activeCell = $first[0];
+ } else {
+ $this->_activeCell = $pCoordinate;
+ }
+ $this->_selectedCells = $pCoordinate;
+ return $this;
+ }
+
+ /**
+ * Selected cell by using numeric cell coordinates
+ *
+ * @param int $pColumn Numeric column coordinate of the cell
+ * @param int $pRow Numeric row coordinate of the cell
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ public function setSelectedCellByColumnAndRow($pColumn = 0, $pRow = 1)
+ {
+ return $this->setSelectedCells(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow);
+ }
+
+ /**
+ * Get right-to-left
+ *
+ * @return boolean
+ */
+ public function getRightToLeft() {
+ return $this->_rightToLeft;
+ }
+
+ /**
+ * Set right-to-left
+ *
+ * @param boolean $value Right-to-left true/false
+ * @return PHPExcel_Worksheet
+ */
+ public function setRightToLeft($value = false) {
+ $this->_rightToLeft = $value;
+ return $this;
+ }
+
+ /**
+ * Fill worksheet from values in array
+ *
+ * @param array $source Source array
+ * @param mixed $nullValue Value in source array that stands for blank cell
+ * @param string $startCell Insert array starting from this cell address as the top left coordinate
+ * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet
+ */
+ 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))) {
+ $source = array($source);
+ }
+
+ // start coordinate
+ list ($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($startCell);
+
+ // Loop through $source
+ foreach ($source as $rowData) {
+ $currentColumn = $startColumn;
+ foreach($rowData as $cellValue) {
+ if ($strictNullComparison) {
+ if ($cellValue !== $nullValue) {
+ // Set cell value
+ $this->getCell($currentColumn . $startRow)->setValue($cellValue);
+ }
+ } else {
+ if ($cellValue != $nullValue) {
+ // Set cell value
+ $this->getCell($currentColumn . $startRow)->setValue($cellValue);
+ }
+ }
+ ++$currentColumn;
+ }
+ ++$startRow;
+ }
+ } else {
+ throw new PHPExcel_Exception("Parameter \$source should be an array.");
+ }
+ return $this;
+ }
+
+ /**
+ * Create array from a range of cells
+ *
+ * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
+ * @param boolean $calculateFormulas Should formulas be calculated?
+ * @param boolean $formatData Should formatting be applied to cell values?
+ * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
+ * True - Return rows and columns indexed by their actual row and column IDs
+ * @return array
+ */
+ public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
+ // Returnvalue
+ $returnValue = array();
+ // Identify the range that we need to extract from the worksheet
+ list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange);
+ $minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1);
+ $minRow = $rangeStart[1];
+ $maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1);
+ $maxRow = $rangeEnd[1];
+
+ $maxCol++;
+ // Loop through rows
+ $r = -1;
+ for ($row = $minRow; $row <= $maxRow; ++$row) {
+ $rRef = ($returnCellRef) ? $row : ++$r;
+ $c = -1;
+ // Loop through columns in the current row
+ 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)) {
+ // Cell exists
+ $cell = $this->_cellCollection->getCacheData($col.$row);
+ if ($cell->getValue() !== null) {
+ if ($cell->getValue() instanceof PHPExcel_RichText) {
+ $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
+ } else {
+ if ($calculateFormulas) {
+ $returnValue[$rRef][$cRef] = $cell->getCalculatedValue();
+ } else {
+ $returnValue[$rRef][$cRef] = $cell->getValue();
+ }
+ }
+
+ if ($formatData) {
+ $style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
+ $returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString(
+ $returnValue[$rRef][$cRef],
+ ($style && $style->getNumberFormat()) ?
+ $style->getNumberFormat()->getFormatCode() :
+ PHPExcel_Style_NumberFormat::FORMAT_GENERAL
+ );
+ }
+ } else {
+ // Cell holds a NULL
+ $returnValue[$rRef][$cRef] = $nullValue;
+ }
+ } else {
+ // Cell doesn't exist
+ $returnValue[$rRef][$cRef] = $nullValue;
+ }
+ }
+ }
+
+ // Return
+ return $returnValue;
+ }
+
+
+ /**
+ * Create array from a range of cells
+ *
+ * @param string $pNamedRange Name of the Named Range
+ * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
+ * @param boolean $calculateFormulas Should formulas be calculated?
+ * @param boolean $formatData Should formatting be applied to cell values?
+ * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
+ * True - Return rows and columns indexed by their actual row and column IDs
+ * @return array
+ * @throws PHPExcel_Exception
+ */
+ 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);
+ }
+
+ throw new PHPExcel_Exception('Named Range '.$pNamedRange.' does not exist.');
+ }
+
+
+ /**
+ * Create array from worksheet
+ *
+ * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
+ * @param boolean $calculateFormulas Should formulas be calculated?
+ * @param boolean $formatData Should formatting be applied to cell values?
+ * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
+ * True - Return rows and columns indexed by their actual row and column IDs
+ * @return array
+ */
+ public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
+ // Garbage collect...
+ $this->garbageCollect();
+
+ // Identify the range that we need to extract from the worksheet
+ $maxCol = $this->getHighestColumn();
+ $maxRow = $this->getHighestRow();
+ // Return
+ return $this->rangeToArray( 'A1:'.$maxCol.$maxRow,
+ $nullValue, $calculateFormulas, $formatData, $returnCellRef);
+ }
+
+ /**
+ * Get row iterator
+ *
+ * @param integer $startRow The row number at which to start iterating
+ * @return PHPExcel_Worksheet_RowIterator
+ */
+ public function getRowIterator($startRow = 1) {
+ return new PHPExcel_Worksheet_RowIterator($this,$startRow);
+ }
+
+ /**
+ * Run PHPExcel garabage collector.
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function garbageCollect() {
+ // Flush cache
+ $this->_cellCollection->getCacheData('A1');
+ // Build a reference table from images
+// $imageCoordinates = array();
+// $iterator = $this->getDrawingCollection()->getIterator();
+// while ($iterator->valid()) {
+// $imageCoordinates[$iterator->current()->getCoordinates()] = true;
+//
+// $iterator->next();
+// }
+//
+ // Lookup highest column and highest row if cells are cleaned
+ $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()));
+ }
+
+ // Loop through row dimensions
+ foreach ($this->_rowDimensions as $dimension) {
+ $highestRow = max($highestRow,$dimension->getRowIndex());
+ }
+
+ // Cache values
+ if ($highestColumn < 0) {
+ $this->_cachedHighestColumn = 'A';
+ } else {
+ $this->_cachedHighestColumn = PHPExcel_Cell::stringFromColumnIndex(--$highestColumn);
+ }
+ $this->_cachedHighestRow = $highestRow;
+
+ // Return
+ return $this;
+ }
+
+ /**
+ * Get hash code
+ *
+ * @return string Hash code
+ */
+ public function getHashCode() {
+ if ($this->_dirty) {
+ $this->_hash = md5( $this->_title .
+ $this->_autoFilter .
+ ($this->_protection->isProtectionEnabled() ? 't' : 'f') .
+ __CLASS__
+ );
+ $this->_dirty = false;
+ }
+ return $this->_hash;
+ }
+
+ /**
+ * Extract worksheet title from range.
+ *
+ * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
+ * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> array('testSheet 1', 'A1');
+ *
+ * @param string $pRange Range to extract title from
+ * @param bool $returnRange Return range? (see example)
+ * @return mixed
+ */
+ public static function extractSheetTitle($pRange, $returnRange = false) {
+ // Sheet title included?
+ if (($sep = strpos($pRange, '!')) === false) {
+ return '';
+ }
+
+ if ($returnRange) {
+ return array( trim(substr($pRange, 0, $sep),"'"),
+ substr($pRange, $sep + 1)
+ );
+ }
+
+ return substr($pRange, $sep + 1);
+ }
+
+ /**
+ * Get hyperlink
+ *
+ * @param string $pCellCoordinate Cell coordinate to get hyperlink for
+ */
+ public function getHyperlink($pCellCoordinate = 'A1')
+ {
+ // return hyperlink if we already have one
+ if (isset($this->_hyperlinkCollection[$pCellCoordinate])) {
+ return $this->_hyperlinkCollection[$pCellCoordinate];
+ }
+
+ // else create hyperlink
+ $this->_hyperlinkCollection[$pCellCoordinate] = new PHPExcel_Cell_Hyperlink();
+ return $this->_hyperlinkCollection[$pCellCoordinate];
+ }
+
+ /**
+ * Set hyperlnk
+ *
+ * @param string $pCellCoordinate Cell coordinate to insert hyperlink
+ * @param PHPExcel_Cell_Hyperlink $pHyperlink
+ * @return PHPExcel_Worksheet
+ */
+ public function setHyperlink($pCellCoordinate = 'A1', PHPExcel_Cell_Hyperlink $pHyperlink = null)
+ {
+ if ($pHyperlink === null) {
+ unset($this->_hyperlinkCollection[$pCellCoordinate]);
+ } else {
+ $this->_hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
+ }
+ return $this;
+ }
+
+ /**
+ * Hyperlink at a specific coordinate exists?
+ *
+ * @param string $pCoordinate
+ * @return boolean
+ */
+ public function hyperlinkExists($pCoordinate = 'A1')
+ {
+ return isset($this->_hyperlinkCollection[$pCoordinate]);
+ }
+
+ /**
+ * Get collection of hyperlinks
+ *
+ * @return PHPExcel_Cell_Hyperlink[]
+ */
+ public function getHyperlinkCollection()
+ {
+ return $this->_hyperlinkCollection;
+ }
+
+ /**
+ * Get data validation
+ *
+ * @param string $pCellCoordinate Cell coordinate to get data validation for
+ */
+ public function getDataValidation($pCellCoordinate = 'A1')
+ {
+ // return data validation if we already have one
+ if (isset($this->_dataValidationCollection[$pCellCoordinate])) {
+ return $this->_dataValidationCollection[$pCellCoordinate];
+ }
+
+ // else create data validation
+ $this->_dataValidationCollection[$pCellCoordinate] = new PHPExcel_Cell_DataValidation();
+ return $this->_dataValidationCollection[$pCellCoordinate];
+ }
+
+ /**
+ * Set data validation
+ *
+ * @param string $pCellCoordinate Cell coordinate to insert data validation
+ * @param PHPExcel_Cell_DataValidation $pDataValidation
+ * @return PHPExcel_Worksheet
+ */
+ public function setDataValidation($pCellCoordinate = 'A1', PHPExcel_Cell_DataValidation $pDataValidation = null)
+ {
+ if ($pDataValidation === null) {
+ unset($this->_dataValidationCollection[$pCellCoordinate]);
+ } else {
+ $this->_dataValidationCollection[$pCellCoordinate] = $pDataValidation;
+ }
+ return $this;
+ }
+
+ /**
+ * Data validation at a specific coordinate exists?
+ *
+ * @param string $pCoordinate
+ * @return boolean
+ */
+ public function dataValidationExists($pCoordinate = 'A1')
+ {
+ return isset($this->_dataValidationCollection[$pCoordinate]);
+ }
+
+ /**
+ * Get collection of data validations
+ *
+ * @return PHPExcel_Cell_DataValidation[]
+ */
+ public function getDataValidationCollection()
+ {
+ return $this->_dataValidationCollection;
+ }
+
+ /**
+ * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet
+ *
+ * @param string $range
+ * @return string Adjusted range value
+ */
+ public function shrinkRangeToFit($range) {
+ $maxCol = $this->getHighestColumn();
+ $maxRow = $this->getHighestRow();
+ $maxCol = PHPExcel_Cell::columnIndexFromString($maxCol);
+
+ $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; }
+ $rangeSet = $rangeBoundaries[0][0].$rangeBoundaries[0][1].':'.$rangeBoundaries[1][0].$rangeBoundaries[1][1];
+ }
+ unset($rangeSet);
+ $stRange = implode(' ',$rangeBlocks);
+
+ return $stRange;
+ }
+
+ /**
+ * Get tab color
+ *
+ * @return PHPExcel_Style_Color
+ */
+ public function getTabColor()
+ {
+ if ($this->_tabColor === NULL)
+ $this->_tabColor = new PHPExcel_Style_Color();
+
+ return $this->_tabColor;
+ }
+
+ /**
+ * Reset tab color
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function resetTabColor()
+ {
+ $this->_tabColor = null;
+ unset($this->_tabColor);
+
+ return $this;
+ }
+
+ /**
+ * Tab color set?
+ *
+ * @return boolean
+ */
+ public function isTabColorSet()
+ {
+ return ($this->_tabColor !== NULL);
+ }
+
+ /**
+ * Copy worksheet (!= clone!)
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function copy() {
+ $copied = clone $this;
+
+ return $copied;
+ }
+
+ /**
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ */
+ public function __clone() {
+ foreach ($this as $key => $val) {
+ if ($key == '_parent') {
+ continue;
+ }
+
+ if (is_object($val) || (is_array($val))) {
+ 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);
+ } 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/PHPExcel/Worksheet/AutoFilter.php b/PHPExcel/Worksheet/AutoFilter.php
new file mode 100644
index 0000000..03055e1
--- /dev/null
+++ b/PHPExcel/Worksheet/AutoFilter.php
@@ -0,0 +1,858 @@
+_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
+ */
+ 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) {
+ $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
+ 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;
+ }
+
+}
diff --git a/PHPExcel/Worksheet/AutoFilter/Column.php b/PHPExcel/Worksheet/AutoFilter/Column.php
new file mode 100644
index 0000000..12043d5
--- /dev/null
+++ b/PHPExcel/Worksheet/AutoFilter/Column.php
@@ -0,0 +1,394 @@
+_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/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
new file mode 100644
index 0000000..ae33683
--- /dev/null
+++ b/PHPExcel/Worksheet/AutoFilter/Column/Rule.php
@@ -0,0 +1,464 @@
+
+ *
+ * $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;
+ }
+
+ /**
+ * Get ResizeProportional
+ *
+ * @return boolean
+ */
+ public function getResizeProportional() {
+ return $this->_resizeProportional;
+ }
+
+ /**
+ * Set ResizeProportional
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_BaseDrawing
+ */
+ public function setResizeProportional($pValue = true) {
+ $this->_resizeProportional = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Rotation
+ *
+ * @return int
+ */
+ public function getRotation() {
+ return $this->_rotation;
+ }
+
+ /**
+ * Set Rotation
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_BaseDrawing
+ */
+ public function setRotation($pValue = 0) {
+ $this->_rotation = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Shadow
+ *
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ public function getShadow() {
+ return $this->_shadow;
+ }
+
+ /**
+ * Set Shadow
+ *
+ * @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;
+ }
+
+ /**
+ * 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;
+ }
+ }
+ }
+}
diff --git a/PHPExcel/Worksheet/CellIterator.php b/PHPExcel/Worksheet/CellIterator.php
new file mode 100644
index 0000000..4b96816
--- /dev/null
+++ b/PHPExcel/Worksheet/CellIterator.php
@@ -0,0 +1,161 @@
+_subject = $subject;
+ $this->_rowIndex = $rowIndex;
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct() {
+ unset($this->_subject);
+ }
+
+ /**
+ * Rewind iterator
+ */
+ public function rewind() {
+ $this->_position = 0;
+ }
+
+ /**
+ * Current PHPExcel_Cell
+ *
+ * @return PHPExcel_Cell
+ */
+ public function current() {
+ return $this->_subject->getCellByColumnAndRow($this->_position, $this->_rowIndex);
+ }
+
+ /**
+ * Current key
+ *
+ * @return int
+ */
+ public function key() {
+ return $this->_position;
+ }
+
+ /**
+ * Next value
+ */
+ public function next() {
+ ++$this->_position;
+ }
+
+ /**
+ * Are there any more PHPExcel_Cell instances available?
+ *
+ * @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;
+ }
+
+ /**
+ * Get loop only existing cells
+ *
+ * @return boolean
+ */
+ public function getIterateOnlyExistingCells() {
+ return $this->_onlyExistingCells;
+ }
+
+ /**
+ * Set the iterator to loop only existing cells
+ *
+ * @param boolean $value
+ */
+ public function setIterateOnlyExistingCells($value = true) {
+ $this->_onlyExistingCells = $value;
+ }
+}
diff --git a/PHPExcel/Worksheet/ColumnDimension.php b/PHPExcel/Worksheet/ColumnDimension.php
new file mode 100644
index 0000000..79db1c5
--- /dev/null
+++ b/PHPExcel/Worksheet/ColumnDimension.php
@@ -0,0 +1,266 @@
+_columnIndex = $pIndex;
+
+ // set default index to cellXf
+ $this->_xfIndex = 0;
+ }
+
+ /**
+ * Get ColumnIndex
+ *
+ * @return string
+ */
+ public function getColumnIndex() {
+ return $this->_columnIndex;
+ }
+
+ /**
+ * Set ColumnIndex
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_ColumnDimension
+ */
+ public function setColumnIndex($pValue) {
+ $this->_columnIndex = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Width
+ *
+ * @return double
+ */
+ public function getWidth() {
+ return $this->_width;
+ }
+
+ /**
+ * Set Width
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_ColumnDimension
+ */
+ public function setWidth($pValue = -1) {
+ $this->_width = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Auto Size
+ *
+ * @return bool
+ */
+ public function getAutoSize() {
+ return $this->_autoSize;
+ }
+
+ /**
+ * Set Auto Size
+ *
+ * @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;
+ }
+
+ /**
+ * 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/PHPExcel/Worksheet/Drawing.php b/PHPExcel/Worksheet/Drawing.php
new file mode 100644
index 0000000..56f0cfd
--- /dev/null
+++ b/PHPExcel/Worksheet/Drawing.php
@@ -0,0 +1,148 @@
+_path = '';
+
+ // Initialize parent
+ parent::__construct();
+ }
+
+ /**
+ * Get Filename
+ *
+ * @return string
+ */
+ public function getFilename() {
+ return basename($this->_path);
+ }
+
+ /**
+ * Get indexed filename (using image index)
+ *
+ * @return string
+ */
+ public function getIndexedFilename() {
+ $fileName = $this->getFilename();
+ $fileName = str_replace(' ', '_', $fileName);
+ return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension();
+ }
+
+ /**
+ * Get Extension
+ *
+ * @return string
+ */
+ public function getExtension() {
+ $exploded = explode(".", basename($this->_path));
+ return $exploded[count($exploded) - 1];
+ }
+
+ /**
+ * Get Path
+ *
+ * @return string
+ */
+ public function getPath() {
+ return $this->_path;
+ }
+
+ /**
+ * Set Path
+ *
+ * @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;
+
+ 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__
+ );
+ }
+
+ /**
+ * 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/PHPExcel/Worksheet/Drawing/Shadow.php b/PHPExcel/Worksheet/Drawing/Shadow.php
new file mode 100644
index 0000000..5df4489
--- /dev/null
+++ b/PHPExcel/Worksheet/Drawing/Shadow.php
@@ -0,0 +1,288 @@
+_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;
+ }
+
+ /**
+ * Get Visible
+ *
+ * @return boolean
+ */
+ public function getVisible() {
+ return $this->_visible;
+ }
+
+ /**
+ * Set Visible
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ public function setVisible($pValue = false) {
+ $this->_visible = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Blur radius
+ *
+ * @return int
+ */
+ public function getBlurRadius() {
+ return $this->_blurRadius;
+ }
+
+ /**
+ * Set Blur radius
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ public function setBlurRadius($pValue = 6) {
+ $this->_blurRadius = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Shadow distance
+ *
+ * @return int
+ */
+ public function getDistance() {
+ return $this->_distance;
+ }
+
+ /**
+ * Set Shadow distance
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ public function setDistance($pValue = 2) {
+ $this->_distance = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Shadow direction (in degrees)
+ *
+ * @return int
+ */
+ public function getDirection() {
+ return $this->_direction;
+ }
+
+ /**
+ * Set Shadow direction (in degrees)
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ public function setDirection($pValue = 0) {
+ $this->_direction = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Shadow alignment
+ *
+ * @return int
+ */
+ public function getAlignment() {
+ return $this->_alignment;
+ }
+
+ /**
+ * Set Shadow alignment
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ public function setAlignment($pValue = 0) {
+ $this->_alignment = $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_Worksheet_Drawing_Shadow
+ */
+ public function setColor(PHPExcel_Style_Color $pValue = null) {
+ $this->_color = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Alpha
+ *
+ * @return int
+ */
+ public function getAlpha() {
+ return $this->_alpha;
+ }
+
+ /**
+ * Set Alpha
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_Drawing_Shadow
+ */
+ 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__
+ );
+ }
+
+ /**
+ * 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/PHPExcel/Worksheet/HeaderFooter.php b/PHPExcel/Worksheet/HeaderFooter.php
new file mode 100644
index 0000000..82d7faf
--- /dev/null
+++ b/PHPExcel/Worksheet/HeaderFooter.php
@@ -0,0 +1,465 @@
+
+ * Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970:
+ *
+ * There are a number of formatting codes that can be written inline with the actual header / footer text, which
+ * affect the formatting in the header or footer.
+ *
+ * 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
+ *
+ * General Rules:
+ * 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.
+ * &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"
+ * &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 - also means "bold font style".
+ * &"-,Regular" - code for "regular font style"
+ * &"-,Italic" - code for "italic font style"
+ * &I - also means "italic font style"
+ * &"-,Bold Italic" code for "bold italic font style"
+ * &O - code for "outline style"
+ * &H - code for "shadow style"
+ *
+ *
+ * @category PHPExcel
+ * @package PHPExcel_Worksheet
+ * @copyright Copyright (c) 2006 - 2014 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();
+
+ /**
+ * Create a new PHPExcel_Worksheet_HeaderFooter
+ */
+ public function __construct()
+ {
+ }
+
+ /**
+ * Get OddHeader
+ *
+ * @return string
+ */
+ public function getOddHeader() {
+ return $this->_oddHeader;
+ }
+
+ /**
+ * Set OddHeader
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setOddHeader($pValue) {
+ $this->_oddHeader = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get OddFooter
+ *
+ * @return string
+ */
+ public function getOddFooter() {
+ return $this->_oddFooter;
+ }
+
+ /**
+ * Set OddFooter
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setOddFooter($pValue) {
+ $this->_oddFooter = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get EvenHeader
+ *
+ * @return string
+ */
+ public function getEvenHeader() {
+ return $this->_evenHeader;
+ }
+
+ /**
+ * Set EvenHeader
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setEvenHeader($pValue) {
+ $this->_evenHeader = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get EvenFooter
+ *
+ * @return string
+ */
+ public function getEvenFooter() {
+ return $this->_evenFooter;
+ }
+
+ /**
+ * Set EvenFooter
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setEvenFooter($pValue) {
+ $this->_evenFooter = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get FirstHeader
+ *
+ * @return string
+ */
+ public function getFirstHeader() {
+ return $this->_firstHeader;
+ }
+
+ /**
+ * Set FirstHeader
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setFirstHeader($pValue) {
+ $this->_firstHeader = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get FirstFooter
+ *
+ * @return string
+ */
+ public function getFirstFooter() {
+ return $this->_firstFooter;
+ }
+
+ /**
+ * Set FirstFooter
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setFirstFooter($pValue) {
+ $this->_firstFooter = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get DifferentOddEven
+ *
+ * @return boolean
+ */
+ public function getDifferentOddEven() {
+ return $this->_differentOddEven;
+ }
+
+ /**
+ * Set DifferentOddEven
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setDifferentOddEven($pValue = false) {
+ $this->_differentOddEven = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get DifferentFirst
+ *
+ * @return boolean
+ */
+ public function getDifferentFirst() {
+ return $this->_differentFirst;
+ }
+
+ /**
+ * Set DifferentFirst
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setDifferentFirst($pValue = false) {
+ $this->_differentFirst = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get ScaleWithDocument
+ *
+ * @return boolean
+ */
+ public function getScaleWithDocument() {
+ return $this->_scaleWithDocument;
+ }
+
+ /**
+ * Set ScaleWithDocument
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setScaleWithDocument($pValue = true) {
+ $this->_scaleWithDocument = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get AlignWithMargins
+ *
+ * @return boolean
+ */
+ public function getAlignWithMargins() {
+ return $this->_alignWithMargins;
+ }
+
+ /**
+ * Set AlignWithMargins
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setAlignWithMargins($pValue = true) {
+ $this->_alignWithMargins = $pValue;
+ return $this;
+ }
+
+ /**
+ * Add header/footer image
+ *
+ * @param PHPExcel_Worksheet_HeaderFooterDrawing $image
+ * @param string $location
+ * @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;
+ }
+
+ /**
+ * Remove header/footer image
+ *
+ * @param string $location
+ * @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;
+ }
+
+ /**
+ * Set header/footer images
+ *
+ * @param PHPExcel_Worksheet_HeaderFooterDrawing[] $images
+ * @throws PHPExcel_Exception
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setImages($images) {
+ if (!is_array($images)) {
+ throw new PHPExcel_Exception('Invalid parameter!');
+ }
+
+ $this->_headerFooterImages = $images;
+ return $this;
+ }
+
+ /**
+ * Get header/footer 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;
+ }
+
+ /**
+ * 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/PHPExcel/Worksheet/HeaderFooterDrawing.php b/PHPExcel/Worksheet/HeaderFooterDrawing.php
new file mode 100644
index 0000000..1c6f4e1
--- /dev/null
+++ b/PHPExcel/Worksheet/HeaderFooterDrawing.php
@@ -0,0 +1,350 @@
+_path = '';
+ $this->_name = '';
+ $this->_offsetX = 0;
+ $this->_offsetY = 0;
+ $this->_width = 0;
+ $this->_height = 0;
+ $this->_resizeProportional = true;
+ }
+
+ /**
+ * Get Name
+ *
+ * @return string
+ */
+ public function getName() {
+ return $this->_name;
+ }
+
+ /**
+ * Set Name
+ *
+ * @param string $pValue
+ * @return PHPExcel_Worksheet_HeaderFooterDrawing
+ */
+ public function setName($pValue = '') {
+ $this->_name = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get OffsetX
+ *
+ * @return int
+ */
+ public function getOffsetX() {
+ return $this->_offsetX;
+ }
+
+ /**
+ * Set OffsetX
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_HeaderFooterDrawing
+ */
+ public function setOffsetX($pValue = 0) {
+ $this->_offsetX = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get OffsetY
+ *
+ * @return int
+ */
+ public function getOffsetY() {
+ return $this->_offsetY;
+ }
+
+ /**
+ * Set OffsetY
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_HeaderFooterDrawing
+ */
+ public function setOffsetY($pValue = 0) {
+ $this->_offsetY = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Width
+ *
+ * @return int
+ */
+ public function getWidth() {
+ return $this->_width;
+ }
+
+ /**
+ * Set Width
+ *
+ * @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);
+ }
+
+ // Set width
+ $this->_width = $pValue;
+
+ return $this;
+ }
+
+ /**
+ * Get Height
+ *
+ * @return int
+ */
+ public function getHeight() {
+ return $this->_height;
+ }
+
+ /**
+ * Set Height
+ *
+ * @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);
+ }
+
+ // Set height
+ $this->_height = $pValue;
+
+ return $this;
+ }
+
+ /**
+ * Set width and height with proportional resize
+ * 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_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;
+ }
+
+ /**
+ * Get ResizeProportional
+ *
+ * @return boolean
+ */
+ public function getResizeProportional() {
+ return $this->_resizeProportional;
+ }
+
+ /**
+ * Set ResizeProportional
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_HeaderFooterDrawing
+ */
+ public function setResizeProportional($pValue = true) {
+ $this->_resizeProportional = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Filename
+ *
+ * @return string
+ */
+ public function getFilename() {
+ return basename($this->_path);
+ }
+
+ /**
+ * Get Extension
+ *
+ * @return string
+ */
+ public function getExtension() {
+ $parts = explode(".", basename($this->_path));
+ return end($parts);
+ }
+
+ /**
+ * Get Path
+ *
+ * @return string
+ */
+ public function getPath() {
+ return $this->_path;
+ }
+
+ /**
+ * Set Path
+ *
+ * @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;
+ }
+
+ /**
+ * 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;
+ }
+ }
+ }
+}
diff --git a/PHPExcel/Worksheet/MemoryDrawing.php b/PHPExcel/Worksheet/MemoryDrawing.php
new file mode 100644
index 0000000..93266d2
--- /dev/null
+++ b/PHPExcel/Worksheet/MemoryDrawing.php
@@ -0,0 +1,200 @@
+_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();
+ }
+
+ /**
+ * Get image resource
+ *
+ * @return resource
+ */
+ public function getImageResource() {
+ return $this->_imageResource;
+ }
+
+ /**
+ * Set image 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;
+ }
+
+ /**
+ * Get rendering function
+ *
+ * @return string
+ */
+ public function getRenderingFunction() {
+ return $this->_renderingFunction;
+ }
+
+ /**
+ * Set rendering function
+ *
+ * @param string $value
+ * @return PHPExcel_Worksheet_MemoryDrawing
+ */
+ public function setRenderingFunction($value = PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT) {
+ $this->_renderingFunction = $value;
+ return $this;
+ }
+
+ /**
+ * Get mime type
+ *
+ * @return string
+ */
+ public function getMimeType() {
+ return $this->_mimeType;
+ }
+
+ /**
+ * Set mime type
+ *
+ * @param string $value
+ * @return PHPExcel_Worksheet_MemoryDrawing
+ */
+ public function setMimeType($value = PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT) {
+ $this->_mimeType = $value;
+ return $this;
+ }
+
+ /**
+ * Get indexed filename (using image index)
+ *
+ * @return string
+ */
+ public function getIndexedFilename() {
+ $extension = strtolower($this->getMimeType());
+ $extension = explode('/', $extension);
+ $extension = $extension[1];
+
+ 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__
+ );
+ }
+
+ /**
+ * 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/PHPExcel/Worksheet/PageMargins.php b/PHPExcel/Worksheet/PageMargins.php
new file mode 100644
index 0000000..671711f
--- /dev/null
+++ b/PHPExcel/Worksheet/PageMargins.php
@@ -0,0 +1,220 @@
+_left;
+ }
+
+ /**
+ * Set Left
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ public function setLeft($pValue) {
+ $this->_left = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Right
+ *
+ * @return double
+ */
+ public function getRight() {
+ return $this->_right;
+ }
+
+ /**
+ * Set Right
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ public function setRight($pValue) {
+ $this->_right = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Top
+ *
+ * @return double
+ */
+ public function getTop() {
+ return $this->_top;
+ }
+
+ /**
+ * Set Top
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ public function setTop($pValue) {
+ $this->_top = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Bottom
+ *
+ * @return double
+ */
+ public function getBottom() {
+ return $this->_bottom;
+ }
+
+ /**
+ * Set Bottom
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ public function setBottom($pValue) {
+ $this->_bottom = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Header
+ *
+ * @return double
+ */
+ public function getHeader() {
+ return $this->_header;
+ }
+
+ /**
+ * Set Header
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ public function setHeader($pValue) {
+ $this->_header = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Footer
+ *
+ * @return double
+ */
+ public function getFooter() {
+ return $this->_footer;
+ }
+
+ /**
+ * Set Footer
+ *
+ * @param double $pValue
+ * @return PHPExcel_Worksheet_PageMargins
+ */
+ 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;
+ }
+ }
+ }
+}
diff --git a/PHPExcel/Worksheet/PageSetup.php b/PHPExcel/Worksheet/PageSetup.php
new file mode 100644
index 0000000..9512dbe
--- /dev/null
+++ b/PHPExcel/Worksheet/PageSetup.php
@@ -0,0 +1,798 @@
+
+ * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988:
+ *
+ * 1 = Letter paper (8.5 in. by 11 in.)
+ * 2 = Letter small paper (8.5 in. by 11 in.)
+ * 3 = Tabloid paper (11 in. by 17 in.)
+ * 4 = Ledger paper (17 in. by 11 in.)
+ * 5 = Legal paper (8.5 in. by 14 in.)
+ * 6 = Statement paper (5.5 in. by 8.5 in.)
+ * 7 = Executive paper (7.25 in. by 10.5 in.)
+ * 8 = A3 paper (297 mm by 420 mm)
+ * 9 = A4 paper (210 mm by 297 mm)
+ * 10 = A4 small paper (210 mm by 297 mm)
+ * 11 = A5 paper (148 mm by 210 mm)
+ * 12 = B4 paper (250 mm by 353 mm)
+ * 13 = B5 paper (176 mm by 250 mm)
+ * 14 = Folio paper (8.5 in. by 13 in.)
+ * 15 = Quarto paper (215 mm by 275 mm)
+ * 16 = Standard paper (10 in. by 14 in.)
+ * 17 = Standard paper (11 in. by 17 in.)
+ * 18 = Note paper (8.5 in. by 11 in.)
+ * 19 = #9 envelope (3.875 in. by 8.875 in.)
+ * 20 = #10 envelope (4.125 in. by 9.5 in.)
+ * 21 = #11 envelope (4.5 in. by 10.375 in.)
+ * 22 = #12 envelope (4.75 in. by 11 in.)
+ * 23 = #14 envelope (5 in. by 11.5 in.)
+ * 24 = C paper (17 in. by 22 in.)
+ * 25 = D paper (22 in. by 34 in.)
+ * 26 = E paper (34 in. by 44 in.)
+ * 27 = DL envelope (110 mm by 220 mm)
+ * 28 = C5 envelope (162 mm by 229 mm)
+ * 29 = C3 envelope (324 mm by 458 mm)
+ * 30 = C4 envelope (229 mm by 324 mm)
+ * 31 = C6 envelope (114 mm by 162 mm)
+ * 32 = C65 envelope (114 mm by 229 mm)
+ * 33 = B4 envelope (250 mm by 353 mm)
+ * 34 = B5 envelope (176 mm by 250 mm)
+ * 35 = B6 envelope (176 mm by 125 mm)
+ * 36 = Italy envelope (110 mm by 230 mm)
+ * 37 = Monarch envelope (3.875 in. by 7.5 in.).
+ * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.)
+ * 39 = US standard fanfold (14.875 in. by 11 in.)
+ * 40 = German standard fanfold (8.5 in. by 12 in.)
+ * 41 = German legal fanfold (8.5 in. by 13 in.)
+ * 42 = ISO B4 (250 mm by 353 mm)
+ * 43 = Japanese double postcard (200 mm by 148 mm)
+ * 44 = Standard paper (9 in. by 11 in.)
+ * 45 = Standard paper (10 in. by 11 in.)
+ * 46 = Standard paper (15 in. by 11 in.)
+ * 47 = Invite envelope (220 mm by 220 mm)
+ * 50 = Letter extra paper (9.275 in. by 12 in.)
+ * 51 = Legal extra paper (9.275 in. by 15 in.)
+ * 52 = Tabloid extra paper (11.69 in. by 18 in.)
+ * 53 = A4 extra paper (236 mm by 322 mm)
+ * 54 = Letter transverse paper (8.275 in. by 11 in.)
+ * 55 = A4 transverse paper (210 mm by 297 mm)
+ * 56 = Letter extra transverse paper (9.275 in. by 12 in.)
+ * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm)
+ * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm)
+ * 59 = Letter plus paper (8.5 in. by 12.69 in.)
+ * 60 = A4 plus paper (210 mm by 330 mm)
+ * 61 = A5 transverse paper (148 mm by 210 mm)
+ * 62 = JIS B5 transverse paper (182 mm by 257 mm)
+ * 63 = A3 extra paper (322 mm by 445 mm)
+ * 64 = A5 extra paper (174 mm by 235 mm)
+ * 65 = ISO B5 extra paper (201 mm by 276 mm)
+ * 66 = A2 paper (420 mm by 594 mm)
+ * 67 = A3 transverse paper (297 mm by 420 mm)
+ * 68 = A3 extra transverse paper (322 mm by 445 mm)
+ *
+ *
+ * @category PHPExcel
+ * @package PHPExcel_Worksheet
+ * @copyright Copyright (c) 2006 - 2014 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;
+
+ /**
+ * Create a new PHPExcel_Worksheet_PageSetup
+ */
+ public function __construct()
+ {
+ }
+
+ /**
+ * Get Paper Size
+ *
+ * @return int
+ */
+ public function getPaperSize() {
+ return $this->_paperSize;
+ }
+
+ /**
+ * Set Paper Size
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_PageSetup
+ */
+ public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) {
+ $this->_paperSize = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Orientation
+ *
+ * @return string
+ */
+ public function getOrientation() {
+ return $this->_orientation;
+ }
+
+ /**
+ * Set Orientation
+ *
+ * @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 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
+ */
+ 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);
+ }
+
+ /**
+ * Get first page number
+ *
+ * @return int
+ */
+ public function getFirstPageNumber() {
+ return $this->_firstPageNumber;
+ }
+
+ /**
+ * Set first page number
+ *
+ * @param int $value
+ * @return PHPExcel_Worksheet_HeaderFooter
+ */
+ public function setFirstPageNumber($value = null) {
+ $this->_firstPageNumber = $value;
+ return $this;
+ }
+
+ /**
+ * Reset first page number
+ *
+ * @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;
+ }
+ }
+ }
+}
diff --git a/PHPExcel/Worksheet/Protection.php b/PHPExcel/Worksheet/Protection.php
new file mode 100644
index 0000000..f41dd53
--- /dev/null
+++ b/PHPExcel/Worksheet/Protection.php
@@ -0,0 +1,545 @@
+_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;
+ }
+
+ /**
+ * Get Sheet
+ *
+ * @return boolean
+ */
+ function getSheet() {
+ return $this->_sheet;
+ }
+
+ /**
+ * Set Sheet
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setSheet($pValue = false) {
+ $this->_sheet = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Objects
+ *
+ * @return boolean
+ */
+ function getObjects() {
+ return $this->_objects;
+ }
+
+ /**
+ * Set Objects
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setObjects($pValue = false) {
+ $this->_objects = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Scenarios
+ *
+ * @return boolean
+ */
+ function getScenarios() {
+ return $this->_scenarios;
+ }
+
+ /**
+ * Set Scenarios
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setScenarios($pValue = false) {
+ $this->_scenarios = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get FormatCells
+ *
+ * @return boolean
+ */
+ function getFormatCells() {
+ return $this->_formatCells;
+ }
+
+ /**
+ * Set FormatCells
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setFormatCells($pValue = false) {
+ $this->_formatCells = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get FormatColumns
+ *
+ * @return boolean
+ */
+ function getFormatColumns() {
+ return $this->_formatColumns;
+ }
+
+ /**
+ * Set FormatColumns
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setFormatColumns($pValue = false) {
+ $this->_formatColumns = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get FormatRows
+ *
+ * @return boolean
+ */
+ function getFormatRows() {
+ return $this->_formatRows;
+ }
+
+ /**
+ * Set FormatRows
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setFormatRows($pValue = false) {
+ $this->_formatRows = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get InsertColumns
+ *
+ * @return boolean
+ */
+ function getInsertColumns() {
+ return $this->_insertColumns;
+ }
+
+ /**
+ * Set InsertColumns
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setInsertColumns($pValue = false) {
+ $this->_insertColumns = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get InsertRows
+ *
+ * @return boolean
+ */
+ function getInsertRows() {
+ return $this->_insertRows;
+ }
+
+ /**
+ * Set InsertRows
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setInsertRows($pValue = false) {
+ $this->_insertRows = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get InsertHyperlinks
+ *
+ * @return boolean
+ */
+ function getInsertHyperlinks() {
+ return $this->_insertHyperlinks;
+ }
+
+ /**
+ * Set InsertHyperlinks
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setInsertHyperlinks($pValue = false) {
+ $this->_insertHyperlinks = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get DeleteColumns
+ *
+ * @return boolean
+ */
+ function getDeleteColumns() {
+ return $this->_deleteColumns;
+ }
+
+ /**
+ * Set DeleteColumns
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setDeleteColumns($pValue = false) {
+ $this->_deleteColumns = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get DeleteRows
+ *
+ * @return boolean
+ */
+ function getDeleteRows() {
+ return $this->_deleteRows;
+ }
+
+ /**
+ * Set DeleteRows
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setDeleteRows($pValue = false) {
+ $this->_deleteRows = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get SelectLockedCells
+ *
+ * @return boolean
+ */
+ function getSelectLockedCells() {
+ return $this->_selectLockedCells;
+ }
+
+ /**
+ * Set SelectLockedCells
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setSelectLockedCells($pValue = false) {
+ $this->_selectLockedCells = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Sort
+ *
+ * @return boolean
+ */
+ function getSort() {
+ return $this->_sort;
+ }
+
+ /**
+ * Set Sort
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setSort($pValue = false) {
+ $this->_sort = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get AutoFilter
+ *
+ * @return boolean
+ */
+ function getAutoFilter() {
+ return $this->_autoFilter;
+ }
+
+ /**
+ * Set AutoFilter
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setAutoFilter($pValue = false) {
+ $this->_autoFilter = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get PivotTables
+ *
+ * @return boolean
+ */
+ function getPivotTables() {
+ return $this->_pivotTables;
+ }
+
+ /**
+ * Set PivotTables
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setPivotTables($pValue = false) {
+ $this->_pivotTables = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get SelectUnlockedCells
+ *
+ * @return boolean
+ */
+ function getSelectUnlockedCells() {
+ return $this->_selectUnlockedCells;
+ }
+
+ /**
+ * Set SelectUnlockedCells
+ *
+ * @param boolean $pValue
+ * @return PHPExcel_Worksheet_Protection
+ */
+ function setSelectUnlockedCells($pValue = false) {
+ $this->_selectUnlockedCells = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Password (hashed)
+ *
+ * @return string
+ */
+ function getPassword() {
+ return $this->_password;
+ }
+
+ /**
+ * Set Password
+ *
+ * @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;
+ }
+ }
+ }
+}
diff --git a/PHPExcel/Worksheet/Row.php b/PHPExcel/Worksheet/Row.php
new file mode 100644
index 0000000..2e9bd13
--- /dev/null
+++ b/PHPExcel/Worksheet/Row.php
@@ -0,0 +1,90 @@
+_parent = $parent;
+ $this->_rowIndex = $rowIndex;
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct() {
+ unset($this->_parent);
+ }
+
+ /**
+ * 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);
+ }
+}
diff --git a/PHPExcel/Worksheet/RowDimension.php b/PHPExcel/Worksheet/RowDimension.php
new file mode 100644
index 0000000..69b7ba8
--- /dev/null
+++ b/PHPExcel/Worksheet/RowDimension.php
@@ -0,0 +1,265 @@
+_rowIndex = $pIndex;
+
+ // set row dimension as unformatted by default
+ $this->_xfIndex = null;
+ }
+
+ /**
+ * Get Row Index
+ *
+ * @return int
+ */
+ public function getRowIndex() {
+ return $this->_rowIndex;
+ }
+
+ /**
+ * Set Row Index
+ *
+ * @param int $pValue
+ * @return PHPExcel_Worksheet_RowDimension
+ */
+ public function setRowIndex($pValue) {
+ $this->_rowIndex = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Row Height
+ *
+ * @return double
+ */
+ public function getRowHeight() {
+ return $this->_rowHeight;
+ }
+
+ /**
+ * Set Row Height
+ *
+ * @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;
+ }
+
+ /**
+ * Get Collapsed
+ *
+ * @return bool
+ */
+ public function getCollapsed() {
+ return $this->_collapsed;
+ }
+
+ /**
+ * Set Collapsed
+ *
+ * @param bool $pValue
+ * @return PHPExcel_Worksheet_RowDimension
+ */
+ 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_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/PHPExcel/Worksheet/RowIterator.php b/PHPExcel/Worksheet/RowIterator.php
new file mode 100644
index 0000000..f2d962f
--- /dev/null
+++ b/PHPExcel/Worksheet/RowIterator.php
@@ -0,0 +1,148 @@
+_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();
+ }
+}
diff --git a/PHPExcel/Worksheet/SheetView.php b/PHPExcel/Worksheet/SheetView.php
new file mode 100644
index 0000000..05fbf28
--- /dev/null
+++ b/PHPExcel/Worksheet/SheetView.php
@@ -0,0 +1,188 @@
+_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 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 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 View
+ *
+ * @return string
+ */
+ public function getView() {
+ return $this->_sheetviewType;
+ }
+
+ /**
+ * 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;
+ }
+ }
+ }
+}
diff --git a/PHPExcel/WorksheetIterator.php b/PHPExcel/WorksheetIterator.php
new file mode 100644
index 0000000..624b49b
--- /dev/null
+++ b/PHPExcel/WorksheetIterator.php
@@ -0,0 +1,118 @@
+_subject = $subject;
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ unset($this->_subject);
+ }
+
+ /**
+ * Rewind iterator
+ */
+ public function rewind()
+ {
+ $this->_position = 0;
+ }
+
+ /**
+ * Current PHPExcel_Worksheet
+ *
+ * @return PHPExcel_Worksheet
+ */
+ public function current()
+ {
+ return $this->_subject->getSheet($this->_position);
+ }
+
+ /**
+ * Current key
+ *
+ * @return int
+ */
+ public function key()
+ {
+ return $this->_position;
+ }
+
+ /**
+ * Next value
+ */
+ public function next()
+ {
+ ++$this->_position;
+ }
+
+ /**
+ * More PHPExcel_Worksheet instances available?
+ *
+ * @return boolean
+ */
+ public function valid()
+ {
+ return $this->_position < $this->_subject->getSheetCount();
+ }
+}
diff --git a/PHPExcel/Writer/Abstract.php b/PHPExcel/Writer/Abstract.php
new file mode 100644
index 0000000..7e09ef8
--- /dev/null
+++ b/PHPExcel/Writer/Abstract.php
@@ -0,0 +1,158 @@
+_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;
+ }
+
+ /**
+ * 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
+ *
+ * @return boolean
+ */
+ 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.
+ *
+ * @param boolean $pValue Pre-Calculate Formulas?
+ * @return PHPExcel_Writer_IWriter
+ */
+ 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;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Get disk caching directory
+ *
+ * @return string
+ */
+ public function getDiskCachingDirectory() {
+ return $this->_diskCachingDirectory;
+ }
+}
diff --git a/PHPExcel/Writer/CSV.php b/PHPExcel/Writer/CSV.php
new file mode 100644
index 0000000..521874f
--- /dev/null
+++ b/PHPExcel/Writer/CSV.php
@@ -0,0 +1,310 @@
+_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) {
+ fwrite($fileHandle, "\xEF\xBB\xBF"); // Enforce UTF-8 BOM Header
+ $this->setEnclosure('"'); // Set enclosure to "
+ $this->setDelimiter(";"); // Set delimiter to a semi-colon
+ $this->setLineEnding("\r\n");
+ fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->_lineEnding);
+ } elseif ($this->_useBOM) {
+ // Write the UTF-8 BOM code if required
+ fwrite($fileHandle, "\xEF\xBB\xBF");
+ }
+
+ // Identify the range that we need to extract from the worksheet
+ $maxCol = $sheet->getHighestDataColumn();
+ $maxRow = $sheet->getHighestDataRow();
+
+ // Write rows to file
+ for($row = 1; $row <= $maxRow; ++$row) {
+ // Convert the row to an array...
+ $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row,'', $this->_preCalculateFormulas);
+ // ... and write to the file
+ $this->_writeLine($fileHandle, $cellsArray[0]);
+ }
+
+ // Close file
+ fclose($fileHandle);
+
+ PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
+ PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ }
+
+ /**
+ * 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
+ fwrite($pFileHandle, $line);
+ } else {
+ throw new PHPExcel_Writer_Exception("Invalid data row passed to CSV writer.");
+ }
+ }
+
+}
diff --git a/PHPExcel/Writer/Excel2007.php b/PHPExcel/Writer/Excel2007.php
new file mode 100644
index 0000000..a8f7593
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007.php
@@ -0,0 +1,532 @@
+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($this->_spreadSheet)->getDebugLog()->getWriteDebugLog();
+ PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(FALSE);
+ $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
+
+ // Create string lookup table
+ $this->_stringTable = array();
+ for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
+ $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable);
+ }
+
+ // Create styles dictionaries
+ $this->_styleHashTable->addFromSource( $this->getWriterPart('Style')->allStyles($this->_spreadSheet) );
+ $this->_stylesConditionalHashTable->addFromSource( $this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet) );
+ $this->_fillHashTable->addFromSource( $this->getWriterPart('Style')->allFills($this->_spreadSheet) );
+ $this->_fontHashTable->addFromSource( $this->getWriterPart('Style')->allFonts($this->_spreadSheet) );
+ $this->_bordersHashTable->addFromSource( $this->getWriterPart('Style')->allBorders($this->_spreadSheet) );
+ $this->_numFmtHashTable->addFromSource( $this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet) );
+
+ // Create drawing dictionary
+ $this->_drawingHashTable->addFromSource( $this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet) );
+
+ // Create new ZIP file and open it for writing
+ $zipClass = PHPExcel_Settings::getZipClass();
+ $objZip = new $zipClass();
+
+ // Retrieve OVERWRITE and CREATE constants from the instantiated zip class
+ // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP
+ $ro = new ReflectionObject($objZip);
+ $zipOverWrite = $ro->getConstant('OVERWRITE');
+ $zipCreate = $ro->getConstant('CREATE');
+
+ if (file_exists($pFilename)) {
+ unlink($pFilename);
+ }
+ // Try opening the ZIP file
+ if ($objZip->open($pFilename, $zipOverWrite) !== true) {
+ if ($objZip->open($pFilename, $zipCreate) !== true) {
+ throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing.");
+ }
+ }
+
+ // Add [Content_Types].xml to ZIP file
+ $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts));
+
+ //if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
+ if($this->_spreadSheet->hasMacros()){
+ $macrosCode=$this->_spreadSheet->getMacrosCode();
+ if(!is_null($macrosCode)){// we have the code ?
+ $objZip->addFromString('xl/vbaProject.bin', $macrosCode);//allways in 'xl', allways named vbaProject.bin
+ if($this->_spreadSheet->hasMacrosCertificate()){//signed macros ?
+ // Yes : add the certificate file and the related rels file
+ $objZip->addFromString('xl/vbaProjectSignature.bin', $this->_spreadSheet->getMacrosCertificate());
+ $objZip->addFromString('xl/_rels/vbaProject.bin.rels',
+ $this->getWriterPart('RelsVBA')->writeVBARelationships($this->_spreadSheet));
+ }
+ }
+ }
+ //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
+ if($this->_spreadSheet->hasRibbon()){
+ $tmpRibbonTarget=$this->_spreadSheet->getRibbonXMLData('target');
+ $objZip->addFromString($tmpRibbonTarget, $this->_spreadSheet->getRibbonXMLData('data'));
+ if($this->_spreadSheet->hasRibbonBinObjects()){
+ $tmpRootPath=dirname($tmpRibbonTarget).'/';
+ $ribbonBinObjects=$this->_spreadSheet->getRibbonBinObjects('data');//the files to write
+ foreach($ribbonBinObjects as $aPath=>$aContent){
+ $objZip->addFromString($tmpRootPath.$aPath, $aContent);
+ }
+ //the rels for files
+ $objZip->addFromString($tmpRootPath.'_rels/'.basename($tmpRibbonTarget).'.rels',
+ $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->_spreadSheet));
+ }
+ }
+
+ // Add relationships to ZIP file
+ $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet));
+ $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet));
+
+ // Add document properties to ZIP file
+ $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet));
+ $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet));
+ $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet);
+ if ($customPropertiesPart !== NULL) {
+ $objZip->addFromString('docProps/custom.xml', $customPropertiesPart);
+ }
+
+ // Add theme to ZIP file
+ $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet));
+
+ // Add string table to ZIP file
+ $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable));
+
+ // Add styles to ZIP file
+ $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet));
+
+ // Add workbook to ZIP file
+ $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas));
+
+ $chartCount = 0;
+ // Add worksheets
+ for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
+ $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts));
+ if ($this->_includeCharts) {
+ $charts = $this->_spreadSheet->getSheet($i)->getChartCollection();
+ if (count($charts) > 0) {
+ foreach($charts as $chart) {
+ $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart));
+ $chartCount++;
+ }
+ }
+ }
+ }
+
+ $chartRef1 = $chartRef2 = 0;
+ // Add worksheet relationships (drawings, ...)
+ for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
+
+ // Add relationships
+ $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), ($i + 1), $this->_includeCharts));
+
+ $drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection();
+ $drawingCount = count($drawings);
+ if ($this->_includeCharts) {
+ $chartCount = $this->_spreadSheet->getSheet($i)->getChartCount();
+ }
+
+ // Add drawing and image relationship parts
+ if (($drawingCount > 0) || ($chartCount > 0)) {
+ // Drawing relationships
+ $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i),$chartRef1, $this->_includeCharts));
+
+ // Drawings
+ $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i),$chartRef2,$this->_includeCharts));
+ }
+
+ // Add comment relationship parts
+ if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) {
+ // VML Comments
+ $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i)));
+
+ // Comments
+ $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i)));
+ }
+
+ // Add header/footer relationship parts
+ if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
+ // VML Drawings
+ $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i)));
+
+ // VML Drawing relationships
+ $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i)));
+
+ // Media
+ foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
+ $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
+ }
+ }
+ }
+
+ // Add media
+ for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
+ if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {
+ $imageContents = null;
+ $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
+ if (strpos($imagePath, 'zip://') !== false) {
+ $imagePath = substr($imagePath, 6);
+ $imagePathSplitted = explode('#', $imagePath);
+
+ $imageZip = new ZipArchive();
+ $imageZip->open($imagePathSplitted[0]);
+ $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
+ $imageZip->close();
+ unset($imageZip);
+ } else {
+ $imageContents = file_get_contents($imagePath);
+ }
+
+ $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
+ } else if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) {
+ ob_start();
+ call_user_func(
+ $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
+ $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
+ );
+ $imageContents = ob_get_contents();
+ ob_end_clean();
+
+ $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
+ }
+ }
+
+ PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);
+ PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+
+ // Close file
+ if ($objZip->close() === false) {
+ throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename.");
+ }
+
+ // If a temporary file was used, copy it to the correct file stream
+ if ($originalFilename != $pFilename) {
+ if (copy($pFilename, $originalFilename) === false) {
+ throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
+ }
+ @unlink($pFilename);
+ }
+ } else {
+ throw new PHPExcel_Writer_Exception("PHPExcel object unassigned.");
+ }
+ }
+
+ /**
+ * 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 string table
+ *
+ * @return string[]
+ */
+ public function getStringTable() {
+ return $this->_stringTable;
+ }
+
+ /**
+ * Get PHPExcel_Style HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getStyleHashTable() {
+ return $this->_styleHashTable;
+ }
+
+ /**
+ * Get PHPExcel_Style_Conditional HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getStylesConditionalHashTable() {
+ return $this->_stylesConditionalHashTable;
+ }
+
+ /**
+ * Get PHPExcel_Style_Fill HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getFillHashTable() {
+ return $this->_fillHashTable;
+ }
+
+ /**
+ * Get PHPExcel_Style_Font HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getFontHashTable() {
+ return $this->_fontHashTable;
+ }
+
+ /**
+ * Get PHPExcel_Style_Borders HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getBordersHashTable() {
+ return $this->_bordersHashTable;
+ }
+
+ /**
+ * Get PHPExcel_Style_NumberFormat HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getNumFmtHashTable() {
+ return $this->_numFmtHashTable;
+ }
+
+ /**
+ * Get PHPExcel_Worksheet_BaseDrawing HashTable
+ *
+ * @return PHPExcel_HashTable
+ */
+ public function getDrawingHashTable() {
+ return $this->_drawingHashTable;
+ }
+
+ /**
+ * Get Office2003 compatibility
+ *
+ * @return boolean
+ */
+ public function getOffice2003Compatibility() {
+ return $this->_office2003compatibility;
+ }
+
+ /**
+ * Set Office2003 compatibility
+ *
+ * @param boolean $pValue Office2003 compatibility?
+ * @return PHPExcel_Writer_Excel2007
+ */
+ public function setOffice2003Compatibility($pValue = false) {
+ $this->_office2003compatibility = $pValue;
+ return $this;
+ }
+
+}
diff --git a/PHPExcel/Writer/Excel2007/Chart.php b/PHPExcel/Writer/Excel2007/Chart.php
new file mode 100644
index 0000000..526daa9
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Chart.php
@@ -0,0 +1,1203 @@
+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();
+
+ $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->_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) ||
+ ($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/PHPExcel/Writer/Excel2007/Comments.php b/PHPExcel/Writer/Excel2007/Comments.php
new file mode 100644
index 0000000..436219c
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Comments.php
@@ -0,0 +1,268 @@
+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();
+ }
+}
diff --git a/PHPExcel/Writer/Excel2007/ContentTypes.php b/PHPExcel/Writer/Excel2007/ContentTypes.php
new file mode 100644
index 0000000..3c17a16
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/ContentTypes.php
@@ -0,0 +1,287 @@
+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() );
+ } 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
+ );
+ }
+ }
+ 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/PHPExcel/Writer/Excel2007/DocProps.php b/PHPExcel/Writer/Excel2007/DocProps.php
new file mode 100644
index 0000000..cfc3089
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/DocProps.php
@@ -0,0 +1,272 @@
+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();
+ }
+
+}
diff --git a/PHPExcel/Writer/Excel2007/Drawing.php b/PHPExcel/Writer/Excel2007/Drawing.php
new file mode 100644
index 0000000..3c52723
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Drawing.php
@@ -0,0 +1,598 @@
+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();
+//*/
+
+// $objWriter->endElement();
+
+// $objWriter->endElement();
+/*
+ // a:ln
+ $objWriter->startElement('a:ln');
+ $objWriter->writeAttribute('w', '88900');
+ $objWriter->writeAttribute('cap', 'sq');
+
+ // a:solidFill
+ $objWriter->startElement('a:solidFill');
+
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FFFFFF');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:miter
+ $objWriter->startElement('a:miter');
+ $objWriter->writeAttribute('lim', '800000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+*/
+
+ 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: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();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+ }
+/*
+
+ // a:scene3d
+ $objWriter->startElement('a:scene3d');
+
+ // 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:rot
+ $objWriter->startElement('a:rot');
+ $objWriter->writeAttribute('lat', '0');
+ $objWriter->writeAttribute('lon', '0');
+ $objWriter->writeAttribute('rev', '0');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+*/
+/*
+ // a:sp3d
+ $objWriter->startElement('a:sp3d');
+
+ // a:bevelT
+ $objWriter->startElement('a:bevelT');
+ $objWriter->writeAttribute('w', '25400');
+ $objWriter->writeAttribute('h', '19050');
+ $objWriter->endElement();
+
+ // a:contourClr
+ $objWriter->startElement('a:contourClr');
+
+ // a:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', 'FFFFFF');
+ $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;
+ }
+}
diff --git a/PHPExcel/Writer/Excel2007/Rels.php b/PHPExcel/Writer/Excel2007/Rels.php
new file mode 100644
index 0000000..0bdb667
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Rels.php
@@ -0,0 +1,437 @@
+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
+ 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
+ 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.");
+ }
+ }
+}
diff --git a/PHPExcel/Writer/Excel2007/RelsRibbon.php b/PHPExcel/Writer/Excel2007/RelsRibbon.php
new file mode 100644
index 0000000..f924a1d
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/RelsRibbon.php
@@ -0,0 +1,77 @@
+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();//Relationship
+ }
+ }
+ $objWriter->endElement();//Relationships
+
+ // Return
+ return $objWriter->getData();
+
+ }
+
+}
diff --git a/PHPExcel/Writer/Excel2007/RelsVBA.php b/PHPExcel/Writer/Excel2007/RelsVBA.php
new file mode 100644
index 0000000..aecb0b8
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/RelsVBA.php
@@ -0,0 +1,72 @@
+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();//Relationship
+ $objWriter->endElement();//Relationships
+
+ // Return
+ return $objWriter->getData();
+
+ }
+
+}
diff --git a/PHPExcel/Writer/Excel2007/StringTable.php b/PHPExcel/Writer/Excel2007/StringTable.php
new file mode 100644
index 0000000..0e8a259
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/StringTable.php
@@ -0,0 +1,319 @@
+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);
+ }
+
+ $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();
+// }
+//
+ $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;
+ }
+}
diff --git a/PHPExcel/Writer/Excel2007/Style.php b/PHPExcel/Writer/Excel2007/Style.php
new file mode 100644
index 0000000..849ad12
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Style.php
@@ -0,0 +1,704 @@
+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->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();
+ } 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;
+ }
+}
diff --git a/PHPExcel/Writer/Excel2007/Theme.php b/PHPExcel/Writer/Excel2007/Theme.php
new file mode 100644
index 0000000..064c3ed
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Theme.php
@@ -0,0 +1,871 @@
+ '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:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '50000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '35000');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '37000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '15000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:lin
+ $objWriter->startElement('a:lin');
+ $objWriter->writeAttribute('ang', '16200000');
+ $objWriter->writeAttribute('scaled', '1');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
+
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '51000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '130000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '80000');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '93000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '130000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '94000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '135000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:lin
+ $objWriter->startElement('a:lin');
+ $objWriter->writeAttribute('ang', '16200000');
+ $objWriter->writeAttribute('scaled', '0');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // 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:solidFill
+ $objWriter->startElement('a:solidFill');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '95000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '105000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $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:solidFill
+ $objWriter->startElement('a:solidFill');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $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:solidFill
+ $objWriter->startElement('a:solidFill');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:prstDash
+ $objWriter->startElement('a:prstDash');
+ $objWriter->writeAttribute('val', 'solid');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+
+
+ // a:effectStyleLst
+ $objWriter->startElement('a:effectStyleLst');
+
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
+
+ // 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:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
+
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '38000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
+
+ // 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:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
+
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '35000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:effectStyle
+ $objWriter->startElement('a:effectStyle');
+
+ // 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:srgbClr
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', '000000');
+
+ // a:alpha
+ $objWriter->startElement('a:alpha');
+ $objWriter->writeAttribute('val', '35000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:scene3d
+ $objWriter->startElement('a:scene3d');
+
+ // 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();
+
+ $objWriter->endElement();
+
+ // 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();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:sp3d
+ $objWriter->startElement('a:sp3d');
+
+ // a:bevelT
+ $objWriter->startElement('a:bevelT');
+ $objWriter->writeAttribute('w', '63500');
+ $objWriter->writeAttribute('h', '25400');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:bgFillStyleLst
+ $objWriter->startElement('a:bgFillStyleLst');
+
+ // 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:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '40000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '40000');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // 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:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '350000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:shade
+ $objWriter->startElement('a:shade');
+ $objWriter->writeAttribute('val', '20000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '255000');
+ $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', '-80000');
+ $objWriter->writeAttribute('r', '50000');
+ $objWriter->writeAttribute('b', '180000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gradFill
+ $objWriter->startElement('a:gradFill');
+ $objWriter->writeAttribute('rotWithShape', '1');
+
+ // a:gsLst
+ $objWriter->startElement('a:gsLst');
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '0');
+
+ // a:schemeClr
+ $objWriter->startElement('a:schemeClr');
+ $objWriter->writeAttribute('val', 'phClr');
+
+ // a:tint
+ $objWriter->startElement('a:tint');
+ $objWriter->writeAttribute('val', '80000');
+ $objWriter->endElement();
+
+ // a:satMod
+ $objWriter->startElement('a:satMod');
+ $objWriter->writeAttribute('val', '300000');
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ $objWriter->endElement();
+
+ // a:gs
+ $objWriter->startElement('a:gs');
+ $objWriter->writeAttribute('pos', '100000');
+
+ // 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();
+
+ $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);
+
+ // 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/PHPExcel/Writer/Excel2007/Workbook.php b/PHPExcel/Writer/Excel2007/Workbook.php
new file mode 100644
index 0000000..d1fe666
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Workbook.php
@@ -0,0 +1,456 @@
+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/PHPExcel/Writer/Excel2007/Worksheet.php b/PHPExcel/Writer/Excel2007/Worksheet.php
new file mode 100644
index 0000000..7d93f5a
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/Worksheet.php
@@ -0,0 +1,1220 @@
+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 = $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 = ($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) ) );
+ } 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();
+ }
+ }
+}
diff --git a/PHPExcel/Writer/Excel2007/WriterPart.php b/PHPExcel/Writer/Excel2007/WriterPart.php
new file mode 100644
index 0000000..982117b
--- /dev/null
+++ b/PHPExcel/Writer/Excel2007/WriterPart.php
@@ -0,0 +1,81 @@
+_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/PHPExcel/Writer/Excel5.php b/PHPExcel/Writer/Excel5.php
new file mode 100644
index 0000000..3f816fa
--- /dev/null
+++ b/PHPExcel/Writer/Excel5.php
@@ -0,0 +1,935 @@
+_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->_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($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);
+
+ } 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();
+ $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)));
+ $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;
+ }
+}
diff --git a/PHPExcel/Writer/Excel5/BIFFwriter.php b/PHPExcel/Writer/Excel5/BIFFwriter.php
new file mode 100644
index 0000000..b3e48bc
--- /dev/null
+++ b/PHPExcel/Writer/Excel5/BIFFwriter.php
@@ -0,0 +1,255 @@
+
+// *
+// * The majority of this is _NOT_ my code. I simply ported it from the
+// * PERL Spreadsheet::WriteExcel module.
+// *
+// * The author of the Spreadsheet::WriteExcel module is John McNamara
+// * ';
+ 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;
+ } 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 $cellAddress) {
+ $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : '';
+ $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'];
+
+ // 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 .= ' _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;
+ }
+
+ private function _setMargins(PHPExcel_Worksheet $pSheet) {
+ $htmlPage = '@page { ';
+ $htmlBody = 'body { ';
+
+ $left = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
+ $htmlPage .= 'left-margin: ' . $left;
+ $htmlBody .= 'left-margin: ' . $left;
+ $right = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
+ $htmlPage .= 'right-margin: ' . $right;
+ $htmlBody .= 'right-margin: ' . $right;
+ $top = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
+ $htmlPage .= 'top-margin: ' . $top;
+ $htmlBody .= 'top-margin: ' . $top;
+ $bottom = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
+ $htmlPage .= 'bottom-margin: ' . $bottom;
+ $htmlBody .= 'bottom-margin: ' . $bottom;
+
+ $htmlPage .= "}\n";
+ $htmlBody .= "}\n";
+
+ return "\n";
+ }
+
+}
diff --git a/PHPExcel/Writer/IWriter.php b/PHPExcel/Writer/IWriter.php
new file mode 100644
index 0000000..6974c93
--- /dev/null
+++ b/PHPExcel/Writer/IWriter.php
@@ -0,0 +1,46 @@
+_renderer = new $rendererName($phpExcel);
+ }
+
+
+ /**
+ * Magic method to handle direct calls to the configured PDF renderer wrapper class.
+ *
+ * @param string $name Renderer library method name
+ * @param mixed[] $arguments Array of arguments to pass to the renderer method
+ * @return mixed Returned data from the PDF renderer wrapper method
+ */
+ public function __call($name, $arguments)
+ {
+ if ($this->_renderer === NULL) {
+ throw new PHPExcel_Writer_Exception("PDF Rendering library has not been defined.");
+ }
+
+ return call_user_func_array(array($this->_renderer, $name), $arguments);
+ }
+
+}
diff --git a/PHPExcel/Writer/PDF/Core.php b/PHPExcel/Writer/PDF/Core.php
new file mode 100644
index 0000000..3b281f4
--- /dev/null
+++ b/PHPExcel/Writer/PDF/Core.php
@@ -0,0 +1,364 @@
+ 'LETTER', // (8.5 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_SMALL
+ => 'LETTER', // (8.5 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_TABLOID
+ => array(792.00, 1224.00), // (11 in. by 17 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEDGER
+ => array(1224.00, 792.00), // (17 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL
+ => 'LEGAL', // (8.5 in. by 14 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_STATEMENT
+ => array(396.00, 612.00), // (5.5 in. by 8.5 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_EXECUTIVE
+ => 'EXECUTIVE', // (7.25 in. by 10.5 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3
+ => 'A3', // (297 mm by 420 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4
+ => 'A4', // (210 mm by 297 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_SMALL
+ => 'A4', // (210 mm by 297 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5
+ => 'A5', // (148 mm by 210 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_B4
+ => 'B4', // (250 mm by 353 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_B5
+ => 'B5', // (176 mm by 250 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_FOLIO
+ => 'FOLIO', // (8.5 in. by 13 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_QUARTO
+ => array(609.45, 779.53), // (215 mm by 275 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_1
+ => array(720.00, 1008.00), // (10 in. by 14 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_2
+ => array(792.00, 1224.00), // (11 in. by 17 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_NOTE
+ => 'LETTER', // (8.5 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO9_ENVELOPE
+ => array(279.00, 639.00), // (3.875 in. by 8.875 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO10_ENVELOPE
+ => array(297.00, 684.00), // (4.125 in. by 9.5 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO11_ENVELOPE
+ => array(324.00, 747.00), // (4.5 in. by 10.375 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO12_ENVELOPE
+ => array(342.00, 792.00), // (4.75 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO14_ENVELOPE
+ => array(360.00, 828.00), // (5 in. by 11.5 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_C
+ => array(1224.00, 1584.00), // (17 in. by 22 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_D
+ => array(1584.00, 2448.00), // (22 in. by 34 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_E
+ => array(2448.00, 3168.00), // (34 in. by 44 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_DL_ENVELOPE
+ => array(311.81, 623.62), // (110 mm by 220 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_C5_ENVELOPE
+ => 'C5', // (162 mm by 229 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_C3_ENVELOPE
+ => 'C3', // (324 mm by 458 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_C4_ENVELOPE
+ => 'C4', // (229 mm by 324 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_C6_ENVELOPE
+ => 'C6', // (114 mm by 162 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_C65_ENVELOPE
+ => array(323.15, 649.13), // (114 mm by 229 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_B4_ENVELOPE
+ => 'B4', // (250 mm by 353 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_B5_ENVELOPE
+ => 'B5', // (176 mm by 250 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_B6_ENVELOPE
+ => array(498.90, 354.33), // (176 mm by 125 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_ITALY_ENVELOPE
+ => array(311.81, 651.97), // (110 mm by 230 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_MONARCH_ENVELOPE
+ => array(279.00, 540.00), // (3.875 in. by 7.5 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_6_3_4_ENVELOPE
+ => array(261.00, 468.00), // (3.625 in. by 6.5 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_US_STANDARD_FANFOLD
+ => array(1071.00, 792.00), // (14.875 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD
+ => array(612.00, 864.00), // (8.5 in. by 12 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD
+ => 'FOLIO', // (8.5 in. by 13 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_ISO_B4
+ => 'B4', // (250 mm by 353 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD
+ => array(566.93, 419.53), // (200 mm by 148 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_1
+ => array(648.00, 792.00), // (9 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_2
+ => array(720.00, 792.00), // (10 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_3
+ => array(1080.00, 792.00), // (15 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_INVITE_ENVELOPE
+ => array(623.62, 623.62), // (220 mm by 220 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER
+ => array(667.80, 864.00), // (9.275 in. by 12 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER
+ => array(667.80, 1080.00), // (9.275 in. by 15 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER
+ => array(841.68, 1296.00), // (11.69 in. by 18 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_EXTRA_PAPER
+ => array(668.98, 912.76), // (236 mm by 322 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER
+ => array(595.80, 792.00), // (8.275 in. by 11 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER
+ => 'A4', // (210 mm by 297 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER
+ => array(667.80, 864.00), // (9.275 in. by 12 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER
+ => array(643.46, 1009.13), // (227 mm by 356 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER
+ => array(864.57, 1380.47), // (305 mm by 487 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_PLUS_PAPER
+ => array(612.00, 913.68), // (8.5 in. by 12.69 in.)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_PLUS_PAPER
+ => array(595.28, 935.43), // (210 mm by 330 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER
+ => 'A5', // (148 mm by 210 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER
+ => array(515.91, 728.50), // (182 mm by 257 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_EXTRA_PAPER
+ => array(912.76, 1261.42), // (322 mm by 445 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5_EXTRA_PAPER
+ => array(493.23, 666.14), // (174 mm by 235 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER
+ => array(569.76, 782.36), // (201 mm by 276 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER
+ => 'A2', // (420 mm by 594 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER
+ => 'A3', // (297 mm by 420 mm)
+ PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER
+ => array(912.76, 1261.42) // (322 mm by 445 mm)
+ );
+
+ /**
+ * Create a new PHPExcel_Writer_PDF
+ *
+ * @param PHPExcel $phpExcel PHPExcel object
+ */
+ public function __construct(PHPExcel $phpExcel)
+ {
+ parent::__construct($phpExcel);
+ $this->setUseInlineCss(TRUE);
+ $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir();
+ }
+
+ /**
+ * Get Font
+ *
+ * @return string
+ */
+ public function getFont()
+ {
+ return $this->_font;
+ }
+
+ /**
+ * Set font. Examples:
+ * 'arialunicid0-chinese-simplified'
+ * 'arialunicid0-chinese-traditional'
+ * 'arialunicid0-korean'
+ * 'arialunicid0-japanese'
+ *
+ * @param string $fontName
+ */
+ public function setFont($fontName)
+ {
+ $this->_font = $fontName;
+ return $this;
+ }
+
+ /**
+ * Get Paper Size
+ *
+ * @return int
+ */
+ public function getPaperSize()
+ {
+ return $this->_paperSize;
+ }
+
+ /**
+ * Set Paper Size
+ *
+ * @param string $pValue Paper size
+ * @return PHPExcel_Writer_PDF
+ */
+ public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER)
+ {
+ $this->_paperSize = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get Orientation
+ *
+ * @return string
+ */
+ public function getOrientation()
+ {
+ return $this->_orientation;
+ }
+
+ /**
+ * Set Orientation
+ *
+ * @param string $pValue Page orientation
+ * @return PHPExcel_Writer_PDF
+ */
+ public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT)
+ {
+ $this->_orientation = $pValue;
+ return $this;
+ }
+
+ /**
+ * Get temporary storage directory
+ *
+ * @return string
+ */
+ public function getTempDir()
+ {
+ return $this->_tempDir;
+ }
+
+ /**
+ * Set temporary storage directory
+ *
+ * @param string $pValue Temporary storage directory
+ * @throws PHPExcel_Writer_Exception when directory does not exist
+ * @return PHPExcel_Writer_PDF
+ */
+ public function setTempDir($pValue = '')
+ {
+ if (is_dir($pValue)) {
+ $this->_tempDir = $pValue;
+ } else {
+ throw new PHPExcel_Writer_Exception("Directory does not exist: $pValue");
+ }
+ return $this;
+ }
+
+ /**
+ * Save PHPExcel to PDF file, pre-save
+ *
+ * @param string $pFilename Name of the file to save as
+ * @throws PHPExcel_Writer_Exception
+ */
+ protected function prepareForSave($pFilename = NULL)
+ {
+ // garbage collect
+ $this->_phpExcel->garbageCollect();
+
+ $this->_saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType();
+ PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
+
+ // Open file
+ $fileHandle = fopen($pFilename, 'w');
+ if ($fileHandle === FALSE) {
+ throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing.");
+ }
+
+ // Set PDF
+ $this->_isPdf = TRUE;
+ // Build CSS
+ $this->buildCSS(TRUE);
+
+ return $fileHandle;
+ }
+
+ /**
+ * Save PHPExcel to PDF file, post-save
+ *
+ * @param resource $fileHandle
+ * @throws PHPExcel_Writer_Exception
+ */
+ protected function restoreStateAfterSave($fileHandle)
+ {
+ // Close file
+ fclose($fileHandle);
+
+ PHPExcel_Calculation::setArrayReturnType($this->_saveArrayReturnType);
+ }
+
+}
diff --git a/PHPExcel/Writer/PDF/DomPDF.php b/PHPExcel/Writer/PDF/DomPDF.php
new file mode 100644
index 0000000..111dd36
--- /dev/null
+++ b/PHPExcel/Writer/PDF/DomPDF.php
@@ -0,0 +1,120 @@
+getSheetIndex())) {
+ $orientation = ($this->_phpExcel->getSheet(0)->getPageSetup()->getOrientation()
+ == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ $printPaperSize = $this->_phpExcel->getSheet(0)->getPageSetup()->getPaperSize();
+ $printMargins = $this->_phpExcel->getSheet(0)->getPageMargins();
+ } else {
+ $orientation = ($this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
+ == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ $printPaperSize = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
+ $printMargins = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageMargins();
+ }
+
+ // Override Page Orientation
+ if (!is_null($this->getOrientation())) {
+ $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT)
+ ? PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT
+ : $this->getOrientation();
+ }
+ // Override Paper Size
+ if (!is_null($this->getPaperSize())) {
+ $printPaperSize = $this->getPaperSize();
+ }
+
+ if (isset(self::$_paperSizes[$printPaperSize])) {
+ $paperSize = self::$_paperSizes[$printPaperSize];
+ }
+
+ $orientation = ($orientation == 'L') ? 'landscape' : 'portrait';
+
+ // Create PDF
+ $pdf = new DOMPDF();
+ $pdf->set_paper(strtolower($paperSize), $orientation);
+
+ $pdf->load_html(
+ $this->generateHTMLHeader(FALSE) .
+ $this->generateSheetData() .
+ $this->generateHTMLFooter()
+ );
+ $pdf->render();
+
+ // Write to file
+ fwrite($fileHandle, $pdf->output());
+
+ parent::restoreStateAfterSave($fileHandle);
+ }
+
+}
diff --git a/PHPExcel/Writer/PDF/mPDF.php b/PHPExcel/Writer/PDF/mPDF.php
new file mode 100644
index 0000000..8e274f4
--- /dev/null
+++ b/PHPExcel/Writer/PDF/mPDF.php
@@ -0,0 +1,130 @@
+getSheetIndex())) {
+ $orientation = ($this->_phpExcel->getSheet(0)->getPageSetup()->getOrientation()
+ == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ $printPaperSize = $this->_phpExcel->getSheet(0)->getPageSetup()->getPaperSize();
+ $printMargins = $this->_phpExcel->getSheet(0)->getPageMargins();
+ } else {
+ $orientation = ($this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
+ == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ $printPaperSize = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
+ $printMargins = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageMargins();
+ }
+ $this->setOrientation($orientation);
+
+ // Override Page Orientation
+ if (!is_null($this->getOrientation())) {
+ $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT)
+ ? PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT
+ : $this->getOrientation();
+ }
+ $orientation = strtoupper($orientation);
+
+ // Override Paper Size
+ if (!is_null($this->getPaperSize())) {
+ $printPaperSize = $this->getPaperSize();
+ }
+
+ if (isset(self::$_paperSizes[$printPaperSize])) {
+ $paperSize = self::$_paperSizes[$printPaperSize];
+ }
+
+ // Create PDF
+ $pdf = new mpdf();
+ $ortmp = $orientation;
+ $pdf->_setPageSize(strtoupper($paperSize), $ortmp);
+ $pdf->DefOrientation = $orientation;
+ $pdf->AddPage($orientation);
+
+ // Document info
+ $pdf->SetTitle($this->_phpExcel->getProperties()->getTitle());
+ $pdf->SetAuthor($this->_phpExcel->getProperties()->getCreator());
+ $pdf->SetSubject($this->_phpExcel->getProperties()->getSubject());
+ $pdf->SetKeywords($this->_phpExcel->getProperties()->getKeywords());
+ $pdf->SetCreator($this->_phpExcel->getProperties()->getCreator());
+
+ $pdf->WriteHTML(
+ $this->generateHTMLHeader(FALSE) .
+ $this->generateSheetData() .
+ $this->generateHTMLFooter()
+ );
+
+ // Write to file
+ fwrite($fileHandle, $pdf->Output('', 'S'));
+
+ parent::restoreStateAfterSave($fileHandle);
+ }
+
+}
diff --git a/PHPExcel/Writer/PDF/tcPDF.php b/PHPExcel/Writer/PDF/tcPDF.php
new file mode 100644
index 0000000..c3809ec
--- /dev/null
+++ b/PHPExcel/Writer/PDF/tcPDF.php
@@ -0,0 +1,136 @@
+getSheetIndex())) {
+ $orientation = ($this->_phpExcel->getSheet(0)->getPageSetup()->getOrientation()
+ == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ $printPaperSize = $this->_phpExcel->getSheet(0)->getPageSetup()->getPaperSize();
+ $printMargins = $this->_phpExcel->getSheet(0)->getPageMargins();
+ } else {
+ $orientation = ($this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
+ == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ $printPaperSize = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
+ $printMargins = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageMargins();
+ }
+
+ // Override Page Orientation
+ if (!is_null($this->getOrientation())) {
+ $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
+ ? 'L'
+ : 'P';
+ }
+ // Override Paper Size
+ if (!is_null($this->getPaperSize())) {
+ $printPaperSize = $this->getPaperSize();
+ }
+
+ if (isset(self::$_paperSizes[$printPaperSize])) {
+ $paperSize = self::$_paperSizes[$printPaperSize];
+ }
+
+
+ // Create PDF
+ $pdf = new TCPDF($orientation, 'pt', $paperSize);
+ $pdf->setFontSubsetting(FALSE);
+ // Set margins, converting inches to points (using 72 dpi)
+ $pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72);
+ $pdf->SetAutoPageBreak(TRUE, $printMargins->getBottom() * 72);
+
+ $pdf->setPrintHeader(FALSE);
+ $pdf->setPrintFooter(FALSE);
+
+ $pdf->AddPage();
+
+ // Set the appropriate font
+ $pdf->SetFont($this->getFont());
+ $pdf->writeHTML(
+ $this->generateHTMLHeader(FALSE) .
+ $this->generateSheetData() .
+ $this->generateHTMLFooter()
+ );
+
+ // Document info
+ $pdf->SetTitle($this->_phpExcel->getProperties()->getTitle());
+ $pdf->SetAuthor($this->_phpExcel->getProperties()->getCreator());
+ $pdf->SetSubject($this->_phpExcel->getProperties()->getSubject());
+ $pdf->SetKeywords($this->_phpExcel->getProperties()->getKeywords());
+ $pdf->SetCreator($this->_phpExcel->getProperties()->getCreator());
+
+ // Write to file
+ fwrite($fileHandle, $pdf->output($pFilename, 'S'));
+
+ parent::restoreStateAfterSave($fileHandle);
+ }
+
+}
diff --git a/PHPExcel/locale/bg/config b/PHPExcel/locale/bg/config
new file mode 100644
index 0000000..d7ecb2b
--- /dev/null
+++ b/PHPExcel/locale/bg/config
@@ -0,0 +1,49 @@
+##
+## PHPExcel
+##
+
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = лв
+
+
+##
+## Excel Error Codes (For future use)
+
+##
+NULL = #ПРАЗНО!
+DIV0 = #ДЕЛ/0!
+VALUE = #СТОЙНОСТ!
+REF = #РЕФ!
+NAME = #ИМЕ?
+NUM = #ЧИСЛО!
+NA = #Н/Д
diff --git a/PHPExcel/locale/cs/config b/PHPExcel/locale/cs/config
new file mode 100644
index 0000000..af4589b
--- /dev/null
+++ b/PHPExcel/locale/cs/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = Kč
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULL!
+DIV0 = #DIV/0!
+VALUE = #HODNOTA!
+REF = #REF!
+NAME = #NÁZEV?
+NUM = #NUM!
+NA = #N/A
diff --git a/PHPExcel/locale/cs/functions b/PHPExcel/locale/cs/functions
new file mode 100644
index 0000000..f324759
--- /dev/null
+++ b/PHPExcel/locale/cs/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Funkce doplňků a automatizace
+##
+GETPIVOTDATA = ZÍSKATKONTDATA ## Vrátí data uložená v kontingenční tabulce. Pomocí funkce ZÍSKATKONTDATA můžete načíst souhrnná data z kontingenční tabulky, pokud jsou tato data v kontingenční sestavě zobrazena.
+
+
+##
+## Cube functions Funkce pro práci s krychlemi
+##
+CUBEKPIMEMBER = CUBEKPIMEMBER ## Vrátí název, vlastnost a velikost klíčového ukazatele výkonu (KUV) a zobrazí v buňce název a vlastnost. Klíčový ukazatel výkonu je kvantifikovatelná veličina, například hrubý měsíční zisk nebo čtvrtletní obrat na zaměstnance, která se používá pro sledování výkonnosti organizace.
+CUBEMEMBER = CUBEMEMBER ## Vrátí člen nebo n-tici v hierarchii krychle. Slouží k ověření, zda v krychli existuje člen nebo n-tice.
+CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY ## Vrátí hodnotu vlastnosti člena v krychli. Slouží k ověření, zda v krychli existuje člen s daným názvem, a k vrácení konkrétní vlastnosti tohoto člena.
+CUBERANKEDMEMBER = CUBERANKEDMEMBER ## Vrátí n-tý nebo pořadový člen sady. Použijte ji pro vrácení jednoho nebo více prvků sady, například obchodníka s nejvyšším obratem nebo deseti nejlepších studentů.
+CUBESET = CUBESET ## Definuje vypočtenou sadu členů nebo n-tic odesláním výrazu sady do krychle na serveru, který vytvoří sadu a potom ji vrátí do aplikace Microsoft Office Excel.
+CUBESETCOUNT = CUBESETCOUNT ## Vrátí počet položek v množině
+CUBEVALUE = CUBEVALUE ## Vrátí úhrnnou hodnotu z krychle.
+
+
+##
+## Database functions Funkce databáze
+##
+DAVERAGE = DPRŮMĚR ## Vrátí průměr vybraných položek databáze.
+DCOUNT = DPOČET ## Spočítá buňky databáze obsahující čísla.
+DCOUNTA = DPOČET2 ## Spočítá buňky databáze, které nejsou prázdné.
+DGET = DZÍSKAT ## Extrahuje z databáze jeden záznam splňující zadaná kritéria.
+DMAX = DMAX ## Vrátí maximální hodnotu z vybraných položek databáze.
+DMIN = DMIN ## Vrátí minimální hodnotu z vybraných položek databáze.
+DPRODUCT = DSOUČIN ## Vynásobí hodnoty určitého pole záznamů v databázi, které splňují daná kritéria.
+DSTDEV = DSMODCH.VÝBĚR ## Odhadne směrodatnou odchylku výběru vybraných položek databáze.
+DSTDEVP = DSMODCH ## Vypočte směrodatnou odchylku základního souboru vybraných položek databáze.
+DSUM = DSUMA ## Sečte čísla ve sloupcovém poli záznamů databáze, která splňují daná kritéria.
+DVAR = DVAR.VÝBĚR ## Odhadne rozptyl výběru vybraných položek databáze.
+DVARP = DVAR ## Vypočte rozptyl základního souboru vybraných položek databáze.
+
+
+##
+## Date and time functions Funkce data a času
+##
+DATE = DATUM ## Vrátí pořadové číslo určitého data.
+DATEVALUE = DATUMHODN ## Převede datum ve formě textu na pořadové číslo.
+DAY = DEN ## Převede pořadové číslo na den v měsíci.
+DAYS360 = ROK360 ## Vrátí počet dní mezi dvěma daty na základě roku s 360 dny.
+EDATE = EDATE ## Vrátí pořadové číslo data, které označuje určený počet měsíců před nebo po počátečním datu.
+EOMONTH = EOMONTH ## Vrátí pořadové číslo posledního dne měsíce před nebo po zadaném počtu měsíců.
+HOUR = HODINA ## Převede pořadové číslo na hodinu.
+MINUTE = MINUTA ## Převede pořadové číslo na minutu.
+MONTH = MĚSÍC ## Převede pořadové číslo na měsíc.
+NETWORKDAYS = NETWORKDAYS ## Vrátí počet celých pracovních dní mezi dvěma daty.
+NOW = NYNÍ ## Vrátí pořadové číslo aktuálního data a času.
+SECOND = SEKUNDA ## Převede pořadové číslo na sekundu.
+TIME = ČAS ## Vrátí pořadové číslo určitého času.
+TIMEVALUE = ČASHODN ## Převede čas ve formě textu na pořadové číslo.
+TODAY = DNES ## Vrátí pořadové číslo dnešního data.
+WEEKDAY = DENTÝDNE ## Převede pořadové číslo na den v týdnu.
+WEEKNUM = WEEKNUM ## Převede pořadové číslo na číslo představující číselnou pozici týdne v roce.
+WORKDAY = WORKDAY ## Vrátí pořadové číslo data před nebo po zadaném počtu pracovních dní.
+YEAR = ROK ## Převede pořadové číslo na rok.
+YEARFRAC = YEARFRAC ## Vrátí část roku vyjádřenou zlomkem a představující počet celých dní mezi počátečním a koncovým datem.
+
+
+##
+## Engineering functions Inženýrské funkce (Technické funkce)
+##
+BESSELI = BESSELI ## Vrátí modifikovanou Besselovu funkci In(x).
+BESSELJ = BESSELJ ## Vrátí modifikovanou Besselovu funkci Jn(x).
+BESSELK = BESSELK ## Vrátí modifikovanou Besselovu funkci Kn(x).
+BESSELY = BESSELY ## Vrátí Besselovu funkci Yn(x).
+BIN2DEC = BIN2DEC ## Převede binární číslo na desítkové.
+BIN2HEX = BIN2HEX ## Převede binární číslo na šestnáctkové.
+BIN2OCT = BIN2OCT ## Převede binární číslo na osmičkové.
+COMPLEX = COMPLEX ## Převede reálnou a imaginární část na komplexní číslo.
+CONVERT = CONVERT ## Převede číslo do jiného jednotkového měrného systému.
+DEC2BIN = DEC2BIN ## Převede desítkového čísla na dvojkové
+DEC2HEX = DEC2HEX ## Převede desítkové číslo na šestnáctkové.
+DEC2OCT = DEC2OCT ## Převede desítkové číslo na osmičkové.
+DELTA = DELTA ## Testuje rovnost dvou hodnot.
+ERF = ERF ## Vrátí chybovou funkci.
+ERFC = ERFC ## Vrátí doplňkovou chybovou funkci.
+GESTEP = GESTEP ## Testuje, zda je číslo větší než mezní hodnota.
+HEX2BIN = HEX2BIN ## Převede šestnáctkové číslo na binární.
+HEX2DEC = HEX2DEC ## Převede šestnáctkové číslo na desítkové.
+HEX2OCT = HEX2OCT ## Převede šestnáctkové číslo na osmičkové.
+IMABS = IMABS ## Vrátí absolutní hodnotu (modul) komplexního čísla.
+IMAGINARY = IMAGINARY ## Vrátí imaginární část komplexního čísla.
+IMARGUMENT = IMARGUMENT ## Vrátí argument théta, úhel vyjádřený v radiánech.
+IMCONJUGATE = IMCONJUGATE ## Vrátí komplexně sdružené číslo ke komplexnímu číslu.
+IMCOS = IMCOS ## Vrátí kosinus komplexního čísla.
+IMDIV = IMDIV ## Vrátí podíl dvou komplexních čísel.
+IMEXP = IMEXP ## Vrátí exponenciální tvar komplexního čísla.
+IMLN = IMLN ## Vrátí přirozený logaritmus komplexního čísla.
+IMLOG10 = IMLOG10 ## Vrátí dekadický logaritmus komplexního čísla.
+IMLOG2 = IMLOG2 ## Vrátí logaritmus komplexního čísla při základu 2.
+IMPOWER = IMPOWER ## Vrátí komplexní číslo umocněné na celé číslo.
+IMPRODUCT = IMPRODUCT ## Vrátí součin komplexních čísel.
+IMREAL = IMREAL ## Vrátí reálnou část komplexního čísla.
+IMSIN = IMSIN ## Vrátí sinus komplexního čísla.
+IMSQRT = IMSQRT ## Vrátí druhou odmocninu komplexního čísla.
+IMSUB = IMSUB ## Vrátí rozdíl mezi dvěma komplexními čísly.
+IMSUM = IMSUM ## Vrátí součet dvou komplexních čísel.
+OCT2BIN = OCT2BIN ## Převede osmičkové číslo na binární.
+OCT2DEC = OCT2DEC ## Převede osmičkové číslo na desítkové.
+OCT2HEX = OCT2HEX ## Převede osmičkové číslo na šestnáctkové.
+
+
+##
+## Financial functions Finanční funkce
+##
+ACCRINT = ACCRINT ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen v pravidelných termínech.
+ACCRINTM = ACCRINTM ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen k datu splatnosti.
+AMORDEGRC = AMORDEGRC ## Vrátí lineární amortizaci v každém účetním období pomocí koeficientu amortizace.
+AMORLINC = AMORLINC ## Vrátí lineární amortizaci v každém účetním období.
+COUPDAYBS = COUPDAYBS ## Vrátí počet dnů od začátku období placení kupónů do data splatnosti.
+COUPDAYS = COUPDAYS ## Vrátí počet dnů v období placení kupónů, které obsahuje den zúčtování.
+COUPDAYSNC = COUPDAYSNC ## Vrátí počet dnů od data zúčtování do následujícího data placení kupónu.
+COUPNCD = COUPNCD ## Vrátí následující datum placení kupónu po datu zúčtování.
+COUPNUM = COUPNUM ## Vrátí počet kupónů splatných mezi datem zúčtování a datem splatnosti.
+COUPPCD = COUPPCD ## Vrátí předchozí datum placení kupónu před datem zúčtování.
+CUMIPMT = CUMIPMT ## Vrátí kumulativní úrok splacený mezi dvěma obdobími.
+CUMPRINC = CUMPRINC ## Vrátí kumulativní jistinu splacenou mezi dvěma obdobími půjčky.
+DB = ODPIS.ZRYCH ## Vrátí odpis aktiva za určité období pomocí degresivní metody odpisu s pevným zůstatkem.
+DDB = ODPIS.ZRYCH2 ## Vrátí odpis aktiva za určité období pomocí dvojité degresivní metody odpisu nebo jiné metody, kterou zadáte.
+DISC = DISC ## Vrátí diskontní sazbu cenného papíru.
+DOLLARDE = DOLLARDE ## Převede částku v korunách vyjádřenou zlomkem na částku v korunách vyjádřenou desetinným číslem.
+DOLLARFR = DOLLARFR ## Převede částku v korunách vyjádřenou desetinným číslem na částku v korunách vyjádřenou zlomkem.
+DURATION = DURATION ## Vrátí roční dobu cenného papíru s pravidelnými úrokovými sazbami.
+EFFECT = EFFECT ## Vrátí efektivní roční úrokovou sazbu.
+FV = BUDHODNOTA ## Vrátí budoucí hodnotu investice.
+FVSCHEDULE = FVSCHEDULE ## Vrátí budoucí hodnotu počáteční jistiny po použití série sazeb složitého úroku.
+INTRATE = INTRATE ## Vrátí úrokovou sazbu plně investovaného cenného papíru.
+IPMT = PLATBA.ÚROK ## Vrátí výšku úroku investice za dané období.
+IRR = MÍRA.VÝNOSNOSTI ## Vrátí vnitřní výnosové procento série peněžních toků.
+ISPMT = ISPMT ## Vypočte výši úroku z investice zaplaceného během určitého období.
+MDURATION = MDURATION ## Vrátí Macauleyho modifikovanou dobu cenného papíru o nominální hodnotě 100 Kč.
+MIRR = MOD.MÍRA.VÝNOSNOSTI ## Vrátí vnitřní sazbu výnosu, přičemž kladné a záporné hodnoty peněžních prostředků jsou financovány podle různých sazeb.
+NOMINAL = NOMINAL ## Vrátí nominální roční úrokovou sazbu.
+NPER = POČET.OBDOBÍ ## Vrátí počet období pro investici.
+NPV = ČISTÁ.SOUČHODNOTA ## Vrátí čistou současnou hodnotu investice vypočítanou na základě série pravidelných peněžních toků a diskontní sazby.
+ODDFPRICE = ODDFPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným prvním obdobím.
+ODDFYIELD = ODDFYIELD ## Vrátí výnos cenného papíru s odlišným prvním obdobím.
+ODDLPRICE = ODDLPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným posledním obdobím.
+ODDLYIELD = ODDLYIELD ## Vrátí výnos cenného papíru s odlišným posledním obdobím.
+PMT = PLATBA ## Vrátí hodnotu pravidelné splátky anuity.
+PPMT = PLATBA.ZÁKLAD ## Vrátí hodnotu splátky jistiny pro zadanou investici za dané období.
+PRICE = PRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen v pravidelných termínech.
+PRICEDISC = PRICEDISC ## Vrátí cenu diskontního cenného papíru o nominální hodnotě 100 Kč.
+PRICEMAT = PRICEMAT ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen k datu splatnosti.
+PV = SOUČHODNOTA ## Vrátí současnou hodnotu investice.
+RATE = ÚROKOVÁ.MÍRA ## Vrátí úrokovou sazbu vztaženou na období anuity.
+RECEIVED = RECEIVED ## Vrátí částku obdrženou k datu splatnosti plně investovaného cenného papíru.
+SLN = ODPIS.LIN ## Vrátí přímé odpisy aktiva pro jedno období.
+SYD = ODPIS.NELIN ## Vrátí směrné číslo ročních odpisů aktiva pro zadané období.
+TBILLEQ = TBILLEQ ## Vrátí výnos směnky státní pokladny ekvivalentní výnosu obligace.
+TBILLPRICE = TBILLPRICE ## Vrátí cenu směnky státní pokladny o nominální hodnotě 100 Kč.
+TBILLYIELD = TBILLYIELD ## Vrátí výnos směnky státní pokladny.
+VDB = ODPIS.ZA.INT ## Vrátí odpis aktiva pro určité období nebo část období pomocí degresivní metody odpisu.
+XIRR = XIRR ## Vrátí vnitřní výnosnost pro harmonogram peněžních toků, který nemusí být nutně periodický.
+XNPV = XNPV ## Vrátí čistou současnou hodnotu pro harmonogram peněžních toků, který nemusí být nutně periodický.
+YIELD = YIELD ## Vrátí výnos cenného papíru, ze kterého je úrok placen v pravidelných termínech.
+YIELDDISC = YIELDDISC ## Vrátí roční výnos diskontního cenného papíru, například směnky státní pokladny.
+YIELDMAT = YIELDMAT ## Vrátí roční výnos cenného papíru, ze kterého je úrok placen k datu splatnosti.
+
+
+##
+## Information functions Informační funkce
+##
+CELL = POLÍČKO ## Vrátí informace o formátování, umístění nebo obsahu buňky.
+ERROR.TYPE = CHYBA.TYP ## Vrátí číslo odpovídající typu chyby.
+INFO = O.PROSTŘEDÍ ## Vrátí informace o aktuálním pracovním prostředí.
+ISBLANK = JE.PRÁZDNÉ ## Vrátí hodnotu PRAVDA, pokud se argument hodnota odkazuje na prázdnou buňku.
+ISERR = JE.CHYBA ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota (kromě #N/A).
+ISERROR = JE.CHYBHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota.
+ISEVEN = ISEVEN ## Vrátí hodnotu PRAVDA, pokud je číslo sudé.
+ISLOGICAL = JE.LOGHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota logická hodnota.
+ISNA = JE.NEDEF ## Vrátí hodnotu PRAVDA, pokud je argument hodnota chybová hodnota #N/A.
+ISNONTEXT = JE.NETEXT ## Vrátí hodnotu PRAVDA, pokud argument hodnota není text.
+ISNUMBER = JE.ČÍSLO ## Vrátí hodnotu PRAVDA, pokud je argument hodnota číslo.
+ISODD = ISODD ## Vrátí hodnotu PRAVDA, pokud je číslo liché.
+ISREF = JE.ODKAZ ## Vrátí hodnotu PRAVDA, pokud je argument hodnota odkaz.
+ISTEXT = JE.TEXT ## Vrátí hodnotu PRAVDA, pokud je argument hodnota text.
+N = N ## Vrátí hodnotu převedenou na číslo.
+NA = NEDEF ## Vrátí chybovou hodnotu #N/A.
+TYPE = TYP ## Vrátí číslo označující datový typ hodnoty.
+
+
+##
+## Logical functions Logické funkce
+##
+AND = A ## Vrátí hodnotu PRAVDA, mají-li všechny argumenty hodnotu PRAVDA.
+FALSE = NEPRAVDA ## Vrátí logickou hodnotu NEPRAVDA.
+IF = KDYŽ ## Určí, který logický test má proběhnout.
+IFERROR = IFERROR ## Pokud je vzorec vyhodnocen jako chyba, vrátí zadanou hodnotu. V opačném případě vrátí výsledek vzorce.
+NOT = NE ## Provede logickou negaci argumentu funkce.
+OR = NEBO ## Vrátí hodnotu PRAVDA, je-li alespoň jeden argument roven hodnotě PRAVDA.
+TRUE = PRAVDA ## Vrátí logickou hodnotu PRAVDA.
+
+
+##
+## Lookup and reference functions Vyhledávací funkce
+##
+ADDRESS = ODKAZ ## Vrátí textový odkaz na jednu buňku listu.
+AREAS = POČET.BLOKŮ ## Vrátí počet oblastí v odkazu.
+CHOOSE = ZVOLIT ## Zvolí hodnotu ze seznamu hodnot.
+COLUMN = SLOUPEC ## Vrátí číslo sloupce odkazu.
+COLUMNS = SLOUPCE ## Vrátí počet sloupců v odkazu.
+HLOOKUP = VVYHLEDAT ## Prohledá horní řádek matice a vrátí hodnotu určené buňky.
+HYPERLINK = HYPERTEXTOVÝ.ODKAZ ## Vytvoří zástupce nebo odkaz, který otevře dokument uložený na síťovém serveru, v síti intranet nebo Internet.
+INDEX = INDEX ## Pomocí rejstříku zvolí hodnotu z odkazu nebo matice.
+INDIRECT = NEPŘÍMÝ.ODKAZ ## Vrátí odkaz určený textovou hodnotou.
+LOOKUP = VYHLEDAT ## Vyhledá hodnoty ve vektoru nebo matici.
+MATCH = POZVYHLEDAT ## Vyhledá hodnoty v odkazu nebo matici.
+OFFSET = POSUN ## Vrátí posun odkazu od zadaného odkazu.
+ROW = ŘÁDEK ## Vrátí číslo řádku odkazu.
+ROWS = ŘÁDKY ## Vrátí počet řádků v odkazu.
+RTD = RTD ## Načte data reálného času z programu, který podporuje automatizaci modelu COM (Automatizace: Způsob práce s objekty určité aplikace z jiné aplikace nebo nástroje pro vývoj. Automatizace (dříve nazývaná automatizace OLE) je počítačovým standardem a je funkcí modelu COM (Component Object Model).).
+TRANSPOSE = TRANSPOZICE ## Vrátí transponovanou matici.
+VLOOKUP = SVYHLEDAT ## Prohledá první sloupec matice, přesune kurzor v řádku a vrátí hodnotu buňky.
+
+
+##
+## Math and trigonometry functions Matematické a trigonometrické funkce
+##
+ABS = ABS ## Vrátí absolutní hodnotu čísla.
+ACOS = ARCCOS ## Vrátí arkuskosinus čísla.
+ACOSH = ARCCOSH ## Vrátí hyperbolický arkuskosinus čísla.
+ASIN = ARCSIN ## Vrátí arkussinus čísla.
+ASINH = ARCSINH ## Vrátí hyperbolický arkussinus čísla.
+ATAN = ARCTG ## Vrátí arkustangens čísla.
+ATAN2 = ARCTG2 ## Vrátí arkustangens x-ové a y-ové souřadnice.
+ATANH = ARCTGH ## Vrátí hyperbolický arkustangens čísla.
+CEILING = ZAOKR.NAHORU ## Zaokrouhlí číslo na nejbližší celé číslo nebo na nejbližší násobek zadané hodnoty.
+COMBIN = KOMBINACE ## Vrátí počet kombinací pro daný počet položek.
+COS = COS ## Vrátí kosinus čísla.
+COSH = COSH ## Vrátí hyperbolický kosinus čísla.
+DEGREES = DEGREES ## Převede radiány na stupně.
+EVEN = ZAOKROUHLIT.NA.SUDÉ ## Zaokrouhlí číslo nahoru na nejbližší celé sudé číslo.
+EXP = EXP ## Vrátí základ přirozeného logaritmu e umocněný na zadané číslo.
+FACT = FAKTORIÁL ## Vrátí faktoriál čísla.
+FACTDOUBLE = FACTDOUBLE ## Vrátí dvojitý faktoriál čísla.
+FLOOR = ZAOKR.DOLŮ ## Zaokrouhlí číslo dolů, směrem k nule.
+GCD = GCD ## Vrátí největší společný dělitel.
+INT = CELÁ.ČÁST ## Zaokrouhlí číslo dolů na nejbližší celé číslo.
+LCM = LCM ## Vrátí nejmenší společný násobek.
+LN = LN ## Vrátí přirozený logaritmus čísla.
+LOG = LOGZ ## Vrátí logaritmus čísla při zadaném základu.
+LOG10 = LOG ## Vrátí dekadický logaritmus čísla.
+MDETERM = DETERMINANT ## Vrátí determinant matice.
+MINVERSE = INVERZE ## Vrátí inverzní matici.
+MMULT = SOUČIN.MATIC ## Vrátí součin dvou matic.
+MOD = MOD ## Vrátí zbytek po dělení.
+MROUND = MROUND ## Vrátí číslo zaokrouhlené na požadovaný násobek.
+MULTINOMIAL = MULTINOMIAL ## Vrátí mnohočlen z množiny čísel.
+ODD = ZAOKROUHLIT.NA.LICHÉ ## Zaokrouhlí číslo nahoru na nejbližší celé liché číslo.
+PI = PI ## Vrátí hodnotu čísla pí.
+POWER = POWER ## Umocní číslo na zadanou mocninu.
+PRODUCT = SOUČIN ## Vynásobí argumenty funkce.
+QUOTIENT = QUOTIENT ## Vrátí celou část dělení.
+RADIANS = RADIANS ## Převede stupně na radiány.
+RAND = NÁHČÍSLO ## Vrátí náhodné číslo mezi 0 a 1.
+RANDBETWEEN = RANDBETWEEN ## Vrátí náhodné číslo mezi zadanými čísly.
+ROMAN = ROMAN ## Převede arabskou číslici na římskou ve formátu textu.
+ROUND = ZAOKROUHLIT ## Zaokrouhlí číslo na zadaný počet číslic.
+ROUNDDOWN = ROUNDDOWN ## Zaokrouhlí číslo dolů, směrem k nule.
+ROUNDUP = ROUNDUP ## Zaokrouhlí číslo nahoru, směrem od nuly.
+SERIESSUM = SERIESSUM ## Vrátí součet mocninné řady určené podle vzorce.
+SIGN = SIGN ## Vrátí znaménko čísla.
+SIN = SIN ## Vrátí sinus daného úhlu.
+SINH = SINH ## Vrátí hyperbolický sinus čísla.
+SQRT = ODMOCNINA ## Vrátí kladnou druhou odmocninu.
+SQRTPI = SQRTPI ## Vrátí druhou odmocninu výrazu (číslo * pí).
+SUBTOTAL = SUBTOTAL ## Vrátí souhrn v seznamu nebo databázi.
+SUM = SUMA ## Sečte argumenty funkce.
+SUMIF = SUMIF ## Sečte buňky vybrané podle zadaných kritérií.
+SUMIFS = SUMIFS ## Sečte buňky určené více zadanými podmínkami.
+SUMPRODUCT = SOUČIN.SKALÁRNÍ ## Vrátí součet součinů odpovídajících prvků matic.
+SUMSQ = SUMA.ČTVERCŮ ## Vrátí součet čtverců argumentů.
+SUMX2MY2 = SUMX2MY2 ## Vrátí součet rozdílu čtverců odpovídajících hodnot ve dvou maticích.
+SUMX2PY2 = SUMX2PY2 ## Vrátí součet součtu čtverců odpovídajících hodnot ve dvou maticích.
+SUMXMY2 = SUMXMY2 ## Vrátí součet čtverců rozdílů odpovídajících hodnot ve dvou maticích.
+TAN = TGTG ## Vrátí tangens čísla.
+TANH = TGH ## Vrátí hyperbolický tangens čísla.
+TRUNC = USEKNOUT ## Zkrátí číslo na celé číslo.
+
+
+##
+## Statistical functions Statistické funkce
+##
+AVEDEV = PRŮMODCHYLKA ## Vrátí průměrnou hodnotu absolutních odchylek datových bodů od jejich střední hodnoty.
+AVERAGE = PRŮMĚR ## Vrátí průměrnou hodnotu argumentů.
+AVERAGEA = AVERAGEA ## Vrátí průměrnou hodnotu argumentů včetně čísel, textu a logických hodnot.
+AVERAGEIF = AVERAGEIF ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk v oblasti, které vyhovují příslušné podmínce.
+AVERAGEIFS = AVERAGEIFS ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk vyhovujících několika podmínkám.
+BETADIST = BETADIST ## Vrátí hodnotu součtového rozdělení beta.
+BETAINV = BETAINV ## Vrátí inverzní hodnotu součtového rozdělení pro zadané rozdělení beta.
+BINOMDIST = BINOMDIST ## Vrátí hodnotu binomického rozdělení pravděpodobnosti jednotlivých veličin.
+CHIDIST = CHIDIST ## Vrátí jednostrannou pravděpodobnost rozdělení chí-kvadrát.
+CHIINV = CHIINV ## Vrátí hodnotu funkce inverzní k distribuční funkci jednostranné pravděpodobnosti rozdělení chí-kvadrát.
+CHITEST = CHITEST ## Vrátí test nezávislosti.
+CONFIDENCE = CONFIDENCE ## Vrátí interval spolehlivosti pro střední hodnotu základního souboru.
+CORREL = CORREL ## Vrátí korelační koeficient mezi dvěma množinami dat.
+COUNT = POČET ## Vrátí počet čísel v seznamu argumentů.
+COUNTA = POČET2 ## Vrátí počet hodnot v seznamu argumentů.
+COUNTBLANK = COUNTBLANK ## Spočítá počet prázdných buněk v oblasti.
+COUNTIF = COUNTIF ## Spočítá buňky v oblasti, které odpovídají zadaným kritériím.
+COUNTIFS = COUNTIFS ## Spočítá buňky v oblasti, které odpovídají více kritériím.
+COVAR = COVAR ## Vrátí hodnotu kovariance, průměrnou hodnotu součinů párových odchylek
+CRITBINOM = CRITBINOM ## Vrátí nejmenší hodnotu, pro kterou má součtové binomické rozdělení hodnotu větší nebo rovnu hodnotě kritéria.
+DEVSQ = DEVSQ ## Vrátí součet čtverců odchylek.
+EXPONDIST = EXPONDIST ## Vrátí hodnotu exponenciálního rozdělení.
+FDIST = FDIST ## Vrátí hodnotu rozdělení pravděpodobnosti F.
+FINV = FINV ## Vrátí hodnotu inverzní funkce k distribuční funkci rozdělení F.
+FISHER = FISHER ## Vrátí hodnotu Fisherovy transformace.
+FISHERINV = FISHERINV ## Vrátí hodnotu inverzní funkce k Fisherově transformaci.
+FORECAST = FORECAST ## Vrátí hodnotu lineárního trendu.
+FREQUENCY = ČETNOSTI ## Vrátí četnost rozdělení jako svislou matici.
+FTEST = FTEST ## Vrátí výsledek F-testu.
+GAMMADIST = GAMMADIST ## Vrátí hodnotu rozdělení gama.
+GAMMAINV = GAMMAINV ## Vrátí hodnotu inverzní funkce k distribuční funkci součtového rozdělení gama.
+GAMMALN = GAMMALN ## Vrátí přirozený logaritmus funkce gama, Γ(x).
+GEOMEAN = GEOMEAN ## Vrátí geometrický průměr.
+GROWTH = LOGLINTREND ## Vrátí hodnoty exponenciálního trendu.
+HARMEAN = HARMEAN ## Vrátí harmonický průměr.
+HYPGEOMDIST = HYPGEOMDIST ## Vrátí hodnotu hypergeometrického rozdělení.
+INTERCEPT = INTERCEPT ## Vrátí úsek lineární regresní čáry.
+KURT = KURT ## Vrátí hodnotu excesu množiny dat.
+LARGE = LARGE ## Vrátí k-tou největší hodnotu množiny dat.
+LINEST = LINREGRESE ## Vrátí parametry lineárního trendu.
+LOGEST = LOGLINREGRESE ## Vrátí parametry exponenciálního trendu.
+LOGINV = LOGINV ## Vrátí inverzní funkci k distribuční funkci logaritmicko-normálního rozdělení.
+LOGNORMDIST = LOGNORMDIST ## Vrátí hodnotu součtového logaritmicko-normálního rozdělení.
+MAX = MAX ## Vrátí maximální hodnotu seznamu argumentů.
+MAXA = MAXA ## Vrátí maximální hodnotu seznamu argumentů včetně čísel, textu a logických hodnot.
+MEDIAN = MEDIAN ## Vrátí střední hodnotu zadaných čísel.
+MIN = MIN ## Vrátí minimální hodnotu seznamu argumentů.
+MINA = MINA ## Vrátí nejmenší hodnotu v seznamu argumentů včetně čísel, textu a logických hodnot.
+MODE = MODE ## Vrátí hodnotu, která se v množině dat vyskytuje nejčastěji.
+NEGBINOMDIST = NEGBINOMDIST ## Vrátí hodnotu negativního binomického rozdělení.
+NORMDIST = NORMDIST ## Vrátí hodnotu normálního součtového rozdělení.
+NORMINV = NORMINV ## Vrátí inverzní funkci k funkci normálního součtového rozdělení.
+NORMSDIST = NORMSDIST ## Vrátí hodnotu standardního normálního součtového rozdělení.
+NORMSINV = NORMSINV ## Vrátí inverzní funkci k funkci standardního normálního součtového rozdělení.
+PEARSON = PEARSON ## Vrátí Pearsonův výsledný momentový korelační koeficient.
+PERCENTILE = PERCENTIL ## Vrátí hodnotu k-tého percentilu hodnot v oblasti.
+PERCENTRANK = PERCENTRANK ## Vrátí pořadí hodnoty v množině dat vyjádřené procentuální částí množiny dat.
+PERMUT = PERMUTACE ## Vrátí počet permutací pro zadaný počet objektů.
+POISSON = POISSON ## Vrátí hodnotu distribuční funkce Poissonova rozdělení.
+PROB = PROB ## Vrátí pravděpodobnost výskytu hodnot v oblasti mezi dvěma mezními hodnotami.
+QUARTILE = QUARTIL ## Vrátí hodnotu kvartilu množiny dat.
+RANK = RANK ## Vrátí pořadí čísla v seznamu čísel.
+RSQ = RKQ ## Vrátí druhou mocninu Pearsonova výsledného momentového korelačního koeficientu.
+SKEW = SKEW ## Vrátí zešikmení rozdělení.
+SLOPE = SLOPE ## Vrátí směrnici lineární regresní čáry.
+SMALL = SMALL ## Vrátí k-tou nejmenší hodnotu množiny dat.
+STANDARDIZE = STANDARDIZE ## Vrátí normalizovanou hodnotu.
+STDEV = SMODCH.VÝBĚR ## Vypočte směrodatnou odchylku výběru.
+STDEVA = STDEVA ## Vypočte směrodatnou odchylku výběru včetně čísel, textu a logických hodnot.
+STDEVP = SMODCH ## Vypočte směrodatnou odchylku základního souboru.
+STDEVPA = STDEVPA ## Vypočte směrodatnou odchylku základního souboru včetně čísel, textu a logických hodnot.
+STEYX = STEYX ## Vrátí standardní chybu předpovězené hodnoty y pro každou hodnotu x v regresi.
+TDIST = TDIST ## Vrátí hodnotu Studentova t-rozdělení.
+TINV = TINV ## Vrátí inverzní funkci k distribuční funkci Studentova t-rozdělení.
+TREND = LINTREND ## Vrátí hodnoty lineárního trendu.
+TRIMMEAN = TRIMMEAN ## Vrátí střední hodnotu vnitřní části množiny dat.
+TTEST = TTEST ## Vrátí pravděpodobnost spojenou se Studentovým t-testem.
+VAR = VAR.VÝBĚR ## Vypočte rozptyl výběru.
+VARA = VARA ## Vypočte rozptyl výběru včetně čísel, textu a logických hodnot.
+VARP = VAR ## Vypočte rozptyl základního souboru.
+VARPA = VARPA ## Vypočte rozptyl základního souboru včetně čísel, textu a logických hodnot.
+WEIBULL = WEIBULL ## Vrátí hodnotu Weibullova rozdělení.
+ZTEST = ZTEST ## Vrátí jednostrannou P-hodnotu z-testu.
+
+
+##
+## Text functions Textové funkce
+##
+ASC = ASC ## Změní znaky s plnou šířkou (dvoubajtové)v řetězci znaků na znaky s poloviční šířkou (jednobajtové).
+BAHTTEXT = BAHTTEXT ## Převede číslo na text ve formátu, měny ß (baht).
+CHAR = ZNAK ## Vrátí znak určený číslem kódu.
+CLEAN = VYČISTIT ## Odebere z textu všechny netisknutelné znaky.
+CODE = KÓD ## Vrátí číselný kód prvního znaku zadaného textového řetězce.
+CONCATENATE = CONCATENATE ## Spojí několik textových položek do jedné.
+DOLLAR = KČ ## Převede číslo na text ve formátu měny Kč (česká koruna).
+EXACT = STEJNÉ ## Zkontroluje, zda jsou dvě textové hodnoty shodné.
+FIND = NAJÍT ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena).
+FINDB = FINDB ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena).
+FIXED = ZAOKROUHLIT.NA.TEXT ## Zformátuje číslo jako text s pevným počtem desetinných míst.
+JIS = JIS ## Změní znaky s poloviční šířkou (jednobajtové) v řetězci znaků na znaky s plnou šířkou (dvoubajtové).
+LEFT = ZLEVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo.
+LEFTB = LEFTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo.
+LEN = DÉLKA ## Vrátí počet znaků textového řetězce.
+LENB = LENB ## Vrátí počet znaků textového řetězce.
+LOWER = MALÁ ## Převede text na malá písmena.
+MID = ČÁST ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem.
+MIDB = MIDB ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem.
+PHONETIC = ZVUKOVÉ ## Extrahuje fonetické znaky (furigana) z textového řetězce.
+PROPER = VELKÁ2 ## Převede první písmeno každého slova textové hodnoty na velké.
+REPLACE = NAHRADIT ## Nahradí znaky uvnitř textu.
+REPLACEB = NAHRADITB ## Nahradí znaky uvnitř textu.
+REPT = OPAKOVAT ## Zopakuje text podle zadaného počtu opakování.
+RIGHT = ZPRAVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo.
+RIGHTB = RIGHTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo.
+SEARCH = HLEDAT ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována).
+SEARCHB = SEARCHB ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována).
+SUBSTITUTE = DOSADIT ## V textovém řetězci nahradí starý text novým.
+T = T ## Převede argumenty na text.
+TEXT = HODNOTA.NA.TEXT ## Zformátuje číslo a převede ho na text.
+TRIM = PROČISTIT ## Odstraní z textu mezery.
+UPPER = VELKÁ ## Převede text na velká písmena.
+VALUE = HODNOTA ## Převede textový argument na číslo.
diff --git a/PHPExcel/locale/da/config b/PHPExcel/locale/da/config
new file mode 100644
index 0000000..1ddecb9
--- /dev/null
+++ b/PHPExcel/locale/da/config
@@ -0,0 +1,48 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = kr
+
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NUL!
+DIV0 = #DIVISION/0!
+VALUE = #VÆRDI!
+REF = #REFERENCE!
+NAME = #NAVN?
+NUM = #NUM!
+NA = #I/T
diff --git a/PHPExcel/locale/da/functions b/PHPExcel/locale/da/functions
new file mode 100644
index 0000000..102d578
--- /dev/null
+++ b/PHPExcel/locale/da/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Tilføjelsesprogram- og automatiseringsfunktioner
+##
+GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data, der er lagret i en pivottabelrapport
+
+
+##
+## Cube functions Kubefunktioner
+##
+CUBEKPIMEMBER = KUBE.KPI.MEDLEM ## Returnerer navn, egenskab og mål for en KPI-indikator og viser navnet og egenskaben i cellen. En KPI-indikator er en målbar størrelse, f.eks. bruttooverskud pr. måned eller personaleudskiftning pr. kvartal, der bruges til at overvåge en organisations præstationer.
+CUBEMEMBER = KUBE.MEDLEM ## Returnerer et medlem eller en tupel fra kubehierarkiet. Bruges til at validere, om et medlem eller en tupel findes i kuben.
+CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB ## Returnerer værdien af en egenskab for et medlem i kuben. Bruges til at validere, om et medlemsnavn findes i kuben, og returnere den angivne egenskab for medlemmet.
+CUBERANKEDMEMBER = KUBEMEDLEM.RANG ## Returnerer det n'te eller rangordnede medlem i et sæt. Bruges til at returnere et eller flere elementer i et sæt, f.eks. topsælgere eller de 10 bedste elever.
+CUBESET = KUBESÆT ## Definerer et beregnet sæt medlemmer eller tupler ved at sende et sætudtryk til kuben på serveren, som opretter sættet og returnerer det til Microsoft Office Excel.
+CUBESETCOUNT = KUBESÆT.TÆL ## Returnerer antallet af elementer i et sæt.
+CUBEVALUE = KUBEVÆRDI ## Returnerer en sammenlagt (aggregeret) værdi fra en kube.
+
+
+##
+## Database functions Databasefunktioner
+##
+DAVERAGE = DMIDDEL ## Returnerer gennemsnittet af markerede databaseposter
+DCOUNT = DTÆL ## Tæller de celler, der indeholder tal, i en database
+DCOUNTA = DTÆLV ## Tæller udfyldte celler i en database
+DGET = DHENT ## Uddrager en enkelt post, der opfylder de angivne kriterier, fra en database
+DMAX = DMAKS ## Returnerer den største værdi blandt markerede databaseposter
+DMIN = DMIN ## Returnerer den mindste værdi blandt markerede databaseposter
+DPRODUCT = DPRODUKT ## Ganger værdierne i et bestemt felt med poster, der opfylder kriterierne i en database
+DSTDEV = DSTDAFV ## Beregner et skøn over standardafvigelsen baseret på en stikprøve af markerede databaseposter
+DSTDEVP = DSTDAFVP ## Beregner standardafvigelsen baseret på hele populationen af markerede databaseposter
+DSUM = DSUM ## Sammenlægger de tal i feltkolonnen i databasen, der opfylder kriterierne
+DVAR = DVARIANS ## Beregner varians baseret på en stikprøve af markerede databaseposter
+DVARP = DVARIANSP ## Beregner varians baseret på hele populationen af markerede databaseposter
+
+
+##
+## Date and time functions Dato- og klokkeslætsfunktioner
+##
+DATE = DATO ## Returnerer serienummeret for en bestemt dato
+DATEVALUE = DATOVÆRDI ## Konverterer en dato i form af tekst til et serienummer
+DAY = DAG ## Konverterer et serienummer til en dag i måneden
+DAYS360 = DAGE360 ## Beregner antallet af dage mellem to datoer på grundlag af et år med 360 dage
+EDATE = EDATO ## Returnerer serienummeret for den dato, der ligger det angivne antal måneder før eller efter startdatoen
+EOMONTH = SLUT.PÅ.MÅNED ## Returnerer serienummeret på den sidste dag i måneden før eller efter et angivet antal måneder
+HOUR = TIME ## Konverterer et serienummer til en time
+MINUTE = MINUT ## Konverterer et serienummer til et minut
+MONTH = MÅNED ## Konverterer et serienummer til en måned
+NETWORKDAYS = ANTAL.ARBEJDSDAGE ## Returnerer antallet af hele arbejdsdage mellem to datoer
+NOW = NU ## Returnerer serienummeret for den aktuelle dato eller det aktuelle klokkeslæt
+SECOND = SEKUND ## Konverterer et serienummer til et sekund
+TIME = KLOKKESLÆT ## Returnerer serienummeret for et bestemt klokkeslæt
+TIMEVALUE = TIDSVÆRDI ## Konverterer et klokkeslæt i form af tekst til et serienummer
+TODAY = IDAG ## Returnerer serienummeret for dags dato
+WEEKDAY = UGEDAG ## Konverterer et serienummer til en ugedag
+WEEKNUM = UGE.NR ## Konverterer et serienummer til et tal, der angiver ugenummeret i året
+WORKDAY = ARBEJDSDAG ## Returnerer serienummeret for dagen før eller efter det angivne antal arbejdsdage
+YEAR = ÅR ## Konverterer et serienummer til et år
+YEARFRAC = ÅR.BRØK ## Returnerer årsbrøken, der repræsenterer antallet af hele dage mellem startdato og slutdato
+
+
+##
+## Engineering functions Tekniske funktioner
+##
+BESSELI = BESSELI ## Returnerer den modificerede Bessel-funktion In(x)
+BESSELJ = BESSELJ ## Returnerer Bessel-funktionen Jn(x)
+BESSELK = BESSELK ## Returnerer den modificerede Bessel-funktion Kn(x)
+BESSELY = BESSELY ## Returnerer Bessel-funktionen Yn(x)
+BIN2DEC = BIN.TIL.DEC ## Konverterer et binært tal til et decimaltal
+BIN2HEX = BIN.TIL.HEX ## Konverterer et binært tal til et heksadecimalt tal
+BIN2OCT = BIN.TIL.OKT ## Konverterer et binært tal til et oktaltal.
+COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koefficienter til et komplekst tal
+CONVERT = KONVERTER ## Konverterer et tal fra én måleenhed til en anden
+DEC2BIN = DEC.TIL.BIN ## Konverterer et decimaltal til et binært tal
+DEC2HEX = DEC.TIL.HEX ## Konverterer et decimaltal til et heksadecimalt tal
+DEC2OCT = DEC.TIL.OKT ## Konverterer et decimaltal til et oktaltal
+DELTA = DELTA ## Tester, om to værdier er ens
+ERF = FEJLFUNK ## Returner fejlfunktionen
+ERFC = FEJLFUNK.KOMP ## Returnerer den komplementære fejlfunktion
+GESTEP = GETRIN ## Tester, om et tal er større end en grænseværdi
+HEX2BIN = HEX.TIL.BIN ## Konverterer et heksadecimalt tal til et binært tal
+HEX2DEC = HEX.TIL.DEC ## Konverterer et decimaltal til et heksadecimalt tal
+HEX2OCT = HEX.TIL.OKT ## Konverterer et heksadecimalt tal til et oktaltal
+IMABS = IMAGABS ## Returnerer den absolutte værdi (modulus) for et komplekst tal
+IMAGINARY = IMAGINÆR ## Returnerer den imaginære koefficient for et komplekst tal
+IMARGUMENT = IMAGARGUMENT ## Returnerer argumentet theta, en vinkel udtrykt i radianer
+IMCONJUGATE = IMAGKONJUGERE ## Returnerer den komplekse konjugation af et komplekst tal
+IMCOS = IMAGCOS ## Returnerer et komplekst tals cosinus
+IMDIV = IMAGDIV ## Returnerer kvotienten for to komplekse tal
+IMEXP = IMAGEKSP ## Returnerer et komplekst tals eksponentialfunktion
+IMLN = IMAGLN ## Returnerer et komplekst tals naturlige logaritme
+IMLOG10 = IMAGLOG10 ## Returnerer et komplekst tals sædvanlige logaritme (titalslogaritme)
+IMLOG2 = IMAGLOG2 ## Returnerer et komplekst tals sædvanlige logaritme (totalslogaritme)
+IMPOWER = IMAGPOTENS ## Returnerer et komplekst tal opløftet i en heltalspotens
+IMPRODUCT = IMAGPRODUKT ## Returnerer produktet af komplekse tal
+IMREAL = IMAGREELT ## Returnerer den reelle koefficient for et komplekst tal
+IMSIN = IMAGSIN ## Returnerer et komplekst tals sinus
+IMSQRT = IMAGKVROD ## Returnerer et komplekst tals kvadratrod
+IMSUB = IMAGSUB ## Returnerer forskellen mellem to komplekse tal
+IMSUM = IMAGSUM ## Returnerer summen af komplekse tal
+OCT2BIN = OKT.TIL.BIN ## Konverterer et oktaltal til et binært tal
+OCT2DEC = OKT.TIL.DEC ## Konverterer et oktaltal til et decimaltal
+OCT2HEX = OKT.TIL.HEX ## Konverterer et oktaltal til et heksadecimalt tal
+
+
+##
+## Financial functions Finansielle funktioner
+##
+ACCRINT = PÅLØBRENTE ## Returnerer den påløbne rente for et værdipapir med periodiske renteudbetalinger
+ACCRINTM = PÅLØBRENTE.UDLØB ## Returnerer den påløbne rente for et værdipapir, hvor renteudbetalingen finder sted ved papirets udløb
+AMORDEGRC = AMORDEGRC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode ved hjælp af en afskrivningskoefficient
+AMORLINC = AMORLINC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode
+COUPDAYBS = KUPONDAGE.SA ## Returnerer antallet af dage fra starten af kuponperioden til afregningsdatoen
+COUPDAYS = KUPONDAGE.A ## Returnerer antallet af dage fra begyndelsen af kuponperioden til afregningsdatoen
+COUPDAYSNC = KUPONDAGE.ANK ## Returnerer antallet af dage i den kuponperiode, der indeholder afregningsdatoen
+COUPNCD = KUPONDAG.NÆSTE ## Returnerer den næste kupondato efter afregningsdatoen
+COUPNUM = KUPONBETALINGER ## Returnerer antallet af kuponudbetalinger mellem afregnings- og udløbsdatoen
+COUPPCD = KUPONDAG.FORRIGE ## Returnerer den forrige kupondato før afregningsdatoen
+CUMIPMT = AKKUM.RENTE ## Returnerer den akkumulerede rente, der betales på et lån mellem to perioder
+CUMPRINC = AKKUM.HOVEDSTOL ## Returnerer den akkumulerede nedbringelse af hovedstol mellem to perioder
+DB = DB ## Returnerer afskrivningen på et aktiv i en angivet periode ved anvendelse af saldometoden
+DDB = DSA ## Returnerer afskrivningsbeløbet for et aktiv over en bestemt periode ved anvendelse af dobbeltsaldometoden eller en anden afskrivningsmetode, som du angiver
+DISC = DISKONTO ## Returnerer et værdipapirs diskonto
+DOLLARDE = KR.DECIMAL ## Konverterer en kronepris udtrykt som brøk til en kronepris udtrykt som decimaltal
+DOLLARFR = KR.BRØK ## Konverterer en kronepris udtrykt som decimaltal til en kronepris udtrykt som brøk
+DURATION = VARIGHED ## Returnerer den årlige løbetid for et værdipapir med periodiske renteudbetalinger
+EFFECT = EFFEKTIV.RENTE ## Returnerer den årlige effektive rente
+FV = FV ## Returnerer fremtidsværdien af en investering
+FVSCHEDULE = FVTABEL ## Returnerer den fremtidige værdi af en hovedstol, når der er tilskrevet rente og rentes rente efter forskellige rentesatser
+INTRATE = RENTEFOD ## Returnerer renten på et fuldt ud investeret værdipapir
+IPMT = R.YDELSE ## Returnerer renten fra en investering for en given periode
+IRR = IA ## Returnerer den interne rente for en række pengestrømme
+ISPMT = ISPMT ## Beregner den betalte rente i løbet af en bestemt investeringsperiode
+MDURATION = MVARIGHED ## Returnerer Macauleys modificerede løbetid for et værdipapir med en formodet pari på kr. 100
+MIRR = MIA ## Returnerer den interne forrentning, hvor positive og negative pengestrømme finansieres til forskellig rente
+NOMINAL = NOMINEL ## Returnerer den årlige nominelle rente
+NPER = NPER ## Returnerer antallet af perioder for en investering
+NPV = NUTIDSVÆRDI ## Returnerer nettonutidsværdien for en investering baseret på en række periodiske pengestrømme og en diskonteringssats
+ODDFPRICE = ULIGE.KURS.PÅLYDENDE ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med en ulige (kort eller lang) første periode
+ODDFYIELD = ULIGE.FØRSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige første periode
+ODDLPRICE = ULIGE.SIDSTE.KURS ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med ulige sidste periode
+ODDLYIELD = ULIGE.SIDSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige sidste periode
+PMT = YDELSE ## Returnerer renten fra en investering for en given periode
+PPMT = H.YDELSE ## Returnerer ydelsen på hovedstolen for en investering i en given periode
+PRICE = KURS ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir med periodiske renteudbetalinger
+PRICEDISC = KURS.DISKONTO ## Returnerer kursen pr. kr 100 nominel værdi for et diskonteret værdipapir
+PRICEMAT = KURS.UDLØB ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir, hvor renten udbetales ved papirets udløb
+PV = NV ## Returnerer den nuværende værdi af en investering
+RATE = RENTE ## Returnerer renten i hver periode for en annuitet
+RECEIVED = MODTAGET.VED.UDLØB ## Returnerer det beløb, der modtages ved udløbet af et fuldt ud investeret værdipapir
+SLN = LA ## Returnerer den lineære afskrivning for et aktiv i en enkelt periode
+SYD = ÅRSAFSKRIVNING ## Returnerer den årlige afskrivning på et aktiv i en bestemt periode
+TBILLEQ = STATSOBLIGATION ## Returnerer det obligationsækvivalente afkast for en statsobligation
+TBILLPRICE = STATSOBLIGATION.KURS ## Returnerer kursen pr. kr 100 nominel værdi for en statsobligation
+TBILLYIELD = STATSOBLIGATION.AFKAST ## Returnerer en afkastet på en statsobligation
+VDB = VSA ## Returnerer afskrivningen på et aktiv i en angivet periode, herunder delperioder, ved brug af dobbeltsaldometoden
+XIRR = INTERN.RENTE ## Returnerer den interne rente for en plan over pengestrømme, der ikke behøver at være periodiske
+XNPV = NETTO.NUTIDSVÆRDI ## Returnerer nutidsværdien for en plan over pengestrømme, der ikke behøver at være periodiske
+YIELD = AFKAST ## Returnerer afkastet for et værdipapir med periodiske renteudbetalinger
+YIELDDISC = AFKAST.DISKONTO ## Returnerer det årlige afkast for et diskonteret værdipapir, f.eks. en statsobligation
+YIELDMAT = AFKAST.UDLØBSDATO ## Returnerer det årlige afkast for et værdipapir, hvor renten udbetales ved papirets udløb
+
+
+##
+## Information functions Informationsfunktioner
+##
+CELL = CELLE ## Returnerer oplysninger om formatering, placering eller indhold af en celle
+ERROR.TYPE = FEJLTYPE ## Returnerer et tal, der svarer til en fejltype
+INFO = INFO ## Returnerer oplysninger om det aktuelle operativmiljø
+ISBLANK = ER.TOM ## Returnerer SAND, hvis værdien er tom
+ISERR = ER.FJL ## Returnerer SAND, hvis værdien er en fejlværdi undtagen #I/T
+ISERROR = ER.FEJL ## Returnerer SAND, hvis værdien er en fejlværdi
+ISEVEN = ER.LIGE ## Returnerer SAND, hvis tallet er lige
+ISLOGICAL = ER.LOGISK ## Returnerer SAND, hvis værdien er en logisk værdi
+ISNA = ER.IKKE.TILGÆNGELIG ## Returnerer SAND, hvis værdien er fejlværdien #I/T
+ISNONTEXT = ER.IKKE.TEKST ## Returnerer SAND, hvis værdien ikke er tekst
+ISNUMBER = ER.TAL ## Returnerer SAND, hvis værdien er et tal
+ISODD = ER.ULIGE ## Returnerer SAND, hvis tallet er ulige
+ISREF = ER.REFERENCE ## Returnerer SAND, hvis værdien er en reference
+ISTEXT = ER.TEKST ## Returnerer SAND, hvis værdien er tekst
+N = TAL ## Returnerer en værdi konverteret til et tal
+NA = IKKE.TILGÆNGELIG ## Returnerer fejlværdien #I/T
+TYPE = VÆRDITYPE ## Returnerer et tal, der angiver datatypen for en værdi
+
+
+##
+## Logical functions Logiske funktioner
+##
+AND = OG ## Returnerer SAND, hvis alle argumenterne er sande
+FALSE = FALSK ## Returnerer den logiske værdi FALSK
+IF = HVIS ## Angiver en logisk test, der skal udføres
+IFERROR = HVIS.FEJL ## Returnerer en værdi, du angiver, hvis en formel evauleres som en fejl. Returnerer i modsat fald resultatet af formlen
+NOT = IKKE ## Vender argumentets logik om
+OR = ELLER ## Returneret værdien SAND, hvis mindst ét argument er sandt
+TRUE = SAND ## Returnerer den logiske værdi SAND
+
+
+##
+## Lookup and reference functions Opslags- og referencefunktioner
+##
+ADDRESS = ADRESSE ## Returnerer en reference som tekst til en enkelt celle i et regneark
+AREAS = OMRÅDER ## Returnerer antallet af områder i en reference
+CHOOSE = VÆLG ## Vælger en værdi på en liste med værdier
+COLUMN = KOLONNE ## Returnerer kolonnenummeret i en reference
+COLUMNS = KOLONNER ## Returnerer antallet af kolonner i en reference
+HLOOKUP = VOPSLAG ## Søger i den øverste række af en matrix og returnerer værdien af den angivne celle
+HYPERLINK = HYPERLINK ## Opretter en genvej kaldet et hyperlink, der åbner et dokument, som er lagret på en netværksserver, på et intranet eller på internettet
+INDEX = INDEKS ## Anvender et indeks til at vælge en værdi fra en reference eller en matrix
+INDIRECT = INDIREKTE ## Returnerer en reference, der er angivet af en tekstværdi
+LOOKUP = SLÅ.OP ## Søger værdier i en vektor eller en matrix
+MATCH = SAMMENLIGN ## Søger værdier i en reference eller en matrix
+OFFSET = FORSKYDNING ## Returnerer en reference forskudt i forhold til en given reference
+ROW = RÆKKE ## Returnerer rækkenummeret for en reference
+ROWS = RÆKKER ## Returnerer antallet af rækker i en reference
+RTD = RTD ## Henter realtidsdata fra et program, der understøtter COM-automatisering (Automation: En metode til at arbejde med objekter fra et andet program eller udviklingsværktøj. Automation, som tidligere blev kaldt OLE Automation, er en industristandard og en funktion i COM (Component Object Model).)
+TRANSPOSE = TRANSPONER ## Returnerer en transponeret matrix
+VLOOKUP = LOPSLAG ## Søger i øverste række af en matrix og flytter på tværs af rækken for at returnere en celleværdi
+
+
+##
+## Math and trigonometry functions Matematiske og trigonometriske funktioner
+##
+ABS = ABS ## Returnerer den absolutte værdi af et tal
+ACOS = ARCCOS ## Returnerer et tals arcus cosinus
+ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus af tal
+ASIN = ARCSIN ## Returnerer et tals arcus sinus
+ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus for tal
+ATAN = ARCTAN ## Returnerer et tals arcus tangens
+ATAN2 = ARCTAN2 ## Returnerer de angivne x- og y-koordinaters arcus tangens
+ATANH = ARCTANH ## Returnerer et tals inverse hyperbolske tangens
+CEILING = AFRUND.LOFT ## Afrunder et tal til nærmeste heltal eller til nærmeste multiplum af betydning
+COMBIN = KOMBIN ## Returnerer antallet af kombinationer for et givet antal objekter
+COS = COS ## Returnerer et tals cosinus
+COSH = COSH ## Returnerer den inverse hyperbolske cosinus af et tal
+DEGREES = GRADER ## Konverterer radianer til grader
+EVEN = LIGE ## Runder et tal op til nærmeste lige heltal
+EXP = EKSP ## Returnerer e opløftet til en potens af et angivet tal
+FACT = FAKULTET ## Returnerer et tals fakultet
+FACTDOUBLE = DOBBELT.FAKULTET ## Returnerer et tals dobbelte fakultet
+FLOOR = AFRUND.GULV ## Runder et tal ned mod nul
+GCD = STØRSTE.FÆLLES.DIVISOR ## Returnerer den største fælles divisor
+INT = HELTAL ## Nedrunder et tal til det nærmeste heltal
+LCM = MINDSTE.FÆLLES.MULTIPLUM ## Returnerer det mindste fælles multiplum
+LN = LN ## Returnerer et tals naturlige logaritme
+LOG = LOG ## Returnerer logaritmen for et tal på grundlag af et angivet grundtal
+LOG10 = LOG10 ## Returnerer titalslogaritmen af et tal
+MDETERM = MDETERM ## Returnerer determinanten for en matrix
+MINVERSE = MINVERT ## Returnerer den inverse matrix for en matrix
+MMULT = MPRODUKT ## Returnerer matrixproduktet af to matrixer
+MOD = REST ## Returnerer restværdien fra division
+MROUND = MAFRUND ## Returnerer et tal afrundet til det ønskede multiplum
+MULTINOMIAL = MULTINOMIAL ## Returnerer et multinomialt talsæt
+ODD = ULIGE ## Runder et tal op til nærmeste ulige heltal
+PI = PI ## Returnerer værdien af pi
+POWER = POTENS ## Returnerer resultatet af et tal opløftet til en potens
+PRODUCT = PRODUKT ## Multiplicerer argumenterne
+QUOTIENT = KVOTIENT ## Returnerer heltalsdelen ved division
+RADIANS = RADIANER ## Konverterer grader til radianer
+RAND = SLUMP ## Returnerer et tilfældigt tal mellem 0 og 1
+RANDBETWEEN = SLUMP.MELLEM ## Returnerer et tilfældigt tal mellem de tal, der angives
+ROMAN = ROMERTAL ## Konverterer et arabertal til romertal som tekst
+ROUND = AFRUND ## Afrunder et tal til et angivet antal decimaler
+ROUNDDOWN = RUND.NED ## Runder et tal ned mod nul
+ROUNDUP = RUND.OP ## Runder et tal op, væk fra 0 (nul)
+SERIESSUM = SERIESUM ## Returnerer summen af en potensserie baseret på en formel
+SIGN = FORTEGN ## Returnerer et tals fortegn
+SIN = SIN ## Returnerer en given vinkels sinusværdi
+SINH = SINH ## Returnerer den hyperbolske sinus af et tal
+SQRT = KVROD ## Returnerer en positiv kvadratrod
+SQRTPI = KVRODPI ## Returnerer kvadratroden af (tal * pi;)
+SUBTOTAL = SUBTOTAL ## Returnerer en subtotal på en liste eller i en database
+SUM = SUM ## Lægger argumenterne sammen
+SUMIF = SUM.HVIS ## Lægger de celler sammen, der er specificeret af et givet kriterium.
+SUMIFS = SUM.HVISER ## Lægger de celler i et område sammen, der opfylder flere kriterier.
+SUMPRODUCT = SUMPRODUKT ## Returnerer summen af produkter af ens matrixkomponenter
+SUMSQ = SUMKV ## Returnerer summen af argumenternes kvadrater
+SUMX2MY2 = SUMX2MY2 ## Returnerer summen af differensen mellem kvadrater af ens værdier i to matrixer
+SUMX2PY2 = SUMX2PY2 ## Returnerer summen af summen af kvadrater af tilsvarende værdier i to matrixer
+SUMXMY2 = SUMXMY2 ## Returnerer summen af kvadrater af differenser mellem ens værdier i to matrixer
+TAN = TAN ## Returnerer et tals tangens
+TANH = TANH ## Returnerer et tals hyperbolske tangens
+TRUNC = AFKORT ## Afkorter et tal til et heltal
+
+
+##
+## Statistical functions Statistiske funktioner
+##
+AVEDEV = MAD ## Returnerer den gennemsnitlige numeriske afvigelse fra stikprøvens middelværdi
+AVERAGE = MIDDEL ## Returnerer middelværdien af argumenterne
+AVERAGEA = MIDDELV ## Returnerer middelværdien af argumenterne og medtager tal, tekst og logiske værdier
+AVERAGEIF = MIDDEL.HVIS ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder et givet kriterium, i et område
+AVERAGEIFS = MIDDEL.HVISER ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder flere kriterier.
+BETADIST = BETAFORDELING ## Returnerer den kumulative betafordelingsfunktion
+BETAINV = BETAINV ## Returnerer den inverse kumulative fordelingsfunktion for en angivet betafordeling
+BINOMDIST = BINOMIALFORDELING ## Returnerer punktsandsynligheden for binomialfordelingen
+CHIDIST = CHIFORDELING ## Returnerer fraktilsandsynligheden for en chi2-fordeling
+CHIINV = CHIINV ## Returnerer den inverse fraktilsandsynlighed for en chi2-fordeling
+CHITEST = CHITEST ## Foretager en test for uafhængighed
+CONFIDENCE = KONFIDENSINTERVAL ## Returnerer et konfidensinterval for en population
+CORREL = KORRELATION ## Returnerer korrelationskoefficienten mellem to datasæt
+COUNT = TÆL ## Tæller antallet af tal på en liste med argumenter
+COUNTA = TÆLV ## Tæller antallet af værdier på en liste med argumenter
+COUNTBLANK = ANTAL.BLANKE ## Tæller antallet af tomme celler i et område
+COUNTIF = TÆLHVIS ## Tæller antallet af celler, som opfylder de givne kriterier, i et område
+COUNTIFS = TÆL.HVISER ## Tæller antallet af de celler, som opfylder flere kriterier, i et område
+COVAR = KOVARIANS ## Beregner kovariansen mellem to stokastiske variabler
+CRITBINOM = KRITBINOM ## Returnerer den mindste værdi for x, for hvilken det gælder, at fordelingsfunktionen er mindre end eller lig med kriterieværdien.
+DEVSQ = SAK ## Returnerer summen af de kvadrerede afvigelser fra middelværdien
+EXPONDIST = EKSPFORDELING ## Returnerer eksponentialfordelingen
+FDIST = FFORDELING ## Returnerer fraktilsandsynligheden for F-fordelingen
+FINV = FINV ## Returnerer den inverse fraktilsandsynlighed for F-fordelingen
+FISHER = FISHER ## Returnerer Fisher-transformationen
+FISHERINV = FISHERINV ## Returnerer den inverse Fisher-transformation
+FORECAST = PROGNOSE ## Returnerer en prognoseværdi baseret på lineær tendens
+FREQUENCY = FREKVENS ## Returnerer en frekvensfordeling i en søjlevektor
+FTEST = FTEST ## Returnerer resultatet af en F-test til sammenligning af varians
+GAMMADIST = GAMMAFORDELING ## Returnerer fordelingsfunktionen for gammafordelingen
+GAMMAINV = GAMMAINV ## Returnerer den inverse fordelingsfunktion for gammafordelingen
+GAMMALN = GAMMALN ## Returnerer den naturlige logaritme til gammafordelingen, G(x)
+GEOMEAN = GEOMIDDELVÆRDI ## Returnerer det geometriske gennemsnit
+GROWTH = FORØGELSE ## Returnerer værdier langs en eksponentiel tendens
+HARMEAN = HARMIDDELVÆRDI ## Returnerer det harmoniske gennemsnit
+HYPGEOMDIST = HYPGEOFORDELING ## Returnerer punktsandsynligheden i en hypergeometrisk fordeling
+INTERCEPT = SKÆRING ## Returnerer afskæringsværdien på y-aksen i en lineær regression
+KURT = TOPSTEJL ## Returnerer kurtosisværdien for en stokastisk variabel
+LARGE = STOR ## Returnerer den k'te største værdi i et datasæt
+LINEST = LINREGR ## Returnerer parameterestimaterne for en lineær tendens
+LOGEST = LOGREGR ## Returnerer parameterestimaterne for en eksponentiel tendens
+LOGINV = LOGINV ## Returnerer den inverse fordelingsfunktion for lognormalfordelingen
+LOGNORMDIST = LOGNORMFORDELING ## Returnerer fordelingsfunktionen for lognormalfordelingen
+MAX = MAKS ## Returnerer den maksimale værdi på en liste med argumenter.
+MAXA = MAKSV ## Returnerer den maksimale værdi på en liste med argumenter og medtager tal, tekst og logiske værdier
+MEDIAN = MEDIAN ## Returnerer medianen for de angivne tal
+MIN = MIN ## Returnerer den mindste værdi på en liste med argumenter.
+MINA = MINV ## Returnerer den mindste værdi på en liste med argumenter og medtager tal, tekst og logiske værdier
+MODE = HYPPIGST ## Returnerer den hyppigste værdi i et datasæt
+NEGBINOMDIST = NEGBINOMFORDELING ## Returnerer den negative binomialfordeling
+NORMDIST = NORMFORDELING ## Returnerer fordelingsfunktionen for normalfordelingen
+NORMINV = NORMINV ## Returnerer den inverse fordelingsfunktion for normalfordelingen
+NORMSDIST = STANDARDNORMFORDELING ## Returnerer fordelingsfunktionen for standardnormalfordelingen
+NORMSINV = STANDARDNORMINV ## Returnerer den inverse fordelingsfunktion for standardnormalfordelingen
+PEARSON = PEARSON ## Returnerer Pearsons korrelationskoefficient
+PERCENTILE = FRAKTIL ## Returnerer den k'te fraktil for datasættet
+PERCENTRANK = PROCENTPLADS ## Returnerer den procentuelle rang for en given værdi i et datasæt
+PERMUT = PERMUT ## Returnerer antallet af permutationer for et givet sæt objekter
+POISSON = POISSON ## Returnerer fordelingsfunktionen for en Poisson-fordeling
+PROB = SANDSYNLIGHED ## Returnerer intervalsandsynligheden
+QUARTILE = KVARTIL ## Returnerer kvartilen i et givet datasæt
+RANK = PLADS ## Returnerer rangen for et tal på en liste med tal
+RSQ = FORKLARINGSGRAD ## Returnerer R2-værdien fra en simpel lineær regression
+SKEW = SKÆVHED ## Returnerer skævheden for en stokastisk variabel
+SLOPE = HÆLDNING ## Returnerer estimatet på hældningen fra en simpel lineær regression
+SMALL = MINDSTE ## Returnerer den k'te mindste værdi i datasættet
+STANDARDIZE = STANDARDISER ## Returnerer en standardiseret værdi
+STDEV = STDAFV ## Estimerer standardafvigelsen på basis af en stikprøve
+STDEVA = STDAFVV ## Beregner standardafvigelsen på basis af en prøve og medtager tal, tekst og logiske værdier
+STDEVP = STDAFVP ## Beregner standardafvigelsen på basis af en hel population
+STDEVPA = STDAFVPV ## Beregner standardafvigelsen på basis af en hel population og medtager tal, tekst og logiske værdier
+STEYX = STFYX ## Returnerer standardafvigelsen for de estimerede y-værdier i den simple lineære regression
+TDIST = TFORDELING ## Returnerer fordelingsfunktionen for Student's t-fordeling
+TINV = TINV ## Returnerer den inverse fordelingsfunktion for Student's t-fordeling
+TREND = TENDENS ## Returnerer værdi under antagelse af en lineær tendens
+TRIMMEAN = TRIMMIDDELVÆRDI ## Returnerer den trimmede middelværdi for datasættet
+TTEST = TTEST ## Returnerer den sandsynlighed, der er forbundet med Student's t-test
+VAR = VARIANS ## Beregner variansen på basis af en prøve
+VARA = VARIANSV ## Beregner variansen på basis af en prøve og medtager tal, tekst og logiske værdier
+VARP = VARIANSP ## Beregner variansen på basis af hele populationen
+VARPA = VARIANSPV ## Beregner variansen på basis af hele populationen og medtager tal, tekst og logiske værdier
+WEIBULL = WEIBULL ## Returnerer fordelingsfunktionen for Weibull-fordelingen
+ZTEST = ZTEST ## Returnerer sandsynlighedsværdien ved en en-sidet z-test
+
+
+##
+## Text functions Tekstfunktioner
+##
+ASC = ASC ## Ændrer engelske tegn i fuld bredde (dobbelt-byte) eller katakana i en tegnstreng til tegn i halv bredde (enkelt-byte)
+BAHTTEXT = BAHTTEKST ## Konverterer et tal til tekst ved hjælp af valutaformatet ß (baht)
+CHAR = TEGN ## Returnerer det tegn, der svarer til kodenummeret
+CLEAN = RENS ## Fjerner alle tegn, der ikke kan udskrives, fra tekst
+CODE = KODE ## Returnerer en numerisk kode for det første tegn i en tekststreng
+CONCATENATE = SAMMENKÆDNING ## Sammenkæder adskillige tekstelementer til ét tekstelement
+DOLLAR = KR ## Konverterer et tal til tekst ved hjælp af valutaformatet kr. (kroner)
+EXACT = EKSAKT ## Kontrollerer, om to tekstværdier er identiske
+FIND = FIND ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver)
+FINDB = FINDB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver)
+FIXED = FAST ## Formaterer et tal som tekst med et fast antal decimaler
+JIS = JIS ## Ændrer engelske tegn i halv bredde (enkelt-byte) eller katakana i en tegnstreng til tegn i fuld bredde (dobbelt-byte)
+LEFT = VENSTRE ## Returnerer tegnet længst til venstre i en tekstværdi
+LEFTB = VENSTREB ## Returnerer tegnet længst til venstre i en tekstværdi
+LEN = LÆNGDE ## Returnerer antallet af tegn i en tekststreng
+LENB = LÆNGDEB ## Returnerer antallet af tegn i en tekststreng
+LOWER = SMÅ.BOGSTAVER ## Konverterer tekst til små bogstaver
+MID = MIDT ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition
+MIDB = MIDTB ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition
+PHONETIC = FONETISK ## Uddrager de fonetiske (furigana) tegn fra en tekststreng
+PROPER = STORT.FORBOGSTAV ## Konverterer første bogstav i hvert ord i teksten til stort bogstav
+REPLACE = ERSTAT ## Erstatter tegn i tekst
+REPLACEB = ERSTATB ## Erstatter tegn i tekst
+REPT = GENTAG ## Gentager tekst et givet antal gange
+RIGHT = HØJRE ## Returnerer tegnet længste til højre i en tekstværdi
+RIGHTB = HØJREB ## Returnerer tegnet længste til højre i en tekstværdi
+SEARCH = SØG ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver)
+SEARCHB = SØGB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver)
+SUBSTITUTE = UDSKIFT ## Udskifter gammel tekst med ny tekst i en tekststreng
+T = T ## Konverterer argumenterne til tekst
+TEXT = TEKST ## Formaterer et tal og konverterer det til tekst
+TRIM = FJERN.OVERFLØDIGE.BLANKE ## Fjerner mellemrum fra tekst
+UPPER = STORE.BOGSTAVER ## Konverterer tekst til store bogstaver
+VALUE = VÆRDI ## Konverterer et tekstargument til et tal
diff --git a/PHPExcel/locale/de/config b/PHPExcel/locale/de/config
new file mode 100644
index 0000000..c997275
--- /dev/null
+++ b/PHPExcel/locale/de/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = €
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULL!
+DIV0 = #DIV/0!
+VALUE = #WERT!
+REF = #BEZUG!
+NAME = #NAME?
+NUM = #ZAHL!
+NA = #NV
diff --git a/PHPExcel/locale/de/functions b/PHPExcel/locale/de/functions
new file mode 100644
index 0000000..8ce08de
--- /dev/null
+++ b/PHPExcel/locale/de/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Add-In- und Automatisierungsfunktionen
+##
+GETPIVOTDATA = PIVOTDATENZUORDNEN ## In einem PivotTable-Bericht gespeicherte Daten werden zurückgegeben.
+
+
+##
+## Cube functions Cubefunktionen
+##
+CUBEKPIMEMBER = CUBEKPIELEMENT ## Gibt Name, Eigenschaft und Measure eines Key Performance Indicators (KPI) zurück und zeigt den Namen und die Eigenschaft in der Zelle an. Ein KPI ist ein quantifizierbares Maß, wie z. B. der monatliche Bruttogewinn oder die vierteljährliche Mitarbeiterfluktuation, mit dessen Hilfe das Leistungsverhalten eines Unternehmens überwacht werden kann.
+CUBEMEMBER = CUBEELEMENT ## Gibt ein Element oder ein Tuple in einer Cubehierarchie zurück. Wird verwendet, um zu überprüfen, ob das Element oder Tuple im Cube vorhanden ist.
+CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT ## Gibt den Wert einer Elementeigenschaft im Cube zurück. Wird verwendet, um zu überprüfen, ob ein Elementname im Cube vorhanden ist, und um die für dieses Element angegebene Eigenschaft zurückzugeben.
+CUBERANKEDMEMBER = CUBERANGELEMENT ## Gibt das n-te oder n-rangige Element in einer Menge zurück. Wird verwendet, um mindestens ein Element in einer Menge zurückzugeben, wie z. B. bester Vertriebsmitarbeiter oder 10 beste Kursteilnehmer.
+CUBESET = CUBEMENGE ## Definiert eine berechnete Menge Elemente oder Tuples durch Senden eines Mengenausdrucks an den Cube auf dem Server, der die Menge erstellt und an Microsoft Office Excel zurückgibt.
+CUBESETCOUNT = CUBEMENGENANZAHL ## Gibt die Anzahl der Elemente in einer Menge zurück.
+CUBEVALUE = CUBEWERT ## Gibt einen Aggregatwert aus einem Cube zurück.
+
+
+##
+## Database functions Datenbankfunktionen
+##
+DAVERAGE = DBMITTELWERT ## Gibt den Mittelwert der ausgewählten Datenbankeinträge zurück
+DCOUNT = DBANZAHL ## Zählt die Zellen mit Zahlen in einer Datenbank
+DCOUNTA = DBANZAHL2 ## Zählt nicht leere Zellen in einer Datenbank
+DGET = DBAUSZUG ## Extrahiert aus einer Datenbank einen einzelnen Datensatz, der den angegebenen Kriterien entspricht
+DMAX = DBMAX ## Gibt den größten Wert aus ausgewählten Datenbankeinträgen zurück
+DMIN = DBMIN ## Gibt den kleinsten Wert aus ausgewählten Datenbankeinträgen zurück
+DPRODUCT = DBPRODUKT ## Multipliziert die Werte in einem bestimmten Feld mit Datensätzen, die den Kriterien in einer Datenbank entsprechen
+DSTDEV = DBSTDABW ## Schätzt die Standardabweichung auf der Grundlage einer Stichprobe aus ausgewählten Datenbankeinträgen
+DSTDEVP = DBSTDABWN ## Berechnet die Standardabweichung auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge
+DSUM = DBSUMME ## Addiert die Zahlen in der Feldspalte mit Datensätzen in der Datenbank, die den Kriterien entsprechen
+DVAR = DBVARIANZ ## Schätzt die Varianz auf der Grundlage ausgewählter Datenbankeinträge
+DVARP = DBVARIANZEN ## Berechnet die Varianz auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge
+
+
+##
+## Date and time functions Datums- und Zeitfunktionen
+##
+DATE = DATUM ## Gibt die fortlaufende Zahl eines bestimmten Datums zurück
+DATEVALUE = DATWERT ## Wandelt ein Datum in Form von Text in eine fortlaufende Zahl um
+DAY = TAG ## Wandelt eine fortlaufende Zahl in den Tag des Monats um
+DAYS360 = TAGE360 ## Berechnet die Anzahl der Tage zwischen zwei Datumsangaben ausgehend von einem Jahr, das 360 Tage hat
+EDATE = EDATUM ## Gibt die fortlaufende Zahl des Datums zurück, bei dem es sich um die angegebene Anzahl von Monaten vor oder nach dem Anfangstermin handelt
+EOMONTH = MONATSENDE ## Gibt die fortlaufende Zahl des letzten Tags des Monats vor oder nach einer festgelegten Anzahl von Monaten zurück
+HOUR = STUNDE ## Wandelt eine fortlaufende Zahl in eine Stunde um
+MINUTE = MINUTE ## Wandelt eine fortlaufende Zahl in eine Minute um
+MONTH = MONAT ## Wandelt eine fortlaufende Zahl in einen Monat um
+NETWORKDAYS = NETTOARBEITSTAGE ## Gibt die Anzahl von ganzen Arbeitstagen zwischen zwei Datumswerten zurück
+NOW = JETZT ## Gibt die fortlaufende Zahl des aktuellen Datums und der aktuellen Uhrzeit zurück
+SECOND = SEKUNDE ## Wandelt eine fortlaufende Zahl in eine Sekunde um
+TIME = ZEIT ## Gibt die fortlaufende Zahl einer bestimmten Uhrzeit zurück
+TIMEVALUE = ZEITWERT ## Wandelt eine Uhrzeit in Form von Text in eine fortlaufende Zahl um
+TODAY = HEUTE ## Gibt die fortlaufende Zahl des heutigen Datums zurück
+WEEKDAY = WOCHENTAG ## Wandelt eine fortlaufende Zahl in den Wochentag um
+WEEKNUM = KALENDERWOCHE ## Wandelt eine fortlaufende Zahl in eine Zahl um, die angibt, in welche Woche eines Jahres das angegebene Datum fällt
+WORKDAY = ARBEITSTAG ## Gibt die fortlaufende Zahl des Datums vor oder nach einer bestimmten Anzahl von Arbeitstagen zurück
+YEAR = JAHR ## Wandelt eine fortlaufende Zahl in ein Jahr um
+YEARFRAC = BRTEILJAHRE ## Gibt die Anzahl der ganzen Tage zwischen Ausgangsdatum und Enddatum in Bruchteilen von Jahren zurück
+
+
+##
+## Engineering functions Konstruktionsfunktionen
+##
+BESSELI = BESSELI ## Gibt die geänderte Besselfunktion In(x) zurück
+BESSELJ = BESSELJ ## Gibt die Besselfunktion Jn(x) zurück
+BESSELK = BESSELK ## Gibt die geänderte Besselfunktion Kn(x) zurück
+BESSELY = BESSELY ## Gibt die Besselfunktion Yn(x) zurück
+BIN2DEC = BININDEZ ## Wandelt eine binäre Zahl (Dualzahl) in eine dezimale Zahl um
+BIN2HEX = BININHEX ## Wandelt eine binäre Zahl (Dualzahl) in eine hexadezimale Zahl um
+BIN2OCT = BININOKT ## Wandelt eine binäre Zahl (Dualzahl) in eine oktale Zahl um
+COMPLEX = KOMPLEXE ## Wandelt den Real- und Imaginärteil in eine komplexe Zahl um
+CONVERT = UMWANDELN ## Wandelt eine Zahl von einem Maßsystem in ein anderes um
+DEC2BIN = DEZINBIN ## Wandelt eine dezimale Zahl in eine binäre Zahl (Dualzahl) um
+DEC2HEX = DEZINHEX ## Wandelt eine dezimale Zahl in eine hexadezimale Zahl um
+DEC2OCT = DEZINOKT ## Wandelt eine dezimale Zahl in eine oktale Zahl um
+DELTA = DELTA ## Überprüft, ob zwei Werte gleich sind
+ERF = GAUSSFEHLER ## Gibt die Gauss'sche Fehlerfunktion zurück
+ERFC = GAUSSFKOMPL ## Gibt das Komplement zur Gauss'schen Fehlerfunktion zurück
+GESTEP = GGANZZAHL ## Überprüft, ob eine Zahl größer als ein gegebener Schwellenwert ist
+HEX2BIN = HEXINBIN ## Wandelt eine hexadezimale Zahl in eine Binärzahl um
+HEX2DEC = HEXINDEZ ## Wandelt eine hexadezimale Zahl in eine dezimale Zahl um
+HEX2OCT = HEXINOKT ## Wandelt eine hexadezimale Zahl in eine Oktalzahl um
+IMABS = IMABS ## Gibt den Absolutbetrag (Modulo) einer komplexen Zahl zurück
+IMAGINARY = IMAGINÄRTEIL ## Gibt den Imaginärteil einer komplexen Zahl zurück
+IMARGUMENT = IMARGUMENT ## Gibt das Argument Theta zurück, einen Winkel, der als Bogenmaß ausgedrückt wird
+IMCONJUGATE = IMKONJUGIERTE ## Gibt die konjugierte komplexe Zahl zu einer komplexen Zahl zurück
+IMCOS = IMCOS ## Gibt den Kosinus einer komplexen Zahl zurück
+IMDIV = IMDIV ## Gibt den Quotienten zweier komplexer Zahlen zurück
+IMEXP = IMEXP ## Gibt die algebraische Form einer in exponentieller Schreibweise vorliegenden komplexen Zahl zurück
+IMLN = IMLN ## Gibt den natürlichen Logarithmus einer komplexen Zahl zurück
+IMLOG10 = IMLOG10 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 10 zurück
+IMLOG2 = IMLOG2 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 2 zurück
+IMPOWER = IMAPOTENZ ## Potenziert eine komplexe Zahl mit einer ganzen Zahl
+IMPRODUCT = IMPRODUKT ## Gibt das Produkt von komplexen Zahlen zurück
+IMREAL = IMREALTEIL ## Gibt den Realteil einer komplexen Zahl zurück
+IMSIN = IMSIN ## Gibt den Sinus einer komplexen Zahl zurück
+IMSQRT = IMWURZEL ## Gibt die Quadratwurzel einer komplexen Zahl zurück
+IMSUB = IMSUB ## Gibt die Differenz zwischen zwei komplexen Zahlen zurück
+IMSUM = IMSUMME ## Gibt die Summe von komplexen Zahlen zurück
+OCT2BIN = OKTINBIN ## Wandelt eine oktale Zahl in eine binäre Zahl (Dualzahl) um
+OCT2DEC = OKTINDEZ ## Wandelt eine oktale Zahl in eine dezimale Zahl um
+OCT2HEX = OKTINHEX ## Wandelt eine oktale Zahl in eine hexadezimale Zahl um
+
+
+##
+## Financial functions Finanzmathematische Funktionen
+##
+ACCRINT = AUFGELZINS ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers mit periodischen Zinszahlungen zurück
+ACCRINTM = AUFGELZINSF ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers zurück, die bei Fälligkeit ausgezahlt werden
+AMORDEGRC = AMORDEGRK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume mithilfe eines Abschreibungskoeffizienten zurück
+AMORLINC = AMORLINEARK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume zurück
+COUPDAYBS = ZINSTERMTAGVA ## Gibt die Anzahl der Tage vom Anfang des Zinstermins bis zum Abrechnungstermin zurück
+COUPDAYS = ZINSTERMTAGE ## Gibt die Anzahl der Tage der Zinsperiode zurück, die den Abrechnungstermin einschließt
+COUPDAYSNC = ZINSTERMTAGNZ ## Gibt die Anzahl der Tage vom Abrechnungstermin bis zum nächsten Zinstermin zurück
+COUPNCD = ZINSTERMNZ ## Gibt das Datum des ersten Zinstermins nach dem Abrechnungstermin zurück
+COUPNUM = ZINSTERMZAHL ## Gibt die Anzahl der Zinstermine zwischen Abrechnungs- und Fälligkeitsdatum zurück
+COUPPCD = ZINSTERMVZ ## Gibt das Datum des letzten Zinstermins vor dem Abrechnungstermin zurück
+CUMIPMT = KUMZINSZ ## Berechnet die kumulierten Zinsen, die zwischen zwei Perioden zu zahlen sind
+CUMPRINC = KUMKAPITAL ## Berechnet die aufgelaufene Tilgung eines Darlehens, die zwischen zwei Perioden zu zahlen ist
+DB = GDA2 ## Gibt die geometrisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück
+DDB = GDA ## Gibt die Abschreibung eines Anlageguts für einen angegebenen Zeitraum unter Verwendung der degressiven Doppelraten-Abschreibung oder eines anderen von Ihnen angegebenen Abschreibungsverfahrens zurück
+DISC = DISAGIO ## Gibt den in Prozent ausgedrückten Abzinsungssatz eines Wertpapiers zurück
+DOLLARDE = NOTIERUNGDEZ ## Wandelt eine Notierung, die als Dezimalbruch ausgedrückt wurde, in eine Dezimalzahl um
+DOLLARFR = NOTIERUNGBRU ## Wandelt eine Notierung, die als Dezimalzahl ausgedrückt wurde, in einen Dezimalbruch um
+DURATION = DURATION ## Gibt die jährliche Duration eines Wertpapiers mit periodischen Zinszahlungen zurück
+EFFECT = EFFEKTIV ## Gibt die jährliche Effektivverzinsung zurück
+FV = ZW ## Gibt den zukünftigen Wert (Endwert) einer Investition zurück
+FVSCHEDULE = ZW2 ## Gibt den aufgezinsten Wert des Anfangskapitals für eine Reihe periodisch unterschiedlicher Zinssätze zurück
+INTRATE = ZINSSATZ ## Gibt den Zinssatz eines voll investierten Wertpapiers zurück
+IPMT = ZINSZ ## Gibt die Zinszahlung einer Investition für die angegebene Periode zurück
+IRR = IKV ## Gibt den internen Zinsfuß einer Investition ohne Finanzierungskosten oder Reinvestitionsgewinne zurück
+ISPMT = ISPMT ## Berechnet die während eines bestimmten Zeitraums für eine Investition gezahlten Zinsen
+MDURATION = MDURATION ## Gibt die geänderte Dauer für ein Wertpapier mit einem angenommenen Nennwert von 100 € zurück
+MIRR = QIKV ## Gibt den internen Zinsfuß zurück, wobei positive und negative Zahlungen zu unterschiedlichen Sätzen finanziert werden
+NOMINAL = NOMINAL ## Gibt die jährliche Nominalverzinsung zurück
+NPER = ZZR ## Gibt die Anzahl der Zahlungsperioden einer Investition zurück
+NPV = NBW ## Gibt den Nettobarwert einer Investition auf Basis periodisch anfallender Zahlungen und eines Abzinsungsfaktors zurück
+ODDFPRICE = UNREGER.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück
+ODDFYIELD = UNREGER.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück
+ODDLPRICE = UNREGLE.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück
+ODDLYIELD = UNREGLE.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück
+PMT = RMZ ## Gibt die periodische Zahlung für eine Annuität zurück
+PPMT = KAPZ ## Gibt die Kapitalrückzahlung einer Investition für eine angegebene Periode zurück
+PRICE = KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das periodisch Zinsen auszahlt
+PRICEDISC = KURSDISAGIO ## Gibt den Kurs pro 100 € Nennwert eines unverzinslichen Wertpapiers zurück
+PRICEMAT = KURSFÄLLIG ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt
+PV = BW ## Gibt den Barwert einer Investition zurück
+RATE = ZINS ## Gibt den Zinssatz pro Zeitraum einer Annuität zurück
+RECEIVED = AUSZAHLUNG ## Gibt den Auszahlungsbetrag eines voll investierten Wertpapiers am Fälligkeitstermin zurück
+SLN = LIA ## Gibt die lineare Abschreibung eines Wirtschaftsguts pro Periode zurück
+SYD = DIA ## Gibt die arithmetisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück
+TBILLEQ = TBILLÄQUIV ## Gibt die Rendite für ein Wertpapier zurück
+TBILLPRICE = TBILLKURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück
+TBILLYIELD = TBILLRENDITE ## Gibt die Rendite für ein Wertpapier zurück
+VDB = VDB ## Gibt die degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode oder Teilperiode zurück
+XIRR = XINTZINSFUSS ## Gibt den internen Zinsfuß einer Reihe nicht periodisch anfallender Zahlungen zurück
+XNPV = XKAPITALWERT ## Gibt den Nettobarwert (Kapitalwert) einer Reihe nicht periodisch anfallender Zahlungen zurück
+YIELD = RENDITE ## Gibt die Rendite eines Wertpapiers zurück, das periodisch Zinsen auszahlt
+YIELDDISC = RENDITEDIS ## Gibt die jährliche Rendite eines unverzinslichen Wertpapiers zurück
+YIELDMAT = RENDITEFÄLL ## Gibt die jährliche Rendite eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt
+
+
+##
+## Information functions Informationsfunktionen
+##
+CELL = ZELLE ## Gibt Informationen zu Formatierung, Position oder Inhalt einer Zelle zurück
+ERROR.TYPE = FEHLER.TYP ## Gibt eine Zahl zurück, die einem Fehlertyp entspricht
+INFO = INFO ## Gibt Informationen zur aktuellen Betriebssystemumgebung zurück
+ISBLANK = ISTLEER ## Gibt WAHR zurück, wenn der Wert leer ist
+ISERR = ISTFEHL ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert außer #N/V ist
+ISERROR = ISTFEHLER ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert ist
+ISEVEN = ISTGERADE ## Gibt WAHR zurück, wenn es sich um eine gerade Zahl handelt
+ISLOGICAL = ISTLOG ## Gibt WAHR zurück, wenn der Wert ein Wahrheitswert ist
+ISNA = ISTNV ## Gibt WAHR zurück, wenn der Wert der Fehlerwert #N/V ist
+ISNONTEXT = ISTKTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das keinen Text enthält
+ISNUMBER = ISTZAHL ## Gibt WAHR zurück, wenn der Wert eine Zahl ist
+ISODD = ISTUNGERADE ## Gibt WAHR zurück, wenn es sich um eine ungerade Zahl handelt
+ISREF = ISTBEZUG ## Gibt WAHR zurück, wenn der Wert ein Bezug ist
+ISTEXT = ISTTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das Text enthält
+N = N ## Gibt den in eine Zahl umgewandelten Wert zurück
+NA = NV ## Gibt den Fehlerwert #NV zurück
+TYPE = TYP ## Gibt eine Zahl zurück, die den Datentyp des angegebenen Werts anzeigt
+
+
+##
+## Logical functions Logische Funktionen
+##
+AND = UND ## Gibt WAHR zurück, wenn alle zugehörigen Argumente WAHR sind
+FALSE = FALSCH ## Gibt den Wahrheitswert FALSCH zurück
+IF = WENN ## Gibt einen logischen Test zum Ausführen an
+IFERROR = WENNFEHLER ## Gibt einen von Ihnen festgelegten Wert zurück, wenn die Auswertung der Formel zu einem Fehler führt; andernfalls wird das Ergebnis der Formel zurückgegeben
+NOT = NICHT ## Kehrt den Wahrheitswert der zugehörigen Argumente um
+OR = ODER ## Gibt WAHR zurück, wenn ein Argument WAHR ist
+TRUE = WAHR ## Gibt den Wahrheitswert WAHR zurück
+
+
+##
+## Lookup and reference functions Nachschlage- und Verweisfunktionen
+##
+ADDRESS = ADRESSE ## Gibt einen Bezug auf eine einzelne Zelle in einem Tabellenblatt als Text zurück
+AREAS = BEREICHE ## Gibt die Anzahl der innerhalb eines Bezugs aufgeführten Bereiche zurück
+CHOOSE = WAHL ## Wählt einen Wert aus eine Liste mit Werten aus
+COLUMN = SPALTE ## Gibt die Spaltennummer eines Bezugs zurück
+COLUMNS = SPALTEN ## Gibt die Anzahl der Spalten in einem Bezug zurück
+HLOOKUP = HVERWEIS ## Sucht in der obersten Zeile einer Matrix und gibt den Wert der angegebenen Zelle zurück
+HYPERLINK = HYPERLINK ## Erstellt eine Verknüpfung, über die ein auf einem Netzwerkserver, in einem Intranet oder im Internet gespeichertes Dokument geöffnet wird
+INDEX = INDEX ## Verwendet einen Index, um einen Wert aus einem Bezug oder einer Matrix auszuwählen
+INDIRECT = INDIREKT ## Gibt einen Bezug zurück, der von einem Textwert angegeben wird
+LOOKUP = LOOKUP ## Sucht Werte in einem Vektor oder einer Matrix
+MATCH = VERGLEICH ## Sucht Werte in einem Bezug oder einer Matrix
+OFFSET = BEREICH.VERSCHIEBEN ## Gibt einen Bezugoffset aus einem gegebenen Bezug zurück
+ROW = ZEILE ## Gibt die Zeilennummer eines Bezugs zurück
+ROWS = ZEILEN ## Gibt die Anzahl der Zeilen in einem Bezug zurück
+RTD = RTD ## Ruft Echtzeitdaten von einem Programm ab, das die COM-Automatisierung (Automatisierung: Ein Verfahren, bei dem aus einer Anwendung oder einem Entwicklungstool heraus mit den Objekten einer anderen Anwendung gearbeitet wird. Die früher als OLE-Automatisierung bezeichnete Automatisierung ist ein Industriestandard und eine Funktion von COM (Component Object Model).) unterstützt
+TRANSPOSE = MTRANS ## Gibt die transponierte Matrix einer Matrix zurück
+VLOOKUP = SVERWEIS ## Sucht in der ersten Spalte einer Matrix und arbeitet sich durch die Zeile, um den Wert einer Zelle zurückzugeben
+
+
+##
+## Math and trigonometry functions Mathematische und trigonometrische Funktionen
+##
+ABS = ABS ## Gibt den Absolutwert einer Zahl zurück
+ACOS = ARCCOS ## Gibt den Arkuskosinus einer Zahl zurück
+ACOSH = ARCCOSHYP ## Gibt den umgekehrten hyperbolischen Kosinus einer Zahl zurück
+ASIN = ARCSIN ## Gibt den Arkussinus einer Zahl zurück
+ASINH = ARCSINHYP ## Gibt den umgekehrten hyperbolischen Sinus einer Zahl zurück
+ATAN = ARCTAN ## Gibt den Arkustangens einer Zahl zurück
+ATAN2 = ARCTAN2 ## Gibt den Arkustangens einer x- und einer y-Koordinate zurück
+ATANH = ARCTANHYP ## Gibt den umgekehrten hyperbolischen Tangens einer Zahl zurück
+CEILING = OBERGRENZE ## Rundet eine Zahl auf die nächste ganze Zahl oder das nächste Vielfache von Schritt
+COMBIN = KOMBINATIONEN ## Gibt die Anzahl der Kombinationen für eine bestimmte Anzahl von Objekten zurück
+COS = COS ## Gibt den Kosinus einer Zahl zurück
+COSH = COSHYP ## Gibt den hyperbolischen Kosinus einer Zahl zurück
+DEGREES = GRAD ## Wandelt Bogenmaß (Radiant) in Grad um
+EVEN = GERADE ## Rundet eine Zahl auf die nächste gerade ganze Zahl auf
+EXP = EXP ## Potenziert die Basis e mit der als Argument angegebenen Zahl
+FACT = FAKULTÄT ## Gibt die Fakultät einer Zahl zurück
+FACTDOUBLE = ZWEIFAKULTÄT ## Gibt die Fakultät zu Zahl mit Schrittlänge 2 zurück
+FLOOR = UNTERGRENZE ## Rundet die Zahl auf Anzahl_Stellen ab
+GCD = GGT ## Gibt den größten gemeinsamen Teiler zurück
+INT = GANZZAHL ## Rundet eine Zahl auf die nächstkleinere ganze Zahl ab
+LCM = KGV ## Gibt das kleinste gemeinsame Vielfache zurück
+LN = LN ## Gibt den natürlichen Logarithmus einer Zahl zurück
+LOG = LOG ## Gibt den Logarithmus einer Zahl zu der angegebenen Basis zurück
+LOG10 = LOG10 ## Gibt den Logarithmus einer Zahl zur Basis 10 zurück
+MDETERM = MDET ## Gibt die Determinante einer Matrix zurück
+MINVERSE = MINV ## Gibt die inverse Matrix einer Matrix zurück
+MMULT = MMULT ## Gibt das Produkt zweier Matrizen zurück
+MOD = REST ## Gibt den Rest einer Division zurück
+MROUND = VRUNDEN ## Gibt eine auf das gewünschte Vielfache gerundete Zahl zurück
+MULTINOMIAL = POLYNOMIAL ## Gibt den Polynomialkoeffizienten einer Gruppe von Zahlen zurück
+ODD = UNGERADE ## Rundet eine Zahl auf die nächste ungerade ganze Zahl auf
+PI = PI ## Gibt den Wert Pi zurück
+POWER = POTENZ ## Gibt als Ergebnis eine potenzierte Zahl zurück
+PRODUCT = PRODUKT ## Multipliziert die zugehörigen Argumente
+QUOTIENT = QUOTIENT ## Gibt den ganzzahligen Anteil einer Division zurück
+RADIANS = BOGENMASS ## Wandelt Grad in Bogenmaß (Radiant) um
+RAND = ZUFALLSZAHL ## Gibt eine Zufallszahl zwischen 0 und 1 zurück
+RANDBETWEEN = ZUFALLSBEREICH ## Gibt eine Zufallszahl aus dem festgelegten Bereich zurück
+ROMAN = RÖMISCH ## Wandelt eine arabische Zahl in eine römische Zahl als Text um
+ROUND = RUNDEN ## Rundet eine Zahl auf eine bestimmte Anzahl von Dezimalstellen
+ROUNDDOWN = ABRUNDEN ## Rundet die Zahl auf Anzahl_Stellen ab
+ROUNDUP = AUFRUNDEN ## Rundet die Zahl auf Anzahl_Stellen auf
+SERIESSUM = POTENZREIHE ## Gibt die Summe von Potenzen (zur Berechnung von Potenzreihen und dichotomen Wahrscheinlichkeiten) zurück
+SIGN = VORZEICHEN ## Gibt das Vorzeichen einer Zahl zurück
+SIN = SIN ## Gibt den Sinus einer Zahl zurück
+SINH = SINHYP ## Gibt den hyperbolischen Sinus einer Zahl zurück
+SQRT = WURZEL ## Gibt die Quadratwurzel einer Zahl zurück
+SQRTPI = WURZELPI ## Gibt die Wurzel aus der mit Pi (pi) multiplizierten Zahl zurück
+SUBTOTAL = TEILERGEBNIS ## Gibt ein Teilergebnis in einer Liste oder Datenbank zurück
+SUM = SUMME ## Addiert die zugehörigen Argumente
+SUMIF = SUMMEWENN ## Addiert Zahlen, die mit den Suchkriterien übereinstimmen
+SUMIFS = SUMMEWENNS ## Die Zellen, die mehrere Kriterien erfüllen, werden in einem Bereich hinzugefügt
+SUMPRODUCT = SUMMENPRODUKT ## Gibt die Summe der Produkte zusammengehöriger Matrixkomponenten zurück
+SUMSQ = QUADRATESUMME ## Gibt die Summe der quadrierten Argumente zurück
+SUMX2MY2 = SUMMEX2MY2 ## Gibt die Summe der Differenzen der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück
+SUMX2PY2 = SUMMEX2PY2 ## Gibt die Summe der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück
+SUMXMY2 = SUMMEXMY2 ## Gibt die Summe der quadrierten Differenzen für zusammengehörige Komponenten zweier Matrizen zurück
+TAN = TAN ## Gibt den Tangens einer Zahl zurück
+TANH = TANHYP ## Gibt den hyperbolischen Tangens einer Zahl zurück
+TRUNC = KÜRZEN ## Schneidet die Kommastellen einer Zahl ab und gibt als Ergebnis eine ganze Zahl zurück
+
+
+##
+## Statistical functions Statistische Funktionen
+##
+AVEDEV = MITTELABW ## Gibt die durchschnittliche absolute Abweichung einer Reihe von Merkmalsausprägungen und ihrem Mittelwert zurück
+AVERAGE = MITTELWERT ## Gibt den Mittelwert der zugehörigen Argumente zurück
+AVERAGEA = MITTELWERTA ## Gibt den Mittelwert der zugehörigen Argumente, die Zahlen, Text und Wahrheitswerte enthalten, zurück
+AVERAGEIF = MITTELWERTWENN ## Der Durchschnittswert (arithmetisches Mittel) für alle Zellen in einem Bereich, die einem angegebenen Kriterium entsprechen, wird zurückgegeben
+AVERAGEIFS = MITTELWERTWENNS ## Gibt den Durchschnittswert (arithmetisches Mittel) aller Zellen zurück, die mehreren Kriterien entsprechen
+BETADIST = BETAVERT ## Gibt die Werte der kumulierten Betaverteilungsfunktion zurück
+BETAINV = BETAINV ## Gibt das Quantil der angegebenen Betaverteilung zurück
+BINOMDIST = BINOMVERT ## Gibt Wahrscheinlichkeiten einer binomialverteilten Zufallsvariablen zurück
+CHIDIST = CHIVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer Chi-Quadrat-verteilten Zufallsgröße zurück
+CHIINV = CHIINV ## Gibt Quantile der Verteilungsfunktion (1-Alpha) der Chi-Quadrat-Verteilung zurück
+CHITEST = CHITEST ## Gibt die Teststatistik eines Unabhängigkeitstests zurück
+CONFIDENCE = KONFIDENZ ## Ermöglicht die Berechnung des 1-Alpha Konfidenzintervalls für den Erwartungswert einer Zufallsvariablen
+CORREL = KORREL ## Gibt den Korrelationskoeffizienten zweier Reihen von Merkmalsausprägungen zurück
+COUNT = ANZAHL ## Gibt die Anzahl der Zahlen in der Liste mit Argumenten an
+COUNTA = ANZAHL2 ## Gibt die Anzahl der Werte in der Liste mit Argumenten an
+COUNTBLANK = ANZAHLLEEREZELLEN ## Gibt die Anzahl der leeren Zellen in einem Bereich an
+COUNTIF = ZÄHLENWENN ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit den Suchkriterien übereinstimmen
+COUNTIFS = ZÄHLENWENNS ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit mehreren Suchkriterien übereinstimmen
+COVAR = KOVAR ## Gibt die Kovarianz zurück, den Mittelwert der für alle Datenpunktpaare gebildeten Produkte der Abweichungen
+CRITBINOM = KRITBINOM ## Gibt den kleinsten Wert zurück, für den die kumulierten Wahrscheinlichkeiten der Binomialverteilung kleiner oder gleich einer Grenzwahrscheinlichkeit sind
+DEVSQ = SUMQUADABW ## Gibt die Summe der quadrierten Abweichungen der Datenpunkte von ihrem Stichprobenmittelwert zurück
+EXPONDIST = EXPONVERT ## Gibt Wahrscheinlichkeiten einer exponential verteilten Zufallsvariablen zurück
+FDIST = FVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer F-verteilten Zufallsvariablen zurück
+FINV = FINV ## Gibt Quantile der F-Verteilung zurück
+FISHER = FISHER ## Gibt die Fisher-Transformation zurück
+FISHERINV = FISHERINV ## Gibt die Umkehrung der Fisher-Transformation zurück
+FORECAST = PROGNOSE ## Gibt einen Wert zurück, der sich aus einem linearen Trend ergibt
+FREQUENCY = HÄUFIGKEIT ## Gibt eine Häufigkeitsverteilung als vertikale Matrix zurück
+FTEST = FTEST ## Gibt die Teststatistik eines F-Tests zurück
+GAMMADIST = GAMMAVERT ## Gibt Wahrscheinlichkeiten einer gammaverteilten Zufallsvariablen zurück
+GAMMAINV = GAMMAINV ## Gibt Quantile der Gammaverteilung zurück
+GAMMALN = GAMMALN ## Gibt den natürlichen Logarithmus der Gammafunktion zurück, Γ(x)
+GEOMEAN = GEOMITTEL ## Gibt das geometrische Mittel zurück
+GROWTH = VARIATION ## Gibt Werte zurück, die sich aus einem exponentiellen Trend ergeben
+HARMEAN = HARMITTEL ## Gibt das harmonische Mittel zurück
+HYPGEOMDIST = HYPGEOMVERT ## Gibt Wahrscheinlichkeiten einer hypergeometrisch-verteilten Zufallsvariablen zurück
+INTERCEPT = ACHSENABSCHNITT ## Gibt den Schnittpunkt der Regressionsgeraden zurück
+KURT = KURT ## Gibt die Kurtosis (Exzess) einer Datengruppe zurück
+LARGE = KGRÖSSTE ## Gibt den k-größten Wert einer Datengruppe zurück
+LINEST = RGP ## Gibt die Parameter eines linearen Trends zurück
+LOGEST = RKP ## Gibt die Parameter eines exponentiellen Trends zurück
+LOGINV = LOGINV ## Gibt Quantile der Lognormalverteilung zurück
+LOGNORMDIST = LOGNORMVERT ## Gibt Werte der Verteilungsfunktion einer lognormalverteilten Zufallsvariablen zurück
+MAX = MAX ## Gibt den Maximalwert einer Liste mit Argumenten zurück
+MAXA = MAXA ## Gibt den Maximalwert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten
+MEDIAN = MEDIAN ## Gibt den Median der angegebenen Zahlen zurück
+MIN = MIN ## Gibt den Minimalwert einer Liste mit Argumenten zurück
+MINA = MINA ## Gibt den kleinsten Wert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten
+MODE = MODALWERT ## Gibt den am häufigsten vorkommenden Wert in einer Datengruppe zurück
+NEGBINOMDIST = NEGBINOMVERT ## Gibt Wahrscheinlichkeiten einer negativen, binominal verteilten Zufallsvariablen zurück
+NORMDIST = NORMVERT ## Gibt Wahrscheinlichkeiten einer normal verteilten Zufallsvariablen zurück
+NORMINV = NORMINV ## Gibt Quantile der Normalverteilung zurück
+NORMSDIST = STANDNORMVERT ## Gibt Werte der Verteilungsfunktion einer standardnormalverteilten Zufallsvariablen zurück
+NORMSINV = STANDNORMINV ## Gibt Quantile der Standardnormalverteilung zurück
+PEARSON = PEARSON ## Gibt den Pearsonschen Korrelationskoeffizienten zurück
+PERCENTILE = QUANTIL ## Gibt das Alpha-Quantil einer Gruppe von Daten zurück
+PERCENTRANK = QUANTILSRANG ## Gibt den prozentualen Rang (Alpha) eines Werts in einer Datengruppe zurück
+PERMUT = VARIATIONEN ## Gibt die Anzahl der Möglichkeiten zurück, um k Elemente aus einer Menge von n Elementen ohne Zurücklegen zu ziehen
+POISSON = POISSON ## Gibt Wahrscheinlichkeiten einer poissonverteilten Zufallsvariablen zurück
+PROB = WAHRSCHBEREICH ## Gibt die Wahrscheinlichkeit für ein von zwei Werten eingeschlossenes Intervall zurück
+QUARTILE = QUARTILE ## Gibt die Quartile der Datengruppe zurück
+RANK = RANG ## Gibt den Rang zurück, den eine Zahl innerhalb einer Liste von Zahlen einnimmt
+RSQ = BESTIMMTHEITSMASS ## Gibt das Quadrat des Pearsonschen Korrelationskoeffizienten zurück
+SKEW = SCHIEFE ## Gibt die Schiefe einer Verteilung zurück
+SLOPE = STEIGUNG ## Gibt die Steigung der Regressionsgeraden zurück
+SMALL = KKLEINSTE ## Gibt den k-kleinsten Wert einer Datengruppe zurück
+STANDARDIZE = STANDARDISIERUNG ## Gibt den standardisierten Wert zurück
+STDEV = STABW ## Schätzt die Standardabweichung ausgehend von einer Stichprobe
+STDEVA = STABWA ## Schätzt die Standardabweichung ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält
+STDEVP = STABWN ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit
+STDEVPA = STABWNA ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält
+STEYX = STFEHLERYX ## Gibt den Standardfehler der geschätzten y-Werte für alle x-Werte der Regression zurück
+TDIST = TVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer (Student) t-verteilten Zufallsvariablen zurück
+TINV = TINV ## Gibt Quantile der t-Verteilung zurück
+TREND = TREND ## Gibt Werte zurück, die sich aus einem linearen Trend ergeben
+TRIMMEAN = GESTUTZTMITTEL ## Gibt den Mittelwert einer Datengruppe zurück, ohne die Randwerte zu berücksichtigen
+TTEST = TTEST ## Gibt die Teststatistik eines Student'schen t-Tests zurück
+VAR = VARIANZ ## Schätzt die Varianz ausgehend von einer Stichprobe
+VARA = VARIANZA ## Schätzt die Varianz ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält
+VARP = VARIANZEN ## Berechnet die Varianz ausgehend von der Grundgesamtheit
+VARPA = VARIANZENA ## Berechnet die Varianz ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält
+WEIBULL = WEIBULL ## Gibt Wahrscheinlichkeiten einer weibullverteilten Zufallsvariablen zurück
+ZTEST = GTEST ## Gibt den einseitigen Wahrscheinlichkeitswert für einen Gausstest (Normalverteilung) zurück
+
+
+##
+## Text functions Textfunktionen
+##
+ASC = ASC ## Konvertiert DB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in SB-Text
+BAHTTEXT = BAHTTEXT ## Wandelt eine Zahl in Text im Währungsformat ß (Baht) um
+CHAR = ZEICHEN ## Gibt das der Codezahl entsprechende Zeichen zurück
+CLEAN = SÄUBERN ## Löscht alle nicht druckbaren Zeichen aus einem Text
+CODE = CODE ## Gibt die Codezahl des ersten Zeichens in einem Text zurück
+CONCATENATE = VERKETTEN ## Verknüpft mehrere Textelemente zu einem Textelement
+DOLLAR = DM ## Wandelt eine Zahl in Text im Währungsformat € (Euro) um
+EXACT = IDENTISCH ## Prüft, ob zwei Textwerte identisch sind
+FIND = FINDEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden)
+FINDB = FINDENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden)
+FIXED = FEST ## Formatiert eine Zahl als Text mit einer festen Anzahl von Dezimalstellen
+JIS = JIS ## Konvertiert SB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in DB-Text
+LEFT = LINKS ## Gibt die Zeichen ganz links in einem Textwert zurück
+LEFTB = LINKSB ## Gibt die Zeichen ganz links in einem Textwert zurück
+LEN = LÄNGE ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück
+LENB = LÄNGEB ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück
+LOWER = KLEIN ## Wandelt Text in Kleinbuchstaben um
+MID = TEIL ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück
+MIDB = TEILB ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück
+PHONETIC = PHONETIC ## Extrahiert die phonetischen (Furigana-)Zeichen aus einer Textzeichenfolge
+PROPER = GROSS2 ## Wandelt den ersten Buchstaben aller Wörter eines Textwerts in Großbuchstaben um
+REPLACE = ERSETZEN ## Ersetzt Zeichen in Text
+REPLACEB = ERSETZENB ## Ersetzt Zeichen in Text
+REPT = WIEDERHOLEN ## Wiederholt einen Text so oft wie angegeben
+RIGHT = RECHTS ## Gibt die Zeichen ganz rechts in einem Textwert zurück
+RIGHTB = RECHTSB ## Gibt die Zeichen ganz rechts in einem Textwert zurück
+SEARCH = SUCHEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden)
+SEARCHB = SUCHENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden)
+SUBSTITUTE = WECHSELN ## Ersetzt in einer Zeichenfolge neuen Text gegen alten
+T = T ## Wandelt die zugehörigen Argumente in Text um
+TEXT = TEXT ## Formatiert eine Zahl und wandelt sie in Text um
+TRIM = GLÄTTEN ## Entfernt Leerzeichen aus Text
+UPPER = GROSS ## Wandelt Text in Großbuchstaben um
+VALUE = WERT ## Wandelt ein Textargument in eine Zahl um
diff --git a/PHPExcel/locale/en/uk/config b/PHPExcel/locale/en/uk/config
new file mode 100644
index 0000000..dfcc63b
--- /dev/null
+++ b/PHPExcel/locale/en/uk/config
@@ -0,0 +1,32 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+##
+## (For future use)
+##
+currencySymbol = £
diff --git a/PHPExcel/locale/es/config b/PHPExcel/locale/es/config
new file mode 100644
index 0000000..0b11eb7
--- /dev/null
+++ b/PHPExcel/locale/es/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = $ ## I'm surprised that the Excel Documentation suggests $ rather than €
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #¡NULO!
+DIV0 = #¡DIV/0!
+VALUE = #¡VALOR!
+REF = #¡REF!
+NAME = #¿NOMBRE?
+NUM = #¡NÚM!
+NA = #N/A
diff --git a/PHPExcel/locale/es/functions b/PHPExcel/locale/es/functions
new file mode 100644
index 0000000..f6e6fd2
--- /dev/null
+++ b/PHPExcel/locale/es/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Funciones de complementos y automatización
+##
+GETPIVOTDATA = IMPORTARDATOSDINAMICOS ## Devuelve los datos almacenados en un informe de tabla dinámica.
+
+
+##
+## Cube functions Funciones de cubo
+##
+CUBEKPIMEMBER = MIEMBROKPICUBO ## Devuelve un nombre, propiedad y medida de indicador de rendimiento clave (KPI) y muestra el nombre y la propiedad en la celda. Un KPI es una medida cuantificable, como los beneficios brutos mensuales o la facturación trimestral por empleado, que se usa para supervisar el rendimiento de una organización.
+CUBEMEMBER = MIEMBROCUBO ## Devuelve un miembro o tupla en una jerarquía de cubo. Se usa para validar la existencia del miembro o la tupla en el cubo.
+CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO ## Devuelve el valor de una propiedad de miembro del cubo Se usa para validar la existencia de un nombre de miembro en el cubo y para devolver la propiedad especificada para este miembro.
+CUBERANKEDMEMBER = MIEMBRORANGOCUBO ## Devuelve el miembro n, o clasificado, de un conjunto. Se usa para devolver uno o más elementos de un conjunto, por ejemplo, el representante con mejores ventas o los diez mejores alumnos.
+CUBESET = CONJUNTOCUBO ## Define un conjunto calculado de miembros o tuplas mediante el envío de una expresión de conjunto al cubo en el servidor, lo que crea el conjunto y, después, devuelve dicho conjunto a Microsoft Office Excel.
+CUBESETCOUNT = RECUENTOCONJUNTOCUBO ## Devuelve el número de elementos de un conjunto.
+CUBEVALUE = VALORCUBO ## Devuelve un valor agregado de un cubo.
+
+
+##
+## Database functions Funciones de base de datos
+##
+DAVERAGE = BDPROMEDIO ## Devuelve el promedio de las entradas seleccionadas en la base de datos.
+DCOUNT = BDCONTAR ## Cuenta el número de celdas que contienen números en una base de datos.
+DCOUNTA = BDCONTARA ## Cuenta el número de celdas no vacías en una base de datos.
+DGET = BDEXTRAER ## Extrae de una base de datos un único registro que cumple los criterios especificados.
+DMAX = BDMAX ## Devuelve el valor máximo de las entradas seleccionadas de la base de datos.
+DMIN = BDMIN ## Devuelve el valor mínimo de las entradas seleccionadas de la base de datos.
+DPRODUCT = BDPRODUCTO ## Multiplica los valores de un campo concreto de registros de una base de datos que cumplen los criterios especificados.
+DSTDEV = BDDESVEST ## Calcula la desviación estándar a partir de una muestra de entradas seleccionadas en la base de datos.
+DSTDEVP = BDDESVESTP ## Calcula la desviación estándar en función de la población total de las entradas seleccionadas de la base de datos.
+DSUM = BDSUMA ## Suma los números de la columna de campo de los registros de la base de datos que cumplen los criterios.
+DVAR = BDVAR ## Calcula la varianza a partir de una muestra de entradas seleccionadas de la base de datos.
+DVARP = BDVARP ## Calcula la varianza a partir de la población total de entradas seleccionadas de la base de datos.
+
+
+##
+## Date and time functions Funciones de fecha y hora
+##
+DATE = FECHA ## Devuelve el número de serie correspondiente a una fecha determinada.
+DATEVALUE = FECHANUMERO ## Convierte una fecha con formato de texto en un valor de número de serie.
+DAY = DIA ## Convierte un número de serie en un valor de día del mes.
+DAYS360 = DIAS360 ## Calcula el número de días entre dos fechas a partir de un año de 360 días.
+EDATE = FECHA.MES ## Devuelve el número de serie de la fecha equivalente al número indicado de meses anteriores o posteriores a la fecha inicial.
+EOMONTH = FIN.MES ## Devuelve el número de serie correspondiente al último día del mes anterior o posterior a un número de meses especificado.
+HOUR = HORA ## Convierte un número de serie en un valor de hora.
+MINUTE = MINUTO ## Convierte un número de serie en un valor de minuto.
+MONTH = MES ## Convierte un número de serie en un valor de mes.
+NETWORKDAYS = DIAS.LAB ## Devuelve el número de todos los días laborables existentes entre dos fechas.
+NOW = AHORA ## Devuelve el número de serie correspondiente a la fecha y hora actuales.
+SECOND = SEGUNDO ## Convierte un número de serie en un valor de segundo.
+TIME = HORA ## Devuelve el número de serie correspondiente a una hora determinada.
+TIMEVALUE = HORANUMERO ## Convierte una hora con formato de texto en un valor de número de serie.
+TODAY = HOY ## Devuelve el número de serie correspondiente al día actual.
+WEEKDAY = DIASEM ## Convierte un número de serie en un valor de día de la semana.
+WEEKNUM = NUM.DE.SEMANA ## Convierte un número de serie en un número que representa el lugar numérico correspondiente a una semana de un año.
+WORKDAY = DIA.LAB ## Devuelve el número de serie de la fecha que tiene lugar antes o después de un número determinado de días laborables.
+YEAR = AÑO ## Convierte un número de serie en un valor de año.
+YEARFRAC = FRAC.AÑO ## Devuelve la fracción de año que representa el número total de días existentes entre el valor de fecha_inicial y el de fecha_final.
+
+
+##
+## Engineering functions Funciones de ingeniería
+##
+BESSELI = BESSELI ## Devuelve la función Bessel In(x) modificada.
+BESSELJ = BESSELJ ## Devuelve la función Bessel Jn(x).
+BESSELK = BESSELK ## Devuelve la función Bessel Kn(x) modificada.
+BESSELY = BESSELY ## Devuelve la función Bessel Yn(x).
+BIN2DEC = BIN.A.DEC ## Convierte un número binario en decimal.
+BIN2HEX = BIN.A.HEX ## Convierte un número binario en hexadecimal.
+BIN2OCT = BIN.A.OCT ## Convierte un número binario en octal.
+COMPLEX = COMPLEJO ## Convierte coeficientes reales e imaginarios en un número complejo.
+CONVERT = CONVERTIR ## Convierte un número de un sistema de medida a otro.
+DEC2BIN = DEC.A.BIN ## Convierte un número decimal en binario.
+DEC2HEX = DEC.A.HEX ## Convierte un número decimal en hexadecimal.
+DEC2OCT = DEC.A.OCT ## Convierte un número decimal en octal.
+DELTA = DELTA ## Comprueba si dos valores son iguales.
+ERF = FUN.ERROR ## Devuelve la función de error.
+ERFC = FUN.ERROR.COMPL ## Devuelve la función de error complementario.
+GESTEP = MAYOR.O.IGUAL ## Comprueba si un número es mayor que un valor de umbral.
+HEX2BIN = HEX.A.BIN ## Convierte un número hexadecimal en binario.
+HEX2DEC = HEX.A.DEC ## Convierte un número hexadecimal en decimal.
+HEX2OCT = HEX.A.OCT ## Convierte un número hexadecimal en octal.
+IMABS = IM.ABS ## Devuelve el valor absoluto (módulo) de un número complejo.
+IMAGINARY = IMAGINARIO ## Devuelve el coeficiente imaginario de un número complejo.
+IMARGUMENT = IM.ANGULO ## Devuelve el argumento theta, un ángulo expresado en radianes.
+IMCONJUGATE = IM.CONJUGADA ## Devuelve la conjugada compleja de un número complejo.
+IMCOS = IM.COS ## Devuelve el coseno de un número complejo.
+IMDIV = IM.DIV ## Devuelve el cociente de dos números complejos.
+IMEXP = IM.EXP ## Devuelve el valor exponencial de un número complejo.
+IMLN = IM.LN ## Devuelve el logaritmo natural (neperiano) de un número complejo.
+IMLOG10 = IM.LOG10 ## Devuelve el logaritmo en base 10 de un número complejo.
+IMLOG2 = IM.LOG2 ## Devuelve el logaritmo en base 2 de un número complejo.
+IMPOWER = IM.POT ## Devuelve un número complejo elevado a una potencia entera.
+IMPRODUCT = IM.PRODUCT ## Devuelve el producto de números complejos.
+IMREAL = IM.REAL ## Devuelve el coeficiente real de un número complejo.
+IMSIN = IM.SENO ## Devuelve el seno de un número complejo.
+IMSQRT = IM.RAIZ2 ## Devuelve la raíz cuadrada de un número complejo.
+IMSUB = IM.SUSTR ## Devuelve la diferencia entre dos números complejos.
+IMSUM = IM.SUM ## Devuelve la suma de números complejos.
+OCT2BIN = OCT.A.BIN ## Convierte un número octal en binario.
+OCT2DEC = OCT.A.DEC ## Convierte un número octal en decimal.
+OCT2HEX = OCT.A.HEX ## Convierte un número octal en hexadecimal.
+
+
+##
+## Financial functions Funciones financieras
+##
+ACCRINT = INT.ACUM ## Devuelve el interés acumulado de un valor bursátil con pagos de interés periódicos.
+ACCRINTM = INT.ACUM.V ## Devuelve el interés acumulado de un valor bursátil con pagos de interés al vencimiento.
+AMORDEGRC = AMORTIZ.PROGRE ## Devuelve la amortización de cada período contable mediante el uso de un coeficiente de amortización.
+AMORLINC = AMORTIZ.LIN ## Devuelve la amortización de cada uno de los períodos contables.
+COUPDAYBS = CUPON.DIAS.L1 ## Devuelve el número de días desde el principio del período de un cupón hasta la fecha de liquidación.
+COUPDAYS = CUPON.DIAS ## Devuelve el número de días del período (entre dos cupones) donde se encuentra la fecha de liquidación.
+COUPDAYSNC = CUPON.DIAS.L2 ## Devuelve el número de días desde la fecha de liquidación hasta la fecha del próximo cupón.
+COUPNCD = CUPON.FECHA.L2 ## Devuelve la fecha del próximo cupón después de la fecha de liquidación.
+COUPNUM = CUPON.NUM ## Devuelve el número de pagos de cupón entre la fecha de liquidación y la fecha de vencimiento.
+COUPPCD = CUPON.FECHA.L1 ## Devuelve la fecha de cupón anterior a la fecha de liquidación.
+CUMIPMT = PAGO.INT.ENTRE ## Devuelve el interés acumulado pagado entre dos períodos.
+CUMPRINC = PAGO.PRINC.ENTRE ## Devuelve el capital acumulado pagado de un préstamo entre dos períodos.
+DB = DB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización de saldo fijo.
+DDB = DDB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización por doble disminución de saldo u otro método que se especifique.
+DISC = TASA.DESC ## Devuelve la tasa de descuento de un valor bursátil.
+DOLLARDE = MONEDA.DEC ## Convierte una cotización de un valor bursátil expresada en forma fraccionaria en una cotización de un valor bursátil expresada en forma decimal.
+DOLLARFR = MONEDA.FRAC ## Convierte una cotización de un valor bursátil expresada en forma decimal en una cotización de un valor bursátil expresada en forma fraccionaria.
+DURATION = DURACION ## Devuelve la duración anual de un valor bursátil con pagos de interés periódico.
+EFFECT = INT.EFECTIVO ## Devuelve la tasa de interés anual efectiva.
+FV = VF ## Devuelve el valor futuro de una inversión.
+FVSCHEDULE = VF.PLAN ## Devuelve el valor futuro de un capital inicial después de aplicar una serie de tasas de interés compuesto.
+INTRATE = TASA.INT ## Devuelve la tasa de interés para la inversión total de un valor bursátil.
+IPMT = PAGOINT ## Devuelve el pago de intereses de una inversión durante un período determinado.
+IRR = TIR ## Devuelve la tasa interna de retorno para una serie de flujos de efectivo periódicos.
+ISPMT = INT.PAGO.DIR ## Calcula el interés pagado durante un período específico de una inversión.
+MDURATION = DURACION.MODIF ## Devuelve la duración de Macauley modificada de un valor bursátil con un valor nominal supuesto de 100 $.
+MIRR = TIRM ## Devuelve la tasa interna de retorno donde se financian flujos de efectivo positivos y negativos a tasas diferentes.
+NOMINAL = TASA.NOMINAL ## Devuelve la tasa nominal de interés anual.
+NPER = NPER ## Devuelve el número de períodos de una inversión.
+NPV = VNA ## Devuelve el valor neto actual de una inversión en función de una serie de flujos periódicos de efectivo y una tasa de descuento.
+ODDFPRICE = PRECIO.PER.IRREGULAR.1 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un primer período impar.
+ODDFYIELD = RENDTO.PER.IRREGULAR.1 ## Devuelve el rendimiento de un valor bursátil con un primer período impar.
+ODDLPRICE = PRECIO.PER.IRREGULAR.2 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un último período impar.
+ODDLYIELD = RENDTO.PER.IRREGULAR.2 ## Devuelve el rendimiento de un valor bursátil con un último período impar.
+PMT = PAGO ## Devuelve el pago periódico de una anualidad.
+PPMT = PAGOPRIN ## Devuelve el pago de capital de una inversión durante un período determinado.
+PRICE = PRECIO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga una tasa de interés periódico.
+PRICEDISC = PRECIO.DESCUENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con descuento.
+PRICEMAT = PRECIO.VENCIMIENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga interés a su vencimiento.
+PV = VALACT ## Devuelve el valor actual de una inversión.
+RATE = TASA ## Devuelve la tasa de interés por período de una anualidad.
+RECEIVED = CANTIDAD.RECIBIDA ## Devuelve la cantidad recibida al vencimiento de un valor bursátil completamente invertido.
+SLN = SLN ## Devuelve la amortización por método directo de un bien en un período dado.
+SYD = SYD ## Devuelve la amortización por suma de dígitos de los años de un bien durante un período especificado.
+TBILLEQ = LETRA.DE.TES.EQV.A.BONO ## Devuelve el rendimiento de un bono equivalente a una letra del Tesoro (de EE.UU.)
+TBILLPRICE = LETRA.DE.TES.PRECIO ## Devuelve el precio por un valor nominal de 100 $ de una letra del Tesoro (de EE.UU.)
+TBILLYIELD = LETRA.DE.TES.RENDTO ## Devuelve el rendimiento de una letra del Tesoro (de EE.UU.)
+VDB = DVS ## Devuelve la amortización de un bien durante un período específico o parcial a través del método de cálculo del saldo en disminución.
+XIRR = TIR.NO.PER ## Devuelve la tasa interna de retorno para un flujo de efectivo que no es necesariamente periódico.
+XNPV = VNA.NO.PER ## Devuelve el valor neto actual para un flujo de efectivo que no es necesariamente periódico.
+YIELD = RENDTO ## Devuelve el rendimiento de un valor bursátil que paga intereses periódicos.
+YIELDDISC = RENDTO.DESC ## Devuelve el rendimiento anual de un valor bursátil con descuento; por ejemplo, una letra del Tesoro (de EE.UU.)
+YIELDMAT = RENDTO.VENCTO ## Devuelve el rendimiento anual de un valor bursátil que paga intereses al vencimiento.
+
+
+##
+## Information functions Funciones de información
+##
+CELL = CELDA ## Devuelve información acerca del formato, la ubicación o el contenido de una celda.
+ERROR.TYPE = TIPO.DE.ERROR ## Devuelve un número que corresponde a un tipo de error.
+INFO = INFO ## Devuelve información acerca del entorno operativo en uso.
+ISBLANK = ESBLANCO ## Devuelve VERDADERO si el valor está en blanco.
+ISERR = ESERR ## Devuelve VERDADERO si el valor es cualquier valor de error excepto #N/A.
+ISERROR = ESERROR ## Devuelve VERDADERO si el valor es cualquier valor de error.
+ISEVEN = ES.PAR ## Devuelve VERDADERO si el número es par.
+ISLOGICAL = ESLOGICO ## Devuelve VERDADERO si el valor es un valor lógico.
+ISNA = ESNOD ## Devuelve VERDADERO si el valor es el valor de error #N/A.
+ISNONTEXT = ESNOTEXTO ## Devuelve VERDADERO si el valor no es texto.
+ISNUMBER = ESNUMERO ## Devuelve VERDADERO si el valor es un número.
+ISODD = ES.IMPAR ## Devuelve VERDADERO si el número es impar.
+ISREF = ESREF ## Devuelve VERDADERO si el valor es una referencia.
+ISTEXT = ESTEXTO ## Devuelve VERDADERO si el valor es texto.
+N = N ## Devuelve un valor convertido en un número.
+NA = ND ## Devuelve el valor de error #N/A.
+TYPE = TIPO ## Devuelve un número que indica el tipo de datos de un valor.
+
+
+##
+## Logical functions Funciones lógicas
+##
+AND = Y ## Devuelve VERDADERO si todos sus argumentos son VERDADERO.
+FALSE = FALSO ## Devuelve el valor lógico FALSO.
+IF = SI ## Especifica una prueba lógica que realizar.
+IFERROR = SI.ERROR ## Devuelve un valor que se especifica si una fórmula lo evalúa como un error; de lo contrario, devuelve el resultado de la fórmula.
+NOT = NO ## Invierte el valor lógico del argumento.
+OR = O ## Devuelve VERDADERO si cualquier argumento es VERDADERO.
+TRUE = VERDADERO ## Devuelve el valor lógico VERDADERO.
+
+
+##
+## Lookup and reference functions Funciones de búsqueda y referencia
+##
+ADDRESS = DIRECCION ## Devuelve una referencia como texto a una sola celda de una hoja de cálculo.
+AREAS = AREAS ## Devuelve el número de áreas de una referencia.
+CHOOSE = ELEGIR ## Elige un valor de una lista de valores.
+COLUMN = COLUMNA ## Devuelve el número de columna de una referencia.
+COLUMNS = COLUMNAS ## Devuelve el número de columnas de una referencia.
+HLOOKUP = BUSCARH ## Busca en la fila superior de una matriz y devuelve el valor de la celda indicada.
+HYPERLINK = HIPERVINCULO ## Crea un acceso directo o un salto que abre un documento almacenado en un servidor de red, en una intranet o en Internet.
+INDEX = INDICE ## Usa un índice para elegir un valor de una referencia o matriz.
+INDIRECT = INDIRECTO ## Devuelve una referencia indicada por un valor de texto.
+LOOKUP = BUSCAR ## Busca valores de un vector o una matriz.
+MATCH = COINCIDIR ## Busca valores de una referencia o matriz.
+OFFSET = DESREF ## Devuelve un desplazamiento de referencia respecto a una referencia dada.
+ROW = FILA ## Devuelve el número de fila de una referencia.
+ROWS = FILAS ## Devuelve el número de filas de una referencia.
+RTD = RDTR ## Recupera datos en tiempo real desde un programa compatible con la automatización COM (automatización: modo de trabajar con los objetos de una aplicación desde otra aplicación o herramienta de entorno. La automatización, antes denominada automatización OLE, es un estándar de la industria y una función del Modelo de objetos componentes (COM).).
+TRANSPOSE = TRANSPONER ## Devuelve la transposición de una matriz.
+VLOOKUP = BUSCARV ## Busca en la primera columna de una matriz y se mueve en horizontal por la fila para devolver el valor de una celda.
+
+
+##
+## Math and trigonometry functions Funciones matemáticas y trigonométricas
+##
+ABS = ABS ## Devuelve el valor absoluto de un número.
+ACOS = ACOS ## Devuelve el arcocoseno de un número.
+ACOSH = ACOSH ## Devuelve el coseno hiperbólico inverso de un número.
+ASIN = ASENO ## Devuelve el arcoseno de un número.
+ASINH = ASENOH ## Devuelve el seno hiperbólico inverso de un número.
+ATAN = ATAN ## Devuelve la arcotangente de un número.
+ATAN2 = ATAN2 ## Devuelve la arcotangente de las coordenadas "x" e "y".
+ATANH = ATANH ## Devuelve la tangente hiperbólica inversa de un número.
+CEILING = MULTIPLO.SUPERIOR ## Redondea un número al entero más próximo o al múltiplo significativo más cercano.
+COMBIN = COMBINAT ## Devuelve el número de combinaciones para un número determinado de objetos.
+COS = COS ## Devuelve el coseno de un número.
+COSH = COSH ## Devuelve el coseno hiperbólico de un número.
+DEGREES = GRADOS ## Convierte radianes en grados.
+EVEN = REDONDEA.PAR ## Redondea un número hasta el entero par más próximo.
+EXP = EXP ## Devuelve e elevado a la potencia de un número dado.
+FACT = FACT ## Devuelve el factorial de un número.
+FACTDOUBLE = FACT.DOBLE ## Devuelve el factorial doble de un número.
+FLOOR = MULTIPLO.INFERIOR ## Redondea un número hacia abajo, en dirección hacia cero.
+GCD = M.C.D ## Devuelve el máximo común divisor.
+INT = ENTERO ## Redondea un número hacia abajo hasta el entero más próximo.
+LCM = M.C.M ## Devuelve el mínimo común múltiplo.
+LN = LN ## Devuelve el logaritmo natural (neperiano) de un número.
+LOG = LOG ## Devuelve el logaritmo de un número en una base especificada.
+LOG10 = LOG10 ## Devuelve el logaritmo en base 10 de un número.
+MDETERM = MDETERM ## Devuelve la determinante matricial de una matriz.
+MINVERSE = MINVERSA ## Devuelve la matriz inversa de una matriz.
+MMULT = MMULT ## Devuelve el producto de matriz de dos matrices.
+MOD = RESIDUO ## Devuelve el resto de la división.
+MROUND = REDOND.MULT ## Devuelve un número redondeado al múltiplo deseado.
+MULTINOMIAL = MULTINOMIAL ## Devuelve el polinomio de un conjunto de números.
+ODD = REDONDEA.IMPAR ## Redondea un número hacia arriba hasta el entero impar más próximo.
+PI = PI ## Devuelve el valor de pi.
+POWER = POTENCIA ## Devuelve el resultado de elevar un número a una potencia.
+PRODUCT = PRODUCTO ## Multiplica sus argumentos.
+QUOTIENT = COCIENTE ## Devuelve la parte entera de una división.
+RADIANS = RADIANES ## Convierte grados en radianes.
+RAND = ALEATORIO ## Devuelve un número aleatorio entre 0 y 1.
+RANDBETWEEN = ALEATORIO.ENTRE ## Devuelve un número aleatorio entre los números que especifique.
+ROMAN = NUMERO.ROMANO ## Convierte un número arábigo en número romano, con formato de texto.
+ROUND = REDONDEAR ## Redondea un número al número de decimales especificado.
+ROUNDDOWN = REDONDEAR.MENOS ## Redondea un número hacia abajo, en dirección hacia cero.
+ROUNDUP = REDONDEAR.MAS ## Redondea un número hacia arriba, en dirección contraria a cero.
+SERIESSUM = SUMA.SERIES ## Devuelve la suma de una serie de potencias en función de la fórmula.
+SIGN = SIGNO ## Devuelve el signo de un número.
+SIN = SENO ## Devuelve el seno de un ángulo determinado.
+SINH = SENOH ## Devuelve el seno hiperbólico de un número.
+SQRT = RAIZ ## Devuelve la raíz cuadrada positiva de un número.
+SQRTPI = RAIZ2PI ## Devuelve la raíz cuadrada de un número multiplicado por PI (número * pi).
+SUBTOTAL = SUBTOTALES ## Devuelve un subtotal en una lista o base de datos.
+SUM = SUMA ## Suma sus argumentos.
+SUMIF = SUMAR.SI ## Suma las celdas especificadas que cumplen unos criterios determinados.
+SUMIFS = SUMAR.SI.CONJUNTO ## Suma las celdas de un rango que cumplen varios criterios.
+SUMPRODUCT = SUMAPRODUCTO ## Devuelve la suma de los productos de los correspondientes componentes de matriz.
+SUMSQ = SUMA.CUADRADOS ## Devuelve la suma de los cuadrados de los argumentos.
+SUMX2MY2 = SUMAX2MENOSY2 ## Devuelve la suma de la diferencia de los cuadrados de los valores correspondientes de dos matrices.
+SUMX2PY2 = SUMAX2MASY2 ## Devuelve la suma de la suma de los cuadrados de los valores correspondientes de dos matrices.
+SUMXMY2 = SUMAXMENOSY2 ## Devuelve la suma de los cuadrados de las diferencias de los valores correspondientes de dos matrices.
+TAN = TAN ## Devuelve la tangente de un número.
+TANH = TANH ## Devuelve la tangente hiperbólica de un número.
+TRUNC = TRUNCAR ## Trunca un número a un entero.
+
+
+##
+## Statistical functions Funciones estadísticas
+##
+AVEDEV = DESVPROM ## Devuelve el promedio de las desviaciones absolutas de la media de los puntos de datos.
+AVERAGE = PROMEDIO ## Devuelve el promedio de sus argumentos.
+AVERAGEA = PROMEDIOA ## Devuelve el promedio de sus argumentos, incluidos números, texto y valores lógicos.
+AVERAGEIF = PROMEDIO.SI ## Devuelve el promedio (media aritmética) de todas las celdas de un rango que cumplen unos criterios determinados.
+AVERAGEIFS = PROMEDIO.SI.CONJUNTO ## Devuelve el promedio (media aritmética) de todas las celdas que cumplen múltiples criterios.
+BETADIST = DISTR.BETA ## Devuelve la función de distribución beta acumulativa.
+BETAINV = DISTR.BETA.INV ## Devuelve la función inversa de la función de distribución acumulativa de una distribución beta especificada.
+BINOMDIST = DISTR.BINOM ## Devuelve la probabilidad de una variable aleatoria discreta siguiendo una distribución binomial.
+CHIDIST = DISTR.CHI ## Devuelve la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola.
+CHIINV = PRUEBA.CHI.INV ## Devuelve la función inversa de la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola.
+CHITEST = PRUEBA.CHI ## Devuelve la prueba de independencia.
+CONFIDENCE = INTERVALO.CONFIANZA ## Devuelve el intervalo de confianza de la media de una población.
+CORREL = COEF.DE.CORREL ## Devuelve el coeficiente de correlación entre dos conjuntos de datos.
+COUNT = CONTAR ## Cuenta cuántos números hay en la lista de argumentos.
+COUNTA = CONTARA ## Cuenta cuántos valores hay en la lista de argumentos.
+COUNTBLANK = CONTAR.BLANCO ## Cuenta el número de celdas en blanco de un rango.
+COUNTIF = CONTAR.SI ## Cuenta el número de celdas, dentro del rango, que cumplen el criterio especificado.
+COUNTIFS = CONTAR.SI.CONJUNTO ## Cuenta el número de celdas, dentro del rango, que cumplen varios criterios.
+COVAR = COVAR ## Devuelve la covarianza, que es el promedio de los productos de las desviaciones para cada pareja de puntos de datos.
+CRITBINOM = BINOM.CRIT ## Devuelve el menor valor cuya distribución binomial acumulativa es menor o igual a un valor de criterio.
+DEVSQ = DESVIA2 ## Devuelve la suma de los cuadrados de las desviaciones.
+EXPONDIST = DISTR.EXP ## Devuelve la distribución exponencial.
+FDIST = DISTR.F ## Devuelve la distribución de probabilidad F.
+FINV = DISTR.F.INV ## Devuelve la función inversa de la distribución de probabilidad F.
+FISHER = FISHER ## Devuelve la transformación Fisher.
+FISHERINV = PRUEBA.FISHER.INV ## Devuelve la función inversa de la transformación Fisher.
+FORECAST = PRONOSTICO ## Devuelve un valor en una tendencia lineal.
+FREQUENCY = FRECUENCIA ## Devuelve una distribución de frecuencia como una matriz vertical.
+FTEST = PRUEBA.F ## Devuelve el resultado de una prueba F.
+GAMMADIST = DISTR.GAMMA ## Devuelve la distribución gamma.
+GAMMAINV = DISTR.GAMMA.INV ## Devuelve la función inversa de la distribución gamma acumulativa.
+GAMMALN = GAMMA.LN ## Devuelve el logaritmo natural de la función gamma, G(x).
+GEOMEAN = MEDIA.GEOM ## Devuelve la media geométrica.
+GROWTH = CRECIMIENTO ## Devuelve valores en una tendencia exponencial.
+HARMEAN = MEDIA.ARMO ## Devuelve la media armónica.
+HYPGEOMDIST = DISTR.HIPERGEOM ## Devuelve la distribución hipergeométrica.
+INTERCEPT = INTERSECCION.EJE ## Devuelve la intersección de la línea de regresión lineal.
+KURT = CURTOSIS ## Devuelve la curtosis de un conjunto de datos.
+LARGE = K.ESIMO.MAYOR ## Devuelve el k-ésimo mayor valor de un conjunto de datos.
+LINEST = ESTIMACION.LINEAL ## Devuelve los parámetros de una tendencia lineal.
+LOGEST = ESTIMACION.LOGARITMICA ## Devuelve los parámetros de una tendencia exponencial.
+LOGINV = DISTR.LOG.INV ## Devuelve la función inversa de la distribución logarítmico-normal.
+LOGNORMDIST = DISTR.LOG.NORM ## Devuelve la distribución logarítmico-normal acumulativa.
+MAX = MAX ## Devuelve el valor máximo de una lista de argumentos.
+MAXA = MAXA ## Devuelve el valor máximo de una lista de argumentos, incluidos números, texto y valores lógicos.
+MEDIAN = MEDIANA ## Devuelve la mediana de los números dados.
+MIN = MIN ## Devuelve el valor mínimo de una lista de argumentos.
+MINA = MINA ## Devuelve el valor mínimo de una lista de argumentos, incluidos números, texto y valores lógicos.
+MODE = MODA ## Devuelve el valor más común de un conjunto de datos.
+NEGBINOMDIST = NEGBINOMDIST ## Devuelve la distribución binomial negativa.
+NORMDIST = DISTR.NORM ## Devuelve la distribución normal acumulativa.
+NORMINV = DISTR.NORM.INV ## Devuelve la función inversa de la distribución normal acumulativa.
+NORMSDIST = DISTR.NORM.ESTAND ## Devuelve la distribución normal estándar acumulativa.
+NORMSINV = DISTR.NORM.ESTAND.INV ## Devuelve la función inversa de la distribución normal estándar acumulativa.
+PEARSON = PEARSON ## Devuelve el coeficiente de momento de correlación de producto Pearson.
+PERCENTILE = PERCENTIL ## Devuelve el k-ésimo percentil de los valores de un rango.
+PERCENTRANK = RANGO.PERCENTIL ## Devuelve el rango porcentual de un valor de un conjunto de datos.
+PERMUT = PERMUTACIONES ## Devuelve el número de permutaciones de un número determinado de objetos.
+POISSON = POISSON ## Devuelve la distribución de Poisson.
+PROB = PROBABILIDAD ## Devuelve la probabilidad de que los valores de un rango se encuentren entre dos límites.
+QUARTILE = CUARTIL ## Devuelve el cuartil de un conjunto de datos.
+RANK = JERARQUIA ## Devuelve la jerarquía de un número en una lista de números.
+RSQ = COEFICIENTE.R2 ## Devuelve el cuadrado del coeficiente de momento de correlación de producto Pearson.
+SKEW = COEFICIENTE.ASIMETRIA ## Devuelve la asimetría de una distribución.
+SLOPE = PENDIENTE ## Devuelve la pendiente de la línea de regresión lineal.
+SMALL = K.ESIMO.MENOR ## Devuelve el k-ésimo menor valor de un conjunto de datos.
+STANDARDIZE = NORMALIZACION ## Devuelve un valor normalizado.
+STDEV = DESVEST ## Calcula la desviación estándar a partir de una muestra.
+STDEVA = DESVESTA ## Calcula la desviación estándar a partir de una muestra, incluidos números, texto y valores lógicos.
+STDEVP = DESVESTP ## Calcula la desviación estándar en función de toda la población.
+STDEVPA = DESVESTPA ## Calcula la desviación estándar en función de toda la población, incluidos números, texto y valores lógicos.
+STEYX = ERROR.TIPICO.XY ## Devuelve el error estándar del valor de "y" previsto para cada "x" de la regresión.
+TDIST = DISTR.T ## Devuelve la distribución de t de Student.
+TINV = DISTR.T.INV ## Devuelve la función inversa de la distribución de t de Student.
+TREND = TENDENCIA ## Devuelve valores en una tendencia lineal.
+TRIMMEAN = MEDIA.ACOTADA ## Devuelve la media del interior de un conjunto de datos.
+TTEST = PRUEBA.T ## Devuelve la probabilidad asociada a una prueba t de Student.
+VAR = VAR ## Calcula la varianza en función de una muestra.
+VARA = VARA ## Calcula la varianza en función de una muestra, incluidos números, texto y valores lógicos.
+VARP = VARP ## Calcula la varianza en función de toda la población.
+VARPA = VARPA ## Calcula la varianza en función de toda la población, incluidos números, texto y valores lógicos.
+WEIBULL = DIST.WEIBULL ## Devuelve la distribución de Weibull.
+ZTEST = PRUEBA.Z ## Devuelve el valor de una probabilidad de una cola de una prueba z.
+
+
+##
+## Text functions Funciones de texto
+##
+ASC = ASC ## Convierte las letras inglesas o katakana de ancho completo (de dos bytes) dentro de una cadena de caracteres en caracteres de ancho medio (de un byte).
+BAHTTEXT = TEXTOBAHT ## Convierte un número en texto, con el formato de moneda ß (Baht).
+CHAR = CARACTER ## Devuelve el carácter especificado por el número de código.
+CLEAN = LIMPIAR ## Quita del texto todos los caracteres no imprimibles.
+CODE = CODIGO ## Devuelve un código numérico del primer carácter de una cadena de texto.
+CONCATENATE = CONCATENAR ## Concatena varios elementos de texto en uno solo.
+DOLLAR = MONEDA ## Convierte un número en texto, con el formato de moneda $ (dólar).
+EXACT = IGUAL ## Comprueba si dos valores de texto son idénticos.
+FIND = ENCONTRAR ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas).
+FINDB = ENCONTRARB ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas).
+FIXED = DECIMAL ## Da formato a un número como texto con un número fijo de decimales.
+JIS = JIS ## Convierte las letras inglesas o katakana de ancho medio (de un byte) dentro de una cadena de caracteres en caracteres de ancho completo (de dos bytes).
+LEFT = IZQUIERDA ## Devuelve los caracteres del lado izquierdo de un valor de texto.
+LEFTB = IZQUIERDAB ## Devuelve los caracteres del lado izquierdo de un valor de texto.
+LEN = LARGO ## Devuelve el número de caracteres de una cadena de texto.
+LENB = LARGOB ## Devuelve el número de caracteres de una cadena de texto.
+LOWER = MINUSC ## Pone el texto en minúsculas.
+MID = EXTRAE ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique.
+MIDB = EXTRAEB ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique.
+PHONETIC = FONETICO ## Extrae los caracteres fonéticos (furigana) de una cadena de texto.
+PROPER = NOMPROPIO ## Pone en mayúscula la primera letra de cada palabra de un valor de texto.
+REPLACE = REEMPLAZAR ## Reemplaza caracteres de texto.
+REPLACEB = REEMPLAZARB ## Reemplaza caracteres de texto.
+REPT = REPETIR ## Repite el texto un número determinado de veces.
+RIGHT = DERECHA ## Devuelve los caracteres del lado derecho de un valor de texto.
+RIGHTB = DERECHAB ## Devuelve los caracteres del lado derecho de un valor de texto.
+SEARCH = HALLAR ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas).
+SEARCHB = HALLARB ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas).
+SUBSTITUTE = SUSTITUIR ## Sustituye texto nuevo por texto antiguo en una cadena de texto.
+T = T ## Convierte sus argumentos a texto.
+TEXT = TEXTO ## Da formato a un número y lo convierte en texto.
+TRIM = ESPACIOS ## Quita los espacios del texto.
+UPPER = MAYUSC ## Pone el texto en mayúsculas.
+VALUE = VALOR ## Convierte un argumento de texto en un número.
diff --git a/PHPExcel/locale/fi/config b/PHPExcel/locale/fi/config
new file mode 100644
index 0000000..380f397
--- /dev/null
+++ b/PHPExcel/locale/fi/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = $ # Symbol not known, should it be a € (Euro)?
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #TYHJÄ!
+DIV0 = #JAKO/0!
+VALUE = #ARVO!
+REF = #VIITTAUS!
+NAME = #NIMI?
+NUM = #LUKU!
+NA = #PUUTTUU
diff --git a/PHPExcel/locale/fi/functions b/PHPExcel/locale/fi/functions
new file mode 100644
index 0000000..bf60bec
--- /dev/null
+++ b/PHPExcel/locale/fi/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Apuohjelma- ja automaatiofunktiot
+##
+GETPIVOTDATA = NOUDA.PIVOT.TIEDOT ## Palauttaa pivot-taulukkoraporttiin tallennettuja tietoja.
+
+
+##
+## Cube functions Kuutiofunktiot
+##
+CUBEKPIMEMBER = KUUTIOKPIJÄSEN ## Palauttaa suorituskykyilmaisimen (KPI) nimen, ominaisuuden sekä mitan ja näyttää nimen sekä ominaisuuden solussa. KPI on mitattavissa oleva suure, kuten kuukauden bruttotuotto tai vuosineljänneksen työntekijäkohtainen liikevaihto, joiden avulla tarkkaillaan organisaation suorituskykyä.
+CUBEMEMBER = KUUTIONJÄSEN ## Palauttaa kuutiohierarkian jäsenen tai monikon. Tällä funktiolla voit tarkistaa, että jäsen tai monikko on olemassa kuutiossa.
+CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS ## Palauttaa kuution jäsenominaisuuden arvon. Tällä funktiolla voit tarkistaa, että nimi on olemassa kuutiossa, ja palauttaa tämän jäsenen määritetyn ominaisuuden.
+CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN ## Palauttaa joukon n:nnen jäsenen. Tällä funktiolla voit palauttaa joukosta elementtejä, kuten parhaan myyjän tai 10 parasta opiskelijaa.
+CUBESET = KUUTIOJOUKKO ## Määrittää lasketun jäsen- tai monikkojoukon lähettämällä joukon lausekkeita palvelimessa olevalle kuutiolle. Palvelin luo joukon ja palauttaa sen Microsoft Office Excelille.
+CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ ## Palauttaa joukon kohteiden määrän.
+CUBEVALUE = KUUTIONARVO ## Palauttaa koostetun arvon kuutiosta.
+
+
+##
+## Database functions Tietokantafunktiot
+##
+DAVERAGE = TKESKIARVO ## Palauttaa valittujen tietokantamerkintöjen keskiarvon.
+DCOUNT = TLASKE ## Laskee tietokannan lukuja sisältävien solujen määrän.
+DCOUNTA = TLASKEA ## Laskee tietokannan tietoja sisältävien solujen määrän.
+DGET = TNOUDA ## Hakee määritettyjä ehtoja vastaavan tietueen tietokannasta.
+DMAX = TMAKS ## Palauttaa suurimman arvon tietokannasta valittujen arvojen joukosta.
+DMIN = TMIN ## Palauttaa pienimmän arvon tietokannasta valittujen arvojen joukosta.
+DPRODUCT = TTULO ## Kertoo määritetyn ehdon täyttävien tietokannan tietueiden tietyssä kentässä olevat arvot.
+DSTDEV = TKESKIHAJONTA ## Laskee keskihajonnan tietokannasta valituista arvoista muodostuvan otoksen perusteella.
+DSTDEVP = TKESKIHAJONTAP ## Laskee keskihajonnan tietokannasta valittujen arvojen koko populaation perusteella.
+DSUM = TSUMMA ## Lisää luvut määritetyn ehdon täyttävien tietokannan tietueiden kenttäsarakkeeseen.
+DVAR = TVARIANSSI ## Laskee varianssin tietokannasta valittujen arvojen otoksen perusteella.
+DVARP = TVARIANSSIP ## Laskee varianssin tietokannasta valittujen arvojen koko populaation perusteella.
+
+
+##
+## Date and time functions Päivämäärä- ja aikafunktiot
+##
+DATE = PÄIVÄYS ## Palauttaa annetun päivämäärän järjestysluvun.
+DATEVALUE = PÄIVÄYSARVO ## Muuntaa tekstimuodossa olevan päivämäärän järjestysluvuksi.
+DAY = PÄIVÄ ## Muuntaa järjestysluvun kuukauden päiväksi.
+DAYS360 = PÄIVÄT360 ## Laskee kahden päivämäärän välisten päivien määrän käyttäen perustana 360-päiväistä vuotta.
+EDATE = PÄIVÄ.KUUKAUSI ## Palauttaa järjestyslukuna päivämäärän, joka poikkeaa aloituspäivän päivämäärästä annetun kuukausimäärän verran joko eteen- tai taaksepäin.
+EOMONTH = KUUKAUSI.LOPPU ## Palauttaa järjestyslukuna sen kuukauden viimeisen päivämäärän, joka poikkeaa annetun kuukausimäärän verran eteen- tai taaksepäin.
+HOUR = TUNNIT ## Muuntaa järjestysluvun tunneiksi.
+MINUTE = MINUUTIT ## Muuntaa järjestysluvun minuuteiksi.
+MONTH = KUUKAUSI ## Muuntaa järjestysluvun kuukausiksi.
+NETWORKDAYS = TYÖPÄIVÄT ## Palauttaa kahden päivämäärän välissä olevien täysien työpäivien määrän.
+NOW = NYT ## Palauttaa kuluvan päivämäärän ja ajan järjestysnumeron.
+SECOND = SEKUNNIT ## Muuntaa järjestysluvun sekunneiksi.
+TIME = AIKA ## Palauttaa annetun kellonajan järjestysluvun.
+TIMEVALUE = AIKA_ARVO ## Muuntaa tekstimuodossa olevan kellonajan järjestysluvuksi.
+TODAY = TÄMÄ.PÄIVÄ ## Palauttaa kuluvan päivän päivämäärän järjestysluvun.
+WEEKDAY = VIIKONPÄIVÄ ## Muuntaa järjestysluvun viikonpäiväksi.
+WEEKNUM = VIIKKO.NRO ## Muuntaa järjestysluvun luvuksi, joka ilmaisee viikon järjestysluvun vuoden alusta laskettuna.
+WORKDAY = TYÖPÄIVÄ ## Palauttaa järjestysluvun päivämäärälle, joka sijaitsee annettujen työpäivien verran eteen tai taaksepäin.
+YEAR = VUOSI ## Muuntaa järjestysluvun vuosiksi.
+YEARFRAC = VUOSI.OSA ## Palauttaa määritettyjen päivämäärien (aloituspäivä ja lopetuspäivä) välisen osan vuodesta.
+
+
+##
+## Engineering functions Tekniset funktiot
+##
+BESSELI = BESSELI ## Palauttaa muunnetun Bessel-funktion In(x).
+BESSELJ = BESSELJ ## Palauttaa Bessel-funktion Jn(x).
+BESSELK = BESSELK ## Palauttaa muunnetun Bessel-funktion Kn(x).
+BESSELY = BESSELY ## Palauttaa Bessel-funktion Yn(x).
+BIN2DEC = BINDES ## Muuntaa binaariluvun desimaaliluvuksi.
+BIN2HEX = BINHEKSA ## Muuntaa binaariluvun heksadesimaaliluvuksi.
+BIN2OCT = BINOKT ## Muuntaa binaariluvun oktaaliluvuksi.
+COMPLEX = KOMPLEKSI ## Muuntaa reaali- ja imaginaariosien kertoimet kompleksiluvuksi.
+CONVERT = MUUNNA ## Muuntaa luvun toisen mittajärjestelmän mukaiseksi.
+DEC2BIN = DESBIN ## Muuntaa desimaaliluvun binaariluvuksi.
+DEC2HEX = DESHEKSA ## Muuntaa kymmenjärjestelmän luvun heksadesimaaliluvuksi.
+DEC2OCT = DESOKT ## Muuntaa kymmenjärjestelmän luvun oktaaliluvuksi.
+DELTA = SAMA.ARVO ## Tarkistaa, ovatko kaksi arvoa yhtä suuria.
+ERF = VIRHEFUNKTIO ## Palauttaa virhefunktion.
+ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ## Palauttaa komplementtivirhefunktion.
+GESTEP = RAJA ## Testaa, onko luku suurempi kuin kynnysarvo.
+HEX2BIN = HEKSABIN ## Muuntaa heksadesimaaliluvun binaariluvuksi.
+HEX2DEC = HEKSADES ## Muuntaa heksadesimaaliluvun desimaaliluvuksi.
+HEX2OCT = HEKSAOKT ## Muuntaa heksadesimaaliluvun oktaaliluvuksi.
+IMABS = KOMPLEKSI.ITSEISARVO ## Palauttaa kompleksiluvun itseisarvon (moduluksen).
+IMAGINARY = KOMPLEKSI.IMAG ## Palauttaa kompleksiluvun imaginaariosan kertoimen.
+IMARGUMENT = KOMPLEKSI.ARG ## Palauttaa theeta-argumentin, joka on radiaaneina annettu kulma.
+IMCONJUGATE = KOMPLEKSI.KONJ ## Palauttaa kompleksiluvun konjugaattiluvun.
+IMCOS = KOMPLEKSI.COS ## Palauttaa kompleksiluvun kosinin.
+IMDIV = KOMPLEKSI.OSAM ## Palauttaa kahden kompleksiluvun osamäärän.
+IMEXP = KOMPLEKSI.EKSP ## Palauttaa kompleksiluvun eksponentin.
+IMLN = KOMPLEKSI.LN ## Palauttaa kompleksiluvun luonnollisen logaritmin.
+IMLOG10 = KOMPLEKSI.LOG10 ## Palauttaa kompleksiluvun kymmenkantaisen logaritmin.
+IMLOG2 = KOMPLEKSI.LOG2 ## Palauttaa kompleksiluvun kaksikantaisen logaritmin.
+IMPOWER = KOMPLEKSI.POT ## Palauttaa kokonaislukupotenssiin korotetun kompleksiluvun.
+IMPRODUCT = KOMPLEKSI.TULO ## Palauttaa kompleksilukujen tulon.
+IMREAL = KOMPLEKSI.REAALI ## Palauttaa kompleksiluvun reaaliosan kertoimen.
+IMSIN = KOMPLEKSI.SIN ## Palauttaa kompleksiluvun sinin.
+IMSQRT = KOMPLEKSI.NELIÖJ ## Palauttaa kompleksiluvun neliöjuuren.
+IMSUB = KOMPLEKSI.EROTUS ## Palauttaa kahden kompleksiluvun erotuksen.
+IMSUM = KOMPLEKSI.SUM ## Palauttaa kompleksilukujen summan.
+OCT2BIN = OKTBIN ## Muuntaa oktaaliluvun binaariluvuksi.
+OCT2DEC = OKTDES ## Muuntaa oktaaliluvun desimaaliluvuksi.
+OCT2HEX = OKTHEKSA ## Muuntaa oktaaliluvun heksadesimaaliluvuksi.
+
+
+##
+## Financial functions Rahoitusfunktiot
+##
+ACCRINT = KERTYNYT.KORKO ## Laskee arvopaperille kertyneen koron, kun korko kertyy säännöllisin väliajoin.
+ACCRINTM = KERTYNYT.KORKO.LOPUSSA ## Laskee arvopaperille kertyneen koron, kun korko maksetaan eräpäivänä.
+AMORDEGRC = AMORDEGRC ## Laskee kunkin laskentakauden poiston poistokerrointa käyttämällä.
+AMORLINC = AMORLINC ## Palauttaa kunkin laskentakauden poiston.
+COUPDAYBS = KORKOPÄIVÄT.ALUSTA ## Palauttaa koronmaksukauden aloituspäivän ja tilityspäivän välisen ajanjakson päivien määrän.
+COUPDAYS = KORKOPÄIVÄT ## Palauttaa päivien määrän koronmaksukaudelta, johon tilityspäivä kuuluu.
+COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA ## Palauttaa tilityspäivän ja seuraavan koronmaksupäivän välisen ajanjakson päivien määrän.
+COUPNCD = KORKOMAKSU.SEURAAVA ## Palauttaa tilityspäivän jälkeisen seuraavan koronmaksupäivän.
+COUPNUM = KORKOPÄIVÄJAKSOT ## Palauttaa arvopaperin ostopäivän ja erääntymispäivän välisten koronmaksupäivien määrän.
+COUPPCD = KORKOPÄIVÄ.EDELLINEN ## Palauttaa tilityspäivää edeltävän koronmaksupäivän.
+CUMIPMT = MAKSETTU.KORKO ## Palauttaa kahden jakson välisenä aikana kertyneen koron.
+CUMPRINC = MAKSETTU.LYHENNYS ## Palauttaa lainalle kahden jakson välisenä aikana kertyneen lyhennyksen.
+DB = DB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan.
+DDB = DDB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DDB-menetelmän (Double-Declining Balance) tai jonkin muun määrittämäsi menetelmän mukaan.
+DISC = DISKONTTOKORKO ## Palauttaa arvopaperin diskonttokoron.
+DOLLARDE = VALUUTTA.DES ## Muuntaa murtolukuna ilmoitetun valuuttamäärän desimaaliluvuksi.
+DOLLARFR = VALUUTTA.MURTO ## Muuntaa desimaalilukuna ilmaistun valuuttamäärän murtoluvuksi.
+DURATION = KESTO ## Palauttaa keston arvopaperille, jonka koronmaksu tapahtuu säännöllisesti.
+EFFECT = KORKO.EFEKT ## Palauttaa todellisen vuosikoron.
+FV = TULEVA.ARVO ## Palauttaa sijoituksen tulevan arvon.
+FVSCHEDULE = TULEVA.ARVO.ERIKORKO ## Palauttaa pääoman tulevan arvon, kun pääomalle on kertynyt korkoa vaihtelevasti.
+INTRATE = KORKO.ARVOPAPERI ## Palauttaa arvopaperin korkokannan täysin sijoitetulle arvopaperille.
+IPMT = IPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona kertyvän koron.
+IRR = SISÄINEN.KORKO ## Laskee sisäisen korkokannan kassavirrasta muodostuvalle sarjalle.
+ISPMT = ONMAKSU ## Laskee sijoituksen maksetun koron tietyllä jaksolla.
+MDURATION = KESTO.MUUNN ## Palauttaa muunnetun Macauley-keston arvopaperille, jonka oletettu nimellisarvo on 100 euroa.
+MIRR = MSISÄINEN ## Palauttaa sisäisen korkokannan, kun positiivisten ja negatiivisten kassavirtojen rahoituskorko on erilainen.
+NOMINAL = KORKO.VUOSI ## Palauttaa vuosittaisen nimelliskoron.
+NPER = NJAKSO ## Palauttaa sijoituksen jaksojen määrän.
+NPV = NNA ## Palauttaa sijoituksen nykyarvon toistuvista kassavirroista muodostuvan sarjan ja diskonttokoron perusteella.
+ODDFPRICE = PARITON.ENS.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa ensimmäinen jakso on pariton.
+ODDFYIELD = PARITON.ENS.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa ensimmäinen jakso on pariton.
+ODDLPRICE = PARITON.VIIM.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa viimeinen jakso on pariton.
+ODDLYIELD = PARITON.VIIM.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa viimeinen jakso on pariton.
+PMT = MAKSU ## Palauttaa annuiteetin kausittaisen maksuerän.
+PPMT = PPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona maksettavan lyhennyksen.
+PRICE = HINTA ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan säännöllisin väliajoin.
+PRICEDISC = HINTA.DISK ## Palauttaa diskontatun arvopaperin hinnan 100 euron nimellisarvoa kohden.
+PRICEMAT = HINTA.LUNASTUS ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan erääntymispäivänä.
+PV = NA ## Palauttaa sijoituksen nykyarvon.
+RATE = KORKO ## Palauttaa annuiteetin kausittaisen korkokannan.
+RECEIVED = SAATU.HINTA ## Palauttaa arvopaperin tuoton erääntymispäivänä kokonaan maksetulle sijoitukselle.
+SLN = STP ## Palauttaa sijoituksen tasapoiston yhdeltä jaksolta.
+SYD = VUOSIPOISTO ## Palauttaa sijoituksen vuosipoiston annettuna kautena amerikkalaisen SYD-menetelmän (Sum-of-Year's Digits) avulla.
+TBILLEQ = OBLIG.TUOTTOPROS ## Palauttaa valtion obligaation tuoton vastaavana joukkovelkakirjan tuottona.
+TBILLPRICE = OBLIG.HINTA ## Palauttaa obligaation hinnan 100 euron nimellisarvoa kohden.
+TBILLYIELD = OBLIG.TUOTTO ## Palauttaa obligaation tuoton.
+VDB = VDB ## Palauttaa annetun kauden tai kauden osan kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan.
+XIRR = SISÄINEN.KORKO.JAKSOTON ## Palauttaa sisäisen korkokannan kassavirtojen sarjoille, jotka eivät välttämättä ole säännöllisiä.
+XNPV = NNA.JAKSOTON ## Palauttaa nettonykyarvon kassavirtasarjalle, joka ei välttämättä ole kausittainen.
+YIELD = TUOTTO ## Palauttaa tuoton arvopaperille, jonka korko maksetaan säännöllisin väliajoin.
+YIELDDISC = TUOTTO.DISK ## Palauttaa diskontatun arvopaperin, kuten obligaation, vuosittaisen tuoton.
+YIELDMAT = TUOTTO.ERÄP ## Palauttaa erääntymispäivänään korkoa tuottavan arvopaperin vuosittaisen tuoton.
+
+
+##
+## Information functions Erikoisfunktiot
+##
+CELL = SOLU ## Palauttaa tietoja solun muotoilusta, sijainnista ja sisällöstä.
+ERROR.TYPE = VIRHEEN.LAJI ## Palauttaa virhetyyppiä vastaavan luvun.
+INFO = KUVAUS ## Palauttaa tietoja nykyisestä käyttöympäristöstä.
+ISBLANK = ONTYHJÄ ## Palauttaa arvon TOSI, jos arvo on tyhjä.
+ISERR = ONVIRH ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo paitsi arvo #PUUTTUU!.
+ISERROR = ONVIRHE ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo.
+ISEVEN = ONPARILLINEN ## Palauttaa arvon TOSI, jos arvo on parillinen.
+ISLOGICAL = ONTOTUUS ## Palauttaa arvon TOSI, jos arvo on mikä tahansa looginen arvo.
+ISNA = ONPUUTTUU ## Palauttaa arvon TOSI, jos virhearvo on #PUUTTUU!.
+ISNONTEXT = ONEI_TEKSTI ## Palauttaa arvon TOSI, jos arvo ei ole teksti.
+ISNUMBER = ONLUKU ## Palauttaa arvon TOSI, jos arvo on luku.
+ISODD = ONPARITON ## Palauttaa arvon TOSI, jos arvo on pariton.
+ISREF = ONVIITT ## Palauttaa arvon TOSI, jos arvo on viittaus.
+ISTEXT = ONTEKSTI ## Palauttaa arvon TOSI, jos arvo on teksti.
+N = N ## Palauttaa arvon luvuksi muunnettuna.
+NA = PUUTTUU ## Palauttaa virhearvon #PUUTTUU!.
+TYPE = TYYPPI ## Palauttaa luvun, joka ilmaisee arvon tietotyypin.
+
+
+##
+## Logical functions Loogiset funktiot
+##
+AND = JA ## Palauttaa arvon TOSI, jos kaikkien argumenttien arvo on TOSI.
+FALSE = EPÄTOSI ## Palauttaa totuusarvon EPÄTOSI.
+IF = JOS ## Määrittää suoritettavan loogisen testin.
+IFERROR = JOSVIRHE ## Palauttaa määrittämäsi arvon, jos kaavan tulos on virhe; muussa tapauksessa palauttaa kaavan tuloksen.
+NOT = EI ## Kääntää argumentin loogisen arvon.
+OR = TAI ## Palauttaa arvon TOSI, jos minkä tahansa argumentin arvo on TOSI.
+TRUE = TOSI ## Palauttaa totuusarvon TOSI.
+
+
+##
+## Lookup and reference functions Haku- ja viitefunktiot
+##
+ADDRESS = OSOITE ## Palauttaa laskentataulukon soluun osoittavan viittauksen tekstinä.
+AREAS = ALUEET ## Palauttaa viittauksessa olevien alueiden määrän.
+CHOOSE = VALITSE.INDEKSI ## Valitsee arvon arvoluettelosta.
+COLUMN = SARAKE ## Palauttaa viittauksen sarakenumeron.
+COLUMNS = SARAKKEET ## Palauttaa viittauksessa olevien sarakkeiden määrän.
+HLOOKUP = VHAKU ## Suorittaa haun matriisin ylimmältä riviltä ja palauttaa määritetyn solun arvon.
+HYPERLINK = HYPERLINKKI ## Luo pikakuvakkeen tai tekstin, joka avaa verkkopalvelimeen, intranetiin tai Internetiin tallennetun tiedoston.
+INDEX = INDEKSI ## Valitsee arvon viittauksesta tai matriisista indeksin mukaan.
+INDIRECT = EPÄSUORA ## Palauttaa tekstiarvona ilmaistun viittauksen.
+LOOKUP = HAKU ## Etsii arvoja vektorista tai matriisista.
+MATCH = VASTINE ## Etsii arvoja viittauksesta tai matriisista.
+OFFSET = SIIRTYMÄ ## Palauttaa annetun viittauksen siirtymän.
+ROW = RIVI ## Palauttaa viittauksen rivinumeron.
+ROWS = RIVIT ## Palauttaa viittauksessa olevien rivien määrän.
+RTD = RTD ## Noutaa COM-automaatiota (automaatio: Tapa käsitellä sovelluksen objekteja toisesta sovelluksesta tai kehitystyökalusta. Automaatio, jota aiemmin kutsuttiin OLE-automaatioksi, on teollisuusstandardi ja COM-mallin (Component Object Model) ominaisuus.) tukevasta ohjelmasta reaaliaikaisia tietoja.
+TRANSPOSE = TRANSPONOI ## Palauttaa matriisin käänteismatriisin.
+VLOOKUP = PHAKU ## Suorittaa haun matriisin ensimmäisestä sarakkeesta ja palauttaa rivillä olevan solun arvon.
+
+
+##
+## Math and trigonometry functions Matemaattiset ja trigonometriset funktiot
+##
+ABS = ITSEISARVO ## Palauttaa luvun itseisarvon.
+ACOS = ACOS ## Palauttaa luvun arkuskosinin.
+ACOSH = ACOSH ## Palauttaa luvun käänteisen hyperbolisen kosinin.
+ASIN = ASIN ## Palauttaa luvun arkussinin.
+ASINH = ASINH ## Palauttaa luvun käänteisen hyperbolisen sinin.
+ATAN = ATAN ## Palauttaa luvun arkustangentin.
+ATAN2 = ATAN2 ## Palauttaa arkustangentin x- ja y-koordinaatin perusteella.
+ATANH = ATANH ## Palauttaa luvun käänteisen hyperbolisen tangentin.
+CEILING = PYÖRISTÄ.KERR.YLÖS ## Pyöristää luvun lähimpään kokonaislukuun tai tarkkuusargumentin lähimpään kerrannaiseen.
+COMBIN = KOMBINAATIO ## Palauttaa mahdollisten kombinaatioiden määrän annetulle objektien määrälle.
+COS = COS ## Palauttaa luvun kosinin.
+COSH = COSH ## Palauttaa luvun hyperbolisen kosinin.
+DEGREES = ASTEET ## Muuntaa radiaanit asteiksi.
+EVEN = PARILLINEN ## Pyöristää luvun ylöspäin lähimpään parilliseen kokonaislukuun.
+EXP = EKSPONENTTI ## Palauttaa e:n korotettuna annetun luvun osoittamaan potenssiin.
+FACT = KERTOMA ## Palauttaa luvun kertoman.
+FACTDOUBLE = KERTOMA.OSA ## Palauttaa luvun osakertoman.
+FLOOR = PYÖRISTÄ.KERR.ALAS ## Pyöristää luvun alaspäin (nollaa kohti).
+GCD = SUURIN.YHT.TEKIJÄ ## Palauttaa suurimman yhteisen tekijän.
+INT = KOKONAISLUKU ## Pyöristää luvun alaspäin lähimpään kokonaislukuun.
+LCM = PIENIN.YHT.JAETTAVA ## Palauttaa pienimmän yhteisen tekijän.
+LN = LUONNLOG ## Palauttaa luvun luonnollisen logaritmin.
+LOG = LOG ## Laskee luvun logaritmin käyttämällä annettua kantalukua.
+LOG10 = LOG10 ## Palauttaa luvun kymmenkantaisen logaritmin.
+MDETERM = MDETERM ## Palauttaa matriisin matriisideterminantin.
+MINVERSE = MKÄÄNTEINEN ## Palauttaa matriisin käänteismatriisin.
+MMULT = MKERRO ## Palauttaa kahden matriisin tulon.
+MOD = JAKOJ ## Palauttaa jakolaskun jäännöksen.
+MROUND = PYÖRISTÄ.KERR ## Palauttaa luvun pyöristettynä annetun luvun kerrannaiseen.
+MULTINOMIAL = MULTINOMI ## Palauttaa lukujoukon multinomin.
+ODD = PARITON ## Pyöristää luvun ylöspäin lähimpään parittomaan kokonaislukuun.
+PI = PII ## Palauttaa piin arvon.
+POWER = POTENSSI ## Palauttaa luvun korotettuna haluttuun potenssiin.
+PRODUCT = TULO ## Kertoo annetut argumentit.
+QUOTIENT = OSAMÄÄRÄ ## Palauttaa osamäärän kokonaislukuosan.
+RADIANS = RADIAANIT ## Muuntaa asteet radiaaneiksi.
+RAND = SATUNNAISLUKU ## Palauttaa satunnaisluvun väliltä 0–1.
+RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ## Palauttaa satunnaisluvun määritettyjen lukujen väliltä.
+ROMAN = ROMAN ## Muuntaa arabialaisen numeron tekstimuotoiseksi roomalaiseksi numeroksi.
+ROUND = PYÖRISTÄ ## Pyöristää luvun annettuun määrään desimaaleja.
+ROUNDDOWN = PYÖRISTÄ.DES.ALAS ## Pyöristää luvun alaspäin (nollaa kohti).
+ROUNDUP = PYÖRISTÄ.DES.YLÖS ## Pyöristää luvun ylöspäin (poispäin nollasta).
+SERIESSUM = SARJA.SUMMA ## Palauttaa kaavaan perustuvan potenssisarjan arvon.
+SIGN = ETUMERKKI ## Palauttaa luvun etumerkin.
+SIN = SIN ## Palauttaa annetun kulman sinin.
+SINH = SINH ## Palauttaa luvun hyperbolisen sinin.
+SQRT = NELIÖJUURI ## Palauttaa positiivisen neliöjuuren.
+SQRTPI = NELIÖJUURI.PII ## Palauttaa tulon (luku * pii) neliöjuuren.
+SUBTOTAL = VÄLISUMMA ## Palauttaa luettelon tai tietokannan välisumman.
+SUM = SUMMA ## Laskee yhteen annetut argumentit.
+SUMIF = SUMMA.JOS ## Laskee ehdot täyttävien solujen summan.
+SUMIFS = SUMMA.JOS.JOUKKO ## Laskee yhteen solualueen useita ehtoja vastaavat solut.
+SUMPRODUCT = TULOJEN.SUMMA ## Palauttaa matriisin toisiaan vastaavien osien tulojen summan.
+SUMSQ = NELIÖSUMMA ## Palauttaa argumenttien neliöiden summan.
+SUMX2MY2 = NELIÖSUMMIEN.EROTUS ## Palauttaa kahden matriisin toisiaan vastaavien arvojen laskettujen neliösummien erotuksen.
+SUMX2PY2 = NELIÖSUMMIEN.SUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen neliösummien summan.
+SUMXMY2 = EROTUSTEN.NELIÖSUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen erotusten neliösumman.
+TAN = TAN ## Palauttaa luvun tangentin.
+TANH = TANH ## Palauttaa luvun hyperbolisen tangentin.
+TRUNC = KATKAISE ## Katkaisee luvun kokonaisluvuksi.
+
+
+##
+## Statistical functions Tilastolliset funktiot
+##
+AVEDEV = KESKIPOIKKEAMA ## Palauttaa hajontojen itseisarvojen keskiarvon.
+AVERAGE = KESKIARVO ## Palauttaa argumenttien keskiarvon.
+AVERAGEA = KESKIARVOA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, keskiarvon.
+AVERAGEIF = KESKIARVO.JOS ## Palauttaa alueen niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka täyttävät annetut ehdot.
+AVERAGEIFS = KESKIARVO.JOS.JOUKKO ## Palauttaa niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka vastaavat useita ehtoja.
+BETADIST = BEETAJAKAUMA ## Palauttaa kumulatiivisen beetajakaumafunktion arvon.
+BETAINV = BEETAJAKAUMA.KÄÄNT ## Palauttaa määritetyn beetajakauman käänteisen kumulatiivisen jakaumafunktion arvon.
+BINOMDIST = BINOMIJAKAUMA ## Palauttaa yksittäisen termin binomijakaumatodennäköisyyden.
+CHIDIST = CHIJAKAUMA ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden.
+CHIINV = CHIJAKAUMA.KÄÄNT ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden käänteisarvon.
+CHITEST = CHITESTI ## Palauttaa riippumattomuustestin tuloksen.
+CONFIDENCE = LUOTTAMUSVÄLI ## Palauttaa luottamusvälin populaation keskiarvolle.
+CORREL = KORRELAATIO ## Palauttaa kahden arvojoukon korrelaatiokertoimen.
+COUNT = LASKE ## Laskee argumenttiluettelossa olevien lukujen määrän.
+COUNTA = LASKE.A ## Laskee argumenttiluettelossa olevien arvojen määrän.
+COUNTBLANK = LASKE.TYHJÄT ## Laskee alueella olevien tyhjien solujen määrän.
+COUNTIF = LASKE.JOS ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa annettuja ehtoja.
+COUNTIFS = LASKE.JOS.JOUKKO ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa useita ehtoja.
+COVAR = KOVARIANSSI ## Palauttaa kovarianssin, joka on keskiarvo havaintoaineiston kunkin pisteparin poikkeamien tuloista.
+CRITBINOM = BINOMIJAKAUMA.KRIT ## Palauttaa pienimmän arvon, jossa binomijakauman kertymäfunktion arvo on pienempi tai yhtä suuri kuin vertailuarvo.
+DEVSQ = OIKAISTU.NELIÖSUMMA ## Palauttaa keskipoikkeamien neliösumman.
+EXPONDIST = EKSPONENTIAALIJAKAUMA ## Palauttaa eksponentiaalijakauman.
+FDIST = FJAKAUMA ## Palauttaa F-todennäköisyysjakauman.
+FINV = FJAKAUMA.KÄÄNT ## Palauttaa F-todennäköisyysjakauman käänteisfunktion.
+FISHER = FISHER ## Palauttaa Fisher-muunnoksen.
+FISHERINV = FISHER.KÄÄNT ## Palauttaa käänteisen Fisher-muunnoksen.
+FORECAST = ENNUSTE ## Palauttaa lineaarisen trendin arvon.
+FREQUENCY = TAAJUUS ## Palauttaa frekvenssijakautuman pystysuuntaisena matriisina.
+FTEST = FTESTI ## Palauttaa F-testin tuloksen.
+GAMMADIST = GAMMAJAKAUMA ## Palauttaa gammajakauman.
+GAMMAINV = GAMMAJAKAUMA.KÄÄNT ## Palauttaa käänteisen gammajakauman kertymäfunktion.
+GAMMALN = GAMMALN ## Palauttaa gammafunktion luonnollisen logaritmin G(x).
+GEOMEAN = KESKIARVO.GEOM ## Palauttaa geometrisen keskiarvon.
+GROWTH = KASVU ## Palauttaa eksponentiaalisen trendin arvon.
+HARMEAN = KESKIARVO.HARM ## Palauttaa harmonisen keskiarvon.
+HYPGEOMDIST = HYPERGEOM.JAKAUMA ## Palauttaa hypergeometrisen jakauman.
+INTERCEPT = LEIKKAUSPISTE ## Palauttaa lineaarisen regressiosuoran leikkauspisteen.
+KURT = KURT ## Palauttaa tietoalueen vinous-arvon eli huipukkuuden.
+LARGE = SUURI ## Palauttaa tietojoukon k:nneksi suurimman arvon.
+LINEST = LINREGR ## Palauttaa lineaarisen trendin parametrit.
+LOGEST = LOGREGR ## Palauttaa eksponentiaalisen trendin parametrit.
+LOGINV = LOGNORM.JAKAUMA.KÄÄNT ## Palauttaa lognormeeratun jakauman käänteisfunktion.
+LOGNORMDIST = LOGNORM.JAKAUMA ## Palauttaa lognormaalisen jakauman kertymäfunktion.
+MAX = MAKS ## Palauttaa suurimman arvon argumenttiluettelosta.
+MAXA = MAKSA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, suurimman arvon.
+MEDIAN = MEDIAANI ## Palauttaa annettujen lukujen mediaanin.
+MIN = MIN ## Palauttaa pienimmän arvon argumenttiluettelosta.
+MINA = MINA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, pienimmän arvon.
+MODE = MOODI ## Palauttaa tietojoukossa useimmin esiintyvän arvon.
+NEGBINOMDIST = BINOMIJAKAUMA.NEG ## Palauttaa negatiivisen binomijakauman.
+NORMDIST = NORM.JAKAUMA ## Palauttaa normaalijakauman kertymäfunktion.
+NORMINV = NORM.JAKAUMA.KÄÄNT ## Palauttaa käänteisen normaalijakauman kertymäfunktion.
+NORMSDIST = NORM.JAKAUMA.NORMIT ## Palauttaa normitetun normaalijakauman kertymäfunktion.
+NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT ## Palauttaa normitetun normaalijakauman kertymäfunktion käänteisarvon.
+PEARSON = PEARSON ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen.
+PERCENTILE = PROSENTTIPISTE ## Palauttaa alueen arvojen k:nnen prosenttipisteen.
+PERCENTRANK = PROSENTTIJÄRJESTYS ## Palauttaa tietojoukon arvon prosentuaalisen järjestysluvun.
+PERMUT = PERMUTAATIO ## Palauttaa mahdollisten permutaatioiden määrän annetulle objektien määrälle.
+POISSON = POISSON ## Palauttaa Poissonin todennäköisyysjakauman.
+PROB = TODENNÄKÖISYYS ## Palauttaa todennäköisyyden sille, että arvot ovat tietyltä väliltä.
+QUARTILE = NELJÄNNES ## Palauttaa tietoalueen neljänneksen.
+RANK = ARVON.MUKAAN ## Palauttaa luvun paikan lukuarvoluettelossa.
+RSQ = PEARSON.NELIÖ ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen neliön.
+SKEW = JAKAUMAN.VINOUS ## Palauttaa jakauman vinouden.
+SLOPE = KULMAKERROIN ## Palauttaa lineaarisen regressiosuoran kulmakertoimen.
+SMALL = PIENI ## Palauttaa tietojoukon k:nneksi pienimmän arvon.
+STANDARDIZE = NORMITA ## Palauttaa normitetun arvon.
+STDEV = KESKIHAJONTA ## Laskee populaation keskihajonnan otoksen perusteella.
+STDEVA = KESKIHAJONTAA ## Laskee populaation keskihajonnan otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot.
+STDEVP = KESKIHAJONTAP ## Laskee normaalijakautuman koko populaation perusteella.
+STDEVPA = KESKIHAJONTAPA ## Laskee populaation keskihajonnan koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot.
+STEYX = KESKIVIRHE ## Palauttaa regression kutakin x-arvoa vastaavan ennustetun y-arvon keskivirheen.
+TDIST = TJAKAUMA ## Palauttaa t-jakautuman.
+TINV = TJAKAUMA.KÄÄNT ## Palauttaa käänteisen t-jakauman.
+TREND = SUUNTAUS ## Palauttaa lineaarisen trendin arvoja.
+TRIMMEAN = KESKIARVO.TASATTU ## Palauttaa tietojoukon tasatun keskiarvon.
+TTEST = TTESTI ## Palauttaa t-testiin liittyvän todennäköisyyden.
+VAR = VAR ## Arvioi populaation varianssia otoksen perusteella.
+VARA = VARA ## Laskee populaation varianssin otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot.
+VARP = VARP ## Laskee varianssin koko populaation perusteella.
+VARPA = VARPA ## Laskee populaation varianssin koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot.
+WEIBULL = WEIBULL ## Palauttaa Weibullin jakauman.
+ZTEST = ZTESTI ## Palauttaa z-testin yksisuuntaisen todennäköisyysarvon.
+
+
+##
+## Text functions Tekstifunktiot
+##
+ASC = ASC ## Muuntaa merkkijonossa olevat englanninkieliset DBCS- tai katakana-merkit SBCS-merkeiksi.
+BAHTTEXT = BAHTTEKSTI ## Muuntaa luvun tekstiksi ß (baht) -valuuttamuotoa käyttämällä.
+CHAR = MERKKI ## Palauttaa koodin lukua vastaavan merkin.
+CLEAN = SIIVOA ## Poistaa tekstistä kaikki tulostumattomat merkit.
+CODE = KOODI ## Palauttaa tekstimerkkijonon ensimmäisen merkin numerokoodin.
+CONCATENATE = KETJUTA ## Yhdistää useat merkkijonot yhdeksi merkkijonoksi.
+DOLLAR = VALUUTTA ## Muuntaa luvun tekstiksi $ (dollari) -valuuttamuotoa käyttämällä.
+EXACT = VERTAA ## Tarkistaa, ovatko kaksi tekstiarvoa samanlaiset.
+FIND = ETSI ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet).
+FINDB = ETSIB ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet).
+FIXED = KIINTEÄ ## Muotoilee luvun tekstiksi, jossa on kiinteä määrä desimaaleja.
+JIS = JIS ## Muuntaa merkkijonossa olevat englanninkieliset SBCS- tai katakana-merkit DBCS-merkeiksi.
+LEFT = VASEN ## Palauttaa tekstiarvon vasemmanpuoliset merkit.
+LEFTB = VASENB ## Palauttaa tekstiarvon vasemmanpuoliset merkit.
+LEN = PITUUS ## Palauttaa tekstimerkkijonon merkkien määrän.
+LENB = PITUUSB ## Palauttaa tekstimerkkijonon merkkien määrän.
+LOWER = PIENET ## Muuntaa tekstin pieniksi kirjaimiksi.
+MID = POIMI.TEKSTI ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta.
+MIDB = POIMI.TEKSTIB ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta.
+PHONETIC = FONEETTINEN ## Hakee foneettiset (furigana) merkit merkkijonosta.
+PROPER = ERISNIMI ## Muuttaa merkkijonon kunkin sanan ensimmäisen kirjaimen isoksi.
+REPLACE = KORVAA ## Korvaa tekstissä olevat merkit.
+REPLACEB = KORVAAB ## Korvaa tekstissä olevat merkit.
+REPT = TOISTA ## Toistaa tekstin annetun määrän kertoja.
+RIGHT = OIKEA ## Palauttaa tekstiarvon oikeanpuoliset merkit.
+RIGHTB = OIKEAB ## Palauttaa tekstiarvon oikeanpuoliset merkit.
+SEARCH = KÄY.LÄPI ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi).
+SEARCHB = KÄY.LÄPIB ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi).
+SUBSTITUTE = VAIHDA ## Korvaa merkkijonossa olevan tekstin toisella.
+T = T ## Muuntaa argumentit tekstiksi.
+TEXT = TEKSTI ## Muotoilee luvun ja muuntaa sen tekstiksi.
+TRIM = POISTA.VÄLIT ## Poistaa välilyönnit tekstistä.
+UPPER = ISOT ## Muuntaa tekstin isoiksi kirjaimiksi.
+VALUE = ARVO ## Muuntaa tekstiargumentin luvuksi.
diff --git a/PHPExcel/locale/fr/config b/PHPExcel/locale/fr/config
new file mode 100644
index 0000000..368b3c3
--- /dev/null
+++ b/PHPExcel/locale/fr/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = €
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NUL!
+DIV0 = #DIV/0!
+VALUE = #VALEUR!
+REF = #REF!
+NAME = #NOM?
+NUM = #NOMBRE!
+NA = #N/A
diff --git a/PHPExcel/locale/fr/functions b/PHPExcel/locale/fr/functions
new file mode 100644
index 0000000..e85dba5
--- /dev/null
+++ b/PHPExcel/locale/fr/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Fonctions de complément et d’automatisation
+##
+GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE ## Renvoie les données stockées dans un rapport de tableau croisé dynamique.
+
+
+##
+## Cube functions Fonctions Cube
+##
+CUBEKPIMEMBER = MEMBREKPICUBE ## Renvoie un nom, une propriété et une mesure d’indicateur de performance clé et affiche le nom et la propriété dans la cellule. Un indicateur de performance clé est une mesure quantifiable, telle que la marge bénéficiaire brute mensuelle ou la rotation trimestrielle du personnel, utilisée pour évaluer les performances d’une entreprise.
+CUBEMEMBER = MEMBRECUBE ## Renvoie un membre ou un uplet dans une hiérarchie de cubes. Utilisez cette fonction pour valider l’existence du membre ou de l’uplet dans le cube.
+CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE ## Renvoie la valeur d’une propriété de membre du cube. Utilisez cette fonction pour valider l’existence d’un nom de membre dans le cube et pour renvoyer la propriété spécifiée pour ce membre.
+CUBERANKEDMEMBER = RANGMEMBRECUBE ## Renvoie le nième membre ou le membre placé à un certain rang dans un ensemble. Utilisez cette fonction pour renvoyer un ou plusieurs éléments d’un ensemble, tels que les meilleurs vendeurs ou les 10 meilleurs étudiants.
+CUBESET = JEUCUBE ## Définit un ensemble calculé de membres ou d’uplets en envoyant une expression définie au cube sur le serveur qui crée l’ensemble et le renvoie à Microsoft Office Excel.
+CUBESETCOUNT = NBJEUCUBE ## Renvoie le nombre d’éléments dans un jeu.
+CUBEVALUE = VALEURCUBE ## Renvoie une valeur d’agrégation issue d’un cube.
+
+
+##
+## Database functions Fonctions de base de données
+##
+DAVERAGE = BDMOYENNE ## Renvoie la moyenne des entrées de base de données sélectionnées.
+DCOUNT = BCOMPTE ## Compte le nombre de cellules d’une base de données qui contiennent des nombres.
+DCOUNTA = BDNBVAL ## Compte les cellules non vides d’une base de données.
+DGET = BDLIRE ## Extrait d’une base de données un enregistrement unique répondant aux critères spécifiés.
+DMAX = BDMAX ## Renvoie la valeur maximale des entrées de base de données sélectionnées.
+DMIN = BDMIN ## Renvoie la valeur minimale des entrées de base de données sélectionnées.
+DPRODUCT = BDPRODUIT ## Multiplie les valeurs d’un champ particulier des enregistrements d’une base de données, qui répondent aux critères spécifiés.
+DSTDEV = BDECARTYPE ## Calcule l’écart type pour un échantillon d’entrées de base de données sélectionnées.
+DSTDEVP = BDECARTYPEP ## Calcule l’écart type pour l’ensemble d’une population d’entrées de base de données sélectionnées.
+DSUM = BDSOMME ## Ajoute les nombres dans la colonne de champ des enregistrements de la base de données, qui répondent aux critères.
+DVAR = BDVAR ## Calcule la variance pour un échantillon d’entrées de base de données sélectionnées.
+DVARP = BDVARP ## Calcule la variance pour l’ensemble d’une population d’entrées de base de données sélectionnées.
+
+
+##
+## Date and time functions Fonctions de date et d’heure
+##
+DATE = DATE ## Renvoie le numéro de série d’une date précise.
+DATEVALUE = DATEVAL ## Convertit une date représentée sous forme de texte en numéro de série.
+DAY = JOUR ## Convertit un numéro de série en jour du mois.
+DAYS360 = JOURS360 ## Calcule le nombre de jours qui séparent deux dates sur la base d’une année de 360 jours.
+EDATE = MOIS.DECALER ## Renvoie le numéro séquentiel de la date qui représente une date spécifiée (l’argument date_départ), corrigée en plus ou en moins du nombre de mois indiqué.
+EOMONTH = FIN.MOIS ## Renvoie le numéro séquentiel de la date du dernier jour du mois précédant ou suivant la date_départ du nombre de mois indiqué.
+HOUR = HEURE ## Convertit un numéro de série en heure.
+MINUTE = MINUTE ## Convertit un numéro de série en minute.
+MONTH = MOIS ## Convertit un numéro de série en mois.
+NETWORKDAYS = NB.JOURS.OUVRES ## Renvoie le nombre de jours ouvrés entiers compris entre deux dates.
+NOW = MAINTENANT ## Renvoie le numéro de série de la date et de l’heure du jour.
+SECOND = SECONDE ## Convertit un numéro de série en seconde.
+TIME = TEMPS ## Renvoie le numéro de série d’une heure précise.
+TIMEVALUE = TEMPSVAL ## Convertit une date représentée sous forme de texte en numéro de série.
+TODAY = AUJOURDHUI ## Renvoie le numéro de série de la date du jour.
+WEEKDAY = JOURSEM ## Convertit un numéro de série en jour de la semaine.
+WEEKNUM = NO.SEMAINE ## Convertit un numéro de série en un numéro représentant l’ordre de la semaine dans l’année.
+WORKDAY = SERIE.JOUR.OUVRE ## Renvoie le numéro de série de la date avant ou après le nombre de jours ouvrés spécifiés.
+YEAR = ANNEE ## Convertit un numéro de série en année.
+YEARFRAC = FRACTION.ANNEE ## Renvoie la fraction de l’année représentant le nombre de jours entre la date de début et la date de fin.
+
+
+##
+## Engineering functions Fonctions d’ingénierie
+##
+BESSELI = BESSELI ## Renvoie la fonction Bessel modifiée In(x).
+BESSELJ = BESSELJ ## Renvoie la fonction Bessel Jn(x).
+BESSELK = BESSELK ## Renvoie la fonction Bessel modifiée Kn(x).
+BESSELY = BESSELY ## Renvoie la fonction Bessel Yn(x).
+BIN2DEC = BINDEC ## Convertit un nombre binaire en nombre décimal.
+BIN2HEX = BINHEX ## Convertit un nombre binaire en nombre hexadécimal.
+BIN2OCT = BINOCT ## Convertit un nombre binaire en nombre octal.
+COMPLEX = COMPLEXE ## Convertit des coefficients réel et imaginaire en un nombre complexe.
+CONVERT = CONVERT ## Convertit un nombre d’une unité de mesure à une autre.
+DEC2BIN = DECBIN ## Convertit un nombre décimal en nombre binaire.
+DEC2HEX = DECHEX ## Convertit un nombre décimal en nombre hexadécimal.
+DEC2OCT = DECOCT ## Convertit un nombre décimal en nombre octal.
+DELTA = DELTA ## Teste l’égalité de deux nombres.
+ERF = ERF ## Renvoie la valeur de la fonction d’erreur.
+ERFC = ERFC ## Renvoie la valeur de la fonction d’erreur complémentaire.
+GESTEP = SUP.SEUIL ## Teste si un nombre est supérieur à une valeur de seuil.
+HEX2BIN = HEXBIN ## Convertit un nombre hexadécimal en nombre binaire.
+HEX2DEC = HEXDEC ## Convertit un nombre hexadécimal en nombre décimal.
+HEX2OCT = HEXOCT ## Convertit un nombre hexadécimal en nombre octal.
+IMABS = COMPLEXE.MODULE ## Renvoie la valeur absolue (module) d’un nombre complexe.
+IMAGINARY = COMPLEXE.IMAGINAIRE ## Renvoie le coefficient imaginaire d’un nombre complexe.
+IMARGUMENT = COMPLEXE.ARGUMENT ## Renvoie l’argument thêta, un angle exprimé en radians.
+IMCONJUGATE = COMPLEXE.CONJUGUE ## Renvoie le nombre complexe conjugué d’un nombre complexe.
+IMCOS = IMCOS ## Renvoie le cosinus d’un nombre complexe.
+IMDIV = COMPLEXE.DIV ## Renvoie le quotient de deux nombres complexes.
+IMEXP = COMPLEXE.EXP ## Renvoie la fonction exponentielle d’un nombre complexe.
+IMLN = COMPLEXE.LN ## Renvoie le logarithme népérien d’un nombre complexe.
+IMLOG10 = COMPLEXE.LOG10 ## Calcule le logarithme en base 10 d’un nombre complexe.
+IMLOG2 = COMPLEXE.LOG2 ## Calcule le logarithme en base 2 d’un nombre complexe.
+IMPOWER = COMPLEXE.PUISSANCE ## Renvoie un nombre complexe élevé à une puissance entière.
+IMPRODUCT = COMPLEXE.PRODUIT ## Renvoie le produit de plusieurs nombres complexes.
+IMREAL = COMPLEXE.REEL ## Renvoie le coefficient réel d’un nombre complexe.
+IMSIN = COMPLEXE.SIN ## Renvoie le sinus d’un nombre complexe.
+IMSQRT = COMPLEXE.RACINE ## Renvoie la racine carrée d’un nombre complexe.
+IMSUB = COMPLEXE.DIFFERENCE ## Renvoie la différence entre deux nombres complexes.
+IMSUM = COMPLEXE.SOMME ## Renvoie la somme de plusieurs nombres complexes.
+OCT2BIN = OCTBIN ## Convertit un nombre octal en nombre binaire.
+OCT2DEC = OCTDEC ## Convertit un nombre octal en nombre décimal.
+OCT2HEX = OCTHEX ## Convertit un nombre octal en nombre hexadécimal.
+
+
+##
+## Financial functions Fonctions financières
+##
+ACCRINT = INTERET.ACC ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu périodiquement.
+ACCRINTM = INTERET.ACC.MAT ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu à l’échéance.
+AMORDEGRC = AMORDEGRC ## Renvoie l’amortissement correspondant à chaque période comptable en utilisant un coefficient d’amortissement.
+AMORLINC = AMORLINC ## Renvoie l’amortissement d’un bien à la fin d’une période fiscale donnée.
+COUPDAYBS = NB.JOURS.COUPON.PREC ## Renvoie le nombre de jours entre le début de la période de coupon et la date de liquidation.
+COUPDAYS = NB.JOURS.COUPONS ## Renvoie le nombre de jours pour la période du coupon contenant la date de liquidation.
+COUPDAYSNC = NB.JOURS.COUPON.SUIV ## Renvoie le nombre de jours entre la date de liquidation et la date du coupon suivant la date de liquidation.
+COUPNCD = DATE.COUPON.SUIV ## Renvoie la première date de coupon ultérieure à la date de règlement.
+COUPNUM = NB.COUPONS ## Renvoie le nombre de coupons dus entre la date de règlement et la date d’échéance.
+COUPPCD = DATE.COUPON.PREC ## Renvoie la date de coupon précédant la date de règlement.
+CUMIPMT = CUMUL.INTER ## Renvoie l’intérêt cumulé payé sur un emprunt entre deux périodes.
+CUMPRINC = CUMUL.PRINCPER ## Renvoie le montant cumulé des remboursements du capital d’un emprunt effectués entre deux périodes.
+DB = DB ## Renvoie l’amortissement d’un bien pour une période spécifiée en utilisant la méthode de l’amortissement dégressif à taux fixe.
+DDB = DDB ## Renvoie l’amortissement d’un bien pour toute période spécifiée, en utilisant la méthode de l’amortissement dégressif à taux double ou selon un coefficient à spécifier.
+DISC = TAUX.ESCOMPTE ## Calcule le taux d’escompte d’une transaction.
+DOLLARDE = PRIX.DEC ## Convertit un prix en euros, exprimé sous forme de fraction, en un prix en euros exprimé sous forme de nombre décimal.
+DOLLARFR = PRIX.FRAC ## Convertit un prix en euros, exprimé sous forme de nombre décimal, en un prix en euros exprimé sous forme de fraction.
+DURATION = DUREE ## Renvoie la durée, en années, d’un titre dont l’intérêt est perçu périodiquement.
+EFFECT = TAUX.EFFECTIF ## Renvoie le taux d’intérêt annuel effectif.
+FV = VC ## Renvoie la valeur future d’un investissement.
+FVSCHEDULE = VC.PAIEMENTS ## Calcule la valeur future d’un investissement en appliquant une série de taux d’intérêt composites.
+INTRATE = TAUX.INTERET ## Affiche le taux d’intérêt d’un titre totalement investi.
+IPMT = INTPER ## Calcule le montant des intérêts d’un investissement pour une période donnée.
+IRR = TRI ## Calcule le taux de rentabilité interne d’un investissement pour une succession de trésoreries.
+ISPMT = ISPMT ## Calcule le montant des intérêts d’un investissement pour une période donnée.
+MDURATION = DUREE.MODIFIEE ## Renvoie la durée de Macauley modifiée pour un titre ayant une valeur nominale hypothétique de 100_euros.
+MIRR = TRIM ## Calcule le taux de rentabilité interne lorsque les paiements positifs et négatifs sont financés à des taux différents.
+NOMINAL = TAUX.NOMINAL ## Calcule le taux d’intérêt nominal annuel.
+NPER = NPM ## Renvoie le nombre de versements nécessaires pour rembourser un emprunt.
+NPV = VAN ## Calcule la valeur actuelle nette d’un investissement basé sur une série de décaissements et un taux d’escompte.
+ODDFPRICE = PRIX.PCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière.
+ODDFYIELD = REND.PCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la première période de coupon est irrégulière.
+ODDLPRICE = PRIX.DCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière.
+ODDLYIELD = REND.DCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la dernière période de coupon est irrégulière.
+PMT = VPM ## Calcule le paiement périodique d’un investissement donné.
+PPMT = PRINCPER ## Calcule, pour une période donnée, la part de remboursement du principal d’un investissement.
+PRICE = PRIX.TITRE ## Renvoie le prix d’un titre rapportant des intérêts périodiques, pour une valeur nominale de 100 euros.
+PRICEDISC = VALEUR.ENCAISSEMENT ## Renvoie la valeur d’encaissement d’un escompte commercial, pour une valeur nominale de 100 euros.
+PRICEMAT = PRIX.TITRE.ECHEANCE ## Renvoie le prix d’un titre dont la valeur nominale est 100 euros et qui rapporte des intérêts à l’échéance.
+PV = PV ## Calcule la valeur actuelle d’un investissement.
+RATE = TAUX ## Calcule le taux d’intérêt par période pour une annuité.
+RECEIVED = VALEUR.NOMINALE ## Renvoie la valeur nominale à échéance d’un effet de commerce.
+SLN = AMORLIN ## Calcule l’amortissement linéaire d’un bien pour une période donnée.
+SYD = SYD ## Calcule l’amortissement d’un bien pour une période donnée sur la base de la méthode américaine Sum-of-Years Digits (amortissement dégressif à taux décroissant appliqué à une valeur constante).
+TBILLEQ = TAUX.ESCOMPTE.R ## Renvoie le taux d’escompte rationnel d’un bon du Trésor.
+TBILLPRICE = PRIX.BON.TRESOR ## Renvoie le prix d’un bon du Trésor d’une valeur nominale de 100 euros.
+TBILLYIELD = RENDEMENT.BON.TRESOR ## Calcule le taux de rendement d’un bon du Trésor.
+VDB = VDB ## Renvoie l’amortissement d’un bien pour une période spécifiée ou partielle en utilisant une méthode de l’amortissement dégressif à taux fixe.
+XIRR = TRI.PAIEMENTS ## Calcule le taux de rentabilité interne d’un ensemble de paiements non périodiques.
+XNPV = VAN.PAIEMENTS ## Renvoie la valeur actuelle nette d’un ensemble de paiements non périodiques.
+YIELD = RENDEMENT.TITRE ## Calcule le rendement d’un titre rapportant des intérêts périodiquement.
+YIELDDISC = RENDEMENT.SIMPLE ## Calcule le taux de rendement d’un emprunt à intérêt simple (par exemple, un bon du Trésor).
+YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## Renvoie le rendement annuel d’un titre qui rapporte des intérêts à l’échéance.
+
+
+##
+## Information functions Fonctions d’information
+##
+CELL = CELLULE ## Renvoie des informations sur la mise en forme, l’emplacement et le contenu d’une cellule.
+ERROR.TYPE = TYPE.ERREUR ## Renvoie un nombre correspondant à un type d’erreur.
+INFO = INFORMATIONS ## Renvoie des informations sur l’environnement d’exploitation actuel.
+ISBLANK = ESTVIDE ## Renvoie VRAI si l’argument valeur est vide.
+ISERR = ESTERR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur, sauf #N/A.
+ISERROR = ESTERREUR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur.
+ISEVEN = EST.PAIR ## Renvoie VRAI si le chiffre est pair.
+ISLOGICAL = ESTLOGIQUE ## Renvoie VRAI si l’argument valeur fait référence à une valeur logique.
+ISNA = ESTNA ## Renvoie VRAI si l’argument valeur fait référence à la valeur d’erreur #N/A.
+ISNONTEXT = ESTNONTEXTE ## Renvoie VRAI si l’argument valeur ne se présente pas sous forme de texte.
+ISNUMBER = ESTNUM ## Renvoie VRAI si l’argument valeur représente un nombre.
+ISODD = EST.IMPAIR ## Renvoie VRAI si le chiffre est impair.
+ISREF = ESTREF ## Renvoie VRAI si l’argument valeur est une référence.
+ISTEXT = ESTTEXTE ## Renvoie VRAI si l’argument valeur se présente sous forme de texte.
+N = N ## Renvoie une valeur convertie en nombre.
+NA = NA ## Renvoie la valeur d’erreur #N/A.
+TYPE = TYPE ## Renvoie un nombre indiquant le type de données d’une valeur.
+
+
+##
+## Logical functions Fonctions logiques
+##
+AND = ET ## Renvoie VRAI si tous ses arguments sont VRAI.
+FALSE = FAUX ## Renvoie la valeur logique FAUX.
+IF = SI ## Spécifie un test logique à effectuer.
+IFERROR = SIERREUR ## Renvoie une valeur que vous spécifiez si une formule génère une erreur ; sinon, elle renvoie le résultat de la formule.
+NOT = NON ## Inverse la logique de cet argument.
+OR = OU ## Renvoie VRAI si un des arguments est VRAI.
+TRUE = VRAI ## Renvoie la valeur logique VRAI.
+
+
+##
+## Lookup and reference functions Fonctions de recherche et de référence
+##
+ADDRESS = ADRESSE ## Renvoie une référence sous forme de texte à une seule cellule d’une feuille de calcul.
+AREAS = ZONES ## Renvoie le nombre de zones dans une référence.
+CHOOSE = CHOISIR ## Choisit une valeur dans une liste.
+COLUMN = COLONNE ## Renvoie le numéro de colonne d’une référence.
+COLUMNS = COLONNES ## Renvoie le nombre de colonnes dans une référence.
+HLOOKUP = RECHERCHEH ## Effectue une recherche dans la première ligne d’une matrice et renvoie la valeur de la cellule indiquée.
+HYPERLINK = LIEN_HYPERTEXTE ## Crée un raccourci ou un renvoi qui ouvre un document stocké sur un serveur réseau, sur un réseau Intranet ou sur Internet.
+INDEX = INDEX ## Utilise un index pour choisir une valeur provenant d’une référence ou d’une matrice.
+INDIRECT = INDIRECT ## Renvoie une référence indiquée par une valeur de texte.
+LOOKUP = RECHERCHE ## Recherche des valeurs dans un vecteur ou une matrice.
+MATCH = EQUIV ## Recherche des valeurs dans une référence ou une matrice.
+OFFSET = DECALER ## Renvoie une référence décalée par rapport à une référence donnée.
+ROW = LIGNE ## Renvoie le numéro de ligne d’une référence.
+ROWS = LIGNES ## Renvoie le nombre de lignes dans une référence.
+RTD = RTD ## Extrait les données en temps réel à partir d’un programme prenant en charge l’automation COM (Automation : utilisation des objets d'une application à partir d'une autre application ou d'un autre outil de développement. Autrefois appelée OLE Automation, Automation est une norme industrielle et une fonctionnalité du modèle d'objet COM (Component Object Model).).
+TRANSPOSE = TRANSPOSE ## Renvoie la transposition d’une matrice.
+VLOOKUP = RECHERCHEV ## Effectue une recherche dans la première colonne d’une matrice et se déplace sur la ligne pour renvoyer la valeur d’une cellule.
+
+
+##
+## Math and trigonometry functions Fonctions mathématiques et trigonométriques
+##
+ABS = ABS ## Renvoie la valeur absolue d’un nombre.
+ACOS = ACOS ## Renvoie l’arccosinus d’un nombre.
+ACOSH = ACOSH ## Renvoie le cosinus hyperbolique inverse d’un nombre.
+ASIN = ASIN ## Renvoie l’arcsinus d’un nombre.
+ASINH = ASINH ## Renvoie le sinus hyperbolique inverse d’un nombre.
+ATAN = ATAN ## Renvoie l’arctangente d’un nombre.
+ATAN2 = ATAN2 ## Renvoie l’arctangente des coordonnées x et y.
+ATANH = ATANH ## Renvoie la tangente hyperbolique inverse d’un nombre.
+CEILING = PLAFOND ## Arrondit un nombre au nombre entier le plus proche ou au multiple le plus proche de l’argument précision en s’éloignant de zéro.
+COMBIN = COMBIN ## Renvoie le nombre de combinaisons que l’on peut former avec un nombre donné d’objets.
+COS = COS ## Renvoie le cosinus d’un nombre.
+COSH = COSH ## Renvoie le cosinus hyperbolique d’un nombre.
+DEGREES = DEGRES ## Convertit des radians en degrés.
+EVEN = PAIR ## Arrondit un nombre au nombre entier pair le plus proche en s’éloignant de zéro.
+EXP = EXP ## Renvoie e élevé à la puissance d’un nombre donné.
+FACT = FACT ## Renvoie la factorielle d’un nombre.
+FACTDOUBLE = FACTDOUBLE ## Renvoie la factorielle double d’un nombre.
+FLOOR = PLANCHER ## Arrondit un nombre en tendant vers 0 (zéro).
+GCD = PGCD ## Renvoie le plus grand commun diviseur.
+INT = ENT ## Arrondit un nombre à l’entier immédiatement inférieur.
+LCM = PPCM ## Renvoie le plus petit commun multiple.
+LN = LN ## Renvoie le logarithme népérien d’un nombre.
+LOG = LOG ## Renvoie le logarithme d’un nombre dans la base spécifiée.
+LOG10 = LOG10 ## Calcule le logarithme en base 10 d’un nombre.
+MDETERM = DETERMAT ## Renvoie le déterminant d’une matrice.
+MINVERSE = INVERSEMAT ## Renvoie la matrice inverse d’une matrice.
+MMULT = PRODUITMAT ## Renvoie le produit de deux matrices.
+MOD = MOD ## Renvoie le reste d’une division.
+MROUND = ARRONDI.AU.MULTIPLE ## Donne l’arrondi d’un nombre au multiple spécifié.
+MULTINOMIAL = MULTINOMIALE ## Calcule la multinomiale d’un ensemble de nombres.
+ODD = IMPAIR ## Renvoie le nombre, arrondi à la valeur du nombre entier impair le plus proche en s’éloignant de zéro.
+PI = PI ## Renvoie la valeur de pi.
+POWER = PUISSANCE ## Renvoie la valeur du nombre élevé à une puissance.
+PRODUCT = PRODUIT ## Multiplie ses arguments.
+QUOTIENT = QUOTIENT ## Renvoie la partie entière du résultat d’une division.
+RADIANS = RADIANS ## Convertit des degrés en radians.
+RAND = ALEA ## Renvoie un nombre aléatoire compris entre 0 et 1.
+RANDBETWEEN = ALEA.ENTRE.BORNES ## Renvoie un nombre aléatoire entre les nombres que vous spécifiez.
+ROMAN = ROMAIN ## Convertit des chiffres arabes en chiffres romains, sous forme de texte.
+ROUND = ARRONDI ## Arrondit un nombre au nombre de chiffres indiqué.
+ROUNDDOWN = ARRONDI.INF ## Arrondit un nombre en tendant vers 0 (zéro).
+ROUNDUP = ARRONDI.SUP ## Arrondit un nombre à l’entier supérieur, en s’éloignant de zéro.
+SERIESSUM = SOMME.SERIES ## Renvoie la somme d’une série géométrique en s’appuyant sur la formule suivante :
+SIGN = SIGNE ## Renvoie le signe d’un nombre.
+SIN = SIN ## Renvoie le sinus d’un angle donné.
+SINH = SINH ## Renvoie le sinus hyperbolique d’un nombre.
+SQRT = RACINE ## Renvoie la racine carrée d’un nombre.
+SQRTPI = RACINE.PI ## Renvoie la racine carrée de (nombre * pi).
+SUBTOTAL = SOUS.TOTAL ## Renvoie un sous-total dans une liste ou une base de données.
+SUM = SOMME ## Calcule la somme de ses arguments.
+SUMIF = SOMME.SI ## Additionne les cellules spécifiées si elles répondent à un critère donné.
+SUMIFS = SOMME.SI.ENS ## Ajoute les cellules d’une plage qui répondent à plusieurs critères.
+SUMPRODUCT = SOMMEPROD ## Multiplie les valeurs correspondantes des matrices spécifiées et calcule la somme de ces produits.
+SUMSQ = SOMME.CARRES ## Renvoie la somme des carrés des arguments.
+SUMX2MY2 = SOMME.X2MY2 ## Renvoie la somme de la différence des carrés des valeurs correspondantes de deux matrices.
+SUMX2PY2 = SOMME.X2PY2 ## Renvoie la somme de la somme des carrés des valeurs correspondantes de deux matrices.
+SUMXMY2 = SOMME.XMY2 ## Renvoie la somme des carrés des différences entre les valeurs correspondantes de deux matrices.
+TAN = TAN ## Renvoie la tangente d’un nombre.
+TANH = TANH ## Renvoie la tangente hyperbolique d’un nombre.
+TRUNC = TRONQUE ## Renvoie la partie entière d’un nombre.
+
+
+##
+## Statistical functions Fonctions statistiques
+##
+AVEDEV = ECART.MOYEN ## Renvoie la moyenne des écarts absolus observés dans la moyenne des points de données.
+AVERAGE = MOYENNE ## Renvoie la moyenne de ses arguments.
+AVERAGEA = AVERAGEA ## Renvoie la moyenne de ses arguments, nombres, texte et valeurs logiques inclus.
+AVERAGEIF = MOYENNE.SI ## Renvoie la moyenne (arithmétique) de toutes les cellules d’une plage qui répondent à des critères donnés.
+AVERAGEIFS = MOYENNE.SI.ENS ## Renvoie la moyenne (arithmétique) de toutes les cellules qui répondent à plusieurs critères.
+BETADIST = LOI.BETA ## Renvoie la fonction de distribution cumulée.
+BETAINV = BETA.INVERSE ## Renvoie l’inverse de la fonction de distribution cumulée pour une distribution bêta spécifiée.
+BINOMDIST = LOI.BINOMIALE ## Renvoie la probabilité d’une variable aléatoire discrète suivant la loi binomiale.
+CHIDIST = LOI.KHIDEUX ## Renvoie la probabilité unilatérale de la distribution khi-deux.
+CHIINV = KHIDEUX.INVERSE ## Renvoie l’inverse de la probabilité unilatérale de la distribution khi-deux.
+CHITEST = TEST.KHIDEUX ## Renvoie le test d’indépendance.
+CONFIDENCE = INTERVALLE.CONFIANCE ## Renvoie l’intervalle de confiance pour une moyenne de population.
+CORREL = COEFFICIENT.CORRELATION ## Renvoie le coefficient de corrélation entre deux séries de données.
+COUNT = NB ## Détermine les nombres compris dans la liste des arguments.
+COUNTA = NBVAL ## Détermine le nombre de valeurs comprises dans la liste des arguments.
+COUNTBLANK = NB.VIDE ## Compte le nombre de cellules vides dans une plage.
+COUNTIF = NB.SI ## Compte le nombre de cellules qui répondent à un critère donné dans une plage.
+COUNTIFS = NB.SI.ENS ## Compte le nombre de cellules à l’intérieur d’une plage qui répondent à plusieurs critères.
+COVAR = COVARIANCE ## Renvoie la covariance, moyenne des produits des écarts pour chaque série d’observations.
+CRITBINOM = CRITERE.LOI.BINOMIALE ## Renvoie la plus petite valeur pour laquelle la distribution binomiale cumulée est inférieure ou égale à une valeur de critère.
+DEVSQ = SOMME.CARRES.ECARTS ## Renvoie la somme des carrés des écarts.
+EXPONDIST = LOI.EXPONENTIELLE ## Renvoie la distribution exponentielle.
+FDIST = LOI.F ## Renvoie la distribution de probabilité F.
+FINV = INVERSE.LOI.F ## Renvoie l’inverse de la distribution de probabilité F.
+FISHER = FISHER ## Renvoie la transformation de Fisher.
+FISHERINV = FISHER.INVERSE ## Renvoie l’inverse de la transformation de Fisher.
+FORECAST = PREVISION ## Calcule une valeur par rapport à une tendance linéaire.
+FREQUENCY = FREQUENCE ## Calcule la fréquence d’apparition des valeurs dans une plage de valeurs, puis renvoie des nombres sous forme de matrice verticale.
+FTEST = TEST.F ## Renvoie le résultat d’un test F.
+GAMMADIST = LOI.GAMMA ## Renvoie la probabilité d’une variable aléatoire suivant une loi Gamma.
+GAMMAINV = LOI.GAMMA.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi Gamma.
+GAMMALN = LNGAMMA ## Renvoie le logarithme népérien de la fonction Gamma, G(x)
+GEOMEAN = MOYENNE.GEOMETRIQUE ## Renvoie la moyenne géométrique.
+GROWTH = CROISSANCE ## Calcule des valeurs par rapport à une tendance exponentielle.
+HARMEAN = MOYENNE.HARMONIQUE ## Renvoie la moyenne harmonique.
+HYPGEOMDIST = LOI.HYPERGEOMETRIQUE ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi hypergéométrique.
+INTERCEPT = ORDONNEE.ORIGINE ## Renvoie l’ordonnée à l’origine d’une droite de régression linéaire.
+KURT = KURTOSIS ## Renvoie le kurtosis d’une série de données.
+LARGE = GRANDE.VALEUR ## Renvoie la k-ième plus grande valeur d’une série de données.
+LINEST = DROITEREG ## Renvoie les paramètres d’une tendance linéaire.
+LOGEST = LOGREG ## Renvoie les paramètres d’une tendance exponentielle.
+LOGINV = LOI.LOGNORMALE.INVERSE ## Renvoie l’inverse de la probabilité pour une variable aléatoire suivant la loi lognormale.
+LOGNORMDIST = LOI.LOGNORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi lognormale.
+MAX = MAX ## Renvoie la valeur maximale contenue dans une liste d’arguments.
+MAXA = MAXA ## Renvoie la valeur maximale d’une liste d’arguments, nombres, texte et valeurs logiques inclus.
+MEDIAN = MEDIANE ## Renvoie la valeur médiane des nombres donnés.
+MIN = MIN ## Renvoie la valeur minimale contenue dans une liste d’arguments.
+MINA = MINA ## Renvoie la plus petite valeur d’une liste d’arguments, nombres, texte et valeurs logiques inclus.
+MODE = MODE ## Renvoie la valeur la plus courante d’une série de données.
+NEGBINOMDIST = LOI.BINOMIALE.NEG ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi binomiale négative.
+NORMDIST = LOI.NORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale.
+NORMINV = LOI.NORMALE.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi normale standard.
+NORMSDIST = LOI.NORMALE.STANDARD ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale standard.
+NORMSINV = LOI.NORMALE.STANDARD.INVERSE ## Renvoie l’inverse de la distribution cumulée normale standard.
+PEARSON = PEARSON ## Renvoie le coefficient de corrélation d’échantillonnage de Pearson.
+PERCENTILE = CENTILE ## Renvoie le k-ième centile des valeurs d’une plage.
+PERCENTRANK = RANG.POURCENTAGE ## Renvoie le rang en pourcentage d’une valeur d’une série de données.
+PERMUT = PERMUTATION ## Renvoie le nombre de permutations pour un nombre donné d’objets.
+POISSON = LOI.POISSON ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Poisson.
+PROB = PROBABILITE ## Renvoie la probabilité que des valeurs d’une plage soient comprises entre deux limites.
+QUARTILE = QUARTILE ## Renvoie le quartile d’une série de données.
+RANK = RANG ## Renvoie le rang d’un nombre contenu dans une liste.
+RSQ = COEFFICIENT.DETERMINATION ## Renvoie la valeur du coefficient de détermination R^2 d’une régression linéaire.
+SKEW = COEFFICIENT.ASYMETRIE ## Renvoie l’asymétrie d’une distribution.
+SLOPE = PENTE ## Renvoie la pente d’une droite de régression linéaire.
+SMALL = PETITE.VALEUR ## Renvoie la k-ième plus petite valeur d’une série de données.
+STANDARDIZE = CENTREE.REDUITE ## Renvoie une valeur centrée réduite.
+STDEV = ECARTYPE ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population.
+STDEVA = STDEVA ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques inclus.
+STDEVP = ECARTYPEP ## Calcule l’écart type d’une population à partir de la population entière.
+STDEVPA = STDEVPA ## Calcule l’écart type d’une population à partir de l’ensemble de la population, nombres, texte et valeurs logiques inclus.
+STEYX = ERREUR.TYPE.XY ## Renvoie l’erreur type de la valeur y prévue pour chaque x de la régression.
+TDIST = LOI.STUDENT ## Renvoie la probabilité d’une variable aléatoire suivant une loi T de Student.
+TINV = LOI.STUDENT.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi T de Student.
+TREND = TENDANCE ## Renvoie des valeurs par rapport à une tendance linéaire.
+TRIMMEAN = MOYENNE.REDUITE ## Renvoie la moyenne de l’intérieur d’une série de données.
+TTEST = TEST.STUDENT ## Renvoie la probabilité associée à un test T de Student.
+VAR = VAR ## Calcule la variance sur la base d’un échantillon.
+VARA = VARA ## Estime la variance d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques incluses.
+VARP = VAR.P ## Calcule la variance sur la base de l’ensemble de la population.
+VARPA = VARPA ## Calcule la variance d’une population en se basant sur la population entière, nombres, texte et valeurs logiques inclus.
+WEIBULL = LOI.WEIBULL ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Weibull.
+ZTEST = TEST.Z ## Renvoie la valeur de probabilité unilatérale d’un test z.
+
+
+##
+## Text functions Fonctions de texte
+##
+ASC = ASC ## Change les caractères anglais ou katakana à pleine chasse (codés sur deux octets) à l’intérieur d’une chaîne de caractères en caractères à demi-chasse (codés sur un octet).
+BAHTTEXT = BAHTTEXT ## Convertit un nombre en texte en utilisant le format monétaire ß (baht).
+CHAR = CAR ## Renvoie le caractère spécifié par le code numérique.
+CLEAN = EPURAGE ## Supprime tous les caractères de contrôle du texte.
+CODE = CODE ## Renvoie le numéro de code du premier caractère du texte.
+CONCATENATE = CONCATENER ## Assemble plusieurs éléments textuels de façon à n’en former qu’un seul.
+DOLLAR = EURO ## Convertit un nombre en texte en utilisant le format monétaire € (euro).
+EXACT = EXACT ## Vérifie si deux valeurs de texte sont identiques.
+FIND = TROUVE ## Trouve un valeur textuelle dans une autre, en respectant la casse.
+FINDB = TROUVERB ## Trouve un valeur textuelle dans une autre, en respectant la casse.
+FIXED = CTXT ## Convertit un nombre au format texte avec un nombre de décimales spécifié.
+JIS = JIS ## Change les caractères anglais ou katakana à demi-chasse (codés sur un octet) à l’intérieur d’une chaîne de caractères en caractères à à pleine chasse (codés sur deux octets).
+LEFT = GAUCHE ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères.
+LEFTB = GAUCHEB ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères.
+LEN = NBCAR ## Renvoie le nombre de caractères contenus dans une chaîne de texte.
+LENB = LENB ## Renvoie le nombre de caractères contenus dans une chaîne de texte.
+LOWER = MINUSCULE ## Convertit le texte en minuscules.
+MID = STXT ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez.
+MIDB = STXTB ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez.
+PHONETIC = PHONETIQUE ## Extrait les caractères phonétiques (furigana) d’une chaîne de texte.
+PROPER = NOMPROPRE ## Met en majuscules la première lettre de chaque mot dans une chaîne textuelle.
+REPLACE = REMPLACER ## Remplace des caractères dans un texte.
+REPLACEB = REMPLACERB ## Remplace des caractères dans un texte.
+REPT = REPT ## Répète un texte un certain nombre de fois.
+RIGHT = DROITE ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères.
+RIGHTB = DROITEB ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères.
+SEARCH = CHERCHE ## Trouve un texte dans un autre texte (sans respecter la casse).
+SEARCHB = CHERCHERB ## Trouve un texte dans un autre texte (sans respecter la casse).
+SUBSTITUTE = SUBSTITUE ## Remplace l’ancien texte d’une chaîne de caractères par un nouveau.
+T = T ## Convertit ses arguments en texte.
+TEXT = TEXTE ## Convertit un nombre au format texte.
+TRIM = SUPPRESPACE ## Supprime les espaces du texte.
+UPPER = MAJUSCULE ## Convertit le texte en majuscules.
+VALUE = CNUM ## Convertit un argument textuel en nombre
diff --git a/PHPExcel/locale/hu/config b/PHPExcel/locale/hu/config
new file mode 100644
index 0000000..e04151c
--- /dev/null
+++ b/PHPExcel/locale/hu/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = Ft
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULLA!
+DIV0 = #ZÉRÓOSZTÓ!
+VALUE = #ÉRTÉK!
+REF = #HIV!
+NAME = #NÉV?
+NUM = #SZÁM!
+NA = #HIÁNYZIK
diff --git a/PHPExcel/locale/hu/functions b/PHPExcel/locale/hu/functions
new file mode 100644
index 0000000..77cae92
--- /dev/null
+++ b/PHPExcel/locale/hu/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Bővítmények és automatizálási függvények
+##
+GETPIVOTDATA = KIMUTATÁSADATOT.VESZ ## A kimutatásokban tárolt adatok visszaadására használható.
+
+
+##
+## Cube functions Kockafüggvények
+##
+CUBEKPIMEMBER = KOCKA.FŐTELJMUT ## Egy fő teljesítménymutató (KPI) nevét, tulajdonságát és mértékegységét adja eredményül, a nevet és a tulajdonságot megjeleníti a cellában. A KPI-k számszerűsíthető mérési lehetőséget jelentenek – ilyen mutató például a havi bruttó nyereség vagy az egy alkalmazottra jutó negyedéves forgalom –, egy szervezet teljesítményének nyomonkövetésére használhatók.
+CUBEMEMBER = KOCKA.TAG ## Kockahierachia tagját vagy rekordját adja eredményül. Ellenőrizhető vele, hogy szerepel-e a kockában az adott tag vagy rekord.
+CUBEMEMBERPROPERTY = KOCKA.TAG.TUL ## A kocka egyik tagtulajdonságának értékét adja eredményül. Használatával ellenőrizhető, hogy szerepel-e egy tagnév a kockában, eredménye pedig az erre a tagra vonatkozó, megadott tulajdonság.
+CUBERANKEDMEMBER = KOCKA.HALM.ELEM ## Egy halmaz rangsor szerinti n-edik tagját adja eredményül. Használatával egy halmaz egy vagy több elemét kaphatja meg, például a legnagyobb teljesítményű üzletkötőt vagy a 10 legjobb tanulót.
+CUBESET = KOCKA.HALM ## Számított tagok vagy rekordok halmazát adja eredményül, ehhez egy beállított kifejezést elküld a kiszolgálón található kockának, majd ezt a halmazt adja vissza a Microsoft Office Excel alkalmazásnak.
+CUBESETCOUNT = KOCKA.HALM.DB ## Egy halmaz elemszámát adja eredményül.
+CUBEVALUE = KOCKA.ÉRTÉK ## Kockából összesített értéket ad eredményül.
+
+
+##
+## Database functions Adatbázis-kezelő függvények
+##
+DAVERAGE = AB.ÁTLAG ## A kijelölt adatbáziselemek átlagát számítja ki.
+DCOUNT = AB.DARAB ## Megszámolja, hogy az adatbázisban hány cella tartalmaz számokat.
+DCOUNTA = AB.DARAB2 ## Megszámolja az adatbázisban lévő nem üres cellákat.
+DGET = AB.MEZŐ ## Egy adatbázisból egyetlen olyan rekordot ad vissza, amely megfelel a megadott feltételeknek.
+DMAX = AB.MAX ## A kiválasztott adatbáziselemek közül a legnagyobb értéket adja eredményül.
+DMIN = AB.MIN ## A kijelölt adatbáziselemek közül a legkisebb értéket adja eredményül.
+DPRODUCT = AB.SZORZAT ## Az adatbázis megadott feltételeknek eleget tevő rekordjaira összeszorozza a megadott mezőben található számértékeket, és eredményül ezt a szorzatot adja.
+DSTDEV = AB.SZÓRÁS ## A kijelölt adatbáziselemek egy mintája alapján megbecsüli a szórást.
+DSTDEVP = AB.SZÓRÁS2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórást.
+DSUM = AB.SZUM ## Összeadja a feltételnek megfelelő adatbázisrekordok mezőoszlopában a számokat.
+DVAR = AB.VAR ## A kijelölt adatbáziselemek mintája alapján becslést ad a szórásnégyzetre.
+DVARP = AB.VAR2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórásnégyzetet.
+
+
+##
+## Date and time functions Dátumfüggvények
+##
+DATE = DÁTUM ## Adott dátum dátumértékét adja eredményül.
+DATEVALUE = DÁTUMÉRTÉK ## Szövegként megadott dátumot dátumértékké alakít át.
+DAY = NAP ## Dátumértéket a hónap egy napjává (0-31) alakít.
+DAYS360 = NAP360 ## Két dátum közé eső napok számát számítja ki a 360 napos év alapján.
+EDATE = EDATE ## Adott dátumnál adott számú hónappal korábbi vagy későbbi dátum dátumértékét adja eredményül.
+EOMONTH = EOMONTH ## Adott dátumnál adott számú hónappal korábbi vagy későbbi hónap utolsó napjának dátumértékét adja eredményül.
+HOUR = ÓRA ## Időértéket órákká alakít.
+MINUTE = PERC ## Időértéket percekké alakít.
+MONTH = HÓNAP ## Időértéket hónapokká alakít.
+NETWORKDAYS = NETWORKDAYS ## Két dátum között a teljes munkanapok számát adja meg.
+NOW = MOST ## A napi dátum dátumértékét és a pontos idő időértékét adja eredményül.
+SECOND = MPERC ## Időértéket másodpercekké alakít át.
+TIME = IDŐ ## Adott időpont időértékét adja meg.
+TIMEVALUE = IDŐÉRTÉK ## Szövegként megadott időpontot időértékké alakít át.
+TODAY = MA ## A napi dátum dátumértékét adja eredményül.
+WEEKDAY = HÉT.NAPJA ## Dátumértéket a hét napjává alakítja át.
+WEEKNUM = WEEKNUM ## Visszatérési értéke egy szám, amely azt mutatja meg, hogy a megadott dátum az év hányadik hetére esik.
+WORKDAY = WORKDAY ## Adott dátumnál adott munkanappal korábbi vagy későbbi dátum dátumértékét adja eredményül.
+YEAR = ÉV ## Sorszámot évvé alakít át.
+YEARFRAC = YEARFRAC ## Az adott dátumok közötti teljes napok számát törtévként adja meg.
+
+
+##
+## Engineering functions Mérnöki függvények
+##
+BESSELI = BESSELI ## Az In(x) módosított Bessel-függvény értékét adja eredményül.
+BESSELJ = BESSELJ ## A Jn(x) Bessel-függvény értékét adja eredményül.
+BESSELK = BESSELK ## A Kn(x) módosított Bessel-függvény értékét adja eredményül.
+BESSELY = BESSELY ## Az Yn(x) módosított Bessel-függvény értékét adja eredményül.
+BIN2DEC = BIN2DEC ## Bináris számot decimálissá alakít át.
+BIN2HEX = BIN2HEX ## Bináris számot hexadecimálissá alakít át.
+BIN2OCT = BIN2OCT ## Bináris számot oktálissá alakít át.
+COMPLEX = COMPLEX ## Valós és képzetes részből komplex számot képez.
+CONVERT = CONVERT ## Mértékegységeket vált át.
+DEC2BIN = DEC2BIN ## Decimális számot binárissá alakít át.
+DEC2HEX = DEC2HEX ## Decimális számot hexadecimálissá alakít át.
+DEC2OCT = DEC2OCT ## Decimális számot oktálissá alakít át.
+DELTA = DELTA ## Azt vizsgálja, hogy két érték egyenlő-e.
+ERF = ERF ## A hibafüggvény értékét adja eredményül.
+ERFC = ERFC ## A kiegészített hibafüggvény értékét adja eredményül.
+GESTEP = GESTEP ## Azt vizsgálja, hogy egy szám nagyobb-e adott küszöbértéknél.
+HEX2BIN = HEX2BIN ## Hexadecimális számot binárissá alakít át.
+HEX2DEC = HEX2DEC ## Hexadecimális számot decimálissá alakít át.
+HEX2OCT = HEX2OCT ## Hexadecimális számot oktálissá alakít át.
+IMABS = IMABS ## Komplex szám abszolút értékét (modulusát) adja eredményül.
+IMAGINARY = IMAGINARY ## Komplex szám képzetes részét adja eredményül.
+IMARGUMENT = IMARGUMENT ## A komplex szám radiánban kifejezett théta argumentumát adja eredményül.
+IMCONJUGATE = IMCONJUGATE ## Komplex szám komplex konjugáltját adja eredményül.
+IMCOS = IMCOS ## Komplex szám koszinuszát adja eredményül.
+IMDIV = IMDIV ## Két komplex szám hányadosát adja eredményül.
+IMEXP = IMEXP ## Az e szám komplex kitevőjű hatványát adja eredményül.
+IMLN = IMLN ## Komplex szám természetes logaritmusát adja eredményül.
+IMLOG10 = IMLOG10 ## Komplex szám tízes alapú logaritmusát adja eredményül.
+IMLOG2 = IMLOG2 ## Komplex szám kettes alapú logaritmusát adja eredményül.
+IMPOWER = IMPOWER ## Komplex szám hatványát adja eredményül.
+IMPRODUCT = IMPRODUCT ## Komplex számok szorzatát adja eredményül.
+IMREAL = IMREAL ## Komplex szám valós részét adja eredményül.
+IMSIN = IMSIN ## Komplex szám szinuszát adja eredményül.
+IMSQRT = IMSQRT ## Komplex szám négyzetgyökét adja eredményül.
+IMSUB = IMSUB ## Két komplex szám különbségét adja eredményül.
+IMSUM = IMSUM ## Komplex számok összegét adja eredményül.
+OCT2BIN = OCT2BIN ## Oktális számot binárissá alakít át.
+OCT2DEC = OCT2DEC ## Oktális számot decimálissá alakít át.
+OCT2HEX = OCT2HEX ## Oktális számot hexadecimálissá alakít át.
+
+
+##
+## Financial functions Pénzügyi függvények
+##
+ACCRINT = ACCRINT ## Periodikusan kamatozó értékpapír felszaporodott kamatát adja eredményül.
+ACCRINTM = ACCRINTM ## Lejáratkor kamatozó értékpapír felszaporodott kamatát adja eredményül.
+AMORDEGRC = AMORDEGRC ## Állóeszköz lineáris értékcsökkenését adja meg az egyes könyvelési időszakokra vonatkozóan.
+AMORLINC = AMORLINC ## Az egyes könyvelési időszakokban az értékcsökkenést adja meg.
+COUPDAYBS = COUPDAYBS ## A szelvényidőszak kezdetétől a kifizetés időpontjáig eltelt napokat adja vissza.
+COUPDAYS = COUPDAYS ## A kifizetés időpontját magában foglaló szelvényperiódus hosszát adja meg napokban.
+COUPDAYSNC = COUPDAYSNC ## A kifizetés időpontja és a legközelebbi szelvénydátum közötti napok számát adja meg.
+COUPNCD = COUPNCD ## A kifizetést követő legelső szelvénydátumot adja eredményül.
+COUPNUM = COUPNUM ## A kifizetés és a lejárat időpontja között kifizetendő szelvények számát adja eredményül.
+COUPPCD = COUPPCD ## A kifizetés előtti utolsó szelvénydátumot adja eredményül.
+CUMIPMT = CUMIPMT ## Két fizetési időszak között kifizetett kamat halmozott értékét adja eredményül.
+CUMPRINC = CUMPRINC ## Két fizetési időszak között kifizetett részletek halmozott (kamatot nem tartalmazó) értékét adja eredményül.
+DB = KCS2 ## Eszköz adott időszak alatti értékcsökkenését számítja ki a lineáris leírási modell alkalmazásával.
+DDB = KCSA ## Eszköz értékcsökkenését számítja ki adott időszakra vonatkozóan a progresszív vagy egyéb megadott leírási modell alkalmazásával.
+DISC = DISC ## Értékpapír leszámítolási kamatlábát adja eredményül.
+DOLLARDE = DOLLARDE ## Egy közönséges törtként megadott számot tizedes törtté alakít át.
+DOLLARFR = DOLLARFR ## Tizedes törtként megadott számot közönséges törtté alakít át.
+DURATION = DURATION ## Periodikus kamatfizetésű értékpapír éves kamatérzékenységét adja eredményül.
+EFFECT = EFFECT ## Az éves tényleges kamatláb értékét adja eredményül.
+FV = JBÉ ## Befektetés jövőbeli értékét számítja ki.
+FVSCHEDULE = FVSCHEDULE ## A kezdőtőke adott kamatlábak szerint megnövelt jövőbeli értékét adja eredményül.
+INTRATE = INTRATE ## A lejáratig teljesen lekötött értékpapír kamatrátáját adja eredményül.
+IPMT = RRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra.
+IRR = BMR ## A befektetés belső megtérülési rátáját számítja ki pénzáramláshoz.
+ISPMT = LRÉSZLETKAMAT ## A befektetés adott időszakára fizetett kamatot számítja ki.
+MDURATION = MDURATION ## Egy 100 Ft névértékű értékpapír Macauley-féle módosított kamatérzékenységét adja eredményül.
+MIRR = MEGTÉRÜLÉS ## A befektetés belső megtérülési rátáját számítja ki a költségek és a bevételek különböző kamatlába mellett.
+NOMINAL = NOMINAL ## Az éves névleges kamatláb értékét adja eredményül.
+NPER = PER.SZÁM ## A törlesztési időszakok számát adja meg.
+NPV = NMÉ ## Befektetéshez kapcsolódó pénzáramlás nettó jelenértékét számítja ki ismert pénzáramlás és kamatláb mellett.
+ODDFPRICE = ODDFPRICE ## Egy 100 Ft névértékű, a futamidő elején töredék-időszakos értékpapír árát adja eredményül.
+ODDFYIELD = ODDFYIELD ## A futamidő elején töredék-időszakos értékpapír hozamát adja eredményül.
+ODDLPRICE = ODDLPRICE ## Egy 100 Ft névértékű, a futamidő végén töredék-időszakos értékpapír árát adja eredményül.
+ODDLYIELD = ODDLYIELD ## A futamidő végén töredék-időszakos értékpapír hozamát adja eredményül.
+PMT = RÉSZLET ## A törlesztési időszakra vonatkozó törlesztési összeget számítja ki.
+PPMT = PRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra.
+PRICE = PRICE ## Egy 100 Ft névértékű, periodikusan kamatozó értékpapír árát adja eredményül.
+PRICEDISC = PRICEDISC ## Egy 100 Ft névértékű leszámítolt értékpapír árát adja eredményül.
+PRICEMAT = PRICEMAT ## Egy 100 Ft névértékű, a lejáratkor kamatozó értékpapír árát adja eredményül.
+PV = MÉ ## Befektetés jelenlegi értékét számítja ki.
+RATE = RÁTA ## Egy törlesztési időszakban az egy időszakra eső kamatláb nagyságát számítja ki.
+RECEIVED = RECEIVED ## A lejáratig teljesen lekötött értékpapír lejáratakor kapott összegét adja eredményül.
+SLN = LCSA ## Tárgyi eszköz egy időszakra eső amortizációját adja meg bruttó érték szerinti lineáris leírási kulcsot alkalmazva.
+SYD = SYD ## Tárgyi eszköz értékcsökkenését számítja ki adott időszakra az évek számjegyösszegével dolgozó módszer alapján.
+TBILLEQ = TBILLEQ ## Kincstárjegy kötvény-egyenértékű hozamát adja eredményül.
+TBILLPRICE = TBILLPRICE ## Egy 100 Ft névértékű kincstárjegy árát adja eredményül.
+TBILLYIELD = TBILLYIELD ## Kincstárjegy hozamát adja eredményül.
+VDB = ÉCSRI ## Tárgyi eszköz amortizációját számítja ki megadott vagy részidőszakra a csökkenő egyenleg módszerének alkalmazásával.
+XIRR = XIRR ## Ütemezett készpénzforgalom (cash flow) belső megtérülési kamatrátáját adja eredményül.
+XNPV = XNPV ## Ütemezett készpénzforgalom (cash flow) nettó jelenlegi értékét adja eredményül.
+YIELD = YIELD ## Periodikusan kamatozó értékpapír hozamát adja eredményül.
+YIELDDISC = YIELDDISC ## Leszámítolt értékpapír (például kincstárjegy) éves hozamát adja eredményül.
+YIELDMAT = YIELDMAT ## Lejáratkor kamatozó értékpapír éves hozamát adja eredményül.
+
+
+##
+## Information functions Információs függvények
+##
+CELL = CELLA ## Egy cella formátumára, elhelyezkedésére vagy tartalmára vonatkozó adatokat ad eredményül.
+ERROR.TYPE = HIBA.TÍPUS ## Egy hibatípushoz tartozó számot ad eredményül.
+INFO = INFÓ ## A rendszer- és munkakörnyezet pillanatnyi állapotáról ad felvilágosítást.
+ISBLANK = ÜRES ## Eredménye IGAZ, ha az érték üres.
+ISERR = HIBA ## Eredménye IGAZ, ha az érték valamelyik hibaérték a #HIÁNYZIK kivételével.
+ISERROR = HIBÁS ## Eredménye IGAZ, ha az érték valamelyik hibaérték.
+ISEVEN = ISEVEN ## Eredménye IGAZ, ha argumentuma páros szám.
+ISLOGICAL = LOGIKAI ## Eredménye IGAZ, ha az érték logikai érték.
+ISNA = NINCS ## Eredménye IGAZ, ha az érték a #HIÁNYZIK hibaérték.
+ISNONTEXT = NEM.SZÖVEG ## Eredménye IGAZ, ha az érték nem szöveg.
+ISNUMBER = SZÁM ## Eredménye IGAZ, ha az érték szám.
+ISODD = ISODD ## Eredménye IGAZ, ha argumentuma páratlan szám.
+ISREF = HIVATKOZÁS ## Eredménye IGAZ, ha az érték hivatkozás.
+ISTEXT = SZÖVEG.E ## Eredménye IGAZ, ha az érték szöveg.
+N = N ## Argumentumának értékét számmá alakítja.
+NA = HIÁNYZIK ## Eredménye a #HIÁNYZIK hibaérték.
+TYPE = TÍPUS ## Érték adattípusának azonosítószámát adja eredményül.
+
+
+##
+## Logical functions Logikai függvények
+##
+AND = ÉS ## Eredménye IGAZ, ha minden argumentuma IGAZ.
+FALSE = HAMIS ## A HAMIS logikai értéket adja eredményül.
+IF = HA ## Logikai vizsgálatot hajt végre.
+IFERROR = HAHIBA ## A megadott értéket adja vissza, ha egy képlet hibához vezet; más esetben a képlet értékét adja eredményül.
+NOT = NEM ## Argumentuma értékének ellentettjét adja eredményül.
+OR = VAGY ## Eredménye IGAZ, ha bármely argumentuma IGAZ.
+TRUE = IGAZ ## Az IGAZ logikai értéket adja eredményül.
+
+
+##
+## Lookup and reference functions Keresési és hivatkozási függvények
+##
+ADDRESS = CÍM ## A munkalap egy cellájára való hivatkozást adja szövegként eredményül.
+AREAS = TERÜLET ## Hivatkozásban a területek számát adja eredményül.
+CHOOSE = VÁLASZT ## Értékek listájából választ ki egy elemet.
+COLUMN = OSZLOP ## Egy hivatkozás oszlopszámát adja eredményül.
+COLUMNS = OSZLOPOK ## A hivatkozásban található oszlopok számát adja eredményül.
+HLOOKUP = VKERES ## A megadott tömb felső sorában adott értékű elemet keres, és a megtalált elem oszlopából adott sorban elhelyezkedő értékkel tér vissza.
+HYPERLINK = HIPERHIVATKOZÁS ## Hálózati kiszolgálón, intraneten vagy az interneten tárolt dokumentumot megnyitó parancsikont vagy hivatkozást hoz létre.
+INDEX = INDEX ## Tömb- vagy hivatkozás indexszel megadott értékét adja vissza.
+INDIRECT = INDIREKT ## Szöveg megadott hivatkozást ad eredményül.
+LOOKUP = KERES ## Vektorban vagy tömbben keres meg értékeket.
+MATCH = HOL.VAN ## Hivatkozásban vagy tömbben értékeket keres.
+OFFSET = OFSZET ## Hivatkozás egy másik hivatkozástól számított távolságát adja meg.
+ROW = SOR ## Egy hivatkozás sorának számát adja meg.
+ROWS = SOROK ## Egy hivatkozás sorainak számát adja meg.
+RTD = RTD ## Valós idejű adatokat keres vissza a COM automatizmust (automatizálás: Egy alkalmazás objektumaival való munka másik alkalmazásból vagy fejlesztőeszközből. A korábban OLE automatizmusnak nevezett automatizálás iparági szabvány, a Component Object Model (COM) szolgáltatása.) támogató programból.
+TRANSPOSE = TRANSZPONÁLÁS ## Egy tömb transzponáltját adja eredményül.
+VLOOKUP = FKERES ## A megadott tömb bal szélső oszlopában megkeres egy értéket, majd annak sora és a megadott oszlop metszéspontjában levő értéked adja eredményül.
+
+
+##
+## Math and trigonometry functions Matematikai és trigonometrikus függvények
+##
+ABS = ABS ## Egy szám abszolút értékét adja eredményül.
+ACOS = ARCCOS ## Egy szám arkusz koszinuszát számítja ki.
+ACOSH = ACOSH ## Egy szám inverz koszinusz hiperbolikuszát számítja ki.
+ASIN = ARCSIN ## Egy szám arkusz szinuszát számítja ki.
+ASINH = ASINH ## Egy szám inverz szinusz hiperbolikuszát számítja ki.
+ATAN = ARCTAN ## Egy szám arkusz tangensét számítja ki.
+ATAN2 = ARCTAN2 ## X és y koordináták alapján számítja ki az arkusz tangens értéket.
+ATANH = ATANH ## A szám inverz tangens hiperbolikuszát számítja ki.
+CEILING = PLAFON ## Egy számot a legközelebbi egészre vagy a pontosságként megadott érték legközelebb eső többszörösére kerekít.
+COMBIN = KOMBINÁCIÓK ## Adott számú objektum összes lehetséges kombinációinak számát számítja ki.
+COS = COS ## Egy szám koszinuszát számítja ki.
+COSH = COSH ## Egy szám koszinusz hiperbolikuszát számítja ki.
+DEGREES = FOK ## Radiánt fokká alakít át.
+EVEN = PÁROS ## Egy számot a legközelebbi páros egész számra kerekít.
+EXP = KITEVŐ ## Az e adott kitevőjű hatványát adja eredményül.
+FACT = FAKT ## Egy szám faktoriálisát számítja ki.
+FACTDOUBLE = FACTDOUBLE ## Egy szám dupla faktoriálisát adja eredményül.
+FLOOR = PADLÓ ## Egy számot lefelé, a nulla felé kerekít.
+GCD = GCD ## A legnagyobb közös osztót adja eredményül.
+INT = INT ## Egy számot lefelé kerekít a legközelebbi egészre.
+LCM = LCM ## A legkisebb közös többszöröst adja eredményül.
+LN = LN ## Egy szám természetes logaritmusát számítja ki.
+LOG = LOG ## Egy szám adott alapú logaritmusát számítja ki.
+LOG10 = LOG10 ## Egy szám 10-es alapú logaritmusát számítja ki.
+MDETERM = MDETERM ## Egy tömb mátrix-determinánsát számítja ki.
+MINVERSE = INVERZ.MÁTRIX ## Egy tömb mátrix inverzét adja eredményül.
+MMULT = MSZORZAT ## Két tömb mátrix-szorzatát adja meg.
+MOD = MARADÉK ## Egy szám osztási maradékát adja eredményül.
+MROUND = MROUND ## A kívánt többszörösére kerekített értéket ad eredményül.
+MULTINOMIAL = MULTINOMIAL ## Számhalmaz multinomiálisát adja eredményül.
+ODD = PÁRATLAN ## Egy számot a legközelebbi páratlan számra kerekít.
+PI = PI ## A pi matematikai állandót adja vissza.
+POWER = HATVÁNY ## Egy szám adott kitevőjű hatványát számítja ki.
+PRODUCT = SZORZAT ## Argumentumai szorzatát számítja ki.
+QUOTIENT = QUOTIENT ## Egy hányados egész részét adja eredményül.
+RADIANS = RADIÁN ## Fokot radiánná alakít át.
+RAND = VÉL ## Egy 0 és 1 közötti véletlen számot ad eredményül.
+RANDBETWEEN = RANDBETWEEN ## Megadott számok közé eső véletlen számot állít elő.
+ROMAN = RÓMAI ## Egy számot római számokkal kifejezve szövegként ad eredményül.
+ROUND = KEREKÍTÉS ## Egy számot adott számú számjegyre kerekít.
+ROUNDDOWN = KEREKÍTÉS.LE ## Egy számot lefelé, a nulla felé kerekít.
+ROUNDUP = KEREKÍTÉS.FEL ## Egy számot felfelé, a nullától távolabbra kerekít.
+SERIESSUM = SERIESSUM ## Hatványsor összegét adja eredményül.
+SIGN = ELŐJEL ## Egy szám előjelét adja meg.
+SIN = SIN ## Egy szög szinuszát számítja ki.
+SINH = SINH ## Egy szám szinusz hiperbolikuszát számítja ki.
+SQRT = GYÖK ## Egy szám pozitív négyzetgyökét számítja ki.
+SQRTPI = SQRTPI ## A (szám*pi) négyzetgyökét adja eredményül.
+SUBTOTAL = RÉSZÖSSZEG ## Lista vagy adatbázis részösszegét adja eredményül.
+SUM = SZUM ## Összeadja az argumentumlistájában lévő számokat.
+SUMIF = SZUMHA ## A megadott feltételeknek eleget tevő cellákban található értékeket adja össze.
+SUMIFS = SZUMHATÖBB ## Több megadott feltételnek eleget tévő tartománycellák összegét adja eredményül.
+SUMPRODUCT = SZORZATÖSSZEG ## A megfelelő tömbelemek szorzatának összegét számítja ki.
+SUMSQ = NÉGYZETÖSSZEG ## Argumentumai négyzetének összegét számítja ki.
+SUMX2MY2 = SZUMX2BŐLY2 ## Két tömb megfelelő elemei négyzetének különbségét összegzi.
+SUMX2PY2 = SZUMX2MEGY2 ## Két tömb megfelelő elemei négyzetének összegét összegzi.
+SUMXMY2 = SZUMXBŐLY2 ## Két tömb megfelelő elemei különbségének négyzetösszegét számítja ki.
+TAN = TAN ## Egy szám tangensét számítja ki.
+TANH = TANH ## Egy szám tangens hiperbolikuszát számítja ki.
+TRUNC = CSONK ## Egy számot egésszé csonkít.
+
+
+##
+## Statistical functions Statisztikai függvények
+##
+AVEDEV = ÁTL.ELTÉRÉS ## Az adatpontoknak átlaguktól való átlagos abszolút eltérését számítja ki.
+AVERAGE = ÁTLAG ## Argumentumai átlagát számítja ki.
+AVERAGEA = ÁTLAGA ## Argumentumai átlagát számítja ki (beleértve a számokat, szöveget és logikai értékeket).
+AVERAGEIF = ÁTLAGHA ## A megadott feltételnek eleget tévő tartomány celláinak átlagát (számtani közepét) adja eredményül.
+AVERAGEIFS = ÁTLAGHATÖBB ## A megadott feltételeknek eleget tévő cellák átlagát (számtani közepét) adja eredményül.
+BETADIST = BÉTA.ELOSZLÁS ## A béta-eloszlás függvényt számítja ki.
+BETAINV = INVERZ.BÉTA ## Adott béta-eloszláshoz kiszámítja a béta eloszlásfüggvény inverzét.
+BINOMDIST = BINOM.ELOSZLÁS ## A diszkrét binomiális eloszlás valószínűségértékét számítja ki.
+CHIDIST = KHI.ELOSZLÁS ## A khi-négyzet-eloszlás egyszélű valószínűségértékét számítja ki.
+CHIINV = INVERZ.KHI ## A khi-négyzet-eloszlás egyszélű valószínűségértékének inverzét számítja ki.
+CHITEST = KHI.PRÓBA ## Függetlenségvizsgálatot hajt végre.
+CONFIDENCE = MEGBÍZHATÓSÁG ## Egy statisztikai sokaság várható értékének megbízhatósági intervallumát adja eredményül.
+CORREL = KORREL ## Két adathalmaz korrelációs együtthatóját számítja ki.
+COUNT = DARAB ## Megszámolja, hogy argumentumlistájában hány szám található.
+COUNTA = DARAB2 ## Megszámolja, hogy argumentumlistájában hány érték található.
+COUNTBLANK = DARABÜRES ## Egy tartományban összeszámolja az üres cellákat.
+COUNTIF = DARABTELI ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek a megadott feltételnek.
+COUNTIFS = DARABHATÖBB ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek több feltételnek.
+COVAR = KOVAR ## A kovarianciát, azaz a páronkénti eltérések szorzatának átlagát számítja ki.
+CRITBINOM = KRITBINOM ## Azt a legkisebb számot adja eredményül, amelyre a binomiális eloszlásfüggvény értéke nem kisebb egy adott határértéknél.
+DEVSQ = SQ ## Az átlagtól való eltérések négyzetének összegét számítja ki.
+EXPONDIST = EXP.ELOSZLÁS ## Az exponenciális eloszlás értékét számítja ki.
+FDIST = F.ELOSZLÁS ## Az F-eloszlás értékét számítja ki.
+FINV = INVERZ.F ## Az F-eloszlás inverzének értékét számítja ki.
+FISHER = FISHER ## Fisher-transzformációt hajt végre.
+FISHERINV = INVERZ.FISHER ## A Fisher-transzformáció inverzét hajtja végre.
+FORECAST = ELŐREJELZÉS ## Az ismert értékek alapján lineáris regresszióval becsült értéket ad eredményül.
+FREQUENCY = GYAKORISÁG ## A gyakorisági vagy empirikus eloszlás értékét függőleges tömbként adja eredményül.
+FTEST = F.PRÓBA ## Az F-próba értékét adja eredményül.
+GAMMADIST = GAMMA.ELOSZLÁS ## A gamma-eloszlás értékét számítja ki.
+GAMMAINV = INVERZ.GAMMA ## A gamma-eloszlás eloszlásfüggvénye inverzének értékét számítja ki.
+GAMMALN = GAMMALN ## A gamma-függvény természetes logaritmusát számítja ki.
+GEOMEAN = MÉRTANI.KÖZÉP ## Argumentumai mértani középértékét számítja ki.
+GROWTH = NÖV ## Exponenciális regresszió alapján ad becslést.
+HARMEAN = HARM.KÖZÉP ## Argumentumai harmonikus átlagát számítja ki.
+HYPGEOMDIST = HIPERGEOM.ELOSZLÁS ## A hipergeometriai eloszlás értékét számítja ki.
+INTERCEPT = METSZ ## A regressziós egyenes y tengellyel való metszéspontját határozza meg.
+KURT = CSÚCSOSSÁG ## Egy adathalmaz csúcsosságát számítja ki.
+LARGE = NAGY ## Egy adathalmaz k-adik legnagyobb elemét adja eredményül.
+LINEST = LIN.ILL ## A legkisebb négyzetek módszerével az adatokra illesztett egyenes paramétereit határozza meg.
+LOGEST = LOG.ILL ## Az adatokra illesztett exponenciális görbe paramétereit határozza meg.
+LOGINV = INVERZ.LOG.ELOSZLÁS ## A lognormális eloszlás inverzét számítja ki.
+LOGNORMDIST = LOG.ELOSZLÁS ## A lognormális eloszlásfüggvény értékét számítja ki.
+MAX = MAX ## Az argumentumai között szereplő legnagyobb számot adja meg.
+MAXA = MAX2 ## Az argumentumai között szereplő legnagyobb számot adja meg (beleértve a számokat, szöveget és logikai értékeket).
+MEDIAN = MEDIÁN ## Adott számhalmaz mediánját számítja ki.
+MIN = MIN ## Az argumentumai között szereplő legkisebb számot adja meg.
+MINA = MIN2 ## Az argumentumai között szereplő legkisebb számot adja meg, beleértve a számokat, szöveget és logikai értékeket.
+MODE = MÓDUSZ ## Egy adathalmazból kiválasztja a leggyakrabban előforduló számot.
+NEGBINOMDIST = NEGBINOM.ELOSZL ## A negatív binomiális eloszlás értékét számítja ki.
+NORMDIST = NORM.ELOSZL ## A normális eloszlás értékét számítja ki.
+NORMINV = INVERZ.NORM ## A normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki.
+NORMSDIST = STNORMELOSZL ## A standard normális eloszlás eloszlásfüggvényének értékét számítja ki.
+NORMSINV = INVERZ.STNORM ## A standard normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki.
+PEARSON = PEARSON ## A Pearson-féle korrelációs együtthatót számítja ki.
+PERCENTILE = PERCENTILIS ## Egy tartományban található értékek k-adik percentilisét, azaz százalékosztályát adja eredményül.
+PERCENTRANK = SZÁZALÉKRANG ## Egy értéknek egy adathalmazon belül vett százalékos rangját (elhelyezkedését) számítja ki.
+PERMUT = VARIÁCIÓK ## Adott számú objektum k-ad osztályú ismétlés nélküli variációinak számát számítja ki.
+POISSON = POISSON ## A Poisson-eloszlás értékét számítja ki.
+PROB = VALÓSZÍNŰSÉG ## Annak valószínűségét számítja ki, hogy adott értékek két határérték közé esnek.
+QUARTILE = KVARTILIS ## Egy adathalmaz kvartilisét (negyedszintjét) számítja ki.
+RANK = SORSZÁM ## Kiszámítja, hogy egy szám hányadik egy számsorozatban.
+RSQ = RNÉGYZET ## Kiszámítja a Pearson-féle szorzatmomentum korrelációs együtthatójának négyzetét.
+SKEW = FERDESÉG ## Egy eloszlás ferdeségét határozza meg.
+SLOPE = MEREDEKSÉG ## Egy lineáris regressziós egyenes meredekségét számítja ki.
+SMALL = KICSI ## Egy adathalmaz k-adik legkisebb elemét adja meg.
+STANDARDIZE = NORMALIZÁLÁS ## Normalizált értéket ad eredményül.
+STDEV = SZÓRÁS ## Egy statisztikai sokaság mintájából kiszámítja annak szórását.
+STDEVA = SZÓRÁSA ## Egy statisztikai sokaság mintájából kiszámítja annak szórását (beleértve a számokat, szöveget és logikai értékeket).
+STDEVP = SZÓRÁSP ## Egy statisztikai sokaság egészéből kiszámítja annak szórását.
+STDEVPA = SZÓRÁSPA ## Egy statisztikai sokaság egészéből kiszámítja annak szórását (beleértve számokat, szöveget és logikai értékeket).
+STEYX = STHIBAYX ## Egy regresszió esetén az egyes x-értékek alapján meghatározott y-értékek standard hibáját számítja ki.
+TDIST = T.ELOSZLÁS ## A Student-féle t-eloszlás értékét számítja ki.
+TINV = INVERZ.T ## A Student-féle t-eloszlás inverzét számítja ki.
+TREND = TREND ## Lineáris trend értékeit számítja ki.
+TRIMMEAN = RÉSZÁTLAG ## Egy adathalmaz középső részének átlagát számítja ki.
+TTEST = T.PRÓBA ## A Student-féle t-próbához tartozó valószínűséget számítja ki.
+VAR = VAR ## Minta alapján becslést ad a varianciára.
+VARA = VARA ## Minta alapján becslést ad a varianciára (beleértve számokat, szöveget és logikai értékeket).
+VARP = VARP ## Egy statisztikai sokaság varianciáját számítja ki.
+VARPA = VARPA ## Egy statisztikai sokaság varianciáját számítja ki (beleértve számokat, szöveget és logikai értékeket).
+WEIBULL = WEIBULL ## A Weibull-féle eloszlás értékét számítja ki.
+ZTEST = Z.PRÓBA ## Az egyszélű z-próbával kapott valószínűségértéket számítja ki.
+
+
+##
+## Text functions Szövegműveletekhez használható függvények
+##
+ASC = ASC ## Szöveg teljes szélességű (kétbájtos) latin és katakana karaktereit félszélességű (egybájtos) karakterekké alakítja.
+BAHTTEXT = BAHTSZÖVEG ## Számot szöveggé alakít a ß (baht) pénznemformátum használatával.
+CHAR = KARAKTER ## A kódszámmal meghatározott karaktert adja eredményül.
+CLEAN = TISZTÍT ## A szövegből eltávolítja az összes nem nyomtatható karaktert.
+CODE = KÓD ## Karaktersorozat első karakterének numerikus kódját adja eredményül.
+CONCATENATE = ÖSSZEFŰZ ## Több szövegelemet egyetlen szöveges elemmé fűz össze.
+DOLLAR = FORINT ## Számot pénznem formátumú szöveggé alakít át.
+EXACT = AZONOS ## Megvizsgálja, hogy két érték azonos-e.
+FIND = SZÖVEG.TALÁL ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével).
+FINDB = SZÖVEG.TALÁL2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével).
+FIXED = FIX ## Számot szöveges formátumúra alakít adott számú tizedesjegyre kerekítve.
+JIS = JIS ## A félszélességű (egybájtos) latin és a katakana karaktereket teljes szélességű (kétbájtos) karakterekké alakítja.
+LEFT = BAL ## Szöveg bal szélső karaktereit adja eredményül.
+LEFTB = BAL2 ## Szöveg bal szélső karaktereit adja eredményül.
+LEN = HOSSZ ## Szöveg karakterekben mért hosszát adja eredményül.
+LENB = HOSSZ2 ## Szöveg karakterekben mért hosszát adja eredményül.
+LOWER = KISBETŰ ## Szöveget kisbetűssé alakít át.
+MID = KÖZÉP ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként.
+MIDB = KÖZÉP2 ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként.
+PHONETIC = PHONETIC ## Szöveg furigana (fonetikus) karaktereit adja vissza.
+PROPER = TNÉV ## Szöveg minden szavának kezdőbetűjét nagybetűsre cseréli.
+REPLACE = CSERE ## A szövegen belül karaktereket cserél.
+REPLACEB = CSERE2 ## A szövegen belül karaktereket cserél.
+REPT = SOKSZOR ## Megadott számú alkalommal megismétel egy szövegrészt.
+RIGHT = JOBB ## Szövegrész jobb szélső karaktereit adja eredményül.
+RIGHTB = JOBB2 ## Szövegrész jobb szélső karaktereit adja eredményül.
+SEARCH = SZÖVEG.KERES ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget).
+SEARCHB = SZÖVEG.KERES2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget).
+SUBSTITUTE = HELYETTE ## Szövegben adott karaktereket másikra cserél.
+T = T ## Argumentumát szöveggé alakítja át.
+TEXT = SZÖVEG ## Számértéket alakít át adott számformátumú szöveggé.
+TRIM = TRIM ## A szövegből eltávolítja a szóközöket.
+UPPER = NAGYBETŰS ## Szöveget nagybetűssé alakít át.
+VALUE = ÉRTÉK ## Szöveget számmá alakít át.
diff --git a/PHPExcel/locale/it/config b/PHPExcel/locale/it/config
new file mode 100644
index 0000000..94499fe
--- /dev/null
+++ b/PHPExcel/locale/it/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = €
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULLO!
+DIV0 = #DIV/0!
+VALUE = #VALORE!
+REF = #RIF!
+NAME = #NOME?
+NUM = #NUM!
+NA = #N/D
diff --git a/PHPExcel/locale/it/functions b/PHPExcel/locale/it/functions
new file mode 100644
index 0000000..033b969
--- /dev/null
+++ b/PHPExcel/locale/it/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Funzioni di automazione e dei componenti aggiuntivi
+##
+GETPIVOTDATA = INFO.DATI.TAB.PIVOT ## Restituisce i dati memorizzati in un rapporto di tabella pivot
+
+
+##
+## Cube functions Funzioni cubo
+##
+CUBEKPIMEMBER = MEMBRO.KPI.CUBO ## Restituisce il nome, la proprietà e la misura di un indicatore di prestazioni chiave (KPI) e visualizza il nome e la proprietà nella cella. Un KPI è una misura quantificabile, ad esempio l'utile lordo mensile o il fatturato trimestrale dei dipendenti, utilizzata per il monitoraggio delle prestazioni di un'organizzazione.
+CUBEMEMBER = MEMBRO.CUBO ## Restituisce un membro o una tupla in una gerarchia di cubi. Consente di verificare l'esistenza del membro o della tupla nel cubo.
+CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO ## Restituisce il valore di una proprietà di un membro del cubo. Consente di verificare l'esistenza di un nome di membro all'interno del cubo e di restituire la proprietà specificata per tale membro.
+CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO ## Restituisce l'n-esimo membro o il membro ordinato di un insieme. Consente di restituire uno o più elementi in un insieme, ad esempio l'agente di vendita migliore o i primi 10 studenti.
+CUBESET = SET.CUBO ## Definisce un insieme di tuple o membri calcolati mediante l'invio di un'espressione di insieme al cubo sul server. In questo modo l'insieme viene creato e restituito a Microsoft Office Excel.
+CUBESETCOUNT = CONTA.SET.CUBO ## Restituisce il numero di elementi di un insieme.
+CUBEVALUE = VALORE.CUBO ## Restituisce un valore aggregato da un cubo.
+
+
+##
+## Database functions Funzioni di database
+##
+DAVERAGE = DB.MEDIA ## Restituisce la media di voci del database selezionate
+DCOUNT = DB.CONTA.NUMERI ## Conta le celle di un database contenenti numeri
+DCOUNTA = DB.CONTA.VALORI ## Conta le celle non vuote in un database
+DGET = DB.VALORI ## Estrae da un database un singolo record che soddisfa i criteri specificati
+DMAX = DB.MAX ## Restituisce il valore massimo dalle voci selezionate in un database
+DMIN = DB.MIN ## Restituisce il valore minimo dalle voci di un database selezionate
+DPRODUCT = DB.PRODOTTO ## Moltiplica i valori in un determinato campo di record che soddisfano i criteri del database
+DSTDEV = DB.DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione di voci di un database selezionate
+DSTDEVP = DB.DEV.ST.POP ## Calcola la deviazione standard sulla base di tutte le voci di un database selezionate
+DSUM = DB.SOMMA ## Aggiunge i numeri nel campo colonna di record del database che soddisfa determinati criteri
+DVAR = DB.VAR ## Restituisce una stima della varianza sulla base di un campione da voci di un database selezionate
+DVARP = DB.VAR.POP ## Calcola la varianza sulla base di tutte le voci di un database selezionate
+
+
+##
+## Date and time functions Funzioni data e ora
+##
+DATE = DATA ## Restituisce il numero seriale di una determinata data
+DATEVALUE = DATA.VALORE ## Converte una data sotto forma di testo in un numero seriale
+DAY = GIORNO ## Converte un numero seriale in un giorno del mese
+DAYS360 = GIORNO360 ## Calcola il numero di giorni compreso tra due date basandosi su un anno di 360 giorni
+EDATE = DATA.MESE ## Restituisce il numero seriale della data che rappresenta il numero di mesi prima o dopo la data di inizio
+EOMONTH = FINE.MESE ## Restituisce il numero seriale dell'ultimo giorno del mese, prima o dopo un determinato numero di mesi
+HOUR = ORA ## Converte un numero seriale in un'ora
+MINUTE = MINUTO ## Converte un numero seriale in un minuto
+MONTH = MESE ## Converte un numero seriale in un mese
+NETWORKDAYS = GIORNI.LAVORATIVI.TOT ## Restituisce il numero di tutti i giorni lavorativi compresi fra due date
+NOW = ADESSO ## Restituisce il numero seriale della data e dell'ora corrente
+SECOND = SECONDO ## Converte un numero seriale in un secondo
+TIME = ORARIO ## Restituisce il numero seriale di una determinata ora
+TIMEVALUE = ORARIO.VALORE ## Converte un orario in forma di testo in un numero seriale
+TODAY = OGGI ## Restituisce il numero seriale relativo alla data odierna
+WEEKDAY = GIORNO.SETTIMANA ## Converte un numero seriale in un giorno della settimana
+WEEKNUM = NUM.SETTIMANA ## Converte un numero seriale in un numero che rappresenta la posizione numerica di una settimana nell'anno
+WORKDAY = GIORNO.LAVORATIVO ## Restituisce il numero della data prima o dopo un determinato numero di giorni lavorativi
+YEAR = ANNO ## Converte un numero seriale in un anno
+YEARFRAC = FRAZIONE.ANNO ## Restituisce la frazione dell'anno che rappresenta il numero dei giorni compresi tra una data_ iniziale e una data_finale
+
+
+##
+## Engineering functions Funzioni ingegneristiche
+##
+BESSELI = BESSEL.I ## Restituisce la funzione di Bessel modificata In(x)
+BESSELJ = BESSEL.J ## Restituisce la funzione di Bessel Jn(x)
+BESSELK = BESSEL.K ## Restituisce la funzione di Bessel modificata Kn(x)
+BESSELY = BESSEL.Y ## Restituisce la funzione di Bessel Yn(x)
+BIN2DEC = BINARIO.DECIMALE ## Converte un numero binario in decimale
+BIN2HEX = BINARIO.HEX ## Converte un numero binario in esadecimale
+BIN2OCT = BINARIO.OCT ## Converte un numero binario in ottale
+COMPLEX = COMPLESSO ## Converte i coefficienti reali e immaginari in numeri complessi
+CONVERT = CONVERTI ## Converte un numero da un sistema di misura in un altro
+DEC2BIN = DECIMALE.BINARIO ## Converte un numero decimale in binario
+DEC2HEX = DECIMALE.HEX ## Converte un numero decimale in esadecimale
+DEC2OCT = DECIMALE.OCT ## Converte un numero decimale in ottale
+DELTA = DELTA ## Verifica se due valori sono uguali
+ERF = FUNZ.ERRORE ## Restituisce la funzione di errore
+ERFC = FUNZ.ERRORE.COMP ## Restituisce la funzione di errore complementare
+GESTEP = SOGLIA ## Verifica se un numero è maggiore del valore di soglia
+HEX2BIN = HEX.BINARIO ## Converte un numero esadecimale in binario
+HEX2DEC = HEX.DECIMALE ## Converte un numero esadecimale in decimale
+HEX2OCT = HEX.OCT ## Converte un numero esadecimale in ottale
+IMABS = COMP.MODULO ## Restituisce il valore assoluto (modulo) di un numero complesso
+IMAGINARY = COMP.IMMAGINARIO ## Restituisce il coefficiente immaginario di un numero complesso
+IMARGUMENT = COMP.ARGOMENTO ## Restituisce l'argomento theta, un angolo espresso in radianti
+IMCONJUGATE = COMP.CONIUGATO ## Restituisce il complesso coniugato del numero complesso
+IMCOS = COMP.COS ## Restituisce il coseno di un numero complesso
+IMDIV = COMP.DIV ## Restituisce il quoziente di due numeri complessi
+IMEXP = COMP.EXP ## Restituisce il valore esponenziale di un numero complesso
+IMLN = COMP.LN ## Restituisce il logaritmo naturale di un numero complesso
+IMLOG10 = COMP.LOG10 ## Restituisce il logaritmo in base 10 di un numero complesso
+IMLOG2 = COMP.LOG2 ## Restituisce un logaritmo in base 2 di un numero complesso
+IMPOWER = COMP.POTENZA ## Restituisce il numero complesso elevato a una potenza intera
+IMPRODUCT = COMP.PRODOTTO ## Restituisce il prodotto di numeri complessi compresi tra 2 e 29
+IMREAL = COMP.PARTE.REALE ## Restituisce il coefficiente reale di un numero complesso
+IMSIN = COMP.SEN ## Restituisce il seno di un numero complesso
+IMSQRT = COMP.RADQ ## Restituisce la radice quadrata di un numero complesso
+IMSUB = COMP.DIFF ## Restituisce la differenza fra due numeri complessi
+IMSUM = COMP.SOMMA ## Restituisce la somma di numeri complessi
+OCT2BIN = OCT.BINARIO ## Converte un numero ottale in binario
+OCT2DEC = OCT.DECIMALE ## Converte un numero ottale in decimale
+OCT2HEX = OCT.HEX ## Converte un numero ottale in esadecimale
+
+
+##
+## Financial functions Funzioni finanziarie
+##
+ACCRINT = INT.MATURATO.PER ## Restituisce l'interesse maturato di un titolo che paga interessi periodici
+ACCRINTM = INT.MATURATO.SCAD ## Restituisce l'interesse maturato di un titolo che paga interessi alla scadenza
+AMORDEGRC = AMMORT.DEGR ## Restituisce l'ammortamento per ogni periodo contabile utilizzando un coefficiente di ammortamento
+AMORLINC = AMMORT.PER ## Restituisce l'ammortamento per ogni periodo contabile
+COUPDAYBS = GIORNI.CED.INIZ.LIQ ## Restituisce il numero dei giorni che vanno dall'inizio del periodo di durata della cedola alla data di liquidazione
+COUPDAYS = GIORNI.CED ## Restituisce il numero dei giorni relativi al periodo della cedola che contiene la data di liquidazione
+COUPDAYSNC = GIORNI.CED.NUOVA ## Restituisce il numero di giorni che vanno dalla data di liquidazione alla data della cedola successiva
+COUPNCD = DATA.CED.SUCC ## Restituisce un numero che rappresenta la data della cedola successiva alla data di liquidazione
+COUPNUM = NUM.CED ## Restituisce il numero di cedole pagabili fra la data di liquidazione e la data di scadenza
+COUPPCD = DATA.CED.PREC ## Restituisce un numero che rappresenta la data della cedola precedente alla data di liquidazione
+CUMIPMT = INT.CUMUL ## Restituisce l'interesse cumulativo pagato fra due periodi
+CUMPRINC = CAP.CUM ## Restituisce il capitale cumulativo pagato per estinguere un debito fra due periodi
+DB = DB ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a quote fisse decrescenti
+DDB = AMMORT ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a doppie quote decrescenti o altri metodi specificati
+DISC = TASSO.SCONTO ## Restituisce il tasso di sconto per un titolo
+DOLLARDE = VALUTA.DEC ## Converte un prezzo valuta, espresso come frazione, in prezzo valuta, espresso come numero decimale
+DOLLARFR = VALUTA.FRAZ ## Converte un prezzo valuta, espresso come numero decimale, in prezzo valuta, espresso come frazione
+DURATION = DURATA ## Restituisce la durata annuale di un titolo con i pagamenti di interesse periodico
+EFFECT = EFFETTIVO ## Restituisce l'effettivo tasso di interesse annuo
+FV = VAL.FUT ## Restituisce il valore futuro di un investimento
+FVSCHEDULE = VAL.FUT.CAPITALE ## Restituisce il valore futuro di un capitale iniziale dopo aver applicato una serie di tassi di interesse composti
+INTRATE = TASSO.INT ## Restituisce il tasso di interesse per un titolo interamente investito
+IPMT = INTERESSI ## Restituisce il valore degli interessi per un investimento relativo a un periodo specifico
+IRR = TIR.COST ## Restituisce il tasso di rendimento interno per una serie di flussi di cassa
+ISPMT = INTERESSE.RATA ## Calcola l'interesse di un investimento pagato durante un periodo specifico
+MDURATION = DURATA.M ## Restituisce la durata Macauley modificata per un titolo con un valore presunto di € 100
+MIRR = TIR.VAR ## Restituisce il tasso di rendimento interno in cui i flussi di cassa positivi e negativi sono finanziati a tassi differenti
+NOMINAL = NOMINALE ## Restituisce il tasso di interesse nominale annuale
+NPER = NUM.RATE ## Restituisce un numero di periodi relativi a un investimento
+NPV = VAN ## Restituisce il valore attuale netto di un investimento basato su una serie di flussi di cassa periodici e sul tasso di sconto
+ODDFPRICE = PREZZO.PRIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente il primo periodo di durata irregolare
+ODDFYIELD = REND.PRIMO.IRR ## Restituisce il rendimento di un titolo avente il primo periodo di durata irregolare
+ODDLPRICE = PREZZO.ULTIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente l'ultimo periodo di durata irregolare
+ODDLYIELD = REND.ULTIMO.IRR ## Restituisce il rendimento di un titolo avente l'ultimo periodo di durata irregolare
+PMT = RATA ## Restituisce il pagamento periodico di una rendita annua
+PPMT = P.RATA ## Restituisce il pagamento sul capitale di un investimento per un dato periodo
+PRICE = PREZZO ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga interessi periodici
+PRICEDISC = PREZZO.SCONT ## Restituisce il prezzo di un titolo scontato dal valore nominale di € 100
+PRICEMAT = PREZZO.SCAD ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga gli interessi alla scadenza
+PV = VA ## Restituisce il valore attuale di un investimento
+RATE = TASSO ## Restituisce il tasso di interesse per un periodo di un'annualità
+RECEIVED = RICEV.SCAD ## Restituisce l'ammontare ricevuto alla scadenza di un titolo interamente investito
+SLN = AMMORT.COST ## Restituisce l'ammortamento a quote costanti di un bene per un singolo periodo
+SYD = AMMORT.ANNUO ## Restituisce l'ammortamento a somma degli anni di un bene per un periodo specificato
+TBILLEQ = BOT.EQUIV ## Restituisce il rendimento equivalente ad un'obbligazione per un Buono ordinario del Tesoro
+TBILLPRICE = BOT.PREZZO ## Restituisce il prezzo di un Buono del Tesoro dal valore nominale di € 100
+TBILLYIELD = BOT.REND ## Restituisce il rendimento di un Buono del Tesoro
+VDB = AMMORT.VAR ## Restituisce l'ammortamento di un bene per un periodo specificato o parziale utilizzando il metodo a doppie quote proporzionali ai valori residui
+XIRR = TIR.X ## Restituisce il tasso di rendimento interno di un impiego di flussi di cassa
+XNPV = VAN.X ## Restituisce il valore attuale netto di un impiego di flussi di cassa non necessariamente periodici
+YIELD = REND ## Restituisce il rendimento di un titolo che frutta interessi periodici
+YIELDDISC = REND.TITOLI.SCONT ## Restituisce il rendimento annuale di un titolo scontato, ad esempio un Buono del Tesoro
+YIELDMAT = REND.SCAD ## Restituisce il rendimento annuo di un titolo che paga interessi alla scadenza
+
+
+##
+## Information functions Funzioni relative alle informazioni
+##
+CELL = CELLA ## Restituisce le informazioni sulla formattazione, la posizione o i contenuti di una cella
+ERROR.TYPE = ERRORE.TIPO ## Restituisce un numero che corrisponde a un tipo di errore
+INFO = INFO ## Restituisce le informazioni sull'ambiente operativo corrente
+ISBLANK = VAL.VUOTO ## Restituisce VERO se il valore è vuoto
+ISERR = VAL.ERR ## Restituisce VERO se il valore è un valore di errore qualsiasi tranne #N/D
+ISERROR = VAL.ERRORE ## Restituisce VERO se il valore è un valore di errore qualsiasi
+ISEVEN = VAL.PARI ## Restituisce VERO se il numero è pari
+ISLOGICAL = VAL.LOGICO ## Restituisce VERO se il valore è un valore logico
+ISNA = VAL.NON.DISP ## Restituisce VERO se il valore è un valore di errore #N/D
+ISNONTEXT = VAL.NON.TESTO ## Restituisce VERO se il valore non è in formato testo
+ISNUMBER = VAL.NUMERO ## Restituisce VERO se il valore è un numero
+ISODD = VAL.DISPARI ## Restituisce VERO se il numero è dispari
+ISREF = VAL.RIF ## Restituisce VERO se il valore è un riferimento
+ISTEXT = VAL.TESTO ## Restituisce VERO se il valore è in formato testo
+N = NUM ## Restituisce un valore convertito in numero
+NA = NON.DISP ## Restituisce il valore di errore #N/D
+TYPE = TIPO ## Restituisce un numero che indica il tipo di dati relativi a un valore
+
+
+##
+## Logical functions Funzioni logiche
+##
+AND = E ## Restituisce VERO se tutti gli argomenti sono VERO
+FALSE = FALSO ## Restituisce il valore logico FALSO
+IF = SE ## Specifica un test logico da eseguire
+IFERROR = SE.ERRORE ## Restituisce un valore specificato se una formula fornisce un errore come risultato; in caso contrario, restituisce il risultato della formula
+NOT = NON ## Inverte la logica degli argomenti
+OR = O ## Restituisce VERO se un argomento qualsiasi è VERO
+TRUE = VERO ## Restituisce il valore logico VERO
+
+
+##
+## Lookup and reference functions Funzioni di ricerca e di riferimento
+##
+ADDRESS = INDIRIZZO ## Restituisce un riferimento come testo in una singola cella di un foglio di lavoro
+AREAS = AREE ## Restituisce il numero di aree in un riferimento
+CHOOSE = SCEGLI ## Sceglie un valore da un elenco di valori
+COLUMN = RIF.COLONNA ## Restituisce il numero di colonna di un riferimento
+COLUMNS = COLONNE ## Restituisce il numero di colonne in un riferimento
+HLOOKUP = CERCA.ORIZZ ## Effettua una ricerca nella riga superiore di una matrice e restituisce il valore della cella specificata
+HYPERLINK = COLLEG.IPERTESTUALE ## Crea un collegamento che apre un documento memorizzato in un server di rete, una rete Intranet o Internet
+INDEX = INDICE ## Utilizza un indice per scegliere un valore da un riferimento o da una matrice
+INDIRECT = INDIRETTO ## Restituisce un riferimento specificato da un valore testo
+LOOKUP = CERCA ## Ricerca i valori in un vettore o in una matrice
+MATCH = CONFRONTA ## Ricerca i valori in un riferimento o in una matrice
+OFFSET = SCARTO ## Restituisce uno scarto di riferimento da un riferimento dato
+ROW = RIF.RIGA ## Restituisce il numero di riga di un riferimento
+ROWS = RIGHE ## Restituisce il numero delle righe in un riferimento
+RTD = DATITEMPOREALE ## Recupera dati in tempo reale da un programma che supporta l'automazione COM (automazione: Metodo per utilizzare gli oggetti di un'applicazione da un'altra applicazione o da un altro strumento di sviluppo. Precedentemente nota come automazione OLE, l'automazione è uno standard del settore e una caratteristica del modello COM (Component Object Model).)
+TRANSPOSE = MATR.TRASPOSTA ## Restituisce la trasposizione di una matrice
+VLOOKUP = CERCA.VERT ## Effettua una ricerca nella prima colonna di una matrice e si sposta attraverso la riga per restituire il valore di una cella
+
+
+##
+## Math and trigonometry functions Funzioni matematiche e trigonometriche
+##
+ABS = ASS ## Restituisce il valore assoluto di un numero.
+ACOS = ARCCOS ## Restituisce l'arcocoseno di un numero
+ACOSH = ARCCOSH ## Restituisce l'inverso del coseno iperbolico di un numero
+ASIN = ARCSEN ## Restituisce l'arcoseno di un numero
+ASINH = ARCSENH ## Restituisce l'inverso del seno iperbolico di un numero
+ATAN = ARCTAN ## Restituisce l'arcotangente di un numero
+ATAN2 = ARCTAN.2 ## Restituisce l'arcotangente delle coordinate x e y specificate
+ATANH = ARCTANH ## Restituisce l'inverso della tangente iperbolica di un numero
+CEILING = ARROTONDA.ECCESSO ## Arrotonda un numero per eccesso all'intero più vicino o al multiplo più vicino a peso
+COMBIN = COMBINAZIONE ## Restituisce il numero di combinazioni possibili per un numero assegnato di elementi
+COS = COS ## Restituisce il coseno dell'angolo specificato
+COSH = COSH ## Restituisce il coseno iperbolico di un numero
+DEGREES = GRADI ## Converte i radianti in gradi
+EVEN = PARI ## Arrotonda il valore assoluto di un numero per eccesso al più vicino intero pari
+EXP = ESP ## Restituisce il numero e elevato alla potenza di num
+FACT = FATTORIALE ## Restituisce il fattoriale di un numero
+FACTDOUBLE = FATT.DOPPIO ## Restituisce il fattoriale doppio di un numero
+FLOOR = ARROTONDA.DIFETTO ## Arrotonda un numero per difetto al multiplo più vicino a zero
+GCD = MCD ## Restituisce il massimo comune divisore
+INT = INT ## Arrotonda un numero per difetto al numero intero più vicino
+LCM = MCM ## Restituisce il minimo comune multiplo
+LN = LN ## Restituisce il logaritmo naturale di un numero
+LOG = LOG ## Restituisce il logaritmo di un numero in una specificata base
+LOG10 = LOG10 ## Restituisce il logaritmo in base 10 di un numero
+MDETERM = MATR.DETERM ## Restituisce il determinante di una matrice
+MINVERSE = MATR.INVERSA ## Restituisce l'inverso di una matrice
+MMULT = MATR.PRODOTTO ## Restituisce il prodotto di due matrici
+MOD = RESTO ## Restituisce il resto della divisione
+MROUND = ARROTONDA.MULTIPLO ## Restituisce un numero arrotondato al multiplo desiderato
+MULTINOMIAL = MULTINOMIALE ## Restituisce il multinomiale di un insieme di numeri
+ODD = DISPARI ## Arrotonda un numero per eccesso al più vicino intero dispari
+PI = PI.GRECO ## Restituisce il valore di pi greco
+POWER = POTENZA ## Restituisce il risultato di un numero elevato a potenza
+PRODUCT = PRODOTTO ## Moltiplica i suoi argomenti
+QUOTIENT = QUOZIENTE ## Restituisce la parte intera di una divisione
+RADIANS = RADIANTI ## Converte i gradi in radianti
+RAND = CASUALE ## Restituisce un numero casuale compreso tra 0 e 1
+RANDBETWEEN = CASUALE.TRA ## Restituisce un numero casuale compreso tra i numeri specificati
+ROMAN = ROMANO ## Restituisce il numero come numero romano sotto forma di testo
+ROUND = ARROTONDA ## Arrotonda il numero al numero di cifre specificato
+ROUNDDOWN = ARROTONDA.PER.DIF ## Arrotonda il valore assoluto di un numero per difetto
+ROUNDUP = ARROTONDA.PER.ECC ## Arrotonda il valore assoluto di un numero per eccesso
+SERIESSUM = SOMMA.SERIE ## Restituisce la somma di una serie di potenze in base alla formula
+SIGN = SEGNO ## Restituisce il segno di un numero
+SIN = SEN ## Restituisce il seno di un dato angolo
+SINH = SENH ## Restituisce il seno iperbolico di un numero
+SQRT = RADQ ## Restituisce una radice quadrata
+SQRTPI = RADQ.PI.GRECO ## Restituisce la radice quadrata di un numero (numero * pi greco)
+SUBTOTAL = SUBTOTALE ## Restituisce un subtotale in un elenco o in un database
+SUM = SOMMA ## Somma i suoi argomenti
+SUMIF = SOMMA.SE ## Somma le celle specificate da un dato criterio
+SUMIFS = SOMMA.PIÙ.SE ## Somma le celle in un intervallo che soddisfano più criteri
+SUMPRODUCT = MATR.SOMMA.PRODOTTO ## Restituisce la somma dei prodotti dei componenti corrispondenti della matrice
+SUMSQ = SOMMA.Q ## Restituisce la somma dei quadrati degli argomenti
+SUMX2MY2 = SOMMA.DIFF.Q ## Restituisce la somma della differenza dei quadrati dei corrispondenti elementi in due matrici
+SUMX2PY2 = SOMMA.SOMMA.Q ## Restituisce la somma della somma dei quadrati dei corrispondenti elementi in due matrici
+SUMXMY2 = SOMMA.Q.DIFF ## Restituisce la somma dei quadrati delle differenze dei corrispondenti elementi in due matrici
+TAN = TAN ## Restituisce la tangente di un numero
+TANH = TANH ## Restituisce la tangente iperbolica di un numero
+TRUNC = TRONCA ## Tronca la parte decimale di un numero
+
+
+##
+## Statistical functions Funzioni statistiche
+##
+AVEDEV = MEDIA.DEV ## Restituisce la media delle deviazioni assolute delle coordinate rispetto alla loro media
+AVERAGE = MEDIA ## Restituisce la media degli argomenti
+AVERAGEA = MEDIA.VALORI ## Restituisce la media degli argomenti, inclusi i numeri, il testo e i valori logici
+AVERAGEIF = MEDIA.SE ## Restituisce la media aritmetica di tutte le celle in un intervallo che soddisfano un determinato criterio
+AVERAGEIFS = MEDIA.PIÙ.SE ## Restituisce la media aritmetica di tutte le celle che soddisfano più criteri
+BETADIST = DISTRIB.BETA ## Restituisce la funzione di distribuzione cumulativa beta
+BETAINV = INV.BETA ## Restituisce l'inverso della funzione di distribuzione cumulativa per una distribuzione beta specificata
+BINOMDIST = DISTRIB.BINOM ## Restituisce la distribuzione binomiale per il termine individuale
+CHIDIST = DISTRIB.CHI ## Restituisce la probabilità a una coda per la distribuzione del chi quadrato
+CHIINV = INV.CHI ## Restituisce l'inverso della probabilità ad una coda per la distribuzione del chi quadrato
+CHITEST = TEST.CHI ## Restituisce il test per l'indipendenza
+CONFIDENCE = CONFIDENZA ## Restituisce l'intervallo di confidenza per una popolazione
+CORREL = CORRELAZIONE ## Restituisce il coefficiente di correlazione tra due insiemi di dati
+COUNT = CONTA.NUMERI ## Conta la quantità di numeri nell'elenco di argomenti
+COUNTA = CONTA.VALORI ## Conta il numero di valori nell'elenco di argomenti
+COUNTBLANK = CONTA.VUOTE ## Conta il numero di celle vuote all'interno di un intervallo
+COUNTIF = CONTA.SE ## Conta il numero di celle all'interno di un intervallo che soddisfa i criteri specificati
+COUNTIFS = CONTA.PIÙ.SE ## Conta il numero di celle in un intervallo che soddisfano più criteri.
+COVAR = COVARIANZA ## Calcola la covarianza, la media dei prodotti delle deviazioni accoppiate
+CRITBINOM = CRIT.BINOM ## Restituisce il più piccolo valore per il quale la distribuzione cumulativa binomiale risulta maggiore o uguale ad un valore di criterio
+DEVSQ = DEV.Q ## Restituisce la somma dei quadrati delle deviazioni
+EXPONDIST = DISTRIB.EXP ## Restituisce la distribuzione esponenziale
+FDIST = DISTRIB.F ## Restituisce la distribuzione di probabilità F
+FINV = INV.F ## Restituisce l'inverso della distribuzione della probabilità F
+FISHER = FISHER ## Restituisce la trasformazione di Fisher
+FISHERINV = INV.FISHER ## Restituisce l'inverso della trasformazione di Fisher
+FORECAST = PREVISIONE ## Restituisce i valori lungo una tendenza lineare
+FREQUENCY = FREQUENZA ## Restituisce la distribuzione di frequenza come matrice verticale
+FTEST = TEST.F ## Restituisce il risultato di un test F
+GAMMADIST = DISTRIB.GAMMA ## Restituisce la distribuzione gamma
+GAMMAINV = INV.GAMMA ## Restituisce l'inverso della distribuzione cumulativa gamma
+GAMMALN = LN.GAMMA ## Restituisce il logaritmo naturale della funzione gamma, G(x)
+GEOMEAN = MEDIA.GEOMETRICA ## Restituisce la media geometrica
+GROWTH = CRESCITA ## Restituisce i valori lungo una linea di tendenza esponenziale
+HARMEAN = MEDIA.ARMONICA ## Restituisce la media armonica
+HYPGEOMDIST = DISTRIB.IPERGEOM ## Restituisce la distribuzione ipergeometrica
+INTERCEPT = INTERCETTA ## Restituisce l'intercetta della retta di regressione lineare
+KURT = CURTOSI ## Restituisce la curtosi di un insieme di dati
+LARGE = GRANDE ## Restituisce il k-esimo valore più grande in un insieme di dati
+LINEST = REGR.LIN ## Restituisce i parametri di una tendenza lineare
+LOGEST = REGR.LOG ## Restituisce i parametri di una linea di tendenza esponenziale
+LOGINV = INV.LOGNORM ## Restituisce l'inverso di una distribuzione lognormale
+LOGNORMDIST = DISTRIB.LOGNORM ## Restituisce la distribuzione lognormale cumulativa
+MAX = MAX ## Restituisce il valore massimo in un elenco di argomenti
+MAXA = MAX.VALORI ## Restituisce il valore massimo in un elenco di argomenti, inclusi i numeri, il testo e i valori logici
+MEDIAN = MEDIANA ## Restituisce la mediana dei numeri specificati
+MIN = MIN ## Restituisce il valore minimo in un elenco di argomenti
+MINA = MIN.VALORI ## Restituisce il più piccolo valore in un elenco di argomenti, inclusi i numeri, il testo e i valori logici
+MODE = MODA ## Restituisce il valore più comune in un insieme di dati
+NEGBINOMDIST = DISTRIB.BINOM.NEG ## Restituisce la distribuzione binomiale negativa
+NORMDIST = DISTRIB.NORM ## Restituisce la distribuzione cumulativa normale
+NORMINV = INV.NORM ## Restituisce l'inverso della distribuzione cumulativa normale standard
+NORMSDIST = DISTRIB.NORM.ST ## Restituisce la distribuzione cumulativa normale standard
+NORMSINV = INV.NORM.ST ## Restituisce l'inverso della distribuzione cumulativa normale
+PEARSON = PEARSON ## Restituisce il coefficiente del momento di correlazione di Pearson
+PERCENTILE = PERCENTILE ## Restituisce il k-esimo dato percentile di valori in un intervallo
+PERCENTRANK = PERCENT.RANGO ## Restituisce il rango di un valore in un insieme di dati come percentuale
+PERMUT = PERMUTAZIONE ## Restituisce il numero delle permutazioni per un determinato numero di oggetti
+POISSON = POISSON ## Restituisce la distribuzione di Poisson
+PROB = PROBABILITÀ ## Calcola la probabilità che dei valori in un intervallo siano compresi tra due limiti
+QUARTILE = QUARTILE ## Restituisce il quartile di un insieme di dati
+RANK = RANGO ## Restituisce il rango di un numero in un elenco di numeri
+RSQ = RQ ## Restituisce la radice quadrata del coefficiente di momento di correlazione di Pearson
+SKEW = ASIMMETRIA ## Restituisce il grado di asimmetria di una distribuzione
+SLOPE = PENDENZA ## Restituisce la pendenza di una retta di regressione lineare
+SMALL = PICCOLO ## Restituisce il k-esimo valore più piccolo in un insieme di dati
+STANDARDIZE = NORMALIZZA ## Restituisce un valore normalizzato
+STDEV = DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione
+STDEVA = DEV.ST.VALORI ## Restituisce una stima della deviazione standard sulla base di un campione, inclusi i numeri, il testo e i valori logici
+STDEVP = DEV.ST.POP ## Calcola la deviazione standard sulla base di un'intera popolazione
+STDEVPA = DEV.ST.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici
+STEYX = ERR.STD.YX ## Restituisce l'errore standard del valore previsto per y per ogni valore x nella regressione
+TDIST = DISTRIB.T ## Restituisce la distribuzione t di Student
+TINV = INV.T ## Restituisce l'inversa della distribuzione t di Student
+TREND = TENDENZA ## Restituisce i valori lungo una linea di tendenza lineare
+TRIMMEAN = MEDIA.TRONCATA ## Restituisce la media della parte interna di un insieme di dati
+TTEST = TEST.T ## Restituisce la probabilità associata ad un test t di Student
+VAR = VAR ## Stima la varianza sulla base di un campione
+VARA = VAR.VALORI ## Stima la varianza sulla base di un campione, inclusi i numeri, il testo e i valori logici
+VARP = VAR.POP ## Calcola la varianza sulla base dell'intera popolazione
+VARPA = VAR.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici
+WEIBULL = WEIBULL ## Restituisce la distribuzione di Weibull
+ZTEST = TEST.Z ## Restituisce il valore di probabilità a una coda per un test z
+
+
+##
+## Text functions Funzioni di testo
+##
+ASC = ASC ## Modifica le lettere inglesi o il katakana a doppio byte all'interno di una stringa di caratteri in caratteri a singolo byte
+BAHTTEXT = BAHTTESTO ## Converte un numero in testo, utilizzando il formato valuta ß (baht)
+CHAR = CODICE.CARATT ## Restituisce il carattere specificato dal numero di codice
+CLEAN = LIBERA ## Elimina dal testo tutti i caratteri che non è possibile stampare
+CODE = CODICE ## Restituisce il codice numerico del primo carattere di una stringa di testo
+CONCATENATE = CONCATENA ## Unisce diversi elementi di testo in un unico elemento di testo
+DOLLAR = VALUTA ## Converte un numero in testo, utilizzando il formato valuta € (euro)
+EXACT = IDENTICO ## Verifica se due valori di testo sono uguali
+FIND = TROVA ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole)
+FINDB = TROVA.B ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole)
+FIXED = FISSO ## Formatta un numero come testo con un numero fisso di decimali
+JIS = ORDINAMENTO.JIS ## Modifica le lettere inglesi o i caratteri katakana a byte singolo all'interno di una stringa di caratteri in caratteri a byte doppio.
+LEFT = SINISTRA ## Restituisce il carattere più a sinistra di un valore di testo
+LEFTB = SINISTRA.B ## Restituisce il carattere più a sinistra di un valore di testo
+LEN = LUNGHEZZA ## Restituisce il numero di caratteri di una stringa di testo
+LENB = LUNB ## Restituisce il numero di caratteri di una stringa di testo
+LOWER = MINUSC ## Converte il testo in lettere minuscole
+MID = MEDIA ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata
+MIDB = MEDIA.B ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata
+PHONETIC = FURIGANA ## Estrae i caratteri fonetici (furigana) da una stringa di testo.
+PROPER = MAIUSC.INIZ ## Converte in maiuscolo la prima lettera di ogni parola di un valore di testo
+REPLACE = RIMPIAZZA ## Sostituisce i caratteri all'interno di un testo
+REPLACEB = SOSTITUISCI.B ## Sostituisce i caratteri all'interno di un testo
+REPT = RIPETI ## Ripete un testo per un dato numero di volte
+RIGHT = DESTRA ## Restituisce il carattere più a destra di un valore di testo
+RIGHTB = DESTRA.B ## Restituisce il carattere più a destra di un valore di testo
+SEARCH = RICERCA ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole)
+SEARCHB = CERCA.B ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole)
+SUBSTITUTE = SOSTITUISCI ## Sostituisce il nuovo testo al testo contenuto in una stringa
+T = T ## Converte gli argomenti in testo
+TEXT = TESTO ## Formatta un numero e lo converte in testo
+TRIM = ANNULLA.SPAZI ## Elimina gli spazi dal testo
+UPPER = MAIUSC ## Converte il testo in lettere maiuscole
+VALUE = VALORE ## Converte un argomento di testo in numero
diff --git a/PHPExcel/locale/nl/config b/PHPExcel/locale/nl/config
new file mode 100644
index 0000000..00c1b0f
--- /dev/null
+++ b/PHPExcel/locale/nl/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = €
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #LEEG!
+DIV0 = #DEEL/0!
+VALUE = #WAARDE!
+REF = #VERW!
+NAME = #NAAM?
+NUM = #GETAL!
+NA = #N/B
diff --git a/PHPExcel/locale/nl/functions b/PHPExcel/locale/nl/functions
new file mode 100644
index 0000000..6380008
--- /dev/null
+++ b/PHPExcel/locale/nl/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Automatiseringsfuncties en functies in invoegtoepassingen
+##
+GETPIVOTDATA = DRAAITABEL.OPHALEN ## Geeft gegevens uit een draaitabelrapport als resultaat
+
+
+##
+## Cube functions Kubusfuncties
+##
+CUBEKPIMEMBER = KUBUSKPILID ## Retourneert de naam, eigenschap en waarde van een KPI (prestatie-indicator) en geeft de naam en de eigenschap in de cel weer. Een KPI is een meetbare waarde, zoals de maandelijkse brutowinst of de omzet per kwartaal per werknemer, die wordt gebruikt om de prestaties van een organisatie te bewaken
+CUBEMEMBER = KUBUSLID ## Retourneert een lid of tupel in een kubushiërarchie. Wordt gebruikt om te controleren of het lid of de tupel in de kubus aanwezig is
+CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP ## Retourneert de waarde van een lideigenschap in de kubus. Wordt gebruikt om te controleren of de lidnaam in de kubus bestaat en retourneert de opgegeven eigenschap voor dit lid
+CUBERANKEDMEMBER = KUBUSGERANGCHIKTLID ## Retourneert het zoveelste, gerangschikte lid in een set. Wordt gebruikt om een of meer elementen in een set te retourneren, zoals de tien beste verkopers of de tien beste studenten
+CUBESET = KUBUSSET ## Definieert een berekende set leden of tupels door een ingestelde expressie naar de kubus op de server te sturen, alwaar de set wordt gemaakt en vervolgens wordt geretourneerd naar Microsoft Office Excel
+CUBESETCOUNT = KUBUSSETAANTAL ## Retourneert het aantal onderdelen in een set
+CUBEVALUE = KUBUSWAARDE ## Retourneert een samengestelde waarde van een kubus
+
+
+##
+## Database functions Databasefuncties
+##
+DAVERAGE = DBGEMIDDELDE ## Berekent de gemiddelde waarde in geselecteerde databasegegevens
+DCOUNT = DBAANTAL ## Telt de cellen met getallen in een database
+DCOUNTA = DBAANTALC ## Telt de niet-lege cellen in een database
+DGET = DBLEZEN ## Retourneert één record dat voldoet aan de opgegeven criteria uit een database
+DMAX = DBMAX ## Retourneert de maximumwaarde in de geselecteerde databasegegevens
+DMIN = DBMIN ## Retourneert de minimumwaarde in de geselecteerde databasegegevens
+DPRODUCT = DBPRODUCT ## Vermenigvuldigt de waarden in een bepaald veld van de records die voldoen aan de criteria in een database
+DSTDEV = DBSTDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef uit geselecteerde databasegegevens
+DSTDEVP = DBSTDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie van geselecteerde databasegegevens
+DSUM = DBSOM ## Telt de getallen uit een kolom records in de database op die voldoen aan de criteria
+DVAR = DBVAR ## Maakt een schatting van de variantie op basis van een steekproef uit geselecteerde databasegegevens
+DVARP = DBVARP ## Berekent de variantie op basis van de volledige populatie van geselecteerde databasegegevens
+
+
+##
+## Date and time functions Datum- en tijdfuncties
+##
+DATE = DATUM ## Geeft als resultaat het seriële getal van een opgegeven datum
+DATEVALUE = DATUMWAARDE ## Converteert een datum in de vorm van tekst naar een serieel getal
+DAY = DAG ## Converteert een serieel getal naar een dag van de maand
+DAYS360 = DAGEN360 ## Berekent het aantal dagen tussen twee datums op basis van een jaar met 360 dagen
+EDATE = ZELFDE.DAG ## Geeft als resultaat het seriële getal van een datum die het opgegeven aantal maanden voor of na de begindatum ligt
+EOMONTH = LAATSTE.DAG ## Geeft als resultaat het seriële getal van de laatste dag van de maand voor of na het opgegeven aantal maanden
+HOUR = UUR ## Converteert een serieel getal naar uren
+MINUTE = MINUUT ## Converteert een serieel naar getal minuten
+MONTH = MAAND ## Converteert een serieel getal naar een maand
+NETWORKDAYS = NETTO.WERKDAGEN ## Geeft als resultaat het aantal hele werkdagen tussen twee datums
+NOW = NU ## Geeft als resultaat het seriële getal van de huidige datum en tijd
+SECOND = SECONDE ## Converteert een serieel getal naar seconden
+TIME = TIJD ## Geeft als resultaat het seriële getal van een bepaald tijdstip
+TIMEVALUE = TIJDWAARDE ## Converteert de tijd in de vorm van tekst naar een serieel getal
+TODAY = VANDAAG ## Geeft als resultaat het seriële getal van de huidige datum
+WEEKDAY = WEEKDAG ## Converteert een serieel getal naar een weekdag
+WEEKNUM = WEEKNUMMER ## Converteert een serieel getal naar een weeknummer
+WORKDAY = WERKDAG ## Geeft als resultaat het seriële getal van de datum voor of na een bepaald aantal werkdagen
+YEAR = JAAR ## Converteert een serieel getal naar een jaar
+YEARFRAC = JAAR.DEEL ## Geeft als resultaat het gedeelte van het jaar, uitgedrukt in het aantal hele dagen tussen begindatum en einddatum
+
+
+##
+## Engineering functions Technische functies
+##
+BESSELI = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie In(x)
+BESSELJ = BESSEL.J ## Geeft als resultaat de Bessel-functie Jn(x)
+BESSELK = BESSEL.K ## Geeft als resultaat de gewijzigde Bessel-functie Kn(x)
+BESSELY = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie Yn(x)
+BIN2DEC = BIN.N.DEC ## Converteert een binair getal naar een decimaal getal
+BIN2HEX = BIN.N.HEX ## Converteert een binair getal naar een hexadecimaal getal
+BIN2OCT = BIN.N.OCT ## Converteert een binair getal naar een octaal getal
+COMPLEX = COMPLEX ## Converteert reële en imaginaire coëfficiënten naar een complex getal
+CONVERT = CONVERTEREN ## Converteert een getal in de ene maateenheid naar een getal in een andere maateenheid
+DEC2BIN = DEC.N.BIN ## Converteert een decimaal getal naar een binair getal
+DEC2HEX = DEC.N.HEX ## Converteert een decimaal getal naar een hexadecimaal getal
+DEC2OCT = DEC.N.OCT ## Converteert een decimaal getal naar een octaal getal
+DELTA = DELTA ## Test of twee waarden gelijk zijn
+ERF = FOUTFUNCTIE ## Geeft als resultaat de foutfunctie
+ERFC = FOUT.COMPLEMENT ## Geeft als resultaat de complementaire foutfunctie
+GESTEP = GROTER.DAN ## Test of een getal groter is dan de drempelwaarde
+HEX2BIN = HEX.N.BIN ## Converteert een hexadecimaal getal naar een binair getal
+HEX2DEC = HEX.N.DEC ## Converteert een hexadecimaal getal naar een decimaal getal
+HEX2OCT = HEX.N.OCT ## Converteert een hexadecimaal getal naar een octaal getal
+IMABS = C.ABS ## Geeft als resultaat de absolute waarde (modulus) van een complex getal
+IMAGINARY = C.IM.DEEL ## Geeft als resultaat de imaginaire coëfficiënt van een complex getal
+IMARGUMENT = C.ARGUMENT ## Geeft als resultaat het argument thèta, een hoek uitgedrukt in radialen
+IMCONJUGATE = C.TOEGEVOEGD ## Geeft als resultaat het complexe toegevoegde getal van een complex getal
+IMCOS = C.COS ## Geeft als resultaat de cosinus van een complex getal
+IMDIV = C.QUOTIENT ## Geeft als resultaat het quotiënt van twee complexe getallen
+IMEXP = C.EXP ## Geeft als resultaat de exponent van een complex getal
+IMLN = C.LN ## Geeft als resultaat de natuurlijke logaritme van een complex getal
+IMLOG10 = C.LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een complex getal
+IMLOG2 = C.LOG2 ## Geeft als resultaat de logaritme met grondtal 2 van een complex getal
+IMPOWER = C.MACHT ## Geeft als resultaat een complex getal dat is verheven tot de macht van een geheel getal
+IMPRODUCT = C.PRODUCT ## Geeft als resultaat het product van complexe getallen
+IMREAL = C.REEEL.DEEL ## Geeft als resultaat de reële coëfficiënt van een complex getal
+IMSIN = C.SIN ## Geeft als resultaat de sinus van een complex getal
+IMSQRT = C.WORTEL ## Geeft als resultaat de vierkantswortel van een complex getal
+IMSUB = C.VERSCHIL ## Geeft als resultaat het verschil tussen twee complexe getallen
+IMSUM = C.SOM ## Geeft als resultaat de som van complexe getallen
+OCT2BIN = OCT.N.BIN ## Converteert een octaal getal naar een binair getal
+OCT2DEC = OCT.N.DEC ## Converteert een octaal getal naar een decimaal getal
+OCT2HEX = OCT.N.HEX ## Converteert een octaal getal naar een hexadecimaal getal
+
+
+##
+## Financial functions Financiële functies
+##
+ACCRINT = SAMENG.RENTE ## Berekent de opgelopen rente voor een waardepapier waarvan de rente periodiek wordt uitgekeerd
+ACCRINTM = SAMENG.RENTE.V ## Berekent de opgelopen rente voor een waardepapier waarvan de rente op de vervaldatum wordt uitgekeerd
+AMORDEGRC = AMORDEGRC ## Geeft als resultaat de afschrijving voor elke boekingsperiode door een afschrijvingscoëfficiënt toe te passen
+AMORLINC = AMORLINC ## Berekent de afschrijving voor elke boekingsperiode
+COUPDAYBS = COUP.DAGEN.BB ## Berekent het aantal dagen vanaf het begin van de coupontermijn tot de stortingsdatum
+COUPDAYS = COUP.DAGEN ## Geeft als resultaat het aantal dagen in de coupontermijn waarin de stortingsdatum valt
+COUPDAYSNC = COUP.DAGEN.VV ## Geeft als resultaat het aantal dagen vanaf de stortingsdatum tot de volgende couponvervaldatum
+COUPNCD = COUP.DATUM.NB ## Geeft als resultaat de volgende coupondatum na de stortingsdatum
+COUPNUM = COUP.AANTAL ## Geeft als resultaat het aantal coupons dat nog moet worden uitbetaald tussen de stortingsdatum en de vervaldatum
+COUPPCD = COUP.DATUM.VB ## Geeft als resultaat de vorige couponvervaldatum vóór de stortingsdatum
+CUMIPMT = CUM.RENTE ## Geeft als resultaat de cumulatieve rente die tussen twee termijnen is uitgekeerd
+CUMPRINC = CUM.HOOFDSOM ## Geeft als resultaat de cumulatieve hoofdsom van een lening die tussen twee termijnen is terugbetaald
+DB = DB ## Geeft als resultaat de afschrijving van activa voor een bepaalde periode met behulp van de 'fixed declining balance'-methode
+DDB = DDB ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'double declining balance'-methode of een andere methode die u opgeeft
+DISC = DISCONTO ## Geeft als resultaat het discontopercentage voor een waardepapier
+DOLLARDE = EURO.DE ## Converteert een prijs in euro's, uitgedrukt in een breuk, naar een prijs in euro's, uitgedrukt in een decimaal getal
+DOLLARFR = EURO.BR ## Converteert een prijs in euro's, uitgedrukt in een decimaal getal, naar een prijs in euro's, uitgedrukt in een breuk
+DURATION = DUUR ## Geeft als resultaat de gewogen gemiddelde looptijd voor een waardepapier met periodieke rentebetalingen
+EFFECT = EFFECT.RENTE ## Geeft als resultaat het effectieve jaarlijkse rentepercentage
+FV = TW ## Geeft als resultaat de toekomstige waarde van een investering
+FVSCHEDULE = TOEK.WAARDE2 ## Geeft als resultaat de toekomstige waarde van een bepaalde hoofdsom na het toepassen van een reeks samengestelde rentepercentages
+INTRATE = RENTEPERCENTAGE ## Geeft als resultaat het rentepercentage voor een volgestort waardepapier
+IPMT = IBET ## Geeft als resultaat de te betalen rente voor een investering over een bepaalde termijn
+IRR = IR ## Geeft als resultaat de interne rentabiliteit voor een reeks cashflows
+ISPMT = ISBET ## Geeft als resultaat de rente die is betaald tijdens een bepaalde termijn van een investering
+MDURATION = AANG.DUUR ## Geeft als resultaat de aangepaste Macauley-looptijd voor een waardepapier, aangenomen dat de nominale waarde € 100 bedraagt
+MIRR = GIR ## Geeft als resultaat de interne rentabiliteit voor een serie cashflows, waarbij voor betalingen een ander rentepercentage geldt dan voor inkomsten
+NOMINAL = NOMINALE.RENTE ## Geeft als resultaat het nominale jaarlijkse rentepercentage
+NPER = NPER ## Geeft als resultaat het aantal termijnen van een investering
+NPV = NHW ## Geeft als resultaat de netto huidige waarde van een investering op basis van een reeks periodieke cashflows en een discontopercentage
+ODDFPRICE = AFW.ET.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende eerste termijn
+ODDFYIELD = AFW.ET.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende eerste termijn
+ODDLPRICE = AFW.LT.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende laatste termijn
+ODDLYIELD = AFW.LT.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende laatste termijn
+PMT = BET ## Geeft als resultaat de periodieke betaling voor een annuïteit
+PPMT = PBET ## Geeft als resultaat de afbetaling op de hoofdsom voor een bepaalde termijn
+PRICE = PRIJS.NOM ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente periodiek wordt uitgekeerd
+PRICEDISC = PRIJS.DISCONTO ## Geeft als resultaat de prijs per € 100 nominale waarde voor een verdisconteerd waardepapier
+PRICEMAT = PRIJS.VERVALDAG ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum
+PV = HW ## Geeft als resultaat de huidige waarde van een investering
+RATE = RENTE ## Geeft als resultaat het periodieke rentepercentage voor een annuïteit
+RECEIVED = OPBRENGST ## Geeft als resultaat het bedrag dat op de vervaldatum wordt uitgekeerd voor een volgestort waardepapier
+SLN = LIN.AFSCHR ## Geeft als resultaat de lineaire afschrijving van activa over één termijn
+SYD = SYD ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'Sum-Of-Years-Digits'-methode
+TBILLEQ = SCHATK.OBL ## Geeft als resultaat het rendement op schatkistpapier, dat op dezelfde manier wordt berekend als het rendement op obligaties
+TBILLPRICE = SCHATK.PRIJS ## Bepaalt de prijs per € 100 nominale waarde voor schatkistpapier
+TBILLYIELD = SCHATK.REND ## Berekent het rendement voor schatkistpapier
+VDB = VDB ## Geeft als resultaat de afschrijving van activa over een gehele of gedeeltelijke termijn met behulp van de 'declining balance'-methode
+XIRR = IR.SCHEMA ## Berekent de interne rentabiliteit voor een betalingsschema van cashflows
+XNPV = NHW2 ## Berekent de huidige nettowaarde voor een betalingsschema van cashflows
+YIELD = RENDEMENT ## Geeft als resultaat het rendement voor een waardepapier waarvan de rente periodiek wordt uitgekeerd
+YIELDDISC = REND.DISCONTO ## Geeft als resultaat het jaarlijkse rendement voor een verdisconteerd waardepapier, bijvoorbeeld schatkistpapier
+YIELDMAT = REND.VERVAL ## Geeft als resultaat het jaarlijkse rendement voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum
+
+
+##
+## Information functions Informatiefuncties
+##
+CELL = CEL ## Geeft als resultaat informatie over de opmaak, locatie of inhoud van een cel
+ERROR.TYPE = TYPE.FOUT ## Geeft als resultaat een getal dat overeenkomt met een van de foutwaarden van Microsoft Excel
+INFO = INFO ## Geeft als resultaat informatie over de huidige besturingsomgeving
+ISBLANK = ISLEEG ## Geeft als resultaat WAAR als de waarde leeg is
+ISERR = ISFOUT2 ## Geeft als resultaat WAAR als de waarde een foutwaarde is, met uitzondering van #N/B
+ISERROR = ISFOUT ## Geeft als resultaat WAAR als de waarde een foutwaarde is
+ISEVEN = IS.EVEN ## Geeft als resultaat WAAR als het getal even is
+ISLOGICAL = ISLOGISCH ## Geeft als resultaat WAAR als de waarde een logische waarde is
+ISNA = ISNB ## Geeft als resultaat WAAR als de waarde de foutwaarde #N/B is
+ISNONTEXT = ISGEENTEKST ## Geeft als resultaat WAAR als de waarde geen tekst is
+ISNUMBER = ISGETAL ## Geeft als resultaat WAAR als de waarde een getal is
+ISODD = IS.ONEVEN ## Geeft als resultaat WAAR als het getal oneven is
+ISREF = ISVERWIJZING ## Geeft als resultaat WAAR als de waarde een verwijzing is
+ISTEXT = ISTEKST ## Geeft als resultaat WAAR als de waarde tekst is
+N = N ## Geeft als resultaat een waarde die is geconverteerd naar een getal
+NA = NB ## Geeft als resultaat de foutwaarde #N/B
+TYPE = TYPE ## Geeft als resultaat een getal dat het gegevenstype van een waarde aangeeft
+
+
+##
+## Logical functions Logische functies
+##
+AND = EN ## Geeft als resultaat WAAR als alle argumenten WAAR zijn
+FALSE = ONWAAR ## Geeft als resultaat de logische waarde ONWAAR
+IF = ALS ## Geeft een logische test aan
+IFERROR = ALS.FOUT ## Retourneert een waarde die u opgeeft als een formule een fout oplevert, anders wordt het resultaat van de formule geretourneerd
+NOT = NIET ## Keert de logische waarde van het argument om
+OR = OF ## Geeft als resultaat WAAR als minimaal een van de argumenten WAAR is
+TRUE = WAAR ## Geeft als resultaat de logische waarde WAAR
+
+
+##
+## Lookup and reference functions Zoek- en verwijzingsfuncties
+##
+ADDRESS = ADRES ## Geeft als resultaat een verwijzing, in de vorm van tekst, naar één bepaalde cel in een werkblad
+AREAS = BEREIKEN ## Geeft als resultaat het aantal bereiken in een verwijzing
+CHOOSE = KIEZEN ## Kiest een waarde uit een lijst met waarden
+COLUMN = KOLOM ## Geeft als resultaat het kolomnummer van een verwijzing
+COLUMNS = KOLOMMEN ## Geeft als resultaat het aantal kolommen in een verwijzing
+HLOOKUP = HORIZ.ZOEKEN ## Zoekt in de bovenste rij van een matrix naar een bepaalde waarde en geeft als resultaat de gevonden waarde in de opgegeven cel
+HYPERLINK = HYPERLINK ## Maakt een snelkoppeling of een sprong waarmee een document wordt geopend dat is opgeslagen op een netwerkserver, een intranet of op internet
+INDEX = INDEX ## Kiest met een index een waarde uit een verwijzing of een matrix
+INDIRECT = INDIRECT ## Geeft als resultaat een verwijzing die wordt aangegeven met een tekstwaarde
+LOOKUP = ZOEKEN ## Zoekt naar bepaalde waarden in een vector of een matrix
+MATCH = VERGELIJKEN ## Zoekt naar bepaalde waarden in een verwijzing of een matrix
+OFFSET = VERSCHUIVING ## Geeft als resultaat een nieuwe verwijzing die is verschoven ten opzichte van een bepaalde verwijzing
+ROW = RIJ ## Geeft als resultaat het rijnummer van een verwijzing
+ROWS = RIJEN ## Geeft als resultaat het aantal rijen in een verwijzing
+RTD = RTG ## Haalt realtimegegevens op uit een programma dat COM-automatisering (automatisering: een methode waarmee de ene toepassing objecten van een andere toepassing of ontwikkelprogramma kan besturen. Automatisering werd vroeger OLE-automatisering genoemd. Automatisering is een industrienorm die deel uitmaakt van het Component Object Model (COM).) ondersteunt
+TRANSPOSE = TRANSPONEREN ## Geeft als resultaat de getransponeerde van een matrix
+VLOOKUP = VERT.ZOEKEN ## Zoekt in de meest linkse kolom van een matrix naar een bepaalde waarde en geeft als resultaat de waarde in de opgegeven cel
+
+
+##
+## Math and trigonometry functions Wiskundige en trigonometrische functies
+##
+ABS = ABS ## Geeft als resultaat de absolute waarde van een getal
+ACOS = BOOGCOS ## Geeft als resultaat de boogcosinus van een getal
+ACOSH = BOOGCOSH ## Geeft als resultaat de inverse cosinus hyperbolicus van een getal
+ASIN = BOOGSIN ## Geeft als resultaat de boogsinus van een getal
+ASINH = BOOGSINH ## Geeft als resultaat de inverse sinus hyperbolicus van een getal
+ATAN = BOOGTAN ## Geeft als resultaat de boogtangens van een getal
+ATAN2 = BOOGTAN2 ## Geeft als resultaat de boogtangens van de x- en y-coördinaten
+ATANH = BOOGTANH ## Geeft als resultaat de inverse tangens hyperbolicus van een getal
+CEILING = AFRONDEN.BOVEN ## Rondt de absolute waarde van een getal naar boven af op het dichtstbijzijnde gehele getal of het dichtstbijzijnde significante veelvoud
+COMBIN = COMBINATIES ## Geeft als resultaat het aantal combinaties voor een bepaald aantal objecten
+COS = COS ## Geeft als resultaat de cosinus van een getal
+COSH = COSH ## Geeft als resultaat de cosinus hyperbolicus van een getal
+DEGREES = GRADEN ## Converteert radialen naar graden
+EVEN = EVEN ## Rondt het getal af op het dichtstbijzijnde gehele even getal
+EXP = EXP ## Verheft e tot de macht van een bepaald getal
+FACT = FACULTEIT ## Geeft als resultaat de faculteit van een getal
+FACTDOUBLE = DUBBELE.FACULTEIT ## Geeft als resultaat de dubbele faculteit van een getal
+FLOOR = AFRONDEN.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af
+GCD = GGD ## Geeft als resultaat de grootste gemene deler
+INT = INTEGER ## Rondt een getal naar beneden af op het dichtstbijzijnde gehele getal
+LCM = KGV ## Geeft als resultaat het kleinste gemene veelvoud
+LN = LN ## Geeft als resultaat de natuurlijke logaritme van een getal
+LOG = LOG ## Geeft als resultaat de logaritme met het opgegeven grondtal van een getal
+LOG10 = LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een getal
+MDETERM = DETERMINANTMAT ## Geeft als resultaat de determinant van een matrix
+MINVERSE = INVERSEMAT ## Geeft als resultaat de inverse van een matrix
+MMULT = PRODUCTMAT ## Geeft als resultaat het product van twee matrices
+MOD = REST ## Geeft als resultaat het restgetal van een deling
+MROUND = AFRONDEN.N.VEELVOUD ## Geeft als resultaat een getal afgerond op het gewenste veelvoud
+MULTINOMIAL = MULTINOMIAAL ## Geeft als resultaat de multinomiaalcoëfficiënt van een reeks getallen
+ODD = ONEVEN ## Rondt de absolute waarde van het getal naar boven af op het dichtstbijzijnde gehele oneven getal
+PI = PI ## Geeft als resultaat de waarde van pi
+POWER = MACHT ## Verheft een getal tot een macht
+PRODUCT = PRODUCT ## Vermenigvuldigt de argumenten met elkaar
+QUOTIENT = QUOTIENT ## Geeft als resultaat de uitkomst van een deling als geheel getal
+RADIANS = RADIALEN ## Converteert graden naar radialen
+RAND = ASELECT ## Geeft als resultaat een willekeurig getal tussen 0 en 1
+RANDBETWEEN = ASELECTTUSSEN ## Geeft een willekeurig getal tussen de getallen die u hebt opgegeven
+ROMAN = ROMEINS ## Converteert een Arabisch getal naar een Romeins getal en geeft het resultaat weer in de vorm van tekst
+ROUND = AFRONDEN ## Rondt een getal af op het opgegeven aantal decimalen
+ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af
+ROUNDUP = AFRONDEN.NAAR.BOVEN ## Rondt de absolute waarde van een getal naar boven af
+SERIESSUM = SOM.MACHTREEKS ## Geeft als resultaat de som van een machtreeks die is gebaseerd op de formule
+SIGN = POS.NEG ## Geeft als resultaat het teken van een getal
+SIN = SIN ## Geeft als resultaat de sinus van de opgegeven hoek
+SINH = SINH ## Geeft als resultaat de sinus hyperbolicus van een getal
+SQRT = WORTEL ## Geeft als resultaat de positieve vierkantswortel van een getal
+SQRTPI = WORTEL.PI ## Geeft als resultaat de vierkantswortel van (getal * pi)
+SUBTOTAL = SUBTOTAAL ## Geeft als resultaat een subtotaal voor een bereik
+SUM = SOM ## Telt de argumenten op
+SUMIF = SOM.ALS ## Telt de getallen bij elkaar op die voldoen aan een bepaald criterium
+SUMIFS = SOMMEN.ALS ## Telt de cellen in een bereik op die aan meerdere criteria voldoen
+SUMPRODUCT = SOMPRODUCT ## Geeft als resultaat de som van de producten van de corresponderende matrixelementen
+SUMSQ = KWADRATENSOM ## Geeft als resultaat de som van de kwadraten van de argumenten
+SUMX2MY2 = SOM.X2MINY2 ## Geeft als resultaat de som van het verschil tussen de kwadraten van corresponderende waarden in twee matrices
+SUMX2PY2 = SOM.X2PLUSY2 ## Geeft als resultaat de som van de kwadratensom van corresponderende waarden in twee matrices
+SUMXMY2 = SOM.XMINY.2 ## Geeft als resultaat de som van de kwadraten van de verschillen tussen de corresponderende waarden in twee matrices
+TAN = TAN ## Geeft als resultaat de tangens van een getal
+TANH = TANH ## Geeft als resultaat de tangens hyperbolicus van een getal
+TRUNC = GEHEEL ## Kapt een getal af tot een geheel getal
+
+
+##
+## Statistical functions Statistische functies
+##
+AVEDEV = GEM.DEVIATIE ## Geeft als resultaat het gemiddelde van de absolute deviaties van gegevenspunten ten opzichte van hun gemiddelde waarde
+AVERAGE = GEMIDDELDE ## Geeft als resultaat het gemiddelde van de argumenten
+AVERAGEA = GEMIDDELDEA ## Geeft als resultaat het gemiddelde van de argumenten, inclusief getallen, tekst en logische waarden
+AVERAGEIF = GEMIDDELDE.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen in een bereik die voldoen aan de opgegeven criteria
+AVERAGEIFS = GEMIDDELDEN.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen die aan meerdere criteria voldoen
+BETADIST = BETA.VERD ## Geeft als resultaat de cumulatieve bèta-verdelingsfunctie
+BETAINV = BETA.INV ## Geeft als resultaat de inverse van de cumulatieve verdelingsfunctie voor een gegeven bèta-verdeling
+BINOMDIST = BINOMIALE.VERD ## Geeft als resultaat de binomiale verdeling
+CHIDIST = CHI.KWADRAAT ## Geeft als resultaat de eenzijdige kans van de chi-kwadraatverdeling
+CHIINV = CHI.KWADRAAT.INV ## Geeft als resultaat de inverse van een eenzijdige kans van de chi-kwadraatverdeling
+CHITEST = CHI.TOETS ## Geeft als resultaat de onafhankelijkheidstoets
+CONFIDENCE = BETROUWBAARHEID ## Geeft als resultaat het betrouwbaarheidsinterval van een gemiddelde waarde voor de elementen van een populatie
+CORREL = CORRELATIE ## Geeft als resultaat de correlatiecoëfficiënt van twee gegevensverzamelingen
+COUNT = AANTAL ## Telt het aantal getallen in de argumentenlijst
+COUNTA = AANTALARG ## Telt het aantal waarden in de argumentenlijst
+COUNTBLANK = AANTAL.LEGE.CELLEN ## Telt het aantal lege cellen in een bereik
+COUNTIF = AANTAL.ALS ## Telt in een bereik het aantal cellen die voldoen aan een bepaald criterium
+COUNTIFS = AANTALLEN.ALS ## Telt in een bereik het aantal cellen die voldoen aan meerdere criteria
+COVAR = COVARIANTIE ## Geeft als resultaat de covariantie, het gemiddelde van de producten van de gepaarde deviaties
+CRITBINOM = CRIT.BINOM ## Geeft als resultaat de kleinste waarde waarvoor de binomiale verdeling kleiner is dan of gelijk is aan het criterium
+DEVSQ = DEV.KWAD ## Geeft als resultaat de som van de deviaties in het kwadraat
+EXPONDIST = EXPON.VERD ## Geeft als resultaat de exponentiële verdeling
+FDIST = F.VERDELING ## Geeft als resultaat de F-verdeling
+FINV = F.INVERSE ## Geeft als resultaat de inverse van de F-verdeling
+FISHER = FISHER ## Geeft als resultaat de Fisher-transformatie
+FISHERINV = FISHER.INV ## Geeft als resultaat de inverse van de Fisher-transformatie
+FORECAST = VOORSPELLEN ## Geeft als resultaat een waarde op basis van een lineaire trend
+FREQUENCY = FREQUENTIE ## Geeft als resultaat een frequentieverdeling in de vorm van een verticale matrix
+FTEST = F.TOETS ## Geeft als resultaat een F-toets
+GAMMADIST = GAMMA.VERD ## Geeft als resultaat de gamma-verdeling
+GAMMAINV = GAMMA.INV ## Geeft als resultaat de inverse van de cumulatieve gamma-verdeling
+GAMMALN = GAMMA.LN ## Geeft als resultaat de natuurlijke logaritme van de gamma-functie, G(x)
+GEOMEAN = MEETK.GEM ## Geeft als resultaat het meetkundige gemiddelde
+GROWTH = GROEI ## Geeft als resultaat de waarden voor een exponentiële trend
+HARMEAN = HARM.GEM ## Geeft als resultaat het harmonische gemiddelde
+HYPGEOMDIST = HYPERGEO.VERD ## Geeft als resultaat de hypergeometrische verdeling
+INTERCEPT = SNIJPUNT ## Geeft als resultaat het snijpunt van de lineaire regressielijn met de y-as
+KURT = KURTOSIS ## Geeft als resultaat de kurtosis van een gegevensverzameling
+LARGE = GROOTSTE ## Geeft als resultaat de op k-1 na grootste waarde in een gegevensverzameling
+LINEST = LIJNSCH ## Geeft als resultaat de parameters van een lineaire trend
+LOGEST = LOGSCH ## Geeft als resultaat de parameters van een exponentiële trend
+LOGINV = LOG.NORM.INV ## Geeft als resultaat de inverse van de logaritmische normale verdeling
+LOGNORMDIST = LOG.NORM.VERD ## Geeft als resultaat de cumulatieve logaritmische normale verdeling
+MAX = MAX ## Geeft als resultaat de maximumwaarde in een lijst met argumenten
+MAXA = MAXA ## Geeft als resultaat de maximumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden
+MEDIAN = MEDIAAN ## Geeft als resultaat de mediaan van de opgegeven getallen
+MIN = MIN ## Geeft als resultaat de minimumwaarde in een lijst met argumenten
+MINA = MINA ## Geeft als resultaat de minimumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden
+MODE = MODUS ## Geeft als resultaat de meest voorkomende waarde in een gegevensverzameling
+NEGBINOMDIST = NEG.BINOM.VERD ## Geeft als resultaat de negatieve binomiaalverdeling
+NORMDIST = NORM.VERD ## Geeft als resultaat de cumulatieve normale verdeling
+NORMINV = NORM.INV ## Geeft als resultaat de inverse van de cumulatieve standaardnormale verdeling
+NORMSDIST = STAND.NORM.VERD ## Geeft als resultaat de cumulatieve standaardnormale verdeling
+NORMSINV = STAND.NORM.INV ## Geeft als resultaat de inverse van de cumulatieve normale verdeling
+PEARSON = PEARSON ## Geeft als resultaat de correlatiecoëfficiënt van Pearson
+PERCENTILE = PERCENTIEL ## Geeft als resultaat het k-de percentiel van waarden in een bereik
+PERCENTRANK = PERCENT.RANG ## Geeft als resultaat de positie, in procenten uitgedrukt, van een waarde in de rangorde van een gegevensverzameling
+PERMUT = PERMUTATIES ## Geeft als resultaat het aantal permutaties voor een gegeven aantal objecten
+POISSON = POISSON ## Geeft als resultaat de Poisson-verdeling
+PROB = KANS ## Geeft als resultaat de kans dat waarden zich tussen twee grenzen bevinden
+QUARTILE = KWARTIEL ## Geeft als resultaat het kwartiel van een gegevensverzameling
+RANK = RANG ## Geeft als resultaat het rangnummer van een getal in een lijst getallen
+RSQ = R.KWADRAAT ## Geeft als resultaat het kwadraat van de Pearson-correlatiecoëfficiënt
+SKEW = SCHEEFHEID ## Geeft als resultaat de mate van asymmetrie van een verdeling
+SLOPE = RICHTING ## Geeft als resultaat de richtingscoëfficiënt van een lineaire regressielijn
+SMALL = KLEINSTE ## Geeft als resultaat de op k-1 na kleinste waarde in een gegevensverzameling
+STANDARDIZE = NORMALISEREN ## Geeft als resultaat een genormaliseerde waarde
+STDEV = STDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef
+STDEVA = STDEVA ## Maakt een schatting van de standaarddeviatie op basis van een steekproef, inclusief getallen, tekst en logische waarden
+STDEVP = STDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie
+STDEVPA = STDEVPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden
+STEYX = STAND.FOUT.YX ## Geeft als resultaat de standaardfout in de voorspelde y-waarde voor elke x in een regressie
+TDIST = T.VERD ## Geeft als resultaat de Student T-verdeling
+TINV = T.INV ## Geeft als resultaat de inverse van de Student T-verdeling
+TREND = TREND ## Geeft als resultaat de waarden voor een lineaire trend
+TRIMMEAN = GETRIMD.GEM ## Geeft als resultaat het gemiddelde van waarden in een gegevensverzameling
+TTEST = T.TOETS ## Geeft als resultaat de kans met behulp van de Student T-toets
+VAR = VAR ## Maakt een schatting van de variantie op basis van een steekproef
+VARA = VARA ## Maakt een schatting van de variantie op basis van een steekproef, inclusief getallen, tekst en logische waarden
+VARP = VARP ## Berekent de variantie op basis van de volledige populatie
+VARPA = VARPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden
+WEIBULL = WEIBULL ## Geeft als resultaat de Weibull-verdeling
+ZTEST = Z.TOETS ## Geeft als resultaat de eenzijdige kanswaarde van een Z-toets
+
+
+##
+## Text functions Tekstfuncties
+##
+ASC = ASC ## Wijzigt Nederlandse letters of katakanatekens over de volle breedte (dubbel-bytetekens) binnen een tekenreeks in tekens over de halve breedte (enkel-bytetekens)
+BAHTTEXT = BAHT.TEKST ## Converteert een getal naar tekst met de valutanotatie ß (baht)
+CHAR = TEKEN ## Geeft als resultaat het teken dat hoort bij de opgegeven code
+CLEAN = WISSEN.CONTROL ## Verwijdert alle niet-afdrukbare tekens uit een tekst
+CODE = CODE ## Geeft als resultaat de numerieke code voor het eerste teken in een tekenreeks
+CONCATENATE = TEKST.SAMENVOEGEN ## Voegt verschillende tekstfragmenten samen tot één tekstfragment
+DOLLAR = EURO ## Converteert een getal naar tekst met de valutanotatie € (euro)
+EXACT = GELIJK ## Controleert of twee tekenreeksen identiek zijn
+FIND = VIND.ALLES ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
+FINDB = VIND.ALLES.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
+FIXED = VAST ## Maakt een getal als tekst met een vast aantal decimalen op
+JIS = JIS ## Wijzigt Nederlandse letters of katakanatekens over de halve breedte (enkel-bytetekens) binnen een tekenreeks in tekens over de volle breedte (dubbel-bytetekens)
+LEFT = LINKS ## Geeft als resultaat de meest linkse tekens in een tekenreeks
+LEFTB = LINKSB ## Geeft als resultaat de meest linkse tekens in een tekenreeks
+LEN = LENGTE ## Geeft als resultaat het aantal tekens in een tekenreeks
+LENB = LENGTEB ## Geeft als resultaat het aantal tekens in een tekenreeks
+LOWER = KLEINE.LETTERS ## Zet tekst om in kleine letters
+MID = MIDDEN ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft
+MIDB = DEELB ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft
+PHONETIC = FONETISCH ## Haalt de fonetische tekens (furigana) uit een tekenreeks op
+PROPER = BEGINLETTERS ## Zet de eerste letter van elk woord in een tekst om in een hoofdletter
+REPLACE = VERVANG ## Vervangt tekens binnen een tekst
+REPLACEB = VERVANGENB ## Vervangt tekens binnen een tekst
+REPT = HERHALING ## Herhaalt een tekst een aantal malen
+RIGHT = RECHTS ## Geeft als resultaat de meest rechtse tekens in een tekenreeks
+RIGHTB = RECHTSB ## Geeft als resultaat de meest rechtse tekens in een tekenreeks
+SEARCH = VIND.SPEC ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
+SEARCHB = VIND.SPEC.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
+SUBSTITUTE = SUBSTITUEREN ## Vervangt oude tekst door nieuwe tekst in een tekenreeks
+T = T ## Converteert de argumenten naar tekst
+TEXT = TEKST ## Maakt een getal op en converteert het getal naar tekst
+TRIM = SPATIES.WISSEN ## Verwijdert de spaties uit een tekst
+UPPER = HOOFDLETTERS ## Zet tekst om in hoofdletters
+VALUE = WAARDE ## Converteert tekst naar een getal
diff --git a/PHPExcel/locale/no/config b/PHPExcel/locale/no/config
new file mode 100644
index 0000000..5bf96a1
--- /dev/null
+++ b/PHPExcel/locale/no/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = kr
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULL!
+DIV0 = #DIV/0!
+VALUE = #VERDI!
+REF = #REF!
+NAME = #NAVN?
+NUM = #NUM!
+NA = #I/T
diff --git a/PHPExcel/locale/no/functions b/PHPExcel/locale/no/functions
new file mode 100644
index 0000000..917c7f7
--- /dev/null
+++ b/PHPExcel/locale/no/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Funksjonene Tillegg og Automatisering
+##
+GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data som er lagret i en pivottabellrapport
+
+
+##
+## Cube functions Kubefunksjoner
+##
+CUBEKPIMEMBER = KUBEKPIMEDLEM ## Returnerer navnet, egenskapen og målet for en viktig ytelsesindikator (KPI), og viser navnet og egenskapen i cellen. En KPI er en målbar enhet, for eksempel månedlig bruttoinntjening eller kvartalsvis inntjening per ansatt, og brukes til å overvåke ytelsen i en organisasjon.
+CUBEMEMBER = KUBEMEDLEM ## Returnerer et medlem eller en tuppel i et kubehierarki. Brukes til å validere at medlemmet eller tuppelen finnes i kuben.
+CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP ## Returnerer verdien til en medlemsegenskap i kuben. Brukes til å validere at et medlemsnavn finnes i kuben, og til å returnere den angitte egenskapen for dette medlemmet.
+CUBERANKEDMEMBER = KUBERANGERTMEDLEM ## Returnerer det n-te, eller rangerte, medlemmet i et sett. Brukes til å returnere ett eller flere elementer i et sett, for eksempel de 10 beste studentene.
+CUBESET = KUBESETT ## Definerer et beregnet sett av medlemmer eller tuppeler ved å sende et settuttrykk til kuben på serveren, noe som oppretter settet og deretter returnerer dette settet til Microsoft Office Excel.
+CUBESETCOUNT = KUBESETTANTALL ## Returnerer antallet elementer i et sett.
+CUBEVALUE = KUBEVERDI ## Returnerer en aggregert verdi fra en kube.
+
+
+##
+## Database functions Databasefunksjoner
+##
+DAVERAGE = DGJENNOMSNITT ## Returnerer gjennomsnittet av merkede databaseposter
+DCOUNT = DANTALL ## Teller celler som inneholder tall i en database
+DCOUNTA = DANTALLA ## Teller celler som ikke er tomme i en database
+DGET = DHENT ## Trekker ut fra en database en post som oppfyller angitte vilkår
+DMAX = DMAKS ## Returnerer maksimumsverdien fra merkede databaseposter
+DMIN = DMIN ## Returnerer minimumsverdien fra merkede databaseposter
+DPRODUCT = DPRODUKT ## Multipliserer verdiene i et bestemt felt med poster som oppfyller vilkårene i en database
+DSTDEV = DSTDAV ## Estimerer standardavviket basert på et utvalg av merkede databaseposter
+DSTDEVP = DSTAVP ## Beregner standardavviket basert på at merkede databaseposter utgjør hele populasjonen
+DSUM = DSUMMER ## Legger til tallene i feltkolonnen med poster, i databasen som oppfyller vilkårene
+DVAR = DVARIANS ## Estimerer variansen basert på et utvalg av merkede databaseposter
+DVARP = DVARIANSP ## Beregner variansen basert på at merkede databaseposter utgjør hele populasjonen
+
+
+##
+## Date and time functions Dato- og tidsfunksjoner
+##
+DATE = DATO ## Returnerer serienummeret som svarer til en bestemt dato
+DATEVALUE = DATOVERDI ## Konverterer en dato med tekstformat til et serienummer
+DAY = DAG ## Konverterer et serienummer til en dag i måneden
+DAYS360 = DAGER360 ## Beregner antall dager mellom to datoer basert på et år med 360 dager
+EDATE = DAG.ETTER ## Returnerer serienummeret som svarer til datoen som er det indikerte antall måneder før eller etter startdatoen
+EOMONTH = MÅNEDSSLUTT ## Returnerer serienummeret som svarer til siste dag i måneden, før eller etter et angitt antall måneder
+HOUR = TIME ## Konverterer et serienummer til en time
+MINUTE = MINUTT ## Konverterer et serienummer til et minutt
+MONTH = MÅNED ## Konverterer et serienummer til en måned
+NETWORKDAYS = NETT.ARBEIDSDAGER ## Returnerer antall hele arbeidsdager mellom to datoer
+NOW = NÅ ## Returnerer serienummeret som svarer til gjeldende dato og klokkeslett
+SECOND = SEKUND ## Konverterer et serienummer til et sekund
+TIME = TID ## Returnerer serienummeret som svarer til et bestemt klokkeslett
+TIMEVALUE = TIDSVERDI ## Konverterer et klokkeslett i tekstformat til et serienummer
+TODAY = IDAG ## Returnerer serienummeret som svarer til dagens dato
+WEEKDAY = UKEDAG ## Konverterer et serienummer til en ukedag
+WEEKNUM = UKENR ## Konverterer et serienummer til et tall som representerer hvilket nummer uken har i et år
+WORKDAY = ARBEIDSDAG ## Returnerer serienummeret som svarer til datoen før eller etter et angitt antall arbeidsdager
+YEAR = ÅR ## Konverterer et serienummer til et år
+YEARFRAC = ÅRDEL ## Returnerer brøkdelen for året, som svarer til antall hele dager mellom startdato og sluttdato
+
+
+##
+## Engineering functions Tekniske funksjoner
+##
+BESSELI = BESSELI ## Returnerer den endrede Bessel-funksjonen In(x)
+BESSELJ = BESSELJ ## Returnerer Bessel-funksjonen Jn(x)
+BESSELK = BESSELK ## Returnerer den endrede Bessel-funksjonen Kn(x)
+BESSELY = BESSELY ## Returnerer Bessel-funksjonen Yn(x)
+BIN2DEC = BINTILDES ## Konverterer et binært tall til et desimaltall
+BIN2HEX = BINTILHEKS ## Konverterer et binært tall til et heksadesimaltall
+BIN2OCT = BINTILOKT ## Konverterer et binært tall til et oktaltall
+COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koeffisienter til et komplekst tall
+CONVERT = KONVERTER ## Konverterer et tall fra ett målsystem til et annet
+DEC2BIN = DESTILBIN ## Konverterer et desimaltall til et binærtall
+DEC2HEX = DESTILHEKS ## Konverterer et heltall i 10-tallsystemet til et heksadesimalt tall
+DEC2OCT = DESTILOKT ## Konverterer et heltall i 10-tallsystemet til et oktaltall
+DELTA = DELTA ## Undersøker om to verdier er like
+ERF = FEILF ## Returnerer feilfunksjonen
+ERFC = FEILFK ## Returnerer den komplementære feilfunksjonen
+GESTEP = GRENSEVERDI ## Tester om et tall er større enn en terskelverdi
+HEX2BIN = HEKSTILBIN ## Konverterer et heksadesimaltall til et binært tall
+HEX2DEC = HEKSTILDES ## Konverterer et heksadesimalt tall til et heltall i 10-tallsystemet
+HEX2OCT = HEKSTILOKT ## Konverterer et heksadesimalt tall til et oktaltall
+IMABS = IMABS ## Returnerer absoluttverdien (koeffisienten) til et komplekst tall
+IMAGINARY = IMAGINÆR ## Returnerer den imaginære koeffisienten til et komplekst tall
+IMARGUMENT = IMARGUMENT ## Returnerer argumentet theta, som er en vinkel uttrykt i radianer
+IMCONJUGATE = IMKONJUGERT ## Returnerer den komplekse konjugaten til et komplekst tall
+IMCOS = IMCOS ## Returnerer cosinus til et komplekst tall
+IMDIV = IMDIV ## Returnerer kvotienten til to komplekse tall
+IMEXP = IMEKSP ## Returnerer eksponenten til et komplekst tall
+IMLN = IMLN ## Returnerer den naturlige logaritmen for et komplekst tall
+IMLOG10 = IMLOG10 ## Returnerer logaritmen med grunntall 10 for et komplekst tall
+IMLOG2 = IMLOG2 ## Returnerer logaritmen med grunntall 2 for et komplekst tall
+IMPOWER = IMOPPHØY ## Returnerer et komplekst tall opphøyd til en heltallspotens
+IMPRODUCT = IMPRODUKT ## Returnerer produktet av komplekse tall
+IMREAL = IMREELL ## Returnerer den reelle koeffisienten til et komplekst tall
+IMSIN = IMSIN ## Returnerer sinus til et komplekst tall
+IMSQRT = IMROT ## Returnerer kvadratroten av et komplekst tall
+IMSUB = IMSUB ## Returnerer differansen mellom to komplekse tall
+IMSUM = IMSUMMER ## Returnerer summen av komplekse tall
+OCT2BIN = OKTTILBIN ## Konverterer et oktaltall til et binært tall
+OCT2DEC = OKTTILDES ## Konverterer et oktaltall til et desimaltall
+OCT2HEX = OKTTILHEKS ## Konverterer et oktaltall til et heksadesimaltall
+
+
+##
+## Financial functions Økonomiske funksjoner
+##
+ACCRINT = PÅLØPT.PERIODISK.RENTE ## Returnerer påløpte renter for et verdipapir som betaler periodisk rente
+ACCRINTM = PÅLØPT.FORFALLSRENTE ## Returnerer den påløpte renten for et verdipapir som betaler rente ved forfall
+AMORDEGRC = AMORDEGRC ## Returnerer avskrivningen for hver regnskapsperiode ved hjelp av en avskrivingskoeffisient
+AMORLINC = AMORLINC ## Returnerer avskrivingen for hver regnskapsperiode
+COUPDAYBS = OBLIG.DAGER.FF ## Returnerer antall dager fra begynnelsen av den rentebærende perioden til innløsningsdatoen
+COUPDAYS = OBLIG.DAGER ## Returnerer antall dager i den rentebærende perioden som inneholder innløsningsdatoen
+COUPDAYSNC = OBLIG.DAGER.NF ## Returnerer antall dager fra betalingsdato til neste renteinnbetalingsdato
+COUPNCD = OBLIG.DAGER.EF ## Returnerer obligasjonsdatoen som kommer etter oppgjørsdatoen
+COUPNUM = OBLIG.ANTALL ## Returnerer antall obligasjoner som skal betales mellom oppgjørsdatoen og forfallsdatoen
+COUPPCD = OBLIG.DAG.FORRIGE ## Returnerer obligasjonsdatoen som kommer før oppgjørsdatoen
+CUMIPMT = SAMLET.RENTE ## Returnerer den kumulative renten som er betalt mellom to perioder
+CUMPRINC = SAMLET.HOVEDSTOL ## Returnerer den kumulative hovedstolen som er betalt for et lån mellom to perioder
+DB = DAVSKR ## Returnerer avskrivningen for et aktivum i en angitt periode, foretatt med fast degressiv avskrivning
+DDB = DEGRAVS ## Returnerer avskrivningen for et aktivum for en gitt periode, ved hjelp av dobbel degressiv avskrivning eller en metode som du selv angir
+DISC = DISKONTERT ## Returnerer diskonteringsraten for et verdipapir
+DOLLARDE = DOLLARDE ## Konverterer en valutapris uttrykt som en brøk, til en valutapris uttrykt som et desimaltall
+DOLLARFR = DOLLARBR ## Konverterer en valutapris uttrykt som et desimaltall, til en valutapris uttrykt som en brøk
+DURATION = VARIGHET ## Returnerer årlig varighet for et verdipapir med renter som betales periodisk
+EFFECT = EFFEKTIV.RENTE ## Returnerer den effektive årlige rentesatsen
+FV = SLUTTVERDI ## Returnerer fremtidig verdi for en investering
+FVSCHEDULE = SVPLAN ## Returnerer den fremtidige verdien av en inngående hovedstol etter å ha anvendt en serie med sammensatte rentesatser
+INTRATE = RENTESATS ## Returnerer rentefoten av et fullfinansiert verdipapir
+IPMT = RAVDRAG ## Returnerer betalte renter på en investering for en gitt periode
+IRR = IR ## Returnerer internrenten for en serie kontantstrømmer
+ISPMT = ER.AVDRAG ## Beregner renten som er betalt for en investering i løpet av en bestemt periode
+MDURATION = MVARIGHET ## Returnerer Macauleys modifiserte varighet for et verdipapir med en antatt pålydende verdi på kr 100,00
+MIRR = MODIR ## Returnerer internrenten der positive og negative kontantstrømmer finansieres med forskjellige satser
+NOMINAL = NOMINELL ## Returnerer årlig nominell rentesats
+NPER = PERIODER ## Returnerer antall perioder for en investering
+NPV = NNV ## Returnerer netto nåverdi for en investering, basert på en serie periodiske kontantstrømmer og en rentesats
+ODDFPRICE = AVVIKFP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde første periode
+ODDFYIELD = AVVIKFP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde første periode
+ODDLPRICE = AVVIKSP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde siste periode
+ODDLYIELD = AVVIKSP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde siste periode
+PMT = AVDRAG ## Returnerer periodisk betaling for en annuitet
+PPMT = AMORT ## Returnerer betalingen på hovedstolen for en investering i en gitt periode
+PRICE = PRIS ## Returnerer prisen per pålydende kr 100 for et verdipapir som gir periodisk avkastning
+PRICEDISC = PRIS.DISKONTERT ## Returnerer prisen per pålydende kr 100 for et diskontert verdipapir
+PRICEMAT = PRIS.FORFALL ## Returnerer prisen per pålydende kr 100 av et verdipapir som betaler rente ved forfall
+PV = NÅVERDI ## Returnerer nåverdien av en investering
+RATE = RENTE ## Returnerer rentesatsen per periode for en annuitet
+RECEIVED = MOTTATT.AVKAST ## Returnerer summen som mottas ved forfallsdato for et fullinvestert verdipapir
+SLN = LINAVS ## Returnerer den lineære avskrivningen for et aktivum i én periode
+SYD = ÅRSAVS ## Returnerer årsavskrivningen for et aktivum i en angitt periode
+TBILLEQ = TBILLEKV ## Returnerer den obligasjonsekvivalente avkastningen for en statsobligasjon
+TBILLPRICE = TBILLPRIS ## Returnerer prisen per pålydende kr 100 for en statsobligasjon
+TBILLYIELD = TBILLAVKASTNING ## Returnerer avkastningen til en statsobligasjon
+VDB = VERDIAVS ## Returnerer avskrivningen for et aktivum i en angitt periode eller delperiode, ved hjelp av degressiv avskrivning
+XIRR = XIR ## Returnerer internrenten for en serie kontantstrømmer som ikke nødvendigvis er periodiske
+XNPV = XNNV ## Returnerer netto nåverdi for en serie kontantstrømmer som ikke nødvendigvis er periodiske
+YIELD = AVKAST ## Returnerer avkastningen på et verdipapir som betaler periodisk rente
+YIELDDISC = AVKAST.DISKONTERT ## Returnerer årlig avkastning for et diskontert verdipapir, for eksempel en statskasseveksel
+YIELDMAT = AVKAST.FORFALL ## Returnerer den årlige avkastningen for et verdipapir som betaler rente ved forfallsdato
+
+
+##
+## Information functions Informasjonsfunksjoner
+##
+CELL = CELLE ## Returnerer informasjon om formatering, plassering eller innholdet til en celle
+ERROR.TYPE = FEIL.TYPE ## Returnerer et tall som svarer til en feiltype
+INFO = INFO ## Returnerer informasjon om gjeldende operativmiljø
+ISBLANK = ERTOM ## Returnerer SANN hvis verdien er tom
+ISERR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst annen feilverdi enn #I/T
+ISERROR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst feilverdi
+ISEVEN = ERPARTALL ## Returnerer SANN hvis tallet er et partall
+ISLOGICAL = ERLOGISK ## Returnerer SANN hvis verdien er en logisk verdi
+ISNA = ERIT ## Returnerer SANN hvis verdien er feilverdien #I/T
+ISNONTEXT = ERIKKETEKST ## Returnerer SANN hvis verdien ikke er tekst
+ISNUMBER = ERTALL ## Returnerer SANN hvis verdien er et tall
+ISODD = ERODDETALL ## Returnerer SANN hvis tallet er et oddetall
+ISREF = ERREF ## Returnerer SANN hvis verdien er en referanse
+ISTEXT = ERTEKST ## Returnerer SANN hvis verdien er tekst
+N = N ## Returnerer en verdi som er konvertert til et tall
+NA = IT ## Returnerer feilverdien #I/T
+TYPE = VERDITYPE ## Returnerer et tall som indikerer datatypen til en verdi
+
+
+##
+## Logical functions Logiske funksjoner
+##
+AND = OG ## Returnerer SANN hvis alle argumentene er lik SANN
+FALSE = USANN ## Returnerer den logiske verdien USANN
+IF = HVIS ## Angir en logisk test som skal utføres
+IFERROR = HVISFEIL ## Returnerer en verdi du angir hvis en formel evaluerer til en feil. Ellers returnerer den resultatet av formelen.
+NOT = IKKE ## Reverserer logikken til argumentet
+OR = ELLER ## Returnerer SANN hvis ett eller flere argumenter er lik SANN
+TRUE = SANN ## Returnerer den logiske verdien SANN
+
+
+##
+## Lookup and reference functions Oppslag- og referansefunksjoner
+##
+ADDRESS = ADRESSE ## Returnerer en referanse som tekst til en enkelt celle i et regneark
+AREAS = OMRÅDER ## Returnerer antall områder i en referanse
+CHOOSE = VELG ## Velger en verdi fra en liste med verdier
+COLUMN = KOLONNE ## Returnerer kolonnenummeret for en referanse
+COLUMNS = KOLONNER ## Returnerer antall kolonner i en referanse
+HLOOKUP = FINN.KOLONNE ## Leter i den øverste raden i en matrise og returnerer verdien for den angitte cellen
+HYPERLINK = HYPERKOBLING ## Oppretter en snarvei eller et hopp som åpner et dokument som er lagret på en nettverksserver, et intranett eller Internett
+INDEX = INDEKS ## Bruker en indeks til å velge en verdi fra en referanse eller matrise
+INDIRECT = INDIREKTE ## Returnerer en referanse angitt av en tekstverdi
+LOOKUP = SLÅ.OPP ## Slår opp verdier i en vektor eller matrise
+MATCH = SAMMENLIGNE ## Slår opp verdier i en referanse eller matrise
+OFFSET = FORSKYVNING ## Returnerer en referanseforskyvning fra en gitt referanse
+ROW = RAD ## Returnerer radnummeret for en referanse
+ROWS = RADER ## Returnerer antall rader i en referanse
+RTD = RTD ## Henter sanntidsdata fra et program som støtter COM-automatisering (automatisering: En måte å arbeide på med programobjekter fra et annet program- eller utviklingsverktøy. Tidligere kalt OLE-automatisering. Automatisering er en bransjestandard og en funksjon i Component Object Model (COM).)
+TRANSPOSE = TRANSPONER ## Returnerer transponeringen av en matrise
+VLOOKUP = FINN.RAD ## Leter i den første kolonnen i en matrise og flytter bortover raden for å returnere verdien til en celle
+
+
+##
+## Math and trigonometry functions Matematikk- og trigonometrifunksjoner
+##
+ABS = ABS ## Returnerer absoluttverdien til et tall
+ACOS = ARCCOS ## Returnerer arcus cosinus til et tall
+ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus til et tall
+ASIN = ARCSIN ## Returnerer arcus sinus til et tall
+ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus til et tall
+ATAN = ARCTAN ## Returnerer arcus tangens til et tall
+ATAN2 = ARCTAN2 ## Returnerer arcus tangens fra x- og y-koordinater
+ATANH = ARCTANH ## Returnerer den inverse hyperbolske tangens til et tall
+CEILING = AVRUND.GJELDENDE.MULTIPLUM ## Runder av et tall til nærmeste heltall eller til nærmeste signifikante multiplum
+COMBIN = KOMBINASJON ## Returnerer antall kombinasjoner for ett gitt antall objekter
+COS = COS ## Returnerer cosinus til et tall
+COSH = COSH ## Returnerer den hyperbolske cosinus til et tall
+DEGREES = GRADER ## Konverterer radianer til grader
+EVEN = AVRUND.TIL.PARTALL ## Runder av et tall oppover til nærmeste heltall som er et partall
+EXP = EKSP ## Returnerer e opphøyd i en angitt potens
+FACT = FAKULTET ## Returnerer fakultet til et tall
+FACTDOUBLE = DOBBELFAKT ## Returnerer et talls doble fakultet
+FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED ## Avrunder et tall nedover, mot null
+GCD = SFF ## Returnerer høyeste felles divisor
+INT = HELTALL ## Avrunder et tall nedover til nærmeste heltall
+LCM = MFM ## Returnerer minste felles multiplum
+LN = LN ## Returnerer den naturlige logaritmen til et tall
+LOG = LOG ## Returnerer logaritmen for et tall til et angitt grunntall
+LOG10 = LOG10 ## Returnerer logaritmen med grunntall 10 for et tall
+MDETERM = MDETERM ## Returnerer matrisedeterminanten til en matrise
+MINVERSE = MINVERS ## Returnerer den inverse matrisen til en matrise
+MMULT = MMULT ## Returnerer matriseproduktet av to matriser
+MOD = REST ## Returnerer resten fra en divisjon
+MROUND = MRUND ## Returnerer et tall avrundet til det ønskede multiplum
+MULTINOMIAL = MULTINOMINELL ## Returnerer det multinominelle for et sett med tall
+ODD = AVRUND.TIL.ODDETALL ## Runder av et tall oppover til nærmeste heltall som er et oddetall
+PI = PI ## Returnerer verdien av pi
+POWER = OPPHØYD.I ## Returnerer resultatet av et tall opphøyd i en potens
+PRODUCT = PRODUKT ## Multipliserer argumentene
+QUOTIENT = KVOTIENT ## Returnerer heltallsdelen av en divisjon
+RADIANS = RADIANER ## Konverterer grader til radianer
+RAND = TILFELDIG ## Returnerer et tilfeldig tall mellom 0 og 1
+RANDBETWEEN = TILFELDIGMELLOM ## Returnerer et tilfeldig tall innenfor et angitt område
+ROMAN = ROMERTALL ## Konverterer vanlige tall til romertall, som tekst
+ROUND = AVRUND ## Avrunder et tall til et angitt antall sifre
+ROUNDDOWN = AVRUND.NED ## Avrunder et tall nedover, mot null
+ROUNDUP = AVRUND.OPP ## Runder av et tall oppover, bort fra null
+SERIESSUM = SUMMER.REKKE ## Returnerer summen av en geometrisk rekke, basert på formelen
+SIGN = FORTEGN ## Returnerer fortegnet for et tall
+SIN = SIN ## Returnerer sinus til en gitt vinkel
+SINH = SINH ## Returnerer den hyperbolske sinus til et tall
+SQRT = ROT ## Returnerer en positiv kvadratrot
+SQRTPI = ROTPI ## Returnerer kvadratroten av (tall * pi)
+SUBTOTAL = DELSUM ## Returnerer en delsum i en liste eller database
+SUM = SUMMER ## Legger sammen argumentene
+SUMIF = SUMMERHVIS ## Legger sammen cellene angitt ved et gitt vilkår
+SUMIFS = SUMMER.HVIS.SETT ## Legger sammen cellene i et område som oppfyller flere vilkår
+SUMPRODUCT = SUMMERPRODUKT ## Returnerer summen av produktene av tilsvarende matrisekomponenter
+SUMSQ = SUMMERKVADRAT ## Returnerer kvadratsummen av argumentene
+SUMX2MY2 = SUMMERX2MY2 ## Returnerer summen av differansen av kvadratene for tilsvarende verdier i to matriser
+SUMX2PY2 = SUMMERX2PY2 ## Returnerer summen av kvadratsummene for tilsvarende verdier i to matriser
+SUMXMY2 = SUMMERXMY2 ## Returnerer summen av kvadratene av differansen for tilsvarende verdier i to matriser
+TAN = TAN ## Returnerer tangens for et tall
+TANH = TANH ## Returnerer den hyperbolske tangens for et tall
+TRUNC = AVKORT ## Korter av et tall til et heltall
+
+
+##
+## Statistical functions Statistiske funksjoner
+##
+AVEDEV = GJENNOMSNITTSAVVIK ## Returnerer datapunktenes gjennomsnittlige absoluttavvik fra middelverdien
+AVERAGE = GJENNOMSNITT ## Returnerer gjennomsnittet for argumentene
+AVERAGEA = GJENNOMSNITTA ## Returnerer gjennomsnittet for argumentene, inkludert tall, tekst og logiske verdier
+AVERAGEIF = GJENNOMSNITTHVIS ## Returnerer gjennomsnittet (aritmetisk gjennomsnitt) av alle cellene i et område som oppfyller et bestemt vilkår
+AVERAGEIFS = GJENNOMSNITT.HVIS.SETT ## Returnerer gjennomsnittet (aritmetisk middelverdi) av alle celler som oppfyller flere vilkår.
+BETADIST = BETA.FORDELING ## Returnerer den kumulative betafordelingsfunksjonen
+BETAINV = INVERS.BETA.FORDELING ## Returnerer den inverse verdien til fordelingsfunksjonen for en angitt betafordeling
+BINOMDIST = BINOM.FORDELING ## Returnerer den individuelle binomiske sannsynlighetsfordelingen
+CHIDIST = KJI.FORDELING ## Returnerer den ensidige sannsynligheten for en kjikvadrert fordeling
+CHIINV = INVERS.KJI.FORDELING ## Returnerer den inverse av den ensidige sannsynligheten for den kjikvadrerte fordelingen
+CHITEST = KJI.TEST ## Utfører testen for uavhengighet
+CONFIDENCE = KONFIDENS ## Returnerer konfidensintervallet til gjennomsnittet for en populasjon
+CORREL = KORRELASJON ## Returnerer korrelasjonskoeffisienten mellom to datasett
+COUNT = ANTALL ## Teller hvor mange tall som er i argumentlisten
+COUNTA = ANTALLA ## Teller hvor mange verdier som er i argumentlisten
+COUNTBLANK = TELLBLANKE ## Teller antall tomme celler i et område.
+COUNTIF = ANTALL.HVIS ## Teller antall celler i et område som oppfyller gitte vilkår
+COUNTIFS = ANTALL.HVIS.SETT ## Teller antallet ikke-tomme celler i et område som oppfyller flere vilkår
+COVAR = KOVARIANS ## Returnerer kovariansen, gjennomsnittet av produktene av parvise avvik
+CRITBINOM = GRENSE.BINOM ## Returnerer den minste verdien der den kumulative binomiske fordelingen er mindre enn eller lik en vilkårsverdi
+DEVSQ = AVVIK.KVADRERT ## Returnerer summen av kvadrerte avvik
+EXPONDIST = EKSP.FORDELING ## Returnerer eksponentialfordelingen
+FDIST = FFORDELING ## Returnerer F-sannsynlighetsfordelingen
+FINV = FFORDELING.INVERS ## Returnerer den inverse av den sannsynlige F-fordelingen
+FISHER = FISHER ## Returnerer Fisher-transformasjonen
+FISHERINV = FISHERINV ## Returnerer den inverse av Fisher-transformasjonen
+FORECAST = PROGNOSE ## Returnerer en verdi langs en lineær trend
+FREQUENCY = FREKVENS ## Returnerer en frekvensdistribusjon som en loddrett matrise
+FTEST = FTEST ## Returnerer resultatet av en F-test
+GAMMADIST = GAMMAFORDELING ## Returnerer gammafordelingen
+GAMMAINV = GAMMAINV ## Returnerer den inverse av den gammakumulative fordelingen
+GAMMALN = GAMMALN ## Returnerer den naturlige logaritmen til gammafunksjonen G(x)
+GEOMEAN = GJENNOMSNITT.GEOMETRISK ## Returnerer den geometriske middelverdien
+GROWTH = VEKST ## Returnerer verdier langs en eksponentiell trend
+HARMEAN = GJENNOMSNITT.HARMONISK ## Returnerer den harmoniske middelverdien
+HYPGEOMDIST = HYPGEOM.FORDELING ## Returnerer den hypergeometriske fordelingen
+INTERCEPT = SKJÆRINGSPUNKT ## Returnerer skjæringspunktet til den lineære regresjonslinjen
+KURT = KURT ## Returnerer kurtosen til et datasett
+LARGE = N.STØRST ## Returnerer den n-te største verdien i et datasett
+LINEST = RETTLINJE ## Returnerer parameterne til en lineær trend
+LOGEST = KURVE ## Returnerer parameterne til en eksponentiell trend
+LOGINV = LOGINV ## Returnerer den inverse lognormale fordelingen
+LOGNORMDIST = LOGNORMFORD ## Returnerer den kumulative lognormale fordelingen
+MAX = STØRST ## Returnerer maksimumsverdien i en argumentliste
+MAXA = MAKSA ## Returnerer maksimumsverdien i en argumentliste, inkludert tall, tekst og logiske verdier
+MEDIAN = MEDIAN ## Returnerer medianen til tallene som er gitt
+MIN = MIN ## Returnerer minimumsverdien i en argumentliste
+MINA = MINA ## Returnerer den minste verdien i en argumentliste, inkludert tall, tekst og logiske verdier
+MODE = MODUS ## Returnerer den vanligste verdien i et datasett
+NEGBINOMDIST = NEGBINOM.FORDELING ## Returnerer den negative binomiske fordelingen
+NORMDIST = NORMALFORDELING ## Returnerer den kumulative normalfordelingen
+NORMINV = NORMINV ## Returnerer den inverse kumulative normalfordelingen
+NORMSDIST = NORMSFORDELING ## Returnerer standard kumulativ normalfordeling
+NORMSINV = NORMSINV ## Returnerer den inverse av den den kumulative standard normalfordelingen
+PEARSON = PEARSON ## Returnerer produktmomentkorrelasjonskoeffisienten, Pearson
+PERCENTILE = PERSENTIL ## Returnerer den n-te persentil av verdiene i et område
+PERCENTRANK = PROSENTDEL ## Returnerer prosentrangeringen av en verdi i et datasett
+PERMUT = PERMUTER ## Returnerer antall permutasjoner for et gitt antall objekter
+POISSON = POISSON ## Returnerer Poissons sannsynlighetsfordeling
+PROB = SANNSYNLIG ## Returnerer sannsynligheten for at verdier i et område ligger mellom to grenser
+QUARTILE = KVARTIL ## Returnerer kvartilen til et datasett
+RANK = RANG ## Returnerer rangeringen av et tall, eller plassen tallet har i en rekke
+RSQ = RKVADRAT ## Returnerer kvadratet av produktmomentkorrelasjonskoeffisienten (Pearsons r)
+SKEW = SKJEVFORDELING ## Returnerer skjevheten i en fordeling
+SLOPE = STIGNINGSTALL ## Returnerer stigningtallet for den lineære regresjonslinjen
+SMALL = N.MINST ## Returnerer den n-te minste verdien i et datasett
+STANDARDIZE = NORMALISER ## Returnerer en normalisert verdi
+STDEV = STDAV ## Estimere standardavvik på grunnlag av et utvalg
+STDEVA = STDAVVIKA ## Estimerer standardavvik basert på et utvalg, inkludert tall, tekst og logiske verdier
+STDEVP = STDAVP ## Beregner standardavvik basert på hele populasjonen
+STDEVPA = STDAVVIKPA ## Beregner standardavvik basert på hele populasjonen, inkludert tall, tekst og logiske verdier
+STEYX = STANDARDFEIL ## Returnerer standardfeilen for den predikerte y-verdien for hver x i regresjonen
+TDIST = TFORDELING ## Returnerer en Student t-fordeling
+TINV = TINV ## Returnerer den inverse Student t-fordelingen
+TREND = TREND ## Returnerer verdier langs en lineær trend
+TRIMMEAN = TRIMMET.GJENNOMSNITT ## Returnerer den interne middelverdien til et datasett
+TTEST = TTEST ## Returnerer sannsynligheten assosiert med en Student t-test
+VAR = VARIANS ## Estimerer varians basert på et utvalg
+VARA = VARIANSA ## Estimerer varians basert på et utvalg, inkludert tall, tekst og logiske verdier
+VARP = VARIANSP ## Beregner varians basert på hele populasjonen
+VARPA = VARIANSPA ## Beregner varians basert på hele populasjonen, inkludert tall, tekst og logiske verdier
+WEIBULL = WEIBULL.FORDELING ## Returnerer Weibull-fordelingen
+ZTEST = ZTEST ## Returnerer den ensidige sannsynlighetsverdien for en z-test
+
+
+##
+## Text functions Tekstfunksjoner
+##
+ASC = STIGENDE ## Endrer fullbreddes (dobbeltbyte) engelske bokstaver eller katakana i en tegnstreng, til halvbreddes (enkeltbyte) tegn
+BAHTTEXT = BAHTTEKST ## Konverterer et tall til tekst, og bruker valutaformatet ß (baht)
+CHAR = TEGNKODE ## Returnerer tegnet som svarer til kodenummeret
+CLEAN = RENSK ## Fjerner alle tegn som ikke kan skrives ut, fra teksten
+CODE = KODE ## Returnerer en numerisk kode for det første tegnet i en tekststreng
+CONCATENATE = KJEDE.SAMMEN ## Slår sammen flere tekstelementer til ett tekstelement
+DOLLAR = VALUTA ## Konverterer et tall til tekst, og bruker valutaformatet $ (dollar)
+EXACT = EKSAKT ## Kontrollerer om to tekstverdier er like
+FIND = FINN ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver)
+FINDB = FINNB ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver)
+FIXED = FASTSATT ## Formaterer et tall som tekst med et bestemt antall desimaler
+JIS = JIS ## Endrer halvbreddes (enkeltbyte) engelske bokstaver eller katakana i en tegnstreng, til fullbreddes (dobbeltbyte) tegn
+LEFT = VENSTRE ## Returnerer tegnene lengst til venstre i en tekstverdi
+LEFTB = VENSTREB ## Returnerer tegnene lengst til venstre i en tekstverdi
+LEN = LENGDE ## Returnerer antall tegn i en tekststreng
+LENB = LENGDEB ## Returnerer antall tegn i en tekststreng
+LOWER = SMÅ ## Konverterer tekst til små bokstaver
+MID = DELTEKST ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir
+MIDB = DELTEKSTB ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir
+PHONETIC = FURIGANA ## Trekker ut fonetiske tegn (furigana) fra en tekststreng
+PROPER = STOR.FORBOKSTAV ## Gir den første bokstaven i hvert ord i en tekstverdi stor forbokstav
+REPLACE = ERSTATT ## Erstatter tegn i en tekst
+REPLACEB = ERSTATTB ## Erstatter tegn i en tekst
+REPT = GJENTA ## Gjentar tekst et gitt antall ganger
+RIGHT = HØYRE ## Returnerer tegnene lengst til høyre i en tekstverdi
+RIGHTB = HØYREB ## Returnerer tegnene lengst til høyre i en tekstverdi
+SEARCH = SØK ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver)
+SEARCHB = SØKB ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver)
+SUBSTITUTE = BYTT.UT ## Bytter ut gammel tekst med ny tekst i en tekststreng
+T = T ## Konverterer argumentene til tekst
+TEXT = TEKST ## Formaterer et tall og konverterer det til tekst
+TRIM = TRIMME ## Fjerner mellomrom fra tekst
+UPPER = STORE ## Konverterer tekst til store bokstaver
+VALUE = VERDI ## Konverterer et tekstargument til et tall
diff --git a/PHPExcel/locale/pl/config b/PHPExcel/locale/pl/config
new file mode 100644
index 0000000..5061311
--- /dev/null
+++ b/PHPExcel/locale/pl/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = zł
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #ZERO!
+DIV0 = #DZIEL/0!
+VALUE = #ARG!
+REF = #ADR!
+NAME = #NAZWA?
+NUM = #LICZBA!
+NA = #N/D!
diff --git a/PHPExcel/locale/pl/functions b/PHPExcel/locale/pl/functions
new file mode 100644
index 0000000..14499c0
--- /dev/null
+++ b/PHPExcel/locale/pl/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Funkcje dodatków i automatyzacji
+##
+GETPIVOTDATA = WEŹDANETABELI ## Zwraca dane przechowywane w raporcie tabeli przestawnej.
+
+
+##
+## Cube functions Funkcje modułów
+##
+CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU ## Zwraca nazwę, właściwość i miarę kluczowego wskaźnika wydajności (KPI) oraz wyświetla nazwę i właściwość w komórce. Wskaźnik KPI jest miarą ilościową, taką jak miesięczny zysk brutto lub kwartalna fluktuacja pracowników, używaną do monitorowania wydajności organizacji.
+CUBEMEMBER = ELEMENT.MODUŁU ## Zwraca element lub krotkę z hierarchii modułu. Służy do sprawdzania, czy element lub krotka istnieje w module.
+CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU ## Zwraca wartość właściwości elementu w module. Służy do sprawdzania, czy nazwa elementu istnieje w module, i zwracania określonej właściwości dla tego elementu.
+CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU ## Zwraca n-ty (albo uszeregowany) element zestawu. Służy do zwracania elementu lub elementów zestawu, na przykład najlepszego sprzedawcy lub 10 najlepszych studentów.
+CUBESET = ZESTAW.MODUŁÓW ## Definiuje obliczony zestaw elementów lub krotek, wysyłając wyrażenie zestawu do serwera modułu, który tworzy zestaw i zwraca go do programu Microsoft Office Excel.
+CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU ## Zwraca liczbę elementów zestawu.
+CUBEVALUE = WARTOŚĆ.MODUŁU ## Zwraca zagregowaną wartość z modułu.
+
+
+##
+## Database functions Funkcje baz danych
+##
+DAVERAGE = BD.ŚREDNIA ## Zwraca wartość średniej wybranych wpisów bazy danych.
+DCOUNT = BD.ILE.REKORDÓW ## Zlicza komórki zawierające liczby w bazie danych.
+DCOUNTA = BD.ILE.REKORDÓW.A ## Zlicza niepuste komórki w bazie danych.
+DGET = BD.POLE ## Wyodrębnia z bazy danych jeden rekord spełniający określone kryteria.
+DMAX = BD.MAX ## Zwraca wartość maksymalną z wybranych wpisów bazy danych.
+DMIN = BD.MIN ## Zwraca wartość minimalną z wybranych wpisów bazy danych.
+DPRODUCT = BD.ILOCZYN ## Mnoży wartości w konkretnym, spełniającym kryteria polu rekordów bazy danych.
+DSTDEV = BD.ODCH.STANDARD ## Szacuje odchylenie standardowe na podstawie próbki z wybranych wpisów bazy danych.
+DSTDEVP = BD.ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji wybranych wpisów bazy danych.
+DSUM = BD.SUMA ## Dodaje liczby w kolumnie pól rekordów bazy danych, które spełniają kryteria.
+DVAR = BD.WARIANCJA ## Szacuje wariancję na podstawie próbki z wybranych wpisów bazy danych.
+DVARP = BD.WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji wybranych wpisów bazy danych.
+
+
+##
+## Date and time functions Funkcje dat, godzin i czasu
+##
+DATE = DATA ## Zwraca liczbę seryjną dla wybranej daty.
+DATEVALUE = DATA.WARTOŚĆ ## Konwertuje datę w formie tekstu na liczbę seryjną.
+DAY = DZIEŃ ## Konwertuje liczbę seryjną na dzień miesiąca.
+DAYS360 = DNI.360 ## Oblicza liczbę dni między dwiema datami na podstawie roku 360-dniowego.
+EDATE = UPŁDNI ## Zwraca liczbę seryjną daty jako wskazaną liczbę miesięcy przed określoną datą początkową lub po niej.
+EOMONTH = EOMONTH ## Zwraca liczbę seryjną ostatniego dnia miesiąca przed określoną liczbą miesięcy lub po niej.
+HOUR = GODZINA ## Konwertuje liczbę seryjną na godzinę.
+MINUTE = MINUTA ## Konwertuje liczbę seryjną na minutę.
+MONTH = MIESIĄC ## Konwertuje liczbę seryjną na miesiąc.
+NETWORKDAYS = NETWORKDAYS ## Zwraca liczbę pełnych dni roboczych między dwiema datami.
+NOW = TERAZ ## Zwraca liczbę seryjną bieżącej daty i godziny.
+SECOND = SEKUNDA ## Konwertuje liczbę seryjną na sekundę.
+TIME = CZAS ## Zwraca liczbę seryjną określonego czasu.
+TIMEVALUE = CZAS.WARTOŚĆ ## Konwertuje czas w formie tekstu na liczbę seryjną.
+TODAY = DZIŚ ## Zwraca liczbę seryjną dla daty bieżącej.
+WEEKDAY = DZIEŃ.TYG ## Konwertuje liczbę seryjną na dzień tygodnia.
+WEEKNUM = WEEKNUM ## Konwertuje liczbę seryjną na liczbę reprezentującą numer tygodnia w roku.
+WORKDAY = WORKDAY ## Zwraca liczbę seryjną dla daty przed określoną liczbą dni roboczych lub po niej.
+YEAR = ROK ## Konwertuje liczbę seryjną na rok.
+YEARFRAC = YEARFRAC ## Zwraca część roku reprezentowaną przez pełną liczbę dni między datą początkową a datą końcową.
+
+
+##
+## Engineering functions Funkcje inżynierskie
+##
+BESSELI = BESSELI ## Zwraca wartość zmodyfikowanej funkcji Bessela In(x).
+BESSELJ = BESSELJ ## Zwraca wartość funkcji Bessela Jn(x).
+BESSELK = BESSELK ## Zwraca wartość zmodyfikowanej funkcji Bessela Kn(x).
+BESSELY = BESSELY ## Zwraca wartość funkcji Bessela Yn(x).
+BIN2DEC = BIN2DEC ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci dziesiętnej.
+BIN2HEX = BIN2HEX ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci szesnastkowej.
+BIN2OCT = BIN2OCT ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci ósemkowej.
+COMPLEX = COMPLEX ## Konwertuje część rzeczywistą i urojoną na liczbę zespoloną.
+CONVERT = CONVERT ## Konwertuje liczbę z jednego systemu miar na inny.
+DEC2BIN = DEC2BIN ## Konwertuje liczbę w postaci dziesiętnej na postać dwójkową.
+DEC2HEX = DEC2HEX ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci szesnastkowej.
+DEC2OCT = DEC2OCT ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci ósemkowej.
+DELTA = DELTA ## Sprawdza, czy dwie wartości są równe.
+ERF = ERF ## Zwraca wartość funkcji błędu.
+ERFC = ERFC ## Zwraca wartość komplementarnej funkcji błędu.
+GESTEP = GESTEP ## Sprawdza, czy liczba jest większa niż wartość progowa.
+HEX2BIN = HEX2BIN ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dwójkowej.
+HEX2DEC = HEX2DEC ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dziesiętnej.
+HEX2OCT = HEX2OCT ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci ósemkowej.
+IMABS = IMABS ## Zwraca wartość bezwzględną (moduł) liczby zespolonej.
+IMAGINARY = IMAGINARY ## Zwraca wartość części urojonej liczby zespolonej.
+IMARGUMENT = IMARGUMENT ## Zwraca wartość argumentu liczby zespolonej, przy czym kąt wyrażony jest w radianach.
+IMCONJUGATE = IMCONJUGATE ## Zwraca wartość liczby sprzężonej danej liczby zespolonej.
+IMCOS = IMCOS ## Zwraca wartość cosinusa liczby zespolonej.
+IMDIV = IMDIV ## Zwraca wartość ilorazu dwóch liczb zespolonych.
+IMEXP = IMEXP ## Zwraca postać wykładniczą liczby zespolonej.
+IMLN = IMLN ## Zwraca wartość logarytmu naturalnego liczby zespolonej.
+IMLOG10 = IMLOG10 ## Zwraca wartość logarytmu dziesiętnego liczby zespolonej.
+IMLOG2 = IMLOG2 ## Zwraca wartość logarytmu liczby zespolonej przy podstawie 2.
+IMPOWER = IMPOWER ## Zwraca wartość liczby zespolonej podniesionej do potęgi całkowitej.
+IMPRODUCT = IMPRODUCT ## Zwraca wartość iloczynu liczb zespolonych.
+IMREAL = IMREAL ## Zwraca wartość części rzeczywistej liczby zespolonej.
+IMSIN = IMSIN ## Zwraca wartość sinusa liczby zespolonej.
+IMSQRT = IMSQRT ## Zwraca wartość pierwiastka kwadratowego z liczby zespolonej.
+IMSUB = IMSUB ## Zwraca wartość różnicy dwóch liczb zespolonych.
+IMSUM = IMSUM ## Zwraca wartość sumy liczb zespolonych.
+OCT2BIN = OCT2BIN ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dwójkowej.
+OCT2DEC = OCT2DEC ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dziesiętnej.
+OCT2HEX = OCT2HEX ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci szesnastkowej.
+
+
+##
+## Financial functions Funkcje finansowe
+##
+ACCRINT = ACCRINT ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem okresowym.
+ACCRINTM = ACCRINTM ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem w terminie wykupu.
+AMORDEGRC = AMORDEGRC ## Zwraca amortyzację dla każdego okresu rozliczeniowego z wykorzystaniem współczynnika amortyzacji.
+AMORLINC = AMORLINC ## Zwraca amortyzację dla każdego okresu rozliczeniowego.
+COUPDAYBS = COUPDAYBS ## Zwraca liczbę dni od początku okresu dywidendy do dnia rozliczeniowego.
+COUPDAYS = COUPDAYS ## Zwraca liczbę dni w okresie dywidendy, z uwzględnieniem dnia rozliczeniowego.
+COUPDAYSNC = COUPDAYSNC ## Zwraca liczbę dni od dnia rozliczeniowego do daty następnego dnia dywidendy.
+COUPNCD = COUPNCD ## Zwraca dzień następnej dywidendy po dniu rozliczeniowym.
+COUPNUM = COUPNUM ## Zwraca liczbę dywidend płatnych między dniem rozliczeniowym a dniem wykupu.
+COUPPCD = COUPPCD ## Zwraca dzień poprzedniej dywidendy przed dniem rozliczeniowym.
+CUMIPMT = CUMIPMT ## Zwraca wartość procentu składanego płatnego między dwoma okresami.
+CUMPRINC = CUMPRINC ## Zwraca wartość kapitału skumulowanego spłaty pożyczki między dwoma okresami.
+DB = DB ## Zwraca amortyzację środka trwałego w danym okresie metodą degresywną z zastosowaniem stałej bazowej.
+DDB = DDB ## Zwraca amortyzację środka trwałego za podany okres metodą degresywną z zastosowaniem podwójnej bazowej lub metodą określoną przez użytkownika.
+DISC = DISC ## Zwraca wartość stopy dyskontowej papieru wartościowego.
+DOLLARDE = DOLLARDE ## Konwertuje cenę w postaci ułamkowej na cenę wyrażoną w postaci dziesiętnej.
+DOLLARFR = DOLLARFR ## Konwertuje cenę wyrażoną w postaci dziesiętnej na cenę wyrażoną w postaci ułamkowej.
+DURATION = DURATION ## Zwraca wartość rocznego przychodu z papieru wartościowego o okresowych wypłatach oprocentowania.
+EFFECT = EFFECT ## Zwraca wartość efektywnej rocznej stopy procentowej.
+FV = FV ## Zwraca przyszłą wartość lokaty.
+FVSCHEDULE = FVSCHEDULE ## Zwraca przyszłą wartość kapitału początkowego wraz z szeregiem procentów składanych.
+INTRATE = INTRATE ## Zwraca wartość stopy procentowej papieru wartościowego całkowicie ulokowanego.
+IPMT = IPMT ## Zwraca wysokość spłaty oprocentowania lokaty za dany okres.
+IRR = IRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii przepływów gotówkowych.
+ISPMT = ISPMT ## Oblicza wysokość spłaty oprocentowania za dany okres lokaty.
+MDURATION = MDURATION ## Zwraca wartość zmodyfikowanego okresu Macauleya dla papieru wartościowego o założonej wartości nominalnej 100 zł.
+MIRR = MIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla przypadku, gdy dodatnie i ujemne przepływy gotówkowe mają różne stopy.
+NOMINAL = NOMINAL ## Zwraca wysokość nominalnej rocznej stopy procentowej.
+NPER = NPER ## Zwraca liczbę okresów dla lokaty.
+NPV = NPV ## Zwraca wartość bieżącą netto lokaty na podstawie szeregu okresowych przepływów gotówkowych i stopy dyskontowej.
+ODDFPRICE = ODDFPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym pierwszym okresem.
+ODDFYIELD = ODDFYIELD ## Zwraca rentowność papieru wartościowego z nietypowym pierwszym okresem.
+ODDLPRICE = ODDLPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym ostatnim okresem.
+ODDLYIELD = ODDLYIELD ## Zwraca rentowność papieru wartościowego z nietypowym ostatnim okresem.
+PMT = PMT ## Zwraca wartość okresowej płatności raty rocznej.
+PPMT = PPMT ## Zwraca wysokość spłaty kapitału w przypadku lokaty dla danego okresu.
+PRICE = PRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem okresowym.
+PRICEDISC = PRICEDISC ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego zdyskontowanego.
+PRICEMAT = PRICEMAT ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem w terminie wykupu.
+PV = PV ## Zwraca wartość bieżącą lokaty.
+RATE = RATE ## Zwraca wysokość stopy procentowej w okresie raty rocznej.
+RECEIVED = RECEIVED ## Zwraca wartość kapitału otrzymanego przy wykupie papieru wartościowego całkowicie ulokowanego.
+SLN = SLN ## Zwraca amortyzację środka trwałego za jeden okres metodą liniową.
+SYD = SYD ## Zwraca amortyzację środka trwałego za dany okres metodą sumy cyfr lat amortyzacji.
+TBILLEQ = TBILLEQ ## Zwraca rentowność ekwiwalentu obligacji dla bonu skarbowego.
+TBILLPRICE = TBILLPRICE ## Zwraca cenę za 100 zł wartości nominalnej bonu skarbowego.
+TBILLYIELD = TBILLYIELD ## Zwraca rentowność bonu skarbowego.
+VDB = VDB ## Oblicza amortyzację środka trwałego w danym okresie lub jego części metodą degresywną.
+XIRR = XIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych.
+XNPV = XNPV ## Zwraca wartość bieżącą netto dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych.
+YIELD = YIELD ## Zwraca rentowność papieru wartościowego z oprocentowaniem okresowym.
+YIELDDISC = YIELDDISC ## Zwraca roczną rentowność zdyskontowanego papieru wartościowego, na przykład bonu skarbowego.
+YIELDMAT = YIELDMAT ## Zwraca roczną rentowność papieru wartościowego oprocentowanego przy wykupie.
+
+
+##
+## Information functions Funkcje informacyjne
+##
+CELL = KOMÓRKA ## Zwraca informacje o formacie, położeniu lub zawartości komórki.
+ERROR.TYPE = NR.BŁĘDU ## Zwraca liczbę odpowiadającą typowi błędu.
+INFO = INFO ## Zwraca informację o aktualnym środowisku pracy.
+ISBLANK = CZY.PUSTA ## Zwraca wartość PRAWDA, jeśli wartość jest pusta.
+ISERR = CZY.BŁ ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu, z wyjątkiem #N/D!.
+ISERROR = CZY.BŁĄD ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu.
+ISEVEN = ISEVEN ## Zwraca wartość PRAWDA, jeśli liczba jest parzysta.
+ISLOGICAL = CZY.LOGICZNA ## Zwraca wartość PRAWDA, jeśli wartość jest wartością logiczną.
+ISNA = CZY.BRAK ## Zwraca wartość PRAWDA, jeśli wartość jest wartością błędu #N/D!.
+ISNONTEXT = CZY.NIE.TEKST ## Zwraca wartość PRAWDA, jeśli wartość nie jest tekstem.
+ISNUMBER = CZY.LICZBA ## Zwraca wartość PRAWDA, jeśli wartość jest liczbą.
+ISODD = ISODD ## Zwraca wartość PRAWDA, jeśli liczba jest nieparzysta.
+ISREF = CZY.ADR ## Zwraca wartość PRAWDA, jeśli wartość jest odwołaniem.
+ISTEXT = CZY.TEKST ## Zwraca wartość PRAWDA, jeśli wartość jest tekstem.
+N = L ## Zwraca wartość przekonwertowaną na postać liczbową.
+NA = BRAK ## Zwraca wartość błędu #N/D!.
+TYPE = TYP ## Zwraca liczbę wskazującą typ danych wartości.
+
+
+##
+## Logical functions Funkcje logiczne
+##
+AND = ORAZ ## Zwraca wartość PRAWDA, jeśli wszystkie argumenty mają wartość PRAWDA.
+FALSE = FAŁSZ ## Zwraca wartość logiczną FAŁSZ.
+IF = JEŻELI ## Określa warunek logiczny do sprawdzenia.
+IFERROR = JEŻELI.BŁĄD ## Zwraca określoną wartość, jeśli wynikiem obliczenia formuły jest błąd; w przeciwnym przypadku zwraca wynik formuły.
+NOT = NIE ## Odwraca wartość logiczną argumentu.
+OR = LUB ## Zwraca wartość PRAWDA, jeśli co najmniej jeden z argumentów ma wartość PRAWDA.
+TRUE = PRAWDA ## Zwraca wartość logiczną PRAWDA.
+
+
+##
+## Lookup and reference functions Funkcje wyszukiwania i odwołań
+##
+ADDRESS = ADRES ## Zwraca odwołanie do jednej komórki w arkuszu jako wartość tekstową.
+AREAS = OBSZARY ## Zwraca liczbę obszarów występujących w odwołaniu.
+CHOOSE = WYBIERZ ## Wybiera wartość z listy wartości.
+COLUMN = NR.KOLUMNY ## Zwraca numer kolumny z odwołania.
+COLUMNS = LICZBA.KOLUMN ## Zwraca liczbę kolumn dla danego odwołania.
+HLOOKUP = WYSZUKAJ.POZIOMO ## Przegląda górny wiersz tablicy i zwraca wartość wskazanej komórki.
+HYPERLINK = HIPERŁĄCZE ## Tworzy skrót lub skok, który pozwala otwierać dokument przechowywany na serwerze sieciowym, w sieci intranet lub w Internecie.
+INDEX = INDEKS ## Używa indeksu do wybierania wartości z odwołania lub tablicy.
+INDIRECT = ADR.POŚR ## Zwraca odwołanie określone przez wartość tekstową.
+LOOKUP = WYSZUKAJ ## Wyszukuje wartości w wektorze lub tablicy.
+MATCH = PODAJ.POZYCJĘ ## Wyszukuje wartości w odwołaniu lub w tablicy.
+OFFSET = PRZESUNIĘCIE ## Zwraca adres przesunięty od danego odwołania.
+ROW = WIERSZ ## Zwraca numer wiersza odwołania.
+ROWS = ILE.WIERSZY ## Zwraca liczbę wierszy dla danego odwołania.
+RTD = RTD ## Pobiera dane w czasie rzeczywistym z programu obsługującego automatyzację COM (Automatyzacja: Sposób pracy z obiektami aplikacji pochodzącymi z innej aplikacji lub narzędzia projektowania. Nazywana wcześniej Automatyzacją OLE, Automatyzacja jest standardem przemysłowym i funkcją obiektowego modelu składników (COM, Component Object Model).).
+TRANSPOSE = TRANSPONUJ ## Zwraca transponowaną tablicę.
+VLOOKUP = WYSZUKAJ.PIONOWO ## Przeszukuje pierwszą kolumnę tablicy i przechodzi wzdłuż wiersza, aby zwrócić wartość komórki.
+
+
+##
+## Math and trigonometry functions Funkcje matematyczne i trygonometryczne
+##
+ABS = MODUŁ.LICZBY ## Zwraca wartość absolutną liczby.
+ACOS = ACOS ## Zwraca arcus cosinus liczby.
+ACOSH = ACOSH ## Zwraca arcus cosinus hiperboliczny liczby.
+ASIN = ASIN ## Zwraca arcus sinus liczby.
+ASINH = ASINH ## Zwraca arcus sinus hiperboliczny liczby.
+ATAN = ATAN ## Zwraca arcus tangens liczby.
+ATAN2 = ATAN2 ## Zwraca arcus tangens liczby na podstawie współrzędnych x i y.
+ATANH = ATANH ## Zwraca arcus tangens hiperboliczny liczby.
+CEILING = ZAOKR.W.GÓRĘ ## Zaokrągla liczbę do najbliższej liczby całkowitej lub do najbliższej wielokrotności dokładności.
+COMBIN = KOMBINACJE ## Zwraca liczbę kombinacji dla danej liczby obiektów.
+COS = COS ## Zwraca cosinus liczby.
+COSH = COSH ## Zwraca cosinus hiperboliczny liczby.
+DEGREES = STOPNIE ## Konwertuje radiany na stopnie.
+EVEN = ZAOKR.DO.PARZ ## Zaokrągla liczbę w górę do najbliższej liczby parzystej.
+EXP = EXP ## Zwraca wartość liczby e podniesionej do potęgi określonej przez podaną liczbę.
+FACT = SILNIA ## Zwraca silnię liczby.
+FACTDOUBLE = FACTDOUBLE ## Zwraca podwójną silnię liczby.
+FLOOR = ZAOKR.W.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera.
+GCD = GCD ## Zwraca największy wspólny dzielnik.
+INT = ZAOKR.DO.CAŁK ## Zaokrągla liczbę w dół do najbliższej liczby całkowitej.
+LCM = LCM ## Zwraca najmniejszą wspólną wielokrotność.
+LN = LN ## Zwraca logarytm naturalny podanej liczby.
+LOG = LOG ## Zwraca logarytm danej liczby przy zadanej podstawie.
+LOG10 = LOG10 ## Zwraca logarytm dziesiętny liczby.
+MDETERM = WYZNACZNIK.MACIERZY ## Zwraca wyznacznik macierzy tablicy.
+MINVERSE = MACIERZ.ODW ## Zwraca odwrotność macierzy tablicy.
+MMULT = MACIERZ.ILOCZYN ## Zwraca iloczyn macierzy dwóch tablic.
+MOD = MOD ## Zwraca resztę z dzielenia.
+MROUND = MROUND ## Zwraca liczbę zaokrągloną do żądanej wielokrotności.
+MULTINOMIAL = MULTINOMIAL ## Zwraca wielomian dla zbioru liczb.
+ODD = ZAOKR.DO.NPARZ ## Zaokrągla liczbę w górę do najbliższej liczby nieparzystej.
+PI = PI ## Zwraca wartość liczby Pi.
+POWER = POTĘGA ## Zwraca liczbę podniesioną do potęgi.
+PRODUCT = ILOCZYN ## Mnoży argumenty.
+QUOTIENT = QUOTIENT ## Zwraca iloraz (całkowity).
+RADIANS = RADIANY ## Konwertuje stopnie na radiany.
+RAND = LOS ## Zwraca liczbę pseudolosową z zakresu od 0 do 1.
+RANDBETWEEN = RANDBETWEEN ## Zwraca liczbę pseudolosową z zakresu określonego przez podane argumenty.
+ROMAN = RZYMSKIE ## Konwertuje liczbę arabską na rzymską jako tekst.
+ROUND = ZAOKR ## Zaokrągla liczbę do określonej liczby cyfr.
+ROUNDDOWN = ZAOKR.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera.
+ROUNDUP = ZAOKR.GÓRA ## Zaokrągla liczbę w górę, w kierunku od zera.
+SERIESSUM = SERIESSUM ## Zwraca sumę szeregu potęgowego na podstawie wzoru.
+SIGN = ZNAK.LICZBY ## Zwraca znak liczby.
+SIN = SIN ## Zwraca sinus danego kąta.
+SINH = SINH ## Zwraca sinus hiperboliczny liczby.
+SQRT = PIERWIASTEK ## Zwraca dodatni pierwiastek kwadratowy.
+SQRTPI = SQRTPI ## Zwraca pierwiastek kwadratowy iloczynu (liczba * Pi).
+SUBTOTAL = SUMY.POŚREDNIE ## Zwraca sumę częściową listy lub bazy danych.
+SUM = SUMA ## Dodaje argumenty.
+SUMIF = SUMA.JEŻELI ## Dodaje komórki określone przez podane kryterium.
+SUMIFS = SUMA.WARUNKÓW ## Dodaje komórki w zakresie, które spełniają wiele kryteriów.
+SUMPRODUCT = SUMA.ILOCZYNÓW ## Zwraca sumę iloczynów odpowiednich elementów tablicy.
+SUMSQ = SUMA.KWADRATÓW ## Zwraca sumę kwadratów argumentów.
+SUMX2MY2 = SUMA.X2.M.Y2 ## Zwraca sumę różnic kwadratów odpowiednich wartości w dwóch tablicach.
+SUMX2PY2 = SUMA.X2.P.Y2 ## Zwraca sumę sum kwadratów odpowiednich wartości w dwóch tablicach.
+SUMXMY2 = SUMA.XMY.2 ## Zwraca sumę kwadratów różnic odpowiednich wartości w dwóch tablicach.
+TAN = TAN ## Zwraca tangens liczby.
+TANH = TANH ## Zwraca tangens hiperboliczny liczby.
+TRUNC = LICZBA.CAŁK ## Przycina liczbę do wartości całkowitej.
+
+
+##
+## Statistical functions Funkcje statystyczne
+##
+AVEDEV = ODCH.ŚREDNIE ## Zwraca średnią wartość odchyleń absolutnych punktów danych od ich wartości średniej.
+AVERAGE = ŚREDNIA ## Zwraca wartość średnią argumentów.
+AVERAGEA = ŚREDNIA.A ## Zwraca wartość średnią argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych.
+AVERAGEIF = ŚREDNIA.JEŻELI ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek w zakresie, które spełniają podane kryteria.
+AVERAGEIFS = ŚREDNIA.WARUNKÓW ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek, które spełniają jedno lub więcej kryteriów.
+BETADIST = ROZKŁAD.BETA ## Zwraca skumulowaną funkcję gęstości prawdopodobieństwa beta.
+BETAINV = ROZKŁAD.BETA.ODW ## Zwraca odwrotność skumulowanej funkcji gęstości prawdopodobieństwa beta.
+BINOMDIST = ROZKŁAD.DWUM ## Zwraca pojedynczy składnik dwumianowego rozkładu prawdopodobieństwa.
+CHIDIST = ROZKŁAD.CHI ## Zwraca wartość jednostronnego prawdopodobieństwa rozkładu chi-kwadrat.
+CHIINV = ROZKŁAD.CHI.ODW ## Zwraca odwrotność wartości jednostronnego prawdopodobieństwa rozkładu chi-kwadrat.
+CHITEST = TEST.CHI ## Zwraca test niezależności.
+CONFIDENCE = UFNOŚĆ ## Zwraca interwał ufności dla średniej populacji.
+CORREL = WSP.KORELACJI ## Zwraca współczynnik korelacji dwóch zbiorów danych.
+COUNT = ILE.LICZB ## Zlicza liczby znajdujące się na liście argumentów.
+COUNTA = ILE.NIEPUSTYCH ## Zlicza wartości znajdujące się na liście argumentów.
+COUNTBLANK = LICZ.PUSTE ## Zwraca liczbę pustych komórek w pewnym zakresie.
+COUNTIF = LICZ.JEŻELI ## Zlicza komórki wewnątrz zakresu, które spełniają podane kryteria.
+COUNTIFS = LICZ.WARUNKI ## Zlicza komórki wewnątrz zakresu, które spełniają wiele kryteriów.
+COVAR = KOWARIANCJA ## Zwraca kowariancję, czyli średnią wartość iloczynów odpowiednich odchyleń.
+CRITBINOM = PRÓG.ROZKŁAD.DWUM ## Zwraca najmniejszą wartość, dla której skumulowany rozkład dwumianowy jest mniejszy niż wartość kryterium lub równy jej.
+DEVSQ = ODCH.KWADRATOWE ## Zwraca sumę kwadratów odchyleń.
+EXPONDIST = ROZKŁAD.EXP ## Zwraca rozkład wykładniczy.
+FDIST = ROZKŁAD.F ## Zwraca rozkład prawdopodobieństwa F.
+FINV = ROZKŁAD.F.ODW ## Zwraca odwrotność rozkładu prawdopodobieństwa F.
+FISHER = ROZKŁAD.FISHER ## Zwraca transformację Fishera.
+FISHERINV = ROZKŁAD.FISHER.ODW ## Zwraca odwrotność transformacji Fishera.
+FORECAST = REGLINX ## Zwraca wartość trendu liniowego.
+FREQUENCY = CZĘSTOŚĆ ## Zwraca rozkład częstotliwości jako tablicę pionową.
+FTEST = TEST.F ## Zwraca wynik testu F.
+GAMMADIST = ROZKŁAD.GAMMA ## Zwraca rozkład gamma.
+GAMMAINV = ROZKŁAD.GAMMA.ODW ## Zwraca odwrotność skumulowanego rozkładu gamma.
+GAMMALN = ROZKŁAD.LIN.GAMMA ## Zwraca logarytm naturalny funkcji gamma, Γ(x).
+GEOMEAN = ŚREDNIA.GEOMETRYCZNA ## Zwraca średnią geometryczną.
+GROWTH = REGEXPW ## Zwraca wartości trendu wykładniczego.
+HARMEAN = ŚREDNIA.HARMONICZNA ## Zwraca średnią harmoniczną.
+HYPGEOMDIST = ROZKŁAD.HIPERGEOM ## Zwraca rozkład hipergeometryczny.
+INTERCEPT = ODCIĘTA ## Zwraca punkt przecięcia osi pionowej z linią regresji liniowej.
+KURT = KURTOZA ## Zwraca kurtozę zbioru danych.
+LARGE = MAX.K ## Zwraca k-tą największą wartość ze zbioru danych.
+LINEST = REGLINP ## Zwraca parametry trendu liniowego.
+LOGEST = REGEXPP ## Zwraca parametry trendu wykładniczego.
+LOGINV = ROZKŁAD.LOG.ODW ## Zwraca odwrotność rozkładu logarytmu naturalnego.
+LOGNORMDIST = ROZKŁAD.LOG ## Zwraca skumulowany rozkład logarytmu naturalnego.
+MAX = MAX ## Zwraca maksymalną wartość listy argumentów.
+MAXA = MAX.A ## Zwraca maksymalną wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych.
+MEDIAN = MEDIANA ## Zwraca medianę podanych liczb.
+MIN = MIN ## Zwraca minimalną wartość listy argumentów.
+MINA = MIN.A ## Zwraca najmniejszą wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych.
+MODE = WYST.NAJCZĘŚCIEJ ## Zwraca wartość najczęściej występującą w zbiorze danych.
+NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC ## Zwraca ujemny rozkład dwumianowy.
+NORMDIST = ROZKŁAD.NORMALNY ## Zwraca rozkład normalny skumulowany.
+NORMINV = ROZKŁAD.NORMALNY.ODW ## Zwraca odwrotność rozkładu normalnego skumulowanego.
+NORMSDIST = ROZKŁAD.NORMALNY.S ## Zwraca standardowy rozkład normalny skumulowany.
+NORMSINV = ROZKŁAD.NORMALNY.S.ODW ## Zwraca odwrotność standardowego rozkładu normalnego skumulowanego.
+PEARSON = PEARSON ## Zwraca współczynnik korelacji momentu iloczynu Pearsona.
+PERCENTILE = PERCENTYL ## Wyznacza k-ty percentyl wartości w zakresie.
+PERCENTRANK = PROCENT.POZYCJA ## Zwraca procentową pozycję wartości w zbiorze danych.
+PERMUT = PERMUTACJE ## Zwraca liczbę permutacji dla danej liczby obiektów.
+POISSON = ROZKŁAD.POISSON ## Zwraca rozkład Poissona.
+PROB = PRAWDPD ## Zwraca prawdopodobieństwo, że wartości w zakresie leżą pomiędzy dwiema granicami.
+QUARTILE = KWARTYL ## Wyznacza kwartyl zbioru danych.
+RANK = POZYCJA ## Zwraca pozycję liczby na liście liczb.
+RSQ = R.KWADRAT ## Zwraca kwadrat współczynnika korelacji momentu iloczynu Pearsona.
+SKEW = SKOŚNOŚĆ ## Zwraca skośność rozkładu.
+SLOPE = NACHYLENIE ## Zwraca nachylenie linii regresji liniowej.
+SMALL = MIN.K ## Zwraca k-tą najmniejszą wartość ze zbioru danych.
+STANDARDIZE = NORMALIZUJ ## Zwraca wartość znormalizowaną.
+STDEV = ODCH.STANDARDOWE ## Szacuje odchylenie standardowe na podstawie próbki.
+STDEVA = ODCH.STANDARDOWE.A ## Szacuje odchylenie standardowe na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych.
+STDEVP = ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji.
+STDEVPA = ODCH.STANDARD.POPUL.A ## Oblicza odchylenie standardowe na podstawie całej populacji, z uwzględnieniem liczb, teksów i wartości logicznych.
+STEYX = REGBŁSTD ## Zwraca błąd standardowy przewidzianej wartości y dla każdej wartości x w regresji.
+TDIST = ROZKŁAD.T ## Zwraca rozkład t-Studenta.
+TINV = ROZKŁAD.T.ODW ## Zwraca odwrotność rozkładu t-Studenta.
+TREND = REGLINW ## Zwraca wartości trendu liniowego.
+TRIMMEAN = ŚREDNIA.WEWN ## Zwraca średnią wartość dla wnętrza zbioru danych.
+TTEST = TEST.T ## Zwraca prawdopodobieństwo związane z testem t-Studenta.
+VAR = WARIANCJA ## Szacuje wariancję na podstawie próbki.
+VARA = WARIANCJA.A ## Szacuje wariancję na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych.
+VARP = WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji.
+VARPA = WARIANCJA.POPUL.A ## Oblicza wariancję na podstawie całej populacji, z uwzględnieniem liczb, tekstów i wartości logicznych.
+WEIBULL = ROZKŁAD.WEIBULL ## Zwraca rozkład Weibulla.
+ZTEST = TEST.Z ## Zwraca wartość jednostronnego prawdopodobieństwa testu z.
+
+
+##
+## Text functions Funkcje tekstowe
+##
+ASC = ASC ## Zamienia litery angielskie lub katakana o pełnej szerokości (dwubajtowe) w ciągu znaków na znaki o szerokości połówkowej (jednobajtowe).
+BAHTTEXT = BAHTTEXT ## Konwertuje liczbę na tekst, stosując format walutowy ß (baht).
+CHAR = ZNAK ## Zwraca znak o podanym numerze kodu.
+CLEAN = OCZYŚĆ ## Usuwa z tekstu wszystkie znaki, które nie mogą być drukowane.
+CODE = KOD ## Zwraca kod numeryczny pierwszego znaku w ciągu tekstowym.
+CONCATENATE = ZŁĄCZ.TEKSTY ## Łączy kilka oddzielnych tekstów w jeden tekst.
+DOLLAR = KWOTA ## Konwertuje liczbę na tekst, stosując format walutowy $ (dolar).
+EXACT = PORÓWNAJ ## Sprawdza identyczność dwóch wartości tekstowych.
+FIND = ZNAJDŹ ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter).
+FINDB = ZNAJDŹB ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter).
+FIXED = ZAOKR.DO.TEKST ## Formatuje liczbę jako tekst przy stałej liczbie miejsc dziesiętnych.
+JIS = JIS ## Zmienia litery angielskie lub katakana o szerokości połówkowej (jednobajtowe) w ciągu znaków na znaki o pełnej szerokości (dwubajtowe).
+LEFT = LEWY ## Zwraca skrajne lewe znaki z wartości tekstowej.
+LEFTB = LEWYB ## Zwraca skrajne lewe znaki z wartości tekstowej.
+LEN = DŁ ## Zwraca liczbę znaków ciągu tekstowego.
+LENB = DŁ.B ## Zwraca liczbę znaków ciągu tekstowego.
+LOWER = LITERY.MAŁE ## Konwertuje wielkie litery tekstu na małe litery.
+MID = FRAGMENT.TEKSTU ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji.
+MIDB = FRAGMENT.TEKSTU.B ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji.
+PHONETIC = PHONETIC ## Wybiera znaki fonetyczne (furigana) z ciągu tekstowego.
+PROPER = Z.WIELKIEJ.LITERY ## Zastępuje pierwszą literę każdego wyrazu tekstu wielką literą.
+REPLACE = ZASTĄP ## Zastępuje znaki w tekście.
+REPLACEB = ZASTĄP.B ## Zastępuje znaki w tekście.
+REPT = POWT ## Powiela tekst daną liczbę razy.
+RIGHT = PRAWY ## Zwraca skrajne prawe znaki z wartości tekstowej.
+RIGHTB = PRAWYB ## Zwraca skrajne prawe znaki z wartości tekstowej.
+SEARCH = SZUKAJ.TEKST ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter).
+SEARCHB = SZUKAJ.TEKST.B ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter).
+SUBSTITUTE = PODSTAW ## Podstawia nowy tekst w miejsce poprzedniego tekstu w ciągu tekstowym.
+T = T ## Konwertuje argumenty na tekst.
+TEXT = TEKST ## Formatuje liczbę i konwertuje ją na tekst.
+TRIM = USUŃ.ZBĘDNE.ODSTĘPY ## Usuwa spacje z tekstu.
+UPPER = LITERY.WIELKIE ## Konwertuje znaki tekstu na wielkie litery.
+VALUE = WARTOŚĆ ## Konwertuje argument tekstowy na liczbę.
diff --git a/PHPExcel/locale/pt/br/config b/PHPExcel/locale/pt/br/config
new file mode 100644
index 0000000..b4bf704
--- /dev/null
+++ b/PHPExcel/locale/pt/br/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = R$
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULO!
+DIV0 = #DIV/0!
+VALUE = #VALOR!
+REF = #REF!
+NAME = #NOME?
+NUM = #NÚM!
+NA = #N/D
diff --git a/PHPExcel/locale/pt/br/functions b/PHPExcel/locale/pt/br/functions
new file mode 100644
index 0000000..f3ba3a3
--- /dev/null
+++ b/PHPExcel/locale/pt/br/functions
@@ -0,0 +1,408 @@
+##
+## Add-in and Automation functions Funções Suplemento e Automação
+##
+GETPIVOTDATA = INFODADOSTABELADINÂMICA ## Retorna os dados armazenados em um relatório de tabela dinâmica
+
+
+##
+## Cube functions Funções de Cubo
+##
+CUBEKPIMEMBER = MEMBROKPICUBO ## Retorna o nome de um KPI (indicador de desempenho-chave), uma propriedade e uma medida e exibe o nome e a propriedade na célula. Um KPI é uma medida quantificável, como o lucro bruto mensal ou a rotatividade trimestral dos funcionários, usada para monitorar o desempenho de uma organização.
+CUBEMEMBER = MEMBROCUBO ## Retorna um membro ou tupla em uma hierarquia de cubo. Use para validar se o membro ou tupla existe no cubo.
+CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Retorna o valor da propriedade de um membro no cubo. Usada para validar a existência do nome do membro no cubo e para retornar a propriedade especificada para esse membro.
+CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Retorna o enésimo membro, ou o membro ordenado, em um conjunto. Use para retornar um ou mais elementos em um conjunto, assim como o melhor vendedor ou os dez melhores alunos.
+CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou tuplas enviando uma expressão do conjunto para o cubo no servidor, que cria o conjunto e o retorna para o Microsoft Office Excel.
+CUBESETCOUNT = CONTAGEMCONJUNTOCUBO ## Retorna o número de itens em um conjunto.
+CUBEVALUE = VALORCUBO ## Retorna um valor agregado de um cubo.
+
+
+##
+## Database functions Funções de banco de dados
+##
+DAVERAGE = BDMÉDIA ## Retorna a média das entradas selecionadas de um banco de dados
+DCOUNT = BDCONTAR ## Conta as células que contêm números em um banco de dados
+DCOUNTA = BDCONTARA ## Conta células não vazias em um banco de dados
+DGET = BDEXTRAIR ## Extrai de um banco de dados um único registro que corresponde a um critério específico
+DMAX = BDMÁX ## Retorna o valor máximo de entradas selecionadas de um banco de dados
+DMIN = BDMÍN ## Retorna o valor mínimo de entradas selecionadas de um banco de dados
+DPRODUCT = BDMULTIPL ## Multiplica os valores em um campo específico de registros que correspondem ao critério em um banco de dados
+DSTDEV = BDEST ## Estima o desvio padrão com base em uma amostra de entradas selecionadas de um banco de dados
+DSTDEVP = BDDESVPA ## Calcula o desvio padrão com base na população inteira de entradas selecionadas de um banco de dados
+DSUM = BDSOMA ## Adiciona os números à coluna de campos de registros do banco de dados que correspondem ao critério
+DVAR = BDVAREST ## Estima a variância com base em uma amostra de entradas selecionadas de um banco de dados
+DVARP = BDVARP ## Calcula a variância com base na população inteira de entradas selecionadas de um banco de dados
+
+
+##
+## Date and time functions Funções de data e hora
+##
+DATE = DATA ## Retorna o número de série de uma data específica
+DATEVALUE = DATA.VALOR ## Converte uma data na forma de texto para um número de série
+DAY = DIA ## Converte um número de série em um dia do mês
+DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base em um ano de 360 dias
+EDATE = DATAM ## Retorna o número de série da data que é o número indicado de meses antes ou depois da data inicial
+EOMONTH = FIMMÊS ## Retorna o número de série do último dia do mês antes ou depois de um número especificado de meses
+HOUR = HORA ## Converte um número de série em uma hora
+MINUTE = MINUTO ## Converte um número de série em um minuto
+MONTH = MÊS ## Converte um número de série em um mês
+NETWORKDAYS = DIATRABALHOTOTAL ## Retorna o número de dias úteis inteiros entre duas datas
+NOW = AGORA ## Retorna o número de série seqüencial da data e hora atuais
+SECOND = SEGUNDO ## Converte um número de série em um segundo
+TIME = HORA ## Retorna o número de série de uma hora específica
+TIMEVALUE = VALOR.TEMPO ## Converte um horário na forma de texto para um número de série
+TODAY = HOJE ## Retorna o número de série da data de hoje
+WEEKDAY = DIA.DA.SEMANA ## Converte um número de série em um dia da semana
+WEEKNUM = NÚMSEMANA ## Converte um número de série em um número que representa onde a semana cai numericamente em um ano
+WORKDAY = DIATRABALHO ## Retorna o número de série da data antes ou depois de um número específico de dias úteis
+YEAR = ANO ## Converte um número de série em um ano
+YEARFRAC = FRAÇÃOANO ## Retorna a fração do ano que representa o número de dias entre data_inicial e data_final
+
+
+##
+## Engineering functions Funções de engenharia
+##
+BESSELI = BESSELI ## Retorna a função de Bessel In(x) modificada
+BESSELJ = BESSELJ ## Retorna a função de Bessel Jn(x)
+BESSELK = BESSELK ## Retorna a função de Bessel Kn(x) modificada
+BESSELY = BESSELY ## Retorna a função de Bessel Yn(x)
+BIN2DEC = BIN2DEC ## Converte um número binário em decimal
+BIN2HEX = BIN2HEX ## Converte um número binário em hexadecimal
+BIN2OCT = BIN2OCT ## Converte um número binário em octal
+COMPLEX = COMPLEX ## Converte coeficientes reais e imaginários e um número complexo
+CONVERT = CONVERTER ## Converte um número de um sistema de medida para outro
+DEC2BIN = DECABIN ## Converte um número decimal em binário
+DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal
+DEC2OCT = DECAOCT ## Converte um número decimal em octal
+DELTA = DELTA ## Testa se dois valores são iguais
+ERF = FUNERRO ## Retorna a função de erro
+ERFC = FUNERROCOMPL ## Retorna a função de erro complementar
+GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite
+HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário
+HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal
+HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal
+IMABS = IMABS ## Retorna o valor absoluto (módulo) de um número complexo
+IMAGINARY = IMAGINÁRIO ## Retorna o coeficiente imaginário de um número complexo
+IMARGUMENT = IMARG ## Retorna o argumento teta, um ângulo expresso em radianos
+IMCONJUGATE = IMCONJ ## Retorna o conjugado complexo de um número complexo
+IMCOS = IMCOS ## Retorna o cosseno de um número complexo
+IMDIV = IMDIV ## Retorna o quociente de dois números complexos
+IMEXP = IMEXP ## Retorna o exponencial de um número complexo
+IMLN = IMLN ## Retorna o logaritmo natural de um número complexo
+IMLOG10 = IMLOG10 ## Retorna o logaritmo de base 10 de um número complexo
+IMLOG2 = IMLOG2 ## Retorna o logaritmo de base 2 de um número complexo
+IMPOWER = IMPOT ## Retorna um número complexo elevado a uma potência inteira
+IMPRODUCT = IMPROD ## Retorna o produto de números complexos
+IMREAL = IMREAL ## Retorna o coeficiente real de um número complexo
+IMSIN = IMSENO ## Retorna o seno de um número complexo
+IMSQRT = IMRAIZ ## Retorna a raiz quadrada de um número complexo
+IMSUB = IMSUBTR ## Retorna a diferença entre dois números complexos
+IMSUM = IMSOMA ## Retorna a soma de números complexos
+OCT2BIN = OCTABIN ## Converte um número octal em binário
+OCT2DEC = OCTADEC ## Converte um número octal em decimal
+OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal
+
+
+##
+## Financial functions Funções financeiras
+##
+ACCRINT = JUROSACUM ## Retorna a taxa de juros acumulados de um título que paga uma taxa periódica de juros
+ACCRINTM = JUROSACUMV ## Retorna os juros acumulados de um título que paga juros no vencimento
+AMORDEGRC = AMORDEGRC ## Retorna a depreciação para cada período contábil usando o coeficiente de depreciação
+AMORLINC = AMORLINC ## Retorna a depreciação para cada período contábil
+COUPDAYBS = CUPDIASINLIQ ## Retorna o número de dias do início do período de cupom até a data de liquidação
+COUPDAYS = CUPDIAS ## Retorna o número de dias no período de cupom que contém a data de quitação
+COUPDAYSNC = CUPDIASPRÓX ## Retorna o número de dias da data de liquidação até a data do próximo cupom
+COUPNCD = CUPDATAPRÓX ## Retorna a próxima data de cupom após a data de quitação
+COUPNUM = CUPNÚM ## Retorna o número de cupons pagáveis entre as datas de quitação e vencimento
+COUPPCD = CUPDATAANT ## Retorna a data de cupom anterior à data de quitação
+CUMIPMT = PGTOJURACUM ## Retorna os juros acumulados pagos entre dois períodos
+CUMPRINC = PGTOCAPACUM ## Retorna o capital acumulado pago sobre um empréstimo entre dois períodos
+DB = BD ## Retorna a depreciação de um ativo para um período especificado, usando o método de balanço de declínio fixo
+DDB = BDD ## Retorna a depreciação de um ativo com relação a um período especificado usando o método de saldos decrescentes duplos ou qualquer outro método especificado por você
+DISC = DESC ## Retorna a taxa de desconto de um título
+DOLLARDE = MOEDADEC ## Converte um preço em formato de moeda, na forma fracionária, em um preço na forma decimal
+DOLLARFR = MOEDAFRA ## Converte um preço, apresentado na forma decimal, em um preço apresentado na forma fracionária
+DURATION = DURAÇÃO ## Retorna a duração anual de um título com pagamentos de juros periódicos
+EFFECT = EFETIVA ## Retorna a taxa de juros anual efetiva
+FV = VF ## Retorna o valor futuro de um investimento
+FVSCHEDULE = VFPLANO ## Retorna o valor futuro de um capital inicial após a aplicação de uma série de taxas de juros compostas
+INTRATE = TAXAJUROS ## Retorna a taxa de juros de um título totalmente investido
+IPMT = IPGTO ## Retorna o pagamento de juros para um investimento em um determinado período
+IRR = TIR ## Retorna a taxa interna de retorno de uma série de fluxos de caixa
+ISPMT = ÉPGTO ## Calcula os juros pagos durante um período específico de um investimento
+MDURATION = MDURAÇÃO ## Retorna a duração de Macauley modificada para um título com um valor de paridade equivalente a R$ 100
+MIRR = MTIR ## Calcula a taxa interna de retorno em que fluxos de caixa positivos e negativos são financiados com diferentes taxas
+NOMINAL = NOMINAL ## Retorna a taxa de juros nominal anual
+NPER = NPER ## Retorna o número de períodos de um investimento
+NPV = VPL ## Retorna o valor líquido atual de um investimento com base em uma série de fluxos de caixa periódicos e em uma taxa de desconto
+ODDFPRICE = PREÇOPRIMINC ## Retorna o preço por R$ 100 de valor nominal de um título com um primeiro período indefinido
+ODDFYIELD = LUCROPRIMINC ## Retorna o rendimento de um título com um primeiro período indefinido
+ODDLPRICE = PREÇOÚLTINC ## Retorna o preço por R$ 100 de valor nominal de um título com um último período de cupom indefinido
+ODDLYIELD = LUCROÚLTINC ## Retorna o rendimento de um título com um último período indefinido
+PMT = PGTO ## Retorna o pagamento periódico de uma anuidade
+PPMT = PPGTO ## Retorna o pagamento de capital para determinado período de investimento
+PRICE = PREÇO ## Retorna a preço por R$ 100,00 de valor nominal de um título que paga juros periódicos
+PRICEDISC = PREÇODESC ## Retorna o preço por R$ 100,00 de valor nominal de um título descontado
+PRICEMAT = PREÇOVENC ## Retorna o preço por R$ 100,00 de valor nominal de um título que paga juros no vencimento
+PV = VP ## Retorna o valor presente de um investimento
+RATE = TAXA ## Retorna a taxa de juros por período de uma anuidade
+RECEIVED = RECEBER ## Retorna a quantia recebida no vencimento de um título totalmente investido
+SLN = DPD ## Retorna a depreciação em linha reta de um ativo durante um período
+SYD = SDA ## Retorna a depreciação dos dígitos da soma dos anos de um ativo para um período especificado
+TBILLEQ = OTN ## Retorna o rendimento de um título equivalente a uma obrigação do Tesouro
+TBILLPRICE = OTNVALOR ## Retorna o preço por R$ 100,00 de valor nominal de uma obrigação do Tesouro
+TBILLYIELD = OTNLUCRO ## Retorna o rendimento de uma obrigação do Tesouro
+VDB = BDV ## Retorna a depreciação de um ativo para um período especificado ou parcial usando um método de balanço declinante
+XIRR = XTIR ## Fornece a taxa interna de retorno para um programa de fluxos de caixa que não é necessariamente periódico
+XNPV = XVPL ## Retorna o valor presente líquido de um programa de fluxos de caixa que não é necessariamente periódico
+YIELD = LUCRO ## Retorna o lucro de um título que paga juros periódicos
+YIELDDISC = LUCRODESC ## Retorna o rendimento anual de um título descontado. Por exemplo, uma obrigação do Tesouro
+YIELDMAT = LUCROVENC ## Retorna o lucro anual de um título que paga juros no vencimento
+
+
+##
+## Information functions Funções de informação
+##
+CELL = CÉL ## Retorna informações sobre formatação, localização ou conteúdo de uma célula
+ERROR.TYPE = TIPO.ERRO ## Retorna um número correspondente a um tipo de erro
+INFO = INFORMAÇÃO ## Retorna informações sobre o ambiente operacional atual
+ISBLANK = ÉCÉL.VAZIA ## Retorna VERDADEIRO se o valor for vazio
+ISERR = ÉERRO ## Retorna VERDADEIRO se o valor for um valor de erro diferente de #N/D
+ISERROR = ÉERROS ## Retorna VERDADEIRO se o valor for um valor de erro
+ISEVEN = ÉPAR ## Retorna VERDADEIRO se o número for par
+ISLOGICAL = ÉLÓGICO ## Retorna VERDADEIRO se o valor for um valor lógico
+ISNA = É.NÃO.DISP ## Retorna VERDADEIRO se o valor for o valor de erro #N/D
+ISNONTEXT = É.NÃO.TEXTO ## Retorna VERDADEIRO se o valor for diferente de texto
+ISNUMBER = ÉNÚM ## Retorna VERDADEIRO se o valor for um número
+ISODD = ÉIMPAR ## Retorna VERDADEIRO se o número for ímpar
+ISREF = ÉREF ## Retorna VERDADEIRO se o valor for uma referência
+ISTEXT = ÉTEXTO ## Retorna VERDADEIRO se o valor for texto
+N = N ## Retorna um valor convertido em um número
+NA = NÃO.DISP ## Retorna o valor de erro #N/D
+TYPE = TIPO ## Retorna um número indicando o tipo de dados de um valor
+
+
+##
+## Logical functions Funções lógicas
+##
+AND = E ## Retorna VERDADEIRO se todos os seus argumentos forem VERDADEIROS
+FALSE = FALSO ## Retorna o valor lógico FALSO
+IF = SE ## Especifica um teste lógico a ser executado
+IFERROR = SEERRO ## Retornará um valor que você especifica se uma fórmula for avaliada para um erro; do contrário, retornará o resultado da fórmula
+NOT = NÃO ## Inverte o valor lógico do argumento
+OR = OU ## Retorna VERDADEIRO se um dos argumentos for VERDADEIRO
+TRUE = VERDADEIRO ## Retorna o valor lógico VERDADEIRO
+
+
+##
+## Lookup and reference functions Funções de pesquisa e referência
+##
+ADDRESS = ENDEREÇO ## Retorna uma referência como texto para uma única célula em uma planilha
+AREAS = ÁREAS ## Retorna o número de áreas em uma referência
+CHOOSE = ESCOLHER ## Escolhe um valor a partir de uma lista de valores
+COLUMN = COL ## Retorna o número da coluna de uma referência
+COLUMNS = COLS ## Retorna o número de colunas em uma referência
+HLOOKUP = PROCH ## Procura na linha superior de uma matriz e retorna o valor da célula especificada
+HYPERLINK = HYPERLINK ## Cria um atalho ou salto que abre um documento armazenado em um servidor de rede, uma intranet ou na Internet
+INDEX = ÍNDICE ## Usa um índice para escolher um valor de uma referência ou matriz
+INDIRECT = INDIRETO ## Retorna uma referência indicada por um valor de texto
+LOOKUP = PROC ## Procura valores em um vetor ou em uma matriz
+MATCH = CORRESP ## Procura valores em uma referência ou em uma matriz
+OFFSET = DESLOC ## Retorna um deslocamento de referência com base em uma determinada referência
+ROW = LIN ## Retorna o número da linha de uma referência
+ROWS = LINS ## Retorna o número de linhas em uma referência
+RTD = RTD ## Recupera dados em tempo real de um programa que ofereça suporte a automação COM (automação: uma forma de trabalhar com objetos de um aplicativo a partir de outro aplicativo ou ferramenta de desenvolvimento. Chamada inicialmente de automação OLE, a automação é um padrão industrial e um recurso do modelo de objeto componente (COM).)
+TRANSPOSE = TRANSPOR ## Retorna a transposição de uma matriz
+VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e move ao longo da linha para retornar o valor de uma célula
+
+
+##
+## Math and trigonometry functions Funções matemáticas e trigonométricas
+##
+ABS = ABS ## Retorna o valor absoluto de um número
+ACOS = ACOS ## Retorna o arco cosseno de um número
+ACOSH = ACOSH ## Retorna o cosseno hiperbólico inverso de um número
+ASIN = ASEN ## Retorna o arco seno de um número
+ASINH = ASENH ## Retorna o seno hiperbólico inverso de um número
+ATAN = ATAN ## Retorna o arco tangente de um número
+ATAN2 = ATAN2 ## Retorna o arco tangente das coordenadas x e y especificadas
+ATANH = ATANH ## Retorna a tangente hiperbólica inversa de um número
+CEILING = TETO ## Arredonda um número para o inteiro mais próximo ou para o múltiplo mais próximo de significância
+COMBIN = COMBIN ## Retorna o número de combinações de um determinado número de objetos
+COS = COS ## Retorna o cosseno de um número
+COSH = COSH ## Retorna o cosseno hiperbólico de um número
+DEGREES = GRAUS ## Converte radianos em graus
+EVEN = PAR ## Arredonda um número para cima até o inteiro par mais próximo
+EXP = EXP ## Retorna e elevado à potência de um número especificado
+FACT = FATORIAL ## Retorna o fatorial de um número
+FACTDOUBLE = FATDUPLO ## Retorna o fatorial duplo de um número
+FLOOR = ARREDMULTB ## Arredonda um número para baixo até zero
+GCD = MDC ## Retorna o máximo divisor comum
+INT = INT ## Arredonda um número para baixo até o número inteiro mais próximo
+LCM = MMC ## Retorna o mínimo múltiplo comum
+LN = LN ## Retorna o logaritmo natural de um número
+LOG = LOG ## Retorna o logaritmo de um número de uma base especificada
+LOG10 = LOG10 ## Retorna o logaritmo de base 10 de um número
+MDETERM = MATRIZ.DETERM ## Retorna o determinante de uma matriz de uma variável do tipo matriz
+MINVERSE = MATRIZ.INVERSO ## Retorna a matriz inversa de uma matriz
+MMULT = MATRIZ.MULT ## Retorna o produto de duas matrizes
+MOD = RESTO ## Retorna o resto da divisão
+MROUND = MARRED ## Retorna um número arredondado ao múltiplo desejado
+MULTINOMIAL = MULTINOMIAL ## Retorna o multinomial de um conjunto de números
+ODD = ÍMPAR ## Arredonda um número para cima até o inteiro ímpar mais próximo
+PI = PI ## Retorna o valor de Pi
+POWER = POTÊNCIA ## Fornece o resultado de um número elevado a uma potência
+PRODUCT = MULT ## Multiplica seus argumentos
+QUOTIENT = QUOCIENTE ## Retorna a parte inteira de uma divisão
+RADIANS = RADIANOS ## Converte graus em radianos
+RAND = ALEATÓRIO ## Retorna um número aleatório entre 0 e 1
+RANDBETWEEN = ALEATÓRIOENTRE ## Retorna um número aleatório entre os números especificados
+ROMAN = ROMANO ## Converte um algarismo arábico em romano, como texto
+ROUND = ARRED ## Arredonda um número até uma quantidade especificada de dígitos
+ROUNDDOWN = ARREDONDAR.PARA.BAIXO ## Arredonda um número para baixo até zero
+ROUNDUP = ARREDONDAR.PARA.CIMA ## Arredonda um número para cima, afastando-o de zero
+SERIESSUM = SOMASEQÜÊNCIA ## Retorna a soma de uma série polinomial baseada na fórmula
+SIGN = SINAL ## Retorna o sinal de um número
+SIN = SEN ## Retorna o seno de um ângulo dado
+SINH = SENH ## Retorna o seno hiperbólico de um número
+SQRT = RAIZ ## Retorna uma raiz quadrada positiva
+SQRTPI = RAIZPI ## Retorna a raiz quadrada de (núm* pi)
+SUBTOTAL = SUBTOTAL ## Retorna um subtotal em uma lista ou em um banco de dados
+SUM = SOMA ## Soma seus argumentos
+SUMIF = SOMASE ## Adiciona as células especificadas por um determinado critério
+SUMIFS = SOMASE ## Adiciona as células em um intervalo que atende a vários critérios
+SUMPRODUCT = SOMARPRODUTO ## Retorna a soma dos produtos de componentes correspondentes de matrizes
+SUMSQ = SOMAQUAD ## Retorna a soma dos quadrados dos argumentos
+SUMX2MY2 = SOMAX2DY2 ## Retorna a soma da diferença dos quadrados dos valores correspondentes em duas matrizes
+SUMX2PY2 = SOMAX2SY2 ## Retorna a soma da soma dos quadrados dos valores correspondentes em duas matrizes
+SUMXMY2 = SOMAXMY2 ## Retorna a soma dos quadrados das diferenças dos valores correspondentes em duas matrizes
+TAN = TAN ## Retorna a tangente de um número
+TANH = TANH ## Retorna a tangente hiperbólica de um número
+TRUNC = TRUNCAR ## Trunca um número para um inteiro
+
+
+##
+## Statistical functions Funções estatísticas
+##
+AVEDEV = DESV.MÉDIO ## Retorna a média aritmética dos desvios médios dos pontos de dados a partir de sua média
+AVERAGE = MÉDIA ## Retorna a média dos argumentos
+AVERAGEA = MÉDIAA ## Retorna a média dos argumentos, inclusive números, texto e valores lógicos
+AVERAGEIF = MÉDIASE ## Retorna a média (média aritmética) de todas as células em um intervalo que atendem a um determinado critério
+AVERAGEIFS = MÉDIASES ## Retorna a média (média aritmética) de todas as células que atendem a múltiplos critérios.
+BETADIST = DISTBETA ## Retorna a função de distribuição cumulativa beta
+BETAINV = BETA.ACUM.INV ## Retorna o inverso da função de distribuição cumulativa para uma distribuição beta especificada
+BINOMDIST = DISTRBINOM ## Retorna a probabilidade de distribuição binomial do termo individual
+CHIDIST = DIST.QUI ## Retorna a probabilidade unicaudal da distribuição qui-quadrada
+CHIINV = INV.QUI ## Retorna o inverso da probabilidade uni-caudal da distribuição qui-quadrada
+CHITEST = TESTE.QUI ## Retorna o teste para independência
+CONFIDENCE = INT.CONFIANÇA ## Retorna o intervalo de confiança para uma média da população
+CORREL = CORREL ## Retorna o coeficiente de correlação entre dois conjuntos de dados
+COUNT = CONT.NÚM ## Calcula quantos números há na lista de argumentos
+COUNTA = CONT.VALORES ## Calcula quantos valores há na lista de argumentos
+COUNTBLANK = CONTAR.VAZIO ## Conta o número de células vazias no intervalo especificado
+COUNTIF = CONT.SE ## Calcula o número de células não vazias em um intervalo que corresponde a determinados critérios
+COUNTIFS = CONT.SES ## Conta o número de células dentro de um intervalo que atende a múltiplos critérios
+COVAR = COVAR ## Retorna a covariância, a média dos produtos dos desvios pares
+CRITBINOM = CRIT.BINOM ## Retorna o menor valor para o qual a distribuição binomial cumulativa é menor ou igual ao valor padrão
+DEVSQ = DESVQ ## Retorna a soma dos quadrados dos desvios
+EXPONDIST = DISTEXPON ## Retorna a distribuição exponencial
+FDIST = DISTF ## Retorna a distribuição de probabilidade F
+FINV = INVF ## Retorna o inverso da distribuição de probabilidades F
+FISHER = FISHER ## Retorna a transformação Fisher
+FISHERINV = FISHERINV ## Retorna o inverso da transformação Fisher
+FORECAST = PREVISÃO ## Retorna um valor ao longo de uma linha reta
+FREQUENCY = FREQÜÊNCIA ## Retorna uma distribuição de freqüência como uma matriz vertical
+FTEST = TESTEF ## Retorna o resultado de um teste F
+GAMMADIST = DISTGAMA ## Retorna a distribuição gama
+GAMMAINV = INVGAMA ## Retorna o inverso da distribuição cumulativa gama
+GAMMALN = LNGAMA ## Retorna o logaritmo natural da função gama, G(x)
+GEOMEAN = MÉDIA.GEOMÉTRICA ## Retorna a média geométrica
+GROWTH = CRESCIMENTO ## Retorna valores ao longo de uma tendência exponencial
+HARMEAN = MÉDIA.HARMÔNICA ## Retorna a média harmônica
+HYPGEOMDIST = DIST.HIPERGEOM ## Retorna a distribuição hipergeométrica
+INTERCEPT = INTERCEPÇÃO ## Retorna a intercepção da linha de regressão linear
+KURT = CURT ## Retorna a curtose de um conjunto de dados
+LARGE = MAIOR ## Retorna o maior valor k-ésimo de um conjunto de dados
+LINEST = PROJ.LIN ## Retorna os parâmetros de uma tendência linear
+LOGEST = PROJ.LOG ## Retorna os parâmetros de uma tendência exponencial
+LOGINV = INVLOG ## Retorna o inverso da distribuição lognormal
+LOGNORMDIST = DIST.LOGNORMAL ## Retorna a distribuição lognormal cumulativa
+MAX = MÁXIMO ## Retorna o valor máximo em uma lista de argumentos
+MAXA = MÁXIMOA ## Retorna o maior valor em uma lista de argumentos, inclusive números, texto e valores lógicos
+MEDIAN = MED ## Retorna a mediana dos números indicados
+MIN = MÍNIMO ## Retorna o valor mínimo em uma lista de argumentos
+MINA = MÍNIMOA ## Retorna o menor valor em uma lista de argumentos, inclusive números, texto e valores lógicos
+MODE = MODO ## Retorna o valor mais comum em um conjunto de dados
+NEGBINOMDIST = DIST.BIN.NEG ## Retorna a distribuição binomial negativa
+NORMDIST = DIST.NORM ## Retorna a distribuição cumulativa normal
+NORMINV = INV.NORM ## Retorna o inverso da distribuição cumulativa normal
+NORMSDIST = DIST.NORMP ## Retorna a distribuição cumulativa normal padrão
+NORMSINV = INV.NORMP ## Retorna o inverso da distribuição cumulativa normal padrão
+PEARSON = PEARSON ## Retorna o coeficiente de correlação do momento do produto Pearson
+PERCENTILE = PERCENTIL ## Retorna o k-ésimo percentil de valores em um intervalo
+PERCENTRANK = ORDEM.PORCENTUAL ## Retorna a ordem percentual de um valor em um conjunto de dados
+PERMUT = PERMUT ## Retorna o número de permutações de um determinado número de objetos
+POISSON = POISSON ## Retorna a distribuição Poisson
+PROB = PROB ## Retorna a probabilidade de valores em um intervalo estarem entre dois limites
+QUARTILE = QUARTIL ## Retorna o quartil do conjunto de dados
+RANK = ORDEM ## Retorna a posição de um número em uma lista de números
+RSQ = RQUAD ## Retorna o quadrado do coeficiente de correlação do momento do produto de Pearson
+SKEW = DISTORÇÃO ## Retorna a distorção de uma distribuição
+SLOPE = INCLINAÇÃO ## Retorna a inclinação da linha de regressão linear
+SMALL = MENOR ## Retorna o menor valor k-ésimo do conjunto de dados
+STANDARDIZE = PADRONIZAR ## Retorna um valor normalizado
+STDEV = DESVPAD ## Estima o desvio padrão com base em uma amostra
+STDEVA = DESVPADA ## Estima o desvio padrão com base em uma amostra, inclusive números, texto e valores lógicos
+STDEVP = DESVPADP ## Calcula o desvio padrão com base na população total
+STDEVPA = DESVPADPA ## Calcula o desvio padrão com base na população total, inclusive números, texto e valores lógicos
+STEYX = EPADYX ## Retorna o erro padrão do valor-y previsto para cada x da regressão
+TDIST = DISTT ## Retorna a distribuição t de Student
+TINV = INVT ## Retorna o inverso da distribuição t de Student
+TREND = TENDÊNCIA ## Retorna valores ao longo de uma tendência linear
+TRIMMEAN = MÉDIA.INTERNA ## Retorna a média do interior de um conjunto de dados
+TTEST = TESTET ## Retorna a probabilidade associada ao teste t de Student
+VAR = VAR ## Estima a variância com base em uma amostra
+VARA = VARA ## Estima a variância com base em uma amostra, inclusive números, texto e valores lógicos
+VARP = VARP ## Calcula a variância com base na população inteira
+VARPA = VARPA ## Calcula a variância com base na população total, inclusive números, texto e valores lógicos
+WEIBULL = WEIBULL ## Retorna a distribuição Weibull
+ZTEST = TESTEZ ## Retorna o valor de probabilidade uni-caudal de um teste-z
+
+
+##
+## Text functions Funções de texto
+##
+ASC = ASC ## Altera letras do inglês ou katakana de largura total (bytes duplos) dentro de uma seqüência de caracteres para caracteres de meia largura (byte único)
+BAHTTEXT = BAHTTEXT ## Converte um número em um texto, usando o formato de moeda ß (baht)
+CHAR = CARACT ## Retorna o caractere especificado pelo número de código
+CLEAN = TIRAR ## Remove todos os caracteres do texto que não podem ser impressos
+CODE = CÓDIGO ## Retorna um código numérico para o primeiro caractere de uma seqüência de caracteres de texto
+CONCATENATE = CONCATENAR ## Agrupa vários itens de texto em um único item de texto
+DOLLAR = MOEDA ## Converte um número em texto, usando o formato de moeda $ (dólar)
+EXACT = EXATO ## Verifica se dois valores de texto são idênticos
+FIND = PROCURAR ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas)
+FINDB = PROCURARB ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas)
+FIXED = DEF.NÚM.DEC ## Formata um número como texto com um número fixo de decimais
+JIS = JIS ## Altera letras do inglês ou katakana de meia largura (byte único) dentro de uma seqüência de caracteres para caracteres de largura total (bytes duplos)
+LEFT = ESQUERDA ## Retorna os caracteres mais à esquerda de um valor de texto
+LEFTB = ESQUERDAB ## Retorna os caracteres mais à esquerda de um valor de texto
+LEN = NÚM.CARACT ## Retorna o número de caracteres em uma seqüência de texto
+LENB = NÚM.CARACTB ## Retorna o número de caracteres em uma seqüência de texto
+LOWER = MINÚSCULA ## Converte texto para minúsculas
+MID = EXT.TEXTO ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada
+MIDB = EXT.TEXTOB ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada
+PHONETIC = FONÉTICA ## Extrai os caracteres fonéticos (furigana) de uma seqüência de caracteres de texto
+PROPER = PRI.MAIÚSCULA ## Coloca a primeira letra de cada palavra em maiúscula em um valor de texto
+REPLACE = MUDAR ## Muda os caracteres dentro do texto
+REPLACEB = MUDARB ## Muda os caracteres dentro do texto
+REPT = REPT ## Repete o texto um determinado número de vezes
+RIGHT = DIREITA ## Retorna os caracteres mais à direita de um valor de texto
+RIGHTB = DIREITAB ## Retorna os caracteres mais à direita de um valor de texto
+SEARCH = LOCALIZAR ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas)
+SEARCHB = LOCALIZARB ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas)
+SUBSTITUTE = SUBSTITUIR ## Substitui um novo texto por um texto antigo em uma seqüência de texto
+T = T ## Converte os argumentos em texto
+TEXT = TEXTO ## Formata um número e o converte em texto
+TRIM = ARRUMAR ## Remove espaços do texto
+UPPER = MAIÚSCULA ## Converte o texto em maiúsculas
+VALUE = VALOR ## Converte um argumento de texto em um número
diff --git a/PHPExcel/locale/pt/config b/PHPExcel/locale/pt/config
new file mode 100644
index 0000000..60b422b
--- /dev/null
+++ b/PHPExcel/locale/pt/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = €
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #NULO!
+DIV0 = #DIV/0!
+VALUE = #VALOR!
+REF = #REF!
+NAME = #NOME?
+NUM = #NÚM!
+NA = #N/D
diff --git a/PHPExcel/locale/pt/functions b/PHPExcel/locale/pt/functions
new file mode 100644
index 0000000..7fe9e3b
--- /dev/null
+++ b/PHPExcel/locale/pt/functions
@@ -0,0 +1,408 @@
+##
+## Add-in and Automation functions Funções de Suplemento e Automatização
+##
+GETPIVOTDATA = OBTERDADOSDIN ## Devolve dados armazenados num relatório de Tabela Dinâmica
+
+
+##
+## Cube functions Funções de cubo
+##
+CUBEKPIMEMBER = MEMBROKPICUBO ## Devolve o nome, propriedade e medição de um KPI (key performance indicator) e apresenta o nome e a propriedade na célula. Um KPI é uma medida quantificável, como, por exemplo, o lucro mensal bruto ou a rotatividade trimestral de pessoal, utilizada para monitorizar o desempenho de uma organização.
+CUBEMEMBER = MEMBROCUBO ## Devolve um membro ou cadeia de identificação numa hierarquia de cubo. Utilizada para validar a existência do membro ou cadeia de identificação no cubo.
+CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Devolve o valor de uma propriedade de membro no cubo. Utilizada para validar a existência de um nome de membro no cubo e para devolver a propriedade especificada para esse membro.
+CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Devolve o enésimo ou a classificação mais alta num conjunto. Utilizada para devolver um ou mais elementos num conjunto, tal como o melhor vendedor ou os 10 melhores alunos.
+CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou cadeias de identificação enviando uma expressão de conjunto para o cubo no servidor, que cria o conjunto e, em seguida, devolve o conjunto ao Microsoft Office Excel.
+CUBESETCOUNT = CONTARCONJUNTOCUBO ## Devolve o número de itens num conjunto.
+CUBEVALUE = VALORCUBO ## Devolve um valor agregado do cubo.
+
+
+##
+## Database functions Funções de base de dados
+##
+DAVERAGE = BDMÉDIA ## Devolve a média das entradas da base de dados seleccionadas
+DCOUNT = BDCONTAR ## Conta as células que contêm números numa base de dados
+DCOUNTA = BDCONTAR.VAL ## Conta as células que não estejam em branco numa base de dados
+DGET = BDOBTER ## Extrai de uma base de dados um único registo que corresponde aos critérios especificados
+DMAX = BDMÁX ## Devolve o valor máximo das entradas da base de dados seleccionadas
+DMIN = BDMÍN ## Devolve o valor mínimo das entradas da base de dados seleccionadas
+DPRODUCT = BDMULTIPL ## Multiplica os valores de um determinado campo de registos que correspondem aos critérios numa base de dados
+DSTDEV = BDDESVPAD ## Calcula o desvio-padrão com base numa amostra de entradas da base de dados seleccionadas
+DSTDEVP = BDDESVPADP ## Calcula o desvio-padrão com base na população total das entradas da base de dados seleccionadas
+DSUM = BDSOMA ## Adiciona os números na coluna de campo dos registos de base de dados que correspondem aos critérios
+DVAR = BDVAR ## Calcula a variância com base numa amostra das entradas de base de dados seleccionadas
+DVARP = BDVARP ## Calcula a variância com base na população total das entradas de base de dados seleccionadas
+
+
+##
+## Date and time functions Funções de data e hora
+##
+DATE = DATA ## Devolve o número de série de uma determinada data
+DATEVALUE = DATA.VALOR ## Converte uma data em forma de texto num número de série
+DAY = DIA ## Converte um número de série num dia do mês
+DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base num ano com 360 dias
+EDATE = DATAM ## Devolve um número de série de data que corresponde ao número de meses indicado antes ou depois da data de início
+EOMONTH = FIMMÊS ## Devolve o número de série do último dia do mês antes ou depois de um número de meses especificado
+HOUR = HORA ## Converte um número de série numa hora
+MINUTE = MINUTO ## Converte um número de série num minuto
+MONTH = MÊS ## Converte um número de série num mês
+NETWORKDAYS = DIATRABALHOTOTAL ## Devolve o número total de dias úteis entre duas datas
+NOW = AGORA ## Devolve o número de série da data e hora actuais
+SECOND = SEGUNDO ## Converte um número de série num segundo
+TIME = TEMPO ## Devolve o número de série de um determinado tempo
+TIMEVALUE = VALOR.TEMPO ## Converte um tempo em forma de texto num número de série
+TODAY = HOJE ## Devolve o número de série da data actual
+WEEKDAY = DIA.SEMANA ## Converte um número de série num dia da semana
+WEEKNUM = NÚMSEMANA ## Converte um número de série num número que representa o número da semana num determinado ano
+WORKDAY = DIA.TRABALHO ## Devolve o número de série da data antes ou depois de um número de dias úteis especificado
+YEAR = ANO ## Converte um número de série num ano
+YEARFRAC = FRACÇÃOANO ## Devolve a fracção de ano que representa o número de dias inteiros entre a data_de_início e a data_de_fim
+
+
+##
+## Engineering functions Funções de engenharia
+##
+BESSELI = BESSELI ## Devolve a função de Bessel modificada In(x)
+BESSELJ = BESSELJ ## Devolve a função de Bessel Jn(x)
+BESSELK = BESSELK ## Devolve a função de Bessel modificada Kn(x)
+BESSELY = BESSELY ## Devolve a função de Bessel Yn(x)
+BIN2DEC = BINADEC ## Converte um número binário em decimal
+BIN2HEX = BINAHEX ## Converte um número binário em hexadecimal
+BIN2OCT = BINAOCT ## Converte um número binário em octal
+COMPLEX = COMPLEXO ## Converte coeficientes reais e imaginários num número complexo
+CONVERT = CONVERTER ## Converte um número de um sistema de medida noutro
+DEC2BIN = DECABIN ## Converte um número decimal em binário
+DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal
+DEC2OCT = DECAOCT ## Converte um número decimal em octal
+DELTA = DELTA ## Testa se dois valores são iguais
+ERF = FUNCERRO ## Devolve a função de erro
+ERFC = FUNCERROCOMPL ## Devolve a função de erro complementar
+GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite
+HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário
+HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal
+HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal
+IMABS = IMABS ## Devolve o valor absoluto (módulo) de um número complexo
+IMAGINARY = IMAGINÁRIO ## Devolve o coeficiente imaginário de um número complexo
+IMARGUMENT = IMARG ## Devolve o argumento Teta, um ângulo expresso em radianos
+IMCONJUGATE = IMCONJ ## Devolve o conjugado complexo de um número complexo
+IMCOS = IMCOS ## Devolve o co-seno de um número complexo
+IMDIV = IMDIV ## Devolve o quociente de dois números complexos
+IMEXP = IMEXP ## Devolve o exponencial de um número complexo
+IMLN = IMLN ## Devolve o logaritmo natural de um número complexo
+IMLOG10 = IMLOG10 ## Devolve o logaritmo de base 10 de um número complexo
+IMLOG2 = IMLOG2 ## Devolve o logaritmo de base 2 de um número complexo
+IMPOWER = IMPOT ## Devolve um número complexo elevado a uma potência inteira
+IMPRODUCT = IMPROD ## Devolve o produto de números complexos
+IMREAL = IMREAL ## Devolve o coeficiente real de um número complexo
+IMSIN = IMSENO ## Devolve o seno de um número complexo
+IMSQRT = IMRAIZ ## Devolve a raiz quadrada de um número complexo
+IMSUB = IMSUBTR ## Devolve a diferença entre dois números complexos
+IMSUM = IMSOMA ## Devolve a soma de números complexos
+OCT2BIN = OCTABIN ## Converte um número octal em binário
+OCT2DEC = OCTADEC ## Converte um número octal em decimal
+OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal
+
+
+##
+## Financial functions Funções financeiras
+##
+ACCRINT = JUROSACUM ## Devolve os juros acumulados de um título que paga juros periódicos
+ACCRINTM = JUROSACUMV ## Devolve os juros acumulados de um título que paga juros no vencimento
+AMORDEGRC = AMORDEGRC ## Devolve a depreciação correspondente a cada período contabilístico utilizando um coeficiente de depreciação
+AMORLINC = AMORLINC ## Devolve a depreciação correspondente a cada período contabilístico
+COUPDAYBS = CUPDIASINLIQ ## Devolve o número de dias entre o início do período do cupão e a data de regularização
+COUPDAYS = CUPDIAS ## Devolve o número de dias no período do cupão que contém a data de regularização
+COUPDAYSNC = CUPDIASPRÓX ## Devolve o número de dias entre a data de regularização e a data do cupão seguinte
+COUPNCD = CUPDATAPRÓX ## Devolve a data do cupão seguinte após a data de regularização
+COUPNUM = CUPNÚM ## Devolve o número de cupões a serem pagos entre a data de regularização e a data de vencimento
+COUPPCD = CUPDATAANT ## Devolve a data do cupão anterior antes da data de regularização
+CUMIPMT = PGTOJURACUM ## Devolve os juros cumulativos pagos entre dois períodos
+CUMPRINC = PGTOCAPACUM ## Devolve o capital cumulativo pago a título de empréstimo entre dois períodos
+DB = BD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas fixas
+DDB = BDD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas duplas ou qualquer outro método especificado
+DISC = DESC ## Devolve a taxa de desconto de um título
+DOLLARDE = MOEDADEC ## Converte um preço em unidade monetária, expresso como uma fracção, num preço em unidade monetária, expresso como um número decimal
+DOLLARFR = MOEDAFRA ## Converte um preço em unidade monetária, expresso como um número decimal, num preço em unidade monetária, expresso como uma fracção
+DURATION = DURAÇÃO ## Devolve a duração anual de um título com pagamentos de juros periódicos
+EFFECT = EFECTIVA ## Devolve a taxa de juros anual efectiva
+FV = VF ## Devolve o valor futuro de um investimento
+FVSCHEDULE = VFPLANO ## Devolve o valor futuro de um capital inicial após a aplicação de uma série de taxas de juro compostas
+INTRATE = TAXAJUROS ## Devolve a taxa de juros de um título investido na totalidade
+IPMT = IPGTO ## Devolve o pagamento dos juros de um investimento durante um determinado período
+IRR = TIR ## Devolve a taxa de rentabilidade interna para uma série de fluxos monetários
+ISPMT = É.PGTO ## Calcula os juros pagos durante um período específico de um investimento
+MDURATION = MDURAÇÃO ## Devolve a duração modificada de Macauley de um título com um valor de paridade equivalente a € 100
+MIRR = MTIR ## Devolve a taxa interna de rentabilidade em que os fluxos monetários positivos e negativos são financiados com taxas diferentes
+NOMINAL = NOMINAL ## Devolve a taxa de juros nominal anual
+NPER = NPER ## Devolve o número de períodos de um investimento
+NPV = VAL ## Devolve o valor actual líquido de um investimento com base numa série de fluxos monetários periódicos e numa taxa de desconto
+ODDFPRICE = PREÇOPRIMINC ## Devolve o preço por € 100 do valor nominal de um título com um período inicial incompleto
+ODDFYIELD = LUCROPRIMINC ## Devolve o lucro de um título com um período inicial incompleto
+ODDLPRICE = PREÇOÚLTINC ## Devolve o preço por € 100 do valor nominal de um título com um período final incompleto
+ODDLYIELD = LUCROÚLTINC ## Devolve o lucro de um título com um período final incompleto
+PMT = PGTO ## Devolve o pagamento periódico de uma anuidade
+PPMT = PPGTO ## Devolve o pagamento sobre o capital de um investimento num determinado período
+PRICE = PREÇO ## Devolve o preço por € 100 do valor nominal de um título que paga juros periódicos
+PRICEDISC = PREÇODESC ## Devolve o preço por € 100 do valor nominal de um título descontado
+PRICEMAT = PREÇOVENC ## Devolve o preço por € 100 do valor nominal de um título que paga juros no vencimento
+PV = VA ## Devolve o valor actual de um investimento
+RATE = TAXA ## Devolve a taxa de juros por período de uma anuidade
+RECEIVED = RECEBER ## Devolve o montante recebido no vencimento de um título investido na totalidade
+SLN = AMORT ## Devolve uma depreciação linear de um activo durante um período
+SYD = AMORTD ## Devolve a depreciação por algarismos da soma dos anos de um activo durante um período especificado
+TBILLEQ = OTN ## Devolve o lucro de um título equivalente a uma Obrigação do Tesouro
+TBILLPRICE = OTNVALOR ## Devolve o preço por € 100 de valor nominal de uma Obrigação do Tesouro
+TBILLYIELD = OTNLUCRO ## Devolve o lucro de uma Obrigação do Tesouro
+VDB = BDV ## Devolve a depreciação de um activo relativo a um período específico ou parcial utilizando um método de quotas degressivas
+XIRR = XTIR ## Devolve a taxa interna de rentabilidade de um plano de fluxos monetários que não seja necessariamente periódica
+XNPV = XVAL ## Devolve o valor actual líquido de um plano de fluxos monetários que não seja necessariamente periódico
+YIELD = LUCRO ## Devolve o lucro de um título que paga juros periódicos
+YIELDDISC = LUCRODESC ## Devolve o lucro anual de um título emitido abaixo do valor nominal, por exemplo, uma Obrigação do Tesouro
+YIELDMAT = LUCROVENC ## Devolve o lucro anual de um título que paga juros na data de vencimento
+
+
+##
+## Information functions Funções de informação
+##
+CELL = CÉL ## Devolve informações sobre a formatação, localização ou conteúdo de uma célula
+ERROR.TYPE = TIPO.ERRO ## Devolve um número correspondente a um tipo de erro
+INFO = INFORMAÇÃO ## Devolve informações sobre o ambiente de funcionamento actual
+ISBLANK = É.CÉL.VAZIA ## Devolve VERDADEIRO se o valor estiver em branco
+ISERR = É.ERROS ## Devolve VERDADEIRO se o valor for um valor de erro diferente de #N/D
+ISERROR = É.ERRO ## Devolve VERDADEIRO se o valor for um valor de erro
+ISEVEN = ÉPAR ## Devolve VERDADEIRO se o número for par
+ISLOGICAL = É.LÓGICO ## Devolve VERDADEIRO se o valor for lógico
+ISNA = É.NÃO.DISP ## Devolve VERDADEIRO se o valor for o valor de erro #N/D
+ISNONTEXT = É.NÃO.TEXTO ## Devolve VERDADEIRO se o valor não for texto
+ISNUMBER = É.NÚM ## Devolve VERDADEIRO se o valor for um número
+ISODD = ÉÍMPAR ## Devolve VERDADEIRO se o número for ímpar
+ISREF = É.REF ## Devolve VERDADEIRO se o valor for uma referência
+ISTEXT = É.TEXTO ## Devolve VERDADEIRO se o valor for texto
+N = N ## Devolve um valor convertido num número
+NA = NÃO.DISP ## Devolve o valor de erro #N/D
+TYPE = TIPO ## Devolve um número que indica o tipo de dados de um valor
+
+
+##
+## Logical functions Funções lógicas
+##
+AND = E ## Devolve VERDADEIRO se todos os respectivos argumentos corresponderem a VERDADEIRO
+FALSE = FALSO ## Devolve o valor lógico FALSO
+IF = SE ## Especifica um teste lógico a ser executado
+IFERROR = SE.ERRO ## Devolve um valor definido pelo utilizador se ocorrer um erro na fórmula, e devolve o resultado da fórmula se não ocorrer nenhum erro
+NOT = NÃO ## Inverte a lógica do respectivo argumento
+OR = OU ## Devolve VERDADEIRO se qualquer argumento for VERDADEIRO
+TRUE = VERDADEIRO ## Devolve o valor lógico VERDADEIRO
+
+
+##
+## Lookup and reference functions Funções de pesquisa e referência
+##
+ADDRESS = ENDEREÇO ## Devolve uma referência a uma única célula numa folha de cálculo como texto
+AREAS = ÁREAS ## Devolve o número de áreas numa referência
+CHOOSE = SELECCIONAR ## Selecciona um valor a partir de uma lista de valores
+COLUMN = COL ## Devolve o número da coluna de uma referência
+COLUMNS = COLS ## Devolve o número de colunas numa referência
+HLOOKUP = PROCH ## Procura na linha superior de uma matriz e devolve o valor da célula indicada
+HYPERLINK = HIPERLIGAÇÃO ## Cria um atalho ou hiperligação que abre um documento armazenado num servidor de rede, numa intranet ou na Internet
+INDEX = ÍNDICE ## Utiliza um índice para escolher um valor de uma referência ou de uma matriz
+INDIRECT = INDIRECTO ## Devolve uma referência indicada por um valor de texto
+LOOKUP = PROC ## Procura valores num vector ou numa matriz
+MATCH = CORRESP ## Procura valores numa referência ou numa matriz
+OFFSET = DESLOCAMENTO ## Devolve o deslocamento de referência de uma determinada referência
+ROW = LIN ## Devolve o número da linha de uma referência
+ROWS = LINS ## Devolve o número de linhas numa referência
+RTD = RTD ## Obtém dados em tempo real a partir de um programa que suporte automatização COM (automatização: modo de trabalhar com objectos de uma aplicação a partir de outra aplicação ou ferramenta de desenvolvimento. Anteriormente conhecida como automatização OLE, a automatização é uma norma da indústria de software e uma funcionalidade COM (Component Object Model).)
+TRANSPOSE = TRANSPOR ## Devolve a transposição de uma matriz
+VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e percorre a linha para devolver o valor de uma célula
+
+
+##
+## Math and trigonometry functions Funções matemáticas e trigonométricas
+##
+ABS = ABS ## Devolve o valor absoluto de um número
+ACOS = ACOS ## Devolve o arco de co-seno de um número
+ACOSH = ACOSH ## Devolve o co-seno hiperbólico inverso de um número
+ASIN = ASEN ## Devolve o arco de seno de um número
+ASINH = ASENH ## Devolve o seno hiperbólico inverso de um número
+ATAN = ATAN ## Devolve o arco de tangente de um número
+ATAN2 = ATAN2 ## Devolve o arco de tangente das coordenadas x e y
+ATANH = ATANH ## Devolve a tangente hiperbólica inversa de um número
+CEILING = ARRED.EXCESSO ## Arredonda um número para o número inteiro mais próximo ou para o múltiplo de significância mais próximo
+COMBIN = COMBIN ## Devolve o número de combinações de um determinado número de objectos
+COS = COS ## Devolve o co-seno de um número
+COSH = COSH ## Devolve o co-seno hiperbólico de um número
+DEGREES = GRAUS ## Converte radianos em graus
+EVEN = PAR ## Arredonda um número por excesso para o número inteiro mais próximo
+EXP = EXP ## Devolve e elevado à potência de um determinado número
+FACT = FACTORIAL ## Devolve o factorial de um número
+FACTDOUBLE = FACTDUPLO ## Devolve o factorial duplo de um número
+FLOOR = ARRED.DEFEITO ## Arredonda um número por defeito até zero
+GCD = MDC ## Devolve o maior divisor comum
+INT = INT ## Arredonda um número por defeito para o número inteiro mais próximo
+LCM = MMC ## Devolve o mínimo múltiplo comum
+LN = LN ## Devolve o logaritmo natural de um número
+LOG = LOG ## Devolve o logaritmo de um número com uma base especificada
+LOG10 = LOG10 ## Devolve o logaritmo de base 10 de um número
+MDETERM = MATRIZ.DETERM ## Devolve o determinante matricial de uma matriz
+MINVERSE = MATRIZ.INVERSA ## Devolve o inverso matricial de uma matriz
+MMULT = MATRIZ.MULT ## Devolve o produto matricial de duas matrizes
+MOD = RESTO ## Devolve o resto da divisão
+MROUND = MARRED ## Devolve um número arredondado para o múltiplo pretendido
+MULTINOMIAL = POLINOMIAL ## Devolve o polinomial de um conjunto de números
+ODD = ÍMPAR ## Arredonda por excesso um número para o número inteiro ímpar mais próximo
+PI = PI ## Devolve o valor de pi
+POWER = POTÊNCIA ## Devolve o resultado de um número elevado a uma potência
+PRODUCT = PRODUTO ## Multiplica os respectivos argumentos
+QUOTIENT = QUOCIENTE ## Devolve a parte inteira de uma divisão
+RADIANS = RADIANOS ## Converte graus em radianos
+RAND = ALEATÓRIO ## Devolve um número aleatório entre 0 e 1
+RANDBETWEEN = ALEATÓRIOENTRE ## Devolve um número aleatório entre os números especificados
+ROMAN = ROMANO ## Converte um número árabe em romano, como texto
+ROUND = ARRED ## Arredonda um número para um número de dígitos especificado
+ROUNDDOWN = ARRED.PARA.BAIXO ## Arredonda um número por defeito até zero
+ROUNDUP = ARRED.PARA.CIMA ## Arredonda um número por excesso, afastando-o de zero
+SERIESSUM = SOMASÉRIE ## Devolve a soma de uma série de potências baseada na fórmula
+SIGN = SINAL ## Devolve o sinal de um número
+SIN = SEN ## Devolve o seno de um determinado ângulo
+SINH = SENH ## Devolve o seno hiperbólico de um número
+SQRT = RAIZQ ## Devolve uma raiz quadrada positiva
+SQRTPI = RAIZPI ## Devolve a raiz quadrada de (núm * pi)
+SUBTOTAL = SUBTOTAL ## Devolve um subtotal numa lista ou base de dados
+SUM = SOMA ## Adiciona os respectivos argumentos
+SUMIF = SOMA.SE ## Adiciona as células especificadas por um determinado critério
+SUMIFS = SOMA.SE.S ## Adiciona as células num intervalo que cumpre vários critérios
+SUMPRODUCT = SOMARPRODUTO ## Devolve a soma dos produtos de componentes de matrizes correspondentes
+SUMSQ = SOMARQUAD ## Devolve a soma dos quadrados dos argumentos
+SUMX2MY2 = SOMAX2DY2 ## Devolve a soma da diferença dos quadrados dos valores correspondentes em duas matrizes
+SUMX2PY2 = SOMAX2SY2 ## Devolve a soma da soma dos quadrados dos valores correspondentes em duas matrizes
+SUMXMY2 = SOMAXMY2 ## Devolve a soma dos quadrados da diferença dos valores correspondentes em duas matrizes
+TAN = TAN ## Devolve a tangente de um número
+TANH = TANH ## Devolve a tangente hiperbólica de um número
+TRUNC = TRUNCAR ## Trunca um número para um número inteiro
+
+
+##
+## Statistical functions Funções estatísticas
+##
+AVEDEV = DESV.MÉDIO ## Devolve a média aritmética dos desvios absolutos à média dos pontos de dados
+AVERAGE = MÉDIA ## Devolve a média dos respectivos argumentos
+AVERAGEA = MÉDIAA ## Devolve uma média dos respectivos argumentos, incluindo números, texto e valores lógicos
+AVERAGEIF = MÉDIA.SE ## Devolve a média aritmética de todas as células num intervalo que cumprem determinado critério
+AVERAGEIFS = MÉDIA.SE.S ## Devolve a média aritmética de todas as células que cumprem múltiplos critérios
+BETADIST = DISTBETA ## Devolve a função de distribuição cumulativa beta
+BETAINV = BETA.ACUM.INV ## Devolve o inverso da função de distribuição cumulativa relativamente a uma distribuição beta específica
+BINOMDIST = DISTRBINOM ## Devolve a probabilidade de distribuição binomial de termo individual
+CHIDIST = DIST.CHI ## Devolve a probabilidade unicaudal da distribuição qui-quadrada
+CHIINV = INV.CHI ## Devolve o inverso da probabilidade unicaudal da distribuição qui-quadrada
+CHITEST = TESTE.CHI ## Devolve o teste para independência
+CONFIDENCE = INT.CONFIANÇA ## Devolve o intervalo de confiança correspondente a uma média de população
+CORREL = CORREL ## Devolve o coeficiente de correlação entre dois conjuntos de dados
+COUNT = CONTAR ## Conta os números que existem na lista de argumentos
+COUNTA = CONTAR.VAL ## Conta os valores que existem na lista de argumentos
+COUNTBLANK = CONTAR.VAZIO ## Conta o número de células em branco num intervalo
+COUNTIF = CONTAR.SE ## Calcula o número de células num intervalo que corresponde aos critérios determinados
+COUNTIFS = CONTAR.SE.S ## Conta o número de células num intervalo que cumprem múltiplos critérios
+COVAR = COVAR ## Devolve a covariância, que é a média dos produtos de desvios de pares
+CRITBINOM = CRIT.BINOM ## Devolve o menor valor em que a distribuição binomial cumulativa é inferior ou igual a um valor de critério
+DEVSQ = DESVQ ## Devolve a soma dos quadrados dos desvios
+EXPONDIST = DISTEXPON ## Devolve a distribuição exponencial
+FDIST = DISTF ## Devolve a distribuição da probabilidade F
+FINV = INVF ## Devolve o inverso da distribuição da probabilidade F
+FISHER = FISHER ## Devolve a transformação Fisher
+FISHERINV = FISHERINV ## Devolve o inverso da transformação Fisher
+FORECAST = PREVISÃO ## Devolve um valor ao longo de uma tendência linear
+FREQUENCY = FREQUÊNCIA ## Devolve uma distribuição de frequência como uma matriz vertical
+FTEST = TESTEF ## Devolve o resultado de um teste F
+GAMMADIST = DISTGAMA ## Devolve a distribuição gama
+GAMMAINV = INVGAMA ## Devolve o inverso da distribuição gama cumulativa
+GAMMALN = LNGAMA ## Devolve o logaritmo natural da função gama, Γ(x)
+GEOMEAN = MÉDIA.GEOMÉTRICA ## Devolve a média geométrica
+GROWTH = CRESCIMENTO ## Devolve valores ao longo de uma tendência exponencial
+HARMEAN = MÉDIA.HARMÓNICA ## Devolve a média harmónica
+HYPGEOMDIST = DIST.HIPERGEOM ## Devolve a distribuição hipergeométrica
+INTERCEPT = INTERCEPTAR ## Devolve a intercepção da linha de regressão linear
+KURT = CURT ## Devolve a curtose de um conjunto de dados
+LARGE = MAIOR ## Devolve o maior valor k-ésimo de um conjunto de dados
+LINEST = PROJ.LIN ## Devolve os parâmetros de uma tendência linear
+LOGEST = PROJ.LOG ## Devolve os parâmetros de uma tendência exponencial
+LOGINV = INVLOG ## Devolve o inverso da distribuição normal logarítmica
+LOGNORMDIST = DIST.NORMALLOG ## Devolve a distribuição normal logarítmica cumulativa
+MAX = MÁXIMO ## Devolve o valor máximo numa lista de argumentos
+MAXA = MÁXIMOA ## Devolve o valor máximo numa lista de argumentos, incluindo números, texto e valores lógicos
+MEDIAN = MED ## Devolve a mediana dos números indicados
+MIN = MÍNIMO ## Devolve o valor mínimo numa lista de argumentos
+MINA = MÍNIMOA ## Devolve o valor mínimo numa lista de argumentos, incluindo números, texto e valores lógicos
+MODE = MODA ## Devolve o valor mais comum num conjunto de dados
+NEGBINOMDIST = DIST.BIN.NEG ## Devolve a distribuição binominal negativa
+NORMDIST = DIST.NORM ## Devolve a distribuição cumulativa normal
+NORMINV = INV.NORM ## Devolve o inverso da distribuição cumulativa normal
+NORMSDIST = DIST.NORMP ## Devolve a distribuição cumulativa normal padrão
+NORMSINV = INV.NORMP ## Devolve o inverso da distribuição cumulativa normal padrão
+PEARSON = PEARSON ## Devolve o coeficiente de correlação momento/produto de Pearson
+PERCENTILE = PERCENTIL ## Devolve o k-ésimo percentil de valores num intervalo
+PERCENTRANK = ORDEM.PERCENTUAL ## Devolve a ordem percentual de um valor num conjunto de dados
+PERMUT = PERMUTAR ## Devolve o número de permutações de um determinado número de objectos
+POISSON = POISSON ## Devolve a distribuição de Poisson
+PROB = PROB ## Devolve a probabilidade dos valores num intervalo se encontrarem entre dois limites
+QUARTILE = QUARTIL ## Devolve o quartil de um conjunto de dados
+RANK = ORDEM ## Devolve a ordem de um número numa lista numérica
+RSQ = RQUAD ## Devolve o quadrado do coeficiente de correlação momento/produto de Pearson
+SKEW = DISTORÇÃO ## Devolve a distorção de uma distribuição
+SLOPE = DECLIVE ## Devolve o declive da linha de regressão linear
+SMALL = MENOR ## Devolve o menor valor de k-ésimo de um conjunto de dados
+STANDARDIZE = NORMALIZAR ## Devolve um valor normalizado
+STDEV = DESVPAD ## Calcula o desvio-padrão com base numa amostra
+STDEVA = DESVPADA ## Calcula o desvio-padrão com base numa amostra, incluindo números, texto e valores lógicos
+STDEVP = DESVPADP ## Calcula o desvio-padrão com base na população total
+STDEVPA = DESVPADPA ## Calcula o desvio-padrão com base na população total, incluindo números, texto e valores lógicos
+STEYX = EPADYX ## Devolve o erro-padrão do valor de y previsto para cada x na regressão
+TDIST = DISTT ## Devolve a distribuição t de Student
+TINV = INVT ## Devolve o inverso da distribuição t de Student
+TREND = TENDÊNCIA ## Devolve valores ao longo de uma tendência linear
+TRIMMEAN = MÉDIA.INTERNA ## Devolve a média do interior de um conjunto de dados
+TTEST = TESTET ## Devolve a probabilidade associada ao teste t de Student
+VAR = VAR ## Calcula a variância com base numa amostra
+VARA = VARA ## Calcula a variância com base numa amostra, incluindo números, texto e valores lógicos
+VARP = VARP ## Calcula a variância com base na população total
+VARPA = VARPA ## Calcula a variância com base na população total, incluindo números, texto e valores lógicos
+WEIBULL = WEIBULL ## Devolve a distribuição Weibull
+ZTEST = TESTEZ ## Devolve o valor de probabilidade unicaudal de um teste-z
+
+
+##
+## Text functions Funções de texto
+##
+ASC = ASC ## Altera letras ou katakana de largura total (byte duplo) numa cadeia de caracteres para caracteres de largura média (byte único)
+BAHTTEXT = TEXTO.BAHT ## Converte um número em texto, utilizando o formato monetário ß (baht)
+CHAR = CARÁCT ## Devolve o carácter especificado pelo número de código
+CLEAN = LIMPAR ## Remove do texto todos os caracteres não imprimíveis
+CODE = CÓDIGO ## Devolve um código numérico correspondente ao primeiro carácter numa cadeia de texto
+CONCATENATE = CONCATENAR ## Agrupa vários itens de texto num único item de texto
+DOLLAR = MOEDA ## Converte um número em texto, utilizando o formato monetário € (Euro)
+EXACT = EXACTO ## Verifica se dois valores de texto são idênticos
+FIND = LOCALIZAR ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas)
+FINDB = LOCALIZARB ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas)
+FIXED = FIXA ## Formata um número como texto com um número fixo de decimais
+JIS = JIS ## Altera letras ou katakana de largura média (byte único) numa cadeia de caracteres para caracteres de largura total (byte duplo)
+LEFT = ESQUERDA ## Devolve os caracteres mais à esquerda de um valor de texto
+LEFTB = ESQUERDAB ## Devolve os caracteres mais à esquerda de um valor de texto
+LEN = NÚM.CARACT ## Devolve o número de caracteres de uma cadeia de texto
+LENB = NÚM.CARACTB ## Devolve o número de caracteres de uma cadeia de texto
+LOWER = MINÚSCULAS ## Converte o texto em minúsculas
+MID = SEG.TEXTO ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada
+MIDB = SEG.TEXTOB ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada
+PHONETIC = FONÉTICA ## Retira os caracteres fonéticos (furigana) de uma cadeia de texto
+PROPER = INICIAL.MAIÚSCULA ## Coloca em maiúsculas a primeira letra de cada palavra de um valor de texto
+REPLACE = SUBSTITUIR ## Substitui caracteres no texto
+REPLACEB = SUBSTITUIRB ## Substitui caracteres no texto
+REPT = REPETIR ## Repete texto um determinado número de vezes
+RIGHT = DIREITA ## Devolve os caracteres mais à direita de um valor de texto
+RIGHTB = DIREITAB ## Devolve os caracteres mais à direita de um valor de texto
+SEARCH = PROCURAR ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas)
+SEARCHB = PROCURARB ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas)
+SUBSTITUTE = SUBST ## Substitui texto novo por texto antigo numa cadeia de texto
+T = T ## Converte os respectivos argumentos em texto
+TEXT = TEXTO ## Formata um número e converte-o em texto
+TRIM = COMPACTAR ## Remove espaços do texto
+UPPER = MAIÚSCULAS ## Converte texto em maiúsculas
+VALUE = VALOR ## Converte um argumento de texto num número
diff --git a/PHPExcel/locale/ru/config b/PHPExcel/locale/ru/config
new file mode 100644
index 0000000..6f6ace2
--- /dev/null
+++ b/PHPExcel/locale/ru/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = р
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #ПУСТО!
+DIV0 = #ДЕЛ/0!
+VALUE = #ЗНАЧ!
+REF = #ССЫЛ!
+NAME = #ИМЯ?
+NUM = #ЧИСЛО!
+NA = #Н/Д
diff --git a/PHPExcel/locale/ru/functions b/PHPExcel/locale/ru/functions
new file mode 100644
index 0000000..bd63686
--- /dev/null
+++ b/PHPExcel/locale/ru/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from information provided by web-junior (http://www.web-junior.net/)
+##
+##
+
+
+##
+## Add-in and Automation functions Функции надстроек и автоматизации
+##
+GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы.
+
+
+##
+## Cube functions Функции Куб
+##
+CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации.
+CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе.
+CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента.
+CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов.
+CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel.
+CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества.
+CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба.
+
+
+##
+## Database functions Функции для работы с базами данных
+##
+DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных.
+DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных.
+DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных.
+DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию.
+DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных.
+DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных.
+DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию.
+DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных.
+DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных
+DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию.
+DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных
+DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных
+
+
+##
+## Date and time functions Функции даты и времени
+##
+DATE = ДАТА ## Возвращает заданную дату в числовом формате.
+DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат.
+DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца.
+DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года.
+EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты.
+EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев.
+HOUR = ЧАС ## Преобразует дату в числовом формате в часы.
+MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты.
+MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы.
+NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами.
+NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате.
+SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды.
+TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате.
+TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат.
+TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате.
+WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели.
+WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата.
+WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней.
+YEAR = ГОД ## Преобразует дату в числовом формате в год.
+YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами.
+
+
+##
+## Engineering functions Инженерные функции
+##
+BESSELI = БЕССЕЛЬ.I ## Возвращает модифицированную функцию Бесселя In(x).
+BESSELJ = БЕССЕЛЬ.J ## Возвращает функцию Бесселя Jn(x).
+BESSELK = БЕССЕЛЬ.K ## Возвращает модифицированную функцию Бесселя Kn(x).
+BESSELY = БЕССЕЛЬ.Y ## Возвращает функцию Бесселя Yn(x).
+BIN2DEC = ДВ.В.ДЕС ## Преобразует двоичное число в десятичное.
+BIN2HEX = ДВ.В.ШЕСТН ## Преобразует двоичное число в шестнадцатеричное.
+BIN2OCT = ДВ.В.ВОСЬМ ## Преобразует двоичное число в восьмеричное.
+COMPLEX = КОМПЛЕКСН ## Преобразует коэффициенты при вещественной и мнимой частях комплексного числа в комплексное число.
+CONVERT = ПРЕОБР ## Преобразует число из одной системы единиц измерения в другую.
+DEC2BIN = ДЕС.В.ДВ ## Преобразует десятичное число в двоичное.
+DEC2HEX = ДЕС.В.ШЕСТН ## Преобразует десятичное число в шестнадцатеричное.
+DEC2OCT = ДЕС.В.ВОСЬМ ## Преобразует десятичное число в восьмеричное.
+DELTA = ДЕЛЬТА ## Проверяет равенство двух значений.
+ERF = ФОШ ## Возвращает функцию ошибки.
+ERFC = ДФОШ ## Возвращает дополнительную функцию ошибки.
+GESTEP = ПОРОГ ## Проверяет, не превышает ли данное число порогового значения.
+HEX2BIN = ШЕСТН.В.ДВ ## Преобразует шестнадцатеричное число в двоичное.
+HEX2DEC = ШЕСТН.В.ДЕС ## Преобразует шестнадцатеричное число в десятичное.
+HEX2OCT = ШЕСТН.В.ВОСЬМ ## Преобразует шестнадцатеричное число в восьмеричное.
+IMABS = МНИМ.ABS ## Возвращает абсолютную величину (модуль) комплексного числа.
+IMAGINARY = МНИМ.ЧАСТЬ ## Возвращает коэффициент при мнимой части комплексного числа.
+IMARGUMENT = МНИМ.АРГУМЕНТ ## Возвращает значение аргумента комплексного числа (тета) — угол, выраженный в радианах.
+IMCONJUGATE = МНИМ.СОПРЯЖ ## Возвращает комплексно-сопряженное комплексное число.
+IMCOS = МНИМ.COS ## Возвращает косинус комплексного числа.
+IMDIV = МНИМ.ДЕЛ ## Возвращает частное от деления двух комплексных чисел.
+IMEXP = МНИМ.EXP ## Возвращает экспоненту комплексного числа.
+IMLN = МНИМ.LN ## Возвращает натуральный логарифм комплексного числа.
+IMLOG10 = МНИМ.LOG10 ## Возвращает обычный (десятичный) логарифм комплексного числа.
+IMLOG2 = МНИМ.LOG2 ## Возвращает двоичный логарифм комплексного числа.
+IMPOWER = МНИМ.СТЕПЕНЬ ## Возвращает комплексное число, возведенное в целую степень.
+IMPRODUCT = МНИМ.ПРОИЗВЕД ## Возвращает произведение от 2 до 29 комплексных чисел.
+IMREAL = МНИМ.ВЕЩ ## Возвращает коэффициент при вещественной части комплексного числа.
+IMSIN = МНИМ.SIN ## Возвращает синус комплексного числа.
+IMSQRT = МНИМ.КОРЕНЬ ## Возвращает значение квадратного корня из комплексного числа.
+IMSUB = МНИМ.РАЗН ## Возвращает разность двух комплексных чисел.
+IMSUM = МНИМ.СУММ ## Возвращает сумму комплексных чисел.
+OCT2BIN = ВОСЬМ.В.ДВ ## Преобразует восьмеричное число в двоичное.
+OCT2DEC = ВОСЬМ.В.ДЕС ## Преобразует восьмеричное число в десятичное.
+OCT2HEX = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное.
+
+
+##
+## Financial functions Финансовые функции
+##
+ACCRINT = НАКОПДОХОД ## Возвращает накопленный процент по ценным бумагам с периодической выплатой процентов.
+ACCRINTM = НАКОПДОХОДПОГАШ ## Возвращает накопленный процент по ценным бумагам, проценты по которым выплачиваются в срок погашения.
+AMORDEGRC = АМОРУМ ## Возвращает величину амортизации для каждого периода, используя коэффициент амортизации.
+AMORLINC = АМОРУВ ## Возвращает величину амортизации для каждого периода.
+COUPDAYBS = ДНЕЙКУПОНДО ## Возвращает количество дней от начала действия купона до даты соглашения.
+COUPDAYS = ДНЕЙКУПОН ## Возвращает число дней в периоде купона, содержащем дату соглашения.
+COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ ## Возвращает число дней от даты соглашения до срока следующего купона.
+COUPNCD = ДАТАКУПОНПОСЛЕ ## Возвращает следующую дату купона после даты соглашения.
+COUPNUM = ЧИСЛКУПОН ## Возвращает количество купонов, которые могут быть оплачены между датой соглашения и сроком вступления в силу.
+COUPPCD = ДАТАКУПОНДО ## Возвращает предыдущую дату купона перед датой соглашения.
+CUMIPMT = ОБЩПЛАТ ## Возвращает общую выплату, произведенную между двумя периодическими выплатами.
+CUMPRINC = ОБЩДОХОД ## Возвращает общую выплату по займу между двумя периодами.
+DB = ФУО ## Возвращает величину амортизации актива для заданного периода, рассчитанную методом фиксированного уменьшения остатка.
+DDB = ДДОБ ## Возвращает величину амортизации актива за данный период, используя метод двойного уменьшения остатка или иной явно указанный метод.
+DISC = СКИДКА ## Возвращает норму скидки для ценных бумаг.
+DOLLARDE = РУБЛЬ.ДЕС ## Преобразует цену в рублях, выраженную в виде дроби, в цену в рублях, выраженную десятичным числом.
+DOLLARFR = РУБЛЬ.ДРОБЬ ## Преобразует цену в рублях, выраженную десятичным числом, в цену в рублях, выраженную в виде дроби.
+DURATION = ДЛИТ ## Возвращает ежегодную продолжительность действия ценных бумаг с периодическими выплатами по процентам.
+EFFECT = ЭФФЕКТ ## Возвращает действующие ежегодные процентные ставки.
+FV = БС ## Возвращает будущую стоимость инвестиции.
+FVSCHEDULE = БЗРАСПИС ## Возвращает будущую стоимость первоначальной основной суммы после начисления ряда сложных процентов.
+INTRATE = ИНОРМА ## Возвращает процентную ставку для полностью инвестированных ценных бумаг.
+IPMT = ПРПЛТ ## Возвращает величину выплаты прибыли на вложения за данный период.
+IRR = ВСД ## Возвращает внутреннюю ставку доходности для ряда потоков денежных средств.
+ISPMT = ПРОЦПЛАТ ## Вычисляет выплаты за указанный период инвестиции.
+MDURATION = МДЛИТ ## Возвращает модифицированную длительность Маколея для ценных бумаг с предполагаемой номинальной стоимостью 100 рублей.
+MIRR = МВСД ## Возвращает внутреннюю ставку доходности, при которой положительные и отрицательные денежные потоки имеют разные значения ставки.
+NOMINAL = НОМИНАЛ ## Возвращает номинальную годовую процентную ставку.
+NPER = КПЕР ## Возвращает общее количество периодов выплаты для данного вклада.
+NPV = ЧПС ## Возвращает чистую приведенную стоимость инвестиции, основанной на серии периодических денежных потоков и ставке дисконтирования.
+ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным первым периодом.
+ODDFYIELD = ДОХОДПЕРВНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным первым периодом.
+ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным последним периодом.
+ODDLYIELD = ДОХОДПОСЛНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным последним периодом.
+PMT = ПЛТ ## Возвращает величину выплаты за один период аннуитета.
+PPMT = ОСПЛТ ## Возвращает величину выплат в погашение основной суммы по инвестиции за заданный период.
+PRICE = ЦЕНА ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг, по которым производится периодическая выплата процентов.
+PRICEDISC = ЦЕНАСКИДКА ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, на которые сделана скидка.
+PRICEMAT = ЦЕНАПОГАШ ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, проценты по которым выплачиваются в срок погашения.
+PV = ПС ## Возвращает приведенную (к текущему моменту) стоимость инвестиции.
+RATE = СТАВКА ## Возвращает процентную ставку по аннуитету за один период.
+RECEIVED = ПОЛУЧЕНО ## Возвращает сумму, полученную к сроку погашения полностью обеспеченных ценных бумаг.
+SLN = АПЛ ## Возвращает величину линейной амортизации актива за один период.
+SYD = АСЧ ## Возвращает величину амортизации актива за данный период, рассчитанную методом суммы годовых чисел.
+TBILLEQ = РАВНОКЧЕК ## Возвращает эквивалентный облигации доход по казначейскому чеку.
+TBILLPRICE = ЦЕНАКЧЕК ## Возвращает цену за 100 рублей нарицательной стоимости для казначейского чека.
+TBILLYIELD = ДОХОДКЧЕК ## Возвращает доход по казначейскому чеку.
+VDB = ПУО ## Возвращает величину амортизации актива для указанного или частичного периода при использовании метода сокращающегося баланса.
+XIRR = ЧИСТВНДОХ ## Возвращает внутреннюю ставку доходности для графика денежных потоков, которые не обязательно носят периодический характер.
+XNPV = ЧИСТНЗ ## Возвращает чистую приведенную стоимость для денежных потоков, которые не обязательно являются периодическими.
+YIELD = ДОХОД ## Возвращает доход от ценных бумаг, по которым производятся периодические выплаты процентов.
+YIELDDISC = ДОХОДСКИДКА ## Возвращает годовой доход по ценным бумагам, на которые сделана скидка (пример — казначейские чеки).
+YIELDMAT = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения.
+
+
+##
+## Information functions Информационные функции
+##
+CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки.
+ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки.
+INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде.
+ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку.
+ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д.
+ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки.
+ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом.
+ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение.
+ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д.
+ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом.
+ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число.
+ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом.
+ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой.
+ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом.
+N = Ч ## Возвращает значение, преобразованное в число.
+NA = НД ## Возвращает значение ошибки #Н/Д.
+TYPE = ТИП ## Возвращает число, обозначающее тип данных значения.
+
+
+##
+## Logical functions Логические функции
+##
+AND = И ## Renvoie VRAI si tous ses arguments sont VRAI.
+FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ.
+IF = ЕСЛИ ## Выполняет проверку условия.
+IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления.
+NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное.
+OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА.
+TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА.
+
+
+##
+## Lookup and reference functions Функции ссылки и поиска
+##
+ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста.
+AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке.
+CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу.
+COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка.
+COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке.
+HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки
+HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете.
+INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива.
+INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением.
+LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве.
+MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве.
+OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки.
+ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой.
+ROWS = ЧСТРОК ## Возвращает количество строк в ссылке.
+RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).).
+TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив.
+VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце.
+
+
+##
+## Math and trigonometry functions Математические и тригонометрические функции
+##
+ABS = ABS ## Возвращает модуль (абсолютную величину) числа.
+ACOS = ACOS ## Возвращает арккосинус числа.
+ACOSH = ACOSH ## Возвращает гиперболический арккосинус числа.
+ASIN = ASIN ## Возвращает арксинус числа.
+ASINH = ASINH ## Возвращает гиперболический арксинус числа.
+ATAN = ATAN ## Возвращает арктангенс числа.
+ATAN2 = ATAN2 ## Возвращает арктангенс для заданных координат x и y.
+ATANH = ATANH ## Возвращает гиперболический арктангенс числа.
+CEILING = ОКРВВЕРХ ## Округляет число до ближайшего целого или до ближайшего кратного указанному значению.
+COMBIN = ЧИСЛКОМБ ## Возвращает количество комбинаций для заданного числа объектов.
+COS = COS ## Возвращает косинус числа.
+COSH = COSH ## Возвращает гиперболический косинус числа.
+DEGREES = ГРАДУСЫ ## Преобразует радианы в градусы.
+EVEN = ЧЁТН ## Округляет число до ближайшего четного целого.
+EXP = EXP ## Возвращает число e, возведенное в указанную степень.
+FACT = ФАКТР ## Возвращает факториал числа.
+FACTDOUBLE = ДВФАКТР ## Возвращает двойной факториал числа.
+FLOOR = ОКРВНИЗ ## Округляет число до ближайшего меньшего по модулю значения.
+GCD = НОД ## Возвращает наибольший общий делитель.
+INT = ЦЕЛОЕ ## Округляет число до ближайшего меньшего целого.
+LCM = НОК ## Возвращает наименьшее общее кратное.
+LN = LN ## Возвращает натуральный логарифм числа.
+LOG = LOG ## Возвращает логарифм числа по заданному основанию.
+LOG10 = LOG10 ## Возвращает десятичный логарифм числа.
+MDETERM = МОПРЕД ## Возвращает определитель матрицы массива.
+MINVERSE = МОБР ## Возвращает обратную матрицу массива.
+MMULT = МУМНОЖ ## Возвращает произведение матриц двух массивов.
+MOD = ОСТАТ ## Возвращает остаток от деления.
+MROUND = ОКРУГЛТ ## Возвращает число, округленное с требуемой точностью.
+MULTINOMIAL = МУЛЬТИНОМ ## Возвращает мультиномиальный коэффициент множества чисел.
+ODD = НЕЧЁТ ## Округляет число до ближайшего нечетного целого.
+PI = ПИ ## Возвращает число пи.
+POWER = СТЕПЕНЬ ## Возвращает результат возведения числа в степень.
+PRODUCT = ПРОИЗВЕД ## Возвращает произведение аргументов.
+QUOTIENT = ЧАСТНОЕ ## Возвращает целую часть частного при делении.
+RADIANS = РАДИАНЫ ## Преобразует градусы в радианы.
+RAND = СЛЧИС ## Возвращает случайное число в интервале от 0 до 1.
+RANDBETWEEN = СЛУЧМЕЖДУ ## Возвращает случайное число в интервале между двумя заданными числами.
+ROMAN = РИМСКОЕ ## Преобразует арабские цифры в римские в виде текста.
+ROUND = ОКРУГЛ ## Округляет число до указанного количества десятичных разрядов.
+ROUNDDOWN = ОКРУГЛВНИЗ ## Округляет число до ближайшего меньшего по модулю значения.
+ROUNDUP = ОКРУГЛВВЕРХ ## Округляет число до ближайшего большего по модулю значения.
+SERIESSUM = РЯД.СУММ ## Возвращает сумму степенного ряда, вычисленную по формуле.
+SIGN = ЗНАК ## Возвращает знак числа.
+SIN = SIN ## Возвращает синус заданного угла.
+SINH = SINH ## Возвращает гиперболический синус числа.
+SQRT = КОРЕНЬ ## Возвращает положительное значение квадратного корня.
+SQRTPI = КОРЕНЬПИ ## Возвращает квадратный корень из значения выражения (число * ПИ).
+SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ ## Возвращает промежуточный итог в списке или базе данных.
+SUM = СУММ ## Суммирует аргументы.
+SUMIF = СУММЕСЛИ ## Суммирует ячейки, удовлетворяющие заданному условию.
+SUMIFS = СУММЕСЛИМН ## Суммирует диапазон ячеек, удовлетворяющих нескольким условиям.
+SUMPRODUCT = СУММПРОИЗВ ## Возвращает сумму произведений соответствующих элементов массивов.
+SUMSQ = СУММКВ ## Возвращает сумму квадратов аргументов.
+SUMX2MY2 = СУММРАЗНКВ ## Возвращает сумму разностей квадратов соответствующих значений в двух массивах.
+SUMX2PY2 = СУММСУММКВ ## Возвращает сумму сумм квадратов соответствующих элементов двух массивов.
+SUMXMY2 = СУММКВРАЗН ## Возвращает сумму квадратов разностей соответствующих значений в двух массивах.
+TAN = TAN ## Возвращает тангенс числа.
+TANH = TANH ## Возвращает гиперболический тангенс числа.
+TRUNC = ОТБР ## Отбрасывает дробную часть числа.
+
+
+##
+## Statistical functions Статистические функции
+##
+AVEDEV = СРОТКЛ ## Возвращает среднее арифметическое абсолютных значений отклонений точек данных от среднего.
+AVERAGE = СРЗНАЧ ## Возвращает среднее арифметическое аргументов.
+AVERAGEA = СРЗНАЧА ## Возвращает среднее арифметическое аргументов, включая числа, текст и логические значения.
+AVERAGEIF = СРЗНАЧЕСЛИ ## Возвращает среднее значение (среднее арифметическое) всех ячеек в диапазоне, которые удовлетворяют данному условию.
+AVERAGEIFS = СРЗНАЧЕСЛИМН ## Возвращает среднее значение (среднее арифметическое) всех ячеек, которые удовлетворяют нескольким условиям.
+BETADIST = БЕТАРАСП ## Возвращает интегральную функцию бета-распределения.
+BETAINV = БЕТАОБР ## Возвращает обратную интегральную функцию указанного бета-распределения.
+BINOMDIST = БИНОМРАСП ## Возвращает отдельное значение биномиального распределения.
+CHIDIST = ХИ2РАСП ## Возвращает одностороннюю вероятность распределения хи-квадрат.
+CHIINV = ХИ2ОБР ## Возвращает обратное значение односторонней вероятности распределения хи-квадрат.
+CHITEST = ХИ2ТЕСТ ## Возвращает тест на независимость.
+CONFIDENCE = ДОВЕРИТ ## Возвращает доверительный интервал для среднего значения по генеральной совокупности.
+CORREL = КОРРЕЛ ## Возвращает коэффициент корреляции между двумя множествами данных.
+COUNT = СЧЁТ ## Подсчитывает количество чисел в списке аргументов.
+COUNTA = СЧЁТЗ ## Подсчитывает количество значений в списке аргументов.
+COUNTBLANK = СЧИТАТЬПУСТОТЫ ## Подсчитывает количество пустых ячеек в диапазоне
+COUNTIF = СЧЁТЕСЛИ ## Подсчитывает количество ячеек в диапазоне, удовлетворяющих заданному условию
+COUNTIFS = СЧЁТЕСЛИМН ## Подсчитывает количество ячеек внутри диапазона, удовлетворяющих нескольким условиям.
+COVAR = КОВАР ## Возвращает ковариацию, среднее произведений парных отклонений
+CRITBINOM = КРИТБИНОМ ## Возвращает наименьшее значение, для которого интегральное биномиальное распределение меньше или равно заданному критерию.
+DEVSQ = КВАДРОТКЛ ## Возвращает сумму квадратов отклонений.
+EXPONDIST = ЭКСПРАСП ## Возвращает экспоненциальное распределение.
+FDIST = FРАСП ## Возвращает F-распределение вероятности.
+FINV = FРАСПОБР ## Возвращает обратное значение для F-распределения вероятности.
+FISHER = ФИШЕР ## Возвращает преобразование Фишера.
+FISHERINV = ФИШЕРОБР ## Возвращает обратное преобразование Фишера.
+FORECAST = ПРЕДСКАЗ ## Возвращает значение линейного тренда.
+FREQUENCY = ЧАСТОТА ## Возвращает распределение частот в виде вертикального массива.
+FTEST = ФТЕСТ ## Возвращает результат F-теста.
+GAMMADIST = ГАММАРАСП ## Возвращает гамма-распределение.
+GAMMAINV = ГАММАОБР ## Возвращает обратное гамма-распределение.
+GAMMALN = ГАММАНЛОГ ## Возвращает натуральный логарифм гамма функции, Γ(x).
+GEOMEAN = СРГЕОМ ## Возвращает среднее геометрическое.
+GROWTH = РОСТ ## Возвращает значения в соответствии с экспоненциальным трендом.
+HARMEAN = СРГАРМ ## Возвращает среднее гармоническое.
+HYPGEOMDIST = ГИПЕРГЕОМЕТ ## Возвращает гипергеометрическое распределение.
+INTERCEPT = ОТРЕЗОК ## Возвращает отрезок, отсекаемый на оси линией линейной регрессии.
+KURT = ЭКСЦЕСС ## Возвращает эксцесс множества данных.
+LARGE = НАИБОЛЬШИЙ ## Возвращает k-ое наибольшее значение в множестве данных.
+LINEST = ЛИНЕЙН ## Возвращает параметры линейного тренда.
+LOGEST = ЛГРФПРИБЛ ## Возвращает параметры экспоненциального тренда.
+LOGINV = ЛОГНОРМОБР ## Возвращает обратное логарифмическое нормальное распределение.
+LOGNORMDIST = ЛОГНОРМРАСП ## Возвращает интегральное логарифмическое нормальное распределение.
+MAX = МАКС ## Возвращает наибольшее значение в списке аргументов.
+MAXA = МАКСА ## Возвращает наибольшее значение в списке аргументов, включая числа, текст и логические значения.
+MEDIAN = МЕДИАНА ## Возвращает медиану заданных чисел.
+MIN = МИН ## Возвращает наименьшее значение в списке аргументов.
+MINA = МИНА ## Возвращает наименьшее значение в списке аргументов, включая числа, текст и логические значения.
+MODE = МОДА ## Возвращает значение моды множества данных.
+NEGBINOMDIST = ОТРБИНОМРАСП ## Возвращает отрицательное биномиальное распределение.
+NORMDIST = НОРМРАСП ## Возвращает нормальную функцию распределения.
+NORMINV = НОРМОБР ## Возвращает обратное нормальное распределение.
+NORMSDIST = НОРМСТРАСП ## Возвращает стандартное нормальное интегральное распределение.
+NORMSINV = НОРМСТОБР ## Возвращает обратное значение стандартного нормального распределения.
+PEARSON = ПИРСОН ## Возвращает коэффициент корреляции Пирсона.
+PERCENTILE = ПЕРСЕНТИЛЬ ## Возвращает k-ую персентиль для значений диапазона.
+PERCENTRANK = ПРОЦЕНТРАНГ ## Возвращает процентную норму значения в множестве данных.
+PERMUT = ПЕРЕСТ ## Возвращает количество перестановок для заданного числа объектов.
+POISSON = ПУАССОН ## Возвращает распределение Пуассона.
+PROB = ВЕРОЯТНОСТЬ ## Возвращает вероятность того, что значение из диапазона находится внутри заданных пределов.
+QUARTILE = КВАРТИЛЬ ## Возвращает квартиль множества данных.
+RANK = РАНГ ## Возвращает ранг числа в списке чисел.
+RSQ = КВПИРСОН ## Возвращает квадрат коэффициента корреляции Пирсона.
+SKEW = СКОС ## Возвращает асимметрию распределения.
+SLOPE = НАКЛОН ## Возвращает наклон линии линейной регрессии.
+SMALL = НАИМЕНЬШИЙ ## Возвращает k-ое наименьшее значение в множестве данных.
+STANDARDIZE = НОРМАЛИЗАЦИЯ ## Возвращает нормализованное значение.
+STDEV = СТАНДОТКЛОН ## Оценивает стандартное отклонение по выборке.
+STDEVA = СТАНДОТКЛОНА ## Оценивает стандартное отклонение по выборке, включая числа, текст и логические значения.
+STDEVP = СТАНДОТКЛОНП ## Вычисляет стандартное отклонение по генеральной совокупности.
+STDEVPA = СТАНДОТКЛОНПА ## Вычисляет стандартное отклонение по генеральной совокупности, включая числа, текст и логические значения.
+STEYX = СТОШYX ## Возвращает стандартную ошибку предсказанных значений y для каждого значения x в регрессии.
+TDIST = СТЬЮДРАСП ## Возвращает t-распределение Стьюдента.
+TINV = СТЬЮДРАСПОБР ## Возвращает обратное t-распределение Стьюдента.
+TREND = ТЕНДЕНЦИЯ ## Возвращает значения в соответствии с линейным трендом.
+TRIMMEAN = УРЕЗСРЕДНЕЕ ## Возвращает среднее внутренности множества данных.
+TTEST = ТТЕСТ ## Возвращает вероятность, соответствующую критерию Стьюдента.
+VAR = ДИСП ## Оценивает дисперсию по выборке.
+VARA = ДИСПА ## Оценивает дисперсию по выборке, включая числа, текст и логические значения.
+VARP = ДИСПР ## Вычисляет дисперсию для генеральной совокупности.
+VARPA = ДИСПРА ## Вычисляет дисперсию для генеральной совокупности, включая числа, текст и логические значения.
+WEIBULL = ВЕЙБУЛЛ ## Возвращает распределение Вейбулла.
+ZTEST = ZТЕСТ ## Возвращает двустороннее P-значение z-теста.
+
+
+##
+## Text functions Текстовые функции
+##
+ASC = ASC ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полноширинные (двухбайтовые) знаки в полуширинные (однобайтовые).
+BAHTTEXT = БАТТЕКСТ ## Преобразует число в текст, используя денежный формат ß (БАТ).
+CHAR = СИМВОЛ ## Возвращает знак с заданным кодом.
+CLEAN = ПЕЧСИМВ ## Удаляет все непечатаемые знаки из текста.
+CODE = КОДСИМВ ## Возвращает числовой код первого знака в текстовой строке.
+CONCATENATE = СЦЕПИТЬ ## Объединяет несколько текстовых элементов в один.
+DOLLAR = РУБЛЬ ## Преобразует число в текст, используя денежный формат.
+EXACT = СОВПАД ## Проверяет идентичность двух текстовых значений.
+FIND = НАЙТИ ## Ищет вхождения одного текстового значения в другом (с учетом регистра).
+FINDB = НАЙТИБ ## Ищет вхождения одного текстового значения в другом (с учетом регистра).
+FIXED = ФИКСИРОВАННЫЙ ## Форматирует число и преобразует его в текст с заданным числом десятичных знаков.
+JIS = JIS ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полуширинные (однобайтовые) знаки в текстовой строке в полноширинные (двухбайтовые).
+LEFT = ЛЕВСИМВ ## Возвращает крайние слева знаки текстового значения.
+LEFTB = ЛЕВБ ## Возвращает крайние слева знаки текстового значения.
+LEN = ДЛСТР ## Возвращает количество знаков в текстовой строке.
+LENB = ДЛИНБ ## Возвращает количество знаков в текстовой строке.
+LOWER = СТРОЧН ## Преобразует все буквы текста в строчные.
+MID = ПСТР ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции.
+MIDB = ПСТРБ ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции.
+PHONETIC = PHONETIC ## Извлекает фонетические (фуригана) знаки из текстовой строки.
+PROPER = ПРОПНАЧ ## Преобразует первую букву в каждом слове текста в прописную.
+REPLACE = ЗАМЕНИТЬ ## Заменяет знаки в тексте.
+REPLACEB = ЗАМЕНИТЬБ ## Заменяет знаки в тексте.
+REPT = ПОВТОР ## Повторяет текст заданное число раз.
+RIGHT = ПРАВСИМВ ## Возвращает крайние справа знаки текстовой строки.
+RIGHTB = ПРАВБ ## Возвращает крайние справа знаки текстовой строки.
+SEARCH = ПОИСК ## Ищет вхождения одного текстового значения в другом (без учета регистра).
+SEARCHB = ПОИСКБ ## Ищет вхождения одного текстового значения в другом (без учета регистра).
+SUBSTITUTE = ПОДСТАВИТЬ ## Заменяет в текстовой строке старый текст новым.
+T = Т ## Преобразует аргументы в текст.
+TEXT = ТЕКСТ ## Форматирует число и преобразует его в текст.
+TRIM = СЖПРОБЕЛЫ ## Удаляет из текста пробелы.
+UPPER = ПРОПИСН ## Преобразует все буквы текста в прописные.
+VALUE = ЗНАЧЕН ## Преобразует текстовый аргумент в число.
diff --git a/PHPExcel/locale/sv/config b/PHPExcel/locale/sv/config
new file mode 100644
index 0000000..5d1a9a9
--- /dev/null
+++ b/PHPExcel/locale/sv/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = kr
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #Skärning!
+DIV0 = #Division/0!
+VALUE = #Värdefel!
+REF = #Referens!
+NAME = #Namn?
+NUM = #Ogiltigt!
+NA = #Saknas!
diff --git a/PHPExcel/locale/sv/functions b/PHPExcel/locale/sv/functions
new file mode 100644
index 0000000..9af37d8
--- /dev/null
+++ b/PHPExcel/locale/sv/functions
@@ -0,0 +1,408 @@
+##
+## Add-in and Automation functions Tilläggs- och automatiseringsfunktioner
+##
+GETPIVOTDATA = HÄMTA.PIVOTDATA ## Returnerar data som lagrats i en pivottabellrapport
+
+
+##
+## Cube functions Kubfunktioner
+##
+CUBEKPIMEMBER = KUBKPIMEDLEM ## Returnerar namn, egenskap och mått för en KPI och visar namnet och egenskapen i cellen. En KPI, eller prestandaindikator, är ett kvantifierbart mått, t.ex. månatlig bruttovinst eller personalomsättning per kvartal, som används för att analysera ett företags resultat.
+CUBEMEMBER = KUBMEDLEM ## Returnerar en medlem eller ett par i en kubhierarki. Används för att verifiera att medlemmen eller paret finns i kuben.
+CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP ## Returnerar värdet för en medlemsegenskap i kuben. Används för att verifiera att ett medlemsnamn finns i kuben, samt för att returnera den angivna egenskapen för medlemmen.
+CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM ## Returnerar den n:te, eller rangordnade, medlemmen i en uppsättning. Används för att returnera ett eller flera element i en uppsättning, till exempelvis den bästa försäljaren eller de tio bästa eleverna.
+CUBESET = KUBINSTÄLLNING ## Definierar en beräknad uppsättning medlemmar eller par genom att skicka ett bestämt uttryck till kuben på servern, som skapar uppsättningen och sedan returnerar den till Microsoft Office Excel.
+CUBESETCOUNT = KUBINSTÄLLNINGANTAL ## Returnerar antalet objekt i en uppsättning.
+CUBEVALUE = KUBVÄRDE ## Returnerar ett mängdvärde från en kub.
+
+
+##
+## Database functions Databasfunktioner
+##
+DAVERAGE = DMEDEL ## Returnerar medelvärdet av databasposterna
+DCOUNT = DANTAL ## Räknar antalet celler som innehåller tal i en databas
+DCOUNTA = DANTALV ## Räknar ifyllda celler i en databas
+DGET = DHÄMTA ## Hämtar en enstaka post från en databas som uppfyller de angivna villkoren
+DMAX = DMAX ## Returnerar det största värdet från databasposterna
+DMIN = DMIN ## Returnerar det minsta värdet från databasposterna
+DPRODUCT = DPRODUKT ## Multiplicerar värdena i ett visst fält i poster som uppfyller villkoret
+DSTDEV = DSTDAV ## Uppskattar standardavvikelsen baserat på ett urval av databasposterna
+DSTDEVP = DSTDAVP ## Beräknar standardavvikelsen utifrån hela populationen av valda databasposter
+DSUM = DSUMMA ## Summerar talen i kolumnfält i databasposter som uppfyller villkoret
+DVAR = DVARIANS ## Uppskattar variansen baserat på ett urval av databasposterna
+DVARP = DVARIANSP ## Beräknar variansen utifrån hela populationen av valda databasposter
+
+
+##
+## Date and time functions Tid- och datumfunktioner
+##
+DATE = DATUM ## Returnerar ett serienummer för ett visst datum
+DATEVALUE = DATUMVÄRDE ## Konverterar ett datum i textformat till ett serienummer
+DAY = DAG ## Konverterar ett serienummer till dag i månaden
+DAYS360 = DAGAR360 ## Beräknar antalet dagar mellan två datum baserat på ett 360-dagarsår
+EDATE = EDATUM ## Returnerar serienumret för ett datum som infaller ett visst antal månader före eller efter startdatumet
+EOMONTH = SLUTMÅNAD ## Returnerar serienumret för sista dagen i månaden ett visst antal månader tidigare eller senare
+HOUR = TIMME ## Konverterar ett serienummer till en timme
+MINUTE = MINUT ## Konverterar ett serienummer till en minut
+MONTH = MÅNAD ## Konverterar ett serienummer till en månad
+NETWORKDAYS = NETTOARBETSDAGAR ## Returnerar antalet hela arbetsdagar mellan två datum
+NOW = NU ## Returnerar serienumret för dagens datum och aktuell tid
+SECOND = SEKUND ## Konverterar ett serienummer till en sekund
+TIME = KLOCKSLAG ## Returnerar serienumret för en viss tid
+TIMEVALUE = TIDVÄRDE ## Konverterar en tid i textformat till ett serienummer
+TODAY = IDAG ## Returnerar serienumret för dagens datum
+WEEKDAY = VECKODAG ## Konverterar ett serienummer till en dag i veckan
+WEEKNUM = VECKONR ## Konverterar ett serienummer till ett veckonummer
+WORKDAY = ARBETSDAGAR ## Returnerar serienumret för ett datum ett visst antal arbetsdagar tidigare eller senare
+YEAR = ÅR ## Konverterar ett serienummer till ett år
+YEARFRAC = ÅRDEL ## Returnerar en del av ett år som representerar antalet hela dagar mellan start- och slutdatum
+
+
+##
+## Engineering functions Tekniska funktioner
+##
+BESSELI = BESSELI ## Returnerar den modifierade Bessel-funktionen In(x)
+BESSELJ = BESSELJ ## Returnerar Bessel-funktionen Jn(x)
+BESSELK = BESSELK ## Returnerar den modifierade Bessel-funktionen Kn(x)
+BESSELY = BESSELY ## Returnerar Bessel-funktionen Yn(x)
+BIN2DEC = BIN.TILL.DEC ## Omvandlar ett binärt tal till decimalt
+BIN2HEX = BIN.TILL.HEX ## Omvandlar ett binärt tal till hexadecimalt
+BIN2OCT = BIN.TILL.OKT ## Omvandlar ett binärt tal till oktalt
+COMPLEX = KOMPLEX ## Omvandlar reella och imaginära koefficienter till ett komplext tal
+CONVERT = KONVERTERA ## Omvandlar ett tal från ett måttsystem till ett annat
+DEC2BIN = DEC.TILL.BIN ## Omvandlar ett decimalt tal till binärt
+DEC2HEX = DEC.TILL.HEX ## Omvandlar ett decimalt tal till hexadecimalt
+DEC2OCT = DEC.TILL.OKT ## Omvandlar ett decimalt tal till oktalt
+DELTA = DELTA ## Testar om två värden är lika
+ERF = FELF ## Returnerar felfunktionen
+ERFC = FELFK ## Returnerar den komplementära felfunktionen
+GESTEP = SLSTEG ## Testar om ett tal är större än ett tröskelvärde
+HEX2BIN = HEX.TILL.BIN ## Omvandlar ett hexadecimalt tal till binärt
+HEX2DEC = HEX.TILL.DEC ## Omvandlar ett hexadecimalt tal till decimalt
+HEX2OCT = HEX.TILL.OKT ## Omvandlar ett hexadecimalt tal till oktalt
+IMABS = IMABS ## Returnerar absolutvärdet (modulus) för ett komplext tal
+IMAGINARY = IMAGINÄR ## Returnerar den imaginära koefficienten för ett komplext tal
+IMARGUMENT = IMARGUMENT ## Returnerar det komplexa talets argument, en vinkel uttryckt i radianer
+IMCONJUGATE = IMKONJUGAT ## Returnerar det komplexa talets konjugat
+IMCOS = IMCOS ## Returnerar cosinus för ett komplext tal
+IMDIV = IMDIV ## Returnerar kvoten för två komplexa tal
+IMEXP = IMEUPPHÖJT ## Returnerar exponenten för ett komplext tal
+IMLN = IMLN ## Returnerar den naturliga logaritmen för ett komplext tal
+IMLOG10 = IMLOG10 ## Returnerar 10-logaritmen för ett komplext tal
+IMLOG2 = IMLOG2 ## Returnerar 2-logaritmen för ett komplext tal
+IMPOWER = IMUPPHÖJT ## Returnerar ett komplext tal upphöjt till en exponent
+IMPRODUCT = IMPRODUKT ## Returnerar produkten av komplexa tal
+IMREAL = IMREAL ## Returnerar den reella koefficienten för ett komplext tal
+IMSIN = IMSIN ## Returnerar sinus för ett komplext tal
+IMSQRT = IMROT ## Returnerar kvadratroten av ett komplext tal
+IMSUB = IMDIFF ## Returnerar differensen mellan två komplexa tal
+IMSUM = IMSUM ## Returnerar summan av komplexa tal
+OCT2BIN = OKT.TILL.BIN ## Omvandlar ett oktalt tal till binärt
+OCT2DEC = OKT.TILL.DEC ## Omvandlar ett oktalt tal till decimalt
+OCT2HEX = OKT.TILL.HEX ## Omvandlar ett oktalt tal till hexadecimalt
+
+
+##
+## Financial functions Finansiella funktioner
+##
+ACCRINT = UPPLRÄNTA ## Returnerar den upplupna räntan för värdepapper med periodisk ränta
+ACCRINTM = UPPLOBLRÄNTA ## Returnerar den upplupna räntan för ett värdepapper som ger avkastning på förfallodagen
+AMORDEGRC = AMORDEGRC ## Returnerar avskrivningen för varje redovisningsperiod med hjälp av en avskrivningskoefficient
+AMORLINC = AMORLINC ## Returnerar avskrivningen för varje redovisningsperiod
+COUPDAYBS = KUPDAGBB ## Returnerar antal dagar från början av kupongperioden till likviddagen
+COUPDAYS = KUPDAGARS ## Returnerar antalet dagar i kupongperioden som innehåller betalningsdatumet
+COUPDAYSNC = KUPDAGNK ## Returnerar antalet dagar från betalningsdatumet till nästa kupongdatum
+COUPNCD = KUPNKD ## Returnerar nästa kupongdatum efter likviddagen
+COUPNUM = KUPANT ## Returnerar kuponger som förfaller till betalning mellan likviddagen och förfallodagen
+COUPPCD = KUPFKD ## Returnerar föregående kupongdatum före likviddagen
+CUMIPMT = KUMRÄNTA ## Returnerar den ackumulerade räntan som betalats mellan två perioder
+CUMPRINC = KUMPRIS ## Returnerar det ackumulerade kapitalbeloppet som betalats på ett lån mellan två perioder
+DB = DB ## Returnerar avskrivningen för en tillgång under en angiven tid enligt metoden för fast degressiv avskrivning
+DDB = DEGAVSKR ## Returnerar en tillgångs värdeminskning under en viss period med hjälp av dubbel degressiv avskrivning eller någon annan metod som du anger
+DISC = DISK ## Returnerar diskonteringsräntan för ett värdepapper
+DOLLARDE = DECTAL ## Omvandlar ett pris uttryckt som ett bråk till ett decimaltal
+DOLLARFR = BRÅK ## Omvandlar ett pris i kronor uttryckt som ett decimaltal till ett bråk
+DURATION = LÖPTID ## Returnerar den årliga löptiden för en säkerhet med periodiska räntebetalningar
+EFFECT = EFFRÄNTA ## Returnerar den årliga effektiva räntesatsen
+FV = SLUTVÄRDE ## Returnerar det framtida värdet på en investering
+FVSCHEDULE = FÖRRÄNTNING ## Returnerar det framtida värdet av ett begynnelsekapital beräknat på olika räntenivåer
+INTRATE = ÅRSRÄNTA ## Returnerar räntesatsen för ett betalt värdepapper
+IPMT = RBETALNING ## Returnerar räntedelen av en betalning för en given period
+IRR = IR ## Returnerar internräntan för en serie betalningar
+ISPMT = RALÅN ## Beräknar räntan som har betalats under en specifik betalningsperiod
+MDURATION = MLÖPTID ## Returnerar den modifierade Macauley-löptiden för ett värdepapper med det antagna nominella värdet 100 kr
+MIRR = MODIR ## Returnerar internräntan där positiva och negativa betalningar finansieras med olika räntor
+NOMINAL = NOMRÄNTA ## Returnerar den årliga nominella räntesatsen
+NPER = PERIODER ## Returnerar antalet perioder för en investering
+NPV = NETNUVÄRDE ## Returnerar nuvärdet av en serie periodiska betalningar vid en given diskonteringsränta
+ODDFPRICE = UDDAFPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda första period
+ODDFYIELD = UDDAFAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda första period
+ODDLPRICE = UDDASPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda sista period
+ODDLYIELD = UDDASAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda sista period
+PMT = BETALNING ## Returnerar den periodiska betalningen för en annuitet
+PPMT = AMORT ## Returnerar amorteringsdelen av en annuitetsbetalning för en given period
+PRICE = PRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger periodisk ränta
+PRICEDISC = PRISDISK ## Returnerar priset per 100 kr nominellt värde för ett diskonterat värdepapper
+PRICEMAT = PRISFÖRF ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger ränta på förfallodagen
+PV = PV ## Returnerar nuvärdet av en serie lika stora periodiska betalningar
+RATE = RÄNTA ## Returnerar räntesatsen per period i en annuitet
+RECEIVED = BELOPP ## Returnerar beloppet som utdelas på förfallodagen för ett betalat värdepapper
+SLN = LINAVSKR ## Returnerar den linjära avskrivningen för en tillgång under en period
+SYD = ÅRSAVSKR ## Returnerar den årliga avskrivningssumman för en tillgång under en angiven period
+TBILLEQ = SSVXEKV ## Returnerar avkastningen motsvarande en obligation för en statsskuldväxel
+TBILLPRICE = SSVXPRIS ## Returnerar priset per 100 kr nominellt värde för en statsskuldväxel
+TBILLYIELD = SSVXRÄNTA ## Returnerar avkastningen för en statsskuldväxel
+VDB = VDEGRAVSKR ## Returnerar avskrivningen för en tillgång under en angiven period (med degressiv avskrivning)
+XIRR = XIRR ## Returnerar internräntan för en serie betalningar som inte nödvändigtvis är periodiska
+XNPV = XNUVÄRDE ## Returnerar det nuvarande nettovärdet för en serie betalningar som inte nödvändigtvis är periodiska
+YIELD = NOMAVK ## Returnerar avkastningen för ett värdepapper som ger periodisk ränta
+YIELDDISC = NOMAVKDISK ## Returnerar den årliga avkastningen för diskonterade värdepapper, exempelvis en statsskuldväxel
+YIELDMAT = NOMAVKFÖRF ## Returnerar den årliga avkastningen för ett värdepapper som ger ränta på förfallodagen
+
+
+##
+## Information functions Informationsfunktioner
+##
+CELL = CELL ## Returnerar information om formatering, plats och innehåll i en cell
+ERROR.TYPE = FEL.TYP ## Returnerar ett tal som motsvarar ett felvärde
+INFO = INFO ## Returnerar information om operativsystemet
+ISBLANK = ÄRREF ## Returnerar SANT om värdet är tomt
+ISERR = Ä ## Returnerar SANT om värdet är ett felvärde annat än #SAKNAS!
+ISERROR = ÄRFEL ## Returnerar SANT om värdet är ett felvärde
+ISEVEN = ÄRJÄMN ## Returnerar SANT om talet är jämnt
+ISLOGICAL = ÄREJTEXT ## Returnerar SANT om värdet är ett logiskt värde
+ISNA = ÄRLOGISK ## Returnerar SANT om värdet är felvärdet #SAKNAS!
+ISNONTEXT = ÄRSAKNAD ## Returnerar SANT om värdet inte är text
+ISNUMBER = ÄRTAL ## Returnerar SANT om värdet är ett tal
+ISODD = ÄRUDDA ## Returnerar SANT om talet är udda
+ISREF = ÄRTOM ## Returnerar SANT om värdet är en referens
+ISTEXT = ÄRTEXT ## Returnerar SANT om värdet är text
+N = N ## Returnerar ett värde omvandlat till ett tal
+NA = SAKNAS ## Returnerar felvärdet #SAKNAS!
+TYPE = VÄRDETYP ## Returnerar ett tal som anger värdets datatyp
+
+
+##
+## Logical functions Logiska funktioner
+##
+AND = OCH ## Returnerar SANT om alla argument är sanna
+FALSE = FALSKT ## Returnerar det logiska värdet FALSKT
+IF = OM ## Anger vilket logiskt test som ska utföras
+IFERROR = OMFEL ## Returnerar ett värde som du anger om en formel utvärderar till ett fel; annars returneras resultatet av formeln
+NOT = ICKE ## Inverterar logiken för argumenten
+OR = ELLER ## Returnerar SANT om något argument är SANT
+TRUE = SANT ## Returnerar det logiska värdet SANT
+
+
+##
+## Lookup and reference functions Sök- och referensfunktioner
+##
+ADDRESS = ADRESS ## Returnerar en referens som text till en enstaka cell i ett kalkylblad
+AREAS = OMRÅDEN ## Returnerar antalet områden i en referens
+CHOOSE = VÄLJ ## Väljer ett värde i en lista över värden
+COLUMN = KOLUMN ## Returnerar kolumnnumret för en referens
+COLUMNS = KOLUMNER ## Returnerar antalet kolumner i en referens
+HLOOKUP = LETAKOLUMN ## Söker i den översta raden i en matris och returnerar värdet för angiven cell
+HYPERLINK = HYPERLÄNK ## Skapar en genväg eller ett hopp till ett dokument i nätverket, i ett intranät eller på Internet
+INDEX = INDEX ## Använder ett index för ett välja ett värde i en referens eller matris
+INDIRECT = INDIREKT ## Returnerar en referens som anges av ett textvärde
+LOOKUP = LETAUPP ## Letar upp värden i en vektor eller matris
+MATCH = PASSA ## Letar upp värden i en referens eller matris
+OFFSET = FÖRSKJUTNING ## Returnerar en referens förskjuten i förhållande till en given referens
+ROW = RAD ## Returnerar radnumret för en referens
+ROWS = RADER ## Returnerar antalet rader i en referens
+RTD = RTD ## Hämtar realtidsdata från ett program som stöder COM-automation (Automation: Ett sätt att arbeta med ett programs objekt från ett annat program eller utvecklingsverktyg. Detta kallades tidigare för OLE Automation, och är en branschstandard och ingår i Component Object Model (COM).)
+TRANSPOSE = TRANSPONERA ## Transponerar en matris
+VLOOKUP = LETARAD ## Letar i den första kolumnen i en matris och flyttar över raden för att returnera värdet för en cell
+
+
+##
+## Math and trigonometry functions Matematiska och trigonometriska funktioner
+##
+ABS = ABS ## Returnerar absolutvärdet av ett tal
+ACOS = ARCCOS ## Returnerar arcus cosinus för ett tal
+ACOSH = ARCCOSH ## Returnerar inverterad hyperbolisk cosinus för ett tal
+ASIN = ARCSIN ## Returnerar arcus cosinus för ett tal
+ASINH = ARCSINH ## Returnerar hyperbolisk arcus sinus för ett tal
+ATAN = ARCTAN ## Returnerar arcus tangens för ett tal
+ATAN2 = ARCTAN2 ## Returnerar arcus tangens för en x- och en y- koordinat
+ATANH = ARCTANH ## Returnerar hyperbolisk arcus tangens för ett tal
+CEILING = RUNDA.UPP ## Avrundar ett tal till närmaste heltal eller närmaste signifikanta multipel
+COMBIN = KOMBIN ## Returnerar antalet kombinationer för ett givet antal objekt
+COS = COS ## Returnerar cosinus för ett tal
+COSH = COSH ## Returnerar hyperboliskt cosinus för ett tal
+DEGREES = GRADER ## Omvandlar radianer till grader
+EVEN = JÄMN ## Avrundar ett tal uppåt till närmaste heltal
+EXP = EXP ## Returnerar e upphöjt till ett givet tal
+FACT = FAKULTET ## Returnerar fakulteten för ett tal
+FACTDOUBLE = DUBBELFAKULTET ## Returnerar dubbelfakulteten för ett tal
+FLOOR = RUNDA.NED ## Avrundar ett tal nedåt mot noll
+GCD = SGD ## Returnerar den största gemensamma nämnaren
+INT = HELTAL ## Avrundar ett tal nedåt till närmaste heltal
+LCM = MGM ## Returnerar den minsta gemensamma multipeln
+LN = LN ## Returnerar den naturliga logaritmen för ett tal
+LOG = LOG ## Returnerar logaritmen för ett tal för en given bas
+LOG10 = LOG10 ## Returnerar 10-logaritmen för ett tal
+MDETERM = MDETERM ## Returnerar matrisen som är avgörandet av en matris
+MINVERSE = MINVERT ## Returnerar matrisinversen av en matris
+MMULT = MMULT ## Returnerar matrisprodukten av två matriser
+MOD = REST ## Returnerar resten vid en division
+MROUND = MAVRUNDA ## Returnerar ett tal avrundat till en given multipel
+MULTINOMIAL = MULTINOMIAL ## Returnerar multinomialen för en uppsättning tal
+ODD = UDDA ## Avrundar ett tal uppåt till närmaste udda heltal
+PI = PI ## Returnerar värdet pi
+POWER = UPPHÖJT.TILL ## Returnerar resultatet av ett tal upphöjt till en exponent
+PRODUCT = PRODUKT ## Multiplicerar argumenten
+QUOTIENT = KVOT ## Returnerar heltalsdelen av en division
+RADIANS = RADIANER ## Omvandlar grader till radianer
+RAND = SLUMP ## Returnerar ett slumptal mellan 0 och 1
+RANDBETWEEN = SLUMP.MELLAN ## Returnerar ett slumptal mellan de tal som du anger
+ROMAN = ROMERSK ## Omvandlar vanliga (arabiska) siffror till romerska som text
+ROUND = AVRUNDA ## Avrundar ett tal till ett angivet antal siffror
+ROUNDDOWN = AVRUNDA.NEDÅT ## Avrundar ett tal nedåt mot noll
+ROUNDUP = AVRUNDA.UPPÅT ## Avrundar ett tal uppåt, från noll
+SERIESSUM = SERIESUMMA ## Returnerar summan av en potensserie baserat på formeln
+SIGN = TECKEN ## Returnerar tecknet för ett tal
+SIN = SIN ## Returnerar sinus för en given vinkel
+SINH = SINH ## Returnerar hyperbolisk sinus för ett tal
+SQRT = ROT ## Returnerar den positiva kvadratroten
+SQRTPI = ROTPI ## Returnerar kvadratroten för (tal * pi)
+SUBTOTAL = DELSUMMA ## Returnerar en delsumma i en lista eller databas
+SUM = SUMMA ## Summerar argumenten
+SUMIF = SUMMA.OM ## Summerar celler enligt ett angivet villkor
+SUMIFS = SUMMA.OMF ## Lägger till cellerna i ett område som uppfyller flera kriterier
+SUMPRODUCT = PRODUKTSUMMA ## Returnerar summan av produkterna i motsvarande matriskomponenter
+SUMSQ = KVADRATSUMMA ## Returnerar summan av argumentens kvadrater
+SUMX2MY2 = SUMMAX2MY2 ## Returnerar summan av differensen mellan kvadraterna för motsvarande värden i två matriser
+SUMX2PY2 = SUMMAX2PY2 ## Returnerar summan av summan av kvadraterna av motsvarande värden i två matriser
+SUMXMY2 = SUMMAXMY2 ## Returnerar summan av kvadraten av skillnaden mellan motsvarande värden i två matriser
+TAN = TAN ## Returnerar tangens för ett tal
+TANH = TANH ## Returnerar hyperbolisk tangens för ett tal
+TRUNC = AVKORTA ## Avkortar ett tal till ett heltal
+
+
+##
+## Statistical functions Statistiska funktioner
+##
+AVEDEV = MEDELAVV ## Returnerar medelvärdet för datapunkters absoluta avvikelse från deras medelvärde
+AVERAGE = MEDEL ## Returnerar medelvärdet av argumenten
+AVERAGEA = AVERAGEA ## Returnerar medelvärdet av argumenten, inklusive tal, text och logiska värden
+AVERAGEIF = MEDELOM ## Returnerar medelvärdet (aritmetiskt medelvärde) för alla celler i ett område som uppfyller ett givet kriterium
+AVERAGEIFS = MEDELOMF ## Returnerar medelvärdet (det aritmetiska medelvärdet) för alla celler som uppfyller flera villkor.
+BETADIST = BETAFÖRD ## Returnerar den kumulativa betafördelningsfunktionen
+BETAINV = BETAINV ## Returnerar inversen till den kumulativa fördelningsfunktionen för en viss betafördelning
+BINOMDIST = BINOMFÖRD ## Returnerar den individuella binomialfördelningen
+CHIDIST = CHI2FÖRD ## Returnerar den ensidiga sannolikheten av c2-fördelningen
+CHIINV = CHI2INV ## Returnerar inversen av chi2-fördelningen
+CHITEST = CHI2TEST ## Returnerar oberoendetesten
+CONFIDENCE = KONFIDENS ## Returnerar konfidensintervallet för en populations medelvärde
+CORREL = KORREL ## Returnerar korrelationskoefficienten mellan två datamängder
+COUNT = ANTAL ## Räknar hur många tal som finns bland argumenten
+COUNTA = ANTALV ## Räknar hur många värden som finns bland argumenten
+COUNTBLANK = ANTAL.TOMMA ## Räknar antalet tomma celler i ett område
+COUNTIF = ANTAL.OM ## Räknar antalet celler i ett område som uppfyller angivna villkor.
+COUNTIFS = ANTAL.OMF ## Räknar antalet celler i ett område som uppfyller flera villkor.
+COVAR = KOVAR ## Returnerar kovariansen, d.v.s. medelvärdet av produkterna för parade avvikelser
+CRITBINOM = KRITBINOM ## Returnerar det minsta värdet för vilket den kumulativa binomialfördelningen är mindre än eller lika med ett villkorsvärde
+DEVSQ = KVADAVV ## Returnerar summan av kvadrater på avvikelser
+EXPONDIST = EXPONFÖRD ## Returnerar exponentialfördelningen
+FDIST = FFÖRD ## Returnerar F-sannolikhetsfördelningen
+FINV = FINV ## Returnerar inversen till F-sannolikhetsfördelningen
+FISHER = FISHER ## Returnerar Fisher-transformationen
+FISHERINV = FISHERINV ## Returnerar inversen till Fisher-transformationen
+FORECAST = PREDIKTION ## Returnerar ett värde längs en linjär trendlinje
+FREQUENCY = FREKVENS ## Returnerar en frekvensfördelning som en lodrät matris
+FTEST = FTEST ## Returnerar resultatet av en F-test
+GAMMADIST = GAMMAFÖRD ## Returnerar gammafördelningen
+GAMMAINV = GAMMAINV ## Returnerar inversen till den kumulativa gammafördelningen
+GAMMALN = GAMMALN ## Returnerar den naturliga logaritmen för gammafunktionen, G(x)
+GEOMEAN = GEOMEDEL ## Returnerar det geometriska medelvärdet
+GROWTH = EXPTREND ## Returnerar värden längs en exponentiell trend
+HARMEAN = HARMMEDEL ## Returnerar det harmoniska medelvärdet
+HYPGEOMDIST = HYPGEOMFÖRD ## Returnerar den hypergeometriska fördelningen
+INTERCEPT = SKÄRNINGSPUNKT ## Returnerar skärningspunkten för en linjär regressionslinje
+KURT = TOPPIGHET ## Returnerar toppigheten av en mängd data
+LARGE = STÖRSTA ## Returnerar det n:te största värdet i en mängd data
+LINEST = REGR ## Returnerar parametrar till en linjär trendlinje
+LOGEST = EXPREGR ## Returnerar parametrarna i en exponentiell trend
+LOGINV = LOGINV ## Returnerar inversen till den lognormala fördelningen
+LOGNORMDIST = LOGNORMFÖRD ## Returnerar den kumulativa lognormala fördelningen
+MAX = MAX ## Returnerar det största värdet i en lista av argument
+MAXA = MAXA ## Returnerar det största värdet i en lista av argument, inklusive tal, text och logiska värden
+MEDIAN = MEDIAN ## Returnerar medianen för angivna tal
+MIN = MIN ## Returnerar det minsta värdet i en lista med argument
+MINA = MINA ## Returnerar det minsta värdet i en lista över argument, inklusive tal, text och logiska värden
+MODE = TYPVÄRDE ## Returnerar det vanligaste värdet i en datamängd
+NEGBINOMDIST = NEGBINOMFÖRD ## Returnerar den negativa binomialfördelningen
+NORMDIST = NORMFÖRD ## Returnerar den kumulativa normalfördelningen
+NORMINV = NORMINV ## Returnerar inversen till den kumulativa normalfördelningen
+NORMSDIST = NORMSFÖRD ## Returnerar den kumulativa standardnormalfördelningen
+NORMSINV = NORMSINV ## Returnerar inversen till den kumulativa standardnormalfördelningen
+PEARSON = PEARSON ## Returnerar korrelationskoefficienten till Pearsons momentprodukt
+PERCENTILE = PERCENTIL ## Returnerar den n:te percentilen av värden i ett område
+PERCENTRANK = PROCENTRANG ## Returnerar procentrangen för ett värde i en datamängd
+PERMUT = PERMUT ## Returnerar antal permutationer för ett givet antal objekt
+POISSON = POISSON ## Returnerar Poisson-fördelningen
+PROB = SANNOLIKHET ## Returnerar sannolikheten att värden i ett område ligger mellan två gränser
+QUARTILE = KVARTIL ## Returnerar kvartilen av en mängd data
+RANK = RANG ## Returnerar rangordningen för ett tal i en lista med tal
+RSQ = RKV ## Returnerar kvadraten av Pearsons produktmomentkorrelationskoefficient
+SKEW = SNEDHET ## Returnerar snedheten för en fördelning
+SLOPE = LUTNING ## Returnerar lutningen på en linjär regressionslinje
+SMALL = MINSTA ## Returnerar det n:te minsta värdet i en mängd data
+STANDARDIZE = STANDARDISERA ## Returnerar ett normaliserat värde
+STDEV = STDAV ## Uppskattar standardavvikelsen baserat på ett urval
+STDEVA = STDEVA ## Uppskattar standardavvikelsen baserat på ett urval, inklusive tal, text och logiska värden
+STDEVP = STDAVP ## Beräknar standardavvikelsen baserat på hela populationen
+STDEVPA = STDEVPA ## Beräknar standardavvikelsen baserat på hela populationen, inklusive tal, text och logiska värden
+STEYX = STDFELYX ## Returnerar standardfelet för ett förutspått y-värde för varje x-värde i regressionen
+TDIST = TFÖRD ## Returnerar Students t-fördelning
+TINV = TINV ## Returnerar inversen till Students t-fördelning
+TREND = TREND ## Returnerar värden längs en linjär trend
+TRIMMEAN = TRIMMEDEL ## Returnerar medelvärdet av mittpunkterna i en datamängd
+TTEST = TTEST ## Returnerar sannolikheten beräknad ur Students t-test
+VAR = VARIANS ## Uppskattar variansen baserat på ett urval
+VARA = VARA ## Uppskattar variansen baserat på ett urval, inklusive tal, text och logiska värden
+VARP = VARIANSP ## Beräknar variansen baserat på hela populationen
+VARPA = VARPA ## Beräknar variansen baserat på hela populationen, inklusive tal, text och logiska värden
+WEIBULL = WEIBULL ## Returnerar Weibull-fördelningen
+ZTEST = ZTEST ## Returnerar det ensidiga sannolikhetsvärdet av ett z-test
+
+
+##
+## Text functions Textfunktioner
+##
+ASC = ASC ## Ändrar helbredds (dubbel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med halvt breddsteg (enkel byte)
+BAHTTEXT = BAHTTEXT ## Omvandlar ett tal till text med valutaformatet ß (baht)
+CHAR = TECKENKOD ## Returnerar tecknet som anges av kod
+CLEAN = STÄDA ## Tar bort alla icke utskrivbara tecken i en text
+CODE = KOD ## Returnerar en numerisk kod för det första tecknet i en textsträng
+CONCATENATE = SAMMANFOGA ## Sammanfogar flera textdelar till en textsträng
+DOLLAR = VALUTA ## Omvandlar ett tal till text med valutaformat
+EXACT = EXAKT ## Kontrollerar om två textvärden är identiska
+FIND = HITTA ## Hittar en text i en annan (skiljer på gemener och versaler)
+FINDB = HITTAB ## Hittar en text i en annan (skiljer på gemener och versaler)
+FIXED = FASTTAL ## Formaterar ett tal som text med ett fast antal decimaler
+JIS = JIS ## Ändrar halvbredds (enkel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med helt breddsteg (dubbel byte)
+LEFT = VÄNSTER ## Returnerar tecken längst till vänster i en sträng
+LEFTB = VÄNSTERB ## Returnerar tecken längst till vänster i en sträng
+LEN = LÄNGD ## Returnerar antalet tecken i en textsträng
+LENB = LÄNGDB ## Returnerar antalet tecken i en textsträng
+LOWER = GEMENER ## Omvandlar text till gemener
+MID = EXTEXT ## Returnerar angivet antal tecken från en text med början vid den position som du anger
+MIDB = EXTEXTB ## Returnerar angivet antal tecken från en text med början vid den position som du anger
+PHONETIC = PHONETIC ## Returnerar de fonetiska (furigana) tecknen i en textsträng
+PROPER = INITIAL ## Ändrar första bokstaven i varje ord i ett textvärde till versal
+REPLACE = ERSÄTT ## Ersätter tecken i text
+REPLACEB = ERSÄTTB ## Ersätter tecken i text
+REPT = REP ## Upprepar en text ett bestämt antal gånger
+RIGHT = HÖGER ## Returnerar tecken längst till höger i en sträng
+RIGHTB = HÖGERB ## Returnerar tecken längst till höger i en sträng
+SEARCH = SÖK ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler)
+SEARCHB = SÖKB ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler)
+SUBSTITUTE = BYT.UT ## Ersätter gammal text med ny text i en textsträng
+T = T ## Omvandlar argumenten till text
+TEXT = TEXT ## Formaterar ett tal och omvandlar det till text
+TRIM = RENSA ## Tar bort blanksteg från text
+UPPER = VERSALER ## Omvandlar text till versaler
+VALUE = TEXTNUM ## Omvandlar ett textargument till ett tal
diff --git a/PHPExcel/locale/tr/config b/PHPExcel/locale/tr/config
new file mode 100644
index 0000000..de69cf5
--- /dev/null
+++ b/PHPExcel/locale/tr/config
@@ -0,0 +1,47 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Settings
+## @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 1.8.0, 2014-03-02
+##
+##
+
+
+ArgumentSeparator = ;
+
+
+##
+## (For future use)
+##
+currencySymbol = YTL
+
+
+##
+## Excel Error Codes (For future use)
+##
+NULL = #BOŞ!
+DIV0 = #SAYI/0!
+VALUE = #DEĞER!
+REF = #BAŞV!
+NAME = #AD?
+NUM = #SAYI!
+NA = #YOK
diff --git a/PHPExcel/locale/tr/functions b/PHPExcel/locale/tr/functions
new file mode 100644
index 0000000..c327bca
--- /dev/null
+++ b/PHPExcel/locale/tr/functions
@@ -0,0 +1,438 @@
+##
+## PHPExcel
+##
+## Copyright (c) 2006 - 2013 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_Calculation
+## @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 1.8.0, 2014-03-02
+##
+## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/
+##
+##
+
+
+##
+## Add-in and Automation functions Eklenti ve Otomasyon fonksiyonları
+##
+GETPIVOTDATA = ÖZETVERİAL ## Bir Özet Tablo raporunda saklanan verileri verir.
+
+
+##
+## Cube functions Küp işlevleri
+##
+CUBEKPIMEMBER = KÜPKPIÜYE ## Kilit performans göstergesi (KPI-Key Performance Indicator) adını, özelliğini ve ölçüsünü verir ve hücredeki ad ve özelliği gösterir. KPI, bir kurumun performansını izlemek için kullanılan aylık brüt kâr ya da üç aylık çalışan giriş çıkışları gibi ölçülebilen bir birimdir.
+CUBEMEMBER = KÜPÜYE ## Bir küp hiyerarşisinde bir üyeyi veya kaydı verir. Üye veya kaydın küpte varolduğunu doğrulamak için kullanılır.
+CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ ## Bir küpte bir üyenin özelliğinin değerini verir. Küp içinde üye adının varlığını doğrulamak ve bu üyenin belli özelliklerini getirmek için kullanılır.
+CUBERANKEDMEMBER = KÜPÜYESIRASI ## Bir küme içindeki üyenin derecesini veya kaçıncı olduğunu verir. En iyi satış elemanı, veya en iyi on öğrenci gibi bir kümedeki bir veya daha fazla öğeyi getirmek için kullanılır.
+CUBESET = KÜPKÜME ## Kümeyi oluşturan ve ardından bu kümeyi Microsoft Office Excel'e getiren sunucudaki küpe küme ifadelerini göndererek hesaplanan üye veya kayıt kümesini tanımlar.
+CUBESETCOUNT = KÜPKÜMESAY ## Bir kümedeki öğelerin sayısını getirir.
+CUBEVALUE = KÜPDEĞER ## Bir küpten toplam değeri getirir.
+
+
+##
+## Database functions Veritabanı işlevleri
+##
+DAVERAGE = VSEÇORT ## Seçili veritabanı girdilerinin ortalamasını verir.
+DCOUNT = VSEÇSAY ## Veritabanında sayı içeren hücre sayısını hesaplar.
+DCOUNTA = VSEÇSAYDOLU ## Veritabanındaki boş olmayan hücreleri sayar.
+DGET = VAL ## Veritabanından, belirtilen ölçütlerle eşleşen tek bir rapor çıkarır.
+DMAX = VSEÇMAK ## Seçili veritabanı girişlerinin en yüksek değerini verir.
+DMIN = VSEÇMİN ## Seçili veritabanı girişlerinin en düşük değerini verir.
+DPRODUCT = VSEÇÇARP ## Kayıtların belli bir alanında bulunan, bir veritabanındaki ölçütlerle eşleşen değerleri çarpar.
+DSTDEV = VSEÇSTDSAPMA ## Seçili veritabanı girişlerinden oluşan bir örneğe dayanarak, standart sapmayı tahmin eder.
+DSTDEVP = VSEÇSTDSAPMAS ## Standart sapmayı, seçili veritabanı girişlerinin tüm popülasyonunu esas alarak hesaplar.
+DSUM = VSEÇTOPLA ## Kayıtların alan sütununda bulunan, ölçütle eşleşen sayıları toplar.
+DVAR = VSEÇVAR ## Seçili veritabanı girişlerinden oluşan bir örneği esas alarak farkı tahmin eder.
+DVARP = VSEÇVARS ## Seçili veritabanı girişlerinin tüm popülasyonunu esas alarak farkı hesaplar.
+
+
+##
+## Date and time functions Tarih ve saat işlevleri
+##
+DATE = TARİH ## Belirli bir tarihin seri numarasını verir.
+DATEVALUE = TARİHSAYISI ## Metin biçimindeki bir tarihi seri numarasına dönüştürür.
+DAY = GÜN ## Seri numarasını, ayın bir gününe dönüştürür.
+DAYS360 = GÜN360 ## İki tarih arasındaki gün sayısını, 360 günlük yılı esas alarak hesaplar.
+EDATE = SERİTARİH ## Başlangıç tarihinden itibaren, belirtilen ay sayısından önce veya sonraki tarihin seri numarasını verir.
+EOMONTH = SERİAY ## Belirtilen sayıda ay önce veya sonraki ayın son gününün seri numarasını verir.
+HOUR = SAAT ## Bir seri numarasını saate dönüştürür.
+MINUTE = DAKİKA ## Bir seri numarasını dakikaya dönüştürür.
+MONTH = AY ## Bir seri numarasını aya dönüştürür.
+NETWORKDAYS = TAMİŞGÜNÜ ## İki tarih arasındaki tam çalışma günlerinin sayısını verir.
+NOW = ŞİMDİ ## Geçerli tarihin ve saatin seri numarasını verir.
+SECOND = SANİYE ## Bir seri numarasını saniyeye dönüştürür.
+TIME = ZAMAN ## Belirli bir zamanın seri numarasını verir.
+TIMEVALUE = ZAMANSAYISI ## Metin biçimindeki zamanı seri numarasına dönüştürür.
+TODAY = BUGÜN ## Bugünün tarihini seri numarasına dönüştürür.
+WEEKDAY = HAFTANINGÜNÜ ## Bir seri numarasını, haftanın gününe dönüştürür.
+WEEKNUM = HAFTASAY ## Dizisel değerini, haftanın yıl içinde bulunduğu konumu sayısal olarak gösteren sayıya dönüştürür.
+WORKDAY = İŞGÜNÜ ## Belirtilen sayıda çalışma günü öncesinin ya da sonrasının tarihinin seri numarasını verir.
+YEAR = YIL ## Bir seri numarasını yıla dönüştürür.
+YEARFRAC = YILORAN ## Başlangıç_tarihi ve bitiş_tarihi arasındaki tam günleri gösteren yıl kesrini verir.
+
+
+##
+## Engineering functions Mühendislik işlevleri
+##
+BESSELI = BESSELI ## Değiştirilmiş Bessel fonksiyonu In(x)'i verir.
+BESSELJ = BESSELJ ## Bessel fonksiyonu Jn(x)'i verir.
+BESSELK = BESSELK ## Değiştirilmiş Bessel fonksiyonu Kn(x)'i verir.
+BESSELY = BESSELY ## Bessel fonksiyonu Yn(x)'i verir.
+BIN2DEC = BIN2DEC ## İkili bir sayıyı, ondalık sayıya dönüştürür.
+BIN2HEX = BIN2HEX ## İkili bir sayıyı, onaltılıya dönüştürür.
+BIN2OCT = BIN2OCT ## İkili bir sayıyı, sekizliye dönüştürür.
+COMPLEX = KARMAŞIK ## Gerçek ve sanal katsayıları, karmaşık sayıya dönüştürür.
+CONVERT = ÇEVİR ## Bir sayıyı, bir ölçüm sisteminden bir başka ölçüm sistemine dönüştürür.
+DEC2BIN = DEC2BIN ## Ondalık bir sayıyı, ikiliye dönüştürür.
+DEC2HEX = DEC2HEX ## Ondalık bir sayıyı, onaltılıya dönüştürür.
+DEC2OCT = DEC2OCT ## Ondalık bir sayıyı sekizliğe dönüştürür.
+DELTA = DELTA ## İki değerin eşit olup olmadığını sınar.
+ERF = HATAİŞLEV ## Hata işlevini verir.
+ERFC = TÜMHATAİŞLEV ## Tümleyici hata işlevini verir.
+GESTEP = BESINIR ## Bir sayının eşik değerinden büyük olup olmadığını sınar.
+HEX2BIN = HEX2BIN ## Onaltılı bir sayıyı ikiliye dönüştürür.
+HEX2DEC = HEX2DEC ## Onaltılı bir sayıyı ondalığa dönüştürür.
+HEX2OCT = HEX2OCT ## Onaltılı bir sayıyı sekizliğe dönüştürür.
+IMABS = SANMUTLAK ## Karmaşık bir sayının mutlak değerini (modül) verir.
+IMAGINARY = SANAL ## Karmaşık bir sayının sanal katsayısını verir.
+IMARGUMENT = SANBAĞ_DEĞİŞKEN ## Radyanlarla belirtilen bir açı olan teta bağımsız değişkenini verir.
+IMCONJUGATE = SANEŞLENEK ## Karmaşık bir sayının karmaşık eşleniğini verir.
+IMCOS = SANCOS ## Karmaşık bir sayının kosinüsünü verir.
+IMDIV = SANBÖL ## İki karmaşık sayının bölümünü verir.
+IMEXP = SANÜS ## Karmaşık bir sayının üssünü verir.
+IMLN = SANLN ## Karmaşık bir sayının doğal logaritmasını verir.
+IMLOG10 = SANLOG10 ## Karmaşık bir sayının, 10 tabanında logaritmasını verir.
+IMLOG2 = SANLOG2 ## Karmaşık bir sayının 2 tabanında logaritmasını verir.
+IMPOWER = SANÜSSÜ ## Karmaşık bir sayıyı, bir tamsayı üssüne yükseltilmiş olarak verir.
+IMPRODUCT = SANÇARP ## Karmaşık sayıların çarpımını verir.
+IMREAL = SANGERÇEK ## Karmaşık bir sayının, gerçek katsayısını verir.
+IMSIN = SANSIN ## Karmaşık bir sayının sinüsünü verir.
+IMSQRT = SANKAREKÖK ## Karmaşık bir sayının karekökünü verir.
+IMSUB = SANÇIKAR ## İki karmaşık sayının farkını verir.
+IMSUM = SANTOPLA ## Karmaşık sayıların toplamını verir.
+OCT2BIN = OCT2BIN ## Sekizli bir sayıyı ikiliye dönüştürür.
+OCT2DEC = OCT2DEC ## Sekizli bir sayıyı ondalığa dönüştürür.
+OCT2HEX = OCT2HEX ## Sekizli bir sayıyı onaltılıya dönüştürür.
+
+
+##
+## Financial functions Finansal fonksiyonlar
+##
+ACCRINT = GERÇEKFAİZ ## Dönemsel faiz ödeyen hisse senedine ilişkin tahakkuk eden faizi getirir.
+ACCRINTM = GERÇEKFAİZV ## Vadesinde ödeme yapan bir tahvilin tahakkuk etmiş faizini verir.
+AMORDEGRC = AMORDEGRC ## Yıpranma katsayısı kullanarak her hesap döneminin değer kaybını verir.
+AMORLINC = AMORLINC ## Her hesap dönemi içindeki yıpranmayı verir.
+COUPDAYBS = KUPONGÜNBD ## Kupon süresinin başlangıcından alış tarihine kadar olan süredeki gün sayısını verir.
+COUPDAYS = KUPONGÜN ## Kupon süresindeki, gün sayısını, alış tarihini de içermek üzere, verir.
+COUPDAYSNC = KUPONGÜNDSK ## Alış tarihinden bir sonraki kupon tarihine kadar olan gün sayısını verir.
+COUPNCD = KUPONGÜNSKT ## Alış tarihinden bir sonraki kupon tarihini verir.
+COUPNUM = KUPONSAYI ## Alış tarihiyle vade tarihi arasında ödenecek kuponların sayısını verir.
+COUPPCD = KUPONGÜNÖKT ## Alış tarihinden bir önceki kupon tarihini verir.
+CUMIPMT = AİÇVERİMORANI ## İki dönem arasında ödenen kümülatif faizi verir.
+CUMPRINC = ANA_PARA_ÖDEMESİ ## İki dönem arasında bir borç üzerine ödenen birikimli temeli verir.
+DB = AZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, sabit azalan bakiye yöntemini kullanarak verir.
+DDB = ÇİFTAZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, çift azalan bakiye yöntemi ya da sizin belirttiğiniz başka bir yöntemi kullanarak verir.
+DISC = İNDİRİM ## Bir tahvilin indirim oranını verir.
+DOLLARDE = LİRAON ## Kesir olarak tanımlanmış lira fiyatını, ondalık sayı olarak tanımlanmış lira fiyatına dönüştürür.
+DOLLARFR = LİRAKES ## Ondalık sayı olarak tanımlanmış lira fiyatını, kesir olarak tanımlanmış lira fiyatına dönüştürür.
+DURATION = SÜRE ## Belli aralıklarla faiz ödemesi yapan bir tahvilin yıllık süresini verir.
+EFFECT = ETKİN ## Efektif yıllık faiz oranını verir.
+FV = ANBD ## Bir yatırımın gelecekteki değerini verir.
+FVSCHEDULE = GDPROGRAM ## Bir seri birleşik faiz oranı uyguladıktan sonra, bir başlangıçtaki anaparanın gelecekteki değerini verir.
+INTRATE = FAİZORANI ## Tam olarak yatırım yapılmış bir tahvilin faiz oranını verir.
+IPMT = FAİZTUTARI ## Bir yatırımın verilen bir süre için faiz ödemesini verir.
+IRR = İÇ_VERİM_ORANI ## Bir para akışı serisi için, iç verim oranını verir.
+ISPMT = ISPMT ## Yatırımın belirli bir dönemi boyunca ödenen faizi hesaplar.
+MDURATION = MSÜRE ## Varsayılan par değeri 10.000.000 lira olan bir tahvil için Macauley değiştirilmiş süreyi verir.
+MIRR = D_İÇ_VERİM_ORANI ## Pozitif ve negatif para akışlarının farklı oranlarda finanse edildiği durumlarda, iç verim oranını verir.
+NOMINAL = NOMİNAL ## Yıllık nominal faiz oranını verir.
+NPER = DÖNEM_SAYISI ## Bir yatırımın dönem sayısını verir.
+NPV = NBD ## Bir yatırımın bugünkü net değerini, bir dönemsel para akışları serisine ve bir indirim oranına bağlı olarak verir.
+ODDFPRICE = TEKYDEĞER ## Tek bir ilk dönemi olan bir tahvilin değerini, her 100.000.000 lirada bir verir.
+ODDFYIELD = TEKYÖDEME ## Tek bir ilk dönemi olan bir tahvilin ödemesini verir.
+ODDLPRICE = TEKSDEĞER ## Tek bir son dönemi olan bir tahvilin fiyatını her 10.000.000 lirada bir verir.
+ODDLYIELD = TEKSÖDEME ## Tek bir son dönemi olan bir tahvilin ödemesini verir.
+PMT = DEVRESEL_ÖDEME ## Bir yıllık dönemsel ödemeyi verir.
+PPMT = ANA_PARA_ÖDEMESİ ## Verilen bir süre için, bir yatırımın anaparasına dayanan ödemeyi verir.
+PRICE = DEĞER ## Dönemsel faiz ödeyen bir tahvilin fiyatını 10.000.00 liralık değer başına verir.
+PRICEDISC = DEĞERİND ## İndirimli bir tahvilin fiyatını 10.000.000 liralık nominal değer başına verir.
+PRICEMAT = DEĞERVADE ## Faizini vade sonunda ödeyen bir tahvilin fiyatını 10.000.000 nominal değer başına verir.
+PV = BD ## Bir yatırımın bugünkü değerini verir.
+RATE = FAİZ_ORANI ## Bir yıllık dönem başına düşen faiz oranını verir.
+RECEIVED = GETİRİ ## Tam olarak yatırılmış bir tahvilin vadesinin bitiminde alınan miktarı verir.
+SLN = DA ## Bir malın bir dönem içindeki doğrusal yıpranmasını verir.
+SYD = YAT ## Bir malın belirli bir dönem için olan amortismanını verir.
+TBILLEQ = HTAHEŞ ## Bir Hazine bonosunun bono eşdeğeri ödemesini verir.
+TBILLPRICE = HTAHDEĞER ## Bir Hazine bonosunun değerini, 10.000.000 liralık nominal değer başına verir.
+TBILLYIELD = HTAHÖDEME ## Bir Hazine bonosunun ödemesini verir.
+VDB = DAB ## Bir malın amortismanını, belirlenmiş ya da kısmi bir dönem için, bir azalan bakiye yöntemi kullanarak verir.
+XIRR = AİÇVERİMORANI ## Dönemsel olması gerekmeyen bir para akışları programı için, iç verim oranını verir.
+XNPV = ANBD ## Dönemsel olması gerekmeyen bir para akışları programı için, bugünkü net değeri verir.
+YIELD = ÖDEME ## Belirli aralıklarla faiz ödeyen bir tahvilin ödemesini verir.
+YIELDDISC = ÖDEMEİND ## İndirimli bir tahvilin yıllık ödemesini verir; örneğin, bir Hazine bonosunun.
+YIELDMAT = ÖDEMEVADE ## Vadesinin bitiminde faiz ödeyen bir tahvilin yıllık ödemesini verir.
+
+
+##
+## Information functions Bilgi fonksiyonları
+##
+CELL = HÜCRE ## Bir hücrenin biçimlendirmesi, konumu ya da içeriği hakkında bilgi verir.
+ERROR.TYPE = HATA.TİPİ ## Bir hata türüne ilişkin sayıları verir.
+INFO = BİLGİ ## Geçerli işletim ortamı hakkında bilgi verir.
+ISBLANK = EBOŞSA ## Değer boşsa, DOĞRU verir.
+ISERR = EHATA ## Değer, #YOK dışındaki bir hata değeriyse, DOĞRU verir.
+ISERROR = EHATALIYSA ## Değer, herhangi bir hata değeriyse, DOĞRU verir.
+ISEVEN = ÇİFTTİR ## Sayı çiftse, DOĞRU verir.
+ISLOGICAL = EMANTIKSALSA ## Değer, mantıksal bir değerse, DOĞRU verir.
+ISNA = EYOKSA ## Değer, #YOK hata değeriyse, DOĞRU verir.
+ISNONTEXT = EMETİNDEĞİLSE ## Değer, metin değilse, DOĞRU verir.
+ISNUMBER = ESAYIYSA ## Değer, bir sayıysa, DOĞRU verir.
+ISODD = TEKTİR ## Sayı tekse, DOĞRU verir.
+ISREF = EREFSE ## Değer bir başvuruysa, DOĞRU verir.
+ISTEXT = EMETİNSE ## Değer bir metinse DOĞRU verir.
+N = N ## Sayıya dönüştürülmüş bir değer verir.
+NA = YOKSAY ## #YOK hata değerini verir.
+TYPE = TİP ## Bir değerin veri türünü belirten bir sayı verir.
+
+
+##
+## Logical functions Mantıksal fonksiyonlar
+##
+AND = VE ## Bütün bağımsız değişkenleri DOĞRU ise, DOĞRU verir.
+FALSE = YANLIŞ ## YANLIŞ mantıksal değerini verir.
+IF = EĞER ## Gerçekleştirilecek bir mantıksal sınama belirtir.
+IFERROR = EĞERHATA ## Formül hatalıysa belirttiğiniz değeri verir; bunun dışındaki durumlarda formülün sonucunu verir.
+NOT = DEĞİL ## Bağımsız değişkeninin mantığını tersine çevirir.
+OR = YADA ## Bağımsız değişkenlerden herhangi birisi DOĞRU ise, DOĞRU verir.
+TRUE = DOĞRU ## DOĞRU mantıksal değerini verir.
+
+
+##
+## Lookup and reference functions Arama ve Başvuru fonksiyonları
+##
+ADDRESS = ADRES ## Bir başvuruyu, çalışma sayfasındaki tek bir hücreye metin olarak verir.
+AREAS = ALANSAY ## Renvoie le nombre de zones dans une référence.
+CHOOSE = ELEMAN ## Değerler listesinden bir değer seçer.
+COLUMN = SÜTUN ## Bir başvurunun sütun sayısını verir.
+COLUMNS = SÜTUNSAY ## Bir başvurudaki sütunların sayısını verir.
+HLOOKUP = YATAYARA ## Bir dizinin en üst satırına bakar ve belirtilen hücrenin değerini verir.
+HYPERLINK = KÖPRÜ ## Bir ağ sunucusunda, bir intranette ya da Internet'te depolanan bir belgeyi açan bir kısayol ya da atlama oluşturur.
+INDEX = İNDİS ## Başvurudan veya diziden bir değer seçmek için, bir dizin kullanır.
+INDIRECT = DOLAYLI ## Metin değeriyle belirtilen bir başvuru verir.
+LOOKUP = ARA ## Bir vektördeki veya dizideki değerleri arar.
+MATCH = KAÇINCI ## Bir başvurudaki veya dizideki değerleri arar.
+OFFSET = KAYDIR ## Verilen bir başvurudan, bir başvuru kaydırmayı verir.
+ROW = SATIR ## Bir başvurunun satır sayısını verir.
+ROWS = SATIRSAY ## Bir başvurudaki satırların sayısını verir.
+RTD = RTD ## COM otomasyonunu destekleyen programdan gerçek zaman verileri alır.
+TRANSPOSE = DEVRİK_DÖNÜŞÜM ## Bir dizinin devrik dönüşümünü verir.
+VLOOKUP = DÜŞEYARA ## Bir dizinin ilk sütununa bakar ve bir hücrenin değerini vermek için satır boyunca hareket eder.
+
+
+##
+## Math and trigonometry functions Matematik ve trigonometri fonksiyonları
+##
+ABS = MUTLAK ## Bir sayının mutlak değerini verir.
+ACOS = ACOS ## Bir sayının ark kosinüsünü verir.
+ACOSH = ACOSH ## Bir sayının ters hiperbolik kosinüsünü verir.
+ASIN = ASİN ## Bir sayının ark sinüsünü verir.
+ASINH = ASİNH ## Bir sayının ters hiperbolik sinüsünü verir.
+ATAN = ATAN ## Bir sayının ark tanjantını verir.
+ATAN2 = ATAN2 ## Ark tanjantı, x- ve y- koordinatlarından verir.
+ATANH = ATANH ## Bir sayının ters hiperbolik tanjantını verir.
+CEILING = TAVANAYUVARLA ## Bir sayıyı, en yakın tamsayıya ya da en yakın katına yuvarlar.
+COMBIN = KOMBİNASYON ## Verilen sayıda öğenin kombinasyon sayısını verir.
+COS = COS ## Bir sayının kosinüsünü verir.
+COSH = COSH ## Bir sayının hiperbolik kosinüsünü verir.
+DEGREES = DERECE ## Radyanları dereceye dönüştürür.
+EVEN = ÇİFT ## Bir sayıyı, en yakın daha büyük çift tamsayıya yuvarlar.
+EXP = ÜS ## e'yi, verilen bir sayının üssüne yükseltilmiş olarak verir.
+FACT = ÇARPINIM ## Bir sayının faktörünü verir.
+FACTDOUBLE = ÇİFTFAKTÖR ## Bir sayının çift çarpınımını verir.
+FLOOR = TABANAYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar.
+GCD = OBEB ## En büyük ortak böleni verir.
+INT = TAMSAYI ## Bir sayıyı aşağıya doğru en yakın tamsayıya yuvarlar.
+LCM = OKEK ## En küçük ortak katı verir.
+LN = LN ## Bir sayının doğal logaritmasını verir.
+LOG = LOG ## Bir sayının, belirtilen bir tabandaki logaritmasını verir.
+LOG10 = LOG10 ## Bir sayının 10 tabanında logaritmasını verir.
+MDETERM = DETERMİNANT ## Bir dizinin dizey determinantını verir.
+MINVERSE = DİZEY_TERS ## Bir dizinin dizey tersini verir.
+MMULT = DÇARP ## İki dizinin dizey çarpımını verir.
+MOD = MODÜLO ## Bölmeden kalanı verir.
+MROUND = KYUVARLA ## İstenen kata yuvarlanmış bir sayı verir.
+MULTINOMIAL = ÇOKTERİMLİ ## Bir sayılar kümesinin çok terimlisini verir.
+ODD = TEK ## Bir sayıyı en yakın daha büyük tek sayıya yuvarlar.
+PI = Pİ ## Pi değerini verir.
+POWER = KUVVET ## Bir üsse yükseltilmiş sayının sonucunu verir.
+PRODUCT = ÇARPIM ## Bağımsız değişkenlerini çarpar.
+QUOTIENT = BÖLÜM ## Bir bölme işleminin tamsayı kısmını verir.
+RADIANS = RADYAN ## Dereceleri radyanlara dönüştürür.
+RAND = S_SAYI_ÜRET ## 0 ile 1 arasında rastgele bir sayı verir.
+RANDBETWEEN = RASTGELEARALIK ## Belirttiğiniz sayılar arasında rastgele bir sayı verir.
+ROMAN = ROMEN ## Bir normal rakamı, metin olarak, romen rakamına çevirir.
+ROUND = YUVARLA ## Bir sayıyı, belirtilen basamak sayısına yuvarlar.
+ROUNDDOWN = AŞAĞIYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar.
+ROUNDUP = YUKARIYUVARLA ## Bir sayıyı daha büyük sayıya, sıfırdan ıraksayarak yuvarlar.
+SERIESSUM = SERİTOPLA ## Bir üs serisinin toplamını, formüle bağlı olarak verir.
+SIGN = İŞARET ## Bir sayının işaretini verir.
+SIN = SİN ## Verilen bir açının sinüsünü verir.
+SINH = SİNH ## Bir sayının hiperbolik sinüsünü verir.
+SQRT = KAREKÖK ## Pozitif bir karekök verir.
+SQRTPI = KAREKÖKPİ ## (* Pi sayısının) kare kökünü verir.
+SUBTOTAL = ALTTOPLAM ## Bir listedeki ya da veritabanındaki bir alt toplamı verir.
+SUM = TOPLA ## Bağımsız değişkenlerini toplar.
+SUMIF = ETOPLA ## Verilen ölçütle belirlenen hücreleri toplar.
+SUMIFS = SUMIFS ## Bir aralıktaki, birden fazla ölçüte uyan hücreleri ekler.
+SUMPRODUCT = TOPLA.ÇARPIM ## İlişkili dizi bileşenlerinin çarpımlarının toplamını verir.
+SUMSQ = TOPKARE ## Bağımsız değişkenlerin karelerinin toplamını verir.
+SUMX2MY2 = TOPX2EY2 ## İki dizideki ilişkili değerlerin farkının toplamını verir.
+SUMX2PY2 = TOPX2AY2 ## İki dizideki ilişkili değerlerin karelerinin toplamının toplamını verir.
+SUMXMY2 = TOPXEY2 ## İki dizideki ilişkili değerlerin farklarının karelerinin toplamını verir.
+TAN = TAN ## Bir sayının tanjantını verir.
+TANH = TANH ## Bir sayının hiperbolik tanjantını verir.
+TRUNC = NSAT ## Bir sayının, tamsayı durumuna gelecek şekilde, fazlalıklarını atar.
+
+
+##
+## Statistical functions İstatistiksel fonksiyonlar
+##
+AVEDEV = ORTSAP ## Veri noktalarının ortalamalarından mutlak sapmalarının ortalamasını verir.
+AVERAGE = ORTALAMA ## Bağımsız değişkenlerinin ortalamasını verir.
+AVERAGEA = ORTALAMAA ## Bağımsız değişkenlerinin, sayılar, metin ve mantıksal değerleri içermek üzere ortalamasını verir.
+AVERAGEIF = EĞERORTALAMA ## Verili ölçütü karşılayan bir aralıktaki bütün hücrelerin ortalamasını (aritmetik ortalama) hesaplar.
+AVERAGEIFS = EĞERLERORTALAMA ## Birden çok ölçüte uyan tüm hücrelerin ortalamasını (aritmetik ortalama) hesaplar.
+BETADIST = BETADAĞ ## Beta birikimli dağılım fonksiyonunu verir.
+BETAINV = BETATERS ## Belirli bir beta dağılımı için birikimli dağılım fonksiyonunun tersini verir.
+BINOMDIST = BİNOMDAĞ ## Tek terimli binom dağılımı olasılığını verir.
+CHIDIST = KİKAREDAĞ ## Kikare dağılımın tek kuyruklu olasılığını verir.
+CHIINV = KİKARETERS ## Kikare dağılımın kuyruklu olasılığının tersini verir.
+CHITEST = KİKARETEST ## Bağımsızlık sınamalarını verir.
+CONFIDENCE = GÜVENİRLİK ## Bir popülasyon ortalaması için güvenirlik aralığını verir.
+CORREL = KORELASYON ## İki veri kümesi arasındaki bağlantı katsayısını verir.
+COUNT = BAĞ_DEĞ_SAY ## Bağımsız değişkenler listesinde kaç tane sayı bulunduğunu sayar.
+COUNTA = BAĞ_DEĞ_DOLU_SAY ## Bağımsız değişkenler listesinde kaç tane değer bulunduğunu sayar.
+COUNTBLANK = BOŞLUKSAY ## Aralıktaki boş hücre sayısını hesaplar.
+COUNTIF = EĞERSAY ## Verilen ölçütlere uyan bir aralık içindeki hücreleri sayar.
+COUNTIFS = ÇOKEĞERSAY ## Birden çok ölçüte uyan bir aralık içindeki hücreleri sayar.
+COVAR = KOVARYANS ## Eşleştirilmiş sapmaların ortalaması olan kovaryansı verir.
+CRITBINOM = KRİTİKBİNOM ## Birikimli binom dağılımının bir ölçüt değerinden küçük veya ölçüt değerine eşit olduğu en küçük değeri verir.
+DEVSQ = SAPKARE ## Sapmaların karelerinin toplamını verir.
+EXPONDIST = ÜSTELDAĞ ## Üstel dağılımı verir.
+FDIST = FDAĞ ## F olasılık dağılımını verir.
+FINV = FTERS ## F olasılık dağılımının tersini verir.
+FISHER = FISHER ## Fisher dönüşümünü verir.
+FISHERINV = FISHERTERS ## Fisher dönüşümünün tersini verir.
+FORECAST = TAHMİN ## Bir doğrusal eğilim boyunca bir değer verir.
+FREQUENCY = SIKLIK ## Bir sıklık dağılımını, dikey bir dizi olarak verir.
+FTEST = FTEST ## Bir F-test'in sonucunu verir.
+GAMMADIST = GAMADAĞ ## Gama dağılımını verir.
+GAMMAINV = GAMATERS ## Gama kümülatif dağılımının tersini verir.
+GAMMALN = GAMALN ## Gama fonksiyonunun (?(x)) doğal logaritmasını verir.
+GEOMEAN = GEOORT ## Geometrik ortayı verir.
+GROWTH = BÜYÜME ## Üstel bir eğilim boyunca değerler verir.
+HARMEAN = HARORT ## Harmonik ortayı verir.
+HYPGEOMDIST = HİPERGEOMDAĞ ## Hipergeometrik dağılımı verir.
+INTERCEPT = KESMENOKTASI ## Doğrusal çakıştırma çizgisinin kesişme noktasını verir.
+KURT = BASIKLIK ## Bir veri kümesinin basıklığını verir.
+LARGE = BÜYÜK ## Bir veri kümesinde k. en büyük değeri verir.
+LINEST = DOT ## Doğrusal bir eğilimin parametrelerini verir.
+LOGEST = LOT ## Üstel bir eğilimin parametrelerini verir.
+LOGINV = LOGTERS ## Bir lognormal dağılımının tersini verir.
+LOGNORMDIST = LOGNORMDAĞ ## Birikimli lognormal dağılımını verir.
+MAX = MAK ## Bir bağımsız değişkenler listesindeki en büyük değeri verir.
+MAXA = MAKA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri içermek üzere, en büyük değeri verir.
+MEDIAN = ORTANCA ## Belirtilen sayıların orta değerini verir.
+MIN = MİN ## Bir bağımsız değişkenler listesindeki en küçük değeri verir.
+MINA = MİNA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri de içermek üzere, en küçük değeri verir.
+MODE = ENÇOK_OLAN ## Bir veri kümesindeki en sık rastlanan değeri verir.
+NEGBINOMDIST = NEGBİNOMDAĞ ## Negatif binom dağılımını verir.
+NORMDIST = NORMDAĞ ## Normal birikimli dağılımı verir.
+NORMINV = NORMTERS ## Normal kümülatif dağılımın tersini verir.
+NORMSDIST = NORMSDAĞ ## Standart normal birikimli dağılımı verir.
+NORMSINV = NORMSTERS ## Standart normal birikimli dağılımın tersini verir.
+PEARSON = PEARSON ## Pearson çarpım moment korelasyon katsayısını verir.
+PERCENTILE = YÜZDEBİRLİK ## Bir aralık içerisinde bulunan değerlerin k. frekans toplamını verir.
+PERCENTRANK = YÜZDERANK ## Bir veri kümesindeki bir değerin yüzde mertebesini verir.
+PERMUT = PERMÜTASYON ## Verilen sayıda nesne için permütasyon sayısını verir.
+POISSON = POISSON ## Poisson dağılımını verir.
+PROB = OLASILIK ## Bir aralıktaki değerlerin iki sınır arasında olması olasılığını verir.
+QUARTILE = DÖRTTEBİRLİK ## Bir veri kümesinin dörtte birliğini verir.
+RANK = RANK ## Bir sayılar listesinde bir sayının mertebesini verir.
+RSQ = RKARE ## Pearson çarpım moment korelasyon katsayısının karesini verir.
+SKEW = ÇARPIKLIK ## Bir dağılımın çarpıklığını verir.
+SLOPE = EĞİM ## Doğrusal çakışma çizgisinin eğimini verir.
+SMALL = KÜÇÜK ## Bir veri kümesinde k. en küçük değeri verir.
+STANDARDIZE = STANDARTLAŞTIRMA ## Normalleştirilmiş bir değer verir.
+STDEV = STDSAPMA ## Bir örneğe dayanarak standart sapmayı tahmin eder.
+STDEVA = STDSAPMAA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder.
+STDEVP = STDSAPMAS ## Standart sapmayı, tüm popülasyona bağlı olarak hesaplar.
+STDEVPA = STDSAPMASA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar.
+STEYX = STHYX ## Regresyondaki her x için tahmini y değerinin standart hatasını verir.
+TDIST = TDAĞ ## T-dağılımını verir.
+TINV = TTERS ## T-dağılımının tersini verir.
+TREND = EĞİLİM ## Doğrusal bir eğilim boyunca değerler verir.
+TRIMMEAN = KIRPORTALAMA ## Bir veri kümesinin içinin ortalamasını verir.
+TTEST = TTEST ## T-test'le ilişkilendirilmiş olasılığı verir.
+VAR = VAR ## Varyansı, bir örneğe bağlı olarak tahmin eder.
+VARA = VARA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder.
+VARP = VARS ## Varyansı, tüm popülasyona dayanarak hesaplar.
+VARPA = VARSA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar.
+WEIBULL = WEIBULL ## Weibull dağılımını hesaplar.
+ZTEST = ZTEST ## Z-testinin tek kuyruklu olasılık değerini hesaplar.
+
+
+##
+## Text functions Metin fonksiyonları
+##
+ASC = ASC ## Bir karakter dizesindeki çift enli (iki bayt) İngilizce harfleri veya katakanayı yarım enli (tek bayt) karakterlerle değiştirir.
+BAHTTEXT = BAHTTEXT ## Sayıyı, ß (baht) para birimi biçimini kullanarak metne dönüştürür.
+CHAR = DAMGA ## Kod sayısıyla belirtilen karakteri verir.
+CLEAN = TEMİZ ## Metindeki bütün yazdırılamaz karakterleri kaldırır.
+CODE = KOD ## Bir metin dizesindeki ilk karakter için sayısal bir kod verir.
+CONCATENATE = BİRLEŞTİR ## Pek çok metin öğesini bir metin öğesi olarak birleştirir.
+DOLLAR = LİRA ## Bir sayıyı YTL (yeni Türk lirası) para birimi biçimini kullanarak metne dönüştürür.
+EXACT = ÖZDEŞ ## İki metin değerinin özdeş olup olmadığını anlamak için, değerleri denetler.
+FIND = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır).
+FINDB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır).
+FIXED = SAYIDÜZENLE ## Bir sayıyı, sabit sayıda ondalıkla, metin olarak biçimlendirir.
+JIS = JIS ## Bir karakter dizesindeki tek enli (tek bayt) İngilizce harfleri veya katakanayı çift enli (iki bayt) karakterlerle değiştirir.
+LEFT = SOL ## Bir metin değerinden en soldaki karakterleri verir.
+LEFTB = SOLB ## Bir metin değerinden en soldaki karakterleri verir.
+LEN = UZUNLUK ## Bir metin dizesindeki karakter sayısını verir.
+LENB = UZUNLUKB ## Bir metin dizesindeki karakter sayısını verir.
+LOWER = KÜÇÜKHARF ## Metni küçük harfe çevirir.
+MID = ORTA ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir.
+MIDB = ORTAB ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir.
+PHONETIC = SES ## Metin dizesinden ses (furigana) karakterlerini ayıklar.
+PROPER = YAZIM.DÜZENİ ## Bir metin değerinin her bir sözcüğünün ilk harfini büyük harfe çevirir.
+REPLACE = DEĞİŞTİR ## Metnin içindeki karakterleri değiştirir.
+REPLACEB = DEĞİŞTİRB ## Metnin içindeki karakterleri değiştirir.
+REPT = YİNELE ## Metni belirtilen sayıda yineler.
+RIGHT = SAĞ ## Bir metin değerinden en sağdaki karakterleri verir.
+RIGHTB = SAĞB ## Bir metin değerinden en sağdaki karakterleri verir.
+SEARCH = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir).
+SEARCHB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir).
+SUBSTITUTE = YERİNEKOY ## Bir metin dizesinde, eski metnin yerine yeni metin koyar.
+T = M ## Bağımsız değerlerini metne dönüştürür.
+TEXT = METNEÇEVİR ## Bir sayıyı biçimlendirir ve metne dönüştürür.
+TRIM = KIRP ## Metindeki boşlukları kaldırır.
+UPPER = BÜYÜKHARF ## Metni büyük harfe çevirir.
+VALUE = SAYIYAÇEVİR ## Bir metin bağımsız değişkenini sayıya dönüştürür.