How can data be written to a Word template using Python?

To write data to a Word template, you can utilize the docx library in Python. This library is used for creating and modifying Microsoft Word documents.

Firstly, the docx library needs to be installed. You can install the docx library in the command line using the following command:

pip install python-docx

Next, you can use the following code to write data to a Word template:

from docx import Document

# 打开Word模板
doc = Document('template.docx')

# 查找并替换模板中的占位符
for paragraph in doc.paragraphs:
    if '<<name>>' in paragraph.text:
        paragraph.text = paragraph.text.replace('<<name>>', 'John Doe')
    if '<<age>>' in paragraph.text:
        paragraph.text = paragraph.text.replace('<<age>>', '30')

# 保存修改后的Word文档
doc.save('output.docx')

In the code above, we start by opening the Word template file (template.docx), then iterate through all the paragraphs using a loop. Within each paragraph, we can use the replace() method to substitute the placeholders in the template (< > and < >) with actual data. Finally, we use the save() method to save the modified Word document as output.docx.

Please note that the code above is just an example. Depending on the actual situation, you may need to replace the specific placeholders in the template.

bannerAds