简体   繁体   English

如何将Excel数据导入MySQL数据库?

[英]How to import excel data into MySQL database?

I have used the following code to read the data of exceltodb.xlsx file and import it into the table city of database world. 我使用以下代码读取exceltodb.xlsx文件的数据,并将其导入数据库世界的表城市。 The library to read the file is PHPExcel which is very common library.The code I found is as follows but the code is executing but the row is not added into the database. 读取文件的库是PHPExcel,这是非常常见的库。我发现的代码如下,但是代码正在执行,但该行未添加到数据库中。

<?php
include 'PHPExcel-develop/Classes/PHPExcel/IOFactory.php';

$inputFileName = 'exceltodb.xlsx';

//  Read your Excel workbook
try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load('exceltodb.xlsx');
} catch(Exception $e) {
    die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();

//  Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){ 
    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                    NULL,
                                    TRUE,
                                    FALSE);
    //  Insert row data array into your database of choice here
    mysql_connect('localhost','root','');
    mysql_select_db('world');
    mysql_query('insert into city("city","id","stateid","countryid") values("$rowData")');
}
?>

This code segment will upload your xml data sheet in to a particular location in the server: 此代码段会将xml数据表上传到服务器中的特定位置:

<?php
 $uploadedStatus = 0;
    if ( isset($_POST["submit"]) ) {
    if ( isset($_FILES["file"])) {
    //if there was an error uploading the file
    if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
    else {
    if (file_exists($_FILES["file"]["name"])) {
    unlink($_FILES["file"]["name"]);
    }
    $storagename = "discussdesk.xlsx";
    move_uploaded_file($_FILES["file"]["tmp_name"],  $storagename);
    $uploadedStatus = 1;
    }
    } else {
    echo "No file selected <br />";
    }
    }

?>

This will upload the data taken from xml to the database: 这会将从xml获取的数据上传到数据库:

     <?php
    /************************ YOUR DATABASE CONNECTION START HERE   ****************************/

    define ("DB_HOST", "localhost"); // set database host
    define ("DB_USER", ""); // set database user
    define ("DB_PASS",""); // set database password
    define ("DB_NAME",""); // set database name

    $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
    $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

    $databasetable = "YOUR_TABLE";

    /************************ YOUR DATABASE CONNECTION END HERE  ****************************/


    set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
    include 'PHPExcel/IOFactory.php';

    // This is the file path to be uploaded.
    $inputFileName = 'discussdesk.xlsx'; 

    try {
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
    } catch(Exception $e) {
        die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
    }

    $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
    $arrayCount = count($allDataInSheet);  // Here get total count of row in that Excel sheet

    for($i=2;$i<=$arrayCount;$i++){
    $userName = trim($allDataInSheet[$i]["A"]);
    $userMobile = trim($allDataInSheet[$i]["B"]);

    $query = "SELECT name FROM YOUR_TABLE WHERE name = '".$userName."' and email = '".$userMobile."'";
    $sql = mysql_query($query);
    $recResult = mysql_fetch_array($sql);
    $existName = $recResult["name"];
    if($existName=="") {
    $insertTable= mysql_query("insert into YOUR_TABLE (name, email) values('".$userName."', '".$userMobile."');");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM