php Laravel Excel导出与表关系

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Laravel Excel导出与表关系相关的知识,希望对你有一定的参考价值。


https://docs.laravel-excel.com/3.1/getting-started/installation.html
https://stackoverflow.com/questions/53301568/maatwebsite-laravel-excel-exports-blank-excel-when-using-inputget-in-model
<?php


0) Install Laravel Excell
composer require maatwebsite/excel

1) create Export Controller:
php artisan make:export RegistrationsExportMapping --model=Registration

2) Generated Export Class will look like:
namespace App\Exports;

use Carbon\Carbon;
use App\Registration;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class RegistrationsExportMapping implements FromCollection, WithMapping, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        //returns Data with User data, all user data, not restricted to start/end dates
        return Registration::with('user')->get();
    }

    public function map($registration) : array {
        return [
            $registration->id,
            $registration->user->email,
            $registration->user->key_num,
            $registration->user->plus_one,
            Carbon::parse($registration->event_date)->toFormattedDateString(),
            Carbon::parse($registration->created_at)->toFormattedDateString()
        ] ;


    }

    public function headings() : array {
        return [
           '#',
           'Email',
           'Key#',
           'Plus One',
           'Event Date',
           'Created At'
        ] ;
    }
}



3) RegistrationsController export method:
    /*
    |----------------------------------------------
    | EXPORT MAP RELATIONSHIPS WITH 'REGISTRATIONS'
    |----------------------------------------------
    */
    public function export_mapping() {
        return Excel::download( new RegistrationsExportMapping(), 'registrations.xlsx') ;
    }

5) in web.php
    Route::get('registrations/export_mapping', 'RegistrationsController@export_mapping')->name('registrations.export_mapping') ;



6) In Blade View
<a href="{{ route('registrations.export_mapping') }}" class="btn btn-dark fright">Export Registration with relational data <i class="fas fa-download"></a>

















以上是关于php Laravel Excel导出与表关系的主要内容,如果未能解决你的问题,请参考以下文章

PHP laravel框架 导入导出excel ,phpexcel数据导出分多个工作区(sheet)

laravel的excel导出

使用 laravel 和 vuejs 导出 Excel

laravel5.4 导出 Excel 表格

laravel 5.4 导出excel表格

laravel PHPExcel导出