'Get field data when using Spout to read an Excel file

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!



Solution 1:[1]

$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!

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrien
Solution 2 Pavel Smirnov