在phpWord模板文档中插入表格

Ter*_*tto 2 php phpword phpoffice

我有里面template.docx有标记的模板${table}。我需要使用phpWord创建表,并在我的插入template.docx,而不是${table}标记内。这是我的代码示例

//Create simple table
$document_with_table = new PhpWord();
$section = $document_with_table->addSection();
$table = $section->addTable();
for ($r = 1; $r <= 8; $r++) {
    $table->addRow();
    for ($c = 1; $c <= 5; $c++) {
        $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
    }
}

//Open template with ${table}
$template_document = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
// some code to replace ${table} with table from $document_with_table
// ???


//save template with table
$template_document->saveAs('template_with_table.docx');
Run Code Online (Sandbox Code Playgroud)

首先,我$document_with_table使用新的 PhpWord 实例在单独的变量中创建表。接下来我加载我的template.docxin$template_document变量。现在我需要从$document_with_table到插入表$template_document而不是${table}在里面标记。我怎样才能做到这一点?

PhpWord 版本 - 最新稳定版 (0.16.0)

小智 8

PhpWord有另一个解决方案,这对我来说更好。

    use PhpOffice\PhpWord\Element\Table;
    use PhpOffice\PhpWord\TemplateProcessor;

    $table = new Table(array('unit' => TblWidth::TWIP));
    foreach ($details as $detail) {
        $table->addRow();
        $table->addCell(700)->addText($detail->column);
        $table->addCell(500)->addText(1);
    }
    $phpWord = new TemplateProcessor('template.docx');
    $phpWord->setComplexBlock('{table}', $table);
    $phpWord->saveAs('template_with_table.docx');
Run Code Online (Sandbox Code Playgroud)


aut*_*tle 6

您可以获取表格的 xml 代码并将其插入到网站模板中

//Create table
$document_with_table = new PhpWord();
$section = $document_with_table->addSection();
$table = $section->addTable();
for ($r = 1; $r <= 8; $r++) {
    $table->addRow();
    for ($c = 1; $c <= 5; $c++) {
        $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
    }
}

// Create writer to convert document to xml
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($document_with_table, 'Word2007');

// Get all document xml code
$fullxml = $objWriter->getWriterPart('Document')->write();

// Get only table xml code
$tablexml = preg_replace('/^[\s\S]*(<w:tbl\b.*<\/w:tbl>).*/', '$1', $fullxml);

//Open template with ${table}
$template_document = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');

// Replace mark by xml code of table
$template_document->setValue('table', $tablexml);

//save template with table
$template_document->saveAs('template_with_table.docx');
Run Code Online (Sandbox Code Playgroud)

  • 这对我帮助很大。我想补充的一件事是,为了让它正常工作,我必须在前面添加 '&lt;/w:t&gt;&lt;/w:r&gt;&lt;/w:p&gt;' 和 '&lt;w:p&gt;&lt;w: r&gt;&lt;w:t&gt;' 在 $tablexml 之后,否则内容存在于 document.xml 中但不可见。 (2认同)