简体   繁体   中英

Read Excel Table headers with xlwings

How can I use xlwings to read a "table" in excel, into a pandas DataFrame, where the table "headers" become the DataFrame column names?

Every way I have tried to read the table, the header row is always excluded from the read!

Here is what I've tried, where "b" is my xlwings workbook object:

b.sheets['Sheet1'].range('Table1').options(pd.DataFrame)
b.sheets['Sheet1'].range('Table1').options(pd.DataFrame, headers=False)
b.sheets['Sheet1'].range('Table1').options(pd.DataFrame, headers=True)

希望这不是最好的答案,但我确实发现我可以引用命名范围,然后.offset(-1).expand('vertical')

Another option is to use the api and Excel's ListObject

import xlwings as xw

wb = xw.books.active
ws = wb.sheets('MySheet')
tbl = ws.api.ListObjects('MyTable') # or .ListObjects(1)
rng = ws.range(tbl.range.address) # get range from table address

df = rng.options(pd.DataFrame, header=True).value # load range to dataframe

Let me add the comment by Felix Zumstein as explicit answer, because in my opinion it is the best solution.

b.sheets['Sheet1'].range('Table1[[#All]]').options(pd.DataFrame)

Using the square bracket notation expands the selection from the table body to the header row as well. Subsequently the conversion to a pandas DataFrame, can use it as header.

To read more, check this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM