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

PHP 產生 Word 文件:HTML 轉 .doc 簡易法與 PHPWord 專業法

     編輯:PHP 相關知識

方法一:HTML 模擬 .doc (最簡單、相容性有限)

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');

缺點:複雜排版 (分頁、頁首尾、樣式) 支援差、大檔案記憶體耗盡。

方法二:PHPWord (專業、純 PHP、支援 .docx/.odt/.rtf/.pdf)

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);

方法三:TemplateProcessor (範本填充,適合固定格式)

// 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 文件平台
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved