Laravel Excel
要求
- PHP: ^7.0
- Laravel: ^5.5
- PhpSpreadsheet: ^1.6
- PHP擴充套件已php_zip啟用
- PHP擴充套件已php_xml啟用
- PHP擴充套件已php_gd2啟用
安裝
-
composer安裝
composer require maatwebsite/excel
ServiceProvider 和 Facade 都是自動發現的,你無需去註冊它。 -
釋出配置
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
基礎使用
最簡單的使用
-
建立一個匯出類
使用artisan命令建立,你也可以直接建立 php artisan make:export UsersExport --model=User <?php namespace App\Exports; use App\User; use Maatwebsite\Excel\Concerns\FromCollection; class UsersExport implements FromCollection { public function collection() { return User::all(); } }
-
控制器中呼叫
use App\Exports\UsersExport; use Maatwebsite\Excel\Facades\Excel; use App\Http\Controllers\Controller; class UsersController extends Controller { public function export() { return Excel::download(new UsersExport, 'users.xlsx'); } }
自定義輸出檢視
上述案例只是簡單的將資料展示出來,如果我們需要多樣化的檢視,就需要自定義檢視檔案
-
建立帶檢視的匯出類
namespace App\Exports; use App\User; use Illuminate\Contracts\View\View; use Maatwebsite\Excel\Concerns\FromView; class UsersExport implements FromView { public function view(): View { return view('exports.users', [ 'users' => User::all() ]); } }
- 建立檢視檔案
<table> <thead> <tr> <th>使用者名稱</th> <th>郵箱</th> </tr> </thead> <tbody> @foreach($users as $user) <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> </tr> @endforeach </tbody> </table>
- 控制器中呼叫
public function export() { return Excel::download(new InvoicesExport, 'invoices.xlsx'); }
同時輸出多張表格
-
建立檢視
<table> <thead> <tr> <th>使用者名稱</th> <th>郵箱</th> </tr> </thead> <tbody> <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> </tr> </tbody> </table>
-
建立子表
<?php namespace App\Exports; use Illuminate\Contracts\View\View; use Maatwebsite\Excel\Concerns\FromView; use Maatwebsite\Excel\Concerns\WithTitle; class UserSheet implements FromView,WithTitle { public $user; public function __construct($user) { $this->user = $user; } //指定子表名稱 public function title(): string { return '使用者' . $this->user->name; } public function view(): View { return view('exports.users', [ 'user' => $this->user ]); } }
-
建立匯出類
namespace App\Exports; use App\User; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\WithMultipleSheets; class UsersExport implements WithMultipleSheets { use Exportable; /** * @return array */ public function sheets(): array { $sheets = []; $users = User::all(); foreach ($users as $user){ $sheets[] = new UserSheet($user); } return $sheets; } }
-
控制器呼叫
public function export() { return Excel::download(new UsersExport, 'invoices.xlsx'); }
其他
表格自動調整寬度
繼承 ShouldAutoSize 介面即可
namespace App\Exports;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class UsersExport implements ShouldAutoSize
{
...
}
參考連結
laravel Excel