<?php
/**
* 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<1){
$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'); //文件通过浏览器下载