【问题标题】:Add table to template PHPWord将表格添加到模板 PHPWord
【发布时间】: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

作为输出,我只是将所有行作为一个段落,而不是作为一个表格......

【问题讨论】:

    标签: php phpword


    【解决方案1】:
    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      相关资源
      最近更新 更多