laravel:Laravel-Excel 3.1.48 导出数据到excel(10.27.0)

发布时间 2023-11-02 08:14:46作者: 刘宏缔的架构森林

一,关于第三方库Laravel-Excel

官方代码站:

https://github.com/SpartnerNL/Laravel-Excel

文档地址:

https://docs.laravel-excel.com/3.1/getting-started/

二,安装/配置

1,用composer安装:

liuhongdi@lhdpc:/data/laravel/dignews$ composer require maatwebsite/excel

2,查看所安装库的版本:

liuhongdi@lhdpc:/data/laravel/dignews$ composer show maatwebsite/excel
name     : maatwebsite/excel
descrip. : Supercharged Excel exports and imports in Laravel
keywords : PHPExcel, batch, csv, excel, export, import, laravel, php, phpspreadsheet
versions : * 3.1.48
type     : library
…

3,创建excel.php配置文件

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

   INFO  Publishing [config] assets.  

  Copying file [vendor/maatwebsite/excel/config/excel.php] to [config/excel.php] .............................................................. DONE

三,php代码:

1,创建export文件

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:export StaffLoginExport --model=StaffLogin

   INFO  Export [app/Exports/StaffLoginExport.php] created successfully.

2,编辑文件代码:app/Exports/StaffLoginExport.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
namespace App\Exports;
 
use App\Models\StaffLogin;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Support\Collection;
 
class StaffLoginExport implements FromCollection
{
    private  $uid;
    private $staffLogin;
 
    public function __construct(int $uid)
    {
        $this->uid = $uid;
        $this->staffLogin = new StaffLogin();
    }
    //得到集合
    public function collection()
    {
        //查询得到数据
        $arr = $this->staffLogin->getRowsByUid($this->uid);
        //转集合后返回
        return new Collection($arr);
    }
}

3,controller中调用export:

1
2
3
4
5
6
7
8
9
10
use App\Exports\StaffLoginExport;
use Maatwebsite\Excel\Facades\Excel;
 
class NewsController extends Controller
{
    //下载excel文件
    public function export()
    {
        return Excel::download(new StaffLoginExport(11), 'stafflogin.xlsx');
    }

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/01/laravel-laravelexcel-dao-chu-shu-ju-dao-excel/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

四,测试效果:

五,查看laravel框架的版本:

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0