步骤一:下载PHPExcel插件,并将PHPExcel核心文件引入TP项目中:
步骤二:在html页面写个超链接<a></a> 来访问后台控制器中导出Excel的方法
步骤三:在后台创建ExcelController.class.php控制器
1.引入PHPExcel
2.在ExcelController控制中编写export_excel()方法来实现导出功能:
<?php
namespace Back\Controller;
use Think\Controller;
Vendor ("PHPExcel.PHPExcel");
class ExcelController extends Controller {
public function export_excel(){
//new一个PHPExcel类,或者说创建一个excel,tp中“\”不能掉
$objExcel = new \PHPExcel();
//使用Excel5对应的类,生成.xls文件
$objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
//设置水平垂直居中
$objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//设置字体和样式
$objExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
$objExcel->getActiveSheet()->getStyle('A2:D2')->getFont()->setBold(true);
$objExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
//设置第一行、第二行的默认高度
$objExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
$objExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
$objExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(20);
$objExcel->getActiveSheet()->getRowDimension('4')->setRowHeight(20);
$objExcel->getActiveSheet()->getRowDimension('5')->setRowHeight(20);
//设置某一列的宽度
$objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
$objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
$objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
//设置表头(第一行合并):
$objExcel->getActiveSheet()->mergeCells('A1:D1');
$objActSheet = $objExcel->getActiveSheet(0);
//填写表头内容:
$objActSheet ->setCellValue('A1','用户信息表');
$objActSheet ->setCellValue('A2','用户名');
$objActSheet ->setCellValue('B2','性别');
$objActSheet ->setCellValue('C2','年龄');
$objActSheet ->setCellValue('D2','电话');
//查询想要要导出的数据:字段-行数
$data=M('User')->field("id,nick_name,sex,age,phone")->order("id DESC")->limit(500)->select();
//print_r($data);die;
$count=count($data);
$baseRow = 3; //前面设置了第一行是合并后的标题栏,第二行为表的各个字段名,所以数据是从第三行开始导入
//将二维数组循环输出
foreach ( $data as $key => $value ) {
$i = $baseRow + $key;
$objExcel->getActiveSheet()->setCellValue('A'.$i,$value['nick_name']);
$objExcel->getActiveSheet()->setCellValue('B'.$i,$value['sex']);
$objExcel->getActiveSheet()->setCellValue('C'.$i,$value['age']);
$objExcel->getActiveSheet()->setCellValue('D'.$i,$value['phone']);
}
$objExcel->setActiveSheetIndex(0);
header('Content-Type: applicationnd.ms-excel');
header('Content-Disposition: attachment;filename="用户信息表('.date('Ymd-His').').xls"');
header('Cache-Control: max-age=0');
//支持浏览器下载生成的文档
$objWriter->save('php://output');
}
}
3.测试点击html页面中的超链接效果