php Excel 导入功能

下载excel类地址 https://pan.baidu.com/s/1OfPmq4dKAaxBUSbQ3an8ZQ  密码:kmh2

本人用的thinkcmf框架 把类文件放在框架的类文件里面,下面直接上代码

注:excel一定要放在框架公共类文件里面,因为这个本人绕了好久,一直报错。所以请大家注意。

function exceladd($sheet=0){ 
        $file = $_FILES['excel']['tmp_name'];
        $file = iconv("utf-8", "gb2312", $file);   //转码 
        if(empty($file) or !file_exists($file)) { 
            die('file not exists!'); 
        } 
         vendor('PHPExcel.Classes.PHPExcel');//引用类文件
        $objRead = new \PHPExcel_Reader_Excel2007();   //实例化 建立reader对象 
        if(!$objRead->canRead($file)){ 
            $objRead = new \PHPExcel_Reader_Excel5(); 
            if(!$objRead->canRead($file)){ 
                die('No Excel!'); 
            } 
        } 
       
        $cellName = array('A', 'B', 'C', 'D'); 
       
        $obj = $objRead->load($file);  //建立excel对象 
        $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表 
        $columnH = $currSheet->getHighestColumn();   //取得最大的列号 
        $columnCnt = array_search($columnH, $cellName); 
        $rowCnt = $currSheet->getHighestRow();   //获取总行数 
       
        $data = array(); 
        for($_row=2; $_row<=$rowCnt; $_row++){  //读取内容 
            for($_column=0; $_column<=$columnCnt; $_column++){ 
                $cellId = $cellName[$_column].$_row; 
                    $cellValue = $currSheet->getCell($cellId)->getValue(); 
                    if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串 
                        $cellValue = $cellValue->__toString(); 
                    } 
               
                $data[$_row][$cellName[$_column]] = $cellValue; 
            } 
        } 
       return $data;
       
       
    } 

  因为根据本人需求,excel表第一行是名称,所以在获取的时候,没有获取第一行名称,所以在循环的时候$_row = 2 从2开始。

 

posted @ 2019-04-23 15:14  小ྀ青ྀ年້  阅读(2057)  评论(0编辑  收藏  举报