1. 程式人生 > >PHP 導出Excel表格

PHP 導出Excel表格

select vendor mar pan tty sig TP 修改 pla

在實際開發中,有很多場景是需要導出Excel表格的,比如後臺的統計數據,客戶希望能導出為表格的形式,今天介紹一下TP5框架內實現Excel表格的導出功能,首先下載技術分享圖片phpexcel.zip,解壓後放到vendor第三方類庫目錄下,直接用函數vendor()引入就可以啦,直接貼代碼:

    public function pushExcelAll(Request $request)
    {
        vendor(‘phpexcel.PHPExcel‘); //引入核心庫文件 
	    vendor(‘phpexcel.PHPExcel.Writer.Excel2007‘); //引入excel2007操作類  
	    vendor(‘phpexcel.PHPExcel.IOFactory‘); 
	        
        $param = $request->param();
        $id = $param[‘id‘]; //要導出的數據id
        $name = isset($param[‘name‘]) ? $param[‘name‘] : ‘ExampleMemb‘; //要導出的Excel表名
        
        $data = MeetingMembs::query("select platform,ticketType,avatar,realName,phone,company,job,email,ticketRemark,seatCode,id from h_meetingmembs where id = $id"); //從數據庫中查到數據

        error_reporting(E_ALL);
        $objPHPExcel = new \PHPExcel();
        $letter = array(‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘);
        //表頭數組
        $tableheader = array(‘購票平臺‘, ‘票類‘, ‘頭像‘, ‘姓名‘, ‘手機號碼‘, ‘單位名稱‘, ‘職位‘, ‘郵箱‘, ‘備註‘, ‘坐席‘, ‘報名號‘);
        
        //填充表頭信息
        for ($i = 0; $i < count($tableheader); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        
        /*以下就是對處理Excel裏的數據,橫著取數據,主要是這一步,其他基本都不要改*/
        foreach ($data as $k => $v) {
            $num = $k + 1 + 1;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列,uid是你查出數組的鍵值,下面以此類推
                ->setCellValue(‘A‘ . $num, $v[‘platform‘])//platform
                ->setCellValue(‘B‘ . $num, $v[‘ticketType‘])//ticketType
                ->setCellValue(‘C‘ . $num, $v[‘avatar‘])//avatar
                ->setCellValue(‘D‘ . $num, $v[‘realName‘])//realName
                ->setCellValue(‘E‘ . $num, $v[‘phone‘])//phone
                ->setCellValue(‘F‘ . $num, $v[‘company‘])//company
                ->setCellValue(‘G‘ . $num, $v[‘job‘])//job
                ->setCellValue(‘H‘ . $num, $v[‘email‘])//email
                ->setCellValue(‘I‘ . $num, $v[‘ticketRemark‘])//ticketRemark
                ->setCellValue(‘J‘ . $num, $v[‘seatCode‘])//seatCode
                ->setCellValue(‘K‘ . $num, $v[‘id‘]);//id
        }
        
        $objPHPExcel->getActiveSheet()->setTitle(‘signMemb‘);
        $objPHPExcel->setActiveSheetIndex(0);
        header(‘Content-Type: application/vnd.ms-excel;charset=UTF-8"‘);
        header(‘Content-Disposition: attachment;filename="‘ . $name . ‘.xls"‘);
        header(‘Cache-Control: max-age=0‘);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘);
        $objWriter->save(‘php://output‘);
        exit;
    }

相對應的修改幾個值,$id,$name,$data,$letter,$tableheader和foreach循環中的$v的屬性名,不出意外的話到此你就已經搞定了導出功能。

PHP 導出Excel表格