TP5.1使用PHPExcel扩展库导出表格文件

composer地址

composer require phpoffice/phpspreadsheet

tp5.1没有tp5.0的vendor助手函数

comosper后直接new根目录类文件即可

$objPHPExcel = new \PHPExcel();

下面是完整代码根据自己业务逻辑改善即可

    //excel导出方法
    public function Out_excel()
    {
        $objPHPExcel = new \PHPExcel();
        $objSheet = $objPHPExcel->getActiveSheet(); // 获取当前活动sheet
        $objSheet->setTitle('戴先生导出测试'); // 给当前的活动sheet起个名称
          // 设置表格列标
        $list = ['A', 'B', 'C','D','E','F','G'];
        // 填充第一行数据【字段名】
        $objSheet->setCellValue($list['0'].'1','ID')
                 ->setCellValue($list['1'].'1','IP地址')
                 ->setCellValue($list['2'].'1', '真实地址')
                 ->setCellValue($list['3'].'1', '用户浏览器')
                 ->setCellValue($list['4'].'1', '用户设备')
                 ->setCellValue($list['5'].'1', '来访时间')
                 ->setCellValue($list['6'].'1', '来访目录');
        //渲染数据
        $data = self::getData();

        foreach($data as $k => $v){  
             $num=$k+2;  
             $objSheet
                    ->setCellValue('A'.$num, $v['id'])     
                    ->setCellValue('B'.$num, $v['ip'])  
                    ->setCellValue('C'.$num, $v['address'])
                    ->setCellValue('D'.$num, $v['llq'])
                    ->setCellValue('E'.$num, $v['phoneorweb'])
                    ->setCellValue('F'.$num, $v['formtime'])
                    ->setCellValue('G'.$num, $v['form_blog']);
            } 

        // 设置加粗
        foreach ($list as $col) {
            // 设置第一行加粗
            $objSheet->getStyle($col . '1')->getFont()->setBold(true);
        }

        $savename='戴先生Test';
        $ua = $_SERVER["HTTP_USER_AGENT"];
        $datetime = date('Y-m-d', time());        
        if (preg_match("/MSIE/", $ua)) {
            $savename = urlencode($savename); //处理IE导出名称乱码
        } 
        // excel头参数  
        header('Content-Type: application/vnd.ms-excel');  
        header('Content-Disposition: attachment;filename="'.$savename.'.xlsx"');  //日期为文件名后缀  
        header('Cache-Control: max-age=0'); 
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式,excel2007为xlsx格式  
        $objWriter->save('php://output');

    }

字段对应数据库字段即可!

为您推荐

评论已关闭