如何使用python格式化html表

时间:2019-06-03 13:14:02

标签: html python-3.x pandas html-email

我正在尝试在python脚本中格式化html表,然后将其作为电子邮件发送。该表源自一个熊猫数据框,然后使用.to_html()函数将其保存为HTML。

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from smtplib import SMTProm email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from smtplib import SMTP

# Save dataframe to html
df_final.to_html(r'Data/trend_report_word_3m_rolling.html',col_space = 20, index = False)

#read html
report_file = open(r'Data\trend_report_word_3m_rolling.html')
html_excel = report_file.read()

# Prepare to send email
part_html = MIMEText(html_report, 'html')

#Attach attachments to message
msg.attach(part)
msg.attach(part_html)

# Send the message via Henkel's SMTP server
with SMTP("") as smtp:
    smtp.send_message(msg)
    #print("The email was sent to: ",string_receiver)
    smtp.quit()

据我了解,使用.read()函数仅读取html文件,但不允许我编辑html吗? 最后,我希望电子邮件的收件人看到具有格式(例如颜色和特定列宽)的表格。

也许我应该先格式化数据框,然后再将其保存为HTML? 如果我的方法不清楚,请问一些问题。

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要一个html模板模块,例如:

https://opensource.com/resources/python/template-libraries

或小胡子(简单易用的小型模板系统):

https://github.com/defunkt/pystache