批量条件导出之---CSV

1.写公共方法

<?php

namespace util;

use Exception;

/**
 * 导出csv
 * @author 6c696e676a696177656e
 */
class ExportCsv
{
    
    public $num = 0;

    private $fp = null;
    private $head = [];
    private $is_header = false;

    public function __construct()
    {
        //打开PHP文件句柄,php://output 表示直接输出到php缓存
        $this->fp = fopen('php://output', 'w');
    }

    //设置头部
    public function setHead($head,$filename = 'export')
    {
        if (!is_array($head)) {
            throw new Exception('head格式不正确');
        }
        //error_reporting(0);
        header("Content-type:text/csv;charset=gbk"); //application/vnd.ms-excel
        header("Content-Disposition:attachment;filename={$filename}.csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0,max-age=0');
        header('Expires:0');
        header('Pragma:public');

        //输出Excel列名信息
        foreach ($head as $key => $arr_key) {
            //CSV的Excel支持GBK编码,一定要转换,否则乱码
            $csv_head[] =  mb_convert_encoding($key, 'GBK', 'UTF-8');
            $this->head[] = $arr_key;
        }
        //将数据通过fputcsv写到文件句柄
        fputcsv($this->fp, $csv_head);
        $this->is_header = true;
    }

    //采用putcsv封装格式
    public function output(array $data)
    {
        if (!$this->is_header) {
            throw new Exception('未设置head');
        }
        $row = [];
        foreach ($this->head as $arr_key) {
            //CSV的Excel支持GBK编码,一定要转换,否则乱码
            $row[] = mb_convert_encoding(@$data[$arr_key], 'GBK', 'UTF-8');
        }
        fputcsv($this->fp, $row);
        ++$this->num;
    }

    //刷新缓存,将PHP的输出缓存输出到浏览器上
    public function flush(&$csv_line)
    {
        ob_flush();
        flush();
        $csv_line = 0;
    }

    //关闭输出流
    public function close()
    {
        fclose($this->fp);
    }
}

2.调用

<?php
// +----------------------------------------------------------------------
// | 功能描述: 
// +----------------------------------------------------------------------
// | Author: Jimlin <lj.xia@163.com>
// +----------------------------------------------------------------------
// | Datetime: 2020/1/13 17:40
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\controller\Base;
use app\common\model\RechargeOrder as RechargeOrderModel;
use app\common\model\User;
use think\exception\DbException;
use util\ExportCsv;

/**
 * 充值订单控制器
 * Class RechargeOrder
 * @package app\admin\controller
 */
class RechargeOrder extends Base
{
    /**
     * 模型
     * @var RechargeOrderModel
     */
    protected $model;

    /**
     * RechargeOrder constructor.
     * @param RechargeOrderModel $model
     */
    public function __construct(RechargeOrderModel $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    }
    /**
     * @description: 导出详情
     * 
     */   
    public function export()
    {
        set_time_limit(0);
        $csv = new ExportCsv();

        $this->page = 1;
        $this->listRows = 5000;
     
        $csv->setHead(
            [
                'ID'       => 'id',
                '订单编号'  => 'order_no',
                '用户昵称'  => 'user',
                '充值金额'  => 'price',
                '生成时间'  => 'create_time',
                '支付状态'  => 'pay_status_text'
            ],
            'export_' . date('YmdHis')
        );

        $data = true;
        $line = 1;
        try {
            while ($data) {
                /**
                 * 获取数据
                 */
                $with = ['user'];
                $order = 'id desc';

                $list = $this->model->customPaginate($this->requestQuery, $order, $with)->append(['pay_status_text'])->toArray();
                $data = $list['data'] ?? [];
                /**
                 * 输出数据
                 */
                foreach ($data as $v) {
                    $v['user'] = $v['user']['nickname'] ?? '';
                    $csv->output($v);
                }
                $csv->flush($line);
                $this->page += 1;
            }
        } catch (\Throwable $th) {
            
        }
        $csv->close();
    } 
}

 

posted @ 2020-11-08 14:46  糖粿  阅读(140)  评论(0编辑  收藏  举报