1

I'm trying to automate Microsoft office word 2010 document using Python with win32 component. Over there I need to read and get the Header information of a WORD document. I had a look at MSDN library (and thought that getFieldNames could help me) and even had a look @Editing MS Word header with win32com (using this I can only edit the header information), but none of it worked for me.

My Code snippet is :

..//

#tell word to open the document
word.Documents.Open (IP_Directory_Dest + "\\" + name)

#open it internally
doc = word.Documents(1)

### get the header of file - using this gives me Attribute Error
## header = doc.getFieldNames() 
## print ('Header = ', header)

..//

Moreover when I'm using getFieldNames(), it gives an error "AttributeError: '' object has no attribute 'getFieldNames'", which make me believe that there is no such attribute like getFieldNames in object lib.

Any suggestions on this are most welcome.

Community
  • 1
  • 1
Varun
  • 107
  • 3
  • 10

1 Answers1

2

Got it. It should be something like this :

...///

#tell word to open the document
word.Documents.Open (IP_Directory_Dest + "\\" + copied_IR_file)

# store the header information
header_string = word.ActiveDocument.Sections(1).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range.Text

...///

Varun
  • 107
  • 3
  • 10
  • When I try your code I get "AttributeError: wdHeaderFooterPrimary". This is my script : .... import win32com.client .... word = win32com.client.Dispatch("Word.Application") ... word.Documents.Open ("C:\Users\ME\Desktop\Test\wordDOC.doc") .... header_string = word.ActiveDocument.Sections(1).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range.Text – Norfeldt May 08 '13 at 12:19
  • 1
    I was missing the word = win32com.client.gencache.EnsureDispatch("Word.Application") – Norfeldt May 08 '13 at 12:55
  • @Norfeldt : haven't tried reading table in the header as such. But, a suggestion which is worth trying: in case if you are stuck on how to write a equivalent python script for it, try recording a macro in word. Though it will be in Vb, but the commands name and syntax in WIN32 are pretty much the same in VB too. See if this could be of any help. Anyways i will also try from my end !!!! – Varun May 16 '13 at 17:50
  • thank you for your comment. I have already found the answer [here](http://stackoverflow.com/questions/16485343/reading-table-contet-in-header-and-footer-in-ms-word-file-using-python) – Norfeldt May 17 '13 at 06:44
  • assuming this link stays active, here's a working example of accessing headers: http://misc.martinbisson.com/tabs/convert.py – ecoe Apr 10 '14 at 15:18