Iron Python read/write data to Microsoft Word (*.doc) files?

python

(Andre Agi) #1

I’m trying to create/populate a Word document .docx file with data from grasshopper.
What I’ve found is this code for ironpython: https://gist.github.com/ejstembler/1049552

But when the script is executed, the text is replaced in the document only if I have the [textfield] in a single row. It doesn’t work if I put each field on a new row.
Anyone know what might is wrong with the script?

My python code:

import sys
import clr
import os
import System
from System import DateTime
import time
clr.AddReference("Microsoft.Office.Interop.Word")
import Microsoft.Office.Interop.Word as Word

source_filename = "C:\Python27\Template.docx"
destination_filename = "C:\Python27\Result.docx"

missing = System.Type.Missing 
replaceAll = Word.WdReplace.wdReplaceAll


word_application = Word.ApplicationClass()
word_application.Visible = False
document = word_application.Documents.Open(source_filename)
print document.StoryRanges

tokens = ["[Today]", "[First Name]", "[Last Name]", "[Company Name]", "[Address1]"] # etc...
values = [DateTime.Now, 'Eric', 'Jonsson', 'Spotify', 'Bridgestreet 1']

for i in range(len(tokens)):
    for r in document.StoryRanges:
        print "i = %d, tokens[i] = %s, values[i] = %s" % (i, tokens[i], values[i])
        r.Find.Text = tokens[i]
        r.Find.Replacement.Text = values[i]
        r.Find.Wrap = Word.WdFindWrap.wdFindContinue
        r.Find.Execute(missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, replaceAll, missing, missing, missing, missing)

document.SaveAs(destination_filename)
document.Close()
print 'saved'
document = None

word_application.Quit()
word_application = None

My Word Document Template.docx
This does not work

<< Template.docx >>
[Today]
[First Name]
[Last Name]
[Company Name]
[Address1]

<< Result.docx >>
[Today]
[First Name]
[Last Name]
[Company Name]
[Address1]

THIS WORKS!! - WHY?

<< Template.docx >>
[Today], [First Name] [Last Name], [Company Name], [Address1]

<< Result.docx >>

2018-04-30, Eric Jonsson, Spotify, Bridgestreet 1


(Dale Fugier) #2

Hi @agi.andre,

If could be that this code sample is, well, junk.

If you Google, you should be able to find plenty of examples of folk using C# to read and write Word files. Since this is all .NET, you should be able to port this samples to IronPython without too much effort.

– Dale