Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert table inside phpWord template document

I have template.docx template with mark ${table} inside. I need to create table using phpWord and insert it in my template.docx instead ${table} mark inside. Here is my code example

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

First, I create table in separate variable $document_with_table using new PhpWord instance. Next I load my template.docx in $template_document variable. And now I need to insert table from $document_with_table to $template_document instead ${table} mark inside. How can I do that?

PhpWord version - latest stable (0.16.0)

like image 232
Teretto Avatar asked Sep 18 '25 04:09

Teretto


2 Answers

You can get xml code of your table and insert it insite template

//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');
like image 98
autumnrustle Avatar answered Sep 20 '25 20:09

autumnrustle


PhpWord has another solution, which better for me.

    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');
like image 31
Богдан Скуба Avatar answered Sep 20 '25 19:09

Богдан Скуба