[SOLVED] Iteration over rows

Topics: User Forum
Jul 29, 2008 at 6:43 PM
Is there an easy way to iterate over rows when reading data from a spreadsheet?

So far, all I can find is something like:

$cells = $worksheet->getCellCollection();
foreach ($cells as $key => $cell) {
// do something
}

The problem is, I constantly have to examine $key to see if I'm in a new row.

Is there a way to end up with something like the following?

// give multidimensional array $rows
foreach ($rows as $row) {
foreach ($row as $cell) {
// do something with $cell
}
}

Thanks
Developer
Jul 29, 2008 at 8:25 PM
Maybe a construction like this will suffice:

for ($i = 1; $i <= $worksheet->getHighestRow(); $i++) {
    $cell = $worksheet->getCellByColumnAndRow(0, $i);
    // do something
}


Jul 29, 2008 at 11:49 PM
Thank you for your suggestion. For those interested, I also found another way to iterate over rows/cells when I was reminded that, in PHP, you can increment letters the same as numbers.

http://us2.php.net/manual/en/language.operators.increment.php

To echo out a column of values starting row 5:
<?php
$lastRow = $worksheet->getHighestRow();
$cells = $worksheet->getCellCollection();
for ($row = 5; $row <= $numRows; $row++) {
echo $cells["B$row"]->getValue();
}
?>

To echo out a row of values starting column C:
<?php
$numCols = $worksheet->getHighestColumn();
$cells = $worksheet->getCellCollection();
for ($col = 'C'; $col <= $numCols; $col++) {
echo $cells[$col . "5"]->getValue();
}
?>

To build an HTML table:
<table>
<?php
$lastRow = $worksheet->getHighestRow();
$lastCol = $worksheet->getHighestColumn();
$cells = $worksheet->getCellCollection();
for ($row = 1; $row <= $lastRow; $row++):
?>
<tr>
<?php for ($col = 'A'; $col <= $lastCol; $col++): ?>
<td><?php echo $cells[$col . $row]->getValue(); ?></td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</table>