在Laravel中将Eloquent导出到Excel时,如何包含列标题?

2022-08-30 19:33:47

我正在尝试允许用户下载Excel,使用带有产品信息的Laravel Excel文件。我当前的 Web 路由如下所示:

Route::get('/excel/release', 'ExcelController@create')->name('Create Excel');

我当前的导出如下所示:

class ProductExport implements FromQuery
{
    use Exportable;

    public function __construct(int $id)
    {
        $this->id = $id;
    }

    public function query()
    {
        return ProductList::query()->where('id', $this->id);
    }
}

我当前的控制器如下所示:

public function create(Request $request) {

    # Only alowed tables
    $alias = [
        'product_list' => ProductExport::class
    ];

    # Ensure request has properties
    if(!$request->has('alias') || !$request->has('id'))
        return Redirect::back()->withErrors(['Please fill in the required fields.'])->withInput();

    # Ensure they can use this
    if(!in_array($request->alias, array_keys($alias)))
        return Redirect::back()->withErrors(['Alias ' . $request->alias . ' is not supported'])->withInput();

    # Download
    return (new ProductExport((int) $request->id))->download('iezon_solutions_' . $request->alias . '_' . $request->id . '.xlsx');
}

当我转到此时,这将正确执行并返回一个excel文件。但是,行没有列标题。数据是这样的:https://example.com/excel/release?alias=product_list&id=1

1   150 1   3       2019-01-16 16:37:25 2019-01-16 16:37:25     10

但是,这应该包含列标题,如ID,成本等...如何在此输出中包含列标题?


答案 1

根据文档,您可以更改类以使用该接口,然后定义函数以返回列标题数组:WithHeadingsheadings

<?php
namespace App;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ProductExport implements FromQuery, WithHeadings
{
    use Exportable;

    public function __construct(int $id)
    {
        $this->id = $id;
    }

    public function query()
    {
        return ProductList::query()->where('id', $this->id);
    }

    public function headings(): array
    {
        return ["your", "headings", "here"];
    }
}

这适用于所有导出类型(、等)。FromQueryFromCollection


答案 2
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use DB;
class LocationTypeExport implements FromCollection,WithHeadings
{
    public function collection()
    {
        $type = DB::table('location_type')->select('id','name')->get();
        return $type ;
    }
     public function headings(): array
    {
        return [
            'id',
            'name',
        ];
    }
}

推荐