你知道Laravel Excel的這五個功能嗎?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

laravel excel package 最近發布了 3.0 版本,它所具有的新功能,可以幫助簡化高級需求,并且可用性極高。大家一起來探討一下可能不知道的一些隱藏功能,這些功能使 laravel excel 成為 excel 拓展的最佳首選。

1. 從 HTML 或者是 Blade 導入數據

假設已經有一個 HTML 表格

你知道Laravel Excel的這五個功能嗎?

模版代碼 —?resources/views/customers/table.blade.php:

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

你可以使用它去重復導入這個表格到 Excel

步驟1. 生成一個 Export 類

php artisan make:export CustomersFromView --model=Customer

步驟2. 使用 FromView 進行操作

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

這里是導入的 Excel 文件:

你知道Laravel Excel的這五個功能嗎?

注意:這里只能導出 HTML 表格,不能具有任何標簽,比如 html,body,p 等。


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

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

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

比如這么做,就導出到了HTML,如下圖所示:

你知道Laravel Excel的這五個功能嗎?

沒有太多的樣式,下面是源代碼:

你知道Laravel Excel的這五個功能嗎?

不僅如此,它還可以導出到 PDF,甚至你可以從中選擇三種庫,使用方法是一樣的,你只要在最后一個參數指定格式就好了,下面是一些例子。?文檔示例:

你知道Laravel Excel的這五個功能嗎?

注意:你必須通過 composer 安裝指定的 PDF 包,比如:

composer require dompdf/dompdf

導出的 PDF 如下所示:

你知道Laravel Excel的這五個功能嗎?


3. 按需格式化單元格

Laravel Excel 有一個強有力的「爸爸」 —?PhpSpreadsheet。因此它就擁有其各種底層功能,包括各種方式的單元格格式化。

此處是一個如何在 Laravel Export 類中使用它的例子,例如?app/Exports/CustomersExportStyling.php:

步驟 1.?在頭部引入適當的類。

use MaatwebsiteExcelConcernsWithEvents; use MaatwebsiteExcelEventsAfterSheet;

步驟 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' => PhpOfficePhpSpreadsheetStyleBorder::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);         },     ]; }

這些「隨機」樣例展示的結果如下所示:

你知道Laravel Excel的這五個功能嗎?

你可以在?Recipes page of PhpSpreadsheet docs中找到所有的以上以及更多示例。


4. 隱藏模型屬性

假設我們已經創建了Laravel 5.7默認的users表:

你知道Laravel Excel的這五個功能嗎?

現在我們嘗試用簡單的FromCollection來導出用戶表數據:

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

在導出的Excel 里,你只能看到如下字段,但是沒有password和remember_token:

你知道Laravel Excel的這五個功能嗎?

這是因為在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 AppCustomer; use MaatwebsiteExcelConcernsFromCollection; use MaatwebsiteExcelConcernsWithMapping;  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,         ];     } }

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享