2015-11-13 174 views
1

我想在excel文件中寫入一些信息到我的數據庫。 excel文件看起來像這樣。使用PHPExcel與Codeigniter讀取excel文件並寫入數據庫

ID123 | subj1 | 50

ID456 | subj2 | 60

ID786 | subj3 | 70

這是觸發控制器中的功能的視圖中的功能。

<a href="http://localhost/SEP/index.php/con_test/readExcel"> Click me </a> 

這是控制器的代碼。

public function readExcel(){    

     $inputFileName = 'C:\wamp\www\SEP\uploads\Format.xlsx'; 

     // Read your Excel workbook 
     try { 
      $inputFileType = PHPExcel_IOFactory::identify($inputFileName); 
      $objReader = PHPExcel_IOFactory::createReader($inputFileType); 
      $objPHPExcel = $objReader->load($inputFileName); 
     } 

     catch(Exception $e) { 
      die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); 
     } 

     // Get worksheet dimensions 
     $sheet = $objPHPExcel->getSheet(0); 
     $highestRow = $sheet->getHighestRow(); 
     $highestColumn = $sheet->getHighestColumn(); 

     // Loop through each row of the worksheet in turn 
     for ($row = 1; $row <= $highestRow; $row++){ 
      // Read a row of data into an array 
      $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
              NULL, 
              TRUE, 
              FALSE); 
      // Insert row data array into your database of choice here 
      $this->mod_test->insertMarks($rowData); 
     } 
    } 

另外我還在控制器的頂部包含了include '../third_party/PHPExcel/IOFactory.php';用於此目的。

這是我的模型中的代碼。

public function insertMarks($data){ 

    $this->db->insert('marks', $data); 
    return; 
} 

這是我第一次使用這個。我沒有得到任何錯誤,值也沒有插入到數據庫中。請幫我解決一下這個。

回答

0

從呼叫返回到rangeToArray$rowData)是一個二維陣列,即使是一個單一的行....我想你可能想要將它壓平成一維數組,然後再傳遞給insertMarks()

$this->mod_test->insertMarks($rowData[0]); 
+0

並沒有爲我工作.. –

+0

然後看看你的數據庫中插入'()'函數.....調試什麼東西被傳遞給它,什麼SQL查詢正在從該數據生成.....我不知道你的數據庫'insert()'函數實際上是d這就是爲什麼我建議的解決方案必須基於我所瞭解的PHPExcel的猜測 –

0

試試這個

<?php 
include ("./Classes/PHPExcel/IOFactory.php"); 

     $inputFileName = './marks.xlsx'; 

     // Read your Excel workbook 
     try { 
      $inputFileType = PHPExcel_IOFactory::identify($inputFileName); 
      $objReader = PHPExcel_IOFactory::createReader($inputFileType); 
      $objPHPExcel = $objReader->load($inputFileName); 
     } 

     catch(Exception $e) { 
      die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); 
     } 

     $sheetInsertData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); 


     //Read excel rows 
     foreach($sheetInsertData as $rec) 
     { 
      //If you want row as a array use $rec 
      $this->mod_test->insertMarks($rec); 

      //Get column values from row array 
      /*foreach($rec as $recm) 
      { 
       echo $recm."<br>"; 
      }*/ 
     } 
?> 
相關問題