【问题标题】:Insert table in .docx file using ZipArchive PHP使用 ZipArchive PHP 在 .docx 文件中插入表格
【发布时间】:2021-02-08 11:46:14
【问题描述】:

我想使用 PHP 和 ZipArchive 在 docx 文件中创建一个表。但它并没有真正起作用。

我有以下 .docx 文件:

我将使用 ZipArchive 将内容放在这里,如下所示:

    $zip = new ZipArchive;

    $my_table = "
    ...
    ";

    if ($zip->open("document.docx") === TRUE) {
        $template_content = $zip->getFromName("word/document.xml");

        $new_content = str_replace("{{ my_table }}", $my_table, $template_content);


        $zip->addFromString("word/document.xml", $new_content);
        $zip->close();
    }

我不知道在 PHP 变量 $my_table 中添加什么。我尝试了这样的 HTML 表格

$my_table = '
    <table>
        <tr>
            <th>H1</th>
            <th>H2</th>
            <th>H3</th>
        </tr>
        <tr>
            <td>a</td>
            <td>b</td>
            <td>c</td>
        </tr>
        <tr>
            <td>a</td>
            <td>b</td>
            <td>c</td>
        </tr>
        <tr>
            <td>a</td>
            <td>b</td>
            <td>c</td>
        </tr>
    </table>
';

输出:

我也尝试了Open Office XML Standard

$my_table = '
    <w:tbl>
        <w:tblPr>
            <w:tblStyle w:val="TableGrid"/>
            <w:tblW w:w="5000" w:type="pct"/>
        </w:tblPr>
        <w:tblGrid>
            <w:gridCol w:w="2880"/>
            <w:gridCol w:w="2880"/>
            <w:gridCol w:w="2880"/>
        </w:tblGrid>
        <w:tr>
        <w:tc>
        <w:tcPr>
            <w:tcW w:w="2880" w:type="dxa"/>
        </w:tcPr>
        <w:p>
            <w:r>
                <w:t>AAA</w:t>
            </w:r>
        </w:p>
        </w:tc>
        <w:tc>
        <w:tcPr>
        <w:tcW w:w="2880" w:type="dxa"/>
        </w:tcPr>
        <w:p>
            <w:r>
                <w:t>BBB</w:t>
            </w:r>
        </w:p>
        </w:tc>
        <w:tc>
        <w:tcPr>
            <w:tcW w:w="2880" w:type="dxa"/>
        </w:tcPr>
        <w:p>
            <w:r>
                <w:t>CCC</w:t>
            </w:r>
        </w:p>
        </w:tc>
        </w:tr>
    </w:tbl>
';

输出:

我还尝试在 Word 中创建一个表格,并从该 Word 文件中提取 Open Office XML。但这也给出了相同的输出。

那么我应该在$my_table 变量中放置什么来在我的输出文件中获得一个带有边框的漂亮表格?

谢谢!

【问题讨论】:

    标签: php ziparchive


    【解决方案1】:

    您尝试直接使用 ZIP 和 Word XML 有什么具体原因吗?您可以使用方便的抽象库,例如PHPWord。有了它,你的任务就可以很简单地完成了。

    最好的问候,安德烈亚斯

    【讨论】:

    • PHPWord 是否可以读取 docx 文件?我正在更改模板。
    • 根据samples,应该也可以读取docx文件。
    • 在没有作曲家的情况下如何包含它?
    • PHPWord 没有此问题所需的功能。 PHPWord 无法将表格放入模板中。
    猜你喜欢
    • 2019-02-16
    • 2018-03-13
    • 1970-01-01
    • 2015-11-11
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多