12

I tried to find a way to just get a row using PHPExcel. After numerous searches on the internet, I only found a way to iterate over them, with an optional start row. This lead to the following solution:

foreach ($this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber) as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);

    foreach ($cellIterator as $cell) {
        echo $cell->getValue();
    }

    break;
}

but this feels a little ugly. Is there another way to do it?

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

2 Answers2

23

Yes!

$row = $this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber)->current();

$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);

foreach ($cellIterator as $cell) {
    echo $cell->getValue();
}

I don't remember if you are supposed to use next or current. If you are getting the wrong row, use current() instead of next().

Kirk Backus
  • 4,776
  • 4
  • 32
  • 52
  • Thanks, I thought it would be in that direction, just never knew about the methods used to cycle in `foreach`. – Bart Friederichs Jul 30 '13 at 19:13
  • PHPExcel's Row and Cell Iterator both implement the standard PHP [Iterator](http://www.php.net/manual/en/class.iterator.php) interface; so all standard Iterator methods - current(), key(), next(), rewind() and valid() - are available. Additionally, they also implement seek(), prev() and resetStart() methods, the latter being useful if you instantiated the iterator with a row or column value other than the first row or column – Mark Baker Jul 30 '13 at 19:21
  • does ther a possible to get an array directly instead of iterator – Aya Jun 11 '21 at 21:40
12
$myRow = 123;

$this->objPHPExcel->getActiveSheet()
    ->rangeToArray(
        'A' . $myRow . 
        ':' . 
        $this->objPHPExcel->getActiveSheet()->getHighestColumn() . $myRow
    );

will return the specified row as an array of cells

Mark Baker
  • 209,507
  • 32
  • 346
  • 385