How can I force python(using win32com) to create a

2019-03-25 19:39发布

问题:

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:

Why don't you do it like this?

from win32com import client
excel=client.Dispatch("Excel.Application")


回答2:

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)


标签: python excel com