PHP實現匯出MySQL資料到Excel檔案

來源:互聯網
上載者:User
 
  1. // 輸出Excel檔案頭,可把user.csv換成你要的檔案名稱  
  2.  
  3.   header('Content-Type: application/vnd.ms-excel');  
  4.  
  5.   header('Content-Disposition: attachment;filename="user.csv"');  
  6.  
  7.   header('Cache-Control: max-age=0');  
  8.  
  9.   // 從資料庫中擷取資料,為了節省記憶體,不要把資料一次性讀到記憶體,從控制代碼中一行一行讀即可  
  10.  
  11.   $sql = 'select * from tbl where ……';  
  12.  
  13.   $stmt = $db->query($sql);  
  14.  
  15.   // 開啟PHP檔案控制代碼,php://output 表示直接輸出到瀏覽器  
  16.  
  17.   $fp = fopen('php://output', 'a');  
  18.  
  19.   // 輸出Excel列名資訊  
  20.  
  21.   $head = array('姓名', '性別', '年齡', 'Email', '電話', '……');  
  22.  
  23.   foreach ($head as $i => $v) {  
  24.  
  25.   // CSV的Excel支援GBK編碼,一定要轉換,否則亂碼  
  26.  
  27.   $head[$i] = iconv('utf-8', 'gbk', $v);  
  28.  
  29.   }  
  30.  
  31.   // 將資料通過fputcsv寫到檔案控制代碼  
  32.  
  33.   fputcsv($fp, $head);  
  34.  
  35.   // 計數器  
  36.  
  37.   $cnt = 0;  
  38.  
  39.   // 每隔$limit行,重新整理一下輸出buffer,不要太大,也不要太小  
  40.  
  41.   $limit = 100000;  
  42.  
  43.   // 逐行取出資料,不浪費記憶體  
  44.  
  45.   while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {  
  46.  
  47.   $cnt ++;  
  48.  
  49.   if ($limit == $cnt) { //重新整理一下輸出buffer,防止由於資料過多造成問題  
  50.  
  51.   ob_flush();  
  52.  
  53.   flush();  
  54.  
  55.   $cnt = 0;  
  56.  
  57.   }  
  58.  
  59.   foreach ($row as $i => $v) {  
  60.  
  61.   $row[$i] = iconv('utf-8', 'gbk', $v);  
  62.  
  63.   }  
  64.  
  65.   fputcsv($fp, $row);  
  66.  
  67.   }   


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.