ThinkPHP5.1使用phpexcel第三方类库生成excel文件(导出功能)

PHP版本要求为5.6,不支持PHP7+,
遇到的错误,是因为php版本太高,PHP7+的不支持,只好换到5.6的版本
传递数据的类型必须为数组,在传递数据前先判断数据是否为数组类型gettype();
方法二与方法三的算法可以学习学习;
在这里插入图片描述
在https://packagist.org/搜索 phpoffice

1.进行composer安装

如果composer之前设置了国内镜像需要解除镜象:
如果需要解除镜像并恢复到 packagist 官方源,请执行以下命令:

composer config -g --unset repos.packagist

2.查看使用方法
在这里插入图片描述安装phpexcel类库
在这里插入图片描述

方法一:Excel文件简单写入,没有使用数组数据

控制器index使用扩展exetend,主要留意如何使用extend扩展目录里定义的类

<?php
namespace app\index\controller;
use think\Controller;
use Excel\Excel;

class Index extends Controller
{
    public function test()
    {
        Excel::export('','title'.date('y-m-d',time()));
    }
}

extend扩展目录Excel.php代码
在这里插入图片描述

<?php
namespace Excel;
//在Excel命名空间下引入了PHPExcel和PHPExcel_IOFactory,下次直接use Excel就可引入他俩
use PHPExcel;
use PHPExcel_IOFactory;

class Excel
{

    /**
     * 数组转xls格式的excel文件
     * @param  array  $data      需要生成excel文件的数组
     * @param  string $filename  生成的excel文件名
     *      示例数据:
    $data = array(
    array(NULL, 2010, 2011, 2012),
    array('Q1',   12,   15,   21),
    array('Q2',   56,   73,   86),
    array('Q3',   52,   61,   69),
    array('Q4',   30,   32,    0),
    );
     */
    public static function export($data='',$title='test'){
        ini_set('max_execution_time', '0');//最长执行时间,php默认为30秒,这里设置为0秒的意思是保持等待知道程序执行完成

        $phpexcel = new PHPExcel();

        // Set properties 设置文件属性
        $properties = $phpexcel->getProperties();
        $properties->setCreator("Boge");//作者是谁 可以不设置
        $properties->setLastModifiedBy("Boge");//最后一次修改的作者
        $properties->setTitle($title);//设置标题
        $properties->setSubject('测试');//设置主题
        $properties->setDescription("备注");//设置备注
        $properties->setKeywords("关键词");//设置关键词
        $properties->setCategory("类别");//设置类别

        // 获取操作单元格对象
        $sheet = $phpexcel->getActiveSheet();
        $sheet->setTitle('Sheet1');//设置sheet名称


        /**---------- 简单写入 ----------**/
        $sheet ->setCellValue("A1","问卷标题");	//可以指定单元格位置
        $sheet ->setCellValue("A2","今天你吃了吗?");	//可以指定单元格位置


        //请求头与curl相似  数据以文件流传递
        $phpexcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=".$title.".xls");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $objwriter->save('php://output');//导出文件
        exit;
    }
    }

方法二:Excel文件写入,使用数组数据批量写入

控制器index使用扩展exetend,主要留意如何使用extend扩展目录里定义的类

<?php
namespace app\index\controller;
use think\Controller;
use Excel\Excel;

class Index extends Controller
{
    public function test()
    {
        $data = array(
            array('ID','姓名','班级','年龄'),
            array('Q1',   12,   15,   21),
            array('Q2',   56,   73,   86),
            array('Q3',   52,   61,   69),
            array('Q4',   30,   32,    0),
        );
        Excel::export($data,'title'.date('Y-m-d',time()));
    }
}

extend扩展目录Excel.php代码
在这里插入图片描述

<?php
namespace Excel;
//在Excel命名空间下引入了PHPExcel和PHPExcel_IOFactory,下次直接use Excel就可引入他俩
use PHPExcel;
use PHPExcel_IOFactory;

class Excel
{

