用Python使用PasteExcelTable将Excel数据复制到Outlook电子邮件的正文中

2024-10-02 14:25:24 发布

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

Formatted Excel range copied to a Word file

这将从Excel复制一系列单元格,并将它们粘贴到Word文档中,保留格式。代码就是这样的。不过,我还想用单元格样式将数据粘贴到电子邮件正文中。在

import sys
from pathlib import Path
import win32com.client as win32


excel_path = str(Path.cwd() / 'input.xlsx')
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(excel_path)
ws = wb.Worksheets(1)
ws.Range("A1:B2").Copy()
wb.Close()

word_path = str(Path.cwd() / 'output.docx')
word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(word_path)
doc.Content.PasteExcelTable(False, False, True)
doc.Close()

# That works, but now I want to paste the copied Excel range into the body of
# an email. The solution may look something like the following with the "X"
# as a "Selection" or "Range" object for the PasteExcelTable method.

outlook = win32.gencache.EnsureDispatch('Outlook.Application')
new_mail = outlook.CreateItem(0)
new_mail.To = 'person@email.com'

new_mail.Body = ws.Range("A1:B2").PasteExcelTable(False, False, True)

new_mail.Send()
sys.exit()

我相信[PasteExcelTable]2可以像Word文件那样在Outlook中实现,也许有人知道如何做到这一点。在

我没有正确定义范围。我的一个例子是:

^{pr2}$

我知道这可以用VBA来实现,但是我想使用Python,看看PasteExcelTable是否能解决这个问题。如果这是不可能的,我会捕捉一个图像的数据范围,并粘贴到电子邮件。在


Tags: thepathimportfalsenew粘贴mailexcel
2条回答

我无法使用PasteExcelTable,但我可以使用HTMLBody使用以下代码完成此操作:

import sys
from pathlib import Path
import win32com.client as win32
from PIL import ImageGrab

excel_path = str(Path.cwd() / 'input.xlsx')
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(excel_path)
ws = wb.Worksheets(1)

win32c = win32.constants
ws.Range("A1:B2").CopyPicture(Format=win32c.xlBitmap)
img = ImageGrab.grabclipboard()
image_path = str(Path.cwd() / 'test.png')
img.save(image_path)

outlook = win32.gencache.EnsureDispatch('Outlook.Application')
new_mail = outlook.CreateItem(0)
new_mail.To = 'person@email.com'
new_mail.Attachments.Add(Source=image_path)
body = "<h1>Email text...</h1><br><br> <img src=test.png>"
new_mail.HTMLBody = (body)
new_mail.Send()
wb.Close()
sys.exit()

This copies a range of cells from Excel and pastes them into a Word document with formatting preserved. The code works for this. However, I also want to paste the data into the body of an email with the cell styles.

在Outlook中使用实体有三种主要方法:

  1. Body-表示消息正文的纯文本。在
  2. HTMLBody。在
  3. 文字编辑器。Outlook使用Word作为电子邮件编辑器。Inspector类提供WordEditor属性,该属性从表示消息体的Word对象模型返回Document类的实例。或者只需使用MailItem类的[GetInspector]方法来检索Inspector类的实例。你可以在Chapter 17: Working with Item Bodies上读到更多。在

所以,基本上你可以在Outlook的情况下重用Word使用的相同的代码库。在

相关问题 更多 >