Excel und Python Win32COM

Hier ein kleines Beispiel, wie man mittels COM eine Excel-Mappe aus Python heraus befüllt und die Excel-Instanz beendet.

from win32com import client
 
# http://stackoverflow.com/questions/10221150/cant-close-excel-completely-using-win32com-on-python
def close_excel_by_force(excel):
    import win32process
    import win32gui
    import win32api
    import win32con
    import time
 
    # Get the window's process id's
    hwnd = excel.Hwnd
    t, p = win32process.GetWindowThreadProcessId(hwnd)
    # Ask window nicely to close
    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
    # Allow some time for app to close
    time.sleep(10)
    # If the application didn't close, force close
    try:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
        if handle:
            win32api.TerminateProcess(handle, 0)
            win32api.CloseHandle(handle)
    except:
        pass
 
# Öffne Referenz zu Excel
excel = client.Dispatch("Excel.Application")
 
# Wir wollen sehen, was geschieht
excel.Visible= True
 
# Öffne eine bestehende Arbeitsmappe (im selben Verzeichnis)
wb = excel.Workbooks.Open('C:/Users/john/doe/win32test.xlsx')
 
# Wähle das erste Arbeitsblatt aus
ws = wb.Worksheets(1)
 
# Wähle alle Zellen aus
excel.Cells.Select()
# Entferne den Zellschutz
excel.Selection.Locked = False
# Wähle die Spalten B bis E aus
excel.Range("B:E").Select()
# setze den Zellschutz
excel.Selection.Locked = True
 
# Schütze das Sheet mit einem Passwort
ws.Protect("password", True, True)
 
# Speichere ab
wb.Save()
 
# Schließe die Mappe
wb.Close()
 
# Close Excel
excel.Quit()
wb = None
wbs = None
 
close_excel_by_force(excel)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website