laravel-excel导出数据,对数据进行样式修改,数据处理
laravel-excel导出数据,对数据进行修改,对样式进行处理,对列求和
·
Maatwebsite 3.1版本excel导出,对数据,样式进行处理,再此记录一下
下载laravel-excel,下载的是最新版本的,需要注意框架版本是否符合,框架版本低可以下载2.1
下载
composer require maatwebsite/excel
发布配置,会添加一个config/excel.php文件
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
创建 App\Exports\UsersExport.php
<?php
namespace App\Exports;
use App\Models\User;//引入用户表models类
use App\Models\Motorcade;
use Dcat\Admin\Grid\Exporters\AbstractExporter;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithPreCalculateFormulas;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
class UsersExport extends AbstractExporter implements WithMapping, WithHeadings, FromCollection,WithColumnWidths,
WithPreCalculateFormulas,WithEvents
{
use Exportable;
protected $fileName = '司机数据表';//导出文件名
protected $titles = [];//标题
public function __construct()
{
$this->fileName = $this->fileName.'_'.Str::random(6).'.xlsx';//拼接下载文件名称
$this->titles = ['id' => 'id','name'=>'司机名称', 'car_id' => '所属车队' ,'created_at'=>'创建时间','updated_at'=>'更新时间'];
parent::__construct();
}
public function export()
{
// TODO: Implement export() method.
$this->download($this->fileName)->prepare(request())->send();
exit;
}
public function collection()
{
// TODO: Implement collection() method.
return collect($this->buildData());
}
public function headings(): array
{
// TODO: Implement headings() method.
return $this->titles();
}
//设置宽度
public function columnWidths(): array
{
//设置行宽度
return [
'A' => 15,
'B' => 35,
'C' => 35,
'D' => 35,
'E' => 35,
];
}
//自定义添加公式
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$rows_line = $event->sheet->getHighestRow();//获取当前总共有多少条数据
$count = $rows_line+1;//获取最后一行
$event->sheet->setCellValue("A$count","=SUM(A:A)");// 设置A列 最后一行的值,值为A列的总和
}
];
}
public function map($row): array
{
//可在里面对数据进行修改
$car = Motorcade::where('id',$row['car_id'])->first();
$row['car_id'] = $car['name'];//修改 $row['car_id']的值
// TODO: Implement map() method.
return [
$row['id'],
$row['name'],
$row['car_id'],
$row['created_at'],
$row['updated_at'],
];
}
}
在控制器中引入
use App\Exports\UsersExport;
$grid->export(new UsersExport());
导出来的数据

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)