pro*_*bat 2 python ms-word pywin32 win32com
我正在使用 pywin32 模块中的 win32com.client 来接受 word 文档中的所有跟踪更改(Windows 10 64 位上的 Python 3.6.4)。
具体来说,我使用的代码如下:
import win32com.client as win32
word = win32.gencache.EnsureDispatch("Word.Application")
word.Visible = False
doc = word.Documents.Open(PATH TO WORD FILE)
doc.Activate()
word.ActiveDocument.TrackRevisions = False # Maybe not need this
try:
word.WordBasic.AcceptAllChangesInDoc()
except TypeError:
pass
word.ActiveDocument.Save()
doc.Close(False)
word.Application.Quit()
Run Code Online (Sandbox Code Playgroud)
我有两个问题。
1.) 有没有比使用 try-except 块更好的方法来接受所有更改?使用此方法会产生 TypeError,因此需要一个 try-except 块来完成程序。
2.) 你知道如何删除用户留下的评论吗?
这是使用Python 2.7的代码(我假设它也适用于Python 3.6.4 - 我还不熟悉2.X和3.X之间的变化)
#!/usr/bin/env python3
import win32com.client as win32
path_file_name = "YourPath\ToYour\doc.docx"
word = win32.gencache.EnsureDispatch("Word.Application")
word.Visible = False
doc = word.Documents.Open(path_file_name )
doc.Activate()
word.ActiveDocument.TrackRevisions = False # Maybe not need this (not really but why not)
# Accept all revisions
word.ActiveDocument.Revisions.AcceptAll()
# Delete all comments
if word.ActiveDocument.Comments.Count >= 1:
word.ActiveDocument.DeleteAllComments()
word.ActiveDocument.Save()
doc.Close(False)
word.Application.Quit()
Run Code Online (Sandbox Code Playgroud)
让我知道它是否适合你。