我想编写自己的装饰器,使用xlwings装饰器在Excel中创建UDF。但是,当我导入我的函数时,导入的函数名称是装饰器内部函数名称。
澄清的一个虚拟例子:
import pandas as pd
import numpy as np
import xlwings as xw
def to_excel(f): # my decorator
@xw.func
@xw.arg('xl_app', vba='Application')
def wrapped(xl_app, arg1 =None, arg2 =None):
# do some stuff
return len(f(arg1, arg2))
return wrapped
def foo(dim1, dim2):
dim1, dim2 =int(dim1), int(dim2)
return pd.DataFrame(np.ones((dim1, dim2)))
@to_excel
def xlFoo(*args, **kwargs): # Excel UDF
return foo(*args, **kwargs)
如果我将其导入Excel,它将自动生成以下VBA代码:
'Autogenerated code by xlwings - changes will be lost with next import!
Function wrapped(Optional arg1, Optional arg2)
If TypeOf Application.Caller Is Range Then On Error GoTo failed
wrapped = Py.CallUDF("xl2", "wrapped", Array(Application, arg1, arg2), ThisWorkbook, Application.Caller)
Exit Function
failed:
wrapped = Err.Description
End Function
如果我将wrapped
替换为xlFoo
,它现在可以正常运行:
Function xlFoo(Optional arg1, Optional arg2)
If TypeOf Application.Caller Is Range Then On Error GoTo failed
xlFoo = Py.CallUDF("xl2", "xlFoo", Array(Application, arg1, arg2), ThisWorkbook, Application.Caller)
Exit Function
failed:
xlFoo = Err.Description
End Function