styler对象需先用format()设置数值格式,再调用独立的to_excel()方法导出,且必须指定engine='openpyxl';format键为列名,百分比用{:.1%};真要设样式需用set_properties()或set_table_styles();条件格式函数返回值须为完整css字典列表;hide_index()/hide_columns()导出时仍生效,调试建议暂注释。

用 style.format() 控制数值显示格式,但别直接链式调用 to_excel()
直接在 Styler 对象上调用 to_excel() 会报错:AttributeError: 'Styler' object has no attribute 'to_excel'。因为 Styler 不是 DataFrame,它只负责渲染样式,导出必须通过 to_excel() 的 engine='openpyxl' 配合 Styler.to_excel()(注意:这是 Pandas 1.3+ 新增的专用方法)。
常见错误是写成 df.style.format(...).to_excel(...) —— 这行不通。正确做法是先构建 Styler,再用其独立的 to_excel() 方法:
styled = df.style.format({'price': '{:.2f}', 'rate': '{:.1%}'})
styled.to_excel('report.xlsx', engine='openpyxl', index=False)
-
engine='openpyxl'必须显式指定,xlsxwriter不支持Styler.to_excel() -
format()中的键必须是列名(字符串),不能是位置索引 - 百分比格式用
{:.1%}会自动乘 100 并加 %,输入值应为小数(如 0.123 → "12.3%")
用 set_properties() 和 set_table_styles() 调整表头与单元格外观
单纯靠 format() 只能改数字显示,真要加背景色、边框、对齐方式,得用 set_properties()(作用于所有单元格)或 set_table_styles()(支持 CSS 选择器,更灵活)。
比如让表头加粗居中、浅灰底色,数据行交替着色:
styled = df.style.set_properties(**{'text-align': 'center'})
styled = styled.set_table_styles([
{'selector': 'thead th', 'props': [('background-color', '#4CAF50'), ('color', 'white'), ('font-weight', 'bold')]},
{'selector': 'tbody tr:nth-child(even)', 'props': [('background-color', '#f2f2f2')]}
])
-
set_properties()会覆盖所有单元格已有样式,慎用于细粒度控制 -
set_table_styles()中的selector支持thead、tbody、tr:hover等,但 Excel 导出时仅支持静态样式(不支持 hover) - 颜色推荐用十六进制(如
#FFEB3B),避免命名色(如'yellow')在 openpyxl 中渲染异常
条件格式用 apply() 或 applymap(),但导出时要注意函数返回值类型
高亮大于阈值的单元格,常用 applymap()(逐单元格)或 apply()(按列/行)。但导出 Excel 前,这些函数必须返回 CSS 字符串字典,且键只能是 'color'、'background-color' 等 openpyxl 能识别的属性。
错误写法:lambda x: 'background-color: red' if x > 100 else '' —— 空字符串会导致样式丢失。正确写法需补全默认样式:
def highlight_high(x):
return ['background-color: #ffdddd' if v > 100 else 'background-color: white' for v in x]
df.style.apply(highlight_high, axis=0).to_excel('report.xlsx', engine='openpyxl')
-
apply()的axis=0表示按列处理,axis=1按行;applymap()无需指定 axis,但性能较差 - 返回列表长度必须等于该列/行元素数,否则报
ValueError: style_fn returned invalid value - 条件格式在 Excel 中生效,但无法保留 Pandas 中的动态逻辑(比如公式联动),纯静态渲染
导出前必须关闭 Styler 的 hide_index() 和 hide_columns(),否则 Excel 里看不到对应区域
如果用了 df.style.hide_index() 或 hide_columns(['id']),导出 Excel 时这些部分依然会被隐藏——但很多人误以为只是“预览隐藏”,实际导出也生效。若需要 Excel 中显示索引或某列,就别调用这两个方法。
- 想隐藏索引但导出时显示?不用
hide_index(),改用df.reset_index(drop=False)把索引转成普通列 -
hide_columns()在导出后不可逆,Excel 打开即无该列,调试时建议先注释掉这行看效果 - 导出文件若打不开,大概率是 openpyxl 写入时样式冲突,可临时删掉所有
set_table_styles()测试是否样式代码引发问题
样式导出不是所见即所得,openpyxl 对 CSS 支持有限,复杂嵌套选择器或渐变色会丢弃。最稳的方式是:先用 Styler.to_excel() 输出基础样式,再用 openpyxl 手动补强(比如合并单元格、设置字体大小),而不是指望 Pandas 一步到位。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











