【问题标题】:Undefined Index in Maatwebsite ExcelMaatwebsite Excel 中的未定义索引
【发布时间】:2021-06-01 03:05:57
【问题描述】:

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

错误:未定义索引: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 图片

有人可以指导我吗?

【问题讨论】:

    标签: laravel import-from-excel maatwebsite-excel


    【解决方案1】:

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

    【讨论】:

    • 非常感谢。有效。同样在 CustomerImport.php 我正在使用 foreach 循环。我不得不删除它。否则它会多次保存相同的数据。
    猜你喜欢
    • 2019-01-28
    • 2021-02-06
    • 1970-01-01
    • 2019-11-02
    • 2018-10-28
    • 2019-10-15
    • 1970-01-01
    • 2018-11-09
    • 2021-10-13
    相关资源
    最近更新 更多