PHPExcel 导入

首先:

//包含excel的类库
require APPPATH . 'third_party/PHPExcel.php';
require APPPATH . 'third_party/PHPExcel/Reader/Excel2007.php';

导入:

    $excel_reader = new PHPExcel_Reader_Excel2007();
        try {
            if (!$excel_reader->canRead($file_name)) {
                return $this->output("无法读取文件",1);
            }
            $obj = $excel_reader->load($file_name);
            // 读取excel文件中的第一个工作表
            $currentSheet = $obj->getSheet(0);
            //
            $allColumn = $currentSheet->getHighestColumn();
            //
            $allRow = $currentSheet->getHighestRow();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($allColumn);//总列数
            $headtitle =array();
            for($cols =0 ;$cols<=$highestColumnIndex;$cols++){
                $headtitle[$cols] =(string)$currentSheet->getCellByColumnAndRow($cols, 1)->getValue();
            }
            if(empty($headtitle[0])){
                for($cols =0 ;$cols<=$highestColumnIndex;$cols++){
                    $headtitle[$cols] =(string)$currentSheet->getCellByColumnAndRow($cols, 2)->getValue();
                }
            }
           
            for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
                /**从第A列开始输出*/
                for($cols =0 ;$cols<=$highestColumnIndex;$cols++){
                    $data[$currentRow - 2][$cols] =(string)$currentSheet->getCellByColumnAndRow($cols, $currentRow)->getValue();
                }
            }
        } catch (Exception $e) {
            @unlink($file_name);
        
        }
        //删除临时文件
        @unlink($file_name);

再将导入数据保存到数据库即可。

posted @ 2017-03-22 14:27  还是小黑  阅读(232)  评论(0编辑  收藏  举报