控制器文件:
1 class ExcelAction extends Action { 2 public function __construct() 3 { 4 import('ORG.Util.ExcelToArrary');//导入excelToArray类 5 } 6 7 public function index() 8 { 9 $this->display(); 10 } 11 public function add() 12 { 13 $tmp_file = $_FILES ['file_stu'] ['tmp_name']; 14 $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] ); 15 $file_type = $file_types [count ( $file_types ) - 1]; 16 17 /*判别是不是.xls文件,判别是不是excel文件*/ 18 if (strtolower ( $file_type ) != "xlsx" && strtolower ( $file_type ) != "xls") 19 { 20 $this->error ( '不是Excel文件,重新上传' ); 21 } 22 23 /*设置上传路径*/ 24 $savePath = C('UPLOAD_DIR'); 25 26 /*以时间来命名上传的文件*/ 27 $str = date ( 'Ymdhis' ); 28 $file_name = $str . "." . $file_type; 29 30 /*是否上传成功*/ 31 if (! copy ( $tmp_file, $savePath . $file_name )) 32 { 33 $this->error ( '上传失败' ); 34 } 35 $ExcelToArrary=new ExcelToArrary();//实例化 36 $res=$ExcelToArrary->read(C('UPLOAD_DIR').$file_name,"UTF-8",$file_type);//传参,判断office2007还是office2003 37 38 foreach ( $res as $k => $v ) //循环excel表 39 { 40 $k=$k-1;//addAll方法要求数组必须有0索引 41 $data[$k]['name1'] = $v [0];//创建二维数组 42 $data[$k]['name2'] = $v [1]; 43 $data[$k]['name3'] = $v [2]; 44 $data[$k]['name4'] = $v [3]; 45 } 46 $kucun=M('kucun');//M方法 47 $result=$kucun->addAll($data); 48 if(! $result) 49 { 50 $this->error('导入数据库失败'); 51 exit(); 52 } 53 else 54 { 55 $this->success ( '导入成功' ); 56 } 57 }
定义Excel转换数组类:
1 class ExcelToArrary { 2 public function __construct() { 3 Vendor("Excel.PHPExcel");//引入phpexcel类(注意你自己的路径) 4 Vendor("Excel.PHPExcel.IOFactory"); 5 } 6 public function read($filename,$encode,$file_type){ 7 if(strtolower ( $file_type )=='xls')//判断excel表类型为2003还是2007 8 { 9 Vendor("Excel.PHPExcel.Reader.Excel5"); 10 $objReader = PHPExcel_IOFactory::createReader('Excel5'); 11 }elseif(strtolower ( $file_type )=='xlsx') 12 { 13 Vendor("Excel.PHPExcel.Reader.Excel2007"); 14 $objReader = PHPExcel_IOFactory::createReader('Excel2007'); 15 } 16 $objReader->setReadDataOnly(true); 17 $objPHPExcel = $objReader->load($filename); 18 $objWorksheet = $objPHPExcel->getActiveSheet(); 19 $highestRow = $objWorksheet->getHighestRow(); 20 $highestColumn = $objWorksheet->getHighestColumn(); 21 $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 22 $excelData = array(); 23 for ($row = 1; $row <= $highestRow; $row++) { 24 for ($col = 0; $col < $highestColumnIndex; $col++) { 25 $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); 26 } 27 } 28 return $excelData; 29 }
前台导入页面:
1 <form method="post" action="Excel/add" enctype="multipart/form-data"> 2 <h3>导入Excel表:</h3><input type="file" name="file_stu" /> 3 4 <input type="submit" value="导入" /> 5 </form>
注意:在php.ini里面把;extension=php_zip.dll前面的分号去掉;
C('UPLOAD_DIR').$file_name是上传的excel的路径;