使用PasteExcelTable通过Python将Excel数据复制到Outlook电子邮件的正文中 [英] Using PasteExcelTable to copy Excel data to the body of an Outlook email with Python

查看:1046
本文介绍了使用PasteExcelTable通过Python将Excel数据复制到Outlook电子邮件的正文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将格式化的Excel范围复制到Word文件

这将从Excel复制一系列单元格并将其粘贴到保留格式设置的Word文档中.该代码为此工作.但是,我也想使用单元格样式将数据粘贴到电子邮件的正文中.

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.

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]

I believe [PasteExcelTable]2 can be used to make this happen with Outlook as it does for Word files and perhaps someone knows how this can be done.

我没有正确定义范围.这是我的尝试之一的示例:

I'm not defining the range correctly. Here's an example of one of my attempts:

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

我知道这可以用VBA来完成,但是我想使用Python并查看PasteExcelTable是否可以解决这个问题.如果不可能,我将捕获数据范围的图像并将其粘贴到电子邮件中.

I know this could be accomplished with VBA, but I want to use Python and to see whether PasteExcelTable will work for this. If it is not possible, I will capture an image of the data range and paste that to the email.

推荐答案

经过数小时的研究和实验,我发现了如何在Outlook中使用PasteExcelTable.我希望这会有所帮助.您只需要剪贴板中有Excel表.

After hours of research and experimentation I found out how to use PasteExcelTable in Outlook. I hope this can be helpful. You only need to have the Excel Table in the clipboard.

import win32com.client


outlook = win32com.client.Dispatch('Outlook.Application')
mail = outlook.CreateItem(0)
mail.To = "person@email.com"
mail.Subject = "Subject"
mail.Display()
inspector = outlook.ActiveInspector()
word_editor = inspector.WordEditor
word_range = word_editor.Application.ActiveDocument.Content
word_range.PasteExcelTable(False, False, True)

这篇关于使用PasteExcelTable通过Python将Excel数据复制到Outlook电子邮件的正文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