yarmenti
yarmenti

Reputation: 101

xlwings / COM API format table

I'm currently using xlwings in Python/Excel and would like to format a table after putting a value with a pandas DataFrame. However, I can't format the table as I want. Indeed, it seems the API doesn't understand that the columns are already set. Could you please tell me how to do so? Here is my code:

range_ = wb.sheets[sheet_name].range("B2")
range_.expand().clear_contents()
range_.options(pd.DataFrame, index=True).value = data_df

range_.select()

tbl = wb.sheets[sheet_name].api.ListObjects.add()           
tbl.TableStyle = "TableStyleMedium4"
tbl.DisplayName = table_name

However, in the XL file, the first row (headers) is set as: Column 1, Column 2 and so on, instead of using the columns of my ```data_df````. Could you please help me?

Thank you very much!

Upvotes: 0

Views: 358

Answers (1)

Kyle
Kyle

Reputation: 67

I am sure you have moved on by now, but in case anyone else is searching for this, I was able to achieve this by using

ws = xw.Book.caller().sheets[sheet_name]
ws.range('A1').options(index=False, header=True).value = df
rng = ws.range('A1').expand('table')
tbl = ws.api.ListObjects.add(1,ws.api.Range(rng.address),False,1)    

The 4th input parameter on the ListObjects.Add call controls the header. You can find more information about the ListObject parameters here

Upvotes: 1

Related Questions