如何强制python(使用win32com)创建Excel的新实例? [英] How can I force python(using win32com) to create a new instance of excel?
问题描述
我正在自动化一些需要很长时间的与excel相关的任务。
I'm automating some excel related tasks which take a long time.
我正在使用以下方法创建excel实例:
I'm creating an excel instance using:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
但是,脚本开始运行后,如果我选择一个打开的excel工作簿(而不是一个python正在工作),则python脚本崩溃。但是,如果我打开一个新的excel工作簿并在其中输入内容,则python脚本不会受到影响。
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.
有没有一种特殊的方式可以调用excel来防止这种情况的发生?还是其他解决方案?
Is there a particular way I can call excel to prevent this from happening? Or any other solution?
编辑:这似乎可行。
excel = win32.DispatchEx('Excel.Application')
推荐答案
这是创建新实例并使用静态缓存的一种方法(更快,并且可以使用kwargs):
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(使用win32com)创建Excel的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!