UDF装饰器

xlwings.func(category='xlwings', volatile=False, call_in_wizard=True)

在运行 “Import Python UDFs” 的时候,被 xlwings.func 装饰过的函数会被作为 Function(函数) 导入到Excel。

Arguments:

categoryint 或 str, 缺省值 “xlwings”

1-14代表内置类别,用户定义类别使用字符串

Added in version 0.10.3.

volatilebool类型, 缺省值为False

把一个用户定义函数标记为易变的。当工作表中的任意单元格发生计算的时候,都必须重新计算易变的函数的值。非易变函数只有在输入变量变化的时候才重新进行计算。当不在用于计算工作表的单元格的用户定义函数中是,此方法不起作用。

Added in version 0.10.3.

call_in_wizardbool类型, 缺省值为True

设置为False时,抑制公式向导中的函数调用。

Added in version 0.10.3.

xlwings.sub()

使用装饰器 xlwings.sub 装饰的函数,在运行”Import Python UDFs”时,会被作为 Sub (例如:宏)导入到Excel。

xlwings.arg(arg, convert=None, **options)

对参数应用转换器及其选项,参见 Range.options()

示例:

x 转换为2维numpy数组:

import xlwings as xw
import numpy as np

@xw.func
@xw.arg('x', np.array, ndim=2)
def add_one(x):
    return x + 1
xlwings.ret(convert=None, **options)

对返回值应用转换器及其选项,参见 Range.options()

示例:

  1. 抑制返回的DataFrame中的索引和表头:

import pandas as pd

@xw.func
@xw.ret(index=False, header=False)
def get_dataframe(n, m):
    return pd.DataFrame(np.arange(n * m).reshape((n, m)))
  1. 动态数组:

备注

If your version of Excel supports the new native dynamic arrays, then you don’t have to do anything special, and you shouldn’t use the expand decorator! To check if your version of Excel supports it, see if you have the =UNIQUE() formula available. Native dynamic arrays were introduced in Office 365 Insider Fast at the end of September 2018.

expand='table' 把UDF转变为动态数组。目前在动态数组中不能使用易变函数,比如,不能用 =TODAY() 作为动态数组的一部分。同时注意动态数组需要在右边和底部有一个空的行或列(以便确定区域范围)而且在覆盖数据时不会发出提醒信息。

不像标准的Excel数组,动态数组是在一个单元格中作为标准函数使用的,它会根据返回数组的范围自动扩展:

import xlwings as xw
import numpy as np

@xw.func
@xw.ret(expand='table')
def dynamic_array(n, m):
    return np.arange(n * m).reshape((n, m))

Added in version 0.10.0.