1

I am trying to auto-adjust the column cells to the excel data i used this code which i found in stack overflow

df=pd.read_excel(r"location of the file")
writer = pd.ExcelWriter(r'C:\Users\Aparna\Downloads\columnwidth1.xlsx') 
df.to_excel(writer, sheet_name='my_analysis', index=False, na_rep='NaN')

# Auto-adjust columns' width
for column in df:
    column_width = max(df[column].astype(str).map(len).max(), len(column))
    col_idx = df.columns.get_loc(column)
    writer.sheets['my_analysis'].set_column(col_idx, col_idx, column_width)

writer.save()

i used this code for increasing the column width but it throws attribute error Attribute Error: 'DataFrame' object has no attribute 'map' and the saved excel sheet is not able to open getting file extention is not valid how to over come this here I am sharing the raw data along with expected output https://docs.google.com/spreadsheets/d/1_iemqwkTYdUCoXKj3O8JNnq3V1ePY5sSRuFD9zDJRPA/edit?usp=sharing this is the link for data.

1 Answers1

1

This will format column width.

df = pd.read_excel(r"location of the file")

with pd.ExcelWriter(r"C:\Users\Aparna\Downloads\columnwidth1.xlsx", engine="xlsxwriter") as writer:
    df.to_excel(writer, startrow=0, sheet_name="my_analysis", index=False)

    for col in pd.Series(range(len(df.columns))).tolist():
        header_name = df.columns[col]
        header_len = len(header_name)
        column_len = df[header_name].map(len).max()
        total_len = sum([header_len, 2]) if header_len > column_len else sum([column_len, 2])

        writer.sheets["my_analysis"].set_column(col, col, total_len)
Jason Baker
  • 3,170
  • 2
  • 12
  • 15