Laravel Excel 的五个隐藏功能

file

Laravel Excel package 最近发布了 3.0 版本,它所具备的新功能,能够帮助简化高级需求,而且可用性极高。你们一块儿来探讨一下可能不知道的一些隐藏功能,这些功能使 Laravel Excel 成为 Excel 拓展的最佳首选。php

1. 从 HTML 或者是 Blade 导入数据

假设已经有一个 HTML 表格html

file

模版代码 -- resources/views/customers/table.blade.php:laravel

<table class="table">
    <thead>
    <tr>
        <th></th>
        <th>First name</th>
        <th>Last name</th>
        <th>Email</th>
        <th>Created at</th>
        <th>Updated at</th>
    </tr>
    </thead>
    <tbody>
    @foreach ($customers as $customer)
    <tr>
        <td>{{ $customer->id }}</td>
        <td>{{ $customer->first_name }}</td>
        <td>{{ $customer->last_name }}</td>
        <td>{{ $customer->email }}</td>
        <td>{{ $customer->created_at }}</td>
        <td>{{ $customer->updated_at }}</td>
    </tr>
    @endforeach
    </tbody>
</table>

复制代码

你可使用它去重复导入这个表格到 Excelgit

步骤1. 生成一个 Export 类github

php artisan make:export CustomersFromView --model=Customer

复制代码

步骤2. 使用 FromView 进行操做web

namespace App\Exports;

use App\Customer;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class CustomersExportView implements FromView
{
    public function view(): View
    {
        return view('customers.table', [
            'customers' => Customer::orderBy('id', 'desc')->take(100)->get()
        ]);
    }
}

复制代码

这里是导入的 Excel 文件:数组

file

注意:这里只能导出 HTML 表格,不能具备任何标签,好比 html,body,div 等。bash


2. 导出到 PDF,HTML,或是其余格式的文件

虽然包的名称是 Laravel Excel,可是提供了多种导出格式,而且使用起来十分简单,只要在类里再添加一个参数便可:app

return Excel::download(new CustomersExport(), 'customers.xlsx', 'Html');

复制代码

好比这么作,就导出到了HTML,以下图所示:composer

file

没有太多的样式,下面是源代码:

file

不只如此,它还能够导出到 PDF,甚至你能够从中选择三种库,使用方法是同样的,你只要在最后一个参数指定格式就行了,下面是一些例子。 文档示例:

file

注意:你必须经过 composer 安装指定的 PDF 包,好比:

composer require dompdf/dompdf

复制代码

导出的 PDF 以下所示:

file


3. 按需格式化单元格

Laravel Excel 有一个强有力的「爸爸」 -- PhpSpreadsheet。所以它就拥有其各类底层功能,包括各类方式的单元格格式化。

此处是一个如何在 Laravel Export 类中使用它的例子,例如 app/Exports/CustomersExportStyling.php:

步骤 1. 在头部引入适当的类。

use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;

复制代码

步骤 2. 在 implements 部分使用 WithEvents 接口。

class CustomersExportStyling implements FromCollection, WithEvents
{
    // ...

复制代码

步骤 3. 用 AfterSheet 事件来建立 registerEvents() 方法。

/**
 * @return array
 */
public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {
            // ... 此处你能够任意格式化
        },
    ];
}

复制代码

这里有个例子:

/**
 * @return array
 */
public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {
            // 全部表头-设置字体为14
            $cellRange = 'A1:W1';
            $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);

            // 将样式数组应用于B2:G8范围单元格
            $styleArray = [
                'borders' => [
                    'outline' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
                        'color' => ['argb' => 'FFFF0000'],
                    ]
                ]
            ];
            $event->sheet->getDelegate()->getStyle('B2:G8')->applyFromArray($styleArray);

            // 将第一行行高设置为20
            $event->sheet->getDelegate()->getRowDimension(1)->setRowHeight(20);

            // 设置 A1:D4 范围内文本自动换行
            $event->sheet->getDelegate()->getStyle('A1:D4')
                ->getAlignment()->setWrapText(true);
        },
    ];
}

复制代码

这些「随机」样例展现的结果以下所示:

file

你能够在 Recipes page of PhpSpreadsheet docs中找到全部的以上以及更多示例。


4. 隐藏模型属性

假设咱们已经建立了Laravel 5.7默认的users表:

file

如今咱们尝试用简单的FromCollection来导出用户表数据:

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

复制代码

在导出的Excel 里,你只能看到以下字段,可是没有passwordremember_token

file

这是由于在User模型里定义了隐藏字段的属性:

class User extends Authenticatable
{
    // ...

    /**
     * 这个数组用来定义须要隐藏的字段。
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

复制代码

因此,默认状况下这些字段是隐藏的,若是你想在导出数据的时候某些字段不被导出的话,能够直接在模型中定义隐藏属性$hidden


5. 公式

出于某种缘由,Laravel Excel 包的官方文档中并无说起公式,可是这是Excel 重要的功能!

幸运的是,咱们能够直接将公式写在导出数据的类中,咱们须要设置cell 的值,就像这样:=A2+1 or SUM(A1:A10)

其中一种方式就是实现WithMapping 接口:

use App\Customer;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;

class CustomersExportFormulas implements FromCollection, WithMapping
{
    public function collection()
    {
        return Customer::all();
    }

    /**
     * @var Customer $customer
     * @return array
     */
    public function map($customer): array
    {
        return [
            $customer->id,
            '=A2+1',
            $customer->first_name,
            $customer->last_name,
            $customer->email,
        ];
    }
}

复制代码

以上就是Laravel Excel的五个不为人知的功能。

文章转自: https://learnku.com/laravel/t/24161 更多文章:https://learnku.com/laravel/c/translations

相关文章
相关标签/搜索