我在使用 python-docx 生成的文档中遇到错误,特别是如果我包含模板中的表格

I'm getting errors in documents generated with python-docx, specifically if I include tables from a template

我正在使用 python-docx 以编程方式将数据插入新文档。打开新文件时,出现以下错误消息。

Word found unreadable content in document_name. Do you want to recover the contents of this document? If you trust the source of this document, click Yes.

这是我的代码达到这一点所经历的过程:

  1. 将我们将调用调查结果模板的 docx 文件复制到 工作文件夹
  2. 将我们的报告文档的另一个 docx 文件复制到同一工作文件夹
  3. 在我们想要包含在报告中的调查结果文档中找到 table
  4. 在table中填写一些数据,将现在完成的table放入报表文档中。
  5. 将报告文档另存为新文件,名为generated.docx

到目前为止我想通了:

经过相当多的谷歌搜索并找到一些没有解决问题的类似答案后,我觉得这可能是相关的。调查结果文档中的 table 包含大量合并单元格。它只有一个 table,而不是像我最初认为的那样嵌套 table。

标题为 2 行深,左侧有 4 个合并单元格用于查找结果标题,右侧是两列标题和下方的相关数据。然后 table 的 body 是每行合并单元格的混合。有些行会合并所有单元格,有些行会合并 3 个单元格中的 2 个单元格。

这是我用来从调查结果文档中获取 table 的代码:

for table in findings_templates.tables:
    row = table.rows[0]
    for cell in row.cells:
        if title.lower() in cell.text.lower():
            severity = get_severity_from_template(table)
            for item in severity_array:
                if severity in item[1]:
                    anchor = item[0]

            # snip
            # Insert some data into table here
            # snip

            addTableAfterParagraph(report_document, table, title)
            return True

由于我们没有修改就出现错误,修改代码我就不放了。下面是将 table 插入模板文档的代码:

def addTableAfterParagraph(report_document, table, title):
    for para in report_document.paragraphs:
        if para.text == title:
            p = para._p
            p.addnext(table._tbl)

此外,我为 table._tbl.xml 添加了一些打印行,我没有发现源代码 table 和插入文档的源代码之间有什么区别,除了第一行有一个几个不同的 xmlns 标签。

我想要一些疑难解答提示或任何建议。让我知道是否需要更多信息。提前致谢!

更新:导致问题的是源 table 中的 hyperlink。我暂时将此标记为已解决,如果我无法解决,可能会提出另一个更具体的问题。

我最终从源文档表中读取数据,然后以编程方式创建我自己的表,然后将该数据插入回去并执行任何转换,例如创建超链接、样式等。

这很痛苦,但最终解决了问题并为将来提供了灵活性。