Yii框架是一个基于组件的大型框架,比较智能,可以自动生成代码,加速开发进程。Yii有很多的扩展,像在后台用来创建页面的bootstrap,srbac权限控制,编辑器等等,由于在目前的项目中需要处理excel数据,所以用到了PHPExcel,下面简单说下Yii中如何使用PHPExcel.
下载后解压到Yii中的protected/extensions目录下
2.如何使用?
①在main.php中配置'import'=>array(
'application.models.*',
'application.components.*',
'application.extensions.PHPExcel.*',//这里引入PHPExcel
),
②由于Yii中的autoload机制是按照类名去查找文件,即类名与文件名一致。而PHPExcel的类文件命名方式则是:dir_dir_classname.php,即文件名把文件的目录名都记录了,这种命名方式yii肯定识别不了。所以首先我们需要注销掉Yii的自动加载,找到PHPExcel中的Autoloader.php文件,修改如下:public static function Register() {
// if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
//spl_autoload_register('__autoload');
// }
// Register ourselves with SPL
// return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));
$functions = spl_autoload_functions();
foreach ( $functions as $function)
spl_autoload_unregister($function);
$functions = array_merge(array(array('PHPExcel_Autoloader','Load')),$functions);
foreach ( $functions as $function)
$x = spl_autoload_register($function);
return $x;
} // function Register()
③PHPExcel读取Excel文件中的内容
第一步:上传文件//上传文件
public function savefile($uploadfile=null){
$folder_path= Yii::getPathOfAlias('webroot').'/../uploads/customer';
if($uploadfile==null){
$uploadfile= CUploadedFile::getInstance($this,'path');
}
if($uploadfile!=null){
if(!preg_match('/(xlsx|application\/vnd.ms-excel|et)/', $uploadfile->getType())){
$fileinfo['error']=array('上传文件格式不正确,应该为.xls、.xlsx、.et格式');
}
$path = '/' . uniqid() . '-' . iconv('utf-8','gb2312', urlencode($uploadfile->getName()));//给上传的文件取别名
//若目录不存在,则创建
if(!file_exists($folder_path)){
mkdir($folder_path, 0777, true);
}
//保存上传的文件
$uploadfile->saveAs($folder_path.$path);
}else{
$path='';
}
$path= iconv('gb2312','utf-8', $path);
$fileinfo['path']=$folder_path.$path;
$fileinfo['minlength']= strlen($folder_path);
return $fileinfo;
}
第二步:读取Excel文件//读取excel文件数据
public function phpExcelRead($filePath){
$PHPExcel = new PHPExcel();
/**默认用excel2007读取excel,若格式不对,则用之前的版本进行读取*/
$PHPReader = new PHPExcel_Reader_Excel2007();
if (!file_exists($filePath) || !is_file($filePath)) {
echo '文件不存在';
return;
}
if(!$PHPReader->canRead($filePath)){
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($filePath)){
echo 'no Excel';
return ;
}
}
$PHPExcel = $PHPReader->load($filePath);//载入excel文件
$currentSheet = $PHPExcel->getSheet(0);/**取得最大的列号*/
$allColumn = $currentSheet->getHighestColumn();/**取得一共有多少列*/
$allRow = $currentSheet->getHighestRow();/**从第二行开始输出,因为excel表中第一行为列名*/
$arr = array();
for($j = 2;$j <=$allRow;$j++){
/**从第A列开始输出*/
$str ='';
for($k= 'A';$k<=$allColumn; $k++){
$str .= $PHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'\\';//读取单元格
$strs = explode("\\",$str);
}
$arr[] = $strs;
}
return $arr;
}