Вставить таблицу в шаблонный документ phpWord - PullRequest
0 голосов
/ 19 января 2019

У меня есть 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');

Сначала я создаю таблицу в отдельной переменной $document_with_table, используя новый экземпляр PhpWord. Затем я загружаю свою переменную template.docx в $template_document. И теперь мне нужно вставить таблицу от $document_with_table до $template_document вместо ${table} метки внутри. Как я могу это сделать?

Версия PhpWord - последняя стабильная версия (0.16.0)

1 Ответ

0 голосов
/ 20 января 2019

Вы можете получить 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');
...