2015-02-07 44 views
0

我想上傳一個excel文件到我的mysql數據庫使用php,但我有兩個問題:第一個,我得到一個「通知:未定義偏移量: 「警告.csv文件的每一行,第二個問題是,它將.csv文件的所有三列導入到一個數據庫中。Excel到MySQL使用PHP導入到一個列

我的代碼如下:

<?php 
if(isset($_POST["Import"])) 
{ 

    $conexion=mysql_connect("localhost","root","") or die("Problemas en la conexion"); 
    mysql_select_db("kontor",$conexion) or die("Problemas en la seleccion de la base de datos"); 

    echo $filename=$_FILES["file"]["tmp_name"]; 
    if($_FILES["file"]["size"] > 0) 
    { 
     $file = fopen($filename, "r"); 
     $count = 0; 
     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) 
     { 
      $count++; 
      if($count>1){ 
      mysql_query("INSERT into stock (nombre,prneto,descr) values ('$emapData[0]','$emapData[1]','$emapData[2]')", $conexion) 
or die("Problemas en el select".mysql_error()); 

      }  
     } 
     fclose($file); 
     echo 'Archivo importado'; 
     //header('Location: index.php'); 
    } 
    else 
     echo 'Formato de archivo incorrecto'; 
} 
?> 

回答

0

只要看看在CSV文件...什麼分離器和外殼被使用?

Excel常用;和「爲分離器和機箱

的大部分時間,這些人會做的工作:

while (($emapData = fgetcsv($file, 10000, ";", '"')) !== FALSE) 

// or 

while (($emapData = fgetcsv($file, 10000, ",", '"')) !== FALSE) 
0

Excel中通常不喜歡一直引用CSV列的值;它只在它認爲必要時才這樣做(至少在某些版本的Excel中)。出於這個原因,我通常不建議使用用Excel生成CSV和選擇只是讀原生格式的Excel文件PHPExcel

// this is the older version of excel for .xls 
// if the file is xlsx you would use PHPExcel_Reader_Excel2007() 
$objReader = new PHPExcel_Reader_Excel5(); 

$objPHPExcel = $objReader->load($_FILES["file"]["tmp_name"]); 
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); 

// you should also be using PDO or mysqli for your db interactions 
// NOT mysql - this example will use pdo 

$db = new PDO($dsn, $user, $pass, array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION 
)); 



try { 
    // presumebaly you want this operation to be atomic 
    // ie. if any one row fails don't insert any of the rows 
    // so we will use a transaction 
    $db->beginTransaction(); 

    // prepare the query 
    $stmt = $db->prepare('INSERT into stock (nombre,prneto,descr) values (?,?,?)'); 

foreach ($sheetData as $row) { 
    // execute the insert for a row of csv 
    $stmt->execute(array_values($row)); 
} 

// attempt to commit the transaction 
$db->commit(); 


} catch (Exception $e) { 
    // we had an error somewhere, roll back the transaction 
    $db->rollBack(); 

    // retrhow the error 
    throw $e; 
}