PHP导出EXCEL

来源:互联网 发布:发散和收敛定义知乎 编辑:程序博客网 时间:2024/06/05 10:53

report.php

<?php/** * @copyright (c) 2014 aircheng * @file report.php * @brief 导出excel类库 * @author LiuQi * @date 2017/03/30 16:36:43 * @version 1.0.0 */class report{    //文件名    private $fileName = 'user';    //构造函数    public function __construct($fileName = '')    {        $this->setFileName($fileName);    }    //设置要导出的文件名    public function setFileName($fileName)    {        $this->fileName = $fileName;    }    //开始下载    public function toDownload($strTable)    {        header("Content-type: application/vnd.ms-excel");        header("Content-Type: application/force-download");        header("Content-Disposition: attachment ; filename=".$this->fileName."_".date('Y-m-d').".xls");        header('Expires:0');        header('Pragma:public');        echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$strTable.'</html>';    }}

demo.php

<?php header('content-type:text/html;charset=utf-8');require "report.php";$ticketFile = "文件名";// $excelStr = "表格中的内容";$excelStr = '<table border="1px"><tr><th>卡号</th><th>网址</th><th>分类</th></tr>';try{    $pdo = new PDO("mysql:host=127.0.0.1;dbname=collect","root","root");}catch(PDOException $e ){    echo $e->getMessage();}$pdo->query("set names utf8");$sql = "SELECT * from day0310 limit 10";$list = $pdo->query($sql);$list->setFetchMode(PDO::FETCH_ASSOC);$re = $list->fetchAll();foreach ($re as $key => $value) {    $excelStr.='<tr align="center">';    $excelStr.='<td>'.$value['id'].'</td>';    $excelStr.='<td>'.$value['link'].'</td>';    $excelStr.='<td>'.$value['title'].'</td>';    $excelStr.='</tr>';}$reportObj = new report($ticketFile);$reportObj->toDownload($excelStr);