In this article, we will guide you through the process of creating a Python script to insert data into a Word text box. This can be useful for automating the process of filling out forms or adding the same information to multiple documents. We will be using the python-docx library, which allows you to create and manipulate Word documents using Python. If you don't have it installed, you can do so by running pip install python-docx in your terminal or command prompt.
First, let's start by importing the necessary libraries and creating a new Word document:
from docx import Document
document = Document()
Next, we will add a new text box to the document. The add_picture() method can be used to insert an image into the text box, but for this example, we will just add some text:
section = document.sections[0]
header = section.header
text_box = header.shapes.add_textbox(1.5, 1.5, 200, 100)
text_frame = text_box.textbox
text_frame.text = "Hello, World!"
In this example, we added the text box to the header of the document, but you can also add it to the body by using the document.add_paragraph() method instead of section.header.
Now, let's create a function to insert data into the text box:
def insert_data(text_box, data):
text_frame = text_box.textbox
text_frame.text = data
We can now use this function to insert data into the text box:
data = "This is some sample data."
insert_data(text_box, data)
Finally, let's save the document:
document.save("sample.docx")
Here is the complete code:
from docx import Document
document = Document()
section = document.sections[0]
header = section.header
text_box = header.shapes.add_textbox(1.5, 1.5, 200, 100)
text_frame = text_box.textbox
text_frame.text = "Hello, World!"
def insert_data(text_box, data):
text_frame = text_box.textbox
text_frame.text = data
data = "This is some sample data."
insert_data(text_box, data)
document.save("sample.docx")
This is just a simple example, but you can use this as a starting point for your own projects. The python-docx library offers a lot of functionality for working with Word documents, such as adding tables, images, and more. You can find more information and examples in the official documentation.
References
| Title | Link |
|---|---|
| python-docx | https://python-docx.readthedocs.io/en/latest/ |