# laravel admin-02-数据导出

默认的csv导出有中文乱码的问题,需修改一下CsvExporter.php文件

打开  vendor/encore/laravel-admin/src/Grid/Exporters/CsvExporter.php
在public function export() 的$headers后面添加
print(chr(0xEF).chr(0xBB).chr(0xBF));

但还是不太方便,改为用laravel-excel吧

# 一.安装

对于laravel5.6及以上的,直接composer安装即可

composer install maatwebsite/excel

php artisan vendor:publish

# 二.使用

在app目录下建一个Exports目录,添加一个excel的导出类。

比如建一个导出用户信息的AdminUserExport.php,内容如下

<?php

namespace App\Exports;

use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\WithMapping;

class AdminUserExport extends ExcelExporter implements WithMapping
{
    protected $fileName = '用户信息表.xlsx';

    protected $columns = [
        'nickName'      => '昵称',
        'openid'   => 'openid',
        'id_card' => '身份证',
    ];

    public function map($user) : array
    {
        return [
            $user->nickName,
            $user->openid,
            $user->id_card,
        ];
    }
}

在admin对应的controller中直接使用

use App\Exports\AdminUserExport;

// excel导出
$grid->exporter(new AdminUserExport());

这样就能导出自定义的excel了

# 三.科学计数法的问题

导出excel时,如果字段的内容是数字(比如身份证),默认则会变成科学计数,导致数字不完整。

方案一

在export对应字段中加入空格,比如AdminUserExport.php对应的内容可改为如下:

public function map($user) : array
{
    return [
        $user->nickName,
        $user->openid,
        $user->id_card = ' '.$user->id_card,
    ];
}

方案二

将config/excel.php中value_binder改为如下配置

'default' => PhpOffice\PhpSpreadsheet\Cell\StringValueBinder::class,

# 四.关联字段问题

有时候我们要导出关联表的字段。比如有两个表users 和 users_gift, users中有name,phone字段,users_gift有个user_id关联users表。 在导出users_gift时如何把name和phone也同时导出呢?

1.在users_gift的module中增加关联关系

public function users()
    {
        return $this->hasOne(Users::class,'id','uid');
    }

2.导出的方法AdminUserGiftExport.php如下

    protected $fileName = '用户中奖表.xlsx';

    protected $columns = [
        'id' => '序号',
        'gift_id' => '礼品id',
        'user_id'      => '用户名',
        'users.phone'      => '用户手机号',
    ];

    public function map($row) : array
    {
        return [
            $row->id,
            $row->gift_id,
            data_get($row,'users.name'),
            data_get($row,'users.phone'),
        ];
    }

这里注意下,在$columns中,关联的第一列直接写导出表的字段(比如这里是user_id),后面就可以用关联字段的格式(比如user.phone)。 关联的第一列如果写user.name则导出的内容为空。