Can't add a trendline to an Excel chart using Office.Interop.Excel and C#


  • I am not able to add a trendline to an Excel chart using 
    Microsoft.Office.Interop.Excel library from Visual Studio 2008, using C#.  
    Works OK with VB .Net, however.
    The following code works as expected using VB .Net:
    Order:=3, Forward:=0, Backward:=0, DisplayEquation:=True, 
    But, neither of these equivalent C# lines compile:
                        Excel.XlTrendlineType.xlPolynomial, //type
                        3,                                  // order
                        Missing.Value,                      // period
                        Missing.Value,                      // forward
                        Missing.Value,                      // backward
                        Missing.Value,                      // intercept
                        true,                               // display equation
                        true,                               // display R squared
    These C# lines seem to work:
    Excel.Series oSeries = (Excel.Series)oChart.SeriesCollection(1);
    But, I still can't get the trendline Add to work, for example:
    oSeries.Trendlines.Add( ...)
    Any ideas why the trendlines automation does not work?
    Thank you,
    Friday, March 07, 2008 6:35 PM


  • The following C# code works for me. I think the issue in your code is that Series.Trendlines is actually a method, not a property collection (see Because C# does not support optional parameters, you must pass System.Type.Missing to the optional index parameter of the Trendlines method to return the entire collection. Also, some explicit casts for some object return values are required, because C# always enforces string type checking.


    Excel.Series series = (Excel.Series)oChart.SeriesCollection(1);
    Excel.Trendlines trendlines = (Excel.Trendlines)series.Trendlines(System.Type.Missing);

    Excel.Trendline newTrendline = trendlines.Add(
        Microsoft.Office.Interop.Excel.XlTrendlineType.xlPolynomial, 3,
        System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
        true, true, System.Type.Missing);


    Please note that this forum is specifically about features in VSTO (Visual Studio Tools for Office) solutions. The following newsgroups are established for general automation questions:


    Working with the Office Primary Interop Assemblies (PIA): office.developer.automation newsgroup


    General programming issues: excel.programming newsgroup


    I hope this helps,

    McLean Schofield

    Friday, March 07, 2008 9:50 PM

All replies