laravel-excel maatwebsite/excel 新版中文文档

laravel 项目从 5.2 升级到了 5.7,Excel 的导入导出,使用的 maatwebsite/excel laravel-excel 依赖包,也从 2.* 升级到了 3.*,发现不能用了,打开文档一看,这尼玛改动也太大了吧,完全不能使用的节奏啊!

先分享几个链接:
	github 地址:
		https://github.com/Maatwebsite/Laravel-Excel

	官网地址:
		https://laravel-excel.maatwebsite.nl

	看文档的升级指南,可以发现官方推荐了个链接,有人从 2.x 升级到 3.x,项目里进行的代码修改
		https://github.com/Maatwebsite/Laravel-Excel/issues/1799
PS:
	想搜下新版的中文文档,打开 google 搜索,输入 'maatwebsite/excel 中文文档',发现第 3 条居然是我之前写的博客,打开一看,吓我一跳,我尼玛压根没有一点印象,之前居然总结过旧版文档,而且写了 700 多行,有点吃惊,我以前居然这么有耐心~

好了,闲话少数,开始新版文档学习之旅~
	依赖:
		PHP: ^7.0
		Laravel: ^5.5
		PhpSpreadsheet: ^1.4
		php_zip
		php_xml
		php_gd2

	安装:
		composer require maatwebsite/excel

	配置:
		Maatwebsite\Excel\ExcelServiceProvider 默认是自动发现并注册,我们也可以手动添加:
			config/app.php
				'providers' => [
					/*
					 * Package Service Providers...
					 */
					Maatwebsite\Excel\ExcelServiceProvider::class,
				]

		Excel 门面(Facade)也是自动发现,也可以手动添加:
			config/app.php
				'aliases' => [
					...
					'Excel' => Maatwebsite\Excel\Facades\Excel::class,
				]

		发布配置文件:
			php artisan vendor:publish
			会创建 config/excel.php

	导出:
		1.5分钟快速入门:
			在 App/Exports 下创建导出类
				php artisan make:export UsersExport --model=User

			UserExport.php 内容:
				<?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');
				    }
				}

			这样就导出了个 'users.xlsx' 文件

		2.导出集合
			导出的最简单方式是,创建一个自定义的导出类。就是使用之前的命令,在 App/Exports 下创建一个导出类
				php artisan make:export UsersExport --model=User

			1>常用方法
				控制器里下载:
					public function export() 
					{
					    return Excel::download(new InvoicesExport, 'invoices.xlsx');
					}

				控制器里保存到硬盘:
					public function storeExcel() 
					{
					    return Excel::store(new InvoicesExport, 'invoices.xlsx', 's3');
					}

			2>依赖注入:
				另一种写法,看文档

			3>集合宏:
				Laravel-Excel 为 Laravel 的导出集合类,提供了一些宏,更方便的下载和存储集合。

				下载:
					(new Collection([
						[1, 'dongxuemin', 30], 
						[2, 'yangyaping', 30])
					)->downloadExcel($filePath, $writerType = null, $headings = false);

				保存:
					(new Collection([
						[1, 'dongxuemin', 30], 
						[2, 'yangyaping', 30])
					)->storeExcel($filePath, $disk = null, $writerType = null, $headings = false);

				总结:
					我们可以自己利用 new Collection 来构造集合,进行下载和存储

		3.在硬盘上存储导出数据:
			导出可以很容易地被存储到 Laravel 所支持的任意文件系统。

			1>不传递参数,默认文件系统
				Excel::store(new InvoicesExport(2018), 'invoices.xlsx');

			2>存储到 's3' 文件系统
				Excel::store(new InvoicesExport(2018), 'invoices.xlsx', 's3');

			3>存储到 's3' 文件系统,并指定 'writer' 类型
				Excel::store(new InvoicesExport(2018), 'invoices.xlsx', 's3', Excel::XLSX);

		4.导出格式:
			默认情况下,导出格式由导出文件的后缀决定,例如:'user.xlsx',导出格式就是:\Maatwebsite\Excel\Excel::XLSX。我们也可以传递第二个参数,显式地指定导出格式。
				(new InvoicesExport)->download('invoices.xlsx', \Maatwebsite\Excel\Excel::XLSX);

			支持的格式有:
				XLSX
				CSV
				TSV
				ODS
				XLS
				SLK
				XML
				GNUMERIC
				HTML
				MPDF
				DOMPDF
				TCPDF

		5.可导出的
			之前的方法中,我们使用 Excel::download 门面(Facade) 来导出。
			例如:在控制器中使用 Excel::download(new InvoicesExport(2018));

			Laravel Excel 也提供了一个 'Maatwebsite\Excel\Concerns\Exportable' trait,使得我们创建的导出类,本身具有可导出的方法。

			示例:
				use Maatwebsite\Excel\Concerns\Exportable;

				class InvoicesExport implements FromCollection
				{
				    use Exportable;

				    public function collection()
				    {
				        return Invoice::all();
				    }
				}

			这样,InvoicesExport 类本身就具有可导出方法,不用再使用 Excel 门面(Facade)

			下载:
				return (new InvoicesExport)->download('invoices.xlsx');

			存储:
				return (new InvoicesExport)->store('invoices.xlsx', 's3');

			可响应:
				可以使用 'Responsable' 接口,进一步简化导出操作。

				use Illuminate\Contracts\Support\Responsable;
				class InvoicesExport implements FromCollection, Responsable
				{

					// 要求必须指定 'fileName' 属性(导出的文件名)
					private $fileName = 'invoices.xlsx';	
				}

				下载:
					return new InvoicesExport();

		6.从查询导出
			在之前的例子中,我们在导出类中进行查询。对于小型导出,这个是一个非常好的解决方案,但是对于大型导出,会有很大的性能开销。

			通过使用 'FromQuery',我们可以为导出准备一个查询。在底层,'FromQuery' 查询使用了 chunks 查询,以减少性能开销。

			普通查询:

				示例:
					use Maatwebsite\Excel\Concerns\FromQuery;		// 引入 'FromQuery'

					class InvoicesExport implements FromQuery		// 实现 'FromQuery'
					{
					    use Exportable;

					    public function query()
					    {
					        return Invoice::query();				// 确保不要使用 'get()' 方法
					    }
					}

				下载:
					return (new InvoicesExport)->download('invoices.xlsx');

			自定义查询

				/*
					这个应该是我们最经常使用的方法!!!
					我们一般都是根据用户的各种筛选条件,然后进行 query 查询,然后得到最终的结果列表,再进行导出。
					但因为新版,导出的数据结果,都是通过外部的导出类来实现了,我们必须将 query 参数,传递到导出类中,来获取结果集。
				 */

				普通示例:
					use Maatwebsite\Excel\Concerns\FromQuery;		// 引入 'FromQuery'

					class InvoicesExport implements FromQuery		// 实现 'FromQuery'
					{
					    use Exportable;

					    public function __construct(int $year)		// 导入外部查询参数
					    {
					        $this->year = $year;
					    }

					    public function query()
					    {
					        return Invoice::query()->whereYear('created_at', $this->year);			// 使用 where 查询
					    }
					}

					下载:
						// 传递查询参数
						return (new InvoicesExport(2018))->download('invoices.xlsx');

				设置器示例(另一种写法):
					use Maatwebsite\Excel\Concerns\FromQuery;		// 引入 'FromQuery'

					class InvoicesExport implements FromQuery		// 实现 'FromQuery'
					{
					    use Exportable;

					    public function forYear(int $year)			// 定义 '设置器'
					    {
					        $this->year = $year;
					        
					        return $this;
					    }

					    public function query()
					    {
					        return Invoice::query()->whereYear('created_at', $this->year);			// 使用 where 查询
					    }
					}

					下载:
						// 调用 '设置器'
						return (new InvoicesExport)->forYear(2018)->download('invoices.xlsx');

		7.从模板中导出
			定义导出类,同时定义一个导出模板,Laravel Excel 会将定义的 HTML table 转换为一个 Excel 电子表单

			示例:
				use Illuminate\Contracts\View\View;
				use Maatwebsite\Excel\Concerns\FromView;

				class InvoicesExport implements FromView
				{
				    public function view(): View
				    {
				        return view('exports.invoices', [
				            'invoices' => Invoice::all()
				        ]);
				    }
				}

			Blade 模板,定义一个标准的 <table> 即可,<thead> - 表头 & <tbody> - 表内容
				<table>
				    <thead>
				    <tr>
				        <th>Name</th>
				        <th>Email</th>
				    </tr>
				    </thead>
				    <tbody>
				    @foreach($users as $user)
				        <tr>
				            <td>{{ $user->name }}</td>
				            <td>{{ $user->email }}</td>
				        </tr>
				    @endforeach
				    </tbody>
				</table>

		8.队列
			如果处理大量的数据导出,推荐使用队列来进行导出。

			队列导出,底层实现是:使用 chunk 查询,多个 job 任务链接在一起(应该是按顺序链接)。这些 job 任务以插入队列的先后顺序正确执行,只有当前面的任务执行成功,后面的才会执行。

			普通示例:
				导出类定义一致

				下载,直接调用 'queue()' 方法
					(new InvoicesExport)->queue('invoices.xlsx');
					return back()->withSuccess('Export started!');

			显示定义导出到队列
				use Maatwebsite\Excel\Concerns\FromQuery;
				use Illuminate\Contracts\Queue\ShouldQueue;			// 引入 'ShouldQueue'

				class InvoicesExport implements FromQuery, ShouldQueue		// 实现 'ShouldQueue'
				{
				    use Exportable;

				    public function query()
				    {
				        return Invoice::query();
				    }
				}

				下载,使用 'store()' 方法
					(new InvoicesExport)->store('invoices.xlsx');

			追加队列任务
				queue() 方法返回 Laravel 的 'PendingDispatch' 实例。意味着,我们可以在队列尾部添加额外的 job 任务,新添加的导出任务,只有在之前的导出都正确后,才会执行。

				示例:
					use Illuminate\Bus\Queueable;					// 引入 'Queueable'
					use Illuminate\Contracts\Queue\ShouldQueue;
					use Illuminate\Queue\SerializesModels;			// 引入 'SerializesModels'

					class NotifyUserOfCompletedExport implements ShouldQueue
					{
					    use Queueable, SerializesModels;			// 使用 'Queueable' & 'SerializesModels'
					    
					    public $user;
					    
					    public function __construct(User $user)		// 传递参数
					    {
					        $this->user = $user;
					    }

					    public function handle()					// 调用了 'handle()' 方法
					    {
					        $this->user->notify(new ExportReady());
					    }
					}

				追加:
					(new InvoicesExport)->queue('invoices.xlsx')->chain([
					    new NotifyUserOfCompletedExport(request()->user()),		// 传递参数
					]);

			自定义队列:
				由于返回了 'PendingDispatch',我们也可以更改使用的队列。(有时间可看下 PendingDispatch 源码)

				(new InvoicesExport)->queue('invoices.xlsx')->allOnQueue('exports');

		9.多个表单
			多表单的导出,需要使用 'WithMultipleSheets'。然后在导出类中,实现 'sheets()' 方法,sheets() 方法,返回一个由 '单个表单对象' 组成的数组。

			多表单的导出,需要2个类:
				1>导出类
				2>单个表单类

			示例:
				1>导出类
					use Maatwebsite\Excel\Concerns\WithMultipleSheets;

					class InvoicesExport implements WithMultipleSheets
					{

						// 实现 sheets() 方法,返回一个由 '单个表单对象' 组成的数组。
					    public function sheets(): array
					    {
					        $sheets = [];

					        for ($month = 1; $month <= 12; $month++) {
					            $sheets[] = new InvoicesPerMonthSheet($this->year, $month);
					        }

					        return $sheets;
					    }
					}

				2>单个表单类,可以实现 'FromQuery','FromCollection',...
					use Maatwebsite\Excel\Concerns\FromQuery;		// 引入 'FromQuery'
					use Maatwebsite\Excel\Concerns\WithTitle;		// 引入 'WithTitle'(可修改 excel 表单名)

					class InvoicesPerMonthSheet implements FromQuery, WithTitle
					{

						// 查询
					    public function query()
					    {
					        return Invoice
					            ::query()
					            ->whereYear('created_at', $this->year)
					            ->whereMonth('created_at', $this->month);
					    }

					    // Excel 电子表单名
					    public function title(): string
					    {
					        return 'Month ' . $this->month;
					    }
					}

		10.映射数据
			映射行
				添加 'WithMapping',我们可以定义一个 'map()' 方法,将查询到的每条数据,经过 map() 方法处理,返回我们需要的 '一整行'。

				示例:
					use Maatwebsite\Excel\Concerns\WithMapping;		// 引入 'WithMapping'

					class InvoicesExport implements FromQuery, WithMapping		// 实现 'WithMapping'
					    
					    // 定义 'map()' 方法,参数是 '查询出来的每行数据对象'
					    public function map($invoice): array
					    {
					        return [
					            $invoice->invoice_number,
					            Date::dateTimeToExcel($invoice->created_at),
					        ];
					    }
					}

			添加标题行
				添加 'WithHeadings',定义 'headings()' 方法,来添加标题行

				示例:
					use Maatwebsite\Excel\Concerns\WithHeadings;		// 引入 'WithHeadings'

					class InvoicesExport implements FromQuery, WithHeadings		// 实现 'WithHeadings'
					    
					    // 定义 'headings()' 方法
					    public function headings(): array
					    {
					        return [
					            '#',
					            'Date',
					        ];
					    }
					}

		11.格式化列
			使用 'WithColumnFormatting',定义 'columnFormats()' 方法,我们可以轻松格式化整列数据。	

			如果想要更多自定义内容,建议使用 AfterSheet 事件直接与底层 Worksheet 类进行交互。

			示例:
				use PhpOffice\PhpSpreadsheet\Shared\Date;			// 日期处理
				use PhpOffice\PhpSpreadsheet\Style\NumberFormat;	// 数字格式化
				use Maatwebsite\Excel\Concerns\WithColumnFormatting;		// 引入 '列格式化'
				use Maatwebsite\Excel\Concerns\WithMapping;

				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,
				        ];
				    }
				}

			日期处理:
				推荐在 map() 方法中使用 '\PhpOffice\PhpSpreadsheet\Shared\Date::dateTimeToExcel()'

			自动调整尺寸:
				引入 'ShouldAutoSize',让 Laravel Excel 自动调整单元格宽度

				use Maatwebsite\Excel\Concerns\ShouldAutoSize;
				Class InvoicesExport implements ShouldAutoSize
				{

				}

		12.提供的所有可用的 'Export concerns'
			接口:
				Maatwebsite\Excel\Concerns\FromArray - 使用 array 来实现导出
				Maatwebsite\Excel\Concerns\FromCollection - 使用 Laravel collection 来实现导出
				Maatwebsite\Excel\Concerns\FromIterator - 使用 iterator(迭代器)来实现导出
				Maatwebsite\Excel\Concerns\FromQuery - 使用 Eloquent query 来实现导出
				Maatwebsite\Excel\Concerns\FromView - 使用 (Blade) 模板来实现导出
				Maatwebsite\Excel\Concerns\WithTitle - 设置工作簿或工作表标题
				Maatwebsite\Excel\Concerns\WithHeadings - 添加表头
				Maatwebsite\Excel\Concerns\WithMapping - 在写入文件前,格式化行
				Maatwebsite\Excel\Concerns\WithColumnFormatting - 格式化列
				Maatwebsite\Excel\Concerns\WithMultipleSheets - 开启多表单支持
				Maatwebsite\Excel\Concerns\ShouldAutoSize - 在工作表中,自动调整列宽
				Maatwebsite\Excel\Concerns\WithStrictNullComparison - 在测试单元格的 null 时,使用严格比较
				Maatwebsite\Excel\Concerns\WithEvents - 注册事件,挂载到 'PhpSpreadsheet' 处理过程中
				Maatwebsite\Excel\Concerns\WithCustomQuerySize - 允许 'Exportable' 实现 'FromQuery',来提供它们自己的自定义查询大小。
				Maatwebsite\Excel\Concerns\WithCustomCsvSettings - 允许对指定的导出,运行自定义的 CSV 设置。
				Maatwebsite\Excel\Concerns\WithCharts - 允许运行一个或多个 PhpSpreadsheet Chart 实例
				Maatwebsite\Excel\Concerns\WithDrawings - 允许运行一个或多个 PhpSpreadsheet Drawing 实例
				Maatwebsite\Excel\Concerns\WithCustomStartCell - 允许指定一个自定义起始单元格。注意:仅支持 'FromCollection' 导出

			Traits:
				Maatwebsite\Excel\Concerns\Exportable - 给导出类自身添加 'download()' 和 'store()' 方法
				Maatwebsite\Excel\Concerns\RegistersEventListeners

		13.扩展
			有点复杂,不总结了,看文档


	导入:
		导出写的有点累了,有时间再完善...

猜你喜欢

转载自blog.csdn.net/beyond__devil/article/details/83008782