最新版 composer require maatwebsite/excel
1、安装的是maatwebsite/excel的2.1.0版本
composer require "maatwebsite/excel:~2.1.0"
注:此命令易报错,最好在网速好的情况下跑2、在config/app.php中注册服务提供者到providers添加
Maatwebsite\Excel\ExcelServiceProvider::class,3、在config/app.php中注册门面到aliases添加:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,4、对Laravel Excel进行更多的自定义设置
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"5、设置路由
Route::get('/user/export','Admin\ExcelController@export');6、创建控制器
php artisan make:controller Admin/ExcelController<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Excel;
use App\User;
use App\Exports\CunliangExport;
class ExcelController extends Controller
{
public function export()
{
//return Excel::download(new CunliangExport, 'invoices.xls');
$data = User::get()->toArray();
return Excel::create('注册用户表', function($excel) use ($data) {
$excel->sheet('用户列表', function($sheet) use ($data)
{
$sheet->cell('A1', function($cell) {$cell->setValue('编号'); });
$sheet->cell('B1', function($cell) {$cell->setValue('姓名'); });
$sheet->cell('C1', function($cell) {$cell->setValue('邮箱'); });
$sheet->cell('D1', function($cell) {$cell->setValue('电话'); });
$sheet->cell('E1', function($cell) {$cell->setValue('性别'); });
$sheet->cell('F1', function($cell) {$cell->setValue('注册时间'); });
if (!empty($data)) {
foreach ($data as $key => $value) {
$i= $key+2;
$sheet->cell('A'.$i, $value['id']);
$sheet->cell('B'.$i, $value['name']);
$sheet->cell('C'.$i, $value['email']);
$sheet->cell('D'.$i, $value['mobile']);
$sheet->cell('E'.$i, $value['sex']);
$sheet->cell('F'.$i, $value['created_at']);
}
}
});
})->download('xls');
}
}
在blade模板文件添加以下代码
<div class="box-header">
<a class="btn btn-success" href="/user/export">导出</a>
</div>备注:导出的数字过长如:身份证,会进行科学计数,则需在导出值前加空格
$sheet->cell('E'.$i, ' '.$value['card']);