问题
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)
回答1:
Hoping this is not the best answer, but I did find I could reference the named range, then .offset(-1).expand('vertical')
回答2:
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
来源:https://stackoverflow.com/questions/44793540/read-excel-table-headers-with-xlwings