懂ni 发表于 2017-12-30 10:35:35

PHP将数据导出Excel表中(投机型)

1 <?php  

2>
3   /**  

4   * @desc   将数据导出到Excel中  

5   * @param$data array 设置表格数据  

6   * @param$titlename string 设置head  

7   * @param$title string 设置表头  

8   * @param$filename 设置默认文件名  

9   * @return 将字符串输出,即输出字节流,下载Excel文件  

10   */  
11   public function excelData($data,$titlename,$title,$filename){
  
12         #xmlns即是xml的命名空间
  
13         $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; \">\r\n</head>\r\n<body>";
  
14         #以下构建一个html类型格式的表格
  
15         $str .= $title;
  
16         $str .="<table border=1><head>".$titlename."</head>";
  
17         foreach ($dataas $key=> $rt )
  
18         {
  
19             $str .= "<tr>";
  
20             foreach ( $rt as $k => $v )
  
21             {
  
22               $str .= "<td>{$v}</td>";
  
23             }
  
24             $str .= "</tr>\n";
  
25         }
  
26         $str .= "</table></body></html>";
  
27         header( "Content-Type: application/vnd.ms-excel; name='excel'" );   #类型
  
28         header( "Content-type: application/octet-stream" );   #告诉浏览器响应的对象的类型(字节流、浏览器默认使用下载方式处理)
  
29         header( "Content-Disposition: attachment; filename=".$filename );   #不打开此文件,刺激浏览器弹出下载窗口、下载文件默认命名
  
30         header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
  
31         header( "Pragma: no-cache" );   #保证不被缓存或者说保证获取的是最新的数据
  
32         header( "Expires: 0" );
  
33         exit( $str );
  
34   }
  
35
  
36
  
37 }
  
38
  
39
  
40 ?>
页: [1]
查看完整版本: PHP将数据导出Excel表中(投机型)