Export mysql database data using PHPExcel
Use PHPExcel to export files
First, let's take a look at the above article. The writing method is the same, but there are more database operations in the middle, followed by the excel browser output.
Database Code (the database configuration file is self-completed)
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;}}
Database Export Code:
0) {$ objPHPExcel-> createSheet () ;}$ objPHPExcel-> setActiveSheetIndex ($ I); $ objSheet = $ objPHPExcel-> getActiveSheet (); $ data = $ db-> getUserinfo (); $ objSheet-> setCellValue (A1, number)-> setCellValue (B1, login name)-> setCellValue (C1, nickname) -> setCellValue (D1, email)-> setCellValue (E1, school)-> setCellValue (F1, Last Logon Time); $ j = 2; foreach ($ data as $ key => $ value) {# code... $ objSheet-> setCellValue (. $ 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'); // generate the excelfile browser_export(excel5, browser_excel03.xls); // the browser outputs $ 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 ');}
Run: