导入文件时如何跳过第一行

How to skip first row when importing file

我正在尝试使用 Maatwebsite-excel 版本 3.1 在 Laravel 版本 5.7 中导入一个 .xlsx 文件。我想要实现的是跳过文件的第一行以避免在我的数据库中导入列 headers。

我尝试使用版本 2 语法,调用 skip() 方法。

public function voter_import(Request $request)
{
    if (empty($request->file('file')->getRealPath())) 
    {
        return back()->with('success','No file selected');
    }
    else 
    {
        Excel::import(new VotersImport, $request->file('file'))->skip(1);
        return response('Import Successful, Please Refresh Page');
    }
}

class VotersImport implements ToModel
{
public function model(array $row)
   {
    return new Voter([
      'fname'          =>  $row[0],
      'lname'          =>  $row[1],
      'phone'          =>  $row[2],
      'gender'         =>  $row[3],
      'state'          =>  $row[4],
      'occupation'     =>  $row[5],
      'address'        =>  $row[6],
      'vin'            =>  $row[7],
      'dob'            =>  $row[8],
      'campaign_id'    =>  $row[9],
    ]);
   }
}

错误信息:

Call to undefined method Maatwebsite\Excel\Excel::skip()

您可以实现 StartingRow

use Maatwebsite\Excel\Concerns\WithStartRow;

class VotersImport implements ToModel, WithStartRow
{
    /**
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
}

另一种选择是使用 HeadingRow https://docs.laravel-excel.com/3.1/imports/heading-row.html

在加载 Excel 文件之前添加此代码。它对我有用。

config(['excel.import.startRow' => your_number_of_row_to_skip]);

例如:

$path = $request->file('select_file')->getRealPath();
config(['excel.import.startRow' => 4]);
$data = Excel::load($path)->get();