0

In pandas Excel columns can be accessed using names that are assigned in the first row of the sheet. How can this be achieved in xlwings?

Amani
  • 13,566
  • 21
  • 88
  • 140

2 Answers2

1

You can use Pandas as a converter as of xlwings 0.7.0. for an example workbook like this:

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

This code will read the table in and allow you to access the data via column headers. The key is the .options(pd.DataFrame, index=False) bit. That particular call will return a Pandas DataFrame, with a default index.

More info on xlwings converters 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()
schoolie
  • 442
  • 3
  • 9
0

You can use square brackets to access the columns, as suggested here:

import xlwings as xw
wb = xw.Workbook.active()
xw.Range('TableName[ColumnName]').value
Community
  • 1
  • 1
tobspr
  • 7,920
  • 3
  • 29
  • 46
  • What do you mean by 'TableName', because all I have is a single Excel sheet with the first row filled with column names. – Amani Apr 28 '16 at 15:46