python win32 COM closing excel workbook

后端 未结 3 904
猫巷女王i
猫巷女王i 2020-12-09 05:52

I open several different workbooks (excel xlsx format) in COM, and mess with them. As the program progresses I wish to close one specific workbook but keep the rest open.

相关标签:
3条回答
  • 2020-12-09 06:05

    You can also try to use the following code:

    excel = Dispatch("Excel.Application")
    excel.Visible = False
    workbook = excel.Workbooks.Open(fileName)
    
    # with saving
    excel.DisplayAlerts = False
    if saveAs:
        excel.ActiveWorkbook.SaveAs(fullFileNameToSave)
    else:
        excel.ActiveWorkbook.Save()
    excel.Quit()
    
    #without saving
    
    map(lambda book: book.Close(False), excel.Workbooks)
    excel.Quit()
    
    0 讨论(0)
  • 2020-12-09 06:14

    The the Workbook COM object has a Close() method. Basically, it should be something like:

    xl = Dispatch('Excel.Application')
    wb = xl.Workbooks.Open('New Workbook.xlsx')
    # do some stuff
    wb.Close(True) # save the workbook
    

    The above was just a skeleton here's some code that works on my machine against Office 2010:

    from win32com.client import Dispatch
    xl = Dispatch('Excel.Application')
    wb = xl.Workbooks.Add()
    ws = wb.Worksheets.Add()
    cell = ws.Cells(1)
    cell.Value = 'Some text'
    wb.Close(True, r'C:\Path\to\folder\Test.xlsx')
    

    Of course, that creates a new xlsx file. But then I'm able to successfully open and modify the file in the same session as follows:

    wb = xl.Workbooks.Open(r'C:\Path\to\folder\Test.xlsx')
    ws = wb.Worksheets(1)
    cell = ws.Cells(2)
    cell.Value = 'Some more text'
    wb.Close(True)
    

    Don't know if any of that helps...

    0 讨论(0)
  • 2020-12-09 06:30
    import os
    
    def closeFile():
    
        try:
            os.system('TASKKILL /F /IM excel.exe')
    
        except Exception:
            print("KU")
    
    closeFile()
    

    I have searched it and tested it, Very useful

    0 讨论(0)
提交回复
热议问题