我将一个数据框嵌入到电子邮件正文中作为html表格。我想根据每个单元格中的值有条件地格式化单元格颜色和文本颜色。使用Python有条件地将内联样式格式应用于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)
我然后转换<style>
使用premailer
蟒模块作为这样的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代码。谢谢