PHP 產生 Excel 檔案有多種方式,從簡單的 HTML 表格輸出到專業的 XML 格式產生。本文整理三種常見方法,並說明適用場景與優缺點。
使用 Microsoft XML Spreadsheet 格式,支援儲存格類型判斷、欄寬設定、工作表命名等功能。
<?php
class ExcelExporter {
private $header = '';
private $lines = [];
private $worksheetTitle = 'Sheet1';
public function addRow(array $rowData) {
$cells = '';
foreach ($rowData as $value) {
if (is_numeric($value)) {
$type = (strlen($value) > 1 && $value[0] === '0') ? 'String' : 'Number';
} else {
$type = 'String';
}
$cells .= "<Cell><Data ss:Type=\"$type\">" . htmlspecialchars($value) . "</Data></Cell>";
}
$this->lines[] = "<Row>$cells</Row>";
}
public function addRows(array $rows) {
foreach ($rows as $row) $this->addRow($row);
}
public function setTitle(string $title) {
$this->worksheetTitle = preg_replace('/[\\|:|\\/|\\?|\\*|\\[|\\]]/', '', $title);
$this->worksheetTitle = substr($this->worksheetTitle, 0, 31);
}
public function download(string $filename = 'export') {
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header("Content-Disposition: attachment; filename=\"{$filename}.xls\"");
echo $this->header;
echo "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
echo "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">";
echo "<Worksheet ss:Name=\"{$this->worksheetTitle}\"><Table>";
echo implode("\n", $this->lines);
echo "</Table></Worksheet></Workbook>";
}
}
// 使用範例
$excel = new ExcelExporter();
$excel->addRows([
['姓名', '年齡', '城市'],
['王小明', 25, '台北'],
['李大華', 30, '台中'],
]);
$excel->download('會員名單');
?>
直接輸出 HTML <table>,瀏覽器會將其識別為 Excel 可開啟格式。
<?php
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="simple.xls"');
?>
<table border="1">
<tr><th>編號</th><th>商品</th><th>價格</th></tr>
<tr><td>1</td><td>筆記型電腦</td><td>25000</td></tr>
<tr><td>2</td><td>滑鼠</td><td>500</td></tr>
</table>
優點:程式碼極簡、支援基本樣式 (合併儲存格、背景色等)。
缺點:非真正 Excel 格式、大檔案效能差、無法設定儲存格資料類型。
使用 \t 分隔欄位、\n 換行,最接近 CSV 但用 Tab 避免逗號衝突。
<?php
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="export.xls"');
$data = [
['身分證字號', '姓名', '電話'],
['A123456789', '陳小美', '0912-345678'],
['B987654321', '林大同', '0933-555888'],
];
foreach ($data as $row) {
echo implode("\t", $row) . "\n";
}
?>
| 特性 | XML 格式 | HTML 表格 | TSV 格式 |
|---|---|---|---|
| 實作複雜度 | 高 | 低 | 極低 |
| 儲存格類型控制 | 支援 | 不支援 | 不支援 |
| 樣式/格式化 | 支援 | 支援 (CSS) | 不支援 |
| 大量資料效能 | 中等 | 差 | 佳 |
| 相容性 | Excel 2003+ | Excel 所有版本 | Excel 所有版本 |
新專案建議使用 PhpSpreadsheet (PHPExcel 繼任者),支援 .xlsx/.ods/.csv 多格式、豐富樣式、記憶體優化、公式計算等企業級功能。安裝指令:composer require phpoffice/phpspreadsheet