I am importing Excel Sheet using Excel::import Maatwebsite / Laravel Excel 3.1.
Controller
$sheet = Excel::toArray(new UsersImport(), $request->file('stock_file'),
null,\Maatwebsite\Excel\Excel::XLSX);
UserImport.php
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Cell;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
class UsersImport implements ToModel, WithCalculatedFormulas, SkipsEmptyRows
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
//
]);
}
public function sheets(): array
{
return ['0'];
}
public function collection(Collection $rows)
{
$sheet_data = $rows->toArray();
}
}
Result
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => Image
[2] => View
[3] => 7.84
[4] => 7.87
)
Expected
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => https://google.com
[2] => https://laravel.com
[3] => 7.84
[4] => 7.87
)

The solution is in a comment in your code.
$url = $cellPHPOffice->getHyperlink()->getUrl(); // Cell URL: works ONLY with excel.imports.read_only => false
Before calling the Excel facade, you must set the false value to the excel.imports.read_only config.
Controller:
config(['excel.imports.read_only' => false]);
$usersImport = new UsersImport();
Excel::import($usersImport, '*****REPLACE_HERE_WITH_FILE_PATH*****');
dd($usersImport->getCells());
UsersImport:
<?php
namespace App\Imports;
use Maatwebsite\Excel\Cell;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Row;
class UsersImport implements OnEachRow, SkipsEmptyRows
{
protected $cells = [];
public function getCells(): array
{
return $this->cells;
}
public function onRow(Row $row)
{
$cells = [];
foreach ($row->getDelegate()->getCellIterator() as $cell) {
$cellObj = new Cell($cell);
$cellPHPOffice = $cellObj->getDelegate();
if ($cellPHPOffice->hasHyperlink()) {
$cells[] = $cellPHPOffice->getHyperlink()->getUrl();
} else {
$cells[] = $cellPHPOffice->getValue();
}
}
$this->cells[] = $cells;
}
}
Note: I used the "SkipsEmptyRows" interface. You can remove it if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With