I am trying to allow users to download Excel, using Laravel Excel files with product information. My current web route looks like this:

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

My current Export looks like this:

class ProductExport implements FromQuery
{
    use Exportable;

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

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

My current controller looks like this:

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');
}

When I head over to https://example.com/excel/release?alias=product_list&id=1 this executes correctly and returns an excel file. However, there is no column headers for the rows. The data comes out like so:

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

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

推荐答案

根据documentation,您可以将类更改为使用WithHeadings接口,然后定义headings函数以返回列标题数组:

<?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"];
    }
}

This works with all export types (FromQuery, FromCollection, etc.)

Laravel相关问答推荐

为什么在Blade 文件中输出用户通知时出现错误?

我应该如何使用遵循依赖反转原则的工厂方法设计模式

如何在Laravel中创建自定义单项集合

Laravel:在行的子集上同步多对多

如何通过 Eloquent 获取单个集合中每位教师的学生人数

如何自定义密码确认不匹配.错误信息?

Laravel 5.3:语法错误或访问冲突:1463 HAVING 子句中使用了非分组字段距离

Laravel 5.3 创建模型返回字段没有默认值

在 laravel 查询构建器中使用多个 where 子句

如何判断是否在laravel中设置了cookie?

Laravel Electron邮件验证模板位置

找不到列:1054字段列表中的未知列0-Laravel-我的代码中的任何地方都没有0列

从 sqlite DB 登录 Laravel,得到PDOException 找不到驱动程序

Homebrew PHP 似乎没有链接

Laravel/Lumen 中两列之间的 SQL

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

今天之前的 Laravel 规则......怎么办

使用 Nginx 设置 Laravel

Laravel 分页漂亮的 URL

基于日期的 Laravel 日志(log)文件