gpt4 book ai didi

laravel - Maatwebsite Excel 中 undefined index

转载 作者:行者123 更新时间:2023-12-04 07:35:18 24 4
gpt4 key购买 nike

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

错误:未定义索引: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);
}

Controller 功能

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

关于laravel - Maatwebsite Excel 中 undefined index ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67782231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com