Skip to content Skip to sidebar Skip to footer

How Does One Define , Extract And Replace Data From A Chart In An Existing Powerpoint Using Python

Currently I am using the following code to define and replace Placeholder (Text data) in existing Powerpoint presentations. current_dir = os.path.dirname(os.path.realpath(__file_

Solution 1:

Yes, it's possible to do that. The documentation will be your best source.

This will find the chart shapes:

for shape in slide.shapes:
    if shape.has_chart:
        chart = shape.chart
        print('found a chart')

Data is extracted from the chart series(es):

forseriesin chart.series:
    forvaluein series.values:
        print(value)

Data is replaced by creating a new ChartData object and calling .replace_data() on the chart using that chart data object:

chart_data = ChartData(...)
...# add categories, series with values, etc.
chart.replace_data(chart_data)

http://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.chart.Chart.replace_data

Solution 2:

Adding to the answer by @scanny above, this worked for me:

if shape.name == 'Chart1':
    chart = shape.chart
    print(shape.name)

    for series in chart.plots:
        print(list(series.categories))
        cat = list(series.categories)

    for series in chart.series:
        ser = series.values
        print(series.values)

    try:    
    # ---define new chart data---
        chart_data = CategoryChartData()
        chart_data.categories = cat
        chart_data.add_series('category', df['column'])
        # ---replace chart data---
        chart.replace_data(chart_data)
    except KeyError:
        continue

Using the code above, you can print the categories and the series values, then replace them with your new values (while keeping category the same).

I added the KeyError exception because without it, you get a "rId3" error. From the forums it seems like there is some XML writing issue in writing to PPTX.

Post a Comment for "How Does One Define , Extract And Replace Data From A Chart In An Existing Powerpoint Using Python"