【发布时间】:2020-02-28 05:27:56
【问题描述】:
我有一个 Excel 文件,它根据可用数据生成图表,图表名称为 thisChart。
我想将thisChart从excel文件复制到ppt文件。现在我知道了两种方法,即 VBA 和 python(使用 win32com.client)。 VBA 的问题在于它真的很耗时,而且它会随机崩溃,这需要持续的监督,因此我计划使用 python 来做同样的事情。
经过研究,我发现了 python 中的 win32com.client,它允许我做同样的事情。
我使用以下脚本来执行此操作。
# Grab the Active Instance of Excel.
ExcelApp = win32com.client.GetActiveObject("Excel.Application")
ExcelApp.Visible = True
# Grab the workbook with the charts.
xlWorkbook = ExcelApp.Workbooks.Open(r'C:\Users\prashant.kumar\Desktop\testxl.xlsx')
# Create a new instance of PowerPoint and make sure it's visible.
PPTApp = win32com.client.gencache.EnsureDispatch("PowerPoint.Application")
PPTApp.Visible = True
# Add a presentation to the PowerPoint Application, returns a Presentation Object.
PPTPresentation = PPTApp.Presentations.Add()
# Loop through each Worksheet.
for xlWorksheet in xlWorkbook.Worksheets:
# Grab the ChartObjects Collection for each sheet.
xlCharts = xlWorksheet.ChartObjects()
# Loop through each Chart in the ChartObjects Collection.
for index, xlChart in enumerate(xlCharts):
# Each chart needs to be on it's own slide, so at this point create a new slide.
PPTSlide = PPTPresentation.Slides.Add(Index=index + 1, Layout=12) # 12 is a blank layout
# Display something to the user.
print('Exporting Chart {} from Worksheet {}'.format(xlChart.Name, xlWorksheet.Name))
# Copy the chart.
xlChart.Copy()
# Paste the Object to the Slide
PPTSlide.Shapes.PasteSpecial(DataType=1)
# Save the presentation.
PPTPresentation.SaveAs(r"C:\Users\prashant.kumar\Desktop\outppt")
但它会将图表粘贴为图像,而我希望将图表粘贴为交互式图表(就像在 excel 文件中时的样子)
原因是质量变差了,以后需要的时候在ppt中对图表进行细微的修改也没有太大的灵活性。
这是两个输出的比较
在这里可以看到质量差异,放大后会变得更糟。
现在我的问题是,有什么方法可以使用 python 或任何其他比 VBA 更快的方式将图表从 excel 粘贴到图表格式的 ppt 中?
附言。我不想读取excel文件数据并在python中生成图表然后粘贴到PPT,因为实际的图表非常复杂,可能很难制作
【问题讨论】:
标签: python charts powerpoint win32com python-pptx