Laravel8导出Excle文件
文章描述:
laravel8导出Excle文件
文档:https://docs.laravel-excel.com/3.1/exports/
1、使用composer命令来部署Excle
composer require maatwebsite/excel
2、使用composer命令创建Excle导出模型,文件位置app/Exports/UserExport.php
php artisan make:export UsersExport --model=User
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings; // 导出Excle表头
class UsersExport implements FromCollection,WithHeadings
{
// 指定查询字段
public function collection()
{
return User::all('id','name');
}
// 指定表头字段
public function headings(): array
{
return [
'ID',
'姓名'
];
}
}
注:如果要导出excle表头的话,需要继承表头文件。
3、使用composer命令来创建User模型,文件位置app/Models/User.php
php artisan make:model User
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $table = 'user';
public $timestamps = false;
protected $fillable = ['name', 'email','password'];
}
控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\DB;
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
class UserController extends Controller
{
//
public function index(){
$users = DB::table('user')->get();
// print_r($users);
return View::make('user',['users'=>$users]);
}
public function export(){
return Excel::download(new UsersExport,'users.xlsx');
}
}
模板
<ul>
@foreach($users as $user)
<li>{{$user->name}}</li>
@endforeach
</ul>
<div>
<a href="route('export')">Export</a>
</div>
路由
Route::get('user/export',[UserController::class,'export'])->name('export');
发布时间:2023/04/07
发表评论