官网:https://docs.laravel-excel.com
1、安装
1.1、安装要求:
PHP: ^7.0
Laravel: ^5.5
PhpSpreadsheet: ^1.6
PHP扩展已php_zip启用
PHP扩展已php_xml启用
PHP扩展已php_gd2启用
1.2、安装
//安装
composer require maatwebsite/excel
在laravel项目config/app.php中
//providers元素添加
Maatwebsite\Excel\ExcelServiceProvider::class,
//aliases元素添加
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
发布配置
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
//将自动建立一个新配置文件config/excel.php
2、导出
2.1、新建导出类
php artisan make:export TestExport
//执行后会在新建app/Export/TestExport.php文件
2.2、导出类实现FromArray接口
一、导出单个Sheet
新建的export,默认实现的接口是FromCollection,更改为FromArray,实现array方法
FromCollection以后有机会再讲
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class Export implements FromArray, WithTitle, WithHeadings, WithColumnFormatting
{
// 数据
private $data;
// 表头
private $headings;
// sheet名称
private $title;
// 字段自定义格式
private $columnFormats;
/**
* @param array $data
* @param array $headings
* @param string $title
* @param string $filename
* @param array $columnFormats
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function download(array $data = [], array $headings = [], $title = 'WorkSheet', $filename = '未命名.xlsx', array $columnFormats = []) {
$this->data = $data;
$this->headings = $headings;
$this->title = $title;
$this->columnFormats = $columnFormats;
return \Maatw