is there a way to use replace function in pandas.excelwriter along with auto fit column widths?

42 views Asked by At

I'm trying to export my dataframe into separate excel sheets and to replace them each time. In the excel output I also have another sheet which I'm using and dont want it to change when I run the code

This is working for me

>>> with ExcelWriter(
...     "Test_AllBookings_Report.xlsx",
...     mode="a",
...     engine="openpyxl",
...     if_sheet_exists="replace",                
... ) as writer:
...     combined.to_excel(writer, sheet_name="Test 1", index=False)
...     not_approved.to_excel(writer, sheet_name="Test 2", index=False)
...     not_pushed.to_excel(writer, sheet_name="Test 3", index=False)

However I want the columns to audo-adjust the width rather than manually having to do that each time I open the output file

I have tried using xlsx writer as the engine but I get the error that the Append function isnt supported

I have seen code like the below, but still no luck

for i, col in enumerate(df.columns):
    width = max(df[col].apply(lambda x: len(str(x))).max(), len(col))
    worksheet.set_column(i, i, width)

Any ideas?

0

There are 0 answers