PHP excel sample code for downloading (retrieving data from a database)
/**
* Generate an excel file in PHPEXCEL
* @ Author: firmy
* @ Desc supports generating excel files for any row and column data without adding cell styles and alignment.
*/
Header ("connect-type: text/html; charset = utf-8 ");
$ Dsn = "mysql: host = localhost; dbname = me ";
$ Db = new PDO ($ dsn, 'root', '000000', array (PDO: MYSQL_ATTR_INIT_COMMAND => 'set NAMES \ 'utf8 \''));
$ Count = $ db-> query ("select * from test ");
$ Data = $ count-> fetchAll (PDO: FETCH_ASSOC );
// Print_r ($ res); die;
Require_once 'classes/PHPExcel. php ';
Require_once 'classes/PHPExcel/Reader/excel2007.php ';
Require_once 'classes/PHPExcel/Reader/excel5.php ';
Include_once 'classes/PHPExcel/IOFactory. php ';
// Create a new PHP Excel Object
$ ObjPHPExcel = new PHPExcel ();
$ ObjProps = $ objPHPExcel-> getProperties ();
// Set the header
$ I = 0;
Foreach ($ data as $ k => $ v ){
// Print_r ($ v); die;
If ($ I <1 ){
$ Arrd = array_keys ($ v );
// Print_r ($ arrd); die;
$ Key = ord ("");
Foreach ($ arrd as $ kk => $ vv ){
$ Colum = chr ($ key );
$ ObjPHPExcel-> setActiveSheetIndex (0)-> setCellValue ($ colum. '1', $ vv );
$ Key + = 1;
}
}
$ I ++;
}
$ Column = 2;
$ ObjActSheet = $ objPHPExcel-> getActiveSheet ();
Foreach ($ data as $ key => $ rows) {// write row
$ Span = ord ("");
Foreach ($ rows as $ keyName => $ value) {// write a column
$ J = chr ($ span );
$ ObjActSheet-> setCellValue ($ j. $ column, $ value );
$ Span ++;
}
$ Column ++;
}
// Download
// Redirect the output to a client web browser (Excel2007)
$ FileName = iconv ("UTF-8", "gb2312", "bao.xls ");
Header ("Content-Disposition: attachment; filename = \" $ fileName \"");
Header ('cache-Control: max-age = 0 ');
$ ObjWriter = PHPExcel_IOFactory: createWriter ($ objPHPExcel, 'excel2007 ');
$ ObjWriter-> save ('php: // output'); // download the file in a browser