1、简介

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

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

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

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

2、代码

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

ExportExcel.class.php文件

<?phpclass 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"xmlns:x="urn:schemas-microsoft-com:office:excel"xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=utf-8"></head><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>";   }   $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 );  }}?>
<?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文件

成功后查看该文件:

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

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

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

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

以上这篇PHP将数据导出Excel表中的实例(投机型)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持网页设计。