1. 程式人生 > >Thinkphp5匯出Excel功能

Thinkphp5匯出Excel功能

Thinkphp5匯出Excel功能

  1. 網上下載PHPExcel包,http://www.php.cn/xiazai/leiku/1491 下載後只需要Classes目錄下的檔案即可
  2. 放在Thinkphp/vendor/下面,前端直接跳轉到該控制器
  3. 前臺直接跳到該控制器方法下
<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
class Excel extends Controller
{
   public function
index() { $time = time(); $xlsData = Db::table('oa_attendance')->where("morning", "=", "1")->where("afternoon", "=", "1") ->alias('a') ->join('oa_user u', 'a.uid = u.uid') ->join('oa_com c', 'u.factory = c.cid') ->select
(); //這裡引入PHPExcel檔案注意路徑修改 vendor("PHPExcel"); vendor("PHPExcel.Writer.Excel5"); vendor("PHPExcel.Writer.Excel2007"); vendor("PHPExcel.IOFactory"); $objExcel = new \PHPExcel(); $objWriter = \PHPExcel_IOFactory:
:createWriter($objExcel, 'Excel2007'); $objActSheet = $objExcel->getActiveSheet(); $key = ord("A"); $letter =explode(',',"A,B,C,D,E,F,G"); $arrHeader = array('ID','姓名','工作單位','電話','職位','上班打卡時間','下班打卡時間'); $lenth = count($arrHeader); for($i = 0;$i < $lenth;$i++) { $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]"); }; foreach($xlsData as $k=>$v){ $k +=2; $objActSheet->setCellValue('A'.$k, $v['id']); $objActSheet->setCellValue('B'.$k, $v['name']); $objActSheet->setCellValue('C'.$k, $v['com_name']); $objActSheet->setCellValue('D'.$k, $v['phone']); $objActSheet->setCellValue('E'.$k, $v['job']); $objActSheet->setCellValue('F'.$k, date("m-d H:i",$v['morningtime'])); $objActSheet->setCellValue('G'.$k, date("m-d H:i",$v['afternoontime'])); $objActSheet->getRowDimension($k)->setRowHeight(20); } $width = array(20,20,15,10,10,30,10,15); //設定表格的寬度 $objActSheet->getColumnDimension('A')->setWidth($width[3]); $objActSheet->getColumnDimension('B')->setWidth($width[1]); $objActSheet->getColumnDimension('C')->setWidth($width[0]); $objActSheet->getColumnDimension('D')->setWidth($width[5]); $objActSheet->getColumnDimension('E')->setWidth($width[5]); $objActSheet->getColumnDimension('F')->setWidth($width[5]); $objActSheet->getColumnDimension('G')->setWidth($width[5]); $outfile = "員工考勤表.xls"; ob_end_clean(); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition:inline;filename="'.$outfile.'"'); header("Content-Transfer-Encoding: binary"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); $objWriter->save('php://output'); //這裡直接匯出檔案 } }
  1. 這裡是目錄結構
    這是下載出來的,只需要Classes檔案下的
    在這裡插入圖片描述在這裡插入圖片描述