【发布时间】:2021-02-09 14:46:30
【问题描述】:
我有一个模板 .docx 文件,我想在其中放置一个表格。我已经可以读入模板文件并在模板中搜索和替换简单的字符串。
但现在我想在模板中放一张表格。
这是我的代码:
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template);
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$templateProcessor->setValue('customer_name', $name);
$templateProcessor->setValue('customer_address', $address);
$templateProcessor->setValue('customer_city', $city);
$templateProcessor->setValue('customer_name', $name);
$templateProcessor->setValue('invoice_date', $date);
$table_section = $phpWord->addSection();
$rows = 10;
$cols = 5;
$table_section->addText('Basic table', "rofl");
$table = $table_section->addTable();
for ($r = 1; $r <= $rows; $r++) {
$table->addRow();
for ($c = 1; $c <= $cols; $c++) {
$table->addCell(1750)->addText("Row {$r}, Cell {$c}");
}
}
$objWriter = new PhpOffice\PhpWord\Writer\Word2007($phpWord);
$tableStr = $objWriter->getWriterPart('Document')->getTableAsText($table);
$templateProcessor->setValue('product_table', $tableStr);
$templateProcessor->saveAs($new_file_path);
我已经添加了这个:
/* CUSTOM FUNCTION */
function getTableAsText($element) {
$xmlWriter = $this->getXmlWriter();
$writer = new \PhpOffice\PhpWord\Writer\Word2007\Element\Table($xmlWriter, $element);
$writer->write();
return $xmlWriter->getData();
}
到PhpWord/Writer/Word2007/Part/Document.php。
作为输出,我只是将所有行作为一个段落,而不是作为一个表格......
【问题讨论】: