使用 时win32com
,请记住您正在与 Word 对象模型对话。您无需了解很多 VBA 或其他语言即可将示例应用到使用 Python;你只需要弄清楚对象模型的哪些部分正在被使用。
让我们采用以下示例(在 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 对象模型的一些链接:
一些 Python 示例: