【问题标题】:How do I get a python dictionary into a document merge as kwargs with docx-mailmerge如何使用 docx-mailmerge 将 python 字典作为 kwargs 合并到文档中
【发布时间】:2019-04-05 03:12:04
【问题描述】:

所以我有这本词典

mydict = {'name': 'Theo', 'age': '39', 'gender': 'male', 'eyecolor': 'brown'}

我使用 docx-mailmerge 将这些数据合并到一个 word 文档中。

template = "myworddoc.docx"
newdoc = "mergeddoc.docx"
document = MailMerge(template)
document.merge(mydict)
document.write(newdoc)

但是创建的文档是空的。我猜它只适用于 kwargs??

我只能使用与 kwargs 的合并吗

document.merge(name='Theo', age='39', gender='male', eyecolor='brown')

我真的很喜欢用字典来合并数据。

我是否将 dict 转换为 kwarg(以及如何执行此操作)还是使用 dict?

感谢您的帮助!

【问题讨论】:

    标签: python dictionary ms-word docx-mailmerge


    【解决方案1】:

    不确定正式名称是什么,但我称之为“爆炸”运算符。

    document.merge(**mydict)
    

    这会将dict 解包到函数/方法的关键字参数中。

    例子:

    def foo_kwargs(a=1, b=2, c=3):
        print(f'a={a} b={b} c={c}')
    
    my_dict = {'a': 100, 'b': 200, 'c': 300}
    foo_kwargs(**my_dict)
    # Prints a=100 b=200 c=300
    

    注意还有 args explode:

    mylist = [1,2,3,4]
    
    def foo_args(a, b, c, d):
        print(a, b, c ,d)
    
    foo_args(*mylist)
    # Prints 1 2 3 4
    

    【讨论】:

      【解决方案2】:

      在将 dict 传递给 Mailmerge 对象时使用 merge_pages 方法:document.merge_pages([mydict])

      # keys = your mergefield names, values = what you want to insert into each mergefield
      mydict = {'name': 'Theo', 'age': '39', 'gender': 'male', 'eyecolor': 'brown'}
      
      template = "myworddoc.docx"
      newdoc = "mergeddoc.docx"
      document = MailMerge(template)
      
      print([i for i in document.get_merge_fields()] # Verify your merge fields exist
      document.merge_pages([mydict])
      document.write(newdoc)
      document.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 2019-05-16
        • 2016-01-02
        • 2018-09-23
        相关资源
        最近更新 更多