Word 可直接開啟 HTML 檔並另存為 .docx。只需輸出正確 Header。
<?php
function exportWord(string $html, string $filename = 'document.doc') {
header("Content-Type: application/msword");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Cache-Control: max-age=0");
echo $html;
}
// 使用
$html = '<h1>報表標題</h1><p>內容段落...</p><table border="1"><tr><th>項目</th><th>金額</th></tr><tr><td>產品 A</td><td>$100</td></tr></table>';
exportWord($html, 'report_'.date('Ymd').'.doc');
缺點:複雜排版 (分頁、頁首尾、樣式) 支援差、大檔案記憶體耗盡。
composer require phpoffice/phpword
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\TemplateProcessor;
function generateReport(array $data): string {
$phpWord = new \PhpOffice\PhpWord\PhpWord();
// 設定預設字型
$phpWord->setDefaultFontName('Microsoft JhengHei');
$phpWord->setDefaultFontSize(11);
// 新增區段 (頁面)
$section = $phpWord->addSection([
'marginTop' => 1440, // 1 吋 = 1440 twips
'marginBottom' => 1440,
'marginLeft' => 1440,
'marginRight' => 1440,
]);
// 標題
$section->addTitle('月度銷售報表', 1);
// 表格
$table = $section->addTable(['borderSize'=>6, 'borderColor'=>'000000', 'cellMargin'=>80]);
$table->addRow();
$table->addCell(2000)->addText('產品', ['bold'=>true, 'size'=>11]);
$table->addCell(2000)->addText('數量', ['bold'=>true, 'size'=>11]);
$table->addCell(2000)->addText('金額', ['bold'=>true, 'size'=>11]);
foreach ($data as $row) {
$table->addRow();
$table->addCell()->addText($row['product']);
$table->addCell()->addText(number_format($row['qty']));
$table->addCell()->addText('$' . number_format($row['amount']));
}
// 總計
$total = array_sum(array_column($data, 'amount'));
$section->addText("總計: $" . number_format($total), ['bold'=>true, 'size'=>12]);
// 頁碼
$footer = $section->addFooter();
$footer->addPreserveText('第 {PAGE} 頁 / 共 {NUMPAGES} 頁', null, ['align'=>'center']);
// 儲存
$filename = 'report_' . date('Ymd_His') . '.docx';
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($filename);
return $filename;
}
// 使用
$data = [
['product'=>'筆電', 'qty'=>10, 'amount'=>120000],
['product'=>'滑鼠', 'qty'=>50, 'amount'=>25000],
];
$file = generateReport($data);
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
unlink($file);
// template.docx 內容含 ${title}、${date}、${table} 等變數
$template = new TemplateProcessor('template.docx');
$template->setValue('title', '2024 年度報告');
$template->setValue('date', date('Y-m-d'));
// 複雜表格需用 cloneRow
$template->cloneRow('product', count($data));
foreach ($data as $i => $row) {
$idx = $i + 1;
$template->setValue("product#$idx", $row['product']);
$template->setValue("qty#$idx", $row['qty']);
$template->setValue("amount#$idx", $row['amount']);
}
$template->saveAs('filled_report.docx');
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| HTML + Header | 零依賴、最快 | 排版受限、非真實 .docx | 簡單匯出、臨時需求 |
| PHPWord | 功能完整、純 PHP、跨平台 | 大檔案較慢、記憶體佔用 | 正式報表、合約、履歷 |
| LibreOffice Headless | 完美轉檔、支援所有格式 | 需安裝、啟動慢、佔資源 | 批次轉檔、伺服器端 |
| OnlyOffice / Collabora | 線上編輯、協同 | 架構複雜 | SaaS 文件平台 |