PHPExcel導出mysql伺服器數據

使用PHPExcel導出文件

 

首先看看上面的文章,寫入方法一樣,隻是中間多瞭伺服器的操作,後面還有excel瀏覽器輸出。

伺服器代碼(伺服器配置文件自行完成)

 

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; $i0){
			$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');
	}
	

	

運行截圖:

 


 

 

發佈留言