Nerdycode
Nerdycode

Reputation: 1

How to deal with Pop-Ups during doc to docx/xls to xlsx conversions using win32

While converting a large number of old MS office documents, Pop-Ups asking for document passwords, permission to save a file without macros, or hinting that files contain comments or revisions occur regularly. Since they halt the conversion progress, I would like to automate responses to them.

I've tried to catch errors using exceptions, but those Pop-Ups don't raise exceptions. I have tried switching switched to pyexcel for excel files, which did work for password-protected files (aka raising an exception so I can skip the file and log), but most of the Pop-Ups come from Word anyways and there doesn't seem to be a word equivalent to pyexcel. I've also read about unoconv, but I would like to try to avoid using LibreOffice.

Here's my code (just the bit for Word files to keep it shorter):

import os
import win32com.client as win32

folder = "FOLDER_PATH"
word = win32.Dispatch("Word.application")

for subdir, dirs, files in os.walk(folder):
    for file in files:
        filename = os.fsdecode(file)
        path = os.path.join(subdir, filename)
        if filename.endswith(".doc") or filename.endswith(".DOC"):
            try:
                wordDoc = word.Documents.Open(path, False, False, False)
                wordDoc.SaveAs(path + 'x', FileFormat=16)  # FileFormat = 16 is .docx
                wordDoc.Close()
                with open('CONVERTED_FILES.txt','a') as f:
                    f.write(path + "\n")
            except Exception as ex:
                with open('CONVERSION_ERRORS.txt','a') as f:
                    if hasattr(ex, 'message'):
                        f.write(path + " Error: " + ex.message + "\n")
                    else:
                        f.write(path + " Error: " + str(ex) + "\n")

word.Application.Quit()

Upvotes: 0

Views: 19

Answers (0)

Related Questions