首页 > 解决方案 > 使用maatwebsite在laravel中导出带有动态数组的excel

问题描述

我想在 Laravel 5.7 版中导出 Excel。我正在使用包 Maatwebsite Laravel Excel 3.1 版。我有一系列人的信息,如下所示:

 $persons = {
        "person 1": [
            {
                "answer1": "shokouh"
            },
            {
                "answer2": "dareshiri"
            },
            {
                "answerN": "answer N"
            }
        ],
...
        "person M ": [
            {
                "answer1": "sarah"
            },
            {
                "answer2": "smith"
            },
            {
                "answerN": "answer N"
            }
        ]
    }

我想在下面的excel中导出它:

Person 1    Answer 1    Answer 2    …   Answer N
Person M    Answer M2   Answer M2   …   Answer MN

这是我在 Controller 中的导出功能:

public function export(Request $request, Tournament $tournament) {

    ... 

    $persons;

    return Excel::download(new ParticipantExport($persons), 'personInformation.xlsx');
}

这是我在 app\Export\participantExport 中的参与者导出:

class participantExport implements FromArray
{
    protected $invoices;

    public function __construct(array $invoices)
    {
        $this->invoices = $invoices;
    }

    public function array(): array
    {
        return $this->invoices;
    }
}

任何机构都可以帮助我吗?

标签: phplaravel-5maatwebsite-excel

解决方案


我解决了如下问题:

在 Controller.php 中:

$rows = array();

        foreach ($persons as $slug => $person) {
            $row = array();
            array_push($row, $slug);
            foreach ($person as $key => $value) {

                array_push($row, $persons[$slug][$key]['answer']);

            }
            array_push($rows, $row);
        }

        $coll = new participantExport([$rows]);


        return Excel::download($coll, 'participant-information.xlsx');

推荐阅读