问题
I'm automating some excel related tasks which take a long time.
I'm creating an excel instance using:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
however, after the script starts running, if i select an open excel workbook(not the one python is working on), The python script crashes. However, if I open a new excel workbook and type stuff into it, the python script is unaffected.
Is there a particular way I can call excel to prevent this from happening? Or any other solution?
EDIT: This seems to work.
excel = win32.DispatchEx('Excel.Application')
回答1:
Here's a way to create a new instance and use static cache (which is faster and gives an ability to use kwargs):
from win32com.client import gencache
import pythoncom
clsid = "Word.Application"
clsid = pythoncom.CoCreateInstanceEx(clsid, None, pythoncom.CLSCTX_SERVER,
None, (pythoncom.IID_IDispatch,))[0]
if gencache.is_readonly:
#fix for "freezed" app: py2exe.org/index.cgi/UsingEnsureDispatch
gencache.is_readonly = False
gencache.Rebuild()
olApp = gencache.EnsureDispatch(clsid)
回答2:
Why don't you do it like this?
from win32com import client
excel=client.Dispatch("Excel.Application")
来源:https://stackoverflow.com/questions/5310255/how-can-i-force-pythonusing-win32com-to-create-a-new-instance-of-excel