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

PHP 生成 Excel 文件三種方案對比:原生 Header、CSV、PhpSpreadsheet

     編輯:PHP 相關知識

需導出數據供 Excel 打開時,常見三種方案各有優劣。本文對比原生 Header 輸出 HTML 表格、CSV 格式、PhpSpreadsheet 庫,助你按場景選型。

方案一:原生 Header 輸出 HTML 表格(最輕量,兼容性一般)

header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="report_' . date('Ymd') . '.xls"');
header('Pragma: no-cache');
header('Expires: 0');

echo "<table border='1'><tr><th>標題</th><th>關鍵詞</th><th>URL</th></tr>";
foreach ($rows as $row) {
    echo "<tr><td>{$row['title']}</td><td>{$row['keywords']}</td><td>{$row['url']}</td></tr>";
}
echo "</table>";
  • ✅ 無依賴、極簡代碼、內存佔用極低(流式輸出)。
  • ❌ 本質是 HTML,Excel 會彈出「文件格式不匹配」警告;不支援多工作表、樣式、公式、超大數據(>65536 行 .xls 限制)。
  • 適用:後台管理小數據導出、臨時需求、無法安裝擴展的環境。

方案二:CSV 格式(通用性最強,純文本)

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="report_' . date('Ymd') . '.csv"');
$out = fopen('php://output', 'w');
// 寫入 BOM 防止 Excel 打開中文亂碼
fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($out, ['標題', '關鍵詞', 'URL']);
foreach ($rows as $row) {
    fputcsv($out, [$row['title'], $row['keywords'], $row['url']]);
}
fclose($out);
  • ✅ 所有表格軟體完美支援、流式寫入無內存壓力、UTF-8+BOM 解決中文編碼。
  • ❌ 無樣式/公式/多 Sheet、數字長文本易被科學計數法顯示(需在數據前加 \t 或 ' 強制文本)。
  • 適用:大數據導出(百萬行)、跨系統數據交換、後續需導入資料庫。

方案三:PhpSpreadsheet(功能最全,資源消耗大)

composer require phpoffice/phpspreadsheet

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([['標題','關鍵詞','URL']], null, 'A1');
$sheet->fromArray($rows, null, 'A2');

// 樣式示例
$sheet->getStyle('A1:C1')->getFont()->setBold(true);
$sheet->getColumnDimension('A')->setWidth(40);

$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="report_' . date('Ymd') . '.xlsx"');
$writer->save('php://output');
  • ✅ 完整支援 .xlsx/.xls/.ods、多 Sheet、樣式、公式、圖表、數據驗證、合併儲存格。
  • ❌ 內存佔用極大(百萬行需 GB 級內存)、執行慢、需 Composer 安裝依賴。
  • 優化大數據:使用 PhpOffice\PhpSpreadsheet\Writer\Xlsx 的 setPreCalculateFormulas(false)、分塊寫入、或改用 Box\Spout(流式寫入庫)。
  • 適用:精美報表、複雜樣式、多 Sheet、客戶交付文件。

選型決策表

場景推薦方案
後台簡單導出 < 1 萬行、無樣式要求方案一(HTML)或方案二(CSV)
大數據導出 > 10 萬行、需流式寫入方案二(CSV)或 Box/Spout
客戶交付、複雜樣式、多 Sheet、公式方案三
禁止安裝擴展/Composer 的受限環境方案一

建議專案中封裝統一 ExcelExporter 介面,根據導出配置自動選擇最優策略,業務代碼零感知切換。

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