Excel在导入之前获取总行数

Excel在导入之前获取总行数

本文介绍了Laravel Excel在导入之前获取总行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直截了当的问题.使用laravel-excel如何获取电子表格中的总行数?

Straight forward question. How does one get the total number of rows in a spreadsheet with laravel-excel?

现在我有了一个工作计数器,可以处理多少行(在CompanyImport文件中),但是在开始将行添加到数据库之前,我需要总行数.

I now have a working counter of how many rows have been processed (in the CompanyImport file), but I need the total number of rows before I start adding the rows to the database.

我要导入的工作表将近100万行,因此我正在尝试创建进度条.

The sheet I'm importing is almost 1M rows, so I am trying to create a progress bar.

我的导入:

public function model(array $row)
{
    # Counter
    ++$this->currentRow;

    # Dont create or validate on empty rows
    # Bad workaround
    # TODO: better solution
    if (!array_filter($row)) {
        return null;
    }

    # Create company
    $company = new Company;
    $company->crn = $row['crn'];
    $company->name = $row['name'];
    $company->email = $row['email'];
    $company->phone = $row['phone'];
    $company->website = (!empty($row['website'])) ? Helper::addScheme($row['website']) : '';
    $company->save();

    # Everything empty.. delete address
    if (!empty($row['country']) || !empty($row['state']) || !empty($row['postal']) || !empty($row['address']) || !empty($row['zip'])) {

        # Create address
        $address = new CompanyAddress;
        $address->company_id = $company->id;
        $address->country = $row['country'];
        $address->state = $row['state'];
        $address->postal = $row['postal'];
        $address->address = $row['address'];
        $address->zip = $row['zip'];
        $address->save();

        # Attach
        $company->addresses()->save($address);

    }

    # Update session counter
    Session::put('importCurrentRow', $this->currentRow);

    return $company;

}

我的控制器:

public function postImport(Import $request)
{
    # Import
    $import = new CompaniesImport;

    # Todo
    # Total number of rows in the sheet to session
    Session::put('importTotalRows');

    #
    Excel::import($import, $request->file('file')->getPathname());

    return response()->json([
        'success' => true
    ]);
}

推荐答案

您可以使用以下代码计算行数

You can use below code to calculate number of rows

Excel::import($import, 'users.xlsx');

dd('Row count: ' . $import->getRowCount());

您可以检查文档

更新

上述方法用于计算到目前为止已导入的行.为了获得工作表中的行数,您需要使用getHighestRow

The above method was for calculating the rows which have been imported so far.In order to get number of rows which are in the sheet, you need to use getHighestRow

    Excel::load($file, function($reader) {
        $lastrow = $reader->getActiveSheet()->getHighestRow();
        dd($lastrow);
    });

的作者在此处对此进行了引用.插件.

This has been referenced here by author of the Plugin.

这篇关于Laravel Excel在导入之前获取总行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:43