php word实现
PHP 操作 Word 文档的方法
使用 PHPWord 库生成 Word 文档
PHPWord 是一个流行的 PHP 库,用于生成和操作 Word 文档(.docx 格式)。它支持文本、表格、图片、页眉页脚等元素的添加。
安装 PHPWord:
composer require phpoffice/phpword
基本示例代码:
require_once 'vendor/autoload.php';
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!', ['name'=>'Arial', 'size'=>12]);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');
使用 COM 对象操作 Word(仅限 Windows)
在 Windows 服务器上,可以通过 COM 扩展直接操作 Microsoft Word:
$word = new COM("word.application") or die("Unable to instantiate Word");
$word->Visible = 1;
$word->Documents->Add();
$word->Selection->TypeText("Hello World");
$word->Documents[1]->SaveAs("test.docx");
$word->Quit();
$word = null;
转换为 PDF
使用 PHPWord 生成文档后,可以转换为 PDF:
$domPdfPath = 'vendor/dompdf/dompdf';
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
$phpWord = \PhpOffice\PhpWord\IOFactory::load('helloWorld.docx');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('helloWorld.pdf');
读取 Word 文档内容
使用 PHPWord 读取现有 Word 文档:
$phpWord = \PhpOffice\PhpWord\IOFactory::load('existing.docx');
$sections = $phpWord->getSections();
foreach ($sections as $section) {
$elements = $section->getElements();
foreach ($elements as $element) {
if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
foreach ($element->getElements() as $text) {
echo $text->getText();
}
}
}
}
高级功能
添加表格:
$table = $section->addTable();
$table->addRow();
$table->addCell(2000)->addText('Cell 1');
$table->addCell(2000)->addText('Cell 2');
添加图片:
$section->addImage('image.jpg', ['width'=>300, 'height'=>200]);
设置样式:
$fontStyle = ['name'=>'Arial', 'size'=>16, 'color'=>'FF0000', 'bold'=>true];
$paragraphStyle = ['align'=>'center', 'spaceAfter'=>100];
$section->addText('Styled Text', $fontStyle, $paragraphStyle);
注意事项

- PHPWord 仅支持 Office 2007 及更高版本的 .docx 格式
- COM 方法需要 Windows 服务器并安装 Microsoft Word
- 生成复杂文档时建议使用模板功能
- 对于大批量文档处理,考虑使用队列系统避免超时






