Search code examples
office365powerpointms-officeoffice-jsoffice-addins

Update data behind chart in powerpoint through office.js add-in


I am using the new Office.js API for PowerPoint. I've inspected the documentation but couldn't find what I was looking for.

I want to know if it possible to update the data behind an existing chart using Office.js?


Solution

  • I think Office.js may not provide a direct method for changing the data source of an existing chart, However, you can do it by creating a new chart and replacing the existing one with the updated / new data:-

    Office.onReady(function (info) {
        if (info.host === Office.HostType.PowerPoint) {
            // Register event handlers and interact with PowerPoint here
            $(document).ready(function () {
                // Replace "YourChartTitle" with the title of the chart you want to update.
                var chartTitle = "YourChartTitle";
                var newChartData = [
                    [1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]
                ]; // Replace with your new data
    
                PowerPoint.run(function (context) {
                    // Get the current slide
                    var currentSlide = context.presentation.slides.getActiveSlide();
    
                    // Get the existing chart
                    var existingChart = currentSlide.shapes.getByName(chartTitle);
    
                    // Delete the existing chart
                    existingChart.delete();
    
                    // Insert a new chart with the updated data
                    var newChart = currentSlide.shapes.addChart(Office.MailboxEnums.ChartType.ColumnClustered, newChartData, "A1:C3");
    
                    return context.sync();
                })
                .catch(function (error) {
                    console.log(error);
                });
            });
        }
    });