How can I force python(using win32com) to create a new instance of excel?

吃可爱长大的小学妹 提交于 2019-12-18 15:33:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!