### Initialize st-aggrid Component (Python) Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid Initializes the st-aggrid component, either in development mode pointing to a local server or in release mode using a pre-built frontend. This setup determines how the Streamlit app communicates with the ag-Grid frontend. ```python from operator import index import os import streamlit.components.v1 as components import pandas as pd import numpy as np import simplejson import warnings from dotenv import load_dotenv import typing from st_aggrid.grid_options_builder import GridOptionsBuilder from st_aggrid.shared import GridUpdateMode, DataReturnMode, JsCode, walk_gridOptions from numbers import Number load_dotenv() _RELEASE = os.getenv("AGGRID_RELEASE", "true").lower() == "true" if not _RELEASE: print("WARNING: Running de development mode") _component_func = components.declare_component( "agGrid", url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend", "build") _component_func = components.declare_component("agGrid", path=build_dir) ``` -------------------------------- ### Build AgGrid Options with GridOptionsBuilder (Python) Source: https://streamlit-aggrid.readthedocs.io/en/docs/Usage Utilizes the `GridOptionsBuilder` to programmatically define `grid_options` for AgGrid, simplifying customization for larger dataframes. This example configures column editing and single row selection. It requires importing `GridOptionsBuilder` from `st_aggrid`. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]}) options_builder = GridOptionsBuilder.from_dataframe(df) options_builder.configure_column('col1', editable=True) options_builder.configure_selection("single") grid_options = options_builder.build() grid_return = AgGrid(df, grid_options) selected_rows = grid_return["selected_rows"] st.write(selected_rows) ``` -------------------------------- ### Configure Pagination with Custom Page Size in Streamlit-AgGrid Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt This example shows how to enable and configure pagination for large datasets using GridOptionsBuilder.configure_pagination. It allows setting a custom page size, disabling automatic page sizing, and is useful for improving performance with many rows. It requires streamlit, pandas, numpy, and st_aggrid. ```python import streamlit as st import pandas as pd import numpy as np from st_aggrid import AgGrid, GridOptionsBuilder # Generate large dataset df = pd.DataFrame({ 'id': range(1, 101), 'name': [f'User {i}' for i in range(1, 101)], 'score': np.random.randint(0, 100, 100), 'category': np.random.choice(['A', 'B', 'C', 'D'], 100) }) try: gb = GridOptionsBuilder.from_dataframe(df) # Configure pagination with custom page size gb.configure_pagination( enabled=True, paginationAutoPageSize=False, paginationPageSize=20 ) gb.configure_default_column(editable=False, filterable=True, sorteable=True) grid_options = gb.build() grid_response = AgGrid( df, gridOptions=grid_options, height=400, theme='streamlit' ) except Exception as e: st.error(f"Pagination configuration error: {str(e)}") ``` -------------------------------- ### Customize AgGrid Columns with grid_options (Python) Source: https://streamlit-aggrid.readthedocs.io/en/docs/Usage Customizes the AgGrid component by defining specific column definitions using the `grid_options` parameter. This example makes only the first column editable while keeping the second read-only. It requires setting the `columnDefs` within the `grid_options` dictionary. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid df = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]}) grid_options = { "columnDefs": [ { "headerName": "col1", "field": "col1", "editable": True, }, { "headerName": "col2", "field": "col2", "editable": False, }, ], } grid_return = AgGrid(df, grid_options) new_df = grid_return["data"] st.write(new_df) ``` -------------------------------- ### AgGrid Function Documentation Source: https://streamlit-aggrid.readthedocs.io/en/docs/AgGrid Detailed documentation for the AgGrid function, including its parameters, return values, and usage. ```APIDOC ## AgGrid ### Description AgGrid is the main function used to render the grid. It renders the Grid Component using the ag-Grid JavaScript library and a dataframe. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **dataframe** (pandas.core.frame.DataFrame) - The underlying dataframe to be displayed in the grid. - **gridOptions** (typing.Optional[typing.Dict]) - A dictionary of options for ag-grid. Documentation on http://www.ag-grid.com If None default grid options will be created with GridOptionsBuilder.from_dataframe() call. - **height** (int) - The grid height, by default 400. - **width** (None) - Deprecated since version 0.2.0. The grid width, by default None. - **fit_columns_on_grid_load** (bool) - Automatically fit columns to the grid width. Defaults to False. - **update_mode** (st_aggrid.shared.GridUpdateMode) - Defines how the grid will send results back to streamlit. Must be either a string, one or a bitwise combination of: GridUpdateMode.NO_UPDATE, GridUpdateMode.MANUAL, GridUpdateMode.VALUE_CHANGED, GridUpdateMode.SELECTION_CHANGED, GridUpdateMode.FILTERING_CHANGED, GridUpdateMode.SORTING_CHANGED, GridUpdateMode.MODEL_CHANGED. Defaults to GridUpdateMode.VALUE_CHANGED | GridUpdateMode.SELECTION_CHANGED. - **data_return_mode** (st_aggrid.shared.DataReturnMode) - Defines how the data will be retrieved from components client side. One of: DataReturnMode.AS_INPUT, DataReturnMode.FILTERED, DataReturnMode.FILTERED_AND_SORTED. Defaults to DataReturnMode.AS_INPUT. - **allow_unsafe_jscode** (bool) - Allows javascript code to be injected in gridOptions. Defaults to False. - **enable_enterprise_modules** (bool) - Loads Ag-Grid enterprise modules (check licensing). Defaults to False. - **license_key** (typing.Optional[str]) - License key for enterprise modules. Defaults to None. - **try_to_convert_back_to_original_types** (bool) - Attempts to convert back to original data types. Defaults to True. - **conversion_errors** (str) - Behaviour when conversion fails. One of: 'raise', 'coerce', 'ignore'. Defaults to ‘coerce’. - **reload_data** (bool) - Force AgGrid to reload data using api calls. Should be false on most use cases. Defaults to False. - **theme** (str) - Theme used by ag-grid. One of: 'streamlit', 'light', 'dark', 'blue', 'fresh', 'material'. Defaults to ‘light’. - **key** (typing.Any, optional) - Streamlit key argument. Check streamlit’s documentation. Defaults to None. - **defaultColDef.** (_additional keyword arguments will be merged to gridOptions_) ### Returns A dictionary with members: `data` -> grid’s data, including edited values. `selected` -> list of selected rows. ### Return type dict ``` -------------------------------- ### GridOptionsBuilder Configuration Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Details on configuration options available through the GridOptionsBuilder. ```APIDOC ## GridOptionsBuilder Configuration ### Description This section details various configuration options for the ag-Grid, accessible via the GridOptionsBuilder. ### Configuration Options #### Row Grouping Selection - **groupSelectsChildren** (boolean) - Defaults to True. When rows are grouped, selecting a group selects all its children. - **groupSelectsFiltered** (boolean) - Defaults to True. When a group is selected, filtered rows within that group are also selected. ### Methods #### `configure_pagination` ##### Description Configures the grid's pagination features. ##### Parameters - **enabled** (boolean) - Optional - Enable or disable pagination. Defaults to True. - **paginationAutoPageSize** (boolean) - Optional - Automatically sets the optimal pagination size based on grid height. Defaults to True. - **paginationPageSize** (integer) - Optional - Forces the page to have a specific number of rows per page. Defaults to 10. ##### Returns - None #### `configure_grid_options` ##### Description Merges key-value pairs into the `gridOptions` dictionary. Use this method to add any other key-value pairs. ##### Parameters - **props** (dict) - A dictionary containing key-value pairs to be merged into `gridOptions`. ##### Returns - None #### `build` ##### Description Builds the `gridOptions` dictionary based on the current configuration. ##### Returns - dict - A dictionary containing the configured grid options. ``` -------------------------------- ### Initialize Grid Configuration with GridOptionsBuilder Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Illustrates how to use `GridOptionsBuilder.from_dataframe` to initialize grid configurations from a pandas DataFrame. This method automatically infers column types and sets up basic properties like editability, sortability, filterability, and resizability for columns. The built grid options can then be passed to the `AgGrid` function. This snippet requires `streamlit`, `pandas`, and `st_aggrid`. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder # Sample DataFrame df = pd.DataFrame({ 'product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor'], 'price': [1200.50, 25.99, 75.00, 350.00], 'quantity': [5, 50, 30, 10], 'in_stock': [True, True, False, True] }) try: # Initialize builder from DataFrame with default column settings gb = GridOptionsBuilder.from_dataframe( df, editable=True, sorteable=True, filterable=True, resizable=True ) # Builder is now ready for further configuration grid_options = gb.build() grid_response = AgGrid(df, gridOptions=grid_options) except Exception as e: st.error(f"Configuration error: {str(e)}") ``` -------------------------------- ### AgGrid: Enterprise Features and Themes in Streamlit Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Demonstrates how to enable AG-Grid enterprise features and apply different built-in themes to the grid within a Streamlit application. This requires an AG-Grid enterprise license key. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({ 'company': ['Acme Corp', 'Globex Inc', 'Soylent Corp', 'Initech', 'Umbrella Corp'], 'revenue': [5000000, 3000000, 4500000, 2000000, 6000000], 'employees': [50, 30, 45, 20, 60], 'region': ['North', 'South', 'North', 'East', 'West'] }) try: gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(editable=False, groupable=True) gb.configure_side_bar() grid_options = gb.build() # Theme selector theme = st.selectbox( 'Select Theme', ['streamlit', 'light', 'dark', 'blue', 'fresh', 'material'] ) grid_response = AgGrid( df, gridOptions=grid_options, height=350, theme=theme, enable_enterprise_modules=False, # Set to True with valid license_key license_key=None, # Replace with your AG-Grid license key fit_columns_on_grid_load=True, allow_unsafe_jscode=False ) st.write(f"Current theme: {theme}") except Exception as e: st.error(f"Theme/enterprise error: {str(e)}") ``` -------------------------------- ### Initialize GridOptionsBuilder from DataFrame Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Creates a GridOptionsBuilder instance from a pandas DataFrame. It infers column types and sets up default column definitions based on the DataFrame's dtypes. This method is useful for quickly setting up basic grid configurations. ```python from st_aggrid import GridOptionsBuilder import pandas as pd # Assuming df is your pandas DataFrame df = pd.DataFrame({'col1': [1, 2], 'col2': ['A', 'B']}) builder = GridOptionsBuilder.from_dataframe(df) # Further configurations can be applied here, e.g.: # builder.configure_column("col1", header_name="Column One", editable=True) gridOptions = builder.build() # AgGrid(df, gridOptions=gridOptions) ``` -------------------------------- ### Build Ag-Grid Options Dictionary Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Constructs the final gridOptions dictionary based on the configured properties. This method is essential for applying all the specified grid settings. ```python build() ``` -------------------------------- ### Build Grid Options from DataFrame - Python Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Initializes a GridOptionsBuilder from a pandas DataFrame, creating column definitions and inferring types. It allows further customization of individual columns and is used to configure AgGrid behavior. ```python from st_aggrid import GridOptionsBuilder, AgGrid # Assuming 'df' is your pandas DataFrame # builder = GridOptionsBuilder.from_dataframe(df) # builder.configure_column("first_column", header_name="First", editable=True) # go = builder.build() # AgGrid(df, gridOptions=go) ``` -------------------------------- ### Build Grid Options Dictionary in Streamlit-AgGrid Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Finalizes the construction of the gridOptions dictionary by converting the column definitions from a dictionary to a list, which is the expected format for ag-Grid. ```python def build(self): """Builds the gridOptions dictionary Returns: dict: Returns a dicionary containing the configured grid options """ self.__grid_options["columnDefs"] = list( self.__grid_options["columnDefs"].values() ) return self.__grid_options ``` -------------------------------- ### Configure Multiple Columns with GridOptionsBuilder Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Applies the same configuration properties to multiple columns simultaneously. This method is efficient for setting common properties across several columns without repetitive code. It takes a list of column names and common configuration options. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({ 'q1_sales': [10000, 15000, 12000], 'q2_sales': [11000, 16000, 13000], 'q3_sales': [12000, 17000, 14000], 'q4_sales': [13000, 18000, 15000], 'region': ['North', 'South', 'East'] }) try: gb = GridOptionsBuilder.from_dataframe(df) # Configure multiple columns at once gb.configure_columns( column_names=['q1_sales', 'q2_sales', 'q3_sales', 'q4_sales'], type=['numericColumn'], editable=True, width=120, cellStyle={'textAlign': 'right'}, valueFormatter="'$" + value.toLocaleString()" ) gb.configure_column('region', editable=False, pinned='left', width=100) grid_options = gb.build() grid_response = AgGrid(df, gridOptions=grid_options, height=250) except Exception as e: st.error(f"Batch configuration error: {str(e)}") ``` -------------------------------- ### AgGrid with Custom Grid Options Dictionary in Streamlit Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Demonstrates using AgGrid with a manually constructed gridOptions dictionary, offering maximum control. This is useful for migrating from JavaScript AG-Grid configurations. It takes a pandas DataFrame and a custom dictionary, outputting the AgGrid component. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridUpdateMode, DataReturnMode df = pd.DataFrame({ 'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': ['A', 'B', 'C'] }) try: # Manually construct grid options dictionary grid_options = { 'columnDefs': [ { 'headerName': 'Column 1', 'field': 'col1', 'editable': True, 'type': ['numericColumn'], 'width': 120 }, { 'headerName': 'Column 2', 'field': 'col2', 'editable': False, 'type': ['numericColumn'], 'width': 120 }, { 'headerName': 'Column 3', 'field': 'col3', 'editable': True, 'filter': 'agTextColumnFilter', 'width': 150 } ], 'defaultColDef': { 'resizable': True, 'sortable': True, 'filter': True }, 'rowSelection': 'single', 'enableRangeSelection': True } grid_response = AgGrid( df, gridOptions=grid_options, height=300, update_mode=GridUpdateMode.VALUE_CHANGED, data_return_mode=DataReturnMode.AS_INPUT, fit_columns_on_grid_load=False, theme='light' ) st.write("Modified DataFrame:", grid_response['data']) except Exception as e: st.error(f"Manual grid options error: {str(e)}") ``` -------------------------------- ### AgGrid: Update Modes and Data Return Modes in Streamlit Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Demonstrates configuring AgGrid's update and data return modes to control when and what data is sent back to Streamlit. It allows users to select different modes via Streamlit widgets. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode df = pd.DataFrame({ 'product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones'], 'category': ['Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories'], 'price': [1200, 25, 75, 350, 150], 'quantity': [5, 50, 30, 10, 20] }) try: gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(editable=True, filterable=True, sorteable=True) gb.configure_selection('multiple', use_checkbox=True) grid_options = gb.build() col1, col2 = st.columns(2) with col1: update_mode = st.selectbox( 'Update Mode', [ GridUpdateMode.NO_UPDATE, GridUpdateMode.MANUAL, GridUpdateMode.VALUE_CHANGED, GridUpdateMode.SELECTION_CHANGED, GridUpdateMode.VALUE_CHANGED | GridUpdateMode.SELECTION_CHANGED ] ) with col2: data_return_mode = st.selectbox( 'Data Return Mode', [ DataReturnMode.AS_INPUT, DataReturnMode.FILTERED, DataReturnMode.FILTERED_AND_SORTED ] ) grid_response = AgGrid( df, gridOptions=grid_options, height=350, update_mode=update_mode, data_return_mode=data_return_mode, fit_columns_on_grid_load=True, theme='streamlit' ) st.write(f"Returned {len(grid_response['data'])} rows") st.write("Data:", grid_response['data']) st.write("Selected rows:", grid_response['selected_rows']) except Exception as e: st.error(f"Update mode error: {str(e)}") ``` -------------------------------- ### Render Interactive Data Table with AgGrid Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Demonstrates the basic usage of the `AgGrid` function to render a pandas DataFrame as an interactive table in Streamlit. It shows how to configure update modes, data return modes, editability, and themes, and how to access the updated data and selected rows from the grid's response. This snippet requires `streamlit`, `pandas`, and `st_aggrid`. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridUpdateMode, DataReturnMode # Create sample data df = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie', 'David'], 'age': [25, 30, 35, 40], 'salary': [50000, 60000, 75000, 80000], 'active': [True, False, True, True] }) # Basic usage with all editable cells try: grid_response = AgGrid( dataframe=df, height=400, fit_columns_on_grid_load=True, update_mode=GridUpdateMode.VALUE_CHANGED | GridUpdateMode.SELECTION_CHANGED, data_return_mode=DataReturnMode.FILTERED_AND_SORTED, editable=True, theme='streamlit', key='my_grid' ) # Access returned data updated_df = grid_response['data'] selected_rows = grid_response['selected_rows'] st.write("Modified Data:", updated_df) st.write("Selected Rows:", selected_rows) except Exception as e: st.error(f"Grid error: {str(e)}") ``` -------------------------------- ### Configure Ag-Grid Options Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Merges key-value pairs into the gridOptions dictionary, allowing customization of various Ag-Grid properties. Refer to the Ag-Grid documentation for a full list of available options. ```python configure_grid_options(_** props: dict_) ``` -------------------------------- ### Batch Configure Columns - Python Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Applies common properties to multiple columns specified by their field names. Properties provided in `props` are merged with the column definitions for the listed `column_names`. ```python # builder.configure_columns( # column_names=["col1", "col2"], # header_name="New Header Name", # editable=True # ) ``` -------------------------------- ### Enable Side Panel with Filters and Columns in Streamlit-AgGrid Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt This snippet illustrates how to enable the AG-Grid side panel for advanced filtering and column management using GridOptionsBuilder.configure_side_bar. It allows users to toggle filters, show/hide columns, and set the default panel to open. Dependencies include streamlit, pandas, and st_aggrid. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({ 'product': ['Laptop', 'Desktop', 'Tablet', 'Phone', 'Monitor', 'Keyboard'], 'brand': ['Dell', 'HP', 'Apple', 'Samsung', 'LG', 'Logitech'], 'price': [1200, 800, 600, 900, 400, 100], 'category': ['Computer', 'Computer', 'Mobile', 'Mobile', 'Display', 'Accessory'], 'in_stock': [True, False, True, True, True, False] }) try: gb = GridOptionsBuilder.from_dataframe(df) # Enable side bar with filters and columns panels gb.configure_side_bar( filters_panel=True, columns_panel=True, defaultToolPanel='filters' # Open filters panel by default ) gb.configure_default_column(filterable=True, sorteable=True) grid_options = gb.build() grid_response = AgGrid( df, gridOptions=grid_options, height=400, fit_columns_on_grid_load=True ) except Exception as e: st.error(f"Side bar configuration error: {str(e)}") ``` -------------------------------- ### Configure Row Selection with Checkboxes in Streamlit-AgGrid Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt This snippet demonstrates how to configure multiple row selection with checkboxes using GridOptionsBuilder.configure_selection. It allows users to select multiple rows, pre-select specific rows, and defines how row selection interacts with clicks and group selections. Dependencies include streamlit, pandas, and st_aggrid. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({ 'task_id': [1, 2, 3, 4, 5], 'task_name': ['Task A', 'Task B', 'Task C', 'Task D', 'Task E'], 'status': ['Complete', 'Pending', 'Complete', 'In Progress', 'Pending'], 'priority': ['High', 'Medium', 'Low', 'High', 'Medium'] }) try: gb = GridOptionsBuilder.from_dataframe(df) # Configure multiple selection with checkboxes gb.configure_selection( selection_mode='multiple', use_checkbox=True, pre_selected_rows=[0, 2], # Pre-select rows 0 and 2 rowMultiSelectWithClick=True, suppressRowDeselection=False, suppressRowClickSelection=False, groupSelectsChildren=True, groupSelectsFiltered=True ) gb.configure_default_column(editable=False) grid_options = gb.build() grid_response = AgGrid(df, gridOptions=grid_options, height=300) selected = grid_response['selected_rows'] if selected is not None and len(selected) > 0: st.write(f"Selected {len(selected)} rows:", selected) else: st.write("No rows selected") except Exception as e: st.error(f"Selection configuration error: {str(e)}") ``` -------------------------------- ### Configure Sidebar - Python Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Configures the sidebar panel in the Ag-Grid table, allowing users to interact with filters and columns. It provides options to enable or disable the filters panel and columns panel, and to set the default tool panel that is visible when the grid loads. This enhances user interaction by providing quick access to grid functionalities. ```python def configure_side_bar( self, filters_panel: bool = True, columns_panel: bool = True, defaultToolPanel: str = "", ): """Configures the side bar. Args: filters_panel (bool, optional): enable or disable filters panel. Defaults to True. columns_panel (bool, optional): enable or disable columns panel. Defaults to True. defaultToolPanel (str, optional): sets default tool panel either 'columns' or 'filters'. Defaults to panel closed ("") Returns: None """ filter_panel = { "id": "filters", "labelDefault": "Filters", "labelKey": "filters", "iconKey": "filter", "toolPanel": "agFiltersToolPanel", } columns_panel = { "id": "columns", "labelDefault": "Columns", "labelKey": "columns", "iconKey": "columns", "toolPanel": "agColumnsToolPanel", } if filters_panel or columns_panel: sideBar = {"toolPanels": [], "defaultToolPanel": defaultToolPanel} if filters_panel: sideBar["toolPanels"].append(filter_panel) if columns_panel: sideBar["toolPanels"].append(columns_panel) self.__grid_options["sideBar"] = sideBar ``` -------------------------------- ### Render DataFrame with AgGrid (Python) Source: https://streamlit-aggrid.readthedocs.io/en/docs/Usage Displays a simple Pandas DataFrame using the AgGrid component with default settings. This is the most straightforward way to visualize tabular data. It requires the streamlit, pandas, and st_aggrid libraries. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) AgGrid(df) ``` -------------------------------- ### Build Grid Options with GridOptionsBuilder in Streamlit Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt Finalizes and returns the gridOptions dictionary after applying various configurations using GridOptionsBuilder. This method must be called last. It takes a pandas DataFrame and returns a dictionary suitable for AgGrid. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({ 'user': ['user1', 'user2', 'user3'], 'email': ['user1@example.com', 'user2@example.com', 'user3@example.com'], 'role': ['Admin', 'User', 'Editor'] }) try: # Build complete grid configuration gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(editable=True, filterable=True) gb.configure_column('user', editable=False) gb.configure_selection('single', use_checkbox=False) gb.configure_pagination(enabled=False) # Build returns the complete gridOptions dictionary grid_options = gb.build() # Inspect the built configuration st.write("Grid Options Structure:", grid_options.keys()) # Use the built options grid_response = AgGrid(df, gridOptions=grid_options, height=250) if grid_response['selected_rows'] is not None: st.write("Selected:", grid_response['selected_rows']) except Exception as e: st.error(f"Build error: {str(e)}") ``` -------------------------------- ### Configure Row Selection and Checkbox in Streamlit-AgGrid Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Configures row selection modes (single, multiple), enables checkboxes for row selection, and sets up pre-selected rows. It also handles suppressions for row click selection and group selection behavior. ```python if use_checkbox: suppressRowClickSelection = True first_key = next(iter(self.__grid_options["columnDefs"].keys())) self.__grid_options["columnDefs"][first_key]["checkboxSelection"] = True if pre_selected_rows: self.__grid_options["preSelectedRows"] = pre_selected_rows self.__grid_options["rowSelection"] = selection_mode self.__grid_options["rowMultiSelectWithClick"] = rowMultiSelectWithClick self.__grid_options["suppressRowDeselection"] = suppressRowDeselection self.__grid_options["suppressRowClickSelection"] = suppressRowClickSelection self.__grid_options["groupSelectsChildren"] = groupSelectsChildren and selection_mode == "multiple" self.__grid_options["groupSelectsFiltered"] = groupSelectsChildren ``` -------------------------------- ### Apply Custom Grid Properties in Streamlit-AgGrid Source: https://context7.com/context7/streamlit-aggrid_readthedocs_io_en/llms.txt This code demonstrates how to merge custom AG-Grid properties directly into the grid options using GridOptionsBuilder.configure_grid_options. This method is useful for applying any AG-Grid configuration not explicitly covered by other builder methods, such as enabling range selection, charts, or row dragging. It requires streamlit, pandas, and st_aggrid. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'city': ['New York', 'London', 'Tokyo'] }) try: gb = GridOptionsBuilder.from_dataframe(df) # Add custom AG-Grid properties directly gb.configure_grid_options( enableRangeSelection=True, enableCharts=True, animateRows=True, rowDragManaged=True, suppressCellSelection=False, enableCellTextSelection=True, ensureDomOrder=True, headerHeight=50, rowHeight=35 ) grid_options = gb.build() grid_response = AgGrid(df, gridOptions=grid_options, height=300) except Exception as e: st.error(f"Custom options error: {str(e)}") ``` -------------------------------- ### Render AgGrid with DataFrame Source: https://streamlit-aggrid.readthedocs.io/en/docs/AgGrid Renders an interactive grid using the ag-Grid JavaScript library with a pandas DataFrame. It supports numerous parameters for customization, including grid options, dimensions, update modes, and theming. The function returns a dictionary containing the grid's data and selection. ```python import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode # Sample DataFrame data = {'col1': [1, 2, 3], 'col2': ['A', 'B', 'C']} df = pd.DataFrame(data) # AgGrid function call grid_response = AgGrid( df, gridOptions=None, # Use default GridOptionsBuilder if None height=400, width=None, fit_columns_on_grid_load=False, update_mode=GridUpdateMode.MODEL_CHANGED, data_return_mode=DataReturnMode.FILTERED_AND_SORTED, allow_unsafe_jscode=False, enable_enterprise_modules=False, license_key=None, try_to_convert_back_to_original_types=True, conversion_errors='coerce', reload_data=False, theme='streamlit', key=None, custom_css=None, **default_column_parameters # Example: "editable": True ) # Accessing the returned data grid_data = grid_response['data'] selected_rows = grid_response['selected'] st.write("Grid Data:") st.write(grid_data) st.write("Selected Rows:") st.write(selected_rows) ``` -------------------------------- ### Configure Ag-Grid Pagination Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Enables or disables grid pagination and allows setting the number of rows per page. It supports automatic page sizing based on grid height. ```python configure_pagination(_enabled =True_, _paginationAutoPageSize =True_, _paginationPageSize =10_) ``` -------------------------------- ### Configure Default Column Properties Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Sets default properties for all columns in the AgGrid. This method allows configuring parameters like minimum width, resizability, filterability, sortability, and editability for columns by default. Additional properties can also be passed as keyword arguments. ```python from st_aggrid import GridOptionsBuilder builder = GridOptionsBuilder() builder.configure_default_column( min_column_width=60, resizable=True, filterable=True, sorteable=True, editable=False, groupable=False ) # builder.configure_grid_options(domLayout='normal') # gridOptions = builder.build() ``` -------------------------------- ### Streamlit ag-grid Component Functionality Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid This Python function serves as the core of the streamlit-aggrid component. It accepts a pandas DataFrame and various configuration options to render an interactive ag-Grid table within a Streamlit app. It handles data serialization, theme application, and integrates with the underlying ag-Grid JavaScript component. Key parameters include `gridOptions`, `dataframe`, `height`, `theme`, and `update_mode`. ```python def aggrid_return_mode_pandas(dataframe, gridOptions=None, data_return_mode=DataReturnMode.AS_INPUT, update_mode=GridUpdateMode.MODEL_CHANGED, fit_columns_on_grid_load=False, allow_unsafe_jscode=True, enable_enterprise_modules=False, height=350, width=None, reload_data=False, theme=GridTheme.STREAMLIT, custom_css=None, key=None, license_key=None, default_column_parameters=None, conversion_errors='coerce', try_to_convert_back_to_original_types=True): """ Renders an ag-Grid in Streamlit, returning the grid's data as a pandas DataFrame. Args: dataframe (pd.DataFrame): Data to be displayed. gridOptions (dict, optional): Dictionary of options for ag-Grid. See ag-Grid documentation for details. Defaults to None. data_return_mode (DataReturnMode, optional): Defines the return mode for data from the grid. Available options are DataReturnMode.AS_INPUT, DataReturnMode.FILTERED_AND_SORTED, and DataReturnMode.AS_FETCHED. Defaults to DataReturnMode.AS_INPUT. update_mode (GridUpdateMode, optional): Defines when the grid should update its data. Available options include GridUpdateMode.SELECTION_CHANGED, GridUpdateMode.VALUE_CHANGED, GridUpdateMode.MODEL_CHANGED, GridUpdateMode.ROW_DATA_UPDATED, GridUpdateMode.MANUAL. Defaults to GridUpdateMode.MODEL_CHANGED. fit_columns_on_grid_load (bool, optional): If True, columns will be resized to fit the grid width on load. Defaults to False. allow_unsafe_jscode (bool, optional): If True, allows the execution of JavaScript code within the grid. Use with caution. Defaults to True. enable_enterprise_modules (bool, optional): If True, enables ag-Grid enterprise modules. Requires a license key. Defaults to False. height (int, optional): The height of the grid in pixels. Defaults to 350. width (int, optional): The width of the grid in pixels. Deprecated and will be removed. Defaults to None. reload_data (bool, optional): If True, forces a reload of the data in the grid. Defaults to False. theme (GridTheme, optional): The theme to apply to the grid. Available themes include GridTheme.STREAMLIT, GridTheme.LIGHT, GridTheme.DARK, GridTheme.BLUE, GridTheme.FRESH, GridTheme.MATERIAL. Defaults to GridTheme.STREAMLIT. custom_css (dict, optional): A dictionary of custom CSS styles to apply to the grid. Defaults to None. key (str, optional): A unique key for the component. Defaults to None. license_key (str, optional): The ag-Grid enterprise license key. Defaults to None. default_column_parameters (dict, optional): Default parameters for grid columns. Defaults to None. conversion_errors (str, optional): Specifies how to handle errors during data conversion. Defaults to 'coerce'. try_to_convert_back_to_original_types (bool, optional): If True, attempts to convert columns back to their original data types. Defaults to True. Returns: dict: A dictionary containing: - data (pd.DataFrame): The grid's data, including edited values. - selected (list): A list of selected rows. Raises: ValueError: If an invalid theme, data_return_mode, or update_mode is provided. components.components.MarshallComponentException: If there's an issue marshalling component data, especially with unsafe JS code. """ if width: warnings.warn( "DEPRECATION Warning: width parameter is deprecated and will be removed on next version." ) response = {} response["data"] = dataframe response["selected_rows"] = [] # basic numpy types of dataframe frame_dtypes = dict(zip(dataframe.columns, (t.kind for t in dataframe.dtypes))) # if no gridOptions is passed, builds a default one. if gridOptions == None: gb = GridOptionsBuilder.from_dataframe(dataframe, **default_column_parameters) gridOptions = gb.build() def get_row_data(df): def cast_to_serializable(value): if isinstance(value, pd.DataFrame): return get_row_data(value) isoformat = getattr(value, 'isoformat', None) if ((isoformat) and callable(isoformat)): return isoformat() elif isinstance(value, Number): if (np.isnan(value) or np.isinf(value)): return value.__str__() return value else: return value.__str__() json_frame = df.applymap(cast_to_serializable) row_data = json_frame.to_dict(orient="records") row_data = simplejson.dumps(row_data, ignore_nan=True) return row_data row_data = get_row_data(dataframe) if allow_unsafe_jscode: walk_gridOptions( gridOptions, lambda v: v.js_code if isinstance(v, JsCode) else v ) _available_themes = ["streamlit", "light", "dark", "blue", "fresh", "material"] if (not isinstance(theme, str)) or (not theme in _available_themes): raise ValueError( f"{theme} is not valid. Available options: {_available_themes}" ) try: if not isinstance(data_return_mode, (str, DataReturnMode)): raise ValueError(f"{data_return_mode} is not valid.") if isinstance(data_return_mode, str): data_return_mode = DataReturnMode[data_return_mode.upper()] except: raise ValueError(f"{data_return_mode} is not valid.") try: if not isinstance(update_mode, (str, GridUpdateMode)): raise ValueError(f"{update_mode} is not valid.") if isinstance(update_mode, str): update_mode = GridUpdateMode[update_mode.upper()] except: raise ValueError(f"{data_return_mode} is not valid.") custom_css = custom_css or dict() try: component_value = _component_func( gridOptions=gridOptions, row_data=row_data, height=height, width=width, fit_columns_on_grid_load=fit_columns_on_grid_load, update_mode=update_mode, data_return_mode=data_return_mode, frame_dtypes=frame_dtypes, allow_unsafe_jscode=allow_unsafe_jscode, enable_enterprise_modules=enable_enterprise_modules, license_key=license_key, default=None, reload_data=reload_data, theme=theme, custom_css=custom_css, key=key ) except components.components.MarshallComponentException as ex: # a more complete error message. args = list(ex.args) args[ 0 ] += ". If you're using custom JsCode objects on gridOptions, ensure that allow_unsafe_jscode is True." ex = components.components.MarshallComponentException(*args) raise (ex) if component_value: if isinstance(component_value, str): component_value = simplejson.loads(component_value) frame = pd.DataFrame(component_value["rowData"]) original_types = component_value["originalDtypes"] if not frame.empty: # maybe this is not the best solution. Should it store original types? What happens when grid pivots? if try_to_convert_back_to_original_types: numeric_columns = { k: v for k, v in original_types.items() if v in ["i", "u", "f"] } if numeric_columns: frame.loc[:, numeric_columns] = frame.loc[:, numeric_columns].apply( pd.to_numeric, errors=conversion_errors ) text_columns = { k: v for k, v in original_types.items() if v in ["O", "S", "U"] } if text_columns: # This part of the code is incomplete in the provided snippet. # It appears to be intended for converting text columns back to their original types, # but the actual conversion logic is missing. pass response["data"] = frame response["selected_rows"] = component_value.get("selected_rows", []) return response ``` -------------------------------- ### Merge Custom Grid Options in Streamlit-AgGrid Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Allows merging arbitrary key-value pairs into the gridOptions dictionary. This is useful for applying advanced configurations not directly exposed by other methods. Refer to ag-Grid documentation for available properties. ```python def configure_grid_options(self, **props: dict): """Merges key-pair values to gridOptions dictionary. Use this method to add any other key-pair values to gridOptions dictionary. A complete list of available options can be found in https://www.ag-grid.com/javascript-data-grid/grid-properties/ Returns: None """ self.__grid_options.update(props) ``` -------------------------------- ### Configure Row Selection - Python Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Configures the row selection behavior in the grid, including selection mode (single, multiple, disabled), checkbox usage, pre-selected rows, and multi-select behavior with clicks. ```python # builder.configure_selection( # selection_mode='multiple', # use_checkbox=True, # pre_selected_rows=[0, 2], # rowMultiSelectWithClick=True, # suppressRowDeselection=False, # suppressRowClickSelection=False, # groupSelectsChildren=True, # groupSelectsFiltered=True # ) ``` -------------------------------- ### Configure Pagination in Streamlit-AgGrid Source: https://streamlit-aggrid.readthedocs.io/en/docs/_modules/st_aggrid/grid_options_builder Enables or disables pagination for the ag-grid and configures its behavior. Options include automatic page size adjustment based on grid height or a fixed page size. ```python def configure_pagination(self, enabled=True, paginationAutoPageSize=True, paginationPageSize=10): """Configure grid's pagination features Args: enabled: enable or disable pagination. Defaults to True. paginationAutoPageSize: Automatically sets optimal pagination size based on grid Height. Defaults to True. paginationPageSize: Forces page to have this number of rows per page. Defaults to 10. Returns: None """ if not enabled: self.__grid_options.pop("pagination", None) self.__grid_options.pop("paginationAutoPageSize", None) self.__grid_options.pop("paginationPageSize", None) return self.__grid_options["pagination"] = True if paginationAutoPageSize: self.__grid_options["paginationAutoPageSize"] = paginationAutoPageSize else: self.__grid_options["paginationPageSize"] = paginationPageSize ``` -------------------------------- ### Configure Default Column Properties - Python Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Sets default properties for all columns in the grid, such as minimum width, resizability, filterability, sortability, editability, and groupability. Additional properties can also be passed as keyword arguments. ```python # builder.configure_default_column( # min_column_width=5, # resizable=True, # filterable=True, # sorteable=True, # editable=False, # groupable=False # ) ``` -------------------------------- ### Configure Side Bar - Python Source: https://streamlit-aggrid.readthedocs.io/en/docs/GridOptionsBuilder Enables or disables the filters and columns panels in the Ag-Grid side bar. It also allows setting the default open panel. ```python # builder.configure_side_bar( # filters_panel=True, # columns_panel=True, # defaultToolPanel='columns' # ) ```