【问题标题】:Laravel excel get total number of rows before importLaravel excel在导入前获取总行数
【发布时间】:2019-09-15 08:24:11
【问题描述】:

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

我现在有一个已处理行数的工作计数器(在CompanyImport 文件中),但在开始将行添加到数据库之前,我需要总行数。

我正在导入的工作表将近 1M 行,所以我正在尝试创建一个进度条。

我的导入:

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

【问题讨论】:

标签: php laravel laravel-excel


【解决方案1】:

1.- 制作导入文件

php artisan make:import ImportableImport

2.- 您的文件导入

<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;

class ImportablesImport implements ToCollection
{

    use Importable;

    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        //
    }
}

3.- 你的控制器

$array = (new ImportablesImport)->toArray($file);
dd(count($array[0]));

此文档:https://docs.laravel-excel.com/3.1/imports/importables.html

【讨论】:

  • 一百万条记录到数组?你确定它有效吗?
【解决方案2】:

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

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

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

您可以查看Docs

更新

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

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

这已被插件作者引用here

【讨论】:

【解决方案3】:

在 Laravel Excel 3.1 中,您可以通过实现 WithEvents 并监听 beforeImport 事件来获取总行数。

<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeImport;

class UserImport extends ToModel, WithEvents {
    [...]

    public function registerEvents(): array
    {
        return [
            BeforeImport::class => function (BeforeImport $event) {
                $totalRows = $event->getReader()->getTotalRows();

                if (!empty($totalRows)) {
                    echo $totalRows['Worksheet'];
                }
            }
        ];
    }

    [...]
}

【讨论】:

  • 这应该是公认的答案:)
  • 这是一个更好的解决方案
【解决方案4】:

您可以使用以下代码在导入前获取行数

$fileExtension     = pathinfo($file, PATHINFO_EXTENSION);
$temporaryFileFactory=new \Maatwebsite\Excel\Files\TemporaryFileFactory(
    config('excel.temporary_files.local_path', 
            config('excel.exports.temp_path', 
            storage_path('framework/laravel-excel'))
    ),
    config('excel.temporary_files.remote_disk')
);


$temporaryFile = $temporaryFileFactory->make($fileExtension);
$currentFile = $temporaryFile->copyFrom($file,null);            
$reader = \Maatwebsite\Excel\Factories\ReaderFactory::make(null,$currentFile);
$info = $reader->listWorksheetInfo($currentFile->getLocalPath());
$totalRows = 0;
foreach ($info as $sheet) {
    $totalRows+= $sheet['totalRows'];
}
$currentFile->delete();

取自 Laravel Excel 库的代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2020-03-23
    相关资源
    最近更新 更多