[英]Python iteratively rendering docx templates to files
I'm trying to write a code that will automatically create documentation for me.我正在尝试编写一个自动为我创建文档的代码。 I'm using python-docx to fill in values in a docx template.我正在使用 python-docx 在 docx 模板中填写值。 I'm having issues with this specific section.我在这个特定部分有问题。 I want it to work such that on each word doc the 'DN' value will increase by 1 for however many documents I am producing.我希望它能够工作,以便在每个单词 doc 上,无论我生成多少文档,'DN' 值都会增加 1。
For example if the batch of docs I want was batch 123 and I wanted 4 separate copies of this document, I would want the following from 'DN':例如,如果我想要的文档批次是批次 123,并且我想要该文档的 4 个单独副本,我想要来自“DN”的以下内容:
123-1, 123-2, 123-3, 123-4, 123-1、123-2、123-3、123-4、
instead I'm getting the following:相反,我得到以下信息:
123-1, 123-1, 123-1, 123-1, 123-1、123-1、123-1、123-1、
This code works fine for the part at the bottom for saving the file name, it is just an issue with the dictionary section.此代码适用于底部用于保存文件名的部分,这只是字典部分的问题。 If someone could suggest a way to make this work it would be very much appreciated.如果有人可以提出一种方法来完成这项工作,将不胜感激。
for i in range(0, int(number_of_docs)):
Enters = {
'DN': f'{doc_number}-{+i + 1}',
'Quantity': number_of_docs,
'Date': date,
}
PN_doc.render(Enters)
PN_doc.save(f"{doc_number}-{+i + 1}.docx")
So the Object composition should work the way you implemented it.所以 Object 组合应该按照您实现它的方式工作。 For the document: ( maybe there's a neat way to copy the template - I'm not aware of any ).对于文档:(也许有一种复制模板的巧妙方法 - 我不知道任何)。 Just instantiating it for each iteration should also do the job只需为每次迭代实例化它也应该完成这项工作
from docxtpl import DocxTemplate
# number_of_docs = ...
# doc_number = ...
# date = ...
for i in range(int(number_of_docs)):
Enters = {
"DN": f"{doc_number}-{i+1}",
"Quantity": number_of_docs,
"Date": date
}
PN_doc = DocxTemplate("your_template.docx")
PN_doc.render(Enters)
PN_doc.save(f"{doc_number}-{i+1}.docx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.