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 等。app

        • *

2. 導出到 PDF,HTML,或是其餘格式的文件

雖然包的名稱是 Laravel Excel,可是提供了多種導出格式,而且使用起來十分簡單,只要在類裏再添加一個參數便可:composer

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

好比這麼作,就導出到了HTML,以下圖所示:dom

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...

更多文章: https://learnku.com/laravel/c...
相關文章
相關標籤/搜索