This would have the same effect as double clicking the edge of a column header (which resizes the column) for every column.
Actually the AgGrid
class has a param that does that. It is not documented in the official documentation, but in the source code it has a nice docstring:
columns_auto_size_mode=ColumnsAutoSizeMode.FIT_CONTENTS,
I found this comment very helpful but it took my a little bit to figure out that I need to import ColumnsAutoSizeMode like this:
from st_aggrid import AgGrid, GridOptionsBuilder, ColumnsAutoSizeMode
Then you can call it as follows:
AgGrid(data=df, columns_auto_size_mode=ColumnsAutoSizeMode.FIT_CONTENTS)
FIT_CONTENTS seems to only fit visible columns, same as FIT_ALL_COLUMNS_TO_VIEW.
Update: I was able to get the non-visible columns to auto-size. Something in custom_css did the trick.
from st_aggrid import GridOptionsBuilder, AgGrid, GridUpdateMode, DataReturnMode, ColumnsAutoSizeMode, AgGridTheme
gb = GridOptionsBuilder.from_dataframe(table_df)
gb.configure_default_column(cellStyle={'color': 'black', 'font-size': '12px'}, suppressMenu=True, wrapHeaderText=True, autoHeaderHeight=True)
custom_css = {".ag-header-cell-text": {"font-size": "12px", 'text-overflow': 'revert;', 'font-weight': 700},
".ag-theme-streamlit": {'transform': "scale(0.8)", "transform-origin": '0 0'}}
gridOptions = gb.build()
AgGrid(
table_df,
gridOptions=gridOptions,
custom_css=custom_css,
#allow_unsafe_jscode=True,
columns_auto_size_mode=ColumnsAutoSizeMode.FIT_CONTENTS,
theme=AgGridTheme.BALHAM, # Only choices: AgGridTheme.STREAMLIT, AgGridTheme.ALPINE, AgGridTheme.BALHAM, AgGridTheme.MATERIAL
height=350,
#width='100%',
)
Is there a version that is mandatory (python, streamlit, streamlit-aggrid) i am getting the ColumnsAutoSize mode is not found (in the from st_aggrid) just did and --update same error…
Found my answer… was running older Python 3.7.5 - needed to update to 3.10.x and good to go now.
I found out after some digging that this is the expected behaviour. As stated in the docs, to improve the performance the column are virtualised, meaning that only the columns that are shown in the screen are actually loaded. This means that autosize works only on them. If you want to avoid this behaviour you need to suppress column virtualization:
from st_aggrid import GridOptionsBuilder, AgGrid, ColumnsAutoSizeMode
gb = GridOptionsBuilder.from_dataframe(df)
other_options = {'suppressColumnVirtualisation': True}
gb.configure_grid_options(**other_options)
gridOptions = gb.build()
grid = AgGrid(
df,
gridOptions=gridOptions,
columns_auto_size_mode=ColumnsAutoSizeMode.FIT_CONTENTS
)