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

2024-06-02 06:40:45 发布

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

使用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)

谢谢你的帮助!在


Tags: 文件附件here电子邮件html格式邮件msg
1条回答
网友
1楼 · 发布于 2024-06-02 06:40:45

您可能需要查看openpyxlhttps://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

相关问题 更多 >