This article mainly introduces the file export function using LaravelExcel in Laravel5. It has certain reference value. Now I share it with you. Friends in need can refer to it.
1. Installation
Here I installed version 2.1.0 of maatwebsite/excel
composer require "maatwebsite/excel:~2.1.0"
Settings after installation
In config/app Register the service provider in .php to the providers array:
Maatwebsite\Excel\ExcelServiceProvider::class,
Also register the facade to the aliases array in config/app.php:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
If you want to customize Laravel Excel more Define the configuration and execute the following Artisan command:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
2. Export the data
Add routing
// excel exportRoute::get('/monitor/export','Admin\ExcelController@export')->name('monitor.export');
Create the controller
php artisan make:controller Admin/ExcelController
Add some code in the control
<?php namespace App\Http\Controllers\Admin;use Illuminate\Http\Request; use App\Http\Controllers\Controller;use Excel;use App\Models\Monitor; use App\Exports\CunliangExport;class ExcelController extends Controller { public function export() { //return Excel::download(new CunliangExport, 'invoices.xlsx'); $data = Monitor::get()->toArray(); return Excel::create('数据更新', function($excel) use ($data) { $excel->sheet('数据更新', function($sheet) use ($data) { $sheet->cell('A1', function($cell) {$cell->setValue('update_date'); }); $sheet->cell('B1', function($cell) {$cell->setValue('file_type'); }); $sheet->cell('C1', function($cell) {$cell->setValue('file_num'); }); $sheet->cell('D1', function($cell) {$cell->setValue('space_size'); }); $sheet->cell('E1', function($cell) {$cell->setValue('exec_time'); }); $sheet->cell('F1', function($cell) {$cell->setValue('created_at'); }); if (!empty($data)) { foreach ($data as $key => $value) { $i= $key+2; $sheet->cell('A'.$i, $value['update_date']); $sheet->cell('B'.$i, $value['file_type']); $sheet->cell('C'.$i, $value['file_num']); $sheet->cell('D'.$i, $value['space_size']); $sheet->cell('E'.$i, $value['exec_time']); $sheet->cell('F'.$i, $value['created_at']); } } }); })->download('xlsx'); } }
Add the following code to the blade template file
. . .<p class="box-header"> <a class="btn btn-success" href="{{route('monitor.export')}}">导出</a></p>. . .
Just change it according to your needs.
Related recommendations:
Laravel5 implements fuzzy matching function
Laravel5.5 new feature error reporting
The above is the detailed content of Using LaravelExcel to implement file export function in Laravel5. For more information, please follow other related articles on the PHP Chinese website!