Laravel 學習筆記 — Simple Export Excel
我們來嘗試試做 Excel 匯出我們前面做的文章列表
首先,我們到 Laravel Excel (https://docs.laravel-excel.com/3.1/getting-started/installation.html),使用指令進行安裝:composer require maatwebsite/excel
接下來在 'providers’ 將 ExcelServiceProvider 設定加入至 config/app.php
在 'aliases' 給予一個別名
最後做一個 publish 的動作,將 config 檔的設定匯出來
建立一個 ExcelController
建立一個 export,php artisan make:export ArticlesExport — model=Article
在 web.php 設定路由
編寫 ExcelController.php,先測試一下,這個 api 有沒有成功
有成功的話,return 改寫成我們要的:return Excel::download(new ArticlesExport, 'articles.xlsx');
記得 ArticlesExport 跟 Excel 在上方都要 import 進來
重新整理 localhost:8000/export 頁面,會出現錯誤,我們來解決一下
我們到 app\Exprots\ArticlesExport.php 中,將 collection() 內的 Article 的 namespace 改掉,改成 import App\Models\Articels; 刪除預設的 App\Article
再次重新整理網頁後,會發現有匯出檔案
打開下載下來的 articles.xlsx 可以發現,資料已經匯入了
特別注意,假刪除 SoftDelete 的資料(即 deleted_at 欄位有值的資料),並不會出現在匯出的 Excel 資料中
我們將這個功能加到首頁
為 Excel 檔名加上時間,import Carbon\Carbon
這裡用 $timeNow = Carbon::now(); 得到現在時間,拿來跟 excel 檔名組成新的檔名,從檔名可以了解匯出檔案的時間