public function actionImport() { $request = Yii::$app->request; if ($request->isPost) { //设置最大执行时间 ini_set("max_execution_time", "360"); $file = UploadedFile::getInstanceByName('excel'); if ($file->size > 5 * 1024 * 1024) { return $this->error('excel文件不能超过5M!'); } $relative_path = 'excel/' . date('Y') . '/' . date('m') . '/' . date('d') . '/'; $absolute_path = rtrim(\Yii::$app->params['upload_dir'], '/') . '/' . $relative_path; if (!file_exists($absolute_path)) { try { FileHelper::createDirectory($absolute_path, 0777, true); } catch (\Exception $e) { return ['errno' => 0, 'msg' => '目录创建失败,' . $e->getMessage()]; } } //文件名 $filename = date('His') . md5($file->getBaseName()) . mt_rand(1000, 9999) . '.' . $file->getExtension(); //保存文件 $file->saveAs($absolute_path . $filename); $fullFileName = $absolute_path . $filename; //将excel文件转换成数组 $data = Excel::import($fullFileName, [ 'setFirstRecordAsKeys' => true, 'getOnlySheet' => 'Sheet1', ]); $success = []; $errors = []; $excel_import_limit = \Yii::$app->params['import_max_limit']; if(count($data) > $excel_import_limit){ $errors[] = '导入数据数量超过'.$excel_import_limit.'条'; return $this->success(['success' => $success, 'errors' => $errors]); } if (empty($data)) { $errors[] = '导入数据为空!'; } else { foreach ($data as $item) { if(empty($this->admin_name) || empty($this->admin_id)){ $errors[] = '账户已过期,请重新登录!'; break; } try { $title_word_min_limit = \Yii::$app->params['import_title_word_min_limit']; $title_word_max_limit = \Yii::$app->params['import_title_word_max_limit']; if(empty(trim($item['title']))){ $errors[] = ['标题不能为空,导入失败!']; continue; }elseif(mb_strlen(trim($item['title'])) < $title_word_min_limit){ $errors[] = ['标题['.$item['title'].']字数少于'.$title_word_min_limit.'个字符,导入失败!']; continue; }elseif(mb_strlen(trim($item['title'])) > $title_word_max_limit){ $errors[] = ['标题['.$item['title'].']字数大于'.$title_word_max_limit.'个字符,导入失败!']; continue; } if (isset($item['category_id']) && !empty(trim($item['category_id']))) { //查询分类信息 $categoryInfo = Category::find()->where(['category_id' => trim($item['category_id'])])->asArray()->one(); if (empty($categoryInfo)) { $errors[] = ['险种[' . $item['category_name'] . ']不存在,导入失败!']; continue; } }else{ $errors[] = ['险种不能为空,导入失败!']; continue; } //判断标题是否在文章表存在,文章表包含自拟标题 $isExistsArticle = Article::find()->where(['title' => trim($item['title'])])->exists(); if($isExistsArticle){ throw new \Exception('此标题['.$item['title'].']已经在文章表存在!'); } $model = new Article(); $model->setAttribute('title', trim($item['title'])); $model->setAttribute('content', trim($item['content'])); $model->setAttribute('category_id', $categoryInfo['category_id']); $model->setAttribute('category_name', $categoryInfo['category_name']); if (isset($item['manager_id']) && !empty($item['manager_id'])) { $managerInfo = Manager::findOne(intval($item['manager_id'])); if(!empty($managerInfo)){ $model->setAttribute('manager_id', intval($item['manager_id'])); $model->setAttribute('manager_name', $managerInfo->manager_name); } } $model->setAttribute('status', 1); $model->setAttribute('is_recommend_title', -1); $model->setAttribute('word_count', mb_strlen(strip_tags(trim($item['content'])))); $model->setAttribute('created_at', time()); $model->setAttribute('admin_id', $this->admin_id); $model->setAttribute('admin_name', $this->admin_name); if (!$model->save()) { $errorsMsg = array_values($model->getFirstErrors()); throw new \Exception('文章[' . $item['title'] . ']保存失败!' . $errorsMsg[0]); }else{ $hashIdTool = new HashIdTool(); //生成hashID $articleHashId = $hashIdTool->getArticleIdEncode($model->article_id); $model->setAttribute('hash_id', $articleHashId); $model->setAttribute('version', 0); if(!$model->save()){ $errorsMsg = array_values($model->getFirstErrors()); throw new \Exception('文章['.$item['title'].'] HashID 保存失败,' . $errorsMsg[0]); } } //记录日志 $sysLogEvent = new SystemLogEvent(); $sysLogEvent->admin_id = $this->admin_id; $sysLogEvent->admin_name = $this->admin_name; $sysLogEvent->model = $model; $sysLogEvent->object_id = $model->article_id; $sysLogEvent->action = SystemOperateLog::ACTION_CREATE; $sysLogEvent->description = '导入文章数据'; CommonFunction::writeLog($sysLogEvent); $success[] = '[' . $item['title'] . '] 导入成功!'; } catch (\Exception $e) { $errors[] = $e->getMessage(); continue; } } } return $this->success(['success' => $success, 'errors' => $errors]); } else { return $this->render('import'); } }
Yii2导入文章数据
最新推荐文章于 2021-03-12 08:12:03 发布