php中简单实现excel下载功能

来源:互联网 发布:js验证手机号码格式 编辑:程序博客网 时间:2024/05/29 15:13

项目中经常有报表下载的需求,用传统的phpexcel等太重,因此写了个简单的scv下载导出功能。

1、实现代码

<?phpclass CsvExport {    private static $instance;    private $fileName;    private $charset;    private $title = [];    private $data = [];    private $prepared = FALSE;    private function __clone() {    }    private function __construct($fileName, $charset) {        $this->fileName = $fileName;        $this->charset = $charset;    }    /**     * 获取实例     *     * @param $fileName     * @param string $charset     * @return self     */    public static function getInstance($fileName, $charset = 'gbk') {        self::$instance === NULL and self::$instance = new self($fileName, $charset);        return self::$instance;    }    /**     * 设置title     *     * @param array $title     * @return $this     */    public function setTitle(array $title) {        $this->title = $title;        return $this;    }    /**     * 追加数据     *     * @param array $data     * @param bool|TRUE $autoStart     * @return $this     */    public function appendData(array $data, $autoStart = TRUE) {        $this->data = $data;        if ($autoStart) {            $this->start();        }        return $this;    }    /**     * 手动开始下载     */    public function start() {        return $this->prepare()->echoCsv($this->data);    }    public function finish() {        exit;    }    protected function prepare() {        if (!$this->prepared) {            header("Pragma: public");            header("Expires: 0");            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");            header("Content-Type: application/force-download");            header("Content-Type: text/comma-separated-values; charset={$this->charset}");            header("Content-Transfer-Encoding: binary");            header("Content-Disposition: attachment; filename={$this->fileName}.csv");            $this->echoCsv($this->title);            $this->prepared = TRUE;        }        return $this;    }    protected function echoCsv(array $arr) {        foreach ($arr as &$val) {            $val = str_replace([',', "\r", "\n", "\r\n", "\t"], '', $val);            $val = mb_convert_encoding($val, $this->charset, 'utf-8');            is_numeric($val) and strlen($val) > 10 and $val = $val . "\t";        }        $str = implode(',', $arr);        echo $str;        echo "\n";    }    public function __toString() {        return json_encode(get_object_vars($this));    }}

2、调用示例

<?php$title = ['id', 'name', 'language'];$datas = [    ['1', 'a', 'php'],    ['2', 'b', 'java'],    ['3', 'c', 'linux']];$csvClient = CsvExport::getInstance('test');$csvClient->setTitle($title);foreach($datas as $data) {    $csvClient->appendData($data);}$csvClient->finish();
原创粉丝点击