【问题标题】:Conditionally Apply In-Line Style Format to HTML Table with Python使用 Python 有条件地将内联样式格式应用于 HTML 表
【发布时间】: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 模块将&lt;style&gt; css 代码转换为内联样式:

from premailer import transform
result = transform(msg)

现在result 是一个 html 字符串,其表格具有像 &lt;table border="1" class="dataframe" style="border:1px solid black"&gt; 这样的内联样式

我将生成的 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 代码。谢谢

【问题讨论】:

    标签: python html css


    【解决方案1】:

    在 pandas 的当前开发中,有一个功能可以在将其转换为 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

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 2013-11-07
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多