php 導出excel類

清華大佬耗費三個月吐血整理的幾百G的資源,免費分享!....>>>

/**

* excel導出類

*

* 使用方法

$excel=new Excel();

* //設置編碼:

*$excel->setEncode("utf-8","gb2312"); //如果不轉碼,參數寫一樣即可,例如$excel->setEncode("utf-8","utf-8");

* //設置標題欄

* $titlearr=array("a","b","c","d");

* //設置內容欄

* $contentarr=array(

* 1=>array("ab","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,"abc");

*/

class Excel {

 var $inEncode; //一般是頁面編碼


 var $outEncode; //一般是Excel文件的編碼


 public function __construct(){


 }

 /**

 *設置編碼

 */

 public function setEncode($incode,$outcode){

  $this->inEncode=$incode;


  $this->outEncode=$outcode;

 }

 /**

 *設置Excel的標題欄

 */

 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;

 }

 /**

 *設置Excel內容

 */

 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;

 }

 /**

 *生成并自動下載Excel

 * $titlearr 標題欄數組

 * $array 內容數組

 * $filename 文件名稱 (為空,已當前日期為名稱)

 */

 public function getExcel($titlearr,$array,$filename=''){

  if($filename==''){

   $filename=date("Y-m-d");

  }

  $title=$this->setTitle($titlearr);

  $content=$this->setRow($array);

  header("Content-type:application/vnd.ms-excel");

  header("Content-Disposition:filename=".$filename.".xls");

  echo $title;

  echo $content;

 }

}