服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - PHP将数据导出Excel表中的实例(投机型)

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

2021-06-09 16:42php中文网 PHP教程

下面小编就为大家带来一篇PHP将数据导出Excel表中的实例(投机型)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

1、简介

如何利用最简单粗糙暴力的方法将数据写入excel文件中呢?

因为ms word和excel的文档都支持html文本格式,因此我们可以基于这个原理采用html文本格式进行数据的输出。

在html中,我们只需要将数据照着所想要的顺序放进相应的html表格中即可。

我们采用php进行数据获取整理以及构造相应的html文本,最后通过字节流输出下载到用户本地。

2、代码

直接上代码,这是一个很简单的程序,里面都带有注释了。

exportexcel.class.php文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
class exportexcel{
 /**
 * @desc 将数据导出到excel中
 * @param $data array 设置表格数据
 * @param $titlename string 设置head
 * @param $title string 设置表头
 * @param $filename 设置默认文件名
 * @return 将字符串输出,即输出字节流,下载excel文件
 */
 public function exceldata($data,$titlename,$title,$filename){
  #xmlns即是xml的命名空间
  $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; charset=utf-8\">\r\n</head>\r\n<body>";
  #以下构建一个html类型格式的表格
  $str .= $title;
  $str .="<table border=1><head>".$titlename."</head>";
  foreach ($data as $key=> $rt )
  {
   $str .= "<tr>";
   foreach ( $rt as $k => $v )
   {
    $str .= "<td>{$v}</td>";
   }
   $str .= "</tr>\n";
  }
  $str .= "</table></body></html>";
  header( "content-type: application/vnd.ms-excel; name='excel'" ); #类型
  header( "content-type: application/octet-stream" );  #告诉浏览器响应的对象的类型(字节流、浏览器默认使用下载方式处理)
  header( "content-disposition: attachment; filename=".$filename ); #不打开此文件,刺激浏览器弹出下载窗口、下载文件默认命名
  header( "cache-control: must-revalidate, post-check=0, pre-check=0" );
  header( "pragma: no-cache" ); #保证不被缓存或者说保证获取的是最新的数据
  header( "expires: 0" );
  exit( $str );
 }
 
 
}
?>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$obj=new exportexcel();
 
$data = array(
 array('a11','a22','a33'),
 array('b11','b22','b33'),
 array('c11','c22','c33'),
 array('d11','d22','d33'),
 array('e11','e22','e33'),
 array('f11','f22','f33'),
 ); 
$excelhead = "这个是excel表格标题";
$title = "我的excel表"; #文件命名
$headtitle= "<tr><th colspan='3' >{$excelhead}</th></tr>";
$titlename = "<tr>
    <th style='width:70px;'>表格1</th>
    <th style='width:70px;'>表格2</th>
    <th style='width:70px;'>表格3</th>
   </tr>";
$filename = $title.".xls";
$obj->exceldata($data,$titlename,$headtitle,$filename);
?>

3、测试

点击访问:

下载该excel文件

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

成功后查看该文件:

进入后excel提示说该文件格式与后缀名不一致,这也间接说明了我们所导出来的excel文件仅仅只是个外表是excel(实质是html文件),格式上并不是excel文件。

点击是进入查看里面的内容,上看去挺像excel的嘛,哈哈。就酱紫

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

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

更改后缀名为html进入查看:

你瞧,实质就是html文件嘛,只是excel支持该格式而已。

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

以上这篇php将数据导出excel表中的实例(投机型)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