Maatwebsite 中的未定义索引 Excel

Undefined Index in Maatwebsite Excel

我正在尝试将 Excel 数据导入 Laravel 并插入到数据库中。我正在使用 maatwebsite/excel 版本 3 作曲家包。

错误:未定义索引:customer_name

Blade 文件:import_excel.blade.php

<form method="post" enctype="multipart/form-data" action="{{ url('/import_excel/import') }}">
    {{ csrf_field() }}
    <div class="form-group">
        <table class="table">
            <tr>
                <td width="40%" align="right"><label>Select File for Upload</label></td>
                <td width="30">
                    <input type="file" name="select_file" />
                </td>
                <td width="30%" align="left">
                    <input type="submit" name="upload" class="btn btn-primary" value="Upload">
                </td>
            </tr>
            <tr>
                <td width="40%" align="right"></td>
                <td width="30"><span class="text-muted">.xls, .xslx</span></td>
                <td width="30%" align="left"></td>
            </tr>
        </table>
    </div>
</form>

导入文件:CustomerImport.php

public function model(array $row)
{
    $data = [];

    foreach ($row as $value)
    {
        $data[] = array(
            'CustomerName' => $row['customer_name'],
            'Gender' => $row['gender'],
            'Address' => $row['address'],
            'City' => $row['city'],
            'PostalCode' => $row['postal_cole'],
            'Country' => $row['country']
        );
    }
    
    DB::table('customers')->insert($data);
}

控制器功能

public function import(Request $request)
{
    $this->validate($request, [
        'select_file' => 'required|mimes:xls,xlsx'
    ]);

    $path = $request->file('select_file')->getRealPath();

    Excel::import(new CustomerImport, $path);
    return back()->with('success','Excel Data Imported successfully.');
}

Excel 图片

有人可以指导我吗?

要使用 heading row 你需要像这个例子一样实现 WithHeadingRow

namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UsersImport implements ToModel, WithHeadingRow
{
    public function model(array $row)
    {
        return new User([
            'name'  => $row['name'],
            'email' => $row['email'],
            'at'    => $row['at_field'],
        ]);
    }
}