Home > Backend Development > PHP Tutorial > PHP excel format (csv) data import and export (example)

PHP excel format (csv) data import and export (example)

WBOY
Release: 2016-07-25 08:55:11
Original
1123 people have browsed it
  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("$titlen");
  19. $sep = "t";
  20. for ($i = 0; $i < mysql_num_fields($result); $i++){
  21. echo mysql_field_name($result,$i)."t";
  22. }
  23. print("n");
  24. $i = 0;
  25. while($row = mysql_fetch_row($result)){
  26. $schema_insert = "";
  27. for($j=0; $jif(!isset($row[$j]))
  28. $schema_insert .= "NULL".$sep;
  29. elseif ($row[$j] != "")
  30. $schema_insert .= "$row[$j]".$sep;
  31. else
  32. $schema_insert .= "".$sep;
  33. }
  34. $schema_insert = str_replace($sep."$", "", $schema_insert);
  35. $schema_insert .= "t";
  36. print(trim($schema_insert));
  37. print "n";
  38. $i++;
  39. }
  40. return (true);
  41. ?>
复制代码


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template