本文實例講述了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);}
}
//導出xml
public 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 裡面的鍵和值了。
更多關於PHP相關內容感興趣的讀者可查看本站專題:《php操作office文檔技巧總結(包括word,excel,access,ppt)》、《PHP數組(Array)操作技巧大全》、《php排序算法總結》、《PHP常用遍歷算法與技巧總結》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》、《php正則表達式用法總結》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。