导出数据到Excel文件
1 使用Thinkphp3.2版本的框架。 2 public function huanxinmsg(){ 3 $identity = I("get.ident"); 4 $roomid = I("get.roomid"); 5 $chatmsg = D('user_zhibo_chatmessage'); 6 $map['identity'] = $identity; 7 $map['roomid'] = $roomid; 8 $res =$chatmsg->field('id,content')->where($map)->order("id asc")->select(); 9 import("Org.Util.PHPExcel"); 10 $EXCEL = new \PHPExcel(); 11 $EXCEL->getProperties()->setCreator("NECionpy") 12 ->setLastModifiedBy("NECionpy") 13 ->setTitle("聊天历史纪录") 14 ->setSubject("聊天历史纪录") 15 ->setDescription("记录导出") 16 ->setKeywords("excel") 17 ->setCategory("result file"); 18 $Sheet = $EXCEL->setActiveSheetIndex(0); 19 $Sheet->getColumnDimension('A')->setAutoSize(true); 20 // 设置水平居中 21 $Sheet->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); 22 // 设置垂直居中 23 $Sheet->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); 24 $EXCEL->setActiveSheetIndex(0)->setCellValue('A1', 'msg'); 25 $num = 2; 26 if(!empty($res) && count($res) != 0){ 27 foreach ($res as $k => $v) { 28 $content = json_decode($v['content'],true); 29 $msg = json_decode($content,true); 30 $EXCEL->setActiveSheetIndex(0)->setCellValue('A' . $num, $msg['payload']['bodies'][0]['msg']); 31 $num++; 32 } 33 header("Pragma: public"); 34 header("Expires: 0"); 35 header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); 36 header("Content-Type:application/force-download"); 37 header("Content-Type:application/vnd.ms-execl"); 38 header("Content-Type:application/octet-stream"); 39 header("Content-Type:application/download");; 40 header('Content-Disposition:attachment;filename="聊天历史纪录_' . date('Ymd',time()) . '.xls"'); 41 header("Content-Transfer-Encoding:binary"); 42 import("Org.Util.PHPExcel.Writer.Excel5"); 43 $Writer = new \PHPExcel_Writer_Excel5($EXCEL); 44 $Writer->save('php://output'); 45 }else{ 46 echo '暂时没有查询到数据';exit; 47 } 48 } 49