Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an Excel row as an array: Does PHPExcel have a fgetcsv() equivalent?

I'm revamping some CSV reading code with the PHPExcel library, and am running into problems iterating through a datasheet.

My code:

$filetype = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($filetype);
$xl = $objReader->load($filename);
$objWorksheet = $xl->getActiveSheet();

foreach($objWorksheet->getRowIterator() as  $rowIndex => $row){
    print_r($row);
}

I'd rather not convert the entire worksheet to an array before iteration because some of my Excel files could be quite large and I'd rather avoid massive memory usage.

What I expected: For $row to return an array of all cells in that row.

What I got: $row is a PHPExcel object with the cells in that row.

Is there an fgetcsv() equivalent in PHPExcel that will let me get an array of all cells in a row?

like image 763
caitlin Avatar asked Dec 11 '15 19:12

caitlin


1 Answers

Yes, when you're using a Row Iterator, then that will return a PHPExcel_Worksheet_Row object for each row in turn; you can then iterate over that row object ($row) using a Cell Iterator (see /Example/28iterator.php)

foreach($objWorksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(true);
    // Iterate over the individual cells in the row
    foreach ($cellIterator as $cell) {
        // Display information about the cell object
        echo 'I am Cell ' , $cell->getCoordinate() , PHP_EOL;
        echo '    and my value is ' , $cell->getValue() , PHP_EOL;
    }
}

Or alternatively, you can convert that row to an array rather than use the Cell Iterator

$lastColumn = $objWorksheet->getHighestColumn();
foreach($objWorksheet->getRowIterator() as $rowIndex => $row) {
    // Convert the cell data from this row to an array of values
    //    just as though you'd retrieved it using fgetcsv()
    $array = $objWorksheet->rangeToArray('A'.$rowIndex.':'.$lastColumn.$rowIndex);
}

and as $array is simply an array of the cells in a single row, it will only take up as much memory as a row retrieved using a fgetcsv() call would have done

like image 179
Mark Baker Avatar answered Nov 05 '22 04:11

Mark Baker