Laravel 加载Maatwebsite\Excel 3.1方法
1,composer.json 中require 添加
“maatwebsite/excel”: “~3.1” composer update 或者直接运行 : composer require maatwebsite/excel
2,config/app.php
打开config/app.php文件
添加以下代码 ‘providers’ => [
Maatwebsite\Excel\ExcelServiceProvider::class,
] ‘aliases’ => [
‘Excel’ => Maatwebsite\Excel\Facades\Excel::class,
],
2,php artisan vendor:publish
将会自动创建一个新配置文件config/excel.php
3、php artisan make:export ExportDemo
将会自动创建一个新文件app/Exports/ExportDemo.php 代码示例:
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExportDemo implements FromCollection
{
private $row;
private $data;
public function __construct($row, $data)
{
$this->row = $row;
$this->data = $data;
}
public function collection()
{
$row = $this->row;
$data = $this->data;
foreach ($row[0] as $key => $value) {
$key_arr[] = $key;
}
foreach ($data as $key => &$value) {
$js = [];
try {
for ($i = 0, $iMax = count($key_arr); $i < $iMax; $i++) {
$js = array_merge($js, [$key_arr[$i] => $value[$key_arr[$i]]]);
}
array_push($row, $js);
unset($val);
} catch (\Throwable $e) {
}
}
return collect($row);
}
}
4,使用之处
use Maatwebsite\Excel\Facades\Excel;
public function postExport(Request $request){
try{
$account_id = $request->input('in_account', '');
$store_id = $request->input('store_id','');
$ids = [];
if($store_id != ''){
$ids = AccountStore::where('store_id',$store_id)->pluck('id')->toArray();
}
$list = AccountStoreLog::with(['accountStore','staff'])->where(function ($q) use ($account_id,$store_id,$ids) {
if ($account_id != '') {
$q->where('account_store_id', $account_id);
}
if($store_id != ''){
$q->whereIn('account_store_id',$ids);
}
})->orderBy('id', 'desc')->get();
$title = [
['ID', '账户名称', '账户类型', '金额', '类型', '关联订单','订单类型','时间','备注']
];
$content = [];
$type_list = config('remark')['account_log_type'];
foreach ($list as $item){
$type_name = '';
foreach ($type_list as $k=>$v){
if($item->order_type == $k){
$type_name = $v['name'];
break;
}
}
$content[] = [
$item->id,
$item->accountStore['name'],
$item->account_type == 0?'银行卡':($item->account_type == 1?'微信':($item->account_type == 2?'支付宝':'')),
$item->money,
$item->type == 1?'收入':'支出',
$item->order_num,
$type_name,
$item->created_at,
$item->remark
];
}
$name = date('YmdHis');
Excel::store(new ExportDemo($title, $content), '/exports/' . $name . '.xlsx', 'local');
return $this->resData(200, "导出成功", url("/exports/" . $name . ".xlsx"));
}catch (\Throwable $e){
return $this->resData(500, '操作失败,请重新操作', ['error_msg' => $e->getMessage(), 'line' => $e->getLine()]);
}
}
over
|