[Laravel-Excel中文文档] 实现Excel/CSV文件导出教程

Song1401 次浏览0个评论2022年03月05日

在上一篇文章我们介绍了maatwebsite/excel的安装以及导入Excel/Csv文件;接下来介绍如何使用Laravel-Excel实现导出。

Laravel使用maatwebsite/excel实现Excel/CSV文件导入导出及常见问题解决方案

Laravel-Excel实现导出

执行command命令快速创建导出代码:

php artisan make:export UsersExport --model=User

命令会在 app/Exports下创建

.
├── app
│   ├── Exports
│   │   ├── UsersExport.php
│ 
└── composer.json

其中UsersExport.php的代码如下

<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}

然后我们在控制器中执行如下代码即可导出全表,同时我们可以在上方加入筛选。

<?php

namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;

class UsersController extends Controller 
{
    public function export() 
    {
        return Excel::download(new UsersExport, users.xlsx);
    }
}

即可

如何向constructor传递参数

我们很多时候不可能导出全表,所以我们可以传递参数。

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromArray;

class InvoicesExport implements FromArray
{
    protected $invoices;

    public function __construct(array $invoices)
    {
        $this->invoices = $invoices;
    }

    public function array(): array
    {
        return $this->invoices;
    }
}

在控制器中我们可以使用如下方法向constructor传递参数

public function export() 
{
    $export = new InvoicesExport([
        [1, 2, 3],
        [4, 5, 6]
    ]);

    return Excel::download($export, invoices.xlsx);
}

自定义起始单元格

默认的起始单元格是A1。在导出类中实现WithCustomStartCell允许您指定自定义起始单元格。

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;

class InvoicesExport implements FromCollection, WithCustomStartCell
{
    public function collection()
    {
        return Invoice::all();
    }

    public function startCell(): string
    {
        return B2;
    }
}

导出格式

支持导出xlsx,csv,tsv,ods,html,mpdf等,具体参考导出格式文档

设置可导出格式

在上一个示例中,我们使用Excel::download facade启动导出。
Laravel Excel还提供了Maatwebsite\Excel\Concerns\Exportable特性,以使导出类可导出。同时还可以在constructor中设置导出配置。参考文档Exportables

从视图View导出

可以使用FromView从视图创建导出。参考From View

多表单导出

您可以参考 Multiple Sheets 实现多张表单导出。



提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文