📌  相关文章
📜  App\Exports\TarefasExport::headings() 的声明必须与 Maatwebsite\Excel\Concerns\WithHeadings::headings(): 数组兼容 - PHP (1)

📅  最后修改于: 2023-12-03 15:29:26.950000             🧑  作者: Mango

App\Exports\TarefasExport::headings() 的声明必须与 Maatwebsite\Excel\Concerns\WithHeadings::headings(): 数组兼容 - PHP

当使用 PHP 中的 Laravel Excel 导出功能时,我们通常需要实现 WithHeadings 接口,其中必须实现 headings() 方法,该方法返回一个数组,定义导出文件的表头。

在定义 headings() 方法时,我们需要注意:

  1. 方法签名必须与 WithHeadings 接口的声明完全相同,包括方法名、参数列表和返回值类型。具体签名为:public function headings(): array

  2. 方法返回的数组内,必须包含所有的表头信息,用于定义导出文件的列名。

因此,在定义 headings() 方法时,我们通常需要从相应的导出类继承,并覆盖父类的 headings() 方法。

例如,若我们想要导出一个 Tarefas 数据表的信息,则可以创建一个 TarefasExport 类,并实现 WithHeadings 接口和 headings() 方法。具体实现为:

<?php

namespace App\Exports;

use App\Models\Tarefas;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class TarefasExport implements FromCollection, WithHeadings
{
    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            '#',
            'Título',
            'Descrição',
            'Criado em',
            'Atualizado em',
        ];
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return Tarefas::all();
    }
}

在上述代码中,我们从 FromCollection 接口继承导出类,并实现了 collection() 方法用于获取数据,并从 WithHeadings 接口继承后,覆盖了父类的 headings() 方法,返回了导出文件的表头数组。

总之,在使用 Laravel Excel 导出数据时,我们需要遵循以上规则,确保定义的 headings() 方法与 WithHeadings 接口的声明相同,并且能够正确地返回导出文件的表头信息。