laravelspout

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

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