简体   繁体   English

如何在PHP中将.xls文件加载到mysql数据库?

[英]How can I load an .xls file to a mysql database in php?

I want the exact opposite of this . 我想的完全相反

I want to load a .xls file full of emails into a database column. 我想将充满电子邮件的.xls文件加载到数据库列中。

What's the simplest way to do this? 最简单的方法是什么?

  1. Export the Excel spreadsheet to CSV format 将Excel电子表格导出为CSV格式
  2. Use MySQL's LOAD DATA INFILE syntax to use the CSV file created in Step 1, using: 使用MySQL的LOAD DATA INFILE语法来使用在步骤1中创建的CSV文件,方法是:

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

The file will have to be locally accessible to the MySQL instance, so you'll have to upload it if the server isn't physically accessible. 该文件必须是MySQL实例在本地可访问的,因此,如果服务器无法物理访问,则必须上载该文件。

You can use PHPExcel , which can read most Excel file formats (BIFF5, BIFF8, spreadsheetML). 您可以使用PHPExcel ,它可以读取大多数Excel文件格式(BIFF5,BIFF8,电子表格ML)。 Unfortunately the project's docs are in a word file, so can't link directly to the specific section, but it's section 6.4.1 / page 37 of this file . 不幸的是,该项目的文档位于Word文件中,因此无法直接链接到特定部分,但这是该文件的 6.4.1节/第37页。

Like Ponies said, you will have to first "Save As > CSV" then upload and do whatever. 就像小马说的那样,您必须先“另存为> CSV”,然后上传并执行任何操作。 Often permissions will not allow that SQL statement however. 但是,通常权限不允许该SQL语句。 My personal favorite is using csv2sql.com because it will do the heavy lifting and give you the SQL to just execute, however you could use fgetcsv which would be more secure, and something you can implement into a script. 我个人最喜欢使用csv2sql.com,因为它将完成繁重的工作,并让您只需执行SQL,但是您可以使用fgetcsv ,它将更加安全,并且您可以将其实现为脚本。

With fgetcsv, you could do something like this assuming you just had a one column file with the email addresses listed: 使用fgetcsv,您可以执行以下操作,假设您只有一个一栏文件,其中列出了电子邮件地址:

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        //echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            if ($c==0){
                 //This is the first column
                 //Just run a generic MySQL insert command here (see below for link for more info on this)
            }
        }
    }
    fclose($handle);
}

Tutorial on PHP MySQL Insert: at W3Schools . W3Schools上的PHP MySQL Insert教程: That should get you going on this endeavor. 那应该使您继续努力。

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

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