忽略 Laravel-Excel Maatwebsite 中的列导入

Ignore Column Import in Laravel-Excel Maatwebsite

我可以忽略在 Laravel-Excel Maatwebsite 中导入的 Excel 列吗?

我的例子有一列 A B C D E F G H。 但是我有 4 种不同的 excel 文件类型,即:

我试过在 ExcelImport 中使用 WithHeadingRow,但是当我导入文件 1 时的响应是 Undefined index: header_D.

在我的Excel控制器中:

Excel::Import(new \App\Imports\ExcelImport,$request->file('file'));
        return redirect('/excel')->with("sukses","Data profiling berhasil di import");

在我的Excel导入中:

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'],
            ]);
            
        }
    }

文件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|

试试这个

它基于文档,应该可以参考 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;
    }
}