php把資料表匯出為Excel表的最簡單、最快的方法(不用外掛程式)_php執行個體

來源:互聯網
上載者:User

先定義頭部資訊,表示輸出一個excel。然後再以table的形式把資料庫的資訊迴圈的echo出來,就好了。

複製代碼 代碼如下:

<?php

 header("Content-type:application/vnd.ms-excel");
 header("Content-Disposition:filename=xls_region.xls");

 $cfg_dbhost = 'localhost';
 $cfg_dbname = 'testdb';
 $cfg_dbuser = 'root';
 $cfg_dbpwd = 'root';
 $cfg_db_language = 'utf8';
 // END 配置

 //連結資料庫
 $link = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd);
 mysql_select_db($cfg_dbname);
 //選擇編碼
 mysql_query("set names ".$cfg_db_language);

 //users表
 $sql = "desc users";

 $res = mysql_query($sql);
 echo "<table><tr>";
 //匯出表頭(也就是表中擁有的欄位)
 while($row = mysql_fetch_array($res)){
  $t_field[] = $row['Field']; //Field中的F要大寫,否則沒有結果
  echo "<th>".$row['Field']."</th>";
 }
 echo "</tr>";
 //匯出100條資料
 $sql = "select * from users limit 100";
 $res = mysql_query($sql);
 while($row = mysql_fetch_array($res)){
  echo "<tr>";
  foreach($t_field as $f_key){
   echo "<td>".$row[$f_key]."</td>";
  }
  echo "</tr>";
 }
 echo "</table>";

?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.