php匯出資料excel

科技小能手發表於2017-11-12
           public function villageinfo(){
              set_time_limit(`0`);
              $villageDb=D("Village");
              $houseDb=D("House");
              $areaDb=D("FangArea");
              $field="villageName,villageId,fangAreaId";
              $data=$villageDb->field($field)->select();
              foreach($data as $key=>$val){
                  $a=$areaDb->getAreaName($val[`fangAreaId`]);
                  $data[$key][`areaname`]=$a[`fangAreaName`];
                  $b=$houseDb->getHouseNum($val[`villageId`],340100);
                  $data[$key][`count`]=$b;

              }
              $this->getExcel(``,``,$data);
          }

private  function getExcel($fileName,$headArr,$data){
   //匯入PHPExcel類庫,因為PHPExcel沒有用名稱空間,只能inport匯入
   require_once THINK_PATH.`Library/Org/Util/PHPexcel/PHPExcel.php`;
   import("Library.Org.Util.PHPExcel");
   import("Library.Org.Util.PHPExcel.Writer.Excel5");
   import("Library.Org.Util.PHPExcel.IOFactory.php");

   $date = date("Y_m_d",time());
   $fileName .= "_{$date}.xls";

   //建立PHPExcel物件,注意,不能少了
   $objPHPExcel = new PHPExcel();
   $objProps = $objPHPExcel->getProperties();

   //設定表頭
   $key = ord("A");
   //print_r($headArr);exit;
   foreach($headArr as $v){
       $colum = chr($key);
       $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.`1`, $v);
       $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.`1`, $v);
       $key += 1;
   }

   $column = 2;
   $objActSheet = $objPHPExcel->getActiveSheet();

   //print_r($data);exit;
   foreach($data as $key => $rows){ //行寫入
       $span = ord("A");
       foreach($rows as $keyName=>$value){// 列寫入
           $j = chr($span);
           $objActSheet->setCellValue($j.$column, $value);
           $span++;
       }
       $column++;
   }

   $fileName = iconv("utf-8", "gb2312", $fileName);

   //重新命名錶
   //$objPHPExcel->getActiveSheet()->setTitle(`test`);
   //設定活動單指數到第一個表,所以Excel開啟這是第一個表
   $objPHPExcel->setActiveSheetIndex(0);
   ob_end_clean();//清除緩衝區,避免亂碼
   header(`Content-Type: application/vnd.ms-excel`);
   header("Content-Disposition: attachment;filename="$fileName"");
   header(`Cache-Control: max-age=0`);

   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, `Excel5`);
   $objWriter->save(`php://output`); //檔案通過瀏覽器下載
   exit;
}



本文轉自 liang3391 51CTO部落格,原文連結:http://blog.51cto.com/liang3391/1877446


相關文章