Python: Add, Count, Retrieve and Remove Word Variables

2024-06-13 06:38:34 Written by  support iceblue
Rate this item
(0 votes)

When dealing with a large volume of customized documents such as contracts, reports, or personal letters, the variable feature in Word documents becomes crucial. Variables allow you to store and reuse information like dates, names, or product details, making the documents more personalized and dynamic. This article will delve into how to use Spire.Doc for Python to insert, count, retrieve, and delete variables in Word documents, enhancing the efficiency and flexibility of document management.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Window through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Window

Add Variables into Word Documents with Python

The way Word variables work is based on the concept of "fields". When you insert a variable into a Word document, what you're actually doing is inserting a field, which points to a value stored either in the document properties or an external data source. Upon updating the fields, Word recalculates them to display the most current information.

Spire.Doc for Python offers the VariableCollection.Add(name, value) method to insert variables into Word documents. Here are the detailed steps:

  • Create a Document object.
  • Call the Document.AddSection() method to create a new section.
  • Call the Section.AddParagraph() method to create a new paragraph.
  • Call the Paragraph.AppendField(fieldName, fieldType) method to add a variable field (FieldDocVariable) within the paragraph.
  • Set Document.IsUpdateFields to True to update the fields.
  • Save the document by Document.SaveToFile() method.
  • Python
from spire.doc import *

# Create a Document object
document = Document()

# Add a new section to the document
section = document.AddSection()

# Add a new paragraph within the newly created section
paragraph = section.AddParagraph()

# Append a FieldDocVariable type field named "CompanyName" to the paragraph
paragraph.AppendField("CompanyName", FieldType.FieldDocVariable)

# Add the variable to the document's variable collection
document.Variables.Add("CompanyName", "E-ICEBLUE")

# Update fields
document.IsUpdateFields = True

# Save the document to a specified path
document.SaveToFile("AddVariable.docx", FileFormat.Docx2016)

# Dispose the document
document.Dispose()

Python: Add, Count, Retrieve and Remove Word Variables

Count the Number of Variables in a Word Document with Python

Here are the detailed steps to use the Document.Variables.Count property to get the number of variables:

  • Create a Document object.
  • Call the Document.LoadFromFile() method to load the document that contains the variables.
  • Use the Document.Variables.Count property to obtain the number of variables.
  • Print the count in console.
  • Python
from spire.doc import *

# Create a Document object
document = Document()

# Load an existing document
document.LoadFromFile("AddVariable.docx")

# Get the count of variables in the document
count=document.Variables.Count

# Print to console
print(f"The count of variables:{count}")

Python: Add, Count, Retrieve and Remove Word Variables

Retrieve Variables from a Word Document with Python

Spire.Doc for Python provides the GetNameByIndex(int index) and GetValueByIndex(int index) methods to retrieve variable names and values by their indices. Below are the detailed steps:

  • Create a Document object.
  • Call the Document.LoadFromFile() method to load the document that contains the variables.
  • Call the Document.Variables.GetNameByIndex(index) method to obtain the variable name.
  • Call the Document.Variables.GetValueByIndex(index) method to obtain the variable value.
  • Call the Document.Variables.get_Item(name) to obtain variable value through the variable name.
  • Print the count in console.
  • Python
from spire.doc import *

# Create a Document object
document = Document()

# Load an existing document
document.LoadFromFile("AddVariable.docx")

# Obtain variable name based on index 0
name=document.Variables.GetNameByIndex(0)

# Obtain variable value based on index 0
value=document.Variables.GetValueByIndex(0)

# Obtain variable value through the variable name
value1=document.Variables.get_Item("CompanyName")

# Print to console
print("Variable Name:", name)
print("Variable Value:", value)

Python: Add, Count, Retrieve and Remove Word Variables

Delete Variables from a Word Document with Python

The VariableCollection.Remove(name) method can be used to delete a specified variable from the document, with the parameter being the name of the variable.

  • Create a Document object.
  • Call the Document.LoadFromFile() method to load the document that contains the variables.
  • Call the Document.Variables.Remove(name) method to remove the variable.
  • Set Document.IsUpdateFields to True to update the fields.
  • Save the document by Document.SaveToFile() method.
  • Python
from spire.doc import *

# Create a Document object
document = Document()

# Load an existing document
document.LoadFromFile("AddVariable.docx")

# Remove the variable named "CompanyName"
document.Variables.Remove("CompanyName")

# Update fields
document.IsUpdateFields=True

# Save the document
document.SaveToFile("RemoveVariable.docx",FileFormat.Docx2016)

# Dispose the document
document.Dispose()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 13 June 2024 06:51