摘要:事件將通過(guò)添加關(guān)注來(lái)激活。自動(dòng)注冊(cè)事件監(jiān)聽(tīng)器通過(guò)使用,你可以自動(dòng)注冊(cè)事件監(jiān)聽(tīng)器,而不需要使用。你可以自由使用這個(gè)宏,或者創(chuàng)造你自己的語(yǔ)法以上例子可作對(duì)于方法可查看文檔測(cè)試測(cè)試下載測(cè)試存儲(chǔ)導(dǎo)出測(cè)試隊(duì)列導(dǎo)出
Basics
最簡(jiǎn)單的導(dǎo)出方法是創(chuàng)建一個(gè)自定義的導(dǎo)出類, 這里我們使用發(fā)票導(dǎo)出作為示例.
在 App/Exports 下創(chuàng)建一個(gè) InvoicesExport 類
namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; class InvoicesExport implements FromCollection { public function collection() { return Invoice::all(); } }
在控制器中你可以使用如下方式來(lái)下載
public function export() { return Excel::download(new InvoicesExport, "invoices.xlsx"); }
或者存儲(chǔ)在 s3 磁盤中
public function storeExcel() { return Excel::store(new InvoicesExport, "invoices.xlsx", "s3"); }依賴注入
如果你的導(dǎo)出需要依賴, 你可以注入導(dǎo)出類
namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; class InvoicesExport implements FromCollection { public function __construct(InvoicesRepository $invoices) { $this->invoices = $invoices; } public function collection() { return $this->invoices->all(); } }
public function export(Excel $excel, InvoicesExport $export) { return $excel->download($export, "invoices.xlsx"); }嚴(yán)格的 null 對(duì)比
如果你希望 0 在 excel 單元格中就是顯示 0, 而不是顯示 null(空單元格), 你可以使用 WithStrictNullComparison
namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; use MaatwebsiteExcelConcernsWithStrictNullComparison; class InvoicesExport implements FromCollection, WithStrictNullComparison { public function __construct(InvoicesRepository $invoices) { $this->invoices = $invoices; } public function collection() { return $this->invoices->all(); } }Collection 全局定義/宏
這個(gè)包提供了 laravel collection 的一些額外的方法(宏) 來(lái)簡(jiǎn)單的下載或者是存儲(chǔ)到 excel
把 collection 作為 Excel 下載(new Collection([[1, 2, 3], [1, 2, 3]]))->downloadExcel( $filePath, $writerType = null, $headings = false )在磁盤上存儲(chǔ) collection
(new Collection([[1, 2, 3], [1, 2, 3]]))->storeExcel( $filePath, $disk = null, $writerType = null, $headings = false )在磁盤上存儲(chǔ)導(dǎo)出
導(dǎo)出可以存儲(chǔ)到任何 Laravel 支持的 文件系統(tǒng)?中
public function storeExcel() { // Store on default disk Excel::store(new InvoicesExport(2018), "invoices.xlsx"); // Store on a different disk (e.g. s3) Excel::store(new InvoicesExport(2018), "invoices.xlsx", "s3"); // Store on a different disk with a defined writer type. Excel::store(new InvoicesExport(2018), "invoices.xlsx", "s3", Excel::XLSX); }Exportables / 可導(dǎo)出的
在之前的例子中, 我們使用 Excel::download 這個(gè) facade 來(lái)開(kāi)始一個(gè)導(dǎo)出.
Laravel-Excel 同樣支持 ?MaatwebsiteExcelConcernsExportable?trait, 來(lái)讓一個(gè)類可以直接導(dǎo)出, 當(dāng)然, 這個(gè)類里邊需要有 collection 方法.
namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; use MaatwebsiteExcelConcernsExportable; class InvoicesExport implements FromCollection { use Exportable; public function collection() { return Invoice::all(); } }
我們可以不通過(guò) facade 直接進(jìn)行類的下載
return (new InvoicesExport)->download("invoices.xlsx");
或者是存儲(chǔ)到磁盤上.
return (new InvoicesExport)->store("invoices.xlsx", "s3");Responsable / 可響應(yīng)的
之前的例子可以做的簡(jiǎn)單一點(diǎn), 例如我們添加 Laravel 的 Responsable 到導(dǎo)出類中
namespace AppExports; use IlluminateContractsSupportResponsable; use MaatwebsiteExcelConcernsFromCollection; use MaatwebsiteExcelConcernsExportable; class InvoicesExport implements FromCollection, Responsable { use Exportable; /** * It"s required to define the fileName within * the export class when making use of Responsable. */ private $fileName = "invoices.xlsx"; public function collection() { return Invoice::all(); } }
你可以更簡(jiǎn)單的返回導(dǎo)出類,但是不需要調(diào)用 ->download() 方法.
return new InvoicesExport();From Query / 從查詢輸出
在之前的例子中, 我們?cè)趯?dǎo)出類中進(jìn)行查詢, 當(dāng)然這個(gè)解決方案可以用在小的導(dǎo)出類中. 對(duì)于更大一點(diǎn)數(shù)據(jù)的導(dǎo)出類可能造成比較大的性能開(kāi)銷.
通過(guò)使用 FromQuery 關(guān)系, 我們可以通過(guò)預(yù)查詢一個(gè)導(dǎo)出, 這個(gè)場(chǎng)景實(shí)現(xiàn)的原理是查詢可以分塊執(zhí)行.
在 InvoicesExport 類中,添加 FromQuery 關(guān)系, 并且添加一個(gè)查詢, 并且確保不要使用 ->get() 來(lái)獲取到數(shù)據(jù)!.
namespace AppExports; use MaatwebsiteExcelConcernsFromQuery; use MaatwebsiteExcelConcernsExportable; class InvoicesExport implements FromQuery { use Exportable; public function query() { return Invoice::query(); } }
我們可以通過(guò)同樣的方式來(lái)下載
return (new InvoicesExport)->download("invoices.xlsx");自定義查詢
這種方式可以通過(guò)自定義的參數(shù)來(lái)進(jìn)行查詢. 簡(jiǎn)單的作為依賴項(xiàng)傳入導(dǎo)出類即可.
作為構(gòu)造器參數(shù)namespace AppExports; use MaatwebsiteExcelConcernsFromQuery; use MaatwebsiteExcelConcernsExportable; class InvoicesExport implements FromQuery { use Exportable; public function __construct(int $year) { $this->year = $year; } public function query() { return Invoice::query()->whereYear("created_at", $this->year); } }
$year 參數(shù)可以傳遞給導(dǎo)出類.
return (new InvoicesExport(2018))->download("invoices.xlsx");作為設(shè)置項(xiàng)
namespace AppExports; use MaatwebsiteExcelConcernsFromQuery; use MaatwebsiteExcelConcernsExportable; class InvoicesExport implements FromQuery { use Exportable; public function forYear(int $year) { $this->year = $year; return $this; } public function query() { return Invoice::query()->whereYear("created_at", $this->year); } }
我們可以通過(guò) forYear 方法來(lái)調(diào)整年份.
return (new InvoicesExport)->forYear(2018)->download("invoices.xlsx");通過(guò)視圖
我們可以通過(guò) blade 視圖來(lái)創(chuàng)建導(dǎo)出. 通過(guò)使用 FromView 關(guān)系.
namespace AppExports; use IlluminateContractsViewView; use MaatwebsiteExcelConcernsFromView; class InvoicesExport implements FromView { public function view(): View { return view("exports.invoices", [ "invoices" => Invoice::all() ]); } }
這種方式會(huì)導(dǎo)出一個(gè) Html 表格到 Excel 單元表, 例如 users.blade.php:
Name | |
---|---|
{{ $user->name }} | {{ $user->email }} |
如果你處理更大數(shù)據(jù)量的數(shù)據(jù), 很明智的方法就是使用隊(duì)列來(lái)運(yùn)行.
例如下邊的導(dǎo)出類:
namespace AppExports; use MaatwebsiteExcelConcernsExportable; use MaatwebsiteExcelConcernsFromQuery; class InvoicesExport implements FromQuery { use Exportable; public function query() { return Invoice::query(); } }
我們只需要調(diào)用一個(gè) ->queue()?方法即可.
return (new InvoicesExport)->queue("invoices.xlsx");
后臺(tái)處理這些查詢的方式是通過(guò)多任務(wù)/多切割的方式來(lái)進(jìn)行. 這些任務(wù)使用正確的順序來(lái)執(zhí)行. 并且保證之前的查詢都是正確的.
另一種方式的隊(duì)列實(shí)現(xiàn)你可以將導(dǎo)出作為一個(gè)可以扔到隊(duì)列中的實(shí)現(xiàn)(利用 Laravel), 可以使用 ShouldQueue 約束.
namespace AppExports; use MaatwebsiteExcelConcernsExportable; use MaatwebsiteExcelConcernsFromQuery; use IlluminateContractsQueueShouldQueue; class InvoicesExport implements FromQuery, ShouldQueue { use Exportable; public function query() { return Invoice::query(); } }
在控制器中可以調(diào)用普通的 ->store() 方法. 基于 ShouldQueue, 通過(guò) laravel 的隊(duì)列方式來(lái)實(shí)現(xiàn)隊(duì)列處理. [ps:你需要首先自行配置隊(duì)列]
return (new InvoicesExport)->store("invoices.xlsx");追加任務(wù) / jobs
?queue() 方法返回一個(gè) Laravel 的 ?PendingDispatch 實(shí)例, 這意味著你可以把其他的任務(wù)串聯(lián)起來(lái), 僅僅當(dāng)前一個(gè)任務(wù)執(zhí)行成功的時(shí)候, 后續(xù)的任務(wù)才能夠被執(zhí)行.
return (new InvoicesExport)->queue("invoices.xlsx")->chain([ new NotifyUserOfCompletedExport(request()->user()), ]);
namespace AppJobs; use IlluminateBusQueueable; use IlluminateContractsQueueShouldQueue; class InvoiceExportCompletedJob implements ShouldQueue { use Queueable; public function handle() { // Do something. } }自定義隊(duì)列
當(dāng) PendingDispatch 返回的時(shí)候, 我們可以改變我們使用的隊(duì)列.
return (new InvoicesExport)->queue("invoices.xlsx")->allOnQueue("exports");多單元表
為了能夠讓導(dǎo)出支持多單元表, 需要使用?WithMultipleSheets?關(guān)系來(lái)實(shí)現(xiàn). 這個(gè) sheets() 方法需要返回一個(gè)單元表數(shù)組.
namespace AppExports; use MaatwebsiteExcelConcernsExportable; use MaatwebsiteExcelConcernsWithMultipleSheets; class InvoicesExport implements WithMultipleSheets { use Exportable; protected $year; public function __construct(int $year) { $this->year = $year; } /** * @return array */ public function sheets(): array { $sheets = []; for ($month = 1; $month <= 12; $month++) { $sheets[] = new InvoicesPerMonthSheet($this->year, $month); } return $sheets; } }
這個(gè) InvoicesPerMonthSheet 可以實(shí)現(xiàn)多種關(guān)系. 例如 FromQuery,?FromCollection, ...
namespace AppExports; use MaatwebsiteExcelConcernsFromQuery; use MaatwebsiteExcelConcernsWithTitle; class InvoicesPerMonthSheet implements FromQuery, WithTitle { private $month; private $year; public function __construct(int $year, int $month) { $this->month = $month; $this->year = $year; } /** * @return Builder */ public function query() { return Invoice ::query() ->whereYear("created_at", $this->year) ->whereMonth("created_at", $this->month); } /** * @return string */ public function title(): string { return "Month " . $this->month; } }
以下可以下載 2018 年的所有的發(fā)票, 它包含 12 單元表來(lái)顯示每個(gè)月的數(shù)據(jù).
public function download() { return (new InvoicesExport(2018))->download("invoices.xlsx"); }數(shù)據(jù)遍歷 遍歷行
通過(guò)添加 ?WithMapping, 你可以遍歷添加到單元行中的每一條數(shù)據(jù)然后并返回.
這種方法你可以控制每一列的數(shù)據(jù), 假設(shè)你使用 Eloquent 的 query builder.
use MaatwebsiteExcelConcernsFromQuery; use MaatwebsiteExcelConcernsWithMapping; class InvoicesExport implements FromQuery, WithMapping { /** * @var Invoice $invoice */ public function map($invoice): array { return [ $invoice->invoice_number, Date::dateTimeToExcel($invoice->created_at), ]; } }添加表頭
可以通過(guò)添加一個(gè) ?WithHeadings?約束來(lái)實(shí)現(xiàn). 表頭會(huì)添加到所有數(shù)據(jù)的第一行的位置上.
use MaatwebsiteExcelConcernsFromQuery; use MaatwebsiteExcelConcernsWithHeadings; class InvoicesExport implements FromQuery, WithHeadings public function headings(): array { return [ "#", "Date", ]; } }格式化列
你可以格式化整列, 通過(guò)添加 WithColumnFormatting, 如果你想更多范圍的自定義. 推薦使用 AfterSheet 事件來(lái)直接和地城的?Worksheet 類進(jìn)行交互.
namespace AppExports; use PhpOfficePhpSpreadsheetSharedDate; use PhpOfficePhpSpreadsheetStyleNumberFormat; use MaatwebsiteExcelConcernsWithColumnFormatting; use MaatwebsiteExcelConcernsWithMapping; class InvoicesExport implements WithColumnFormatting, WithMapping { public function map($invoice): array { return [ $invoice->invoice_number, Date::dateTimeToExcel($invoice->created_at), $invoice->total ]; } /** * @return array */ public function columnFormats(): array { return [ "B" => NumberFormat::FORMAT_DATE_DDMMYYYY, "C" => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE, ]; } }日期
當(dāng)操作日期的時(shí)候. 推薦使用 PhpOfficePhpSpreadsheetSharedDate::dateTimeToExcel() 來(lái)正確的解析你的日期數(shù)據(jù).
導(dǎo)出關(guān)系Interface | Explanation |
---|---|
MaatwebsiteExcelConcernsFromCollection | Use a Laravel Collection to populate the export. |
MaatwebsiteExcelConcernsFromQuery | Use an Eloquent query to populate the export. |
MaatwebsiteExcelConcernsFromView | Use a (Blade) view to to populate the export. |
MaatwebsiteExcelConcernsWithTitle | Set the Workbook or Worksheet title. |
MaatwebsiteExcelConcernsWithHeadings | Prepend a heading row. |
MaatwebsiteExcelConcernsWithMapping | Format the row before it"s written to the file. |
MaatwebsiteExcelConcernsWithColumnFormatting | Format certain columns. |
MaatwebsiteExcelConcernsWithMultipleSheets | Enable multi-sheet support. Each sheet can have its own concerns (except this one). |
MaatwebsiteExcelConcernsShouldAutoSize | Auto-size the columns in the worksheet. |
MaatwebsiteExcelConcernsWithStrictNullComparison | Uses strict comparisions when testing cells for null value. |
MaatwebsiteExcelConcernsWithEvents | Register events to hook into the PhpSpreadsheet process. |
Trait | Explanation |
---|---|
MaatwebsiteExcelConcernsExportable | Add download/store abilities right on the export class itself. |
MaatwebsiteExcelConcernsRegistersEventListeners | Auto-register the available event listeners. |
導(dǎo)出過(guò)程有一些事件,你可以利用這些事件與底層類進(jìn)行交互,以向?qū)С鎏砑幼远x行為。
通過(guò)使用事件,您可以連接到父包。如果你需要完全控制導(dǎo)出,則不需要使用諸如 "query" 或者 "view" 之類的便利方法。
事件將通過(guò)添加 WithEvents 關(guān)注來(lái)激活。在 registerEvents 方法中,你必須返回一系列事件。Key 是事件的完全限定名(FQN),Value 是可調(diào)用的事件監(jiān)聽(tīng)器。這可以是一個(gè)閉包、可調(diào)用的數(shù)組 或 invokable 類。
namespace AppExports; use MaatwebsiteExcelConcernsWithEvents; use MaatwebsiteExcelEventsBeforeExport; use MaatwebsiteExcelEventsBeforeWriting; use MaatwebsiteExcelEventsBeforeSheet; class InvoicesExport implements WithEvents { /** * @return array */ public function registerEvents(): array { return [ // Handle by a closure. BeforeExport::class => function(BeforeExport $event) { $event->writer->getProperties()->setCreator("Patrick"); }, // Array callable, refering to a static method. BeforeWriting::class => [self::class, "beforeWriting"], // Using a class with an __invoke method. BeforeSheet::class => new BeforeSheetHandler() ]; } public static function beforeWriting(BeforeWriting $event) { // } }
請(qǐng)注意,使用 Closure?將不可能與隊(duì)列導(dǎo)出合并,因?yàn)镻HP不能序列化閉包。在這些情況下,最好使用 RegistersEventListeners 特性。
自動(dòng)注冊(cè)事件監(jiān)聽(tīng)器通過(guò)使用?RegistersEventListeners?trait ,你可以自動(dòng)注冊(cè)事件監(jiān)聽(tīng)器,而不需要使用 registerEvents 。只有在創(chuàng)建方法時(shí),偵聽(tīng)器才會(huì)被注冊(cè)。
namespace AppExports; use MaatwebsiteExcelConcernsWithEvents; use MaatwebsiteExcelConcernsRegistersEventListeners; use MaatwebsiteExcelEventsBeforeExport; use MaatwebsiteExcelEventsBeforeWriting; use MaatwebsiteExcelEventsBeforeSheet; use MaatwebsiteExcelEventsAfterSheet; class InvoicesExport implements WithEvents { use Exportable, RegistersEventListeners; public static function beforeExport(BeforeExport $event) { // } public static function beforeWriting(BeforeWriting $event) { // } public static function beforeSheet(BeforeSheet $event) { // } public static function afterSheet(AfterSheet $event) { // } }可用的事件
Event name | Payload | Explanation |
---|---|---|
MaatwebsiteExcelEventsBeforeExport | $event->writer : Writer | Event gets raised at the start of the process. |
MaatwebsiteExcelEventsBeforeWriting | $event->writer : Writer | Event gets raised before the download/store starts. |
MaatwebsiteExcelEventsBeforeSheet | $event->sheet : Sheet | Event gets raised just after the sheet is created. |
MaatwebsiteExcelEventsAfterSheet | $event->sheet : Sheet | Event gets raised at the end of the sheet process. |
Writer 和 Sheet 都是可以進(jìn)行宏操作的,這意味著它可以很容易地?cái)U(kuò)展以滿足你的需要。Writer 和 Sheet都有一個(gè) ->getDelegate() 方法,它返回底層的PhpSpreadsheet 類。這將允許你為 PhpSpreadsheets 方法添加快捷方法,而這個(gè)方法在這個(gè)包中是不可用的。
Writer / 寫入use MaatwebsiteExcelWriter; Writer::macro("setCreator", function (Writer $writer, string $creator) { $writer->getDelegate()->getProperties()->setCreator($creator); });Sheet / 單元表
use MaatwebsiteExcelSheet; Sheet::macro("setOrientation", function (Sheet $sheet, $orientation) { $sheet->getDelegate()->getPageSetup()->setOrientation($orientation); });
你還可以為樣式單元添加一些快捷方法。你可以自由使用這個(gè)宏,或者創(chuàng)造你自己的語(yǔ)法!
use MaatwebsiteExcelSheet; Sheet::macro("styleCells", function (Sheet $sheet, string $cellRange, array style) { $sheet->getDelegate()->getStyle($cellRange)->applyFromArray($style); });
以上例子可作:
namespace AppExports; use MaatwebsiteExcelConcernsWithEvents; use MaatwebsiteExcelEventsBeforeExport; use MaatwebsiteExcelEventsAfterSheet; class InvoicesExport implements WithEvents { /** * @return array */ public function registerEvents(): array { return [ BeforeExport::class => function(BeforeExport $event) { $event->writer->setCreator("Patrick"); }, AfterSheet::class => function(AfterSheet $event) { $event->sheet->setOrientation(PhpOfficePhpSpreadsheetWorksheetPageSetup::ORIENTATION_LANDSCAPE); $event->sheet->styleCells( "B2:G8", [ "borders" => [ "outline" => [ "borderStyle" => PhpOfficePhpSpreadsheetStyleBorder::BORDER_THICK, "color" => ["argb" => "FFFF0000"], ], ] ] ); }, ]; } }
對(duì)于 PhpSpreadsheet 方法, 可查看文檔:?https://phpspreadsheet.readthedocs.io/
測(cè)試 / TestingThe Excel facade can be used to swap the exporter to a fake.
測(cè)試下載/** * @test */ public function user_can_download_invoices_export() { Excel::fake(); $this->actingAs($this->givenUser()) ->get("/invoices/download/xlsx"); Excel::assertDownloaded("filename.xlsx", function(InvoicesExport $export) { // Assert that the correct export is downloaded. return $export->collection()->contains("#2018-01"); }); }測(cè)試存儲(chǔ)導(dǎo)出
/** * @test */ public function user_can_store_invoices_export() { Excel::fake(); $this->actingAs($this->givenUser()) ->get("/invoices/store/xlsx"); Excel::assertStored("filename.xlsx", "diskName"); Excel::assertStored("filename.xlsx", "diskName", function(InvoicesExport $export) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertStored("filename.xlsx", function(InvoicesExport $export) { return true; }); }測(cè)試隊(duì)列導(dǎo)出
/** * @test */ public function user_can_queue_invoices_export() { Excel::fake(); $this->actingAs($this->givenUser()) ->get("/invoices/queue/xlsx"); Excel::assertQueued("filename.xlsx", "diskName"); Excel::assertQueued("filename.xlsx", "diskName", function(InvoicesExport $export) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertQueued("filename.xlsx", function(InvoicesExport $export) { return true; }); }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/30731.html
摘要:關(guān)于的包的使用筆記關(guān)于安裝官網(wǎng)已經(jīng)很詳細(xì)了不再描述關(guān)于導(dǎo)入導(dǎo)入的話只有幾個(gè)小地方需要注意導(dǎo)入的時(shí)候會(huì)有產(chǎn)生一些的在循環(huán)遍歷導(dǎo)入的數(shù)據(jù)的時(shí)候主動(dòng)忽略關(guān)于中文或者亂碼問(wèn)題或者在配置文件在安裝這個(gè)模塊的文檔有介紹怎么生成這個(gè)文件 關(guān)于laravel5的excel包maatwebsite/excel的使用筆記 關(guān)于安裝 官網(wǎng)已經(jīng)很詳細(xì)了,不再描述.http://www.maatwebsite....
摘要:版微信第三方登陸包括微信微博等等,查看支持列表擴(kuò)展好用的圖片處理,也方便使用百度版百度版支付集合,包含支付寶等支付寶在的封裝各國(guó)語(yǔ)言包,包含簡(jiǎn)體中文生成二維碼工具,親測(cè)好用未完大家可以向我推薦,直接在本文下留言即可。 Laravel不權(quán)威導(dǎo)航 Hi 這里是Roy整理的Laravel相關(guān)索引,希望能幫到大家showImg(http://static.segmentfault.com/bu...
摘要:介紹是經(jīng)常會(huì)使用的,里有非常好的組件,能夠?qū)崿F(xiàn)文件的導(dǎo)入和導(dǎo)出。 1.介紹 Excel是經(jīng)常會(huì)使用的,Laravel里有非常好的Excel組件,能夠?qū)崿F(xiàn)Excel/CSV文件的導(dǎo)入和導(dǎo)出 。 組件項(xiàng)目地址: composer: https://packagist.org/packages/maatwebsite/excel。 GitHub: https://github.com/M...
閱讀 2604·2021-11-02 14:39
閱讀 4322·2021-10-11 10:58
閱讀 1446·2021-09-06 15:12
閱讀 1837·2021-09-01 10:49
閱讀 1326·2019-08-29 18:31
閱讀 1882·2019-08-29 16:10
閱讀 3331·2019-08-28 18:21
閱讀 867·2019-08-26 10:42