[Laravel-Excel中文文档] 实现Excel/CSV文件导出教程
Song •
1626 次浏览 •
0个评论 •
2022年03月05日
在上一篇文章我们介绍了maatwebsite/excel的安装以及导入Excel/Csv文件;接下来介绍如何使用Laravel-Excel实现导出。
Laravel使用maatwebsite/excel实现Excel/CSV文件导入导出及常见问题解决方案
Laravel-Excel实现导出
执行command命令快速创建导出代码:
php artisan make:export UsersExport --model=User
命令会在 app/Exports
下创建
.
├── app
│ ├── Exports
│ │ ├── UsersExport.php
│
└── composer.json
其中UsersExport.php的代码如下
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
然后我们在控制器中执行如下代码即可导出全表,同时我们可以在上方加入筛选。
<?php
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
class UsersController extends Controller
{
public function export()
{
return Excel::download(new UsersExport, users.xlsx);
}
}
即可
如何向constructor传递参数
我们很多时候不可能导出全表,所以我们可以传递参数。
namespace App\Exports;
use App\Invoice;
use Maatwebsite\Excel\Concerns\FromArray;
class InvoicesExport implements FromArray
{
protected $invoices;
public function __construct(array $invoices)
{
$this->invoices = $invoices;
}
public function array(): array
{
return $this->invoices;
}
}
在控制器中我们可以使用如下方法向constructor传递参数
public function export()
{
$export = new InvoicesExport([
[1, 2, 3],
[4, 5, 6]
]);
return Excel::download($export, invoices.xlsx);
}
自定义起始单元格
默认的起始单元格是A1。在导出类中实现WithCustomStartCell
允许您指定自定义起始单元格。
namespace App\Exports;
use App\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
class InvoicesExport implements FromCollection, WithCustomStartCell
{
public function collection()
{
return Invoice::all();
}
public function startCell(): string
{
return B2;
}
}
导出格式
支持导出xlsx,csv,tsv,ods,html,mpdf等,具体参考导出格式文档
设置可导出格式
在上一个示例中,我们使用Excel::download facade启动导出。
Laravel Excel还提供了Maatwebsite\Excel\Concerns\Exportable特性,以使导出类可导出。同时还可以在constructor中设置导出配置。参考文档Exportables
从视图View导出
可以使用FromView从视图创建导出。参考From View
多表单导出
您可以参考 Multiple Sheets 实现多张表单导出。
更多相关好文
-
laravel中distinct()的使用方法与去重 2017-09-11
-
Laravel将view缓存为静态html,laravel页面静态缓存 2021-10-09
-
[ laravel爬虫实战--基础篇 ] guzzle描述与安装 2017-11-01
-
[ 配置教程 ] 在ubuntu16.04中部署LNMP环境(php7+maridb且开启maridb远程以及nginx多域名访问 )并配置laravel环境 2017-07-18
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
热门文章
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
-
Mac 安装mysql并且配置密码 2024-11-20
-
阿里云不同账号(跨账号)ECS服务器同地域如何实现免费内网互通? 2024-11-12
-
electron安装使用better-sqlite3并解决NODE_MODULE_VERSION xxx. This version of Node.js requires 2024-11-06
-
Zerotier+Moon+Nginx实现内网穿透搭建网站 2024-08-23
所以SheetJS实现table导出数据为Excel