使用 Maatwebsite/Laravel-Excel 生成 csv 文件 如何使标题 returns 动态数组
Generating csv file with Maatwebsite/Laravel-Excel how make headings returns dynamic array
在laravel 5.8生成我使用的csv文件
https://github.com/Maatwebsite/Laravel-Excel
插件,它工作正常,但是当我使用 headings 方法生成 header
https://docs.laravel-excel.com/3.1/exports/mapping.html
我需要 headers,具体取决于我从数据库获得的结果集:
<?php
namespace App\Exports;
use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class exportSearchResults implements FromCollection, WithHeadings
{
public function collection()
{
$searchResultRows = SearchResult
::getByUserList($this->user_list_id)
->select( 'source_id' )
->groupBy( 'source_id' )
->orderBy('source_id', 'asc')
->get()
->toArray();
...
return $searchResultRows;
}
public function headings(): array
{
return [
'field',
'value',
];
// I need Somehow to return content of this array based on $searchResultRows array in collection method
}
}
有这样的方法吗?
你可以使用这样的东西:
<?php
namespace App\Exports;
use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class exportSearchResults implements FromCollection, WithHeadings
{
private $searchResultRows;
public function collection()
{
return $this->searchResultRows;
}
public function headings(): array {
$this->searchResultRows = SearchResult::getByUserList($this->user_list_id)
->select( 'source_id' )
->groupBy( 'source_id' )
->orderBy('source_id', 'asc')
->get()
->toArray();
...
if ($this->searchResultRows ...){
return [
'field',
'value',
];
} else {
return ...
}
}
}
在laravel 5.8生成我使用的csv文件 https://github.com/Maatwebsite/Laravel-Excel 插件,它工作正常,但是当我使用 headings 方法生成 header https://docs.laravel-excel.com/3.1/exports/mapping.html
我需要 headers,具体取决于我从数据库获得的结果集:
<?php
namespace App\Exports;
use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class exportSearchResults implements FromCollection, WithHeadings
{
public function collection()
{
$searchResultRows = SearchResult
::getByUserList($this->user_list_id)
->select( 'source_id' )
->groupBy( 'source_id' )
->orderBy('source_id', 'asc')
->get()
->toArray();
...
return $searchResultRows;
}
public function headings(): array
{
return [
'field',
'value',
];
// I need Somehow to return content of this array based on $searchResultRows array in collection method
}
}
有这样的方法吗?
你可以使用这样的东西:
<?php
namespace App\Exports;
use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class exportSearchResults implements FromCollection, WithHeadings
{
private $searchResultRows;
public function collection()
{
return $this->searchResultRows;
}
public function headings(): array {
$this->searchResultRows = SearchResult::getByUserList($this->user_list_id)
->select( 'source_id' )
->groupBy( 'source_id' )
->orderBy('source_id', 'asc')
->get()
->toArray();
...
if ($this->searchResultRows ...){
return [
'field',
'value',
];
} else {
return ...
}
}
}