python - python 中的 MS Word r/w、Python-docx 问题和 win32com 引用?

标签 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

我在通过源代码和 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 对象模型的一些链接:

一些 Python 示例:

关于python - python 中的 MS Word r/w、Python-docx 问题和 win32com 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509207/

相关文章:

Python ctypes 和没有足够的参数(缺少 4 个字节)

python - 如何在 PySNMP 中进行单个 GETNEXT 查询

python - Python中迭代器的最后N个元素以外的所有元素

c# - 在不破坏字段的情况下设置 Range.Text?

vba - 使用 VBA 在 MS Word 中创建表格

php - 使用 PHP 从 MS Word 文档中提取图像的最简单方法?

python - 像 openpyxl 或 xlrd/xlwt 这样的第三方库有什么,win32com 没有什么?

python - 使用 Python 自动比较 Word 文档

python - (Python) 如果数据类型不是数字,则使变量等于 0

Python win32com outlook 附加文件与 "insert as text"方法