Excel到MySQL使用PHP导入到单个列中


Excel to MySQL using PHP imports into a single column

我正试图使用php将excel文件上传到我的mysql数据库中,但我遇到了两个问题:第一个问题是,我收到了.csv文件每行的"注意:未定义的偏移量:"警告,第二个问题是它将.csv文件的所有三列导入到一个数据库中。

我的代码如下:

<?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';
}
?>

只需查看csv文件。。。使用了什么分离器和外壳?

Excel经常使用;和"用于分离器和外壳。

大多数时候,其中一个会完成任务:

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

Excel通常不喜欢一致地引用CSV列值;它只有在认为有必要的时候才会这样做(至少在某些版本的excel中是这样)。出于这个原因,我通常不建议使用Excel生成的CSV,而是选择只使用PHPExcel 读取Excel文件的原生格式

// 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;
}