dede織夢繫統後臺的文章或自定義模型中的資料庫內容到匯出excel檔案,解決亂碼。
阿新 • • 發佈:2018-11-19
dede織夢繫統後臺的文章或自定義模型中的資料庫內容到匯出excel檔案,解決亂碼。好品牌小編下面分享的開發過程。
1、在後臺目錄建立一個php檔案toexcel.php,在最上面加入程式碼:
require_once(dirname(__FILE__).'/config.php'); require_once(DEDEINC.'/typelink.class.php'); require_once(DEDEINC.'/datalistcp.class.php'); require_once(DEDEADMIN.'/inc/inc_list_functions.php');
2.加入匯出到excel類;
class Excel { private $head; private $body; public function addHeader($arr){ foreach($arr as $headVal){ $headVal = $this->charset($headVal); $this->head .= "{$headVal}\t "; } $this->head .= "\n"; } public function addBody($arr){ foreach($arr as $arrBody){ foreach($arrBody as $bodyVal){ $bodyVal = $this->charset($bodyVal); $this->body .= "{$bodyVal}\t "; } $this->body .= "\n"; } } public function downLoad($filename=''){ if(!$filename) $filename = date('YmdHis',time()).'.xls'; header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:attachment;filename=$filename"); header("Content-Type:charset=gb2312"); if($this->head) echo $this->head; echo $this->body; } public function charset($string){ return mb_convert_encoding($string,'GBK','auto'); } }
農業經小編做了程式碼解釋:
1.輸出列名陣列,並轉碼
public function addHeader($arr){ foreach($arr as $headVal){ $headVal = $this->charset($headVal); $this->head .= "{$headVal}\t "; } $this->head .= "\n"; }
2.輸出匯出內容陣列,並轉碼
public function addBody($arr){
foreach($arr as $arrBody){
foreach($arrBody as $bodyVal){
$bodyVal = $this->charset($bodyVal);
$this->body .= "{$bodyVal}\t ";
}
$this->body .= "\n";
}
}
3.設定header頭部資訊和匯出到excel內容,並輸出到瀏覽器
public function downLoad($filename=''){
if(!$filename)
$filename = date('YmdHis',time()).'.xls';
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=$filename");
header("Content-Type:charset=gb2312");
if($this->head)
echo $this->head;
echo $this->body;
}
4.轉碼,這裡不用iconv函式,有可能會與gd衝突導致輸出空白。用mb_convert_encoding
public function charset($string){
return mb_convert_encoding($string,'GBK','auto');
}
7.呼叫方法;
$excel = new Excel();
$excel->addHeader(array('列一','列二','列三','列四'));
global $dsql;
$sql="select 列一欄位,列二欄位,列三欄位,列四欄位 from 表名";
$dsql->SetQuery($sql);
$dsql->Execute();
while($row = $dsql->GetArray()){
$list[]=$row;
}
unset($row);
$excel->addBody($list);
$excel->downLoad();
後臺新增匯出到excel程式碼:
找到後臺目錄下的templets目錄,下面有個content_list.htm檔案,
找到:
<a href="javascript:;" onClick="cAtts('attsDel',event,this)" class="coolbg"> 刪除屬性 </a>
在後面加一段程式碼:
<?php if($channelid==1) echo " <a href=\"toexcel.php\" class=\"coolbg\" target=\"_blank\">匯出到excel</a>\r\n"; ?>
$channelid就是你的模型id,根據你匯出的表填寫。填寫完之後開啟後臺欄目列表就出現匯出按鈕。來源:谷康網