Search code examples
excellaravelcelllaravel-excel

Laravel Excel get importing cell access with URL


I'm working with Laravel 8 and Laravel Excel 3.1 on importing the sheet and there is no way to access to the current Cell object and its Hyperlink/URL there.


Solution

  • There is the solution! Use Laravel Excel Import-to-model with OnEachRow interface: Handling persistence on your own and code little bit more

    <?php
    //call your import script
    config(['excel.imports.read_only' => false]); // to get access to all of the cells content
    \Maatwebsite\Excel\Facades\Excel::import(new \App\Imports\Sheet1, $xlsFile);
    

    Laravel Excel Import class:

    <?php
    namespace App\Imports;
    use Maatwebsite\Excel\Cell;
    use Maatwebsite\Excel\Row;
    use Maatwebsite\Excel\Concerns\OnEachRow;
    
    class Sheet1 implements OnEachRow
    {
        public function onRow(Row $row)
        {
            foreach ($row->getDelegate()->getCellIterator() as $cell) {
                $cellObj = new Cell($cell); //Laravel Facade Cell Object
                $cellPHPOffice = $cellObj->getDelegate(); // PHP SpreadsheetCell object
                if ($cellPHPOffice->hasHyperlink()) {
                    $url = $cellPHPOffice->getHyperlink()->getUrl(); // Cell URL: works ONLY with excel.imports.read_only => false
                }
            }
        }
    }