You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何自定义tabulate生成的HTML表格?(Streamlit场景)

自定义Tabulate生成的HTML表格样式(Streamlit)

要修改tabulate生成的HTML表格内容,比如自定义表头、调整字体大小、设置表格高度,有几种可行的方法,下面逐一说明:

方法1:用BeautifulSoup解析并修改HTML

直接字符串处理HTML容易出错,用BeautifulSoup可以安全地修改DOM元素。

步骤:

  1. 安装依赖:pip install beautifulsoup4
  2. 解析tabulate生成的HTML,按需修改表头、样式属性。

示例代码:

import tabulate as tb
import streamlit as st
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup

np.random.seed(42)

data = {
    'A': np.random.rand(100),
    'B': np.random.randint(1, 100, size=100),
    'C': np.random.choice(['X', 'Y', 'Z'], size=100)
}
df = pd.DataFrame(data)

# 生成带表头的HTML表格
html_table = tb.tabulate(df.values.tolist(), headers=df.columns, tablefmt='html')

# 解析HTML
soup = BeautifulSoup(html_table, 'html.parser')

# 设置表格整体样式:字体大小、高度、滚动
table_tag = soup.find('table')
table_tag['style'] = 'font-size: 16px; height: 150px; overflow-y: auto; display: block; border-collapse: collapse; width: 100%;'

# 自定义表头样式
thead_tag = soup.find('thead')
for th in thead_tag.find_all('th'):
    th['style'] = 'background-color: #f0f2f6; font-weight: bold; padding: 8px;'

# 给偶数行添加背景色(可选)
for tr in soup.find('tbody').find_all('tr')[::2]:
    tr['style'] = 'background-color: #f9f9f9;'

# 转换回HTML字符串
modified_html = str(soup)

# 在Streamlit中渲染
st.markdown(modified_html, unsafe_allow_html=True)

方法2:用Pandas的to_html生成更易定制的表格

Pandas的to_html方法支持更多原生参数,搭配内嵌CSS可以实现更灵活的样式控制。

示例代码:

import streamlit as st
import pandas as pd
import numpy as np

np.random.seed(42)

data = {
    'A': np.random.rand(100),
    'B': np.random.randint(1, 100, size=100),
    'C': np.random.choice(['X', 'Y', 'Z'], size=100)
}
df = pd.DataFrame(data)

# 生成带自定义类名的HTML表格
html_table = df.to_html(classes='custom-table', header=True, index=False)

# 包裹div并添加内嵌CSS
modified_html = f'''
<div style="height: 150px; overflow: auto;">
    <style>
        .custom-table {{
            font-size: 16px;
            border-collapse: collapse;
            width: 100%;
        }}
        .custom-table th {{
            background-color: #f0f2f6;
            font-weight: bold;
            padding: 8px;
            text-align: left;
        }}
        .custom-table td {{
            padding: 8px;
            border-bottom: 1px solid #eee;
        }}
        .custom-table tr:hover {{
            background-color: #f5f5f5;
        }}
    </style>
    {html_table}
</div>
'''

st.markdown(modified_html, unsafe_allow_html=True)

方法3:直接修改Tabulate的HTML字符串(简单场景)

如果只需要做少量修改(比如替换表头文本),可以直接用字符串替换快速实现,但不适合复杂样式调整。

示例代码:

import tabulate as tb
import streamlit as st
import pandas as pd
import numpy as np

np.random.seed(42)

data = {
    'A': np.random.rand(100),
    'B': np.random.randint(1, 100, size=100),
    'C': np.random.choice(['X', 'Y', 'Z'], size=100)
}
df = pd.DataFrame(data)

html_table = tb.tabulate(df.values.tolist(), headers=df.columns, tablefmt='html')

# 替换表头文本并添加样式
html_table = html_table.replace('<th>A</th>', '<th style="font-size:18px; background:#f0f2f6;">自定义列A</th>')
html_table = html_table.replace('<th>B</th>', '<th style="font-size:18px; background:#f0f2f6;">自定义列B</th>')
html_table = html_table.replace('<th>C</th>', '<th style="font-size:18px; background:#f0f2f6;">自定义列C</th>')

# 添加外层滚动容器和全局字体样式
modified_html = f'<div style="height:150px; overflow:auto; font-size:16px;">{html_table}</div>'

st.markdown(modified_html, unsafe_allow_html=True)

内容的提问来源于stack exchange,提问作者bwainwright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:06:00