如何强制python(使用win32com)创建一个新的excel实例?

时间:2022-11-25 08:15:02

I'm automating some excel related tasks which take a long time.

我正在自动执行一些需要很长时间的excel相关任务。

I'm creating an excel instance using:

我正在使用以下方法创建一个excel实例:

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.

然而,在脚本开始运行后,如果我选择一个打开的excel工作簿(不是一个python正在处理),python脚本崩溃。但是,如果我打开一个新的excel工作簿并在其中键入内容,则python脚本不受影响。

Is there a particular way I can call excel to prevent this from happening? Or any other solution?

是否有一种特殊方式可以调用excel来防止这种情况发生?或任何其他解决方案?

EDIT: This seems to work.

编辑:这似乎工作。

excel = win32.DispatchEx('Excel.Application')

2 个解决方案

#1


1  

Why don't you do it like this?

你为什么不这样做?

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

#2


1  

Here's a way to create a new instance and use static cache (which is faster and gives an ability to use kwargs):

这是一种创建新实例并使用静态缓存的方法(它更快并且能够使用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)

#1


1  

Why don't you do it like this?

你为什么不这样做?

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

#2


1  

Here's a way to create a new instance and use static cache (which is faster and gives an ability to use kwargs):

这是一种创建新实例并使用静态缓存的方法(它更快并且能够使用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)