zoukankan      html  css  js  c++  java
  • PHP导出Mysql数据到Excel

    临时需要将Mysql中一张表导出成Excel表格,有个phpexcel的插件可以用,我觉得有点麻烦,况且我是临时要备份的,就直接自己写了。

    <?php 
    /*连接数据库*/
     $DB_Server = "ServerIP";
     $DB_Username = "UserName"; 
     $DB_Password = "PassWord"; 
     $DB_DBName = "DBname";  //目标数据库名
    $DB_TBLName = "TableName";  //目标表名
    
    $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect."); 
     mysql_query("set names utf8"); 
    
    $savename = date("YmjHis"); //导出excel文件名
    $file_type = "vnd.ms-excel"; 
     $file_ending = "xls"; 
     header("Content-Type: application/$file_type;charset=utf-8"); 
     header("Content-Disposition: attachment; filename=".$savename.".$file_ending"); 
    header("Pragma: no-cache"); 
    
    /*写入备注信息*/
     $now_date = date("Y-m-j H:i:s"); 
     $title = "数据库名:$DB_DBName,数据表:$DB_TBLName,备份日期:$now_date"; 
     echo iconv("utf-8","gbk",$title)."
    "; 
    
    /*查询数据库*/
     $sql = "Select * from $DB_TBLName"; 
     $ALT_Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database"); 
     $result = @mysql_query($sql,$Connect) or die(mysql_error()); 
    
    /*写入表字段名*/
    for ($i = 0; $i < mysql_num_fields($result); $i++) { 
      
      echo mysql_field_name($result,$i) . "	"; 
     } 
     echo "
    ";
    
    /*写入表数据*/
     $sep = "	"; 
     while($row = mysql_fetch_row($result)) { 
      $data = ""; 
       for($i=0; $i<mysql_num_fields($result);$i++) { 
        if(!isset($row[$i])) 
         $data .= "NULL".$sep; //处理NULL字段
       elseif ($row[$i] != ""){
         $datmp=iconv("utf-8", "gbk",$row[$i]);
         $data .= $datmp.$sep; 
       }
        else 
         $data .= "".$sep; //处理空字段
      } 
      echo $data."
    "; 
     }
     ?> 

    好了,这样直接访问这个php文件就可以将指定的表中数据导出了。

  • 相关阅读:
    python列表转json树菜单
    lvm分区创建和扩容
    分布式网络概述
    mycat权威指南阅读笔记--序言1
    Mongodb副本集实现及读写分离
    线程和进程
    socket客户端怎么判断http响应数据的结束
    java遍历http请求request的所有参数实现方法
    Java中mongodb使用and和or的复合查询
    idea @Override is not allowed when implementing interface method
  • 原文地址:https://www.cnblogs.com/mediciyan/p/4149678.html
Copyright © 2011-2022 走看看