【问题标题】:Give color to the text of HTML table body based on condition根据条件为 HTML 表格正文的文本着色
【发布时间】:2019-02-06 06:47:29
【问题描述】:

我正在使用 python 在电子邮件正文中发送一个 html 表格。 html 表包含作业状态,我需要以红色和粗体突出显示失败的作业。 我尝试了不同的方法,包括分离失败和成功的工作,并制作单独的 html 表格并在最后将它们合并。但即使在合并后第二个表格也有额外的边框。

PFB 我用来发送 html 表格的代码。

import pandas
df = pandas.read_excel("C:\\"+os.environ["HOMEPATH"]+"\\Desktop\\Daily 
Monitoring.xlsx", sheetname='Status Sheet')

import tabulate
html = """
<html>
<head>
<style> 
 table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
  th, td {{ padding: 5px; }}
</style>
</head>
<body><p>Hi All,</p>

<p> Kindly find below the monitoring result:  </p>
{table}

</body></html>
"""


col_list=list(df.columns.values)
html = html.format(table=tabulate.tabulate(df, headers=col_list, tablefmt="html",showindex=False))

【问题讨论】:

    标签: html python-3.x


    【解决方案1】:

    自己把pandas表改成字符串怎么样?

    table = ['<table>']
    
    for row in range (5): #depends on your df size
    
       table.append('<tr>')
    
       for col in range (5): #depends on your df size
    
          if df.iloc[row, col] == 'Failed'
    
             table.append('<td class=\"failed\">Failed</td>')
          else
             table.append('<td>' + df.iloc[row, col] + '</td>')
    
       table.append('</tr>')
    
    table.append('</table>')
    table = '\n'.join(table)
    

    尚未运行该代码,但希望您能理解 O:-)

    【讨论】:

    • 感谢@Martin,对您的代码进行了一些更改,并且成功了!
    【解决方案2】:

    在 css 中有一个 :nth 子属性可以用来实现它。我觉得

    `table:nth-child(2) > td 
    { 
    color:red;
    font-weight:bold;
    }
    `
    

    由于您知道哪些元素受到影响,因此您必须重复多次。

    一个更简洁的解决方案是将每个表格单元格的内容放入一个跨度中,并给它一个类。 然后编写这些类,你就完成了。 喜欢

    <table>
    <tr>
    <td><span class='importaint'>a</span></td>
    <td><span class='importaint'>b</span></td>
    </tr>
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-27
      • 2023-03-23
      • 2014-05-04
      • 2023-04-07
      • 2022-01-12
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      相关资源
      最近更新 更多