2016-08-02 93 views
0

我有csv文件。我已經上傳,現在我想要把它的數據到我的數據庫在CakePHP中2.7.5使用cakephp從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'加載並通過文件迭代。 –

回答

1

如果你在導入前需要循環的數據中的每一行, 考慮使用

$this->Csvimport->create() 
$this->Csvimport->save(['fieldName'=>$data1, 'fieldName'=>$data2, ... ]); 

如果你不需要,那麼一旦你擁有了它,那麼在整個數組上使用saveAll。 這裏是蛋糕文檔:

http://book.cakephp.org/2.0/en/models/saving-your-data.html