php Laravel excel在导入前获取总行数

vjhs03f7  于 2022-12-17  发布在  PHP
关注(0)|答案(6)|浏览(244)

直截了当的问题:如何用laravel-excel得到电子表格的总行数?
现在我有了一个工作计数器,它显示已经处理了多少行(在CompanyImport文件中),但是在开始向数据库添加行之前,我需要知道总行数。
我导入的工作表几乎有1 M行,所以我尝试创建一个进度条。
我的导入:

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

cbjzeqam1#

在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'];
                }
            }
        ];
    }

    [...]
}
u7up0aaq

u7up0aaq2#

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

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

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

您可以查看单据

更新

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

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

插件的作者已在此处引用了该内容。

smtd7mpg

smtd7mpg3#

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

ldxq2e6h

ldxq2e6h4#

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

$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库

laximzn5

laximzn55#

检查以下示例:

$sheet->getActiveSheet()->getStyle('A2:A' . $sheet->getHighestRow())->getFont()->setBold(true);

通过使用**getHighestRow()**方法,你可以获取总行数。在上面的代码示例中,我将字体作为粗体应用于第一列的第二个单元格,直到相同的第一列的最大行数。

另一个示例的详细代码段:

$excel->sheet('Employee Details', function ($sheet) use ($AllData) {
                $sheet->fromArray($AllData);
                $sheet->setAutoSize(true);
                $sheet->getStyle('A2:A' . $sheet->getHighestRow())->applyFromArray(array('alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT)));
                
            });
bd1hkmkf

bd1hkmkf6#

通过此链接的文档,您可以计算受影响的行数
https://docs.laravel-excel.com/3.1/architecture/objects.html

相关问题