PHP导出EXCEL

本文介绍了一个使用PHP实现的Excel导出类库,通过简单的构造函数和下载方法即可将数据库查询结果转换为Excel文件并提供下载。该类库支持设置文件名,并能够自动生成包含查询结果的表格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值