TypechoJoeTheme

Dcr163的博客

统计

网站使用 PHPExcel导出excel表格

2017-01-09
/
0 评论
/
787 阅读
/
正在检测是否收录...
01/09

首先下载一个PHPExcel类文件,下载地址:http://phpexcel.codeplex.com/
定义一个数据库配置文件,db.inc.php:

'127.0.0.1',
	'db_name'=>'test',
	'db_user'=>'root',
	'db_pass'=>'root',
	'db_charset'=>'utf-8'
	);


 ?>

数据库信息根据自己的信息修改;
在新建一个 db类,db.class.php:

mysql=mysql_connect($config['db_host'],$config['db_user'],$config['db_pass']) or die(mysql_error());
		mysql_select_db($config['db_name'],$this->mysql) or mysql_error();
		mysql_query('set names '.$config['db_charset'],$this->mysql) or mysql_error();
	}

	public function query($sql){
		$rst=mysql_query($sql);
		$rows=array();
		while ($row=mysql_fetch_assoc($rst)) {
			$rows[]=$row;
		}
		return $rows;
	}

	public function getInfo(){
		$sql="SELECT id,name,age,color,money FROM user ORDER BY money DESC LIMIT 20";
		return self::query($sql);
	}

}


 ?>

这里只使用了一个query查询语句;
在新建一个需要导出的php文件,index.php,代码全部贴上来:

<?php 
$dir=dirname(__FILE__);
include $dir.'/db.class.php';
include $dir.'/PHPExcel/PHPExcel.php';

$db=new db();											//实例化数据库对象
$excelObj=new PHPExcel();								//实例化phpexcel

for($i=1;$i1){
		$excelObj->createSheet();						//创建3个内置表 sheet
	}
	$excelObj->setActiveSheetIndex($i-1);				//设置当前为活动对象 sheet
	$sheetObj=$excelObj->getActiveSheet();				//
	$sheetObj->getDefaultStyle()
			 ->getAlignment()
			 ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)		//设置垂直居中
			 ->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);	//设置水平居中
	$sheetObj->setTitle('color-'.$i);					//设置sheet名称
	$sheetObj->setCellValue('A1','id')
			 ->setCellValue('B1','用户名')
			 ->setCellValue('C1','颜色')
			 ->setCellValue('D1','金钱');				//添加表头

	$infos=$db->getInfo();  							//取得数据库内的数据
	$j=2;	
	foreach($infos as $k =>$v){							//遍历填充表数据
		$sheetObj->setCellValue('A'.$j,$v['id'])
				 ->setCellValue('B'.$j,$v['name'])
				 ->setCellValue('C'.$j,$v['color'])
				 ->setCellValue('D'.$j,$v['money']);
		$j++;
	}
}

$saveObj=PHPExcel_IOFactory::createWriter($excelObj,'Excel2007');
// 直接保存到服务器
// $saveObj->save(time().'demo_2.xlsx');

//输出至浏览器 
outFile(time().'demo3.xlsx');
$saveObj->save('php://output');
// 输出到浏览器
// 
function outFile($fileName,$type='Execl2007'){
	if($type=='Execl5'){
		header('Content-Type: application/vnd.ms-excel');
	}else{
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	}
	header('Content-Disposition: attachment;filename="'.$fileName.'"');
	header('Cache-Control: max-age=0');
}


?>

这样就可以把数据库的数据导出到指定的文件下了

朗读
赞(0)
版权属于:

Dcr163的博客

本文链接:

http://dcr163.cn/111.html(转载时请注明本文出处及文章链接)

评论 (0)

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

最新回复

  1. slot mpo terbaru
    2025-02-08
  2. Sherry Stockdill
    2025-01-28
  3. slot demo
    2025-01-13
  4. 陌天
    2025-01-09
  5. Kerrie Bostick
    2024-12-28

标签云