【发布时间】:2016-11-01 21:03:25
【问题描述】:
我将数据框作为 html 表格嵌入到电子邮件正文中。我想根据每个单元格中的值有条件地格式化单元格颜色和文本颜色。
我首先从一个示例 csv 文件中读取一些数据,并使用 pandas to_html() 方法将其格式化为 html 表格:
df = pd.read_csv('example.csv')
table = df.to_html()
现在我为邮件正文创建一些带有<style> 标记的基本html,并将table html 代码插入<div> 到msg 字符串的正文中,如下所示:
msg = """<html>
<style type = "text/css">
table, th, td { border: 1px solid black; }
</style>
<head></head>
<body>
<p>some text</p>
<div> %s </div>
</body
</html>""" % (table)
然后我使用premailer python 模块将<style> css 代码转换为内联样式:
from premailer import transform
result = transform(msg)
现在result 是一个 html 字符串,其表格具有像 <table border="1" class="dataframe" style="border:1px solid black"> 这样的内联样式
我将生成的 html 嵌入到电子邮件中:
msg_body = MIMEText(result, 'html')
msg.attach(msg_body)
这一切都很好。
现在我需要根据每个单元格中的值有条件地格式化单元格颜色和字体颜色。
我怎样才能最好地做到这一点? 正在考虑一些功能,例如:
def styleTable(x):
if x < 0:
return 'background-color: red'
else
return ''
但是如何将它应用到我的 html 字符串?还是我需要在上游做一些不同的事情?
同样,这将嵌入在电子邮件中,因此其中不能包含 Javascript 或 CSS 代码。谢谢
【问题讨论】: