使用Streamlit展示DataFrame时如何自动显示完整列名
Streamlit DataFrame列名截断自动适配方案

以下是无需手动拉伸列宽即可完整展示所有列名的可落地方案:
方案1:官方原生配置(推荐,Streamlit 1.23.0+ 可用)
直接利用Streamlit原生的列配置能力,将所有列宽设置为自动适配模式,列宽会自动取「列名渲染宽度」和「单元格最长内容宽度」的最大值,从根本上避免列名被短单元格宽度截断的问题。
import streamlit as st import pandas as pd # 此处替换为你自己的DataFrame加载逻辑 # df = your_dataframe st.dataframe( df, column_config={ col: st.column_config.Column(width="auto") for col in df.columns }, # 需要表格撑满整个页面宽度时,取消注释下一行即可 # use_container_width=True )
方案2:自定义CSS兼容方案(适用于Streamlit <1.23.0 旧版本)
低版本Streamlit没有开放列宽配置接口,可以通过注入全局CSS强制修改列头渲染规则,让列头宽度自动适配文本长度,不做截断处理。
在渲染DataFrame前加入以下代码即可生效:
st.markdown(""" <style> /* 覆盖DataFrame列头默认截断样式 */ [data-testid="stDataFrame"] .column-header { overflow: visible !important; text-overflow: clip !important; white-space: nowrap !important; } /* 设置列头最小宽度适配文本长度 */ [data-testid="stDataFrame"] .gd-column-header { min-width: fit-content !important; } </style> """, unsafe_allow_html=True)
使用提示
- 优先选择原生配置方案,不存在版本迭代后的样式兼容问题,稳定性更高
- 若存在极长的列名,自动适配后表格出现横向滚动为正常表现,不影响列名完整查看
- 不要给列设置固定width参数,否则会覆盖自动适配规则
内容的提问来源于stack exchange,提问作者sammy
相关产品推荐
相关产品推荐

