MS Word r / w in python, Python-docx problem and win32com links?

Recently, I experimented with various APIs for managing MS Word files (now written). For now, I need a simple API for writing python. I tried the win32com module, which turned out to be very reliable with no examples for python online (very little knowledge of VB and C to be able to translate examples from MSDN).

I tried using python-docx, but after installation I get this trace for any docx function.

Traceback (most recent call last):
  File "C:\filepath.py", line 9, in <module>
    ispit = newdocument()
NameError: name 'newdocument' is not defined

I am having trouble installing lxml by source and using easy_install. He checked the binaries libxlm2 and libxslt. I downloaded them and added paths to the environment, but the installation source or easy_install stopped every time.

Finally, I used the unofficial python extension package from this Link site . The installation was quick and there were no errors at the end.

Is there something I can do to make docx work and are there any python win32com links on the internet? I could not find. (except MSDN (VB not python) and O'Reily Python Programming on win32 )

+2
source share
1 answer

When using, win32comremember that you are talking to the Word object model. You do not need to know a lot of VBA or other languages ​​to apply the patterns to using Python; you just need to figure out which parts of the object model are used.

( VBA), Application, :

Public Sub NewWordApp()

    'Create variables to reference objects
    '(This line is not needed in Python; you don't need to declare variables 
    'or their types before using them)
    Dim wordApp As Word.Application, wordDoc As Word.Document

    'Create a new instance of a Word Application object
    '(Another difference - in VBA you use Set for objects and simple assignment for 
    'primitive values. In Python, you use simple assignment for objects as well.)
    Set wordApp = New Word.Application

    'Show the application
    wordApp.Visible = True

    'Create a new document in the application
    Set wordDoc = wordApp.Documents.Add()

    'Set the text of the first paragraph
    '(A Paragraph object doesn't have a Text property. Instead, it has a Range property
    'which refers to a Range object, which does have a Text property.)
    wordDoc.Paragraphs(1).Range.Text = "Hello, World!"

End Sub

Python :

import win32com.client

#Create an instance of Word.Application
wordApp = win32com.client.Dispatch('Word.Application')

#Show the application
wordApp.Visible = True

#Create a new document in the application
wordDoc = wordApp.Documents.Add()

#Set the text of the first paragraph
wordDoc.Paragraphs(1).Range.Text = "Hello, World!"

Word:

  • object
  • object

Python:

+8

All Articles