2015-02-11 136 views
0

我想使用php将excel中的数据导入到mySQL DB中。我尝试过使用其他问题中解释的方式,但没有为我解决。请让我知道如何使用php将数据导入到数据库。如何使用php将excel文件导入到mySQL数据库

另外,请让我知道在哪里放置Excel文件上传,我的意思是在系统中的位置。

+0

这是不是很难?你可以写你自己的实行。尝试不使用一些第三方软件 – 2015-02-11 06:21:34

+0

我是新来的PHP。你能帮我写代码吗? – 2015-02-11 06:24:05

回答

0

方法1.you可以使用负载数据命令

http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html 

方法2的Excel读者

https://code.google.com/p/php-excel-reader/

方法3. parseCSV

https://github.com/parsecsv/parsecsv-for-php 

方法4。 (PHP 4,PHP 5)fgetcsv

http://in1.php.net/fgetcsv 
+0

哪里可以在我的系统中放置excel阅读器的代码? – 2015-02-11 06:52:28

0

请参阅此PHP代码

<?php 

//table Name 
$tableName = "MyTable"; 
//database name 
$dbName = "MyDatabase"; 


$conn = mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db($dbName) or die(mysql_error()); 

//get the first row fields 
$fields = ""; 
$fieldsInsert = ""; 
if (($handle = fopen("test.csv", "r")) !== FALSE) { 
    if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 
     $num = count($data); 
     $fieldsInsert .= '('; 
     for ($c=0; $c < $num; $c++) { 
      $fieldsInsert .=($c==0) ? '' : ', '; 
      $fieldsInsert .="`".$data[$c]."`"; 
      $fields .="`".$data[$c]."` varchar(500) DEFAULT NULL,"; 
     } 

     $fieldsInsert .= ')'; 
    } 


    //drop table if exist 
    if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))>=1) { 
     mysql_query('DROP TABLE IF EXISTS `'.$tableName.'`') or die(mysql_error()); 
    } 

    //create table 
    $sql = "CREATE TABLE `".$tableName."` (
       `".$tableName."Id` int(100) unsigned NOT NULL AUTO_INCREMENT, 
       ".$fields." 
       PRIMARY KEY (`".$tableName."Id`) 
      ) "; 

    $retval = mysql_query($sql, $conn); 

    if(! $retval) 
    { 
     die('Could not create table: ' . mysql_error()); 
    } 
    else { 
     while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 

       $num = count($data); 
       $fieldsInsertvalues=""; 
       //get field values of each row 
       for ($c=0; $c < $num; $c++) { 
        $fieldsInsertvalues .=($c==0) ? '(' : ', '; 
        $fieldsInsertvalues .="'".$data[$c]."'"; 
       } 
       $fieldsInsertvalues .= ')'; 
       //insert the values to table 
       $sql = "INSERT INTO ".$tableName." ".$fieldsInsert." VALUES ".$fieldsInsertvalues; 
       mysql_query($sql,$conn); 
     } 
     echo 'Table Created'; 
    } 

    fclose($handle); 

} 

?> 
+0

我得到的错误如下fopen(protected/extensions/phpexcel/test1.xls):无法打开流:没有这样的文件或目录 – 2015-02-11 07:24:41

+0

更新文件的目录只是一个文件名,并确保您有权限用于访问文件 – user3925225 2015-02-11 08:42:35

+0

我试过只给出文件名。请让我知道我必须放置文件的位置。现在我已经将它放在C:\ xampp \ htdocs \ www \ ClaimSystem \ claimNew \ protected \ extensions \ phpexcel – 2015-02-11 09:09:27

相关问题