把这些方法都放到controller控制器类里面,如果封装成公共方法,要注意导入的EXCEL类的路径问题
一、下载PHPExcel
PHPExcel官网:http://phpexcel.codeplex.com/
PHPExcel On GitHub:https://github.com/PHPOffice/PHPExcel
然后把文件放在TP框架里面
二、逻辑代码
1、文件上传处理
/**
* 上传的文件信息
* @var array
*/
public $fileInfo=array();
public function _initialize(){
//检查上传的文件是否合法
$this->fileInfo=$this->checkUploadFile(array('xls','xlsx'),这里写文件的相对路径);
}
/**
* 检查上传的文件
* @param array $exts
* @return array|bool
*/
public function checkUploadFile($exts=array('jpg', 'gif', 'png', 'jpeg'),$savePath=''){
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728 ;// 设置附件上传大小
$upload->exts = $exts;// 设置附件上传类型
$upload->savePath = $savePath?$savePath:''; // 设置附件上传目录,留空则默认文件夹
// 上传文件
$info = $upload->upload();
if(!$info) {
$res['status']=-100;
$res['upload_info']=$upload->getError();
}else{// 上传成功
foreach($info as $file){
$res['file_path'][]='/Uploads'.$file['savepath'].$file['savename'];//文件路径
$res['file_ext']=$file['ext'];
}
$res['file_path'] = implode(',',$res['file_path']);//把数组用,拼接
$res['status']=10000;
$res['upload_info']='文件上传成功!';
}
return $res;
}
注意:把返回的 文件信息,赋值给全局变量,$fileInfo,下面就是用此变
2、文件上传成功处理:读取EXCEL
/**
* 导入Excel
*/
public function getExcel(){
if($this->fileInfo['status'] == 10000){
Vendor("PHPExcel");//导入excel类
Vendor('PHPExcel.IOFactory');//导入excel的其它类
//按文件扩展名导出
switch ($this->fileInfo['file_ext']){
case 'xls':
$excelType = 'Excel5';//Excel5支持2003或以下版本,Excel2007代表2007版
break;
case 'xlsx':
$excelType = 'Excel2007';//Excel5支持2003或以下版本,Excel2007代表2007版
break;
}
$excelReader=\PHPExcel_IOFactory::createReader($excelType);
$excelReader->setReadDataOnly(true);//只读取
if(!file_exists('./'.$this->fileInfo['file_path'])){
$res['status']=-100;
$res['upload_info']='文件不存在!';
}else{
$getExcelReader=$excelReader->load('./' .$this->fileInfo['file_path']);
$array = $getExcelReader->getSheet()->toArray();//获取整个表格的数据,转成数组
}
$array)就是导入的EXCEL表格的数据,这里自行做处理
}else{
echo json_encode($this->fileInfo);
exit();
}
}
三、PHPexcel导入功能完成了