# Compute & set column width for each column _to_str = functools.partial(_to_str_for_length, decimals=decimals) Return str(Decimal(v).quantize(Decimal('1.' + '0' * decimals)).normalize())ĭef auto_adjust_xlsx_column_width(df, writer, sheet_name, margin=3, length_factor=1.0, decimals=3, index=False): Like str() but rounds decimals to predefined length Get the effective text length in characters, taking into account newlines I may be a bit late to the party but this code works when using 'openpyxl' as your engine, sometimes pip install xlsxwriter wont solve the issue. It gets DataFrame and lets you to style it very easily.īy default the columns width is auto-adjusting.įor example: from StyleFrame import StyleFrameĭf = pd.DataFrame( is written as sheet')Ĭall example: writer = write_to_excel(writer, dataframe, "Statistical_Analysis") There is a nice package that I started to use recently called StyleFrame. Make sure to install xlsxwriter: pip install xlsxwriterĪnd use it as the engine: writer = pd.ExcelWriter('/path/to/output/file.xlsx', engine='xlsxwriter')įor a more comprehensive explanation you can read the article How to Auto-Adjust the Width of Excel Columns with Pandas ExcelWriter on TDS. In case any of the above is failing with AttributeError: 'Worksheet' object has no attribute 'set_column' Manually adjust a column using Column Index _column(col_idx, col_idx, 15) Manually adjust a column using Column Name col_idx = df.columns.get_loc('columnName') Dynamically adjust all the column lengths writer = pd.ExcelWriter('/path/to/output/file.xlsx')ĭf.to_excel(writer, sheet_name='sheetName', index=False, na_rep='NaN')Ĭolumn_length = max(df.astype(str).map(len).max(), len(column))
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |