PHP导出Excel实例讲解
发布:smiling 来源: PHP粉丝网 添加日期:2021-07-07 10:28:01 浏览: 评论:0
本次实现PHP导出Excel文件使用的是PHP开源程序PHPExcel,部分关键代码分享给大家,具体内容如下:
- <?php
- error_reporting(E_ALL);
- date_default_timezone_set('Asia/Shanghai');
- require_once './Classes/PHPExcel.php';
- $data=array(
- 0=>array(
- 'id'=>1001,
- 'username'=>'张飞',
- 'password'=>'123456',
- 'address'=>'三国时高老庄250巷101室'
- ),
- 1=>array(
- 'id'=>1002,
- 'username'=>'关羽',
- 'password'=>'123456',
- 'address'=>'三国时花果山'
- ),
- 2=>array(
- 'id'=>1003,
- 'username'=>'曹操',
- 'password'=>'123456',
- 'address'=>'延安西路2055弄3号'
- ),
- 3=>array(
- 'id'=>1004,
- 'username'=>'刘备',
- 'password'=>'654321',
- 'address'=>'愚园路188号3309室'
- )
- );
- $objPHPExcel=new PHPExcel();
- $objPHPExcel->getProperties()->setCreator('https://www.jb51.net')
- ->setLastModifiedBy('https://www.jb51.net')
- ->setTitle('Office 2007 XLSX Document')
- ->setSubject('Office 2007 XLSX Document')
- ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
- ->setKeywords('office 2007 openxml php')
- ->setCategory('Result file');
- $objPHPExcel->setActiveSheetIndex(0)
- ->setCellValue('A1','ID')
- ->setCellValue('B1','用户名')
- ->setCellValue('C1','密码')
- ->setCellValue('D1','地址');
- $i=2;
- foreach($data as $k=>$v){
- $objPHPExcel->setActiveSheetIndex(0)
- ->setCellValue('A'.$i,$v['id'])
- ->setCellValue('B'.$i,$v['username'])
- ->setCellValue('C'.$i,$v['password'])
- ->setCellValue('D'.$i,$v['address']);
- $i++;
- }
- $objPHPExcel->getActiveSheet()->setTitle('三年级2班');
- $objPHPExcel->setActiveSheetIndex(0);
- $filename=urlencode('学生信息统计表').'_'.date('Y-m-dHis');
- //生成xlsx文件
- /*
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
- header('Cache-Control: max-age=0');
- $objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
- */
- //生成xls文件
- header('Content-Type: application/vnd.ms-excel');
- header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
- header('Cache-Control: max-age=0');
- $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
- $objWriter->save('php://output');
- exit;
注意:如果导出中文时出现乱码,可以尝试将字符串转换成gb2312,代码类似如下:
查看代码打印
$str=mb_convert_encoding("gb2312","UTF-8",$str);
Tags: PHP导出Excel
相关文章
- ·php导出生成excel表格几种方法介绍(2014-08-01)
- ·php导出excel格式数据问题(2020-10-26)
- ·PHP 导出Excel示例分享(2021-04-03)
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)