前端点击按钮,导入excel文件,上传到后台,excel接收和更新数据
<extend name="Public:public"/> <block name="admin"> <div class="main-content"> <div class="container-fluid"> <!-- OVERVIEW --> <div class="container-fluid"> <div class="row"> <!-- BASIC TABLE --> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title">小米充值账号列表</h3> </div> <div class="panel-body"> <form class="form-inline" id="searchForm" method="post" action="{:U('XmrechargeBuyerAccount/index')}"> <div class="form-group" style="margin-left: 20px; margin-top: 25px" > <label for="merchant_no" style="width: 100px">备注 : </label> <input style="width: 245px" type="text" name="account" class="form-control" id="account" placeholder="请输入备注" value="{$params['desc']}"> </div> <div class="form-group" style="margin-left: 20px; margin-top: 25px" > <label for="platform_type">状态 : </label> <select style="width: 200px" class="selectbox form-control" id="status" name="status"> <option value="">--- 请选择 ---</option> <option value="1" <if condition="$params['status'] == 1">selected</if>>启用</option> <option value="2" <if condition="$params['status'] == 2">selected</if>>禁用</option> </select> </div> <div style="float: right;margin-top:23px"> 每页显示 <select class="selectbox1" onchange="changeLimit()" id="pid" name="size" style="padding: 6px 12px;background-color: #fff;border: 1px solid #ccc;border-radius: 4px;"> <option grade='10' value="10" <if condition="$params['size'] == 10">selected</if>>10</option> <option grade='25' value="25" <if condition="$params['size'] == 25">selected</if>>25</option> <option grade='50' value="50" <if condition="$params['size'] == 50">selected</if>>50</option> <option grade='100' value="100" <if condition="$params['size'] == 100">selected</if>>100</option> </select> 条 <a href="__MODULE__/XmrechargeBuyerAccount/add"><div style="margin-left: 10px;" class="btn btn-info">添加账号</div></a> <button style="margin-left: 10px;" type="submit" class="btn btn-info">查 询</button> <button style="margin-left: 10px;" type="button" class="btn btn-success" onclick="batch()">批量导入手机账号</button>
<button style="margin-left: 10px;" type="button" class="btn btn-success" onclick="batch(1)">批量导入手机账号</button>
<button style="margin-left: 10px;" type="button" class="btn btn-danger" onclick="batch(2)">批量禁用</button>
<button style="margin-left: 10px;" type="button" class="btn btn-info" onclick="batch(3)">批量启用</button>
<button style="margin-left: 10px;" type="button" class="btn btn-danger" onclick="batch(4)">批量删除</button>
<input type="hidden" id="type_value">
#第一步 设置按钮,然后点击方法
#第二步设置打开窗口layui
#第三步把隐藏的div盒子显示处理,并且写好div布局
#第四步提交文件内容
</div> </form> </div> <div class="panel-body"> <table class="table table-striped table-bordered "> <thead> <tr > <th style="width: 14%">备注</th> <th style="width: 14%">金额</th> <th style="width: 14%">状态</th> <th style="width: 14%">添加时间</th> <th style="width: 16%">操作</th> </tr> </thead> <tbody class="listTd"> <if condition="empty($list)"> <tr class="even gradeC "><td colspan="10" align="center" height="50px">没有检索到数据</td></tr> <else /> <volist name="list" id="litem"> <tr class="even gradeC " > <td style="line-height: 40px;">{$litem['desc']}</td> <td style="line-height: 40px;">{$litem['server_id']}</td> <td style="line-height: 40px;">{$ACCOUNT_STATUS[$litem['status']]}</td> <td style="line-height: 40px;">{$litem['create_time']|date="Y-m-d H:i:s",###}</td> <td> <a href="__MODULE__/XmrechargeBuyerAccount/edit?id={$litem['id']}"><button class="btn btn-info" href style="margin-top:5px;">修改</button></a> <?php if($litem['status'] == 1){ ?> <a href="javascript:void(0)" onclick="unseleve({$litem['id']},2,'禁用')"><button class="btn btn-danger" href style="margin-top:5px;">禁用</button></a> <?php }else{ ?> <a href="javascript:void(0)" onclick="unseleve({$litem['id']},1,'启用')"><button class="btn btn-info" href style="margin-top:5px;">启用</button></a> <?php } ?> <a href="javascript:void(0)" onclick="delAccount({$litem['id']})"><button class="btn btn-danger" href style="margin-top:5px;">删除</button></a> <a href="javascript:void(0)" onclick="synchronization({$litem['id']})" ><button class="btn btn-info" href style="margin-top:5px;">一键同步</button></a> </td> </tr> </volist> </if> </tbody> </table> <div class="b-page"> <div class="page "> {$page} </div> </div> </div> <!-- END BASIC TABLE --> </div> </div> </div> </div> </div> <!-- <link rel="stylesheet" type="text/css" href="__PUBLIC__/datetimepicker-master/jquery.datetimepicker.css"/ >--> <!-- <script src="__PUBLIC__/datetimepicker-master/jquery.js"></script>--> <!-- <script src="__PUBLIC__/datetimepicker-master/build/jquery.datetimepicker.full.min.js"></script>--> <script type="text/javascript"> window.onload=function(){ layui.use(['layer'], function(){ var layer = layui.layer; }) }; function delAccount(id){ layer.confirm('确认要删除吗?', { btn : [ '确定', '取消' ]//按钮 }, function(index) { $.ajax({ type: "post", url: "{:U('XmrechargeBuyerAccount/del')}", data : {id:id}, dataType: "json", async: false, success:function(response){ layer.msg(response.message,{time:1*1000},function() { if(response.flag == 1){ window.location = '__MODULE__/XmrechargeBuyerAccount/index'; } }) } }) }); } function synchronization(id){ layer.confirm('确认要一键同步吗?', { btn : [ '确定', '取消' ]//按钮 }, function(index) { $.ajax({ type: "post", url: "{:U('XmrechargeBuyerAccount/tongBu')}", data : {id:id}, dataType: "json", async: false, success:function(response){ layer.msg(response.message,{time:1*1000},function() { if(response.flag == 1){ window.location = '__MODULE__/XmrechargeBuyerAccount/index'; } }) } }) }); } /** 搜索条件时间插件结束 **/ function batch(id){
$("#type_value").val(id); layui.use('layer', function(){ var layer = layui.layer; layer.open({ offset: '10%', skin: 'layui-layer-demo', //样式类名 anim: 2, closeBtn: 1, type: 1, title: '批量导入手机账号', shadeClose: true, area: '800px', content: $('.Button_Cargo-tcb') }); }); } function do_submitb() { $.ajax({ type : 'post', url : "{:U('Admin/Base/batchExcel')}", data : formData, async:false, processData : false, contentType : false, dataType: 'json', beforeSend: function () { i = ityzl_SHOW_LOAD_LAYER(); }, success:function(response){ layer.close(i); layui.use('layer', function(){ var layer = layui.layer; top.layer.msg(response.message,{offset:'200px'}); if( response.flag == 1){ location.reload(); } }); } }) } function unseleve(id,type,msg){ layer.confirm('确认要'+msg+'吗?', { btn : [ '确定', '取消' ]//按钮 }, function(index) { $.ajax({ type: "post", url: "{:U('XmrechargeBuyerAccount/unseleve')}", data : {id:id,type:type}, dataType: "json", async: false, success:function(response){ layer.msg(msg+response.message,{time:1*1000},function() { if(response.flag == 1){ window.location = '__MODULE__/XmrechargeBuyerAccount/index'; } }) } }) }); } // 修改分页数 function changeLimit(){ $("#searchForm").submit(); } function Init(node){ return node.html("<option value=''>--- 请选择 ---</option>"); };
#第二种获取文件传输的方法
layui.use('upload', function(){
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '.test' //绑定元素
,url: "{:U('Admin/Order/batchExcel')}" //上传接口
,accept:'file'
,
,before: function(obj){ #获取传输参数
layer.load(); //上传loading
this.data={'id':$("#type_value").val()};
} ,done: function(res){
layer.open({
type: 0, //可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
title: ['提示信息', 'font-size:18px; color:orange;'],//数组第二项可以写任意css样式;如果你不想显示标题栏,你可以title: false
content: res.message,
btn: ['确定'],
yes: function(index, layero){
layer.close(index); //如果设定了yes回调,需进行手工关闭
if(res.flag == 1){
location.reload();
}
},
});
}
,error: function(){
//请求异常回调
}
});
});
</script> <div class="Button_Cargo-tcb" style="display: none"> <div class="col-xs-12" > <div class="panel panel-default" style="border: 0"> <div class="panel-body" style="margin-left: 20px;margin-right: 20px"> <form class="" id="changPwdFormb"> <div class="form-group"> <label for="APPID" class="col-sm-2 control-label" style="margin-bottom: 20px">excel文件 : </label> <div class="col-sm-9"> <input type="file"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <a class="btn btn-primary" href="javascript:do_submitb();">提 交</a> </div> </div> </form> </div> </div> </div> </div>
#新的配置方法
<div class="Button_Cargo-tcb" style="display: none">
<div class="col-xs-12" >
<div class="panel panel-default" style="border: 0">
<div class="panel-body" style="margin-left: 20px;margin-right: 20px">
<button class="layui-btn test"><i class="layui-icon"></i>上传文件</button>
<a href="/Public/demo.xls">
<button class="btn btn-success" style="height:38px;margin-left:80px;">
<i class="fa fa-download"></i> 模板下载
</button>
</a>
<span style="color:red;padding-left:50px;">/* 仅支持xls、xlsx格式Excel文件上传!!! */</span>
</div>
</div>
</div>
</div>
</block> <block name="title"> </block>
第二种模式变化:
php后端接收execl文件
/** * 备付金excel上传 */ public function batchExcel(){ header('Content-type: text/html; charset=utf-8'); vendor('PHPExcel.Classes.PHPExcel'); // 如果excel文件后缀名为.xls vendor("PHPExcel.Classes.PHPExcel.Reader.Excel5"); // 如果excel文件后缀名为.xlsx vendor("PHPExcel.Classes.PHPExcel.Reader.Excel2007"); $upload = new \Think\Upload();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->exts = array('xls','xlsx');// 设置附件上传类型 $upload->rootPath = './Public/BFJ/'; // 设置附件上传根目录 if(!is_dir($upload->rootPath)){ mkdir($upload->rootPath,0777,true); } // 上传单个文件 $info = $upload->uploadOne($_FILES['file']); if(!$info) { $response = array( 'flag' => -1, 'message' =>$upload->getError() ); echo json_encode($response);exit; } $file = $upload->rootPath.$info['savepath'].$info['savename']; if($info['ext']=="xlsx"){ $PHPReader = new \PHPExcel_Reader_Excel2007(); //xlsx } if($info['ext']=="xls"){ $PHPReader = new \PHPExcel_Reader_Excel5(); //xls } // 载入文件 $Excel = $PHPReader -> load($file); //获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推 $currentSheet = $Excel -> getSheet(0); //获取总列数 $allColumn = $currentSheet -> getHighestColumn(); //获取总行数 $allRow = $currentSheet -> getHighestRow(); //循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始 for($currentRow = 2; $currentRow <= $allRow; $currentRow++) { //从哪列开始,A表示第一列 for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) { //数据坐标 $address = $currentColumn . $currentRow; //读取到的数据,保存到数组$arr中 $arr[$currentRow][$currentColumn] = $currentSheet ->getCell($address) ->getValue(); } } if(!$arr){ $response = array( 'flag' => -1, 'message' =>"excel无有效数据" ); echo json_encode($response);exit; } foreach($arr as $k=>$v){ $n = $k-1; if(empty($v['A']) || empty($v['B']) || empty($v['C']) || empty($v['D']) || empty($v['E']) || empty($v['F']) || empty($v['I'])){ $response = array( 'flag' => -1, 'message' =>"第{$n}条数据有误" ); //self::exceldc($arr); echo json_encode($response);exit; } if($v['D']!="个人账户" && $v['D']!="对公账户" && $v['D']!="支付宝"){ $response = array( 'flag' => -1, 'message' =>"第{$n}条银行账户类型有误," ); //self::exceldc($arr); echo json_encode($response);exit; } if($v['I']>50000){ $response = array( 'flag' => -1, 'message' =>"第{$n}条金额不能大于50000" ); echo json_encode($response);exit; } //通过商户号获取业务员ID $sales_id_arr = M("MerchantInfo")->where(array('platform_merchant_no'=>$v['B']))->Field('sales_id')->find(); if(!$sales_id_arr){ $response = array( 'flag' => -1, 'message' =>"第{$n}条商户号不匹配" ); //self::exceldc($arr); echo json_encode($response);exit; } if($v['D']=='个人账户'){ $accountType = 1; }elseif($v['D']=='对公账户'){ $accountType = 2; }else{ $accountType = 3; } $param[] = [ 'num' => $n,//条数 'orderId' => $v['A'],//商户流水号 'mer_id' => $v['B'], //商户号 'accountName' => $v['C'], //银行账户名 'accountType' => $accountType, //银行账户类型 'accountNumber' => $v['E'], //银行账户号 'openingBank' => $v['F'], //开户行 'account_area' => $v['G'], //开户行地区 'sub_branch' => $v['H'], //开户行支行 'totalAmount' => $v['I'], //代付金额 'remark' => $v['J'], //备注 'notifyUrl' => $v['K'], //回调通知路径 'sales_id' => $sales_id_arr['sales_id'], //开户行支行 ]; } $success = []; foreach ($param as $k=>$v){ $result = self::DfOnlyMore($v); if($result['flag']!=1){ $response = array( 'flag' => -1, 'message' =>"<p>当前流水号 <span style='color:red'>".$v['orderId']."</span> 发起代付订单失败,<p/><p>原因为:".$result['message']."。</p><p style='color:red'>此流水号之前的代付订单均已发起成功,请注意</p>" ); echo json_encode($response);exit; } $success[] = $v; } $response = array( 'flag' => 1, 'message' =>"excel导入成功" ); //批量导入记录 $logContent = "\r\n"; $logContent .= "Datetime: ".date("Y-m-d H:i:s").' time: '.time()."\r\n"; $logContent .= "excel_file: ".$file."\r\n"; $logContent .= "success: ".$success."\r\n"; $logContent .= "sales_id: ".$_SESSION['sales']['id']."\r\n"; $logContent .= "管理员操作excel批量导入结果".json_encode($response)."\r\n"; $this->writeLog($logContent, "SalesDf"); echo json_encode($response);exit; }
public function writeLog ($content,$filename='create') { $logFileDir = DOCUMENT_ROOT.'/Log'; $path = $logFileDir.'/'.$filename ; if (!is_dir($path)){ mkdir($path,0777); } $file = $path.'/'.date('Y_m_d').'_'.$filename.'.txt'; file_put_contents($file,$content.PHP_EOL,FILE_APPEND); // 最简单的快速的以追加的方w式写入写入方法, }