Get field data when using Spout to read an Excel file

9.7k Views Asked by At

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!

2

There are 2 best solutions below

2
Adrien On BEST ANSWER

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

0
Najmus Sakib On

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.