laravel导出execl
时间: 2023-08-31 21:12:37 浏览: 50
要在 Laravel 中导出 Excel,你可以使用 Laravel Excel 这个扩展包。下面是简单的步骤:
1. 使用 Composer 安装 Laravel Excel
```
composer require maatwebsite/excel
```
2. 在 `config/app.php` 文件中添加服务提供者和门面
```php
'providers' => [
// ...
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
// ...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
```
3. 创建控制器和视图
创建一个控制器来处理 Excel 导出的逻辑,例如 `ExcelController`,并在其中创建一个 `export()` 方法来生成 Excel 表格。
```php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\UsersExport;
class ExcelController extends Controller
{
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
}
```
在 `app/Exports` 目录下创建一个 `UsersExport` 类,用于生成 Excel 数据。
```php
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
```
创建一个视图文件来呈现导出 Excel 表格的按钮,例如 `export.blade.php`。
```html
<a href="{{ route('export') }}">Export Users</a>
```
4. 定义路由
在 `routes/web.php` 文件中定义一个路由,指向 `ExcelController` 的 `export()` 方法。
```php
Route::get('export', 'ExcelController@export')->name('export');
```
现在,当用户访问 `/export` 路径时,会生成一个名为 `users.xlsx` 的 Excel 文件,包含用户数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)