Display dataframe as a handle on Excel via XLwings

82 Views Asked by At

I am trying to write a function to return dataframe by handle via Xlwings:

@xw.func
@xw.ret(index=False)
def create_df():
    # initialize data of lists. 
    data = {'Name': ['Tom', 'nick', 'krish', 'jack'], 
        'Age': [20, 21, 19, 18]} 
    df = pd.DataFrame(data) 

    return df 

When applied on excel, it will automatically display the whole dataframe. In PyXLL the way of returning dataframe is by handle (for the same function). May I ask if there is a way to do the same in python Xlwings?

enter image description here

1

There are 1 best solutions below

2
mouwsy On

I am not sure if I understood your question corretly. If you would like to insert the dataframe to a single cell of an excel worksheet you can orientate yourself on the following example:

import pandas as pd
import xlwings as xw

df = pd.DataFrame({'Name': ['Tom', 'nick', 'krish', 'jack'],
                   'Age': [20, 21, 19, 18]}
                  )

wb = xw.Book(r"test.xlsx")
ws = wb.sheets[0]

ws["A5"].value = df.to_string()  # "A5" specifies the address of the excel cell.