5

I'm using Spout to read an Excel file. Here is what my Excel looks like:

enter image description here

I tried doing this with some basic code from the Spout documentation:

$filePath = '/Users/nhathao/Desktop/employee-test.xlsx';
    $reader = ReaderEntityFactory::createXLSXReader();
    //$reader = ReaderFactory::create(Type::XLSX);
    $reader->open($filePath);

    foreach ($reader->getSheetIterator() as $sheet) {
        foreach ($sheet->getRowIterator() as $row) {
            echo "<pre>";
            print_r($row->getCells());
            echo "</pre>";
        }
    }

When I run that, I get the following data from the cells:

enter image description here

Is there any way to access these fields? Could I use something like $row->email? I want to get that value and store it in a variable to compare it with my value in database.

Hope you can help me!

Thank you very much!

DavidHyogo
  • 2,838
  • 4
  • 31
  • 48
Tomato
  • 759
  • 2
  • 14
  • 26

2 Answers2

12

$row->getCells returns an array of Cells. You can access the value of each cell by calling $cell->getValue() on it.

In your case, if you want the email field, there's no magic mapping. If the email column is the 5th column, then you can do:

$cells = $row->getCells();
$emailCell = $cells[4]; // 4 because first column is at index 0.
$email = $emailCell->getValue();

Hope that helps!

Adrien
  • 1,929
  • 1
  • 13
  • 23
5

You can get value simply converting a row to an array. Assume you want to get the value of name. As you see the index of name is 1. What you have to do is:

foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        $value = $row->toArray();
        $name = $value[1];
    }
}

Hope it'll help you.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
Najmus Sakib
  • 737
  • 8
  • 12