get a cell value by name, not by coordinates

Topics: User Forum
Mar 5, 2010 at 10:16 PM

need to get a cell value by its name, as it can be done?

Coordinator
Mar 5, 2010 at 10:28 PM

Use getCell() passing in the name rather than a cell ID

Mar 6, 2010 at 8:46 AM

require_once './Classes/PHPExcel/IOFactory.php';
    
$objReader = PHPExcel_IOFactory::createReaderForFile("sumatorio.xlsx");
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("sumatorio.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();    
echo $objWorksheet->getCell('sumatorio1')->getValue()."<br />";
echo $objWorksheet->getCell('total')->getCalculatedValue();

Error:
Fatal error: Uncaught exception 'Exception' with message 'Column string index can not be longer than 3 characters.' in
 Z:\home\prueba\www\Classes\PHPExcel\Cell.php:640 Stack trace: #0 Z:\home\prueba\www\Classes\PHPExcel\Worksheet.php(996):
 PHPExcel_Cell::columnIndexFromString('SUMATORIO') #1 Z:\home\prueba\www\index.php(10): PHPExcel_Worksheet->getCell('sumatorio1')
 #2 {main} thrown in Z:\home\prueba\www\Classes\PHPExcel\Cell.php on line 640

Aug 15, 2014 at 1:23 AM
Edited Aug 15, 2014 at 1:25 AM
/**
 * Helper function to search for cell based on string contents.
 * @param PHPExcel_Worksheet worksheet- our haystack.
 * @param string needle - the contents we are searching for.
 * @return PHPExcel_Cell
 */
function getCellByContents($worksheet, $needle) {
    foreach($worksheet->getCellCollection(false) as $cellCoordinate) {
        $cell = $worksheet->getCell($cellCoordinate);
        
        if (strcmp($cell->getValue(), $needle) == 0) {
            return $cell;
        }        
    }
}
Usage
print_r(getCellByContents($spreadsheet->getActiveSheet(), 'This is my cell!'));