PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/PHPExcel/Calculation/LookupRef.php

https://github.com/yuweijun/blog
PHP | 878 lines | 687 code | 35 blank | 156 comment | 68 complexity | 4dc3dcd7190279c8f6b9fa46f9775ee6 MD5 | raw file
  1. <?php
  2. /** PHPExcel root directory */
  3. if (!defined('PHPEXCEL_ROOT')) {
  4. /**
  5. * @ignore
  6. */
  7. define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
  8. require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
  9. }
  10. /**
  11. * PHPExcel_Calculation_LookupRef
  12. *
  13. * Copyright (c) 2006 - 2015 PHPExcel
  14. *
  15. * This library is free software; you can redistribute it and/or
  16. * modify it under the terms of the GNU Lesser General Public
  17. * License as published by the Free Software Foundation; either
  18. * version 2.1 of the License, or (at your option) any later version.
  19. *
  20. * This library is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23. * Lesser General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Lesser General Public
  26. * License along with this library; if not, write to the Free Software
  27. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  28. *
  29. * @category PHPExcel
  30. * @package PHPExcel_Calculation
  31. * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
  32. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  33. * @version ##VERSION##, ##DATE##
  34. */
  35. class PHPExcel_Calculation_LookupRef
  36. {
  37. /**
  38. * CELL_ADDRESS
  39. *
  40. * Creates a cell address as text, given specified row and column numbers.
  41. *
  42. * Excel Function:
  43. * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
  44. *
  45. * @param row Row number to use in the cell reference
  46. * @param column Column number to use in the cell reference
  47. * @param relativity Flag indicating the type of reference to return
  48. * 1 or omitted Absolute
  49. * 2 Absolute row; relative column
  50. * 3 Relative row; absolute column
  51. * 4 Relative
  52. * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
  53. * TRUE or omitted CELL_ADDRESS returns an A1-style reference
  54. * FALSE CELL_ADDRESS returns an R1C1-style reference
  55. * @param sheetText Optional Name of worksheet to use
  56. * @return string
  57. */
  58. public static function CELL_ADDRESS($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '')
  59. {
  60. $row = PHPExcel_Calculation_Functions::flattenSingleValue($row);
  61. $column = PHPExcel_Calculation_Functions::flattenSingleValue($column);
  62. $relativity = PHPExcel_Calculation_Functions::flattenSingleValue($relativity);
  63. $sheetText = PHPExcel_Calculation_Functions::flattenSingleValue($sheetText);
  64. if (($row < 1) || ($column < 1)) {
  65. return PHPExcel_Calculation_Functions::VALUE();
  66. }
  67. if ($sheetText > '') {
  68. if (strpos($sheetText, ' ') !== false) {
  69. $sheetText = "'".$sheetText."'";
  70. }
  71. $sheetText .='!';
  72. }
  73. if ((!is_bool($referenceStyle)) || $referenceStyle) {
  74. $rowRelative = $columnRelative = '$';
  75. $column = PHPExcel_Cell::stringFromColumnIndex($column-1);
  76. if (($relativity == 2) || ($relativity == 4)) {
  77. $columnRelative = '';
  78. }
  79. if (($relativity == 3) || ($relativity == 4)) {
  80. $rowRelative = '';
  81. }
  82. return $sheetText.$columnRelative.$column.$rowRelative.$row;
  83. } else {
  84. if (($relativity == 2) || ($relativity == 4)) {
  85. $column = '['.$column.']';
  86. }
  87. if (($relativity == 3) || ($relativity == 4)) {
  88. $row = '['.$row.']';
  89. }
  90. return $sheetText.'R'.$row.'C'.$column;
  91. }
  92. }
  93. /**
  94. * COLUMN
  95. *
  96. * Returns the column number of the given cell reference
  97. * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
  98. * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
  99. * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
  100. *
  101. * Excel Function:
  102. * =COLUMN([cellAddress])
  103. *
  104. * @param cellAddress A reference to a range of cells for which you want the column numbers
  105. * @return integer or array of integer
  106. */
  107. public static function COLUMN($cellAddress = null)
  108. {
  109. if (is_null($cellAddress) || trim($cellAddress) === '') {
  110. return 0;
  111. }
  112. if (is_array($cellAddress)) {
  113. foreach ($cellAddress as $columnKey => $value) {
  114. $columnKey = preg_replace('/[^a-z]/i', '', $columnKey);
  115. return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
  116. }
  117. } else {
  118. if (strpos($cellAddress, '!') !== false) {
  119. list($sheet, $cellAddress) = explode('!', $cellAddress);
  120. }
  121. if (strpos($cellAddress, ':') !== false) {
  122. list($startAddress, $endAddress) = explode(':', $cellAddress);
  123. $startAddress = preg_replace('/[^a-z]/i', '', $startAddress);
  124. $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
  125. $returnValue = array();
  126. do {
  127. $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
  128. } while ($startAddress++ != $endAddress);
  129. return $returnValue;
  130. } else {
  131. $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress);
  132. return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
  133. }
  134. }
  135. }
  136. /**
  137. * COLUMNS
  138. *
  139. * Returns the number of columns in an array or reference.
  140. *
  141. * Excel Function:
  142. * =COLUMNS(cellAddress)
  143. *
  144. * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
  145. * @return integer The number of columns in cellAddress
  146. */
  147. public static function COLUMNS($cellAddress = null)
  148. {
  149. if (is_null($cellAddress) || $cellAddress === '') {
  150. return 1;
  151. } elseif (!is_array($cellAddress)) {
  152. return PHPExcel_Calculation_Functions::VALUE();
  153. }
  154. reset($cellAddress);
  155. $isMatrix = (is_numeric(key($cellAddress)));
  156. list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
  157. if ($isMatrix) {
  158. return $rows;
  159. } else {
  160. return $columns;
  161. }
  162. }
  163. /**
  164. * ROW
  165. *
  166. * Returns the row number of the given cell reference
  167. * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
  168. * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
  169. * reference of the cell in which the ROW function appears; otherwise this function returns 0.
  170. *
  171. * Excel Function:
  172. * =ROW([cellAddress])
  173. *
  174. * @param cellAddress A reference to a range of cells for which you want the row numbers
  175. * @return integer or array of integer
  176. */
  177. public static function ROW($cellAddress = null)
  178. {
  179. if (is_null($cellAddress) || trim($cellAddress) === '') {
  180. return 0;
  181. }
  182. if (is_array($cellAddress)) {
  183. foreach ($cellAddress as $columnKey => $rowValue) {
  184. foreach ($rowValue as $rowKey => $cellValue) {
  185. return (integer) preg_replace('/[^0-9]/i', '', $rowKey);
  186. }
  187. }
  188. } else {
  189. if (strpos($cellAddress, '!') !== false) {
  190. list($sheet, $cellAddress) = explode('!', $cellAddress);
  191. }
  192. if (strpos($cellAddress, ':') !== false) {
  193. list($startAddress, $endAddress) = explode(':', $cellAddress);
  194. $startAddress = preg_replace('/[^0-9]/', '', $startAddress);
  195. $endAddress = preg_replace('/[^0-9]/', '', $endAddress);
  196. $returnValue = array();
  197. do {
  198. $returnValue[][] = (integer) $startAddress;
  199. } while ($startAddress++ != $endAddress);
  200. return $returnValue;
  201. } else {
  202. list($cellAddress) = explode(':', $cellAddress);
  203. return (integer) preg_replace('/[^0-9]/', '', $cellAddress);
  204. }
  205. }
  206. }
  207. /**
  208. * ROWS
  209. *
  210. * Returns the number of rows in an array or reference.
  211. *
  212. * Excel Function:
  213. * =ROWS(cellAddress)
  214. *
  215. * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
  216. * @return integer The number of rows in cellAddress
  217. */
  218. public static function ROWS($cellAddress = null)
  219. {
  220. if (is_null($cellAddress) || $cellAddress === '') {
  221. return 1;
  222. } elseif (!is_array($cellAddress)) {
  223. return PHPExcel_Calculation_Functions::VALUE();
  224. }
  225. reset($cellAddress);
  226. $isMatrix = (is_numeric(key($cellAddress)));
  227. list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
  228. if ($isMatrix) {
  229. return $columns;
  230. } else {
  231. return $rows;
  232. }
  233. }
  234. /**
  235. * HYPERLINK
  236. *
  237. * Excel Function:
  238. * =HYPERLINK(linkURL,displayName)
  239. *
  240. * @access public
  241. * @category Logical Functions
  242. * @param string $linkURL Value to check, is also the value returned when no error
  243. * @param string $displayName Value to return when testValue is an error condition
  244. * @param PHPExcel_Cell $pCell The cell to set the hyperlink in
  245. * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
  246. */
  247. public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null)
  248. {
  249. $args = func_get_args();
  250. $pCell = array_pop($args);
  251. $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL);
  252. $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName);
  253. if ((!is_object($pCell)) || (trim($linkURL) == '')) {
  254. return PHPExcel_Calculation_Functions::REF();
  255. }
  256. if ((is_object($displayName)) || trim($displayName) == '') {
  257. $displayName = $linkURL;
  258. }
  259. $pCell->getHyperlink()->setUrl($linkURL);
  260. return $displayName;
  261. }
  262. /**
  263. * INDIRECT
  264. *
  265. * Returns the reference specified by a text string.
  266. * References are immediately evaluated to display their contents.
  267. *
  268. * Excel Function:
  269. * =INDIRECT(cellAddress)
  270. *
  271. * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
  272. *
  273. * @param cellAddress $cellAddress The cell address of the current cell (containing this formula)
  274. * @param PHPExcel_Cell $pCell The current cell (containing this formula)
  275. * @return mixed The cells referenced by cellAddress
  276. *
  277. * @todo Support for the optional a1 parameter introduced in Excel 2010
  278. *
  279. */
  280. public static function INDIRECT($cellAddress = null, PHPExcel_Cell $pCell = null)
  281. {
  282. $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress);
  283. if (is_null($cellAddress) || $cellAddress === '') {
  284. return PHPExcel_Calculation_Functions::REF();
  285. }
  286. $cellAddress1 = $cellAddress;
  287. $cellAddress2 = null;
  288. if (strpos($cellAddress, ':') !== false) {
  289. list($cellAddress1, $cellAddress2) = explode(':', $cellAddress);
  290. }
  291. if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
  292. ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
  293. if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
  294. return PHPExcel_Calculation_Functions::REF();
  295. }
  296. if (strpos($cellAddress, '!') !== false) {
  297. list($sheetName, $cellAddress) = explode('!', $cellAddress);
  298. $sheetName = trim($sheetName, "'");
  299. $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
  300. } else {
  301. $pSheet = $pCell->getWorksheet();
  302. }
  303. return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false);
  304. }
  305. if (strpos($cellAddress, '!') !== false) {
  306. list($sheetName, $cellAddress) = explode('!', $cellAddress);
  307. $sheetName = trim($sheetName, "'");
  308. $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
  309. } else {
  310. $pSheet = $pCell->getWorksheet();
  311. }
  312. return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
  313. }
  314. /**
  315. * OFFSET
  316. *
  317. * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
  318. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
  319. * the number of columns to be returned.
  320. *
  321. * Excel Function:
  322. * =OFFSET(cellAddress, rows, cols, [height], [width])
  323. *
  324. * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
  325. * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
  326. * @param rows The number of rows, up or down, that you want the upper-left cell to refer to.
  327. * Using 5 as the rows argument specifies that the upper-left cell in the reference is
  328. * five rows below reference. Rows can be positive (which means below the starting reference)
  329. * or negative (which means above the starting reference).
  330. * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result
  331. * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
  332. * reference is five columns to the right of reference. Cols can be positive (which means
  333. * to the right of the starting reference) or negative (which means to the left of the
  334. * starting reference).
  335. * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
  336. * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
  337. * @return string A reference to a cell or range of cells
  338. */
  339. public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null)
  340. {
  341. $rows = PHPExcel_Calculation_Functions::flattenSingleValue($rows);
  342. $columns = PHPExcel_Calculation_Functions::flattenSingleValue($columns);
  343. $height = PHPExcel_Calculation_Functions::flattenSingleValue($height);
  344. $width = PHPExcel_Calculation_Functions::flattenSingleValue($width);
  345. if ($cellAddress == null) {
  346. return 0;
  347. }
  348. $args = func_get_args();
  349. $pCell = array_pop($args);
  350. if (!is_object($pCell)) {
  351. return PHPExcel_Calculation_Functions::REF();
  352. }
  353. $sheetName = null;
  354. if (strpos($cellAddress, "!")) {
  355. list($sheetName, $cellAddress) = explode("!", $cellAddress);
  356. $sheetName = trim($sheetName, "'");
  357. }
  358. if (strpos($cellAddress, ":")) {
  359. list($startCell, $endCell) = explode(":", $cellAddress);
  360. } else {
  361. $startCell = $endCell = $cellAddress;
  362. }
  363. list($startCellColumn, $startCellRow) = PHPExcel_Cell::coordinateFromString($startCell);
  364. list($endCellColumn, $endCellRow) = PHPExcel_Cell::coordinateFromString($endCell);
  365. $startCellRow += $rows;
  366. $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1;
  367. $startCellColumn += $columns;
  368. if (($startCellRow <= 0) || ($startCellColumn < 0)) {
  369. return PHPExcel_Calculation_Functions::REF();
  370. }
  371. $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1;
  372. if (($width != null) && (!is_object($width))) {
  373. $endCellColumn = $startCellColumn + $width - 1;
  374. } else {
  375. $endCellColumn += $columns;
  376. }
  377. $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn);
  378. if (($height != null) && (!is_object($height))) {
  379. $endCellRow = $startCellRow + $height - 1;
  380. } else {
  381. $endCellRow += $rows;
  382. }
  383. if (($endCellRow <= 0) || ($endCellColumn < 0)) {
  384. return PHPExcel_Calculation_Functions::REF();
  385. }
  386. $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn);
  387. $cellAddress = $startCellColumn.$startCellRow;
  388. if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
  389. $cellAddress .= ':'.$endCellColumn.$endCellRow;
  390. }
  391. if ($sheetName !== null) {
  392. $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
  393. } else {
  394. $pSheet = $pCell->getWorksheet();
  395. }
  396. return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
  397. }
  398. /**
  399. * CHOOSE
  400. *
  401. * Uses lookup_value to return a value from the list of value arguments.
  402. * Use CHOOSE to select one of up to 254 values based on the lookup_value.
  403. *
  404. * Excel Function:
  405. * =CHOOSE(index_num, value1, [value2], ...)
  406. *
  407. * @param index_num Specifies which value argument is selected.
  408. * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
  409. * between 1 and 254.
  410. * @param value1... Value1 is required, subsequent values are optional.
  411. * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
  412. * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
  413. * text.
  414. * @return mixed The selected value
  415. */
  416. public static function CHOOSE()
  417. {
  418. $chooseArgs = func_get_args();
  419. $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs));
  420. $entryCount = count($chooseArgs) - 1;
  421. if (is_array($chosenEntry)) {
  422. $chosenEntry = array_shift($chosenEntry);
  423. }
  424. if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
  425. --$chosenEntry;
  426. } else {
  427. return PHPExcel_Calculation_Functions::VALUE();
  428. }
  429. $chosenEntry = floor($chosenEntry);
  430. if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) {
  431. return PHPExcel_Calculation_Functions::VALUE();
  432. }
  433. if (is_array($chooseArgs[$chosenEntry])) {
  434. return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
  435. } else {
  436. return $chooseArgs[$chosenEntry];
  437. }
  438. }
  439. /**
  440. * MATCH
  441. *
  442. * The MATCH function searches for a specified item in a range of cells
  443. *
  444. * Excel Function:
  445. * =MATCH(lookup_value, lookup_array, [match_type])
  446. *
  447. * @param lookup_value The value that you want to match in lookup_array
  448. * @param lookup_array The range of cells being searched
  449. * @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.
  450. * @return integer The relative position of the found item
  451. */
  452. public static function MATCH($lookup_value, $lookup_array, $match_type = 1)
  453. {
  454. $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array);
  455. $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
  456. $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type);
  457. // MATCH is not case sensitive
  458. $lookup_value = strtolower($lookup_value);
  459. // lookup_value type has to be number, text, or logical values
  460. if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
  461. return PHPExcel_Calculation_Functions::NA();
  462. }
  463. // match_type is 0, 1 or -1
  464. if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
  465. return PHPExcel_Calculation_Functions::NA();
  466. }
  467. // lookup_array should not be empty
  468. $lookupArraySize = count($lookup_array);
  469. if ($lookupArraySize <= 0) {
  470. return PHPExcel_Calculation_Functions::NA();
  471. }
  472. // lookup_array should contain only number, text, or logical values, or empty (null) cells
  473. foreach ($lookup_array as $i => $lookupArrayValue) {
  474. // check the type of the value
  475. if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
  476. (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
  477. return PHPExcel_Calculation_Functions::NA();
  478. }
  479. // convert strings to lowercase for case-insensitive testing
  480. if (is_string($lookupArrayValue)) {
  481. $lookup_array[$i] = strtolower($lookupArrayValue);
  482. }
  483. if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
  484. $lookup_array = array_slice($lookup_array, 0, $i-1);
  485. }
  486. }
  487. // if match_type is 1 or -1, the list has to be ordered
  488. if ($match_type == 1) {
  489. asort($lookup_array);
  490. $keySet = array_keys($lookup_array);
  491. } elseif ($match_type == -1) {
  492. arsort($lookup_array);
  493. $keySet = array_keys($lookup_array);
  494. }
  495. // **
  496. // find the match
  497. // **
  498. foreach ($lookup_array as $i => $lookupArrayValue) {
  499. if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
  500. // exact match
  501. return ++$i;
  502. } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
  503. $i = array_search($i, $keySet);
  504. // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
  505. if ($i < 1) {
  506. // 1st cell was already smaller than the lookup_value
  507. break;
  508. } else {
  509. // the previous cell was the match
  510. return $keySet[$i-1]+1;
  511. }
  512. } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
  513. $i = array_search($i, $keySet);
  514. // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
  515. if ($i < 1) {
  516. // 1st cell was already bigger than the lookup_value
  517. break;
  518. } else {
  519. // the previous cell was the match
  520. return $keySet[$i-1]+1;
  521. }
  522. }
  523. }
  524. // unsuccessful in finding a match, return #N/A error value
  525. return PHPExcel_Calculation_Functions::NA();
  526. }
  527. /**
  528. * INDEX
  529. *
  530. * Uses an index to choose a value from a reference or array
  531. *
  532. * Excel Function:
  533. * =INDEX(range_array, row_num, [column_num])
  534. *
  535. * @param range_array A range of cells or an array constant
  536. * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
  537. * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
  538. * @return mixed the value of a specified cell or array of cells
  539. */
  540. public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0)
  541. {
  542. if (($rowNum < 0) || ($columnNum < 0)) {
  543. return PHPExcel_Calculation_Functions::VALUE();
  544. }
  545. if (!is_array($arrayValues)) {
  546. return PHPExcel_Calculation_Functions::REF();
  547. }
  548. $rowKeys = array_keys($arrayValues);
  549. $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
  550. if ($columnNum > count($columnKeys)) {
  551. return PHPExcel_Calculation_Functions::VALUE();
  552. } elseif ($columnNum == 0) {
  553. if ($rowNum == 0) {
  554. return $arrayValues;
  555. }
  556. $rowNum = $rowKeys[--$rowNum];
  557. $returnArray = array();
  558. foreach ($arrayValues as $arrayColumn) {
  559. if (is_array($arrayColumn)) {
  560. if (isset($arrayColumn[$rowNum])) {
  561. $returnArray[] = $arrayColumn[$rowNum];
  562. } else {
  563. return $arrayValues[$rowNum];
  564. }
  565. } else {
  566. return $arrayValues[$rowNum];
  567. }
  568. }
  569. return $returnArray;
  570. }
  571. $columnNum = $columnKeys[--$columnNum];
  572. if ($rowNum > count($rowKeys)) {
  573. return PHPExcel_Calculation_Functions::VALUE();
  574. } elseif ($rowNum == 0) {
  575. return $arrayValues[$columnNum];
  576. }
  577. $rowNum = $rowKeys[--$rowNum];
  578. return $arrayValues[$rowNum][$columnNum];
  579. }
  580. /**
  581. * TRANSPOSE
  582. *
  583. * @param array $matrixData A matrix of values
  584. * @return array
  585. *
  586. * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
  587. */
  588. public static function TRANSPOSE($matrixData)
  589. {
  590. $returnMatrix = array();
  591. if (!is_array($matrixData)) {
  592. $matrixData = array(array($matrixData));
  593. }
  594. $column = 0;
  595. foreach ($matrixData as $matrixRow) {
  596. $row = 0;
  597. foreach ($matrixRow as $matrixCell) {
  598. $returnMatrix[$row][$column] = $matrixCell;
  599. ++$row;
  600. }
  601. ++$column;
  602. }
  603. return $returnMatrix;
  604. }
  605. private static function vlookupSort($a, $b)
  606. {
  607. reset($a);
  608. $firstColumn = key($a);
  609. if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) {
  610. return 0;
  611. }
  612. return ($aLower < $bLower) ? -1 : 1;
  613. }
  614. /**
  615. * VLOOKUP
  616. * 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.
  617. * @param lookup_value The value that you want to match in lookup_array
  618. * @param lookup_array The range of cells being searched
  619. * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
  620. * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
  621. * @return mixed The value of the found cell
  622. */
  623. public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
  624. {
  625. $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
  626. $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
  627. $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
  628. // index_number must be greater than or equal to 1
  629. if ($index_number < 1) {
  630. return PHPExcel_Calculation_Functions::VALUE();
  631. }
  632. // index_number must be less than or equal to the number of columns in lookup_array
  633. if ((!is_array($lookup_array)) || (empty($lookup_array))) {
  634. return PHPExcel_Calculation_Functions::REF();
  635. } else {
  636. $f = array_keys($lookup_array);
  637. $firstRow = array_pop($f);
  638. if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
  639. return PHPExcel_Calculation_Functions::REF();
  640. } else {
  641. $columnKeys = array_keys($lookup_array[$firstRow]);
  642. $returnColumn = $columnKeys[--$index_number];
  643. $firstColumn = array_shift($columnKeys);
  644. }
  645. }
  646. if (!$not_exact_match) {
  647. uasort($lookup_array, array('self', 'vlookupSort'));
  648. }
  649. $rowNumber = $rowValue = false;
  650. foreach ($lookup_array as $rowKey => $rowData) {
  651. if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
  652. (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) {
  653. break;
  654. }
  655. $rowNumber = $rowKey;
  656. $rowValue = $rowData[$firstColumn];
  657. }
  658. if ($rowNumber !== false) {
  659. if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
  660. // if an exact match is required, we have what we need to return an appropriate response
  661. return PHPExcel_Calculation_Functions::NA();
  662. } else {
  663. // otherwise return the appropriate value
  664. return $lookup_array[$rowNumber][$returnColumn];
  665. }
  666. }
  667. return PHPExcel_Calculation_Functions::NA();
  668. }
  669. /**
  670. * HLOOKUP
  671. * 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.
  672. * @param lookup_value The value that you want to match in lookup_array
  673. * @param lookup_array The range of cells being searched
  674. * @param index_number The row number in table_array from which the matching value must be returned. The first row is 1.
  675. * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
  676. * @return mixed The value of the found cell
  677. */
  678. public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
  679. {
  680. $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
  681. $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
  682. $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
  683. // index_number must be greater than or equal to 1
  684. if ($index_number < 1) {
  685. return PHPExcel_Calculation_Functions::VALUE();
  686. }
  687. // index_number must be less than or equal to the number of columns in lookup_array
  688. if ((!is_array($lookup_array)) || (empty($lookup_array))) {
  689. return PHPExcel_Calculation_Functions::REF();
  690. } else {
  691. $f = array_keys($lookup_array);
  692. $firstRow = array_pop($f);
  693. if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
  694. return PHPExcel_Calculation_Functions::REF();
  695. } else {
  696. $columnKeys = array_keys($lookup_array[$firstRow]);
  697. $firstkey = $f[0] - 1;
  698. $returnColumn = $firstkey + $index_number;
  699. $firstColumn = array_shift($f);
  700. }
  701. }
  702. if (!$not_exact_match) {
  703. $firstRowH = asort($lookup_array[$firstColumn]);
  704. }
  705. $rowNumber = $rowValue = false;
  706. foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) {
  707. if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) ||
  708. (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) {
  709. break;
  710. }
  711. $rowNumber = $rowKey;
  712. $rowValue = $rowData;
  713. }
  714. if ($rowNumber !== false) {
  715. if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
  716. // if an exact match is required, we have what we need to return an appropriate response
  717. return PHPExcel_Calculation_Functions::NA();
  718. } else {
  719. // otherwise return the appropriate value
  720. return $lookup_array[$returnColumn][$rowNumber];
  721. }
  722. }
  723. return PHPExcel_Calculation_Functions::NA();
  724. }
  725. /**
  726. * LOOKUP
  727. * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
  728. * @param lookup_value The value that you want to match in lookup_array
  729. * @param lookup_vector The range of cells being searched
  730. * @param result_vector The column from which the matching value must be returned
  731. * @return mixed The value of the found cell
  732. */
  733. public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null)
  734. {
  735. $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
  736. if (!is_array($lookup_vector)) {
  737. return PHPExcel_Calculation_Functions::NA();
  738. }
  739. $lookupRows = count($lookup_vector);
  740. $l = array_keys($lookup_vector);
  741. $l = array_shift($l);
  742. $lookupColumns = count($lookup_vector[$l]);
  743. if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
  744. $lookup_vector = self::TRANSPOSE($lookup_vector);
  745. $lookupRows = count($lookup_vector);
  746. $l = array_keys($lookup_vector);
  747. $lookupColumns = count($lookup_vector[array_shift($l)]);
  748. }
  749. if (is_null($result_vector)) {
  750. $result_vector = $lookup_vector;
  751. }
  752. $resultRows = count($result_vector);
  753. $l = array_keys($result_vector);
  754. $l = array_shift($l);
  755. $resultColumns = count($result_vector[$l]);
  756. if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
  757. $result_vector = self::TRANSPOSE($result_vector);
  758. $resultRows = count($result_vector);
  759. $r = array_keys($result_vector);
  760. $resultColumns = count($result_vector[array_shift($r)]);
  761. }
  762. if ($lookupRows == 2) {
  763. $result_vector = array_pop($lookup_vector);
  764. $lookup_vector = array_shift($lookup_vector);
  765. }
  766. if ($lookupColumns != 2) {
  767. foreach ($lookup_vector as &$value) {
  768. if (is_array($value)) {
  769. $k = array_keys($value);
  770. $key1 = $key2 = array_shift($k);
  771. $key2++;
  772. $dataValue1 = $value[$key1];
  773. } else {
  774. $key1 = 0;
  775. $key2 = 1;
  776. $dataValue1 = $value;
  777. }
  778. $dataValue2 = array_shift($result_vector);
  779. if (is_array($dataValue2)) {
  780. $dataValue2 = array_shift($dataValue2);
  781. }
  782. $value = array($key1 => $dataValue1, $key2 => $dataValue2);
  783. }
  784. unset($value);
  785. }
  786. return self::VLOOKUP($lookup_value, $lookup_vector, 2);
  787. }
  788. }