laravel 命令行 导出十万行excel [dcat easy excel]
<?php
//导出指定地区的花费数据
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Dcat\EasyExcel\Excel;
use App\Models\User;
use App\Models\Cost;
use App\Models\CostProject;
class ExportCost extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'export:cost {area}';
/**
* The console command description.
*
* @var string
*/
protected $description = '导出消费数据';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$area = $this->argument('area');
$area = intval($area);
if (!$area) {
echo "area错误\n";
return 0;
}
$this->down($area);
echo "导出完成\n";
return 0;
}
private function down($area)
{
$titles = [
'date' => '日期',
'project_id' => '项目',
'user_id' => '姓名',
'amount' => '金额',
'note' => '备注',
'created_at' => '创建时间',
'area' => '地区'
];
$lastId = 0;
$projectKV = CostProject::pluck('name', 'id')->toArray();
$userKv = User::pluck('name', 'id')->toArray();
Excel::export()
->headings($titles) // 设置标题
->chunk(function (int $times) use (&$lastId, $projectKV, $userKv, $area) {
// 每次获取500条数据导入
$chunkSize = 500;
//导出页数限制
if ($times > 3) {
//return;
}
// 这里使用forPageAfterId批量读取数据,也可以用forPage
$collection = Cost::query()
->where('area', $area)
->forPageAfterId($chunkSize, $lastId)->get();
// 暂存最后一个ID
$size = $collection->count();
if ($size == 0) {
return [];
}
$lastId = $collection->last()->id;
$array = $collection->toArray();
//循环处理集合
$areaArr = [1 => '河北', 2 => '湖北', 3 => '天津', 4 => '北京'];
//处理关联字段
foreach ($array as $key => $item) {
$array[$key]['project_id'] = $projectKV[$item['project_id']];
$array[$key]['user_id'] = $userKv[$item['user_id']];
$array[$key]['area'] = $areaArr[$item['area']];
}
// 当数据库查不到值时会停止执行闭包内的逻辑
return $array;
})
->store('cost_all/' . $area . '.xlsx');//保存到文件.
}
}
1 创建命令文件
2 执行 php artisan export:cost 4
文件保存到指定地址
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: