Python呼叫Win32com實現批量Office轉PDF
阿新 • • 發佈:2021-01-03
from win32com.client import Dispatch from os import walk import sys import fitz def doc2pdf(input_file): word = Dispatch('Word.Application') # WPS改為Kwps.Application output_file = input_file.split(".") try: doc = word.Documents.Open(input_file) doc.SaveAs(output_file[0] + ".pdf", FileFormat=17) doc.Close() except: print("Unexpected error:", sys.exc_info()) word.Quit() def ppt2pdf(input_file): powerpoint = Dispatch('Powerpoint.Application') # WPS改為Kwpp.Application output_file = input_file.split(".") try: ppt = powerpoint.Presentations.Open(input_file) ppt.SaveAs(output_file[0] + ".pdf", FileFormat=32) ppt.Close() except: print("Unexpected error:", sys.exc_info()) powerpoint.Quit() def xls2pdf(input_file): excel = Dispatch('Excel.Application') # WPS改為Ket.Application output_file = input_file.split(".") try: xls = excel.Workbooks.Open(input_file) xls.SaveAs(output_file[0] + ".pdf", FileFormat=57) xls.Close() except: print("Unexpected error:", sys.exc_info()) excel.Quit() if __name__ == "__main__": doc_files = [] directory = "C:\\Users\\Administrator\\Desktop\\" for root, dirs, filenames in walk(directory): for file in filenames: # 忽略~$開頭的臨時檔案,並以後綴名作為檔案型別判斷 if file.find("~$") == -1: if file.endswith(".doc") or file.endswith(".docx") or file.endswith(".DOC"): doc2pdf(str(root + "\\" + file)) elif file.endswith(".ppt") or file.endswith(".pptx") or file.endswith(".PPT"): ppt2pdf(str(root + "\\" + file)) elif file.endswith(".xls") or file.endswith(".xlsx") or file.endswith(".XLS"): xls2pdf(str(root + "\\" + file))