Python - 使用 win32com.client 接受 Word 文档中的所有更改 [英] Python - Using win32com.client to accept all changes in Word Documents
问题描述
我正在使用 pywin32 模块中的 win32com.client 来接受 Word 文档中的所有跟踪更改(Windows 10 64 位上的 Python 3.6.4).
I'm using win32com.client from the pywin32 module to accept all tracked changes in a word document (Python 3.6.4 on Windows 10 64 bit).
具体来说,我使用的代码如下:
Specifically the code I'm using is the following:
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()
我有两个问题.
1.) 有没有比使用 try-except 块更好的方法来接受所有更改?使用此方法会产生一个 TypeError,因此需要一个 try-except 块来完成程序.
1.) Is there a better way to accept all changes rather than using the try-except block? Using this method produces a TypeError so a try-except block is required to finish the program.
2.) 您知道如何删除用户留下的评论吗?
2.) Do you know how you can delete comments left from users?
推荐答案
这里是使用 Python 2.7 的代码(我假设它适用于 Python 3.6.4 作为好吧 - 我还不熟悉 2.X 和 3.X) 之间的变化
Here is a code working with Python 2.7 (I assume it works with Python 3.6.4 as well - I'm not familiar yet with the change between 2.X and 3.X)
#!/usr/bin/env python3
import win32com.client as win32
path_file_name = "YourPathToYourdoc.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()
告诉我它是否适合您.
这篇关于Python - 使用 win32com.client 接受 Word 文档中的所有更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!