Vincy Mathew
Vincy Mathew

Reputation: 141

Give color to the text of HTML table body based on condition

I am sending out an html table in an email body using python. The html table consists of job status and I need to highlight the failed jobs in red and bold. I have tried out different ways, including segregating failed and successful jobs and making seperate html tables and clubbing them at the end.But even after clubbing the second table had an extra border.

PFB the code I use for sending out html table.

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))

enter image description here

Upvotes: 0

Views: 4356

Answers (2)

Martin Melichar
Martin Melichar

Reputation: 1156

What about rewriting the pandas table into string yourself?

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)

Haven't run that code, but hope you get that idea O:-)

Upvotes: 1

MasterOfDesaster
MasterOfDesaster

Reputation: 171

In css there is a :nth child property you can use to realize it. I think

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

Since you know which elements are affected, you have to repeat this multiple Times.

A much cleaner solution is to put the content of each table cell into a span, and give it a class. Then write those classes and you are done. Like

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

Upvotes: 0

Related Questions