如何在 laravel 7 中导入 CSV?

how to import CSV in laravel 7?

如何在 laravel 7?

中导入格式类似于此图像的 CSV 文件

之前,我能够创建一个功能来导入 xls 或 xlsx 格式的 excel 文件,现在我想将其设为 CSV 格式,如上所示。使用我创建的如下代码,导入 csv 文件时总是出现错误:“Undefined offset: 1”。

控制器

    public function import(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|mimes:csv'
        ]);

        if ($validator->fails()) {
            return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
        }

        $data = new BookedVoucher();

        $data->name = $request->name;
        $fileName = time().'_'.$request->file->getClientOriginalName();
        $filePath = $request->file('file')->storeAs('reports', $fileName, 'public');

        $data->file = $filePath;
        $data->created_by = \Auth::user()->id;

        if ($data->save()) {
            
            // Excel::queueImport(new BookedVoucherDetailImport($data), $request->file('file'));
            Excel::queueImport(new BookedVoucherDetailImport($data),$request->file('file'), \Maatwebsite\Excel\Excel::CSV);
        }
        
        return redirect()->back()->with('success','Data was imported successfully.');
    }

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

Blade

<form action="{{ route('booked.import')}}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group">
        <label for="name">Name</label>
        <input name="name" type="text" class="form-control" required>
    </div>
    <div class="form-group">
        <label for="file">File</label>
        <input name="file" type="file" class="form-control" required>
    </div>
    <button type="submit" class="btn btn-primary">Import</button>
</form>

请帮忙,如何导入该格式的 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();

从数据库导入导出 Excel 或 CSV 是管理项目的主要要求。在本教程中,我将向您展示如何在 Laravel 6 应用程序中使用 maatwebsite/excel 版本 3 导入 CSV 或 Excel 文件以及导出 CSV 或 Excel 文件。

laravelcode.com/post/import-and-export-excel-file-in-laravel-7

这个问题,已经解决了。我使用了定界符并且它有效。谢谢大家

https://docs.laravel-excel.com/3.1/imports/custom-csv-settings.html