PHPExcel下载(从数据库获取数据)示例代码
2015-04-28 11:28
441 查看
<?php
function exportExcel($filename,$content){
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/vnd.ms-execl");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
echo $content;
}
$dsn="mysql:dbname=ci;host=localhost";
$db=new PDO($dsn,'root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES \'UTF8\''));//实例化pdo对象
$res=$db->query("select * from student");//从数据库查询数据
$str = "姓名\t性别\t年龄\t\n";
$str = iconv('utf-8','gb2312',$str);//iconv() 是编码转换函数
while($row=$res->fetchAll()){
$name = iconv('utf-8','gb2312',$row['name']);
$sex = iconv('utf-8','gb2312',$row['sex']);
$str .= $name."\t".$sex."\t".$row['age']."\t\n";
}
$filename = date('Ymd').'.xls';
exportExcel($filename,$str); //生成excel表格
function exportExcel($filename,$content){
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/vnd.ms-execl");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
echo $content;
}
$dsn="mysql:dbname=ci;host=localhost";
$db=new PDO($dsn,'root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES \'UTF8\''));//实例化pdo对象
$res=$db->query("select * from student");//从数据库查询数据
$str = "姓名\t性别\t年龄\t\n";
$str = iconv('utf-8','gb2312',$str);//iconv() 是编码转换函数
while($row=$res->fetchAll()){
$name = iconv('utf-8','gb2312',$row['name']);
$sex = iconv('utf-8','gb2312',$row['sex']);
$str .= $name."\t".$sex."\t".$row['age']."\t\n";
}
$filename = date('Ymd').'.xls';
exportExcel($filename,$str); //生成excel表格
相关文章推荐
- 电子表格数据导入数据库和数据库下载数据到excel PHP代码phpexecl
- java下载excel,excel从数据库获取数据
- PHP上传Excel文件导入数据到MySQL数据库(详细示例代码)【原创】
- PHP处理excel文件 包括处理excel数据上传到数据库以及从数据库下载数据到excel
- 生成/读取(反向更新数据库) Excel文件(示例代码下载)
- 生成/读取(反向更新数据库) Excel文件(示例代码下载)
- Asp.net 2.0 装载XML文件中数据到Excel文件中(示例代码下载)
- AjaxPro.NET实现TextBox智能获取服务端数据功能(Asp.net 2.0)(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
- 生成/读取(反向更新数据库) Excel文件(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
- AjaxPro.NET实现TextBox智能获取服务端数据功能(Asp.net 2.0)(示例代码下载)
- AjaxPro.NET完成TextBox智能获取服务端数据功能(Asp.net 2.0)(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
- Asp.net 2.0 装载XML文件中数据到Excel文件中(示例代码下载)
- AjaxPro.NET实现TextBox智能获取服务端数据功能(Asp.net 2.0)(示例代码下载)
- Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)