How to fill form fields in Word automatically with pywin32 in python?

Jammmme 0 Reputation points
2023-02-23T13:04:05.2433333+00:00

I have a little problem to solve, but I don´t get an acceptable solution. I try to have a script that automaticcaly fills in FormFields in Word with entries of dictionaries. So far I used pywin32 for that task and somehow I managed to find a solution that works at all. At least as long as I update the word document.

The command that I use so far in a loop is "marks(i).Result = keyValue". Here "marks" is - as far as I understand - a formfields object, which I get by "marks = doc.FormFields".

As I said, all this works to some extent, but as soon as I update the document in Word, all entries disappear again.

Would be really great if someone could help me and knows how to make it that the entry remains permanent. Unfortunately I do not understand the documentation of pywin32 at all. Attached below is the whole function.

Thanks in advance!

def wordExport(window, excDict, docPath):
  
    wordApp = win32com.client.Dispatch('Word.Application') #Word App Object
    wordApp.Visible = False
    doc = wordApp.Documents.Open(docPath) #Open .docx
    marks = doc.FormFields # FormFields object
    cMarks = marks.Count # FormField count
    cMatches = 0 #Match counter
    cOverwrt = 0 #Fields overwritten

    for i in range(1, cMarks + 1):
        fieldName = str(marks(i).Name) #String object of FormField

        #Default Cases --------------------------------------------------------------------
        if fieldName in excDict:
            keyValue = excDict.get(fieldName) #Get value to key(FormField)
            resultIsEmpty = not marks(i).Result #No text has been entered before

            # No prior entry present
            if keyValue != "None"
                marks(i).Result = keyValue + " "
                cMatches += 1
                if not resultIsEmpty:
                    cOverwrt += 1

    doc.Close()
    wordApp.Visible = False
Word
Word
A family of Microsoft word processing software products for creating web, email, and print documents.
714 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alan Farias 750 Reputation points
    2023-02-24T16:29:21.5066667+00:00

    I know it might sound stupid, but have you ever tried something simple like:

    doc.Save()