Can#39;t close Excel completely using win32com on Python(无法在 Python 上使用 win32com 完全关闭 Excel)
问题描述
这是我的代码,我为 VBA、.NET 框架找到了很多答案,并且是很奇怪.当我执行此操作时,Excel 将关闭.
This is my code, and I found many answers for VBA, .NET framework and is pretty strange. When I execute this, Excel closes.
from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wbs.Close()
excel.Quit()
wbs = None
excel = None # <-- Excel Closes here
但是当我执行以下操作时,它并没有关闭.
But when I do the following, it does not close.
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 !!!
我在 Stack Overflow 问题中找到了一些可能的答案 Excel 进程在互操作后保持打开状态;传统方法不起作用.问题是那不是 Python,我没有找到 Marshal.ReleaseComObject 和 GC.我查看了 ...site-packages/win32com 和其他网站上的所有演示.
I found some possible answer in Stack Overflow question Excel process remains open after interop; traditional method not working. The problem is that is not Python, and I don't find Marshal.ReleaseComObject and GC. I looked over all the demos on ...site-packages/win32com and others.
如果我能得到 PID 并杀死它,即使它不会打扰我.
Even it does not bother me if I can just get the PID and kill it.
我在 根据窗口名杀死进程(win32).
可能不是正确的方法,但解决方法是:
May be not the proper way, but a workround is:
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!!!
推荐答案
试试这个:
wbs.Close()
excel.Quit()
del excel # this line removed it from task manager in my case
这篇关于无法在 Python 上使用 win32com 完全关闭 Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在 Python 上使用 win32com 完全关闭 Excel
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
