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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With