Dom*_*goj 3 python ms-word win32com
最近我正在尝试使用不同的API进行MS Word文件管理(现在写).在这一点上,我只需要一个简单的编写python API.我尝试了win32com模块,证明它非常强大,缺乏python在线的例子(很少有VB和C知识能够从MSDN翻译实例).
我尝试使用python-docx,但在安装后我得到任何docx函数的回溯.
Traceback (most recent call last):
File "C:\filepath.py", line 9, in <module>
ispit = newdocument()
NameError: name 'newdocument' is not defined
Run Code Online (Sandbox Code Playgroud)
我通过source和easy_install安装lxml时遇到了一些问题.它正在检查libxlm2和libxslt二进制文件.我下载了它们并添加了环境路径,但每次都停止安装槽源或easy_install.
最后我使用了这个站点链接的非官方python扩展包.安装速度很快,最终没有错误.
我可以做些什么来使docx工作,并且在线有一些python win32com相关参考吗?我找不到任何东西.(除了MSDN(VB不是python)和O'Reily在win32上的Python编程)
使用时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
Run Code Online (Sandbox Code Playgroud)
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!"
Run Code Online (Sandbox Code Playgroud)
一些指向Word对象模型的链接:
一些Python示例: