准备工作:
1.首先,下载一个PHPExcel类包,下方是上传的类包的下载路径
https://github.com/PHPOffice/PHPExcel
2.安装PHPExcel到CI中
a). 解压压缩包中的Classes文件夹中的内容到application\libraries\目录下,目录结构如下:
—application\libraries\PHPExcel.PHP
— application\libraries\PHPExcel (文件夹)
b).修改application\libraries\PHPExcel\IOFactory.php 文件
— 将文件中其定义的类名从PHPExcel_IOFactory改为IOFactory,遵从CI类命名规则。
—将其构造函数改为public
3.编写代码
$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');
$phpexcel = new PHPExcel();
// 设置表头
$phpexcel->setActiveSheetIndex(0)
->setCellValue('A1', '订单号')
->setCellValue('B1', '订单内容')
->setCellValue('C1', '创建时间')
->setCellValue('D1', '付费时间')
->setCellValue('E1', '金额')
->setCellValue('F1', '状态');
// 设置样式
$phpexcel->createSheet();
$objSheet = $phpexcel->getActiveSheet();
$objSheet->getColumnDimension('A')->setWidth(25); //设置列宽
$objSheet->getColumnDimension('B')->setWidth(35);
$objSheet->getColumnDimension('C')->setWidth(15);
$objSheet->getColumnDimension('D')->setWidth(15);
// 标签名
$phpexcel->getActiveSheet()->setTitle('付费记录');
// 使用第一个表
$phpexcel->setActiveSheetIndex(0);
$objWriter = new PHPExcel_Writer_Excel5($phpexcel);
// 查询到的数据源
$key = 0;
foreach ($result->orderlist as $value) {
//表格是从2开始的 因为上面还有表头
$value->o_month_num;
$i=$key+2;
$key++;
//这里是设置A1单元格的内容
$phpexcel->getActiveSheet()->setCellValue('A'.$i, $value->orderid);
//这里是设置B1单元格的内容
$phpexcel->getActiveSheet()->setCellValue('B'.$i, "按并发人数付费(".$value->o_concurrent_num. "人)开通时长:".$value->o_month_num."个月");
//这里是设置C1单元格的内容
$phpexcel->getActiveSheet()->setCellValue('C'.$i, $this->getToolTime($value->o_time));
//这里是设置D1单元格的内容
$phpexcel->getActiveSheet()->setCellValue('D'.$i, $this->getToolTime($value->o_charge_time));
//这里是设置E1单元格的内容
$phpexcel->getActiveSheet()->setCellValue('E'.$i, "¥".$value->o_actual_amount."00");
$state = "";
if ($value->o_state == 3) {
$state = "成功";
}else if($value->o_state == 2) {
$state = "失败";
}else{
$state = "待支付";
}
$phpexcel->getActiveSheet()->setCellValue('F'.$i, $state);
//以此类推,可以设置C D E F G看你需要了。
}
$outputFileName = '订单记录'.time().'.xls';
header('Content-Type: application/vnd.ms-excel');
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition:inline;filename="'.$outputFileName.'"');
header("Content-Transfer-Encoding: binary");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
$objWriter->save("php://output");