Laravel Excel

一.首先安装Laravel Excel

1.Composer安装依赖:

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”
二.安装好 Excel库之后,我们的上传前端页面这样写:

1.前端样式写法:

<form action=”/device/imports” method=’post’ enctype=”multipart/form-data”>
{{ csrf_field() }}
<input id=”fileId1″ type=”file” name=”file”/>
<input type=”submit” value=”确认上传”>
</form>
2.添加路由文件例如:

Route::group([‘prefix’ => ‘device’],function(){
Route::post(‘imports’, [‘uses’=>’DeviceController@imports’,’permissions’=>’device/imports’]);
});
3.后端写法,首先要文件开头要引入Excel门面类:

use Excel;
/**
* 批量导入设备
* 2018年08月22日09:58:26
*/
public function imports(){
if(!$this->_request->hasFile(‘file’)){
exit(‘上传文件为空!’);
}

$file = $_FILES;
$excel_file_path = $file[‘file’][‘tmp_name’];
$res = [];
Excel::load($excel_file_path, function($reader) use( &$res ) {
$reader = $reader->getSheet(0);
$res = $reader->toArray();
},’GBK’);
for($i = 1;$i<count($res);$i++){
$check = Device::where(‘name’,$res[$i][0])->where(‘title’,$res[$i][4])->count();
if($check){
continue;
}
//            $stu = new Device;
//            $stu->name = $res[$i][0];
//            $stu->group = $res[$i][1];
//            $stu->teacher = $res[$i][2];
//            $stu->school = $res[$i][3];
//            $stu->mobile = $res[$i][4];
//            $stu->title = $res[$i][5];
//            $stu->save();
}
//        return Device::to(‘/admin/student’)->withSuccess(“导入成功”);

}
4.之后再for循环中实现你的业务逻辑,最后入库之类。其实蛮简单的。
———————
作者:yyb5683
来源:CSDN
原文:https://blog.csdn.net/yyb5683/article/details/81940428
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lxfamn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值