控制器文件:
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还是office200337 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 else54 {55 $this->success ( '导入成功' ); 56 }57 }