🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
在 Laravel 5 中使用 Laravel Excel 实现 Excel文件导入导出功能 ----需进行安装&配置 使用laravel进行excel导出 - 定义路由 - 链接数据库(.env config-database.php) - 创建模型&控制器 ~~~ <?php namespace App\Http\Controllers; use App\Models\MemberInfo; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Excel; class MemberInfoController extends Controller{ //打印member_info表中数据 public function export(){ //取回要打印的数据 $memberinfos = MemberInfo::all(); //声明一个空数组并存入置顶栏备注信息 $celldata = []; $celldata[] = ['id','花名','真名','入职时间','电话号码']; //将需要打印的数据字段 id nickname name jobtime job phone 赋值给变量 foreach ($memberinfos as $key=>$memberinfo){ $id = $memberinfo->id; $nickname = $memberinfo->nickname; $name = $memberinfo->name; $jobtime = $memberinfo->jobtime; $phone = $memberinfo->phone; $celldata[] = [$id,$nickname,$name,$jobtime,$phone]; } Excel::create('用户详情',function($excel) use ($celldata){ $excel->sheet('score', function($sheet) use ($celldata){ $sheet->rows($celldata); }); })->export('xls'); } } ~~~ 参考文档:http://laravelacademy.org/post/2024.html 优化后: ~~~ <?php namespace App\Http\Controllers; use App\Models\MemberInfo; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Excel; class MemberInfoController extends Controller{ //打印member_info表中数据 public function export(){ //取回要打印的数据(指定字段)并转成数组 $memberinfos = MemberInfo::all(['id','nickname','name','jobtime','phone'])->toArray(); //将需要打印的数据字段 id nickname name jobtime job phone 赋值给变量 $celldata = [['id','花名','真名','入职时间','电话号码']]; //合并数组添加分栏置顶备注 $celldata = array_merge($celldata,$memberinfos); Excel::create('用户详情',function($excel) use ($celldata){ $excel->sheet('score', function($sheet) use ($celldata){ $sheet->rows($celldata); $sheet->setWidth(['D'=>100]); //设置单元格样式 $count = count($celldata); $sheet->cells("B1:B$count", function($cells) { $cells->setFontWeight('bold'); }); }); })->export('xls'); } } ~~~