首页 > 解决方案 > 如何访问以编辑已打开的 DOCX(在 python 中使用 win32com.client)

问题描述

我想在以前打开的 MS Docx (如 VS 脚本)中制作一些“魔法”,但我不知道该怎么做。在 Dispatch 之后,我只看到了像“word.Documents.Open”这样的例子。

我可以用 excel 来做(我可以“即时”访问打开的 MS Excel 文件),例如:

from win32com.client import Dispatch
xl = Dispatch("Excel.application")
xl.Visible = True
xl.Sheets["Action"].Select
current=xl.Sheets["Action"]
...

我如何在 MS Word 中也能做到这一点?

我希望我是可以理解的。谢谢,

标签: python

解决方案


最后我得到了它。关键是:“word.ActiveDocument”

这是代码:

from win32com.client import Dispatch

word = Dispatch('Word.Application')
word.Visible = 1
doc=word.ActiveDocument

for word_t in doc.Words:
     print(word_t)  

推荐阅读