前端代码
<form class="layui-form" method="post" action="">
<div class="layui-form-item" >
<label class="layui-form-label">上传excel</label>
<div class="layui-input-inline">
<div class="layui-upload">
<button type="button" name="myfile" class="layui-btn" id="myfile"><i class="layui-icon"></i>上传文件</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
layui.use(['form','upload'],function(){
var form=layui.form;
var upload=layui.upload;
upload.render({ //允许上传的文件后缀
elem: '#myfile'
,url: "{:url('zhoubian/do_upload')}"
,accept: 'file' //普通文件
,exts: 'xls|excel|xlsx'
,done: function(res){
if(res.code===1){
layer.msg(res.msg,{icon:6});
}else{
layer.msg('解析失败',{icon:5});
}
}
});
form.on('submit(formsub)',function(data){
layer.msg('导入数据具体详情未协商确认,待确认后处理');
return false;
})
});
</script>
后台PHP接口
//导入excel接口,将数据放入缓存中
public function do_upload(){
$file=request()->file("file");
$info=$file->move(ROOT_PATH.'public'.DS . 'uploads'.DS."zhoubian");
$file_name="";
if($info){
$file_name = $info->getSaveName();
}else{
$this->error("错误,未获取到文件信息");
}
//引入文件
\think\Loader::import('PHPExcel.PHPExcel');
$objPHPExcel = new \PHPExcel();
$filename = ROOT_PATH.'public'.DS . 'uploads'.DS ."zhoubian".DS.$file_name;
$filename=iconv('GB2312','UTF-8',$filename);
if(is_file($filename)==false){
$this->error("未发现文件!");
}
$extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );
\think\Loader::import('PHPExcel.IOFactory.PHPExcel_IOFactory');
//使用 PHPExcel_IOFactory 来鉴别文件应该使用哪一个读取类
$inputFileType = \PHPExcel_IOFactory::identify($filename);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
//只设为读取,加快读取速度
$objReader->setReadDataOnly(true);
$objExcel = $objReader->load($filename);
$sheet = $objExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
// 取得总列数
$highestColumn = $sheet->getHighestColumn();
//循环读取excel文件,读取一条,插入一条
$excel_array=array();
//从第一行开始读取数据
for($j=1;$j<=$highestRow;$j++){
//从A列读取数据
for($k='A';$k<=$highestColumn;$k++){
// 读取单元格
$excel_array[$j][]=$objExcel->getActiveSheet()->getCell($k.$j)->getFormattedValue();
}
}
var_dump($excel_array);die();
//unset($excel_array[1]);
$data=[];
foreach ($excel_array as $k=>$v){
$data[$k]["store"]=$v["1"];
$data[$k]["goods"]=$v["5"];
}
//获取解析excel后的数组
$final_arr=$this->tongji($data);
if(!empty($final_arr)){
//设置快递excel的数据缓存
Cache::set("Kdexcel",$final_arr,6000);
$msg=[
'code'=>1,
'msg'=>"解析成功",
];
}else{
$msg=[
'code'=>0,
'msg'=>"解析失败!",
];
}
return json($msg);
}
注意点:
1.我用的TP5框架,PHPexcel放的目录如下图,把phpexcel的源码下下来后,放到extend扩展目录里面