Pandas dataframe.to_html () - add background color to title

I am trying to send multiple data frames as tables in an email. Using df.to_html() , I can display the HTML string for the table that I am attaching as part of the email body. I can successfully get the tables in the letter.

 html.append(table.to_html(na_rep = " ",index = False)) body = '\r\n\n<br>'.join('%s'%item for item in html) msg.attach(MIMEText(body, 'html')) 

But how to add background color to the header of these tables?

+6
source share
2 answers

You can try to do this in two ways:

With set_table_styles from pandas.DataFrame.style :

 import pandas as pd import numpy as np # Set up a DataFrame np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) df.iloc[0, 2] = np.nan df_html_output = df.style.set_table_styles( [{'selector': 'thead th', 'props': [('background-color', 'red')]}, {'selector': 'thead th:first-child', 'props': [('display','none')]}, {'selector': 'tbody th:first-child', 'props': [('display','none')]}] ).render() html.append(df_html_output) body = '\r\n\n<br>'.join('%s'%item for item in html) msg.attach(MIMEText(body, 'html')) 

Or with .to_html :

 df_html_output = df.to_html(na_rep = "", index = False).replace('<th>','<th style = "background-color: red">') html.append(df_html_output) body = '\r\n\n<br>'.join('%s'%item for item in html) msg.attach(MIMEText(body, 'html')) 

The second option provides the ability to delete the index column during export ( to_html ) without having to make too many t26 tweaks; therefore, it may be more suitable for your needs.

Hope this is helpful.

+8
source

I would recommend using Jinja2 for easy HTML formatting. Just create a word document, add two lines {{Header}} with whatever background color you want, {{DF}}, add a page break and save it as html. Now use Jinja2 to display the templates. The following is a sample Jinja2 usage code:

 from jinja2 import Environment, FileSystemLoader import StringIO import pandas as pd Template_Path = '/home/test/' DF = [pd.DataFrame()]*5 # List of Dataframes Header_Text = ['header']*5 # list of headers env = Environment(loader=FileSystemLoader(Template_Path)) template = env.get_template('PDF_Temp.html') # name of your html template Master_HTML = '' for x in range(len(DF)): buf = StringIO.StringIO() DF_HTML = DF[x].to_html(buf) template_vars = {"Header" : Header_Text[x] , "DF" : buf.getvalue() } # Create PDF Master_HTML += template.render(template_vars) FN = 'test.html' with open(FN, "w") as f: f.write(Master_HTML.encode('utf-8') ) 

This is a good tutorial on Jinja2: http://pbpython.com/pdf-reports.html

+2
source

Source: https://habr.com/ru/post/1013725/


All Articles