這篇文章主要介紹了PHP實現匯出excel資料的類庫用法,結合執行個體形式分析了php操作Excel資料的讀取與匯出操作相關實現技巧,需要的朋友可以參考下
今天一個項目要做一個PHP匯出資料用excel儲存,在網上找到一個本來是想用phpexcel的,後來發現太難了,就換了一個但匯出的歌聲是XML
類寫的很簡單,但很實用。只能簡單的匯出字串和數字二種格式。
如果你有興趣,你可以拿去擴充了,基本夠用。
class Excel_XML{//定於私人變數,頂部標籤private $header = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<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\">";//底部標籤private $footer = "</Workbook>";//定於行數組private $lines = array();//設定編碼private $sEncoding;//設定類型private $bConvertTypes;//設定sheet名稱private $sWorksheetTitle;//建構函式public function __construct( $sEncoding = 'UTF-8',$bConvertTypes = false,$sWorksheetTitle = 'Table1'){$this->bConvertTypes = $bConvertTypes;$this->setEncoding($sEncoding);$this->setWorksheetTitle($sWorksheetTitle);}//設定編碼,在建構函式裡面預設的事UTF-8格式public function setEncoding($sEncoding){$this->sEncoding = $sEncoding;}//設定excel的頭public function setWorksheetTitle ($title){$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);$title = substr ($title, 0, 31);$this->sWorksheetTitle = $title;}//增加行函數(關鍵函數)private function addRow ($array){$cells = ""; //設定每個單元為空白foreach ($array as $k => $v){ $type = 'String'; //預設類型是字串 if ($this->bConvertTypes === true && is_numeric($v)): //判斷類型 { $type = 'Number'; } $v = htmlentities($v, ENT_COMPAT, $this->sEncoding); $cells .= "<Cell><Data ss:Type=\"$type\">" . $v . "</Data></Cell>\n";} $this->lines[] = "<Row>\n" . $cells . "</Row>\n"; //寫入數組}//增加數組public function addArray ($array){foreach ($array as $k => $v) {$this->addRow ($v);}}//匯出xmlpublic function generateXML ($filename = 'excel-export'){$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");echo stripslashes (sprintf($this->header, $this->sEncoding));echo "\n<Worksheet ss:Name=\"" . $this->sWorksheetTitle . "\">\n<Table>\n";foreach ($this->lines as $line)echo $line;echo "</Table>\n</Worksheet>\n";echo $this->footer;}}
原理很簡單,就是把資料數組,讀出來,再用XML的標籤封上,在用php內建的header()函數告訴遊覽器,就可以了。
調用:
public function import(){ $data = array( 1 => array ('學校名稱',"隊伍名稱") ); foreach($this->team as $key=>$value) { array_push($data,array($key, $value)); } $xls = new Excel_XML('UTF-8', false, 'My Test Sheet'); //執行個體化函數 $xls->addArray($data); $xls->generateXML('school'); //匯出並設定名稱}
上面是的寫一個匯出方式。在遊覽器運行就已經匯出數組$this->team 裡面的鍵和值了。
總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。