PHP Yii2框架 Excel导出功能

5 篇文章 0 订阅

PHP Yii2框架 Excel导出功能

第一步 框架中安装插件
composer require phpoffice/phpexcel "*" -v
第二步 直接使用

下面是已经封装

/**
     *  @DESC 数据导入
     *  @example
     *  $data = [[1, "小明", "20"],[2, "小王", "21"]];
     *  $header = ["id", "姓名", "年龄"];
     *  Myhelpers::exportEXCEL($data, $header);
     *  @return void, Browser direct output
     */
    static function exportEXCEL($data, $header, $title = "simple", $filename = "data"){
        if (!is_array($data) || !is_array($header)) return false;
        $objPHPExcel = new \PHPExcel();
        // Set properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
        $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
        $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
        
        //设置表头,也就是第一行数据
        foreach ($header as $k => $v){
            $column = \PHPExcel_Cell::stringFromColumnIndex($k);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($column."1", $v);
        }
        
        //设置行数据,从第二行开始
        foreach ($data as $key=>$item){
            foreach ($item as $key2=>$val){
                $column = \PHPExcel_Cell::stringFromColumnIndex($key2);  //获得列位置
                // 添加一行数据,A1、B1、C1.....N1的各个数据
                //设置为$key+2,因为key是从0开始,而我们的行数据第一个索引是“1”,而上面因为设置了表头,占了一行数据,所以就直接+2
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($column.($key+2), $val);
            }
        }
        
        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle($title);
        
        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        
        // If you're serving to IE over SSL, then the following may be needed
        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($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;//这个是防止导出之后office版本过高不兼容的问题
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值