使用laravel excel和laravel队列导入大型excel文件

时间:2019-03-05 07:05:52

标签: excel laravel

laravel excel 3.1版 laravel 5.6版 我在excel文件中有超过100000行数据。我想将此数据导入我的数据库。

在“我的controller.php”中

if(request()->file('fertilizer_import')) {
    $import = new FertilizerImport();
    $file = request()->file('fertilizer_import');
    dispatch(new FertilizerImportJob($import, $file));
}

在我的FertilizerImportJob.php

public function __construct($import, $file)
{
    $this->import = $import;
    $this->file = $file;
}
public function handle()
{
    Excel::import($this->import, $this->file);
}

然后,我上传了我的Excel文件。在作业表中输入一行。我运行php artisan make:queue,但数据未输入肥料表。 我怎样才能做到这一点?请给我建议。

1 个答案:

答案 0 :(得分:0)

您应该尝试在laravel / Maatwebsite中使用块和队列 在控制器文件中

public function importExcel()
    {
        $path = resource_path() . "/Houten.xlsx";
        \Excel::import(new TestImport, $path);
        return redirect('/')->with('success', 'All good!');
    return back();
    }

在您的导入文件中app / Imports / testImports.php

use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class TestImport implements ToCollection, WithChunkReading, ShouldQueue,WithStartRow
{
    public function collection(Collection $rows)
    {
        //do your insertion here. //no seprate job required
    }

     public function startRow(): int 
    {
         return 1;
    }

    public function batchSize(): int
    {
        return 500;
    }

    public function chunkSize(): int
    {
        return 500;
    }
}

然后设置QUEUE_DRIVER = database并运行代码。您将在作业表中看到一个条目。那么您需要运行此作业。有多种方法可以运行任何作业。下面是一个 在您的终端中

php artisan queue:restart
php artisan queue:listen

这将分块执行收集功能中的代码,并将插入您的数据。