Python 使用 DocxTemplate 填充 docx 表

jim*_*jim 4 python templating docx

我阅读了这个文档,python-docx-template但我对表格部分很困惑。假设我有一个名为 .docx 的模板Template.docx。在 docx 文件中,我有一个表格,其中只有标题的标题。

如何使用python-docx-template动态填充表(添加行和值)?

Roe*_*ant 13

一般情况下,你unlease的力量jinja2python-docx-template

填充单个变量

想象一下,你template.docx用一张表创建了一个文件:

**table 1**           **table 2**
{{some_content1}}      {{some_content2}}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它填充它

from docxtpl import DocxTemplate
import jinja2

doc = DocxTemplate("template.docx")
context = { 'some_content1' : "test", "some_content_2": "other"}  # Where the magic happens
doc.render(context)
doc.save("generated_doc.docx")
Run Code Online (Sandbox Code Playgroud)

如果您有可用的数据,pd.DataFrame那么您还可以生成context字典。例如:

import itertools 
context = {}
for row, col in itertools.product(df.index, df.columns):
    context[f'{row}_{col}'] = df.loc[row, col]
Run Code Online (Sandbox Code Playgroud)

动态表

您还可以动态生成表格,我想您可能不想这样做(如果您正在谈论在 docx 中指定“表格标题”)。不过值得研究一下。将此模板与 git 测试中的示例一起使用:

from docxtpl import DocxTemplate
tpl = DocxTemplate('templates/dynamic_table_tpl.docx')

context = {
'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'],
'tbl_contents': [
    {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']},
    {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']},
    {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']},
    ]
}

tpl.render(context)
tpl.save('output/dynamic_table.docx')
Run Code Online (Sandbox Code Playgroud)