You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP实现动态表头的SQL Server表转可下载Excel?

实现PHP+SQL Server动态表头的Excel导出功能

原代码依赖硬编码的<th>标签和列名,只能适配特定表。要实现任意列、多表的通用导出,需通过以下方式替换固定表头:

核心思路

  1. 动态获取表头:从SQL查询结果中提取字段名称,作为Excel表头
  2. 动态渲染表格内容:循环遍历每一行的所有字段值,无需指定列名
  3. 修正Header位置:原代码将header放在while循环内会导致重复输出,需移到表格输出前

具体实现代码

<?php
// 数据库连接
include('connection.php');

// 配置导出参数:可根据需求动态传入表名或自定义SQL
$tableName = "CVL_USERS1";
$filename = "EmpData";

// 执行查询:支持自定义SQL,比如"SELECT col1, col2 FROM table"
$query = sqlsrv_query($conn, "SELECT * FROM $tableName");
if (!$query) {
    die("查询失败: " . print_r(sqlsrv_errors(), true));
}

// 获取字段元数据,生成表头
$fieldMetadata = sqlsrv_field_metadata($query);
$headers = [];
foreach ($fieldMetadata as $field) {
    $headers[] = $field['Name'];
}
// 额外添加序号列(如果需要)
array_unshift($headers, "序号");

// 输出Excel头信息(必须在任何内容输出前)
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename={$filename}-Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
?>

<table border="1">
<thead>
    <tr>
        <?php foreach ($headers as $header): ?>
            <th><?php echo htmlspecialchars($header); ?></th>
        <?php endforeach; ?>
    </tr>
</thead>
<tbody>
    <?php
    $cnt = 1;
    while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)):
        // 插入序号
        $rowWithIndex = [$cnt] + $row;
    ?>
    <tr>
        <?php foreach ($rowWithIndex as $value): ?>
            <!-- 处理SQL Server的日期类型等特殊值 -->
            <td><?php echo $value instanceof DateTime ? $value->format('Y-m-d H:i:s') : htmlspecialchars($value ?? ''); ?></td>
        <?php endforeach; ?>
    </tr>
    <?php
        $cnt++;
    endwhile;
    ?>
</tbody>
</table>

关键说明

  • 动态表头生成:使用sqlsrv_field_metadata()获取查询结果的字段名称,确保表头与查询列完全匹配,支持任意表和自定义SQL
  • 通用内容渲染:通过foreach遍历每行的所有字段值,无需硬编码列名,适配任意列数
  • 数据安全处理:用htmlspecialchars()转义内容,避免特殊字符破坏Excel格式;处理SQL Server返回的DateTime类型数据
  • Header修正:将header移到最前面,确保只发送一次,避免HTTP头错误

内容的提问来源于stack exchange,提问作者PARINEETI GUPTA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:45:56