在yii中将CSV文件导入数据库?

时间:2016-06-08 08:26:42

标签: php csv yii

我想通过验证将.csv文件重要到数据库表。

我在添加用户表单上有一个函数add user,它对分机号码进行了验证,这是唯一的..

我还可以选择使用.csv文件添加批量用户。我可以添加用户但是如何为其添加验证,当我尝试上传带有用户详细信息的.csv文件时,它应显示错误extension is already used,但上传其他分机号码。

例如,如果.csv有100个用户,上传了80个用户,但由于他们的分机号码已经存在于数据库表中,因此没有上传20个用户,所以我希望这些20个用.csv文件导出。并显示错误。

我的模特是

我有一家公司,每家公司都有很多用户,每个用户都有唯一的分机号码。如果分机号码100分配给用户1,则无法将其分配给用户2。

我怎样才能做到这一点?任何建议,帮助一些代码。?感谢

2 个答案:

答案 0 :(得分:1)

通常,如果您在任何DataBase中使用Yii,您应该维护一个扩展ActiveQuery的Model类,如下所示:

<?php

namespace common\models;

use Yii;

class Profile extends \yii\db\ActiveRecord
{
public static function tableName()
{
    return 'TABLE_NAME';
}

public function rules()
{
    return [
        [['Phone', 'Email'], 'required'],
        [['Phone'], 'string', 'max' => 30],
        [['Email'], 'string', 'max' => 100],
    ];
}

public function attributeLabels()
{
    return [
        'Phone' => Yii::t('profile', 'Phone'),
        'Email' => Yii::t('profile', 'Email')
    ];
}

如您所见,您可以在return的{​​{1}}中声明您的验证规则。这里的示例中的那些非常简单,但是,存在许多其他内置验证器以及使用您自己的自定义验证器的能力,包括添加JS验证的可能性。您可以阅读更多相关信息here

现在,当您使用模型时,您必须将数据加载到其中并验证它以便以后保存它。首先,在我看来,确保您的输入在PHP服务器上输入有效(在本例中为.csv文件)之前更正确,而不是从DataBase的验证引擎收到“硬错误” 。无论如何,为了将数据加载到模型中,我们首先需要将.csv作为字符串加载。为此,将.csv放入项目文件夹,例如function rules()

\common\models\file.csv

剩下的就是将<?php $csv = file_get_contents(Yii::getAlias('@app/common/models/').'file.csv'); $csvArray = str_getcsv($csv); $errorCsvArray = []; foreach ($csvArray as $newEntry) { $model = new \common\models\Profile(); if ($model->load($newEntry)) { $model->save(); } else { $errorCsvArray[] = $model->errors; } } 转换为$errorCsvArray。这样做的一种方法是here

此外,请注意.csv在填充模型之前也会验证。有关load()load()validate()save()的更多内容,您可以找到here

答案 1 :(得分:0)

在我的Yii应用程序中也有员工导入。在该唯一字段中是员工代码。我的功能是,

