欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php excel格式(csv)数据导入导出(示例)

程序员文章站 2022-04-17 09:41:02
...
  1. $fname = $_FILES['MyFile']['name'];
  2. $do = copy($_FILES['MyFile']['tmp_name'],$fname);
  3. if ($do){
  4. echo"导入数据成功
    ";
  5. }else{
  6. echo "";
  7. }
  8. ?>
  9. " METHOD="POST">
  10. 导入CVS数据

  11. error_reporting(0);//导入CSV格式的文件
  12. $connect=mysql_connect("localhost","a0530093319","123456") or die("could not connect to database");
  13. mysql_select_db("a0530093319",$connect) or die (mysql_error());
  14. $fname = $_FILES['MyFile']['name'];
  15. $handle=fopen("$fname","r");
  16. while($data=fgetcsv($handle,10000,",")){
  17. $q="insert into test (code,name,date) values ('$data[0]','$data[1]','$data[2]')";
  18. mysql_query($q) or die (mysql_error());
  19. }
  20. fclose($handle);
  21. ?>
复制代码

用php将数据库导出成excel,测试成功。

测试代码:

  1. $DB_Server = "localhost";
  2. $DB_Username = "root";
  3. $DB_Password = "";
  4. $DB_DBName = "ishop";
  5. $DB_TBLName = "oi_mall_payment";
  6. $savename = date("YmjHis");
  7. $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect.");
  8. mysql_query("Set Names gbk"); $file_type = "vnd.ms-excel";
  9. $file_ending = "xls";
  10. header("Content-Type: application/$file_type;charset=big5");
  11. header("Content-Disposition: attachment; filename=".$savename.".$file_ending");
  12. //header("Pragma: no-cache");
  13. $now_date = date("Y-m-j H:i:s");
  14. $title = "数据库名:$DB_DBName,数据表:$DB_TBLName,备份日期:$now_date";
  15. $sql = "Select * from $DB_TBLName";
  16. $ALT_Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database");
  17. $result = @mysql_query($sql,$Connect) or die(mysql_error());
  18. echo("$title\n");
  19. $sep = "\t";
  20. for ($i = 0; $i echo mysql_field_name($result,$i)."\t";
  21. }
  22. print("\n");
  23. $i = 0;
  24. while($row = mysql_fetch_row($result)){
  25. $schema_insert = "";
  26. for($j=0; $jif(!isset($row[$j]))
  27. $schema_insert .= "NULL".$sep;
  28. elseif ($row[$j] != "")
  29. $schema_insert .= "$row[$j]".$sep;
  30. else
  31. $schema_insert .= "".$sep;
  32. }
  33. $schema_insert = str_replace($sep."$", "", $schema_insert);
  34. $schema_insert .= "\t";
  35. print(trim($schema_insert));
  36. print "\n";
  37. $i++;
  38. }
  39. return (true);
  40. ?>
复制代码