我使用以下代码使用pywin32
从Excel COM Object触发事件
import win32com.client as win32
def record_events(key_,hash_):
if key_ not in hash_.keys():
hash_[key_] = 0
else:
hash_[key_] += 1
class ExcelEvents:
def __init__(self):
self.seen_events = {}
event_methods_hash = self._dispid_to_func_
def OnWorkbookOpen(self, *args):
key_ = "OnWorkbookOpen"
record_events(key_,self.seen_events)
print(args)
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel_events = win32.WithEvents(excel, ExcelEvents)
self._dispid_to_func_
中显示为
{1554: 'OnWindowResize',
1556: 'OnWindowActivate',
1557: 'OnWindowDeactivate',
1558: 'OnSheetSelectionChange',
1559: 'OnSheetBeforeDoubleClick',
1560: 'OnSheetBeforeRightClick',
1561: 'OnSheetActivate',
1562: 'OnSheetDeactivate',
1563: 'OnSheetCalculate',
1564: 'OnSheetChange',
1565: 'OnNewWorkbook',
1567: 'OnWorkbookOpen',
1568: 'OnWorkbookActivate',
1569: 'OnWorkbookDeactivate',
1570: 'OnWorkbookBeforeClose',
1571: 'OnWorkbookBeforeSave',
1572: 'OnWorkbookBeforePrint',
1573: 'OnWorkbookNewSheet',
1574: 'OnWorkbookAddinInstall',
1575: 'OnWorkbookAddinUninstall',
1854: 'OnSheetFollowHyperlink',
.............
当我想通过一种方法而不是复制和粘贴来创建所有可用方法时,我尝试了python常规事件处理程序。但是,当我分配给excel_events = win32.WithEvents(excel, ExcelEvents)
时,出现了错误
class ExcelEvents:
def __init__(self):
self.seen_events = {}
def __getattr__(self,name):
return handlerFunctionClosure(self,name)
def handlerFunctionClosure(self,name):
def handlerFunction(*args,**kwargs):
print(name,args,kwargs)
return handlerFunction
c = ExcelEvents()
c.OnChange(1,4,2,c= 123) => OnChange (1, 4, 2) {'c': 123}
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel_events = win32.WithEvents(excel, ExcelEvents) => Error:TypeError: 'function' object is not iterable
似乎pywin32
在我的ExcelEvents
类和COM events
类的基础上创建了一个新类,并给出了这样的错误。我应该如何为所有可用的事件处理程序归档目标或动态添加方法?