如何使用PHPWord TemplateProcessor修改Word文档标题中的变量
PHPWord模板替换无法更新文档标题中的变量
我尝试用以下代码通过模板生成docx文件:
$phpWord = new \PhpOffice\PhpWord\TemplateProcessor(storage_path().'\app\public\sample\sample.docx'); $phpWord->setValue('days', '365'); $phpWord->setValue('what', 'Benchmark'); $phpWord->setValue('test', 'KKKK'); $phpWord->setValue('best', 'MMMM'); $phpWord->saveAs(storage_path().'\app\public\sample\final.docx');
sample.docx里,标题区域包含{days}和{what}变量,正文区域有{test}和{best}变量。但运行代码后,只有正文的test和best成功更新,标题里的days和what完全没变化。
解决方法
PHPWord的TemplateProcessor默认只处理文档的正文内容,要替换标题(或页眉)里的变量,需要先定位到对应的节或页眉对象:
方法1:切换到标题所在的节
如果标题和正文在同一个节里,直接切换节之后再替换变量即可:
$phpWord = new \PhpOffice\PhpWord\TemplateProcessor(storage_path().'\app\public\sample\sample.docx'); // 切换到标题所在的节(文档的第一个节索引为0) $phpWord->setActiveSection(0); // 替换标题中的变量 $phpWord->setValue('days', '365'); $phpWord->setValue('what', 'Benchmark'); // 处理正文变量 $phpWord->setValue('test', 'KKKK'); $phpWord->setValue('best', 'MMMM'); $phpWord->saveAs(storage_path().'\app\public\sample\final.docx');
方法2:直接操作页眉对象
如果标题属于文档的页眉区域,需要先获取页眉对象再替换:
$phpWord = new \PhpOffice\PhpWord\TemplateProcessor(storage_path().'\app\public\sample\sample.docx'); // 获取第一个节的页眉 $header = $phpWord->getSection(0)->getHeader(); // 替换页眉中的变量 $header->replaceBlock('days', '365'); $header->replaceBlock('what', 'Benchmark'); // 处理正文变量 $phpWord->setValue('test', 'KKKK'); $phpWord->setValue('best', 'MMMM'); $phpWord->saveAs(storage_path().'\app\public\sample\final.docx');
如果不确定标题所在的节索引,可以调用$phpWord->getSections()查看文档中的所有节,确认目标节的位置。
内容的提问来源于stack exchange,提问作者Divyesh Jesadiya
相关产品推荐
相关产品推荐

