yii2 phpexecl导入

composer requirephpoffice/phpexcel:"*"

public function actionImport()
    {
        $model = new Quenstion();
        $ok = "";
        if ($model->load(Yii::$app->request->post())) {
            $file = UploadedFile::getInstance($model, '字段名' );  //获取上传的文件实例
        
        if ($file) { 
            $filename = date('Y-m-d',time()).'_'.rand(1,9999).".". $file->extension;
            $file->saveAs($this->path.$filename);   //保存文件

            $format = $file->extension;
            if(in_array($file->extension,array('xls','xlsx'))){
                    $excelFile = Yii::getAlias('@frontend/web/'$this->path.$filename.'');//获取文件名

                    // $phpexcel=new \PHPExcel();
                    // if ($format == "xls") {
                    //    $excelReader = \PHPExcel_IOFactory::createReader('Excel5');
                    // } else {
                    //    $excelReader = \PHPExcel_IOFactory::createReader('Excel2007'); 
                    // }
                    
                    $fileType   = \PHPExcel_IOFactory::identify($excelFile); //文件名自动判断文件类型
                    $excelReader  = \PHPExcel_IOFactory::createReader($fileType);

                    
                    $phpexcel    = $excelReader->load($excelFile)->getSheet(0);//载入文件并获取第一个sheet
                    $total_line  = $phpexcel->getHighestRow();//总行数
                    $total_column= $phpexcel->getHighestColumn();//总列数
                    // $highestColumn = $objWorksheet->getHighestColumn();//最大列数 为数字
                    // $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); //将字母变为数字

                    if($total_line > 1){
                        for($row = 2;$row <= $total_line; $row++){
                            $data = array();
                            for($column = 'A'; $column <= $total_column; $column++){
                                $data[] = trim($phpexcel->getCell($column.$row)->getValue());
                            }

                            //一行行的插入数据库操作
                            $_model = new Quenstion;
                            $_model->content = $data[0];
                            $_model->create  = time();
                            if ($_model->save()) {
                                $ok = 1;
                            }
                        } 
                    }
                    if ($ok == 1){
                        $this->redirect(array('index']);
                    } else{
                        echo "<script>alert('操作失败');window.history.back();</script>";
                    }
            }
        }     
            
        } else {
            return $this->render('import', [
                'model' => $model,
            ]);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值