简体   繁体   English

使用PHP将Excel数据导入MySQL数据库

[英]Import Excel Data into MySQL Database using PHP

I have a website. 我有一个网站。 The website shows a schedule of school. 该网站显示了学校时间表。

Every day might have some changes, for example: John calls and informs he is sick so he can't arrive tomorrow. 每天可能会有一些变化,例如:约翰打电话通知他生病了,所以明天不能到。 His students should have a substitute teacher. 他的学生应有一名代课老师。

So, I have an email address that should get a mail containing the Excel file of the changes. 因此,我有一个电子邮件地址,应该会收到包含更改的Excel文件的邮件。 and what I want is create a PHP code that take the file from the eMail and import it to SQL Database, and show it in the website. 我想要的是创建一个PHP代码,该代码从电子邮件中提取文件并将其导入SQL数据库,并在网站上显示。 of course - it's should be done automatically and done on a daily basis. 当然-它应该自动完成并每天执行。

If you have a better idea or a better way for how to "code" the site - I will be happy to hear it. 如果您对网站“编码”有一个更好的主意或更好的方法-我将很高兴听到它。

BTW I found a little piece of code in PHP from Webslesson 顺便说一句,我在Webslesson的 PHP中发现了一些代码

Database Table 数据库表

CREATE TABLE IF NOT EXISTS `tbl_excel` (
  `excel_id`    INT(11)      NOT NULL AUTO_INCREMENT,
  `excel_name`  VARCHAR(250) NOT NULL,
  `excel_email` VARCHAR(300) NOT NULL,
  PRIMARY KEY (`excel_id`)
)
  ENGINE = MyISAM
  DEFAULT CHARSET = latin1
  AUTO_INCREMENT = 1;

index.php 的index.php

 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 include ("PHPExcel/IOFactory.php");  
 $html="<table border='1'>";  
 $objPHPExcel = PHPExcel_IOFactory::load('example.xls');  
 foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)   
 {  
      $highestRow = $worksheet->getHighestRow();  
      for ($row=2; $row<=$highestRow; $row++)  
      {  
           $html.="<tr>";  
           $name = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(0, $row)->getValue());  
           $email = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(1, $row)->getValue());  
           $sql = "INSERT INTO tbl_excel(excel_name, excel_email) VALUES ('".$name."', '".$email."')";  
           mysqli_query($connect, $sql);  
           $html.= '<td>'.$name.'</td>';  
           $html .= '<td>'.$email.'</td>';  
           $html .= "</tr>";  
      }  
 }  
 $html .= '</table>';  
 echo $html;  
 echo '<br />Data Inserted';  
 ?>  

this code working fine 此代码工作正常

 $file = "your-file.xls";
 $handle = fopen($file, "r");
 $c = 0;
 while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
 {
 $name = $filesop[0];
 $email = $filesop[1];

 $sql = mysql_query("INSERT INTO xls (name, email) VALUES ('$name','$email')");
 }

 if($sql){
 echo "You database has imported successfully";
 }else{
 echo "Sorry! There is some problem.";
 }

Try this 尝试这个

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

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