欢迎访问优讯网!
您当前的位置:首页 > 爱编程

yii2.0框架实现上传excel文件后导入到数据库的方法示例

时间:2020-04-14 14:25:07  来源:优讯网  作者:小卡司  浏览次数:
这篇文章主要介绍了yii2.0框架实现上传excel文件后导入到数据库的方法,结合实例形式详细分析了yii2.0上传excel文件后导入到数据库的相关模型、视图、控制器实现技巧,需要的朋友可以参考下

本文实例讲述了yii2.0框架实现上传excel文件后导入到数据库的方法。分享给大家供大家参考,具体如下:

Model模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/**
 * 描述...
 * @author zcy
 * @date 2019/8/13
 */
 
namespace app\models;
 
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;
 
class uploadForm extends ActiveRecord
{
  public $file;
 
  public function rules()
  {
    return [
      [['file'],'file', 'skipOnEmpty' => false,'extensions' => 'xls,xlsx'],
    ];
  }
 
  public function attributeLabels()
  {
    return [
      'file'=> '上传文件'
    ];
  }
 
  public function upload()
  {
    $file = UploadedFile::getInstance($this, 'file');
 
    if ($this->rules()) {
      $tmp_file = $file->baseName . '.' . $file->extension;
      $path = 'upload/' . 'Files/';
      if (is_dir($path)) {
        $file->saveAs($path . $tmp_file);
      } else {
        mkdir($path, 0777, true);
      }
      $file->saveAs($path . $tmp_file);
      return true;
    } else {
      return '验证失败';
    }
  }
 
}

Views视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
use yii\widgets\ActiveForm;
 
$model = new app\models\uploadForm();
$form = ActiveForm::begin([
  'id' => 'upload',
  'options' => ['enctype' => 'multipart/form-data'],
])
?>
 
<?= $form->field($model,'file')->fileInput(['multiple'=>'multiple']) ?>
 
  <button>上传</button>
<?php ActiveForm::end() ?>

Controller控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/**
 * 描述...
 * @author zcy
 * @date 2019/8/16
 */
 
namespace app\controllers;
 
use app\models\uploadForm;
use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
 
class UploadController extends Controller
{
  /**
   * 导入
   * @author zcy
   * @date 2019/8/16
   */
  public function actionImport()
  {
    $model = new uploadForm();
 
    if (Yii::$app->request->isPost) {
      $model->file = UploadedFile::getInstance($model,'file');
//      if ($model->upload()) {
//        print <<<EOT
// <script>alert('上传成功')</script>
//EOT;
//      } else {
//        print <<<EOT
// <script>alert('上传失败')</script>
//EOT;
//      }
      if (!$model->upload()) {
        print <<<EOT
 <script>alert('上传失败')</script>
EOT;
      }
    }
 
    $ok = 0;
    if ($model->load(Yii::$app->request->post())) {
      $file = UploadedFile::getInstance($model,'file');
 
      if ($file) {
        $filename = 'upload/Files/' . $file->name;
        $file->saveAs($filename);
 
        if (in_array($file->extension,array('xls','xlsx'))) {
          $fileType = \PHPExcel_IOFactory::identify($filename);
//文件名自动判断类型
          $excelReader = \PHPExcel_IOFactory::createReader($fileType);
 
          $phpexcel = $excelReader->load($filename)->getSheet(0);
//载入文件并获取第一个sheet
          $total_line = $phpexcel->getHighestRow();//总行数
          $total_column = $phpexcel->getHighestColumn();//总列数
 
          if (1 < $total_line) {
            for ($row = 2;$row <= $total_line;$row++) {
              $data = [];
              for ($column = 'A';$column <= $total_column;$column++) {
                $data[] = trim($phpexcel->getCell($column.$row));
              }
 
              $info = Yii::$app->db->createCommand()
->insert('{{%shop_info}}',['shop_name' => $data[0],'shop_type' => $data[1]])
->execute();
 
              if ($info) {
                $ok = 1;
              }
            }
          }
 
          if ($ok == 1) {
            echo "<script>alert('导入成功');window.history.back();</script>";
          } else {
            echo "<script>alert('操作失败');window.history.back();</script>";
          }
        }
      }
    } else {
      return $this->render('import',['model' => $model]);
    }
  }
}
来顶一下
返回首页
返回首页

原文链接:https://www.jb51.net/article/184605.htm


推荐资讯
如何下载旧版centos iso镜像 如何下载迷你mini版的centos镜像
如何下载旧版centos i
计算机的正确使用姿势 电脑痴如何正确的使用电脑
计算机的正确使用姿势
好用的后台管理的前端框架模版H-ui H-ui框架模版分享
好用的后台管理的前端
微信电脑多开方法 无需辅助电脑版微信双开方法分享
微信电脑多开方法 无
相关文章
栏目更新
栏目热门