1 year ago

How to export database table to excel file in laravel

Posted 1 year ago by konrms

Hi guys.

I'm trying to export the table "formal", to a simple excel file. I have installed the packet necessary with "composer require maatwebsite/excel" command from cmd and also have edited my app.php file adding "Maatwebsite\Excel\ExcelServiceProvider::class," to providers and "'Excel' => Maatwebsite\Excel\Facades\Excel::class," to aliases.

My blade successfully shows "formal" as html. Now I have added a second button with export to excel option. Unfortunately, I'm getting an error "Call to undefined method Maatwebsite\Excel\Excel::create()" when pressing "Download excel button".

Could you help me please?

This is my blade with the "Download excel" button added.

<!DOCTYPE html>
<html lang="el">
    <meta charset="UTF-8">

<b>Programme: {{ $key }}</b>

<table border="1">
        <th>Column n</th>
    @foreach($star as $v2)
        <th>{{ $v2->category }}</th>
        <td>{{ $v2->code }}</td>
        <td>{{ $v2->title }}</td>

	<td>{{ $v2->... }}</td>

<form action = '/excel'>
	<input type="submit" value="Download excel">

<form action ='/programma'>
    <input type="submit" value="New Search" />


This is the ExportExcelController:

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;  

class ExportExcelController extends Controller
	public function excel()
		$formal_data = DB::table('formal')->get()->toArray();
		$programma_array[] = array('category', 'code', 'title', 'dep', 'pms',
		foreach($formal_data as $pass)
			$programma_array[] = array
			'category'  => $pass->category,
			'code'   => $pass->code,
			'title'    => $pass->title,
			Excel::create('Programma_Data', function($excel) use ($programma_array)
				$excel->sheet('Programma_Data', function($sheet) use ($programma_array)
					$sheet->fromArray($programma_array, null, 'A1', false, false);
			}) -> download('xlsx');

And my web.php

Route::get('/excel', '[email protected]')->name('export_excel.excel');

Please sign in or create an account to participate in this conversation.