简体   繁体   English

使用PHP将CSV / Excel导入MYSQL

[英]Import CSV/Excel with PHP into MYSQL

Have a bit of a problem with importing CSV/Excel into MYSQL and frankly not sure whether if this scenario is even possible? 将CSV / Excel导入MYSQL时遇到问题,并且坦率地说不确定这种情况是否可行? Sorry I don't have any code, I am just trying to get a grisp on how to do this. 抱歉,我没有任何代码,我只是想对如何做到这一点有所了解。

Here's the drift: I have a table with 4 columns, id, userid, starttime, endtime. 这是漂移:我有一个包含4列的表,id,userid,starttime,endtime。 ID, is primary key. ID,是主键。 Starttime and Endtime are both stored as DATETIME. 开始时间和结束时间都存储为DATETIME。 Example: 例:

id    userid      starttime              endtime
1        3    2015-01-18 12:00:00  2015-01-18 16:00:00

I want to import a excel sheet that is laid out like this: http://tinypic.com/r/281lyd/8 (also, the start and end are columns in its own) 我想导入一个像这样布置的Excel工作表: http : //tinypic.com/r/281lyd/8 (而且,开始和结束都是其自己的列)

Questions: 问题:

  1. Is this possible? 这可能吗? If so, how? 如果是这样,怎么办?
  2. If not, what are other alternative solutions to this problem? 如果没有,还有什么其他替代解决方案? I need to somehow import weekly data into mysql database which is then outputted into a table online by week. 我需要以某种方式将每周数据导入mysql数据库,然后按周在线输出到表中。 (An admin would do this, but it should be effortless or time consuming.) (管理员可以执行此操作,但这应该毫不费力或耗时。)

You can use EasyXLS library to import the Excel file. 您可以使用EasyXLS库导入Excel文件。 I don't know if you need to import xls or xlsx file, so my below source code is for xlsx. 我不知道您是否需要导入xls或xlsx文件,因此下面的源代码适用于xlsx。 The code for xlsx file is similar. xlsx文件的代码相似。 First you import the cell values into a list of rows and then insert the list values into MySQL database. 首先,将单元格值导入到行列表中,然后将列表值插入MySQL数据库中。

// Create an instance of the class that imports Excel files
$xls = new COM("EasyXLS.ExcelDocument");

// Import Excel file to List
$rows = $xls->easy_ReadXLSXSheet_AsList("Excel.xls", "Sheet1");

// Iterate List values
for ($rowIndex=0; $rowIndex<$rows->size(); $rowIndex++)
{
        $row = $rows->elementAt($rowIndex);
        for ($cellIndex=0; $cellIndex<$row->size(); $cellIndex++)
        {
            echo "At row ".($rowIndex + 1).", column ".($cellIndex + 1).
                        " the value is '".$row->elementAt($cellIndex)."'<br>";
            // SQL syntax to insert cell value into MySQL database: $row->elementAt($cellIndex)
            ...
        }
}

For more technical data, you may take a look at the following link: http://www.easyxls.com/manual/FAQ/import-excel-to-mysql.html 有关更多技术数据,您可以查看以下链接: http : //www.easyxls.com/manual/FAQ/import-excel-to-mysql.html

To insert the data into MySQL use a similiar syntax: http://www.w3schools.com/php/php_mysql_insert.asp 要将数据插入MySQL,请使用类似的语法: http : //www.w3schools.com/php/php_mysql_insert.asp

and use $row->elementAt($cellIndex) on VALUE section of the SQL syntax. 并在SQL语法的VALUE部分使用$row->elementAt($cellIndex)

For importing the CSV file, you can use easy_ReadCSVFile_AsList in a similar way. 要导入CSV文件,您可以类似的方式使用easy_ReadCSVFile_AsList

If you wanted to use a csv instead of a xls file you can do this you can put both the php script and the html form in one php file and it should do exactly what you need it to 如果您想使用csv而不是xls文件,则可以执行此操作,可以将php脚本和html表单都放在一个php文件中,它应该完全满足您的需要。

php script PHP脚本

<?php
    session_start();

$message = null;

$allowed_extensions = array('csv');

$upload_path = 'uploadlocation';

if (!empty($_FILES['file'])) {

    if ($_FILES['file']['error'] == 0) {

        // check extension
        $file = explode(".", $_FILES['file']['name']);
        $extension = array_pop($file);

        if (in_array($extension, $allowed_extensions)) {

            if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) {

                if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) {

                    $keys = array();
                    $out = array();

                    $insert = array();

                    $line = 1;

                    while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) {

                        foreach($row as $key => $value) {
                            if ($line === 1) {
                                $keys[$key] = $value;
                            } else {
                                $out[$line][$key] = $value;

                            }
                        }

                        $line++;

                    }

                    fclose($handle);    

                    if (!empty($keys) && !empty($out)) {

                        $db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
                        $db->exec("SET CHARACTER SET utf8");

                        foreach($out as $key => $value) {

                            $sql  = "INSERT INTO wherever(`";
                            $sql .= implode("`, `", $keys);
                            $sql .= "`) VALUES (";
                            $sql .= implode(", ", array_fill(0, count($keys), "?"));
                            $sql .= ")";
                            $statement = $db->prepare($sql);
                            $statement->execute($value);

                        }

                        $message = '<span color="green">File has been uploaded successfully</span>';

                    }   

                }

            }

        } else {
            $message = '<span class="red">Only .csv file format is allowed</span>';
        }

    } else {
        $message = '<span class="red">There was a problem with your file</span>';
    }

}
?>

HTML Form HTML表格

<table cellpadding="0" cellspacing="0" border="0" class="table">
    <tr>
        <C><label for="file">Select file</label> <?php echo $message; ?></th>
    </tr></h2>
    <tr>
        <td><input type="file" name="file" id="file" size="30" /></td>
    </tr>
    <tr>
        <td><input type="submit" id="btn" class="fl_l" value="Submit" /></td>
    </tr>
</table>

you need to layout your excel like your database table for this code to work and you need to change the login etc for the database. 您需要像数据库表一样布置Excel才能使此代码正常工作,并且需要更改数据库的登录名等。 Since this is Dbo it should work with all databases or atleast most of them !. 由于这是Dbo,因此它应该与所有数据库一起使用,或者至少其中的大多数! If you need any help comment below 如果您需要任何帮助,请在下面评论

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

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