首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP匯出帶樣式的Excel完整實作教學

     編輯:PHP 綜合知識

在日常開發工作中,資料匯出是常見需求。但預設匯出的Excel往往格式單調,難以滿足業務呈現需求。本文將透過完整實例,示範如何使用PHP匯出包含自訂樣式(顏色、字型、粗體、合併儲存格等)的Excel檔案。

預覽成品效果

匯出Excel樣式效果圖

核心實作代碼

PHP控制器邏輯

控制器負責設定HTTP標頭並載入視圖模板:

/**
 * 匯出Excel檔案
 * @return string
 */
public function export() {
    $file_name = "成績單-" . date("Y-m-d H:i:s", time());
    $file_suffix = "xls";
    
    // 設定HTTP標頭,告訴瀏覽器這是Excel檔案
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=$file_name.$file_suffix");
    
    // 根據業務邏輯賦值模板變數
    $this->display();
}

HTML模板結構(含Office命名空間)

關鍵在於引入Microsoft Office相關XML命名空間,讓Excel能正確解析樣式:

<html xmlns:o="urn:schemas-microsoft-com:office:office" 
      xmlns:x="urn:schemas-microsoft-com:office:excel" 
      xmlns="https://www.w3.org/TR/REC-html40">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="ProgId" content="Excel.Sheet">
    <meta name="Generator" content="Microsoft Excel 11">
</head>
<body>
    <table border="1" cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td colspan="5" align="center">
                <h2>成績單</h2>
            </td>
        </tr>
        <tr>
            <td style='width:54pt' align="center">編號</td>
            <td style='width:54pt' align="center">姓名</td>
            <td style='width:54pt' align="center">語文</td>
            <td style='width:54pt' align="center">數學</td>
            <td style='width:54pt' align="center">英語</td>
        </tr>
        <tr>
            <td align="center">1</td>
            <td style="background-color: #00CC00;" align="center">Jone</td>
            <td style="background-color: #00adee;" align="center">90</td>
            <td style="background-color: #00CC00;" align="center">85</td>
            <td style="background-color: #00adee;" align="center">100</td>
        </tr>
        <tr>
            <td align="center">2</td>
            <td style="background-color: #00CC00;" align="center">Tom</td>
            <td style="background-color: #00adee;" align="center">99</td>
            <td style="background-color: #00CC00;" align="center">85</td>
            <td style="background-color: #00adee;" align="center">80</td>
        </tr>
    </table>
</body>
</html>

關鍵技術要點

  • 命名空間宣告:xmlns:x="urn:schemas-microsoft-com:office:excel" 讓Excel識別專屬屬性
  • Meta標籤:ProgId 和 Generator 標識檔案來源
  • 內嵌樣式:直接在 td 使用 style 屬性設定背景色、對齊、寬度
  • 合併儲存格:使用 colspan 實現標題跨欄
  • 編碼設定:charset=utf-8 確保中文正常顯示

進階應用建議

實際專案中可將HTML模板獨立為視圖檔案,控制器透過模板引擎動態填充資料,支援更複雜的報表需求(如動態欄位、條件式樣式、多工作表等)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved