微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 ZipArchive PHP 在 .docx 文件中插入表格

如何解决使用 ZipArchive PHP 在 .docx 文件中插入表格

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

我有以下 .docx 文件

Word document template PHP

我将使用 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>
';

输出

HTML table output from PHP

我还尝试了 Open Office XML 标准

$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>
';

输出

Open Office XML standard

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

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

谢谢!

解决方法

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

最好的问候,安德烈亚斯

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。