欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHPExcel下载(从数据库获取数据)示例代码

程序员文章站 2022-06-08 12:38:02
...

/**

* PHPEXCEL生成excel文件

* @author:firmy

* @desc 支持任意行列数据生成excel文件,暂未添加单元格样式和对齐

*/


header("connect-type:text/html;charset=utf-8");

$dsn="mysql:host=localhost;dbname=me";

$db=new PDO($dsn,'root','123',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';



//创建新的PHPExcel对象

$objPHPExcel = new PHPExcel();

$objProps = $objPHPExcel->getProperties();


//设置表头

$i=0;

foreach($data as $k=>$v){

//print_r($v);die;

if($i

$arrd=array_keys($v);

//print_r($arrd);die;

$key = ord("A");

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){ //行写入

$span = ord("A");

foreach($rows as $keyName=>$value){// 列写入

$j = chr($span);

$objActSheet->setCellValue($j.$column, $value);

$span++;

}

$column++;

}



//下载

//将输出重定向到一个客户端web浏览器(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'); //文件通过浏览器下载

相关标签: PHPExcel