简体   繁体   中英

Copy An Excel table in a worksheet with styling to an msg file using python

I have an Excel worksheet with a table that I want to copy into an msg file with the styling.

I know how to do the msg part:

import win32com.client as win32

def read_excel_into_msg(excel_file,msg_file):

    excel_table = ''

    outlook = win32.Dispatch('Outlook.Application').GetNamespace("MAPI")
    msg = outlook.OpenSharedItem(msg_file)
    msg.HTMLBody = excel_table
    msg.SaveAs(msg_file)

How can I get the excel table from a worksheet in the excel file to attach it to the msg body?

  • I have tried:
excel_table = pandas.read_excel(excel_file,sheetname,header=n,usecols=cols)
excel_table = excel_table.to_html()

But it copied the plain table without the styling (the header and footer colors)

Use Pillow Library Imaging Library, copy range, save it then add it to outlook html body

Example, I'm using pywin32

import os
import win32com.client
from PIL import ImageGrab


workbook_path = r"D:\Temp\test.xlsx"

excel = win32com.client.DispatchEx('Excel.Application')
excel.Visible = True
workbook = excel.Workbooks.Open(Filename=workbook_path)
sheet = workbook.Sheets["sheet1"]
copy_range = sheet.Range("A1:C6").CopyPicture(Appearance=1, Format=2)

ImageGrab.grabclipboard().save("copy_range.png")
image_path = os.getcwd() + "\\copy_range.png"

Outlook = win32com.client.Dispatch("Outlook.Application")
mail = Outlook.CreateItem(0)
mail.To = '0m3r@Email.com'
mail.Subject = 'Message subject'
html_body = """<div><img src={}></img></div>"""
mail.HTMLBody = html_body.format(image_path)

mail.Display()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM