在Python中的电子邮件正文中包含Excel表格

时间:2017-06-26 16:27:32

标签: python excel openpyxl

使用Python,我试图在电子邮件正文中发送一个包含Excel表格的电子邮件。我想保留Excel文件中的所有条件格式。我可以将Excel文件作为附件轻松发送,但我还想把表放在电子邮件正文中。如果需要,我会将其转换为HTML表格,但我需要知道如何将HTML表格包含在电子邮件正文中。下面将该文件作为电子邮件附加,但我还没有弄清楚如何将表格放在电子邮件中。我怎样才能做到这一点?

msg = MIMEMultipart()
msg['Subject'] = 'Subject goes here'
msg.attach(MIMEText('Text goes here'))
part = MIMEBase('application', "octet-stream")
f = 'file_name.xlsx'
part.set_payload(open(f, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % f)
msg.attach(part)

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用熊猫。像这样:

import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def generate_html():
    read_file = pd.read_csv("example.csv")
    html_file = read_file.to_html()
    sendEmail(html_file)

def sendEmail(html_file):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Hello"
    msg['From'] = EmailFrom
    msg['To'] = EmailTo
    part = MIMEText(html_file, 'html')
    msg.attach(part)
    s = smtplib.SMTP("smtp.gmail.com")
    s.sendmail(EmailFrom, EmailTo, msg.as_string())
    s.quit()

答案 1 :(得分:-2)

您可能需要查看openpyxl https://openpyxl.readthedocs.io/en/default/

这样的事情可能会解决您的问题:

import openpyxl
from openpyxl import load_workbook

workbook = load_workbook(f)
worksheet = workbook.get_active_sheet()

html_data = """
<html>
    <head>
        <title>
        XLSX to HTML demo
        <title>
    <head>
    <body>
        <h3>
        XLSX to HTML demo
        <h3>
    <table>
"""

ws_range = worksheet.range('A1:H13')
for row in ws_range:
    html_data += "<tr>
    for cell in row:
        if cell.value is None:
            html_data += "<td> + ' ' + "<td>
        else:
            html_data += "<td> + str(cell.value) + "<td>
    html_data += "<tr>
html_data += "</table></body></html>
msg.attach(MIMEText(html_data))

with open(f, "rb") as fil:
    part = MIMEApplication(
        fil.read(),
        Name=basename(f)
    )
    part['Content-Disposition'] = 'attachment; filename="{0}"'.format(basename(f))
    msg.attach(part)

https://jugad2.blogspot.ch/2013/11/publish-microsoft-excel-xlsx-data-to.html?m=1启发