Laravel-excel操作

参考文档:
Laravel学院:http://laravelacademy.org/post/2024.html(基础操作)
简书:http://www.jianshu.com/p/6deece958a30(很多骚操作,需要时在找)

 
一、安装及准备
 使用composer安装依赖:
composer require maatwebsite/excel ~2.0.0


 在config/app.php中注册服务到providers数组中:
Maatwebsite\Excel\ExcelServiceProvider::class,


同样在config/app.php中注册门面到aliases数组:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,


 
二、 导出
先引入: use Excel;
导出:
Laravel-excel操作


//iconv('UTF-8', 'GBK', '任_测试表格') 保证中文名称不出现乱码
        Excel::create(iconv('UTF-8', 'GBK', '任_测试表格'),function($excel)use($res){
            $excel->sheet('score',function($sheet)use($res){
                $sheet->fromArray($res);//根据$res生成数据表 use必须为数组
                $sheet->setFontSize(30);//设置字体大小
            });
        })
        // ->store('xls')  在/storage/exports/ 下生成对应的表
        ->export('xls');//保存在本地
 
三、 导入
 注:导入时该表格应先上传服务器。
Laravel-excel操作


$filePath = 'storage/exports/'.iconv('UTF-8', 'GBK', '任_测试表格').'.xls';
        $res = Excel::load($filePath, function($reader) {
            //方法一
            $data1 = $reader->all()->toArray();//直接得到可用数组(注意:整形被转化为浮点型)
 
            //方法二
            $reader = $reader->getSheet(0);//excel第一张sheet
            $results = $reader->toArray();
            unset($results[0]);//去除表头
            
            //数据操作 注因为是闭包故只能在此操作数据
        });