Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel search cell by value

Tags:

php

phpexcel

I'm wondering, how it's possible to help with such issue. Let's say, I have an excel with such info in it (it could be much more info):

**Country**            **Currency**
Germany                 EUR    
USA                     USD    
Russia                  RUB

and I'm entering in input form "USA", and I want to see the result USD from excel. Is there some kind of function in PHP, which allows to search for a value in excel?

Or at least, if there existing such function, which returns in which cell (e.g. B2) such value exists?

like image 217
Yuriy T. Avatar asked Jan 20 '15 12:01

Yuriy T.


1 Answers

There's nothing built-in to PHPExcel to do a search, but it's pretty straightforward to write something yourself based around the iterators.... take a look at 28iterator.php in /Examples

$foundInCells = array();
$searchValue = 'USA';
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    $ws = $worksheet->getTitle();
    foreach ($worksheet->getRowIterator() as $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(true);
        foreach ($cellIterator as $cell) {
            if ($cell->getValue() == $searchValue) {
                $foundInCells[] = $ws . '!' . $cell->getCoordinate();
            }
        }
    }
}
var_dump($foundInCells);

Of course, if you're only wanting to search a specific column in a specific worksheet, you can simplify this a great deal, e.g. using rangeToArray() and then searching the array using standard PHP array functions.

like image 112
Mark Baker Avatar answered Sep 28 '22 15:09

Mark Baker