Can I ignore Excel columns import in Laravel-Excel Maatwebsite?
My example has a column A B C D E F G H. But I have 4 different excel file types, namely:
I've tried using WithHeadingRow in ExcelImport, but the response when I imported file 1 was Undefined index: header_D.
in my ExcelController:
Excel::Import(new \App\Imports\ExcelImport,$request->file('file'));
return redirect('/excel')->with("sukses","Data profiling berhasil di import");
in my ExcelImport:
class ProfilingImport implements ToCollection, WithChunkReading, WithCalculatedFormulas, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
use Importable;
public function collection(Collection $collection)
{
$collection = $collection->toArray();
foreach ($collection as $key => $row){
if($key >= 2){
return Profiling::create([
'A' => $row['A'],
'B' => $row['B'],
'C' => $row['C'],
'D' => $row['D'],
'E' => $row['E'],
'F' => $row['F'],
'G' => $row['G'],
'H' => $row['H'],
]);
}
}
File Excel:
| A | B | C | G | H |
|111|523|585|785|789|
| A | B | F | G | H |
|785|556|712|368|782|
| A | B | C | D | E | F |
|524|756|624|765|522|446|
| A | B | C | D | E | F | G | H |
|123|456|789|012|345|678|901|234|
try this
it's based on doc it should work ref link https://docs.laravel-excel.com/3.1/imports/heading-row.html
<?php
namespace App\Imports;
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProfilingImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new Profiling([
'A' => $row['A'] ?? null ,
'B' => $row['B'] ?? null,
'C' => $row['C'] ?? null,
'D' => $row['D'] ?? null,
'E' => $row['E'] ?? null,
'F' => $row['F'] ?? null,
'G' => $row['G'] ?? null,
'H' => $row['H'] ?? null,
]);
}
public function headingRow(): int
{
return 2;
}
}