Laravel 如何实现 Excel 导入及导出功能

安装依赖

首先使用Composer安装依赖,在项目根目录下执行:

composer require maatwebsite/excel

导出Excel文件

首先创建一个 export

php artisan make:export SchoolExport

该命令会在 app/Exports 创建 SchoolExport.php 文件。

数组形式导出

因为一般我们都是有选择性的导出指定数据。所以这里需要用 FromArray 来实现。

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;

class SchoolExport implements FromArray
{
    protected $invoices;

    public function __construct(array $invoices)
    {
        $this->invoices = $invoices;
    }

    public function array(): array
    {
        // TODO: Implement array() method.
        return $this->invoices;
    }

}

然后直接在控制器中操作导出数据即可。

public function school()
{

    $sql = "select a.zwmc,a.id,a.szgj from gwdxyxk as a left join yu_school_ersanshi as b on a.id=b.s_ys_id where a.szgj='a0920192AD18538XLtaQ' and b.content1 is null and a.zwmc is not null";

    $res = DB::connection('mysql_crm')->select($sql);

    $arr = array_map(function ($value){
        return (array)$value;
    },$res);


    foreach ($arr as $k=>$v){
        $arr[$k]['url'] = "https://baike.baidu.com/item/".$v['zwmc'];
    }

    //因为要设置行名称,所以讲表头合并到结果集的第一行
    $result = array_merge([[
        'zwmc',
        'id',
        'szgj',
        'url'
    ]],$arr);

    return Excel::download(new SchoolExport($result),'school.xlsx');
}

collection 导出

若你直接导出表中所有数据。则可以直接使用 collection:

<?php
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}

然后直接在控制器中操作导出数据即可。

<?php
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
class UsersController extends Controller
{
    public function export()
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
}

针对数据太多,还支持队列导出以及更多的导出格式。详细请查看官方文档

导入Excel文件

首先创建一个 import

php artisan make:import UsersImport --model=User

该命令会在 app/Imports 创建 UsersImport.php 文件。

<?php
namespace App\Imports;
use App\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return User|null
     */
    public function model(array $row)
    {
        return new User([
           'name'     => $row[0],
           'email'    => $row[1],
           'password' => Hash::make($row[2]),
        ]);
    }
}

然后直接在控制器中导出数据即可:

use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
    public function import()
    {
        Excel::import(new UsersImport, 'users.xlsx');
        return redirect('/')->with('success', 'All good!');
    }
}
posted @ 2021-01-15 16:43  caibaotimes  阅读(1078)  评论(0编辑  收藏  举报