2016-06-29 72 views
3

我将一个数据框嵌入到电子邮件正文中作为html表格。我想根据每个单元格中的值有条件地格式化单元格颜色和文本颜色。使用Python有条件地将内联样式格式应用于HTML表格

予先在一些数据从例如CSV文件中读取,并使用pandasto_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代码。谢谢

回答

0

随着熊猫当前的发展,有一种功能可以在将数据帧转换为HTML之前修改数据帧的style

简单的解决方案是定义一个函数并将其作为参数传递给styleapply函数。

下面是一个例子:

def f(val): 
    # @params: val is the entire column if axis is 0 
    # @returns: css style attributes based on the cell value 
    return ['color: red' if x < 0 else 'color: blue' for x in val] 

html_style = df.style.apply(f, axis = 0, subset = ['column_name']) # this will apply the css style to td of that column 

# above only returns Styler object so you need to convert it to string to render it 
html_style.render() # this does the job 

你可以阅读更多关于它在这里:http://pandas.pydata.org/pandas-docs/stable/style.html#Building-Styles