简体   繁体   English

Python - 使用win32com.client接受Word文档中的所有更改

[英]Python - Using win32com.client to accept all changes in Word Documents

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). 我正在使用pywin32模块中的win32com.client来接受word文档中的所有跟踪更改(Windows 10 64位上的Python 3.6.4)。

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()

I have two questions. 我有两个问题。

1.) Is there a better way to accept all changes rather than using the try-except block? 1.)是否有更好的方法来接受所有更改而不是使用try-except块? Using this method produces a TypeError so a try-except block is required to finish the program. 使用此方法会产生TypeError,因此需要try-except块来完成程序。

2.) Do you know how you can delete comments left from users? 2.)您知道如何删除用户留下的评论吗?

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 ) 这是一个使用Python 2.7的代码(我假设它也适用于Python 3.6.4 - 我不熟悉2.X3.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()

Let me know if it works out for you. 如果它适合您,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM