sac*_*che 20 python com excel pywin32 win32com
这是我的代码,我找到了许多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
Run Code Online (Sandbox Code Playgroud)
但是,当我执行以下操作时,它不会关闭.
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 !!!
Run Code Online (Sandbox Code Playgroud)
我在Stack Overflow问题中找到了一些可能的答案.传统方法不起作用.问题是不是Python,我找不到Marshal.ReleaseComObject和GC.我查看了所有演示...site-packages/win32com和其他演示.
如果我能获得PID并杀死它,即使它也不会打扰我.
我在Kill进程中找到了一个基于窗口名称(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!!!
Run Code Online (Sandbox Code Playgroud)
小智 9
试试这个:
wbs.Close()
excel.Quit()
del excel # this line removed it from task manager in my case
Run Code Online (Sandbox Code Playgroud)
我使用 Excel 的文件中有以下内容:
self.excel.Application.Quit()
Run Code Online (Sandbox Code Playgroud)