首先:在extend里面引入PHPexcel文件,直接根目錄導(dǎo)入進去
html創(chuàng)建上傳按鈕
<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>
<div class="layui-form-item" style="padding-left: 35%;">
<div class="layui-input-inline" >
<button class="layui-btn" lay-submit lay-filter="formsub">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</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('sale/do_upload')}"
,accept: 'file' //普通文件
,exts: 'xls|excel|xlsx' //只允許上傳壓縮文件
,done: function(res){
if(res.code==1){
layer.msg('上傳成功,已解析數(shù)據(jù)',{icon:6});
}else{
layer.msg('解析失敗',{icon:5});
}
}
});
form.on('submit(formsub)',function(data){
layer.msg('導(dǎo)入數(shù)據(jù)具體詳情未協(xié)商確認(rèn),待確認(rèn)后處理');
return false;
})
})
</script>
在上傳后的sale/do_upload中去進行解析上傳的excel
public function do_upload(){
//引入文件
\think\Loader::import('PHPExcel.PHPExcel');
$objPHPExcel = new \PHPExcel();
//獲取表單上傳文件
$file = request()->file('file');
$info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'uploads');
//數(shù)據(jù)為空返回錯誤
if(empty($info)){
$output['status'] = false;
$output['info'] = '導(dǎo)入數(shù)據(jù)失敗~';
$this->ajaxReturn($output);
}
//獲取文件名
$exclePath = $info->getSaveName();
//上傳文件的地址
$filename = ROOT_PATH . 'public' . DS . 'uploads'.DS . $exclePath;
$extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );
\think\Loader::import('PHPExcel.IOFactory.PHPExcel_IOFactory');
if ($extension =='xlsx') {
$objReader = new \PHPExcel_Reader_Excel2007();
$objExcel = $objReader ->load($filename);
} else if ($extension =='xls') {
$objReader = new \PHPExcel_Reader_Excel5();
$objExcel = $objReader->load($filename);
}
$excel_array=$objExcel->getsheet(0)->toArray(); //轉(zhuǎn)換為數(shù)組格式
array_shift($excel_array); //刪除第一個數(shù)組(標(biāo)題);
array_shift($excel_array); //刪除th
$data=[];
foreach ($excel_array as $k=>$v){
$data[$k]["danhao"]=$v[0];//單號
$data[$k]["type_name"]=$v[1];//類型名稱
$data[$k]["name"]=$v[2];
$data[$k]["number"]=$v[3];
$data[$k]["price"]=$v[4];
$data[$k]["danwei"]=$v[0];
$data[$k]["create_user"]=$v[5];
$data[$k]["create_time"]=$v[6];
$data[$k]["remark"]=$v[7];
}
$msg=[
'code'=>1,
'msg'=>'已獲取信息',
];
$msg['data']['src']=$filename;
$msg['data']['data']=$data;
return json_encode($msg);
}
|