2016-08-02 13 views
0

私はcsvファイルを持っています。そして、私はすでに私は、CakePHPで私のデータベースにそのデータを入れたくなりましたアップロードした2.7.5cakephpを使ってcsvからmysqlにデータをインポートする2.7.5

csvファイルには、従業員テーブルのフィールド名とまったく同じフィールド名が含まれている 私の質問は、ここでは、従業員テーブル 機能コードのデータを配置する方法です

パブリック関数import_csv(){

$this->loadModel('Csvimport');  

    if ($this->request->is('post', 'put')) { 

     $this->request->data['Csvimport']['created_user_id'] = $this->Auth->user('id'); 
     $this->request->data['Csvimport']['modified_user_id'] = $this->Auth->user('id'); 

     if (!empty($this->request->data)) { 

      $file = $this->request->data['Csvimport']['file_name']; 

       $name = explode(".", $file['name']); 
       //echo "before:".$file['name'][$i]; 
       $name = uniqid().".".$name[1]; 
       //echo "after:".$name; 

       $ext = substr(strtolower(strrchr($name, '.')), 1); //get the extension 
       $arr_ext = array('csv'); //set allowed extensions 
       //only process if the extension is valid 
      if ($file['size'] < 1000000) { 

       if(in_array($ext, $arr_ext)){ 

        //do the actual uploading of the file. First arg is the tmp name, second arg is 
        //where we are putting it 

        move_uploaded_file($file['tmp_name'], WWW_ROOT . '/attachments/csvimports/' . $name); 
        //prepare the filename for database entry 
        $this->request->data['Csvimport']['file_name'] = $name; 
        $this->request->data['Csvimport']['file_type'] = $file['type']; 
        $this->request->data['Csvimport']['file_size'] = $file['size']; 
       }else{ 
        $message = 'Your File should be in given formats only.'; 
        $this->set('message',$message); 
        $this->Session->setFlash($message, 'error_flesh', array(), 'error'); 

        $this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv')); 
       } 
      }else{ 
       $message = 'Your File should be Upto 1MB only.'; 
       $this->set('message',$message); 
       $this->Session->setFlash($message, 'error_flesh', array(), 'error'); 

       $this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv')); 
      } 
     } 
     $this->Csvimport->id = $id; 
     if ($this->Csvimport->save($this->request->data)){ 

      $message = 'The Csv File has been Uploaded'; 
      $this->set('message',$message); 
      $this->Session->setFlash($message, 'success_flesh', array(), 'successfully'); 

      $this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv')); 
     } else { 

      $message = 'The Csv File could not be Uploaded. Please, try again.'; 
      $this->set('message',$message); 
      $this->Session->setFlash($message, 'error_flesh', array(), 'error'); 

     } 
    } 
} 
+0

あなたがロードし、ファイルを反復処理するために 'PHPExcel'のようなものを使用する必要があります。 は、ここではケーキのドキュメントです。 –

答えて

関連する問題