【问题标题】:how to skip the row about importing excel laravel with the Maatwebsite/Laravel-Excel如何跳过有关使用 Maatwebsite/Laravel-Excel 导入 excel laravel 的行
【发布时间】:2020-07-09 14:15:33
【问题描述】:

我在跳过有关使用 Maatwebsite / Laravel-Excel 包导入 excel laravel 的行时遇到问题。 网上试了很多方法还是不行。

这是我的控制器代码

if ($request->hasFile('file')) {
        $import = new HsatuImport();
        $file = $request->file('file'); //GET FILE
        // config(['excel.import.startRow' => 2]);
        Excel::import($import, $file)->limit(false, 2); //IMPORT FILE
        return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Berhasil '.$import->getRowCount().' Data');
    } else {
        return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Gagal');
    }

这是我的导入代码

<?php

namespace App\Imports;

use App\Models\Hsatu;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\ToModel;

class HsatuImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    private $rows = 0;
    public function model(array $row)
    {
        ++$this->rows;
        return new Hsatu([
            'region' => @$row[0],
            'nomor_faktur' => @$row[1],
            'nomor_rangka' => @$row[2],
            'kode_mesin' => @$row[3]
        ]);
    }

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

    public function getRowCount(): int
    {
        return $this->rows;
    }
}

【问题讨论】:

    标签: php excel laravel laravel-excel


    【解决方案1】:

    当已有 Eloquent 模型时,我遇到了跳过问题。所以在我的代码下面:

    public function model(array $row)
        {
            $name = $row['name'];
            if (!Category::where('name', $name)->exists())
                return new Category([
                    'name' => $name
                ]);
        }
    

    仅当给定语句为真时,我才会返回模型实例。

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 2020-08-28
      • 2021-10-08
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2019-05-20
      相关资源
      最近更新 更多