如何通过电子邮件发送样式化的熊猫DataFrame而不丢失格式?

时间:2019-07-31 01:57:52

标签: python pandas dataframe jupyter-notebook html-email

我对Python和Jupyter Notebook很陌生。因此,任何帮助将不胜感激。我可以根据this问题为DataFrame的特定单元格着色。

现在假设我的桌子上有“样式”(作为接受的答案中的那个),我希望通过电子邮件将其发送给某人(在这种情况下为我自己),而不会丢失任何格式(它应包含彩色单元格,边框和其他所有内容)。

我尝试使用.render()函数,然后将HTML代码附加到电子邮件的正文中,但是我一直在获取没有结构的无边界表。我已遵循此post来对电子邮件部分进行编码。唯一的区别是我没有使用“纯文本”部分。

此外,如何向表本身添加更多功能?像添加表格标题一样,修改列之间的间距,增加还是减小字体大小?

谢谢!

3 个答案:

答案 0 :(得分:0)

这是我在这种情况下使用的功能。 for循环用于创建带区的行。

def html_style_basic(df,index=True):
    import pandas as pd
    x = df.to_html(index = index)
    x = x.replace('<table border="1" class="dataframe">','<table style="border-collapse: collapse; border-spacing: 0; width: 25%;">')
    x = x.replace('<th>','<th style="text-align: left; padding: 2px; border-left: 1px solid #cdd0d4;" align="left">')
    x = x.replace('<td>','<td style="text-align: left; padding: 2px; border-left: 1px solid #cdd0d4; border-right: 1px solid #cdd0d4;" align="left">')
    x = x.replace('<tr style="text-align: right;">','<tr>')

    x = x.split()
    count = 2 
    index = 0
    for i in x:
        if '<tr>' in i:
            count+=1
            if count%2==0:
                x[index] = x[index].replace('<tr>','<tr style="background-color: #f2f2f2;" bgcolor="#f2f2f2">')
        index += 1
    return ' '.join(x)

答案 1 :(得分:0)

基于您已经通过Format the color of a cell in a pandas dataframe according to multiple conditions获得样式化的DataFrame的事实,则可以将其保存到html文件中。

with open('DataFrame.html', 'a') as f:
    f.write(df.render() )

对于进一步的自定义需求,请访问https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

答案 2 :(得分:0)

在这篇文章之后,我能够找到我的问题的答案:how to draw a beautiful colorful table with pandas or other package in Python?

基本上,如果在将颜色添加到单元格后使用.set_table_styles添加边框,则将正确显示通过电子邮件发送的html代码。我希望它能对遇到相同问题的所有人有所帮助。