简体   繁体   English

如何在yii 1.16中将Excel数据导入MySQL

[英]How to import excel data into mySQL in yii 1.16

I have customer table in MySQL database.I have list of customers in excel csv and i want to import excel data into MySQL customer table.I want someone show me step by step How i can do it and also tell model view and controller. 我在MySQL数据库中有客户表。我在excel csv中有客户列表,我想将excel数据导入到MySQL客户表中。我希望有人逐步向我展示如何做到这一点,并告诉模型视图和控制器。

I have Written MySQL Query of customer table to show you that I will be same coloumns in excel csv. 我已经编写了MySQL客户表查询,向您展示我将在excel csv中使用相同的语言。

(`CustomerID`, `FirstName`, `LastName`, `JobTitle`, `BusinessPhone`, `MobilePhone`, `FaxNumber`, `Address`, `Area`, `State`, `ZipCode`, `Country`, `Email`, `Webpage`, `Notes`, `CustomerInvoice`, `Status`)

Would you like to show me How i can import csv data into MySQL table or Yii have any plugin to import excel data into MySQL database? 您想给我看看我如何将csv数据导入MySQL表或Yii有任何插件将excel数据导入MySQL数据库吗?

This is best plugin with proper documentation and examples 这是带有适当文档和示例的最佳插件

http://phpexcel.codeplex.com/ http://phpexcel.codeplex.com/

with this plugin you can import excel data in mysql. 使用此插件,您可以在mysql中导入Excel数据。

You can use "LOAD DATA" command. 您可以使用“ LOAD DATA”命令。 Here is the example from yiiframework documentation. 这是yiiframework文档中的示例。

http://www.yiiframework.com/wiki/336/importing-csv-file-to-mysql-table-using-load-data-command/ http://www.yiiframework.com/wiki/336/importing-csv-file-to-mysql-table-using-load-data-command/

You can get reference from YII: http://www.yiiframework.com/forum/index.php/topic/23536-upload-data-excel-to-mysql/ 您可以从YII获取参考: http ://www.yiiframework.com/forum/index.php/topic/23536-upload-data-excel-to-mysql/

**step1:**Define a Form model ie **步骤1:**定义表单模型,即

class UserImportForm extends CFormModel
{
    public $file;
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(  
             array('file', 'file', 
                                            'types'=>'csv',
                                            'maxSize'=>1024 * 1024 * 10, // 10MB
                                            'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
                                            'allowEmpty' => false
                              ),
                   );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'file' => 'Select file',
        );
    }

}

step2: Now you need to define a form in your view.ie 步骤2:现在您需要在view.ie中定义一个表单

Note: i have used bootstrap form widget here.you can change it based on your needs. 注意:我在这里使用了引导表单小部件。您可以根据需要进行更改。

<div class="form">

<?php
$form = $this->beginWidget('bootstrap.widgets.BootActiveForm', array(
    'id'=>'service-form',
    'enableAjaxValidation'=>false,
    'method'=>'post',
    'type'=>'horizontal',
    'htmlOptions'=>array(
        'enctype'=>'multipart/form-data'
    )
)); ?>

    <fieldset>
        <legend>
            <p class="note">Fields with <span class="required">*</span> are required.</p>
        </legend>

        <?php echo $form->errorSummary($model, 'Opps!!!', null, array('class'=>'alert alert-error span12')); ?>

        <div class="control-group">     
            <div class="span4">
                                <div class="control-group <?php if ($model->hasErrors('postcode')) echo "error"; ?>">
        <?php echo $form->labelEx($model,'file'); ?>
        <?php echo $form->fileField($model,'file'); ?>
        <?php echo $form->error($model,'file'); ?>
                            </div>


            </div>
        </div>

        <div class="form-actions">
            <?php $this->widget('bootstrap.widgets.BootButton', array('buttonType'=>'submit', 'type'=>'primary', 'icon'=>'ok white', 'label'=>'UPLOAD')); ?>
            <?php $this->widget('bootstrap.widgets.BootButton', array('buttonType'=>'reset', 'icon'=>'remove', 'label'=>'Reset')); ?>
        </div>

    </fieldset>

<?php $this->endWidget(); ?>

</div><!-- form -->

**step3:**Now you need to write an action in your controller to import the file.ie **步骤3:**现在,您需要在控制器中编写一个操作以导入文件。

public function actionImportCSV()
        {
           $model=new UserImportForm;

           if(isset($_POST['UserImportForm']))
             {

               $model->attributes=$_POST['UserImportForm'];

               if($model->validate())
                 {

                  $csvFile=CUploadedFile::getInstance($model,'file');  
                  $tempLoc=$csvFile->getTempName();

                    $sql="LOAD DATA LOCAL INFILE '".$tempLoc."'
        INTO TABLE `tbl_user`
        FIELDS
            TERMINATED BY ','
            ENCLOSED BY '\"'
        LINES
            TERMINATED BY '\n'
         IGNORE 1 LINES
        (`name`, `age`, `location`)
        ";

                    $connection=Yii::app()->db;
                    $transaction=$connection->beginTransaction();
                        try
                            {

                                $connection->createCommand($sql)->execute();
                                $transaction->commit();
                            }
                            catch(Exception $e) // an exception is raised if a query fails
                             {
                                print_r($e);
                                exit;
                                $transaction->rollBack();

                             }
                      $this->redirect(array("user/index"));


                 }
             }  

           $this->render("importcsv",array('model'=>$model));
        }

If i understood correctly,you can do something in controller action 如果我理解正确,您可以在控制器操作中执行某些操作

public function actionYourActionName(){
   if (isset($_FILES['csv_file']) && !empty($_FILES['csv_file'])) {
    $csv = array();
    $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
    while (($line = fgetcsv($file)) !== FALSE) {
       //$line is an array of the csv elements
        $csv[] = $line;
    }
    fclose($file);
    for ($i = 1; $i < count($csv); $i++) {
       $model = new YourmodelName();
      foreach ($csv[0] as $key => $value) {
         $model->$value = $csv[$i][$key];
     }
        if($model->save()){
          //do here what you want to do after saving model
       }else{return $model->getErrors();}
    }
}
}else{
    $this->render('your view name');
}

and in your view file something like eg 在您的视图文件中,例如

echo CHtml::form('', 'post', array('id' => "verticalForm", 'class' => 'well form-vertical', 'enctype' => 'multipart/form-data'));
echo CHtml::fileField('csv_file[]', '', array('id' => 'csv_file', 'multiple' => 'multiple'));
echo '<p class="help-block">Please upload .csv files only.</p>';
echo CHtml::submitButton('Submit', array('class' => 'btn btn-primary'));
echo CHtml::endForm();

and i suppose you have created a model.for your mysql table, hope this will help you 我想你已经为你的mysql表创建了一个model。希望这对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM