最近我正在尝试使用不同的 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
我在通过源代码和 easy_install 安装 lxml 时遇到了一些问题。它正在检查 libxlm2 和 libxslt 二进制文件。我下载了它们并添加了环境路径,但安装槽源或 easy_install 每次都停止。
最后我使用了来自该站点的非官方 python 扩展包 Link . 安装很快,最后没有出错。
我可以做些什么来使 docx 正常工作,是否有一些与 python win32com 相关的在线引用资料?我找不到任何。 (除了 MSDN(VB 不是 python)和 O'Reily's Python programming on win32 )
最佳答案
使用 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 对象模型的一些链接:
- Application对象
- Documents收藏
- Document对象
- Paragraphs收藏
- Paragraph对象
- Range对象
- Concepts
一些 Python 示例:
关于python - python 中的 MS Word r/w、Python-docx 问题和 win32com 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509207/