第一步:
通过composer安装:
composer require maatwebsite/excel ~2.0.0
第二步:
在项目下composer.json中require里添加"maatwebsite/excel":"~2.0.0",并运行composer update 加载该包
第三步:
在config/app.php中注册服务提供者到providers数组:Maatwebsite\Excel\ExcelServiceProvider::class,
第四步:
在config/app.php中注册门面到aliases数组 'Excel' => Maatwebsite\Excel\Facades\Excel::class,
第五步:
在项目根目录下执行命令:
php artisan vendor:publish
执行完后会有一行这个 [9 ] Provider: Maatwebsite\Excel\ExcelServiceProvider
输入数字9,并回车.
第六步:
在项目app/Exceptions目录下新建一个类
ExcelExpoter.php内容如下:
<?php
/**
* Created by PhpStorm.
* User: php
* Date: 2019/3/28
* Time: 下午7:54
*/
namespace App\Exceptions;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
use MaatwebsiteExcelFacadesExcel;
class ExcelExpoter extends AbstractExporter
{
protected $head = [];
protected $body = [];
public function setAttr($head, $body){
$this->head = $head;
$this->body = $body;
}
public function export()
{
Excel::create('回复表', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
// 这段逻辑是从表格数据中取出需要导出的字段
$head = $this->head;
$body = $this->body;
//init列
$title_array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH'];
$rows = collect([$head]); //写入标题
$sheet->rows($rows);
// 这段逻辑是从表格数据中取出需要导出的字段
collect( $this->getData() )->map( function ($item,$k)use($body,$sheet,$title_array ) {
foreach ($body as $i=>$keyName){
$v = array_get($item, $keyName);
$sheet->cell($title_array[$i] . ($k+2), function ($cell) use ($v) {
$cell->setValue($v);
});
}
});
$sheet->rows($rows);
});
})->export('xls');
}
}
第七步:开始在控制器中使用,比如一个快捷回复表内容导出:
在控制器上面加入:
use App\Exceptions\ExcelExpoter;
grid方法里加上:
$excel = new ExcelExpoter(); $excel->setAttr(['id', '问题描述', '内容'], ['id', 'description', 'content']); $grid->exporter($excel);
至此可以完成导出!如果看完能学会请点赞关注哦,谢谢!
本文详细介绍了如何在laravel-admin项目中导出数据库数据,包括安装maatwebsite/excel包、配置服务提供者和门面、发布资源、创建异常类以及在控制器中实现数据导出。
2929

被折叠的 条评论
为什么被折叠?



