Pandas dataframe.to_html()-将背景色添加到头部

2024-05-14 18:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一封电子邮件中将多个数据帧作为表发送。使用df.to_html()我可以为作为电子邮件正文一部分附加的表呈现HTML字符串。我成功地拿到了电子邮件中的表格。

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

但如何将背景色添加到这些表的标题中?


Tags: to数据字符串df电子邮件htmltablebody
2条回答

您可以尝试以下两种方式:

来自^{}^{}

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

或者用^{}

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

第二个选项提供了在导出期间删除索引列(to_html)的选项,而不必做太多的HTML调整;因此它可能更适合您的需要。

我希望这证明是有用的。

我建议使用Jinja2进行方便的HTML格式化。只需创建一个word文档,添加两行{{Header}和您想要的任何背景颜色{{DF},添加一个分页符并将其保存为html。现在使用Jinja2渲染模板。下面是Jinja2的使用示例代码:

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

这是关于Jinja2的一个很好的教程: http://pbpython.com/pdf-reports.html

相关问题 更多 >

    热门问题