如何使用PHP将Excel或CSV上传到MySQL数据库?

时间:2010-07-02 06:04:30

标签: php mysql excel

我有一个包含数据的Excel文件(电话号码列表),我希望使用PHP代码将Excel文件中的数据导入我的数据库表(例如名为phonenumber_list)?我知道如何将MySQl转换为Excel,但它可以反过来吗?请帮助!

2 个答案:

答案 0 :(得分:3)

<强> CSV
如果您可以先将Excel文件转换为CSV,则可以使用mysqlimport导入CSV。这可能是将数据导入MySQL的最快方法。

您可以使用LOAD DATA INFILE从PHP执行此操作。这是要导入data.csv的示例SQL语句:

LOAD DATA INFILE 'data.csv' INTO TABLE phonenumber_list
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

<强> Excel中
如果您不能使用CSV,并且需要使用原始Excel文件,则需要一个能够读取Excel文件的PHP库。

有一些可用,但我不知道它们有多可靠或维护得很好:

Pear: Spreadsheet_Excel_Writer

PHPExcel

PHP-ExcelReader

您可能还想查看使用Excel API的替代方法,但是您需要安装Excel才能执行此操作。这里有一些信息:

http://www.sydphp.org/presentations/010606-excel.html

如果使用此方法,则需要编写一些读取和解析Excel文件的代码,并逐行将其发送到MySQL。这可能比批量CSV导入慢得多。

答案 1 :(得分:3)

首先,您必须将Excel文件转换为CSV格式(逗号分隔)文件。

然后使用以下PHP脚本将其插入MySQL:

<?php 
error_reporting(E_ALL & ~E_NOTICE);
$connect = mysql_connect("localhost","root","");
@mysql_select_db("dbname");

$inputFile=@$_FILES[csv][name];
$ext=end(explode('.',$inputFile));

if($ext=='csv')
{
    $tmpFile=@$_FILES[csv][tmp_name];
    $f = @fopen($tmpFile, 'r');
    $contents = @fread($f, 10000); 
    fclose($f);
    $fileLines = explode("\r\n", $contents); // explode to make sure we are only using the first line.
    $fieldList_header = explode(',', $fileLines[0]);
    $csv_header=array("ID","Name","Address","Email-Id","Contact-No"); // Excel file heading

    $i=0;
    //index keys for each column
    $ID_key=null;
    $Name_key=null;
    $Address_key=null;
    $Email_ID_key=null;
    $Contact_No_key=null;

    foreach($csv_header as $csv)
    {
        //searching index for each value
        if(in_array($csv,$fieldList_header))
        {
            $key=array_search($csv,$fieldList_header);

            if($i==0)
                $ID_key=$key;   
            if($i==1)
                $Name_key=$key;
            if($i==2)
                $address_key=$key;
            if($i==3)
                $Email_ID_key=$key;
            if($i==4)
                $Contact_No_key=$key;
        }
        else
        {
            echo "Failed to search : ".$csv." blank space will be inserted.<br>";
        }
        $i++;
    }
    echo "<table border=1px>";
    echo "<tr>";
        echo "<td>";
            echo "Id";
        echo "</td>";
        echo "<td>";
            echo "Name";
        echo "</td>";
        echo "<td>";
            echo "Address";
        echo "</td>";
        echo "<td>";
            echo "Email ID";
        echo "</td>";
        echo "<td>";
            echo "Contact No";
        echo "</td>";
    echo "</tr>";
    $j=1;
    for($i=2;$i<count($fileLines)-1;$i++)
    {

        $fieldList_other = explode(',', $fileLines[$i]);
        echo "<tr>";
            echo "<td>";
                echo $fieldList_other[$ID_key];
            echo "</td>";
            echo "<td>";
                echo $fieldList_other[$Name_key];
            echo "</td>";
            echo "<td>";
                echo $fieldList_other[$Address_key];
            echo "</td>";
            echo "<td>";
                echo $fieldList_other[$Email_ID_key];
            echo "</td>";
            echo "<td>";
                echo $fieldList_other[$Contact_No_key];
            echo "</td>";
        echo "</tr>";

        $query="insert into Contact (EmployeeName,DateOfJoining,SalaryPerDay,Address,Designation,BalanceLeaves,ContactNumber) values('$fieldList_other[$ID_key]','$fieldList_other[$Name_key]','$fieldList_other[$Address_key]','$fieldList_other[$Email_ID_key]','$fieldList_other[$Contact_No_key]')";

        $result=mysql_query($query);
        if(!$result)
            echo "Record $j failed.<br>";
        else
            echo "Record $j inserted in database.";
        $j++;
    }
    echo "</table>";    
}
?>




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Import a CSV File with PHP & MySQL</title>
        <script>
            <!--
            function noempty()
            {
            var y=document.forms["form1"]["csv"].value;
            if (y==null || y=="" )
              {
                alert("Please enter the required field");
                return false;
              }

            }
            -->
        </script> 
    </head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
</br></br>
  Choose your file: <br />
    <input name="csv" type="file" id="csv" />
  <input type="submit" name="Submit" value="Submit" onclick="return noempty()"/>
  </center>
</form>
</body>

</html>

此脚本对您有所帮助。因为无论Excel文件列的顺序如何,相应的数据都只输入MySQL。