【问题标题】:Generating csv file with Maatwebsite/Laravel-Excel how make headings returns dynamic array使用 Maatwebsite/Laravel-Excel 生成 csv 文件如何使标题返回动态数组
【发布时间】:2019-11-06 06:46:06
【问题描述】:

在 laravel 5.8 生成 csv 文件中我使用 https://github.com/Maatwebsite/Laravel-Excel 插件,它工作正常,但我使用标题方法生成标题 https://docs.laravel-excel.com/3.1/exports/mapping.html

我需要根据从数据库获得的结果集来设置标题:

<?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
    }

}

有这样的方法吗?

【问题讨论】:

    标签: laravel laravel-5 maatwebsite-excel


    【解决方案1】:

    你可以这样使用:

    <?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 ...
            }
        }
    
    }
    

    【讨论】:

    • 我尝试过这种方式,但是首先调用带有日志记录的方法标题进行调试,然后调用集合
    • 你也可以试试beforeExport。我没有使用它,但试一试..
    • 两次读取数据分别获取数据和标题?是的,这可以工作。
    • 也许你可以这样做。检查更新。避免干燥。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2016-06-07
    相关资源
    最近更新 更多