在 phpWord 模板文档中插入 table

Insert table inside phpWord template document

我有 template.docx 模板,里面有标记 ${table}。我需要使用 phpWord 创建 table 并将其插入我的 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');

首先,我使用新的 PhpWord 实例在单独的变量 $document_with_table 中创建 table。接下来,我将 template.docx 加载到 $template_document 变量中。现在我需要插入 table 从 $document_with_table$template_document 而不是 ${table} 标记。我该怎么做?

PhpWord 版本 - 最新版本table (0.16.0)

您可以获得 table 的 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>).*/', '', $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');

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