【问题标题】:How to copy chart from excel and paste it as chart into powerpoint (not image) using python如何使用python从excel复制图表并将其作为图表粘贴到powerpoint(不是图像)中
【发布时间】: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


    【解决方案1】:

    请在现有代码中尝试 PPTSlide.Shapes.PasteSpecial() 而不是 PPTSlide.Shapes.PasteSpecial(DataType=1)。 这将有助于将源保持在您的形状中,使其保持活力并且不会降低图像质量。

    【讨论】:

      【解决方案2】:

      在现有代码中尝试使用PPTSlide.Shapes.Paste 而不是PasteSpecial

      这将以可编辑的格式复制和粘贴图表,而不是图片。

      我也很努力,发现它很有用。

      【讨论】:

        猜你喜欢
        • 2015-02-06
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        • 2019-11-03
        相关资源
        最近更新 更多