gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:26:14 24 4
gpt4 key购买 nike

我试图让用户下载 Excel,使用 Laravel Excel包含产品信息的文件。我当前的网络路线如下所示:

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

我当前的 Controller 如下所示:
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');
}

当我前往 https://example.com/excel/release?alias=product_list&id=1这会正确执行并返回一个 excel 文件。但是,行没有列标题。数据是这样出来的:
1   150 1   3       2019-01-16 16:37:25 2019-01-16 16:37:25     10

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

最佳答案

根据documentation您可以更改您的类(class)以使用 WithHeadings接口(interface),然后定义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"];
}
}
这适用于所有导出类型( FromQueryFromCollection 等)

关于php - 在 Laravel 中将 Eloquent 导出到 Excel 时如何包含列标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com