程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP將mysql數據庫導出為excel表

PHP將mysql數據庫導出為excel表

編輯:關於PHP編程

利用php導出mysql數據庫為excel表格的方法很多,最簡單的就直接使用php fputcsv函數了,還有就是直接輸入csv格式也是可以了,要生成excel標准格式我們需使用第三方插件了

方法一,利用fputcsv

 代碼如下 復制代碼


// 輸出Excel文件頭,可把user.csv換成你要的文件名
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="user.csv"');
header('Cache-Control: max-age=0');

// 從數據庫中獲取數據,為了節省內存,不要把數據一次性讀到內存,從句柄中一行一行讀即可
$sql = 'select * from tbl where ……';
$stmt = $db->query($sql);

// 打開PHP文件句柄,php://output 表示直接輸出到浏覽器
$fp = fopen('php://output', 'a');

// 輸出Excel列名信息
$head = array('姓名', '性別', '年齡', 'Email', '電話', '……');
foreach ($head as $i => $v) {
// CSV的Excel支持GBK編碼,一定要轉換,否則亂碼
$head[$i] = iconv('utf-8', 'gbk', $v);
}

// 將數據通過fputcsv寫到文件句柄
fputcsv($fp, $head);

// 計數器
$cnt = 0;
// 每隔$limit行,刷新一下輸出buffer,不要太大,也不要太小
$limit = 100000;

// 逐行取出數據,不浪費內存
while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {

$cnt ++;
if ($limit == $cnt) { //刷新一下輸出buffer,防止由於數據過多造成問題
ob_flush();
flush();
$cnt = 0;
}

foreach ($row as $i => $v) {
$row[$i] = iconv('utf-8', 'gbk', $v);
}
fputcsv($fp, $row);
}

方法二,直接在浏覽器用header輸出csv格式的數據

 代碼如下 復制代碼

<?php
/*連接數據庫*/
$DB_Server = "localhost";
$DB_Username = "root";
$DB_Password = "123456";
$DB_DBName = "mydb";  //目標數據庫名
$DB_TBLName = "mytable";  //目標表名
$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=utf8");
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("$titlen");

/*查詢數據庫*/
$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 "n";

/*寫入表數據*/
$sep = ",t";
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] != "")
    $data .= "$row[$i]".$sep;
   else
    $data .= "".$sep; //處理空字段
  }
 echo $data."n";
}
?>

例3,第二個差不多了

 代碼如下 復制代碼


//搜索
    $start_time = strtotime($start_date);
    $end_time = strtotime($end_date);
    $sql = "select a.*,b.order_amount,b.money_paid from ".$ecs->table('invoice')." as a ".
                " left join ".$ecs->table('order_info')." as b on a.order_id=b.order_sn".
                " where a.add_time >=".$start_time." and a.add_time <=".$end_time." ";
    $temp_list = $db->getAll($sql);

    if($temp_list){//有數據
        $Html='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><body>'.chr(13).chr(10);
        $Html.='<table width="700" border="1" align="center" cellpadding="2" cellspacing="1">
                            <tr align="center">
                                    <td align="center" nowrap="nowrap">時間:</td>
                                    <td align="center" nowrap="nowrap" colspan="9">'.$start_date.'~'.$end_date.'</td>
                            </tr>
                            <tr align="center">
                                     <td align="center" nowrap="nowrap">編號</td>
                                     <td align="center" nowrap="nowrap">發票類型</td>
                                     <td align="center" nowrap="nowrap">發票抬頭</td>
                                     <td align="center" nowrap="nowrap">發票內容</td>
                                     <td align="center" nowrap="nowrap">訂單號</td>
                                     <td align="center" nowrap="nowrap">金額</td>
                                     <td align="center" nowrap="nowrap">添加日期</td>
                                     <td align="center" nowrap="nowrap">收件人</td>
                                     <td align="center" nowrap="nowrap">聯系方式</td>
                                     <td align="center" nowrap="nowrap">地址</td>
                           </tr>';
            //取得符合條件的數組
            for($i=0;$i<count($temp_list);$i++){
                 $temp_i = $i+1;
                 if($temp_list[$i][order_amount]==0){
                     $temp_money = $temp_list[$i][money_paid];
                 }else{
                     $temp_money = $temp_list[$i][order_amount];
                 }

                 $temp_time = date('Y-m-d', $temp_list[$i]['add_time']);
                 $Html.='<tr align="center">
                                     <td align="center" nowrap="nowrap">'.$temp_i.'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_list[$i][type_name].'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_list[$i][top].'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_list[$i][content].'</td>
                                     <td align="center" nowrap="nowrap" style="vnd.ms-excel.numberformat:@">'.$temp_list[$i][order_id].'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_money.'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_time.'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_list[$i][user_name].'</td>
                                     <td align="center" nowrap="nowrap">'.$temp_list[$i][mobile].' '.$temp_list[$i][tel].' </td>
                                     <td align="center" nowrap="nowrap">'.$temp_list[$i][address].'</td>
                           </tr>';
             }
             $Html.='</table>';
             $Html.='</body></html>';
             $mime_type = 'application/vnd.ms-excel';
             header('Content-Type: ' . $mime_type);
             header('Content-Disposition: attachment; filename="invoice.xls"');
             header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
             header('Pragma: public');
            echo $Html;

有時excel會自動把數字轉換格式,於是有些手機號碼,身份證之類的就亂了,因此可以在導出時,先定義好

 代碼如下 復制代碼

<td align="center" nowrap="nowrap" style="vnd.ms-excel.numberformat:@">'.$temp_list[$i][order_id].'</td>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved