php 匯出excel

(二少)在南極發表於2014-09-18

<?php
class Excel {
var $inEncode;
var $outEncode;
public function _construct() {
}
public function setEncode($incode, $outcode) {
$this->inEncode = $incode;
$this->outEncode = $outcode;
}
public function setTitle($titlearr) {
$title = "";
foreach ( $titlearr as $v ) {
if ($this->inEncode == $this->outEncode) {
$title .= iconv ( $this->inEncode, $this->outEncode, $v ) . "\t";
} else {
$title .= $v . "\t";
}
}
$title .= "\n";
return $title;
}
public function setRow($array) {
$content = "";
foreach ( $array as $k => $v ) {
foreach ( $v as $vs ) {
if ($this->inEncode != $this->outEncode) {
$content .= iconv ( $this->inEncode, $this->outEncode, $vs ) . "\t";
} else {
$content .= $vs . ".\t";
}
}
$content .= "\n";
}
return $content;
}
public function getExcel($titlearr, $array, $filename = '') {
if ($filename == '') {
$filename = date ( 'Y-m-d' );
}
$title = $this->setTitle ( $titlearr );
$content = $this->setRow ( $array );
$filename=iconv("UTF-8","GB2312",$filename);
header ( "Content-type:application/vnd.ms-exce8 charset=UTF-8" );
header ( "Content-Disposition:attachment; filename=" . $filename . ".xls" );
echo $title;
echo $content;
}
}

$excel = new Excel ();
// 設定編碼:
$excel->setEncode ( "utf-8", "gb2312" ); // 如果不轉碼,引數寫一樣即可,例如$excel->setEncode("utf-8","utf-8");
// 設定標題欄
$titlearr = array (
"a",
"b",
"c",
"d"
);
// 設定內容欄
$contentarr = array (
1 => array (
"中國",
"ac",
"ad",
"ae"
),
2 => array (
"abc",
"acc",
"adc",
"aec"
),
3 => array (
"abd",
"acd",
"add",
"aed"
),
4 => array (
"abe",
"ace",
"ade",
"aee"
)
);
$excel->getExcel ( $titlearr, $contentarr, "匯出excel" );

?>

 

相關文章