    /**
     * 数组转xls格式的excel文件
     * @param  array  $data      需要生成excel文件的数组
     * @param  string $filename  生成的excel文件名
     *      示例数据:
    $data = array(
    array(NULL, 2010, 2011, 2012),
    array('Q1',   12,   15,   21),
    array('Q2',   56,   73,   86),
    array('Q3',   52,   61,   69),
    array('Q4',   30,   32,    0),
    );
     */
    public static function export($data='',$title='test'){
        ini_set('max_execution_time', '0');//最长执行时间,php默认为30秒,这里设置为0秒的意思是保持等待直到程序执行完成

        $phpexcel = new PHPExcel();

        // Set properties 设置文件属性
        $properties = $phpexcel->getProperties();
        $properties->setCreator("Boge");//作者是谁 可以不设置
        $properties->setLastModifiedBy("Boge");//最后一次修改的作者
        $properties->setTitle($title);//设置标题
        $properties->setSubject('测试');//设置主题
        $properties->setDescription("备注");//设置备注
        $properties->setKeywords("关键词");//设置关键词
        $properties->setCategory("类别");//设置类别

        // 获取操作单元格对象
        $sheet = $phpexcel->getActiveSheet();
        //数组数据传递用到
        $sheet->fromArray($data);
        $sheet->setTitle('Sheet1');//设置sheet名称


        //请求头与curl相似  数据以文件流传递
        $phpexcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=".$title.".xls");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $objwriter->save('php://output');//导出文件
        exit;
    }

方法三(推荐使用):Excel文件写入,使用数组数据批量写入

控制器index使用扩展exetend,主要留意如何使用extend扩展目录里定义的类

<?php
namespace app\index\controller;
use think\Controller;
use Excel\Excel;
use think\Db;

class Index extends Controller
{
    public function test()
    {
    	//方法一:
        //Excel::export();

        //方法二:
      /*  $userLiset =  Db::table('user')->select();
        Excel::export($userLiset,'title'.date('y-m-d',time()));*/
        
        //方法三:
        $data = array(			// 按照该结构封装即可
            'cols' => array('姓名','班级','年龄'),
            'rows' =>array(
                array('小明','三年一班','10岁'),
                array('小波','三年二班','30岁'),
                array('小薛','三年三班','11岁'),
            ),
        );
        Excel::exportexcel($data,'test002'.date('Y-m-d',time()));
    }
}

extend扩展目录Excel.php代码

<?php
namespace Excel;
//在Excel命名空间下引入了PHPExcel和PHPExcel_IOFactory,下次直接use Excel就可引入他俩
use PHPExcel;
use PHPExcel_IOFactory;

class Excel
{

