如何使用MailMerge用python填写单词模板?

时间:2018-12-14 23:27:25

标签: python mailmerge

我有一个带有MergeFields key1,key2,key3 .....的Word文件,我想在每个MergeField分别用values1,values2,values3 ....预填充此Word文档。如果我像这样显式地写出这些值,则可以很好地工作

 with MailMerge(file_path_with_old_name) as document:
    document.merge(
         key1 = value1, 
         key2 = value2,
         key3 = value3
         ....)
    document.write(file_path_with_new_name)

但是我希望能够将字典传递给MailMerge,而不必将其写出来。键将是单词document MergeFields,值将替换它们,即key1被value1替换:

a = { key1:value1, key2:value2, key3:value3.....}
with MailMerge(file_path_with_old_name) as document:
     document.merge(a)
     document.write(file_path_with_new_name)

我发现这个问题(How do I get a python dictionary into a document merge as kwargs with docx-mailmerge)似乎在问我同样的问题,他们建议在字典前放置**,但是当我这样做时,出现以下错误

 File "C:/Python_All/python_scripts/data_gather_2.0.py", line 151, in template_manipulation
document.merge(**all_fields_full) # merges documents  note that the ** is critical it  unpacks the dictionary

 File "C:\Python_All\Anaconda\lib\site-packages\mailmerge.py", line 179, in merge
self.__merge_field(part, field, replacement)

 File "C:\Python_All\Anaconda\lib\site-packages\mailmerge.py", line 191, in __merge_field
text_parts = text.replace('\r', '').split('\n')

 AttributeError: 'tuple' object has no attribute 'replace'

0 个答案:

没有答案