gpt4 book ai didi

php - 在 PHPWord 中操作模板

转载 作者:行者123 更新时间:2023-12-03 00:11:35 26 4
gpt4 key购买 nike

我正在使用 PHP 的 Word 文档生成器作为我正在开发的 Web 应用程序的报告模块。我选择 PHPWord 是因为 PHPDocX 的免费版本功能非常有限,而且它的页脚表明它只是免费版本。我有客户给的模板。我想要的是加载模板并向其中添加动态元素,例如附加文本或表格。我的代码在这里:

<?php
require_once '../PHPWord.php';

$PHPWord = new PHPWord();

$document = $PHPWord->loadTemplate('Template.docx');
$document->setValue('Value1', 'Great');

$section = $PHPWord->createSection();
$section->addText('Hello World!');
$section->addTextBreak(2);

$document->setValue('Value2', $section);

$document->save('test.docx');
?>

我尝试创建一个新部分并尝试将其分配给模板中的一个变量(Value2),但出现了此错误:

[28-Jan-2013 10:36:37 UTC] PHP Warning:  utf8_encode() expects parameter 1 to be string, object given in /Users/admin/localhost/PHPWord_0.6.2_Beta/PHPWord/Template.php on line 99

最佳答案

setValue 期望第二个参数是纯字符串。无法提供节对象。

我深入研究了代码,发现没有一种简单的方法可以让节对象返回 setValue 函数可以使用的值。

由于我遇到了同样的问题,我为 Template.php 文件编写了一个补丁,允许您在用 s​​etValue 替换其标签之前克隆表行。每行都有一个唯一的 ID,允许您识别每个不同行的模板标签。

它是这样工作的:

将此函数添加到您的 Template.php 文件(在 PHPWord 目录中找到)

public function cloneRow($search, $numberOfClones) {
if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${'.$search.'}';
}
$tagPos = strpos($this->_documentXML, $search);
$rowStartPos = strrpos($this->_documentXML, "<w:tr", ((strlen($this->_documentXML) - $tagPos) * -1));
$rowEndPos = strpos($this->_documentXML, "</w:tr>", $tagPos) + 7;

$result = substr($this->_documentXML, 0, $rowStartPos);
$xmlRow = substr($this->_documentXML, $rowStartPos, ($rowEndPos - $rowStartPos));
for ($i = 1; $i <= $numberOfClones; $i++) {
$result .= preg_replace('/\$\{(.*?)\}/','\${\\1#'.$i.'}', $xmlRow);
}
$result .= substr($this->_documentXML, $rowEndPos);
$this->_documentXML = $result;
}

在模板文件中,向每个表添加一行,将其用作模板行。假设您已在此行添加标签 ${first_name}。

要获取包含 3 行的表,请调用: $document->cloneRow('first_name', 3);

模板的工作副本现已更新为包含 3 行的表格。行内的每个标签都附加了 # 和行号。

要设置您的值,请使用 setValue $document->setValue('first_name#1', '第一行的名称'); $document->setValue('first_name#2', '第二行的名称'); $document->setValue('first_name#3', '第三行的名字');

我希望这有用!我将在此处保留代码和文档的更新版本:http://jeroen.is/phpword-templates-with-repeating-rows/

关于php - 在 PHPWord 中操作模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14560142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com