 public function actionEmployeeimport() {
    $model = new ContactForm;
    if (isset($_POST['ContactForm'])) {
        $model->attributes = $_POST['ContactForm'];
        $uploadedFile = CUploadedFile::getInstance($model, 'filea');
        if ($uploadedFile == "") {
            Yii::app()->user->setFlash('error', 'Please select a file.');
        } else {
            $allowed = array('xlsx', 'xls');
            $filename = CUploadedFile::getInstance($model, 'filea');
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if (!in_array($ext, $allowed)) {
                throw new CHttpException(404, 'File extension error. The allowed extension is xlsx.');
                exit(0);
            } else {

                $ext = end((explode(".", $uploadedFile)));
                $timezone = new DateTimeZone(Yii::app()->params['timezone']);
                $date = new DateTime();
                $date->setTimezone($timezone);
                $date = $date->format('dmYhis');
                $fileName = "{$date}.{$ext}";
                if (isset($uploadedFile)) {
                    $uploadedFile->saveAs(Yii::app()->basePath . '/../banner/' . $fileName);
                }
                //reading portion : here each column is read row and column wise; please check the sample
                //import file to get the column format. The heading row can be kept. The heading is ignored
                //while reading the excel or csv file.

                $sheet_array = Yii::app()->yexcel->readActiveSheet(Yii::app()->basePath . '/../banner/' . $fileName);
                $count = 0;
                foreach ($sheet_array as $row) {
                    $count = $count + 1;
                }
                for ($x = 2; $x <= $count; $x++) {

                    try {
                        if ($sheet_array[$x]['A'] == "" && $sheet_array[$x]['B'] == "" && $sheet_array[$x]['C'] == "" && $sheet_array[$x]['D'] == "" && $sheet_array[$x]['E'] == "" && $sheet_array[$x]['F'] == "" && $sheet_array[$x]['G'] == "" && $sheet_array[$x]['H'] == "" && $sheet_array[$x]['I'] == "" && $sheet_array[$x]['J'] == "" && $sheet_array[$x]['K'] == "" && $sheet_array[$x]['L'] == "" && $sheet_array[$x]['M'] == "" && $sheet_array[$x]['N'] == "" && $sheet_array[$x]['O'] == "" && $sheet_array[$x]['P'] == "" && $sheet_array[$x]['Q'] == "" && $sheet_array[$x]['R'] == "" && $sheet_array[$x]['S'] == "" && $sheet_array[$x]['T'] == "" && $sheet_array[$x]['U'] == "" && $sheet_array[$x]['V'] == "") {
                            $this->redirect(array('/core/employeedetails/admin'), array('message' => 'Successfuly Updated!'));
                        }
                        $employee_master = new Employeemaster;
                        $emp_code = Employeemaster::model()->findByAttributes(array('employee_code' => $sheet_array[$x]['A']));

                        if ($sheet_array[$x]['A'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field employee code validation error');
                            exit(0);
                        } elseif ($emp_code != "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'Employee code already exist.');
                            exit(0);
                        } else {
                            $institution = Institution::model()->findByPk(Yii::app()->user->institutionid);
                            if ($institution->isautogeneration === '1') {
                                $schoolcode = $institution->institution_code;
                                $employee_master->employee_code = "e" . $schoolcode . $sheet_array[$x]['A'];
                            } else {
                                $employee_master->employee_code = "e" . $sheet_array[$x]['A'];
                            }
                        }
                        if ($sheet_array[$x]['B'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field employee name validation error');
                            exit(0);
                        } else {
                            $employee_master->employee_firstname = $sheet_array[$x]['B'];
                        }
                        $employee_master->employee_middlename = $sheet_array[$x]['C'];
                        $employee_master->employee_lastname = $sheet_array[$x]['D'];
                        if ($sheet_array[$x]['E'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field date of birth validation error');
                            exit(0);
                        } else {
                            $date1 = date_create($sheet_array[$x]['E']);
                            $date = date_format($date1, 'Y-m-d');
                            $employee_master->employee_dob = $date;
                        }
                        if ($sheet_array[$x]['F'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field gender validation error');
                            exit(0);
                        } else {
                            $gender = (strcasecmp($sheet_array[$x]['F'], "female")) ? 1 : 2;
                            $employee_master->employee_gender = $gender;
                        }
                        $department = Department::model()->findByAttributes(array('department_name' => $sheet_array[$x]['G']));
                        if ($department == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field department validation error');
                            exit(0);
                        } else {
                            $employee_master->departmentid = $department->departmentid;
                        }
                        $designation = Designation::model()->findByAttributes(array('designation_name' => $sheet_array[$x]['I']));

                        if ($designation == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field designation validation error');
                            exit(0);
                        } else {
                            $employee_master->designationid = $designation->designationid;
                        }
                        if ($sheet_array[$x]['J'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field joining date validation error');
                            exit(0);
                        } else {
                            $date1 = date_create($sheet_array[$x]['J']);
                            $date = date_format($date1, 'Y-m-d');
                            $employee_master->employee_joiningdate = $date;
                        }
                        $employee_master->institutionid = $sheet_array[$x]['H'];
                        $employee_master->status = 1; //! existing employee
                        $employee_master->save(false);} catch (CDbException $e) {
                        throw new CHttpException(404, 'Something went wrong while uploading your excel file.');
                    }
                }
//                $this->render('contact_emp', array('model' => $model, 'message' => 'Successfuly Updated!'));
                if ($x == 2) {
                    $this->render('contact', array('model' => $model, 'message' => 'The file you uploaded is empty.!'));
                } else {
                    $this->redirect(array('/core/employeedetails/admin'), array('message' => 'Successfuly Updated!'));
                }
            }
        }
    }

    $this->render('contact_emp', array('model' => $model, 'message' => ''));
}

我认为这会对你有所帮助。 :)