PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to download excel template will display with only header in Laravel Excel 3.1?

 November 15, 2022     excel, export-to-excel, laravel, laravel-6, laravel-excel     No comments   

Issue

Good Day guys,.. I need to download a excel template only show with headers,..

I have good and working function code in laravel-excel version 2 of my problem,. but in version 3.1 i dont know how to code it.

this is my code in version 2;

public function downloadCoursesTemplate()
{
    $columns = array(
        'Course Code',
        'Course Description',
        'Status'
    );

    return Excel::download('Courses', function ($excel) use ($columns) {
        $excel->sheet('Courses', function ($sheet) use ($columns) {
            $sheet->fromArray($columns);
        });
    })->export('xlsx');
}

this is the output:

enter image description here

I want that on laravel-excel version 3.1

There have documentation in new versions but i could not find it to solve my issue.

Is anyone can help me? thanks. sorry for my English grammar.


Solution

The documentation should be pretty clear, it even has a quick start guide here

But here is what you can do:

Generate the export class

php artisan make:export CoursesTemplateExport

Change the class to the following:

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;

class CoursesTemplateExport implements FromArray, WithHeadings
{
    /**
     * @return array
     */
    public function array(): array
    {
        return [];
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            'Course Code',
            'Course Description',
            'Status'
        ];
    }
}

We can implement the FromArray interface so we can just return an empty array since we don't have any data, and we can implement the WithHeadings interface to declare the headings the export should have.

In your Controller:

use App\Exports\CoursesTemplateExport;

public function downloadCoursesTemplate()
{
    return Excel::download(new CoursesTemplateExport(), 'Courses.xlsx');
}

This will result in the following excel:

enter image description here



Answered By - Remul
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing