Automating Comparison of Word Documents Using Python
I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:
import win32com.client
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
Document=Application.Documents.Add()
Application.CompareDocuments("Original.docx","Revised.docx")
But I am getting the following error:
Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
Application.CompareDocuments("Original.docx","Revised.docx")
File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
, CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings
File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)
TypeError: The Python instance can not be converted to a COM object
I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.
Thanks in Advance
python word-vba pywin32 win32com
add a comment |
I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:
import win32com.client
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
Document=Application.Documents.Add()
Application.CompareDocuments("Original.docx","Revised.docx")
But I am getting the following error:
Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
Application.CompareDocuments("Original.docx","Revised.docx")
File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
, CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings
File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)
TypeError: The Python instance can not be converted to a COM object
I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.
Thanks in Advance
python word-vba pywin32 win32com
add a comment |
I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:
import win32com.client
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
Document=Application.Documents.Add()
Application.CompareDocuments("Original.docx","Revised.docx")
But I am getting the following error:
Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
Application.CompareDocuments("Original.docx","Revised.docx")
File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
, CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings
File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)
TypeError: The Python instance can not be converted to a COM object
I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.
Thanks in Advance
python word-vba pywin32 win32com
I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:
import win32com.client
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
Document=Application.Documents.Add()
Application.CompareDocuments("Original.docx","Revised.docx")
But I am getting the following error:
Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
Application.CompareDocuments("Original.docx","Revised.docx")
File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
, CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings
File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)
TypeError: The Python instance can not be converted to a COM object
I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.
Thanks in Advance
python word-vba pywin32 win32com
python word-vba pywin32 win32com
asked Nov 9 '17 at 22:11
AngryMan14AngryMan14
12
12
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
The error is thrown because the arguments you pass in the function Application.CompareDocuments()
, being written such as "Original.docx" and "Revised.docx", are not a Document
object from the point of view of your python code.
You need to create these objects with the function Application.Documents.Open()
A code working for me is:
import win32com.client
path = "C:ThePathOfYourFolderWithYourDocuments\"
# note the \ at the end of the path name to prevent a SyntaxError
#Create the Application word
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
# Compare documents
Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
Application.Documents.Open(path + "Revised.docx"))
# Save the comparison document as "Comparison.docx"
Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
# Don't forget to quit your Application
Application.Quit()
The you have your Comparison.docx you can open to check.
Let me know if it works for you.
add a comment |
Ben. T's answer works. I would include:
Application.ActiveDocument.ActiveWindow.View.Type = 3
before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).
add a comment |
I created a more versatile version of this with path and file checks, if someone wants it...
#!/usr/bin/python3
# This uses win32com to automate the comparison of two Microsoft Word files.
# Make sure to have win32com installed for your environment and python version:
# https://github.com/mhammond/pywin32/releases
# Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python
from os import getcwd, path
from sys import argv, exit
from win32com import client
def die(message):
print (message)
exit(1)
def cmp(original_file, modified_file):
dir = getcwd() + '\'
print('Working...')
# some file checks
if not path.exists(dir+original_file):
die('Original file does not exist')
if not path.exists(dir+modified_file):
die('Modified file does not exist')
cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
if path.exists(cmp_file):
die('Comparison file already exists... abortingnRemove or rename '+cmp_file)
# actual Word automation
app = client.gencache.EnsureDispatch("Word.Application")
app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.ActiveDocument.SaveAs(cmp_file)
print('Saved comparison as: '+cmp_file)
app.Quit()
def main():
if len(argv) != 3:
die('Usage: wrd_cmp <original_file> <modified_file>')
cmp(argv[1], argv[2])
if __name__ == '__main__':
main()
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47212459%2fautomating-comparison-of-word-documents-using-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
The error is thrown because the arguments you pass in the function Application.CompareDocuments()
, being written such as "Original.docx" and "Revised.docx", are not a Document
object from the point of view of your python code.
You need to create these objects with the function Application.Documents.Open()
A code working for me is:
import win32com.client
path = "C:ThePathOfYourFolderWithYourDocuments\"
# note the \ at the end of the path name to prevent a SyntaxError
#Create the Application word
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
# Compare documents
Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
Application.Documents.Open(path + "Revised.docx"))
# Save the comparison document as "Comparison.docx"
Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
# Don't forget to quit your Application
Application.Quit()
The you have your Comparison.docx you can open to check.
Let me know if it works for you.
add a comment |
The error is thrown because the arguments you pass in the function Application.CompareDocuments()
, being written such as "Original.docx" and "Revised.docx", are not a Document
object from the point of view of your python code.
You need to create these objects with the function Application.Documents.Open()
A code working for me is:
import win32com.client
path = "C:ThePathOfYourFolderWithYourDocuments\"
# note the \ at the end of the path name to prevent a SyntaxError
#Create the Application word
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
# Compare documents
Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
Application.Documents.Open(path + "Revised.docx"))
# Save the comparison document as "Comparison.docx"
Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
# Don't forget to quit your Application
Application.Quit()
The you have your Comparison.docx you can open to check.
Let me know if it works for you.
add a comment |
The error is thrown because the arguments you pass in the function Application.CompareDocuments()
, being written such as "Original.docx" and "Revised.docx", are not a Document
object from the point of view of your python code.
You need to create these objects with the function Application.Documents.Open()
A code working for me is:
import win32com.client
path = "C:ThePathOfYourFolderWithYourDocuments\"
# note the \ at the end of the path name to prevent a SyntaxError
#Create the Application word
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
# Compare documents
Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
Application.Documents.Open(path + "Revised.docx"))
# Save the comparison document as "Comparison.docx"
Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
# Don't forget to quit your Application
Application.Quit()
The you have your Comparison.docx you can open to check.
Let me know if it works for you.
The error is thrown because the arguments you pass in the function Application.CompareDocuments()
, being written such as "Original.docx" and "Revised.docx", are not a Document
object from the point of view of your python code.
You need to create these objects with the function Application.Documents.Open()
A code working for me is:
import win32com.client
path = "C:ThePathOfYourFolderWithYourDocuments\"
# note the \ at the end of the path name to prevent a SyntaxError
#Create the Application word
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
# Compare documents
Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
Application.Documents.Open(path + "Revised.docx"))
# Save the comparison document as "Comparison.docx"
Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
# Don't forget to quit your Application
Application.Quit()
The you have your Comparison.docx you can open to check.
Let me know if it works for you.
answered Mar 5 '18 at 16:39
Ben.TBen.T
6,0272625
6,0272625
add a comment |
add a comment |
Ben. T's answer works. I would include:
Application.ActiveDocument.ActiveWindow.View.Type = 3
before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).
add a comment |
Ben. T's answer works. I would include:
Application.ActiveDocument.ActiveWindow.View.Type = 3
before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).
add a comment |
Ben. T's answer works. I would include:
Application.ActiveDocument.ActiveWindow.View.Type = 3
before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).
Ben. T's answer works. I would include:
Application.ActiveDocument.ActiveWindow.View.Type = 3
before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).
edited Nov 21 '18 at 23:32
Fabio Turati
2,57652138
2,57652138
answered Nov 21 '18 at 23:10
Zenon AndersonZenon Anderson
1
1
add a comment |
add a comment |
I created a more versatile version of this with path and file checks, if someone wants it...
#!/usr/bin/python3
# This uses win32com to automate the comparison of two Microsoft Word files.
# Make sure to have win32com installed for your environment and python version:
# https://github.com/mhammond/pywin32/releases
# Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python
from os import getcwd, path
from sys import argv, exit
from win32com import client
def die(message):
print (message)
exit(1)
def cmp(original_file, modified_file):
dir = getcwd() + '\'
print('Working...')
# some file checks
if not path.exists(dir+original_file):
die('Original file does not exist')
if not path.exists(dir+modified_file):
die('Modified file does not exist')
cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
if path.exists(cmp_file):
die('Comparison file already exists... abortingnRemove or rename '+cmp_file)
# actual Word automation
app = client.gencache.EnsureDispatch("Word.Application")
app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.ActiveDocument.SaveAs(cmp_file)
print('Saved comparison as: '+cmp_file)
app.Quit()
def main():
if len(argv) != 3:
die('Usage: wrd_cmp <original_file> <modified_file>')
cmp(argv[1], argv[2])
if __name__ == '__main__':
main()
add a comment |
I created a more versatile version of this with path and file checks, if someone wants it...
#!/usr/bin/python3
# This uses win32com to automate the comparison of two Microsoft Word files.
# Make sure to have win32com installed for your environment and python version:
# https://github.com/mhammond/pywin32/releases
# Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python
from os import getcwd, path
from sys import argv, exit
from win32com import client
def die(message):
print (message)
exit(1)
def cmp(original_file, modified_file):
dir = getcwd() + '\'
print('Working...')
# some file checks
if not path.exists(dir+original_file):
die('Original file does not exist')
if not path.exists(dir+modified_file):
die('Modified file does not exist')
cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
if path.exists(cmp_file):
die('Comparison file already exists... abortingnRemove or rename '+cmp_file)
# actual Word automation
app = client.gencache.EnsureDispatch("Word.Application")
app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.ActiveDocument.SaveAs(cmp_file)
print('Saved comparison as: '+cmp_file)
app.Quit()
def main():
if len(argv) != 3:
die('Usage: wrd_cmp <original_file> <modified_file>')
cmp(argv[1], argv[2])
if __name__ == '__main__':
main()
add a comment |
I created a more versatile version of this with path and file checks, if someone wants it...
#!/usr/bin/python3
# This uses win32com to automate the comparison of two Microsoft Word files.
# Make sure to have win32com installed for your environment and python version:
# https://github.com/mhammond/pywin32/releases
# Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python
from os import getcwd, path
from sys import argv, exit
from win32com import client
def die(message):
print (message)
exit(1)
def cmp(original_file, modified_file):
dir = getcwd() + '\'
print('Working...')
# some file checks
if not path.exists(dir+original_file):
die('Original file does not exist')
if not path.exists(dir+modified_file):
die('Modified file does not exist')
cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
if path.exists(cmp_file):
die('Comparison file already exists... abortingnRemove or rename '+cmp_file)
# actual Word automation
app = client.gencache.EnsureDispatch("Word.Application")
app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.ActiveDocument.SaveAs(cmp_file)
print('Saved comparison as: '+cmp_file)
app.Quit()
def main():
if len(argv) != 3:
die('Usage: wrd_cmp <original_file> <modified_file>')
cmp(argv[1], argv[2])
if __name__ == '__main__':
main()
I created a more versatile version of this with path and file checks, if someone wants it...
#!/usr/bin/python3
# This uses win32com to automate the comparison of two Microsoft Word files.
# Make sure to have win32com installed for your environment and python version:
# https://github.com/mhammond/pywin32/releases
# Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python
from os import getcwd, path
from sys import argv, exit
from win32com import client
def die(message):
print (message)
exit(1)
def cmp(original_file, modified_file):
dir = getcwd() + '\'
print('Working...')
# some file checks
if not path.exists(dir+original_file):
die('Original file does not exist')
if not path.exists(dir+modified_file):
die('Modified file does not exist')
cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
if path.exists(cmp_file):
die('Comparison file already exists... abortingnRemove or rename '+cmp_file)
# actual Word automation
app = client.gencache.EnsureDispatch("Word.Application")
app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.ActiveDocument.SaveAs(cmp_file)
print('Saved comparison as: '+cmp_file)
app.Quit()
def main():
if len(argv) != 3:
die('Usage: wrd_cmp <original_file> <modified_file>')
cmp(argv[1], argv[2])
if __name__ == '__main__':
main()
answered Dec 10 '18 at 13:52
paipai
67154
67154
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47212459%2fautomating-comparison-of-word-documents-using-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown