本文章收藏了三款php生成excel文件代码程序,第一款为比较全面的生成函数,后面二款很简单,但是不如第一款好,好了现在来看看生成excel的代码如下:
- class excel{
- var $header = "<?xml version="1.0" encoding="utf-8"?>
- <workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
- xmlns:x="urn:schemas-microsoft-com:office:excel"
- xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
- xmlns:html="http://www.w3.org/tr/rec-html40">";
- var $footer = "</workbook>";
- var $lines = array ();
- var $worksheet_title = "table1";
-
- function addrow ($array) {
-
-
- $cells = "";
-
-
- foreach ($array as $k => $v):
-
-
- if(is_numeric($v)) {
-
- if(substr($v, 0, 1) == 0) {
- $cells .= "<cell><data ss:type="string">" . $v . "</data></cell> ";
- } else {
- $cells .= "<cell><data ss:type="number">" . $v . "</data></cell> ";
- }
- } else {
- $cells .= "<cell><data ss:type="string">" . $v . "</data></cell> ";
- }
-
- endforeach;
-
-
- $this->lines[] = "<row> " . $cells . "</row> ";
-
- }
-
- function addarray ($array) {
-
-
- foreach ($array as $k => $v):
- $this->addrow ($v);
- endforeach;
-
- }
-
- function setworksheettitle ($title) {
-
-
- $title = preg_replace ("/[\|:|/|?|*|[|]]/", "", $title);
-
-
- $title = substr ($title, 0, 31);
-
-
- $this->worksheet_title = $title;
-
- }
-
- function generatexml ($filename) {
-
-
- header("content-type: application/vnd.ms-excel; charset=utf-8");
- header("content-disposition: inline; filename="" . $filename . ".xls"");
-
- echo stripslashes ($this->header);
- echo " <worksheet ss:name="" . $this->worksheet_title . ""> <table> ";
- echo "<column ss:index="1" ss:autofitwidth="0" ss:width="110"/> ";
- echo implode (" ", $this->lines);
- echo "</table> </worksheet> ";
- echo $this->footer;
-
- }
-
- }
-
-
-
-
-
-
-
-
-
-
-
方法二:
其实在做真正的应用的时候,大家可以将数据从数据库中取出,然后按照每一列数据结束后加t,每一行数据结束后加n的方法echo出来,在php的开头用header("content-type:application/vnd.ms-excel");表示输出的是excel文件,用header("content-disposition:filename=test.xls");表示输出的文件名为text.xls,这样就ok了.代码如下:
- <?php
- header("content-type:application/vnd.ms-excel");
- header("content-disposition:filename=test.xls");
- echo "test1";
- echo "test2";
- echo "test1";
- echo "test2";
- echo "test1";
- echo "test2";
- echo "test1";
- echo "test2";
- echo "test1";
- echo "test2";
- echo "test1";
- echo "test2";
- ?>
方法三,代码如下:
- <?php
- header("content-type: application/octet-stream");
- header("accept-ranges: bytes");
- header("content-type:application/vnd.ms-excel");
- header("content-disposition:attachment;filename=export_excel_gshjsl.xls");
-
- $tx='表头';
- echo $tx." ";
- echo "编号"." ";
- echo "姓名"." ";
- echo " ";
- echo "="411481198507150666""." ";
- echo "="0123456""." ";
-
- echo " ";
- ?>
|