这是我的代码,我为VBA、.NET 框架找到了很多答案,而且很奇怪。当我执行此操作时,Excel 将关闭。
from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wbs.Close()
excel.Quit()
wbs = None
excel = None # <-- Excel Closes here
但是当我执行以下操作时,它不会关闭。
excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wb = wbs.Open('D:\\Xaguar\\A1.xlsm')
wb.Close(False)
wbs.Close()
excel.Quit()
wb = None
wbs = None
excel = None # <-- NOT Closing !!!
我在堆栈溢出问题中找到了一些可能的答案Excel 进程在互操作后仍然打开;传统方法行不通。问题是那不是 Python,我找不到Marshal.ReleaseComObject
和GC
. 我查看了所有演示...site-packages/win32com
和其他演示。
如果我能得到PID并杀死它,即使它也不会打扰我。
我在Kill process based on window name (win32)中找到了一种解决方法。
可能不是正确的方法,但解决方法是:
def close_excel_by_force(excel):
import win32process
import win32gui
import win32api
import win32con
# 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
excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wb = wbs.Open('D:\\Xaguar\\A1.xlsm')
wb.Close(False)
wbs.Close()
excel.Quit()
wb = None
wbs = None
close_excel_by_force(excel) # <--- YOU #@#$# DIEEEEE!! DIEEEE!!!