Laravel Excel package 最近發(fā)布了 3.0 版本,它所具有的新功能,可以幫助簡化高級需求,并且可用性極高。大家一起來探討一下可能不知道的一些隱藏功能,這些功能使 Laravel Excel 成為 Excel 拓展的最佳首選。
1. 從 HTML 或者是 Blade 導入數(shù)據(jù)
假設已經(jīng)有一個 HTML 表格
模版代碼 — 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 文件:
注意:這里只能導出 HTML 表格,不能具有任何標簽,比如 html,body,div 等。
2. 導出到 PDF,HTML,或是其他格式的文件
雖然包的名稱是 Laravel Excel,但是提供了多種導出格式,并且使用起來十分簡單,只要在類里再添加一個參數(shù)即可:
return Excel::download(new CustomersExport(), 'customers.xlsx', 'Html');
比如這么做,就導出到了HTML,如下圖所示:
沒有太多的樣式,下面是源代碼:
不僅如此,它還可以導出到 PDF,甚至你可以從中選擇三種庫,使用方法是一樣的,你只要在最后一個參數(shù)指定格式就好了,下面是一些例子。 文檔示例:
注意:你必須通過 composer 安裝指定的 PDF 包,比如:
composer require dompdf/dompdf
導出的 PDF 如下所示:
3. 按需格式化單元格
Laravel Excel 有一個強有力的「爸爸」 — PhpSpreadsheet。因此它就擁有其各種底層功能,包括各種方式的單元格格式化。
此處是一個如何在 Laravel Export 類中使用它的例子,例如 app/Exports/CustomersExportStyling.php:
步驟 1. 在頭部引入適當?shù)念悺?/p>
use MaatwebsiteExcelConcernsWithEvents; use MaatwebsiteExcelEventsAfterSheet;
步驟 2. 在 implements 部分使用 WithEvents 接口。
class CustomersExportStyling implements FromCollection, WithEvents { // ...
步驟 3. 用 AfterSheet 事件來創(chuàng)建 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); // 將樣式數(shù)組應用于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); }, ]; }
這些「隨機」樣例展示的結果如下所示:
你可以在 Recipes page of PhpSpreadsheet docs中找到所有的以上以及