使用时
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.ApplicationwordApp = win32com.client.Dispatch('Word.Application')#Show the applicationwordApp.Visible = True#Create a new document in the applicationwordDoc = wordApp.documents.Add()#Set the text of the first paragraphwordDoc.Paragraphs(1).Range.Text = "Hello, World!"
Word对象模型的一些链接:
- 应用对象
- 文件收集
- 文件对象
- 段落集合
- 段落对象
- 范围对象
- 概念
一些Python示例:
- Python和Microsoft Office –使用PyWin32
- 使用Python通过PyWin32库解析Microsoft Word文档
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)