按xlwings中的名称访问Excel列

时间:2016-04-28 15:38:51

标签: python xlwings

在pandas中,可以使用在工作表第一行中指定的名称访问Excel列。如何在xlwings中实现这一目标?

2 个答案:

答案 0 :(得分:1)

从xlwings 0.7.0开始,您可以使用Pandas作为转换器。对于像这样的示例工作簿:

A  B  C
1  4  7
2  5  8
3  6  9

此代码将读取该表,并允许您通过列标题访问数据。关键是.options(pd.DataFrame, index=False)位。该特定调用将返回带有默认索引的Pandas DataFrame。

有关xlwings converter here的更多信息。

import xlwings as xw
import pandas as pd

def calc():    
    # Create a reference to the calling Excel xw.Workbook
    wb = xw.Workbook.caller() 

    table = xw.Range('A1').table.options(pd.DataFrame, index=False).value

    # Access columns as attributes of the Pandas DataFrame
    print table.A
    print table.B

    # Access columns as column labels of the Pandas DataFrame
    print table['A']
    print table['B']

if __name__ == '__main__':
    path = "test.xlsm"        
    xw.Workbook.set_mock_caller(path)
    calc()

答案 1 :(得分:0)

您可以使用方括号来访问列,如建议here

import xlwings as xw
wb = xw.Workbook.active()
xw.Range('TableName[ColumnName]').value