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是否能解决这个问题。如果这是不可能的,我会捕捉一个图像的数据范围,并粘贴到电子邮件。在
我无法使用PasteExcelTable,但我可以使用HTMLBody使用以下代码完成此操作:
在Outlook中使用实体有三种主要方法:
MailItem
类的[GetInspector]方法来检索Inspector
类的实例。你可以在Chapter 17: Working with Item Bodies上读到更多。在所以,基本上你可以在Outlook的情况下重用Word使用的相同的代码库。在
相关问题 更多 >
编程相关推荐