    /**
     * 数组转xls格式的excel文件
     * @param  array  $data      需要生成excel文件的数组
     * @param  string $filename  生成的excel文件名
     *      示例数据:
    $data = array(
    array(NULL, 2010, 2011, 2012),
    array('Q1',   12,   15,   21),
    array('Q2',   56,   73,   86),
    array('Q3',   52,   61,   69),
    array('Q4',   30,   32,    0),
    );
     */
    public static function export($data='',$title='test'){
        ini_set('max_execution_time', '0');//最长执行时间,php默认为30秒,这里设置为0秒的意思是保持等待直到程序执行完成

        $phpexcel = new PHPExcel();

        // Set properties 设置文件属性
        $properties = $phpexcel->getProperties();
        $properties->setCreator("Boge");//作者是谁 可以不设置
        $properties->setLastModifiedBy("Boge");//最后一次修改的作者
        $properties->setTitle($title);//设置标题
        $properties->setSubject('测试');//设置主题
        $properties->setDescription("备注");//设置备注
        $properties->setKeywords("关键词");//设置关键词
        $properties->setCategory("类别");//设置类别

        // 获取操作单元格对象
        $sheet = $phpexcel->getActiveSheet();
        //数组数据传递用到
        $sheet->fromArray($data);
        $sheet->setTitle('Sheet1');//设置sheet名称


        /**---------- 简单写入 ----------**/
 /*       $sheet ->setCellValue("A1","问卷标题");	//可以指定单元格位置
        $sheet ->setCellValue("A2","今天你吃了吗?");	//可以指定单元格位置*/


//        /**---------- 遍历写入数据 --------------**/
        // 准备数据
/*        $data = array(			// 按照该结构封装即可
            'cols' => array('姓名','班级','年龄'),
            'rows' =>array(
                array('小明','三年一班','10岁'),
                array('小波','三年二班','30岁'),
                array('小薛','三年三班','11岁'),
            ),
        );

        // 提前定义好 列号映射数组
        $colArray = array('A','B','C'); // 如果列数大于 Z ,使用 AA-AZ  BA-BZ ... ZA-ZZ ;

        // 遍历表头
        foreach ($data['cols'] as $key => $col) {
            $sheet ->setCellValue($colArray[$key].'1' , $col);
        }

        // 遍历数据
        foreach ($data['rows'] as $key => $row) {
            $rowNum = $key+2; // 数据从第二行开始写,第一行是表头
            foreach ($row as $key => $value) {
                $sheet ->setCellValue($colArray[$key].$rowNum , $value);
            }
        }*/


        //请求头与curl相似  数据以文件流传递
        $phpexcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=".$title.".xls");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $objwriter->save('php://output');//导出文件
        exit;
    }
    /**
     * 数组转xls格式的excel文件
     * @param  array  $data      需要生成excel文件的数组
     * @param  string $filename  生成的excel文件名
     *      示例数据:
    $data = array(			// 按照该结构封装即可
    'cols' => array('姓名','班级','年龄'),
    'rows' =>array(
    array('小明','三年一班','10岁'),
    array('小波','三年二班','30岁'),
    array('小薛','三年三班','11岁'),
    ),
    );
     */
    //这个封装的方法值得学习一下,可以参看上边的export()方法看看规律
    public static function exportexcel($data,$title){
        ini_set('max_execution_time', '0');//最长执行时间,php默认为30秒,这里设置为0秒的意思是保持等待直到程序执行完成

        $phpexcel = new PHPExcel();

        // Set properties 设置文件属性
        $properties = $phpexcel->getProperties();
        $properties->setCreator("Boge");//作者是谁 可以不设置
        $properties->setLastModifiedBy("Boge");//最后一次修改的作者
        $properties->setTitle($title);//设置标题
        $properties->setSubject('测试');//设置主题
        $properties->setDescription("备注");//设置备注
        $properties->setKeywords("关键词");//设置关键词
        $properties->setCategory("类别");//设置类别

        $sheet = $phpexcel->getActiveSheet();
        $sheet->setTitle('Sheet1');//设置sheet名称

        //从A开始
        $startLetter = 'A';
        $rowNumber = 1;

        // 遍历表头
        foreach ($data['cols'] as $key => $col) {
            $sheet ->setCellValue($startLetter++.$rowNumber , $col);
        }
        ++$rowNumber;
        // 遍历数据
        foreach ($data['rows'] as $key => $row) {
            $startLetter = 'A';
            foreach ($row as $key => $value) {
                $sheet ->setCellValue($startLetter++.$rowNumber , $value);
            }
            ++ $rowNumber;
        }

        $phpexcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=".$title.".xls");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $objwriter->save('php://output');
        exit;
    }

}
推展知识 vendor与extend目录说明

1、thinkPHP5.0 vendor

vendor的是通过composer的方法进行自动引入到第三方扩展库vendor目录里的,调用方法是利用的vendor方法:

$re = vendor ( ‘PHPExcel’ );

$mail = new \PHPExcel ();

2、thinkPHP5.0 extend

extend是通过手动的方法直接把第三方扩展库或者自己写的封装库直接引入到extend目录里,调用方法的实例:

    use think\Loader;

    Loader::import("PHPExcel",EXTEND_PATH);

    $objPHPExcel=new \PHPExcel();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值