Search code examples
c#powerpointoffice-interopnetoffice

changing range of source data for a chart in Powerpoint


I have a powerpoint template with a simple bar chart with (say) 15 rows

Depending of the results of a data lookup occurring in the c# application, using NetOffice Interop I may need to reduce the number of rows that are being displayed

I had hoped that SetSourceData would allow me to override the current selection but

Shape sh = slide.Shapes['mychart'];
NetOffice.PowerPointApi.Chart cx = sh.Chart;
cx.SetSourceData("='Sheet1'!$A$1:$B$5");

seems to be ignored, and the source range remains the full underlying data

(not critical to keep the underlying data, so if there's a way to solve the problem by truncating rows happy to do that)


Solution

  • rather than use the setSourceData (which seems to be ignored unless you're creating a new graph I was able to use the following to update the range that was being used to display data:

    Range tRange = ws.Cells.get_Range("A1","B5");
    ListObject tbl1 = ws.ListObjects[1];  // Table1
    tbl1.Resize(tRange);
    

    where ws was the Worksheet in the workbook for the chartdata in the chart

    Shape sh = slide.Shapes['mychart'];
    Chart cc = sh.Chart;
    ChartData cd = cc.ChartData;
    Workbook wb = (Workbook)cd.Workbook;
    Worksheet ws = (Worksheet)wb.Worksheets[1];