问题描述
我有一个模板 .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
。
作为输出,我只是将所有行作为一个段落,而不是作为一个表格......
解决方法
This is just a siple table customized with width and color. you also have to add and on top of you page.
use PhpOffice\PhpWord\Shared\Converter;
$fancyTableStyleName = 'Fancy Table';
$fancyTableStyle = array('borderSize' => 1,'borderColor' => '006699','cellMargin' => 0,'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER,'cellSpacing' => 0);
$fancyTableFirstRowStyle = array('borderBottomSize' => 1,'borderBottomColor' => '0000FF','bgColor' => '66BBFF');
$fancyTableCellStyle = array('valign' => 'center');
$fancyTableCellBtlrStyle = array('valign' => 'center','textDirection' => \PhpOffice\PhpWord\Style\Cell::TEXT_DIR_BTLR);
$fancyTableFontStyle = array('bold' => true);
$phpWord->addTableStyle($fancyTableStyleName,$fancyTableStyle,$fancyTableFirstRowStyle);
$table = $section->addTable($fancyTableStyleName);
$table->addRow(900);
$table->addCell(2000,$fancyTableCellStyle)->addText('Row 1',$fancyTableFontStyle);
$table->addCell(2000,$fancyTableCellStyle)->addText('Row 2',$fancyTableFontStyle);
$table->addRow();
$table->addCell(2000)->addText("Cell 1");
$table->addCell(2000)->addText("Cell 2");