PhpSpreadsheet - get row without iterating on each cell

Jeremy Belolo picture Jeremy Belolo · Apr 1, 2018 · Viewed 21.6k times · Source

I'm using PhpSpreadsheet to easily read from a xls document and insert into a DB after some calculations. I succeeded using examples from the documentation, but I find it sooo complicated I'm sure I missed something and it can be done much more easily.

$worksheet = $this->getWorksheet("file.xls");
foreach ($worksheet->getRowIterator() as $row) {
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(FALSE);
  foreach ($cellIterator as $key => $cell) {
    $cellValue = $cell->getValue();

    if($key == 'A')
      $field1 = $cellValue;
    if($key == 'B') {
      $dateTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
      $date = $dateTime->format("Y-m-d");
    }
    if($key == 'C')
      $field2 = $cellValue;
    if($key == 'D')
      $field3 = $cellValue;
    if($key == 'E')
      $field4 = $cellValue;
  }
}

I would have expected something like $row->getCell("A")->getValue() to be available.

So... Have I missed something ?

Answer

saeed yadgari picture saeed yadgari · Feb 7, 2019

Hope this helps

$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5
for ($row = 1; $row <= $highestRow; ++$row) {
    for ($col = 1; $col <= $highestColumnIndex; ++$col) {
        $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
    }
}