2016-02-24 80 views
0

我在MySQL數據庫中有客戶表。我有excel csv中的客戶列表,我想將excel數據導入到MySQL客戶表中。我希望有人向我演示如何一步一步如何我可以做到這一點,並告訴模型視圖和控制器。如何在Excel中導入excel數據到mySQL 1.16

我已經寫了客戶表的MySQL查詢,告訴你我會在excel csv中使用相同的顏色。

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

你願意告訴我如何導入CSV數據到MySQL表或Yii中有任何插件Excel數據導入MySQL數據庫?

+0

您需要在您的網站或此功能只是一個時間CSV導入? – mohit

回答

0

您可以從誼得到參考:http://www.yiiframework.com/forum/index.php/topic/23536-upload-data-excel-to-mysql/

**第一步:**定義表單模型即

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', 
     ); 
    } 

} 

第二步:現在你需要定義表單在你的視圖中.ie

注意:我已經在這裏使用了引導窗體小部件。你可以根據它改變它根據您的需求。

<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 --> 

**第三步:**現在,你需要在你的控制器寫入動作導入file.ie

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)); 
     } 
+0

你的代碼正在工作? –

0

如果我理解正確的話,你可以做的控制器操作的東西

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'); 
} 

並在你的視圖文件中有一些像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(); 

,我想你已經創建了一個model.for你的mysql表,希望這將幫助你