python3和pywin32关闭excel

时间:2017-07-27 02:57:34

标签: python python-3.x pywin32 win32com

使用Dispatch后,我遇到了关闭excel的问题。

import openpyxl
import os 
from win32com import client



class CTAutomation:

    def __init__(self, file):
        self.invoice = xl.load_workbook(os.getcwd() + "\Templates\ctrates.xlsx")
        self.xlTemplate = xl.load_workbook(os.getcwd() + "\Templates\invoiceTemplate.xlsx")
        self.vpc = xl.load_workbook(os.getcwd() + "\Templates\Vpc.xlsx")
        self.file = file

    def invoice_make(self):
        self.xlApp = client.Dispatch("Excel.Application")
        self.xlbook = self.xlApp.Workbooks.Open(os.getcwd() + '\TestFiles\\' + self.file)
        self.ws = self.xlbook.Worksheets[0]
        self.ws.Visible = 1
        self.ws.ExportAsFixedFormat(0, os.getcwd() + "\complitedpdf\\" + self.file + ".pdf")
        self.quit()

    def quit(self):
        self.xlbook.Close()
        self.xlApp.Quit()

    def xlformater(self):
        return None

def main():
    pwd = os.listdir(os.getcwd() + "\TestFiles")
    for file in pwd:
        CTAutomation(file.strip(".xlsx")).invoice_make()

if __name__ == "__main__":
    main()

直到这部分一切顺利。我在论坛上发现了一些关于这个主题的帖子,但我觉得我仍然缺少关闭应用程序的东西, 示例中的.xlsx and xls(Latest Versions) to pdf using python

一些建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

本质上,它是持久存储在内存中的类对象。考虑使用with()将流程包装在上下文管理器中。并在上下文中调用invoice_make()

此外,通过使用方括号将工作簿索引为零,您的Excel方法不正确。

最后,考虑使用os.path.join()来回避或转发斜杠,并使用try/except块来捕获COM异常并从内存中正确释放对象。

import openpyxl as xl
import os 
from win32com import client

cwd = os.getcwd()

class CTAutomation:

    def __init__(self):
        self.invoice = xl.load_workbook(os.path.join(cwd, "Templates", "ctrates.xlsx"))
        self.xlTemplate = xl.load_workbook(os.path.join(cwd, "Templates", "invoiceTemplate.xlsx"))
        self.vpc = xl.load_workbook(os.path.join(cwd, "Templates", "Vpc.xlsx"))

    def invoice_make(self, file):
        try:
            self.xlApp = client.Dispatch("Excel.Application")
            self.xlbook = self.xlApp.Workbooks.Open(os.path.join(cwd, "TestFiles", file))
            self.ws = self.xlbook.Worksheets(1)       # USE PARENTHESES (NOT BRACKETS AND NON-ZERO INDEX)
            #self.ws.Visible = 1                      # KEEP PROCESS IN BACKGROUND
            self.ws.ExportAsFixedFormat(0, os.path.join(cwd, "complitedpdf", file.replace(".xlsx",".pdf")))
            self.xlbook.Close(False)
            self.xlApp.Quit()

        except Exception as e:
            print(e)

        finally:
            self.ws = None                            # RELEASE EXCEL OBJS FROM MEMORY
            self.xlbook = None
            self.xlApp = None

    def xlformater(self):
        return None

    def __enter__(self):
        return self                                   # BOUND TO as IN with()

    def __exit__(self, *err):
        return None

def main():
    pwd = os.listdir(os.path.join(cwd, "TestFiles"))   

    with CTAutomation() as obj:                       # CONTEXT MANAGER
        for file in pwd:
            print(file)
            obj.invoice_make(file)

if __name__ == "__main__":
    main()