如何使用 xlwings 在 Excel Python 中获取单元格的列号和行号?

时间:2021-07-01 03:18:27

标签: python excel openpyxl xlwings

我正在尝试获取从中调用函数的单元格或在 Excel 中的函数代码中传递的单元格的列号和行号。

如果我在 excel 中调用用户定义的函数 (UDF),例如 =some_udf(A2:D2) 和后端,即该函数的定义是使用 xlwings 用 python 编写的,我想获取单元格行调用此函数的编号和列编号,或者使用作为参数传递的范围获取该编号和列编号。我无法弄清楚如何做到这一点。

请帮忙! 或者,如果可以使用一些其他工具,如 openpyxl 等,请务必告知。

1 个答案:

答案 0 :(得分:0)

当您使用 xlwings 调用用户定义的函数时,您可以在函数定义中包含特殊参数 caller,这将是您从中调用函数的范围对象:

@xw.func
def some_udf(your_arg, caller):
    # caller will not be exposed in Excel, so use it like so:
    # =some_udf(your_arg)
    # Now you can access infos about the caller, e.g.:
    caller.address
    caller.row
    caller.column

另见:https://docs.xlwings.org/en/stable/udfs.html#the-caller-argument