微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Maatwebsite Excel 中的未定义索引

如何解决Maatwebsite Excel 中的未定义索引

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

错误:未定义索引:customer_name

刀片文件: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 图像

enter image description here

有人可以指导我吗?

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。