核心内容
Styler 对象支持将带样式的表格导出为 HTML、Excel、LaTeX、字符串 四种形式。
一、to_html() — 导出 HTML
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
styler = df.style.highlight_max(color='lightgreen')
# 返回 HTML 字符串
html_str = styler.to_html()
# 写入文件
styler.to_html('styled_table.html')
# 更多参数
styler.to_html(
buf='output.html',
encoding='utf-8',
doctype_html=True, # 输出完整 HTML 文档
exclude_styles=False, # 是否排除 <style>
max_rows=None, # 限制输出行数
max_cols=None,
table_uuid=None,
bold_headers=True, # 表头加粗
caption='统计表', # 标题
sparse_index=True,
sparse_columns=True,
border=1
)嵌入 Jupyter / 网页
# 在 Jupyter 中使用
from IPython.display import HTML
HTML(df.style.background_gradient(cmap='Blues').to_html())二、to_excel() — 导出 Excel(保留样式)
# 将带样式的 DataFrame 写入 Excel
df.style.background_gradient(cmap='RdYlGn').to_excel(
'styled.xlsx',
sheet_name='Sheet1',
engine='openpyxl'
)
# 指定列宽、冻结窗格等
df.style.to_excel(
'styled.xlsx',
sheet_name='数据',
float_format='%.2f',
columns=['A', 'B'],
freeze_panes=(1, 0) # 冻结首行
)| 参数 | 说明 |
|---|---|
excel_writer | 文件路径或 ExcelWriter 对象 |
sheet_name | 工作表名称 |
na_rep | 缺失值表示 |
float_format | 浮点格式 |
columns | 选择导出列 |
freeze_panes | 冻结窗格位置 |
engine | ’openpyxl’ / ‘xlsxwriter’ |
注意
Styler 的
to_excel()会保留颜色、字体、边框等样式;纯DataFrame.to_excel()不保留样式。
三、to_latex() — 导出 LaTeX
# 基础导出
latex_str = df.style.to_latex()
# 带样式
df.style.highlight_max().to_latex()
# 完整参数
df.style.to_latex(
buf='table.tex',
column_format='lcc', # 列对齐:l=左,c=中,r=右
position='ht',
caption='测试表格',
label='tab:example',
multicolumn=True,
multirow=True,
hrules=True, # 使用 booktabs 风格横线
clines='skip-last',
convert_css=True, # 将 CSS 样式转为 LaTeX 命令
siunitx=True
)LaTeX 样式支持
convert_css=True时会将背景色、文字颜色、加粗等转换为 LaTeX 颜色命令。
四、to_string() — 导出字符串
# 返回纯文本字符串(类似控制台输出)
text = df.style.to_string()
# 保存为文本文件
df.style.to_string(buf='output.txt')参数
| 参数 | 说明 |
|---|---|
buf | 文件对象或路径 |
max_rows / max_cols | 限制行列数 |
sparse_index | 多级索引合并显示 |
na_rep | 缺失值表示 |
float_format | 浮点格式化函数 |
index_names | 显示索引名称 |
导出方式对比
| 方法 | 格式 | 保留样式 | 适用场景 |
|---|---|---|---|
to_html() | HTML | 完整 CSS | 网页展示、邮件报告 |
to_excel() | Excel | 颜色 / 字体 / 边框 | 办公报表 |
to_latex() | LaTeX | 颜色 / 粗体 | 学术论文 |
to_string() | 纯文本 | 无 | 控制台 / 日志 |
相关笔记
- Pandas-二十三-数据导出与序列化-MOC - DataFrame 的常规导出方法
- 22.3 样式函数 - 在导出前组合样式效果