Outlook邮件中插入Pandas DataFrame时如何高亮列标题背景?
解决方法
有两种常用实现方案,都可以兼容Outlook的渲染规则:
方案1:添加全局CSS样式(最简便)
直接在邮件HTML的<head>块内增加表格样式规则,所有插入的DataFrame表格都会自动生效,无需修改原有DataFrame的转HTML逻辑:
修改后的邮件代码示例:
import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = 'patrick.oneill@example.com' mail.Subject = 'Example mail format for monthly Eurex DMA fee stats' mail.HTMLBody = """\ <html> <head> <style> /* 表格表头样式 */ table th { background-color: #2E75B5; /* 可替换为任意你需要的颜色值,比如浅黄#FFF2CC */ color: #ffffff; /* 表头文字颜色 */ padding: 5px 10px; border: 1px solid #dddddd; } /* 可选:统一设置表格单元格样式 */ table td { padding: 5px 10px; border: 1px solid #dddddd; } </style> </head> <body> Hi All,<br> <br> The total Eurex DMA fees for the previous month per currency were:<br> <br> {3} <p><br> Fees broken down by product:<br> {0} <br>Fees broken down by trader:<br> {1} <br>Fees broken down by broker across Barclays & Goldmans:<br> {2} <br>Number of lots traded by broker across Barclays & Goldmans:<br> {4} Regards, <br> Patrick </p> </body> </html> """.format(product_splits.to_html(), trader_splits.to_html(), broker_splits.to_html(), total_fees.to_html(), count_contracts.to_html())
方案2:单个DataFrame自定义样式
如果需要给不同表格设置不同的表头样式,可以用Pandas自带的Styler单独配置每个表格的渲染效果:
示例代码:
# 对单个DataFrame设置表头样式 def df_to_styled_html(df, hide_index=True): styler = df.style.set_table_styles([ {'selector': 'th', 'props': [ ('background-color', '#2E75B5'), ('color', 'white'), ('border', '1px solid #ddd') ]}, {'selector': 'td', 'props': [ ('border', '1px solid #ddd') ]} ]) if hide_index: styler = styler.hide(axis='index') # 可选:隐藏表格索引列 return styler.render() # 调用时替换原有的to_html()即可 mail.HTMLBody = """\ <html> <head></head> <body> Hi All,<br> <br> The total Eurex DMA fees for the previous month per currency were:<br> <br> {3} <p><br> Fees broken down by product:<br> {0} <br>Fees broken down by trader:<br> {1} <br>Fees broken down by broker across Barclays & Goldmans:<br> {2} <br>Number of lots traded by broker across Barclays & Goldmans:<br> {4} Regards, <br> Patrick </p> </body> </html> """.format( df_to_styled_html(product_splits), df_to_styled_html(trader_splits), df_to_styled_html(broker_splits), df_to_styled_html(total_fees), df_to_styled_html(count_contracts) )
注意事项
Outlook对CSS的支持能力有限,仅使用background-color、color、padding、border这类基础属性即可,避免使用Flex、Grid等现代CSS特性,颜色统一用十六进制编码兼容性最好。
内容的提问来源于stack exchange,提问作者paddyusa
相关产品推荐
相关产品推荐

