【问题标题】:Fill tables in a template Word with Python (DocxTemplate, Jinja2)用 Python 填充模板 Word 中的表格(DocxTemplate,Jinja2)
【发布时间】:2021-05-16 06:53:54
【问题描述】:

我正在尝试使用 DocxTemplate 在 Word 中用 Python 填充一个表格,但我有一些问题要正确完成。我想使用 2 个字典来填充 1 个表中的数据,如下图所示。

Table to fill

2个字典循环填充,最后我编写模板文档。 创建我的词典的输入文档是用 SQL 编写的 DB 提取。 我的主要问题是当我想用 2 个不同词典中的数据填充表格时。 在下面的代码中,我将举例说明其中包含值的 2 个字典。

# -*- coding: utf8 -*-
#
#
from docxtpl import DocxTemplate                        
if __name__ == "__main__":
    document = DocxTemplate("template.docx")
    DicoOccuTable = {'`num_carnet_adresses`': '`annuaire_telephonique`\n`carnet_adresses`\n`carnet_adresses_complement', 
    '`num_eleve`': '`CFA_apprentissage_ctrl_coherence`\n`CFA_apprentissage_ctrl_examen`}
    DicoChamp = {'`num_carnet_adresses`': 72, '`num_eleve`': 66}
    template_values = {}
    #
    template_values["keys"] = [[{"name":cle, "occu":val} for cle,val in DicoChamp.items()],
    [{"table":vals} for cles,vals in DicoOccuTable.items()]]
    # 
    document.render(template_values)
    document.save('output/' + nomTable.replace('`','') + '.docx')  

结果,表格的两行被创建了,但里面没有写任何东西...... 我想补充一点,我在 Python 上工作只有 1 周,所以我觉得我没有正确管理这里的不同对象。 如果您有任何建议可以帮助我,我将不胜感激!

我在这里放了循环来创建字典,它可以帮助你理解我为什么编码错误:)

for c in ChampList:
        with open("db_reference.sql", "r") as f:
            listTable = []
            line = f.readlines()
            for l in line:
                if 'CREATE TABLE' in l:
                    begin = True
                    linecreateTable = l
                    x = linecreateTable.split()
                    nomTable = x[2]
                elif c in l and begin == True:
                    listTable.append(nomTable)
                elif ') ENGINE=MyISAM DEFAULT CHARSET=latin1;' in l:    
                    begin = False
            nbreOccu=len(listTable)
            Tables = "\n".join(listTable)
            DicoChamp.update({c:nbreOccu})
            DicoOccuTable.update({c:Tables})
            # DicoChamp = {c:nbreOccu}
            template_values = {}

非常感谢!

【问题讨论】:

  • 终于找到了解决这个问题的办法。在这里。

标签: python ms-word jinja2 word-template


【解决方案1】:

我终于找到了解决这个问题的方法。这里是。 我没有使用 2 个字典,而是使用这种结构创建了 1 个字典:

Dico = { Champ : [Occu , Tables] }

创建表格的完整代码如下:

from docxtpl import DocxTemplate 
document = DocxTemplate("template.docx")
template_values = {}
Context = {}
for c in ChampList:
    listTable = []
    nbreOccu = 0
    OccuTables = []
    with open("db_reference.sql", "r") as g:
        listTable = []
        ligne = g.readlines()
        for li in ligne:
            if 'CREATE TABLE' in li:
                begin = True
                linecreateTable2 = li
                y = linecreateTable2.split()
                nomTable2 = y[2]
            elif c in li and begin == True:
                listTable.append(nomTable2)
            elif ') ENGINE=MyISAM DEFAULT CHARSET=latin1;' in li:    
                begin = False
            elif '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' in li:
                nbreOccu=len(listTable)
                inter = "\n".join(listTable)
                OccuTables.append(nbreOccu)
                OccuTables.append(inter)
                ChampNumPropre = c.replace('`','')
                Context.update({ChampNumPropre:OccuTables})
            else:
                continue
    template_values["keys"] = [{"label":cle, "cols":val} for cle,val in Context.items()]
# 
document.render(template_values)
document.save('output/' + nomTable.replace('`','') + '.docx') 

我使用了一个结构如下的表格:

希望你能在这里找到答案,祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多