2017-04-18 56 views
0

我想上傳一個excel文件,逐行讀取並將數據插入到數據庫中。我該怎麼做?PHPEXCEL:如何讀取excel文件中的每一行並插入到數據庫中

這是我到目前爲止已經試過:

for ($row = 1; $row <= $highestRow; $row++) { 

     // Read a row of data into an array 

     $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
     NULL, TRUE, FALSE); 
     // This line works as $sheet->rangeToArray('A1:E1') that is selecting all the cells in that row from cell A to highest column cell 

     echo "<tr>"; 

     //echoing every cell in the selected row for simplicity. You can save the data in database too. 
     foreach($rowData[0] as $k=>$v) 
     // echo "<td>".$v."</td>"; 
     // foreach($xlsx->rows() as $r) 


     $sql = "INSERT into temperature (datetime, MODE_Value, MV_Value,PV_Value, PV_HighEng_Value, PV_LowEng_Value,SV_Value) 
     values('$datetime', '$MODE_Value','$MV_Value','$PV_Value','$PV_HighEng_Value','$PV_LowEng_Value','$SV_Value')"; 
     //we are using mysql_query function. it returns a resource on true else False on error 
     $result = mysqli_query($conn, $sql); 
     //echo "</tr>"; 
    } 

任何提示,建議和幫助表示讚賞。

回答

1

嘗試這樣的事情。

for ($row = 2; $row <= $highestRow; $row++) { 
     $column_1 = mysql_real_escape_string(trim($objPHPExcel->getActiveSheet()->getCell('A' . $row)->getValue())); 
     $column_2 = mysql_real_escape_string(trim($objPHPExcel->getActiveSheet()->getCell('B' . $row)->getValue())); 
     $column_3 = mysql_real_escape_string(trim($objPHPExcel->getActiveSheet()->getCell('C' . $row)->getValue())); 
     $column_4 = mysql_real_escape_string(trim($objPHPExcel->getActiveSheet()->getCell('D' . $row)->getValue())); 
     $column_5 = mysql_real_escape_string(trim($objPHPExcel->getActiveSheet()->getCell('E' . $row)->getValue())); 
     $column_6 = mysql_real_escape_string(trim($objPHPExcel->getActiveSheet()->getCell('F' . $row)->getValue())); 

     $values = "('$column_1','$column_2','$column_3','$column_4','$column_5','$column_6')"; 
     if ($values != '') { 
      $sqlInsert = "INSERT INTO table (column_1,column_2,column_3,column_4,column_5,column_6) VALUES $values"; 
      mysql_query($sqlInsert) or die(mysql_error()); 
     } 
    } 
+0

謝謝,它的工作!有一個愉快的一天:) –

+0

謝謝!爲了投票。 – Webinion

相關問題