我想使用 CSV 格式创建 CSV 导入功能,如上图所示。使用我编写的代码如下,在导入 CSV 文件时,我总是收到错误:“未定义的偏移量:1”。
BookedVoucherDetailImport.php
<?php
namespace App\Imports;
use App\Model\BookedVoucher;
use App\Model\BookedVoucherDetail;
use App\Model\Voucher;
// use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithChunkReading;
class BookedVoucherDetailImport implements ToCollection, WithStartRow, WithChunkReading, ShouldQueue
{
/**
* @var BookedVoucher
*/
protected $bookedVoucher;
/**
* @param BookedVoucher $bookedVoucher
*/
public function __construct(BookedVoucher $bookedVoucher)
{
$this->bookedVoucher = $bookedVoucher;
}
/**
* @return int
*/
public function startRow(): int
{
return 2;
}
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function chunkSize(): int
{
return 1000;
}
public function collection(Collection $rows)
{
$data = BookedVoucher::latest()->first();
foreach ($rows as $row)
{
$item = new BookedVoucherDetail();
$item->booked_voucher_id = $this->bookedVoucher->id;
$item->course_code = $row[0];
$item->voucher_code = $row[1];
$item->prakerja_name = $row[2];
$voucher = Voucher::where('code', $row[1])->first();
// check the data in the voucher table
// and set the status in the BookedVoucherDetails table
if ($voucher && $voucher->claimed == 0 && $voucher->is_booked == 0) {
$item->status = 'OK';
} elseif ($voucher && $voucher->claimed == 0 && $voucher->is_booked == 1) {
$item->status = 'Already Booked';
} elseif ($voucher && $voucher->claimed == 1 && $voucher->is_booked == 0) {
$item->status = 'Already Claimed';
} elseif ($voucher && $voucher->claimed == 1 && $voucher->is_booked == 1) {
$item->status = 'Already Booked and Claimed';
} else {
$item->status = 'Not Found';
}
$item->save();
// check the voucher table.
// If the data exists, then update is_booked = 1.
if ($voucher) {
$voucher->update(['is_booked' => 1]);
}
}
}
}
在 Laravel 中导入具有上述示例格式的 CSV 文件的正确方法是什么?
由于没有$row[1]而导致的错误。 CSV 必须用逗号分隔。 在 BookedVoucherDetailImport 中试试这个
$item = new BookedVoucherDetail();
$item->booked_voucher_id = $this->bookedVoucher->id;
$item->course_code = expolde(';',$row)[0];
$item->voucher_code = expolde(';',$row)[1];
$item->prakerja_name = expolde(';',$row)[2];
$voucher = Voucher::where('code', expolde(';',$row)[1])->first();
这个问题就解决了。我已经使用了分隔符并且它有效。谢谢大家
https://docs.laravel-excel.com/3.1/imports/custom-csv-settings.html
从数据库导入导出 Excel 或 CSV 是管理项目的首要条件。在本教程中,我将向您展示如何在 Laravel 6 应用程序中利用 maatwebsite/excel 版本 3 导入 CSV 或 Excel 文件以及导出 CSV 或 Excel 文件。
laravelcode.com/post/import-and-export-excel-file-in-laravel-7