You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPWord表格插入Word模板后列顺序反转问题求助

PHPWord插入模板后表格列顺序反转问题

我使用PHPWord创建表格并插入至Word模板中,生成的输出文件内表格的列顺序发生了反转,但我确认单元格的创建逻辑是正确的,相关实现代码如下:

<?php
$data = [
    ['cell 1 row 1','cell 2 row 1'],
    ['cell 1 row 2','cell 2 row 2']
];
// phpword
require_once '../vendor/autoload.php';
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use PhpOffice\PhpWord\Style\Table;
use PhpOffice\PhpWord\Writer\Word2007\Element\Container;
use PhpOffice\PhpWord\Shared\XMLWriter;

$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setName('Times');
$phpWord = new PhpWord(); // phpword object
$section = $phpWord->addSection(); // section
$tbl = $section->addTable(array(
/*'ltr' => true,*/
/*"layout" => Table::LAYOUT_AUTO,
"width"  => 100 * 50, // in word 1% == 50 unit (with in 1/50)
"unit"   => TblWidth::PERCENT,
'lineHeight' => 1*/
));
for($i=0;$i < 40;$i++){
    $tbl->addRow();
    $tbl->addCell(150)->addText("cell 1 row:$i");
    $tbl->addCell(150)->addText("cell 2 row:$i");
    $tbl->addCell(150)->addText("cell 3 row:$i");
    $tbl->addCell(150)->addText("cell 4 row:$i");
    //$tbl->addCell(150)->addMultiLineText("cell 4 row:$i");
}

$xmlWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY, './', Settings::hasCompatibility());
$containerWriter = new Container($xmlWriter, $section);
$containerWriter->write();
$elXml = $xmlWriter->getData();

// replace our templateContent
Settings::setOutputEscapingEnabled(false);
$templateProcessor = new TemplateProcessor('testing_tabledirection.docx');
$templateProcessor->setValue('table', $elXml);
Settings::setOutputEscapingEnabled(true);
$pathToSave = 'output_tabledirection.docx';
$templateProcessor->saveAs($pathToSave);
?>

解决方案

  1. 强制表格左到右布局
    取消代码中表格配置里'ltr' => true的注释,显式指定表格采用从左到右的排列方向:

    $tbl = $section->addTable(array(
        'ltr' => true,
        /*"layout" => Table::LAYOUT_AUTO,
        "width"  => 100 * 50, // in word 1% == 50 unit (with in 1/50)
        "unit"   => TblWidth::PERCENT,
        'lineHeight' => 1*/
    ));
    
  2. 检查模板的文本方向设置
    打开模板文件testing_tabledirection.docx,确认替换标记${table}所在段落或文档整体未设置为**右到左(RTL)**方向,若有则调整为左到右。

  3. 确认XML转义逻辑
    确保Settings::setOutputEscapingEnabled(false)仅在模板替换阶段启用,避免生成的表格XML结构被转义破坏。

内容的提问来源于stack exchange,提问作者Premlatha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:31:15