您的位置:首页 > 编程语言 > PHP开发

thinkphp5 , tp5 导入 Excel ,phpExcel 插件使用,文件上传

2017-05-31 16:33 816 查看
HTML

<form action="/index.php?m=Admin&c=TaoBao&a=do_upload" enctype="multipart/form-data" method="post" style="display: none;" id="uploadForm">
<input type="file" name="excel" id="file_excel" value="" onchange="select_file_excel()"/>
<a class="btn red" onclick="file_excel()"><i class="fa fa-fax"></i>导入数据</a>
</form>


JS

//导入excel
function file_excel(){
$("#file_excel").click();
}

//选择文件
function select_file_excel() {

$.ajax({
url: '你的上传路径',
type: 'POST',
cache: false,
data: new FormData($('#uploadForm')[0]),
dataType:'json',
processData: false,
contentType: false,
success:function(json){
//清空内容
$("#file_excel").val('');

//返回提示信息
//todo 待处理代码
}
});
}


PHP

<?php
namespace app\admin\controller;
use think\Db;

//此父类可能有变动,自行修改
class TaoBao extends Base{

public function do_upload(){

//引入文件(把扩展文件放入vendor目录下,路径自行修改)
vendor("PHPExcelClass.PHPExcel");

//获取表单上传文件
$file = request()->file('excel');
$info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'TaoBao');

//数据为空返回错误
if(empty($info)){
$output['status'] = false;
$output['info'] = '导入数据失败~';
$this->ajaxReturn($output);
}

//获取文件名
$exclePath = $info->getSaveName();
//上传文件的地址
$filename = ROOT_PATH . 'public' . DS . 'upload' . DS . 'TaoBao'. DS . $exclePath;

//判断截取文件
$extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );

//区分上传文件格式
if($extension == 'xlsx') {
$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
}else if($extension == 'xls'){
$objReader =\PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
}

$excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
array_shift($excel_array);  //删除第一个数组(标题);
$city = [];
foreach($excel_array as $k=>$v) {
if(empty(Db::name('excel_shop')->where(['goods_id'=>$v[0]])->value('name'))){
$city[$k]['goods_id'] = $v[0];
//$city[$k]['xxx'] = $v[1];
//$city[$k]['xxx'] = $v[2];
}
}

Db::name('excel_shop')->insertAll($city); //批量插入数据
$output['status'] = true;
$output['info'] = '导入数据成功~';
$this->ajaxReturn($output);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