PHPExcel匯出mysql資料庫資料

來源:互聯網
上載者:User

標籤:excel   php   

使用PHPExcel匯出檔案


首先看看上面的文章,寫入方法一樣,只是中間多了資料庫的操作,後面還有excel瀏覽器輸出。

資料庫代碼(資料庫設定檔自行完成)

<?php/*db.php*/require dirname(__FILE__)."/dbconfig.php";class db{public $conn = null;public function __construct($config){$this->conn=mysql_connect($config['host'],$config['username'],$config['password']) or die(mysql_error());mysql_select_db($config['database'],$this->conn) or die(mysql_error());mysql_query("set names ".$config['charset']) or die(mysql_error());}public function getResult($sql){$resource = mysql_query($sql,$this->conn) or die(mysql_error());$res = array();while(($row=mysql_fetch_assoc($resource))!=false){$res[] = $row;}return $res;}public function getUserinfo(){$sql = "。。。";$res = self::getResult($sql);return $res;}}


資料庫匯出代碼:

<?php$dir = dirname(__FILE__);require $dir."/db.php";require $dir."/PHPExcel.php";$db = new db($phpexcel);$objPHPExcel = new PHPExcel();for($i=0; $i<3; $i++){if($i>0){$objPHPExcel->createSheet();}$objPHPExcel->setActiveSheetIndex($i);$objSheet = $objPHPExcel->getActiveSheet();$data = $db->getUserinfo();$objSheet->setCellValue("A1","編號")->setCellValue("B1","登陸名")->setCellValue("C1","暱稱")->setCellValue("D1","電子郵箱")->setCellValue("E1","學校")->setCellValue("F1","最後登陸時間");$j = 2;foreach ($data as $key => $value) {# code...$objSheet->setCellValue("A".$j,$value['id'])->setCellValue("B".$j,$value['user_login'])->setCellValue("C".$j,$value['user_nicename'])->setCellValue("D".$j,$value['user_email'])->setCellValue("E".$j,$value['sch_name'])->setCellValue("F".$j,$value['last_login_time']);$j++;}}$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel5");// $objWriter->save($dir.'/export.xls'); //產生excel檔案browser_export("Excel5","browser_excel03.xls"); //瀏覽器輸出$objWriter->save("php://output");function browser_export($type, $filename){if($type == "Excel5"){header('Content-Type: application/vnd.ms-excel'); //excel2003}else{header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //excel2007}header('Content-Disposition: attachment;filename="'.$filename.'"');header('Cache-Control: max-age=0');}

運行:



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

PHPExcel匯出mysql資料庫資料

聯繫我們

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