我希望使用PasteSpecial复制和粘贴Excel单元格范围到Powerpoint,同时保留Excel单元格格式。我使用Office 2016。
我的Excel工作簿如下所示:
您可以在这里下载Excel文件:https://docs.google.com/spreadsheets/d/1uicqSQEEMJIttxW6r1_E8higTk2HXbtC/edit?usp=sharing&ouid=103651073926513131793&rtpof=true&sd=true
我希望使用第二个粘贴选项(**Keep Source Formatting (K)
**),在中复制单元格的手动复制和Powerpoint中的“特殊粘贴”
手动操作的结果是一个具有Excel源代码格式的可编辑表:
我使用以下代码创建powerpoint演示文稿,并将表数据复制到演示文稿的第一张幻灯片:
import win32com.client
# initialize Powerpoint and get slide object
ppt_app = win32com.client.Dispatch("PowerPoint.Application")
ppt_presentation = ppt_app.Presentations.Add(True)
ppt_presentation.Slides.Add(1, 12)
ppt_slide = ppt_presentation.Slides(1)
# load Excel file and get worksheet object
excel_app = win32com.client.Dispatch("Excel.Application")
workbook = excel_app.Workbooks.Open(Filename="my_excel_file.xlsx", ReadOnly=1)
worksheet = workbook.Sheets(1)
worksheet.Range("A1:H8").Copy() # select cells and copy to clipboard
# paste cells to Powerpoint slide
ppt_slide.Shapes.PasteSpecial(DataType=0, Link=False)
由于Python脚本,单元格作为可编辑数据被复制到Powerpoint (这是我想要的,而不是图像),但是单元格格式丢失了:
脚本显然应用了第一个粘贴选项(**Use Destination Theme (H)
**).我想知道如何在这里指定第二个粘贴选项,以保持单元格格式。
我尝试了不同的DataType选项的PasteSpecial
方法,但它没有工作。要么不应用任何格式,要么将单元格粘贴为图像对象。
ppt_slide.Shapes.PasteSpecial(DataType=0, Link=False)
下面列出了所有可用的DataType选项(PpPasteDataType
)的列表:https://learn.microsoft.com/en-us/office/vba/api/powerpoint.pppastedatatype
PasteSpecial
方法记录在这里:https://learn.microsoft.com/en-us/office/vba/api/powerpoint.shapes.pastespecial
有没有人知道如何在不丢失格式的情况下粘贴Excel单元格?谢谢你!!
发布于 2022-09-27 00:15:28
我刚刚找到了一个解决办法,避免了Shapes
对象的Shapes
方法。相反,我使用Powerpoint应用程序对象的宏执行方法:
ppt_app.CommandBars.ExecuteMso("PasteSourceFormatting")
在这里,完整的工作代码:
import win32com.client
# initialize Powerpoint and get slide object
ppt_app = win32com.client.Dispatch("PowerPoint.Application")
ppt_presentation = ppt_app.Presentations.Add(True)
ppt_presentation.Slides.Add(1, 12)
# load Excel file and get worksheet object
excel_app = win32com.client.Dispatch("Excel.Application")
workbook = excel_app.Workbooks.Open(Filename="my_excel_file.xlsx", ReadOnly=1)
worksheet = workbook.Sheets(1)
worksheet.Range("A1:H8").Copy() # select cells and copy to clipboard
# paste cells to Powerpoint slide with macro command
ppt_app.CommandBars.ExecuteMso("PasteSourceFormatting")
https://stackoverflow.com/questions/73856399
复制相似问题