用phpExcel和tp5导出数据

1.首先将下载phpexcel放入extend文件夹下面,引用文件时在前面加上\

2.查出需导出的数据装入数组

下面是代码

public function user(){
     //查询数据
$user_table = Db::table('user_msg')->select(); $show_table = array(); foreach($user_table as $k=>$v){ $orderArr = Db::query("SELECT * from orders where user_id='{$v['user_id']}' limit 0,1"); if(!empty($orderArr)){ //总价格表 $total_price = Db::query("select sum(total_price) from (SELECT total_price FROM orders where user_id = '{$v['user_id']}') as newtable"); // 用户最后一次消费表 $last_time = Db::query("select create_time from orders WHERE user_id = '{$v['user_id']}' order by create_time desc limit 0,1 "); } // 用户的总价表 $show_table[$k]['total_price'] = !empty($orderArr)?$total_price[0]['sum(total_price)']:false; $show_table[$k]['last_time'] = !empty($orderArr)?$last_time[0]['create_time']:false; foreach ($v as $m=>$n) { $show_table[$k][$m] = $n; } } //按价格对数组进行排序 foreach($show_table as $a=>$b){ $show[] = $b['total_price'];//价格存入一个数组 } array_multisort($show,SORT_DESC,$show_table);//对数组按照价格(total_price)进行排序 //链接phpexcel.PHPExcel页 import('phpexcel.PHPExcel', EXTEND_PATH); //实例化PHPExcel()类 $obj = new \PHPExcel(); $objsheet = $obj->getActiveSheet();//获得当前活动sheet的操作对象 $objsheet ->setTitle('用户列表');//给当前sheet设置名称      //设置表中数据 //设置标题(按照表格的方式) $objsheet ->setCellValue("A1",'账号')->setCellValue("B1",'昵称')->setCellValue('D1','创建时间')->setCellValue('E1','最近一次消费')->setCellValue("F1",'总消费'); $j = 2; //录入数据 foreach($show_table as $k=>$v){ $objsheet ->setCellValue("A".$j,$v['user_id'])->setCellValue("B".$j,$v['user_name'])->setCellValue("C".$j,$v['tel'])->setCellValue('D'.$j,$v['create_time'])->setCellValue('E'.$j,$v['last_time'])->setCellValue("F".$j,$v['total_price']); $j++; } //生成Excel文件 $obj1 = \PHPExcel_IOFactory::createWriter($obj,'Excel5'); $this->create('Excel5','用户列表.xls');//命名并生成文件下载,调用下面方法 $obj1->save("php://output"); } //生成报表方法 function create($type,$file){ if($type == "Excel5"){ header('Content-Type: application/vnd.ms-excel'); }else{ header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); } header('Content-Disposition: attachment;filename = "'.$file.'"'); header('Cache-Control:max-age=0');//禁止缓存 }

猜你喜欢

转载自www.cnblogs.com/notesbooks/p/9160225.html