laravel5 Excel导出

版权声明:本文为博主原创,未经博主同意,不得转载! https://blog.csdn.net/qq_39188306/article/details/82950146

1、安装:maatwebsite/excel的2.1.0版本,命令行:composer require "maatwebsite/excel:~2.1.0";

2、在config/app.php中,注册服务提供者和注册门面:

'providers' => [
    /*
     * 注册服务提供者
     * Laravel Framework Service Providers...
     */
    Illuminate\Auth\AuthServiceProvider::class,
    ... ...
    App\Providers\RouteServiceProvider::class,
    //Excel导入导出
    Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
     //注册门面
    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    ... ...
    'View' => Illuminate\Support\Facades\View::class,
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

3、添加路由

$router->group([
    'prefix'    => 'excel',
    'namespace' => 'Excel',
], function(Router $router) {
    //导出用户列表
    $router->get('/excelExports', "ExcelController@excelExport");

});

4、创建控制器,命令:php artisan make:controller Admin/Excel/ExcelController ,并复制以下代码:

<?php

namespace App\Http\Controllers\Admin\Excel;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Excel;
use App\Models\Admin\User\Users;

class ExcelController extends Controller
{
    /**
     * 导出
     *
     * @param Users $users
     * @return mixed
     */
    public function excelExport(Request $request,Users $users)
    {
        //筛选条件 -- 根据需要 -- 修改你的查询语句
        //$where['client_id'] = $request->client_id;

        $data = $users->get()->toArray();

        return Excel::create('用户数据导出', function($excel) use ($data) {
            $excel->sheet('用户数据导出', function($sheet) use ($data)
            {
                $sheet->cell('A1', function($cell) {$cell->setValue('用户名');   });
                $sheet->cell('B1', function($cell) {$cell->setValue('角色名');   });
                $sheet->cell('C1', function($cell) {$cell->setValue('登陆IP');   });
                $sheet->cell('D1', function($cell) {$cell->setValue('登陆时间'); });
                if (!empty($data)) {
                    foreach ($data as $key => $value) {
                        $i= $key+2;
                        $sheet->cell('A'.$i, $value['username']);
                        $sheet->cell('B'.$i, $value['name']);
                        $sheet->cell('C'.$i, $value['login_ip']);
                        $sheet->cell('D'.$i, $value['login_at']);
                    }
                }
            });
        })->download('xls');
    }

}

5、测试看看能不能成功:

导出就到此结束啦!希望能帮到你!

猜你喜欢

转载自blog.csdn.net/qq_39188306/article/details/82950146