1.上代码
<?php
namespace app\manage\controller;
use think\Controller;
use think\Request;
use think\Cookie;
use think\Session;
use think\Db;
use org\util\ExcelToArrary ;
use app\manage\controller\Base;
class Customer extends Base
{
public function do_upload(Request $request){
$file=request()->file("file");
$info=$file->move(ROOT_PATH.'public'.DS . 'uploads'.DS."file");
$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 ."file".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');
$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_array=array();
for($j=1;$j<=$highestRow;$j++){
for($k='A';$k<=$highestColumn;$k++){
$excel_array[$j][]=$objExcel->getActiveSheet()->getCell($k.$j)->getFormattedValue();
}
}
unset($excel_array[1]);
foreach ($excel_array as $k=>$v){
$res = Db::name("customer")->where('company','=',$v[0])->find();
if(!$res) {
$data['company'] = $v[0];
$data['contact_name'] = $v[1];
$data['contact'] = $v[2];
$data['address'] = $v[3];
$data['create_time'] = time();
$customer_id = Db::name("customer")->insertGetId($data);
$data_contact['name'] = $v[1];
$data_contact['mobile'] = $v[2];
$data_contact['create_time'] = time();
$data_contact['customer_id'] = $customer_id;
Db::name("contact")->insert($data_contact);
}
}
$msg=[
'code'=>200,
'msg'=>"成功导入数据!",
];
return json($msg);
}
}
2.1 前端代码-js部分
var form=layui.form;
var upload=layui.upload;
upload.render({
elem: '#myfile'
,url: "{:url('customer/do_upload')}"
,accept: 'file'
,exts: 'xls|excel|xlsx'
,done: function(res){
if(res.code===200){
layer.msg('数据导入成功!', {
offset: '15px'
,icon: 1
,time: 1000
}, function(){
location.href = "{:url('manage/customer/index')}";
});
}else{
layer.msg('操作失败',{icon:5});
}
}
});
form.on('submit(formsub)',function(data){
layer.msg('导入数据具体详情未协商确认,待确认后处理');
return false;
})
2.2 前端代码-htm部分
<form class="layui-form" method="post" action="" style="float: left">
<div class="layui-input-inline">
<div class="layui-upload">
<button type="button" name="myfile" class="layui-btn layui-btn-danger" id="myfile"><i class="layui-icon"></i>excel批量导入数据</button>
</div>
</div>
</form>
3.phpexcel库文件位置