Skip to content

Python xpath

中文文档

https://www.kancloud.cn/gnefnuy/xlwings-docs/1127461

补充

获取当前单元格的地址

使用vba关键字, ==application==

@xw.func
@xw.arg('xl_app', vba='Application')
def get_caller_address(xl_app):
    return xl_app.Caller.Address

Application.Caller.Address表示当前单元格的地址, 例如返回$A$1绝对位置, Application.ThisCell.Address也可以表示当前单元格的地址, 详情可以参考VBA教程

表格的整理

之前同事问我, 能不能把如下这样的数据整理一下, 整理成一个表格, 我想了想这个excel不大好实现啊, 于是用的python

orange
age=18
height=180
weight=60
oufeng
age=19
height=178
cookie
height=182
weight=58
lemo
age=22
weight=21

需要整理成的表格大概如下表, 空值依然是空值, 这个excel该怎么做, 还有VBA该怎么做

age height weight
orange 18 180 60
oufeng 19 178
cookie 182 58
lemo 22 21

如果用python, 这些都会变得非常简单

import xlwings as xw
import pandas as pd

@xw.func
@xw.ret(expand='table')
def getTable(parameter_list):
    dic = {}
    point = ''
    for i in parameter_list:
        if '=' not in i:
            dic[i] = {}
            point = i
        else:
            temp = i.split('=')
            dic[point][temp[0]] = temp[1]
    return pd.DataFrame(dic).T

然后在excel 里面的xlwings点击import functions, 顺利的话, 你可以调用函数python函数了

在其他空余的单元格内, 输入下面这个公式

=getTable(A1:A13)

回车, 你的结果已经生成了