提问人:mawardyansyah rachman 提问时间:9/14/2020 最后编辑:kaya3mawardyansyah rachman 更新时间:8/14/2021 访问量:3269
忽略Laravel-Excel Maatwebsite中的列导入
Ignore Column Import in Laravel-Excel Maatwebsite
问:
我可以忽略 Laravel-Excel Maatwebsite 中的 Excel 列导入吗?
我的示例有一列 A、B、C、D、E、F、G、H。 但我有 4 种不同的 excel 文件类型,即:
- 文件 1,有一个列标题 A B C F G H
- 文件 2,有一个列标题 A B F G H
- 文件 3,有一个列标题 A B C D E F
- 文件 4,有一个列标题 A B C D E F G H
我尝试在ExcelImport中使用WithHeadingRow,但是当我导入文件1时的响应是Undefined index: header_D。
在我的ExcelController中:
Excel::Import(new \App\Imports\ExcelImport,$request->file('file'));
return redirect('/excel')->with("sukses","Data profiling berhasil di import");
在我的ExcelImport中:
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|
答:
0赞
Kamlesh Paul
9/14/2020
#1
试试这个
它基于文档,它应该可以工作 ref 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;
}
}
评论
0赞
mawardyansyah rachman
9/14/2020
感谢您的回答,我一直在使用 ToCollection,结果不在 excel 文件中的列标题将为 null。
评论