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

1586010002-jmsa.png

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

I have two questions.

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.) Do you know how you can delete comments left from users?

解决方案

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 = "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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值