How to extract the trendline equation from an Excel chart

Excel provides an option to display the trendline equation when we add a trendline on a chart. Sometimes, we may have the requirement of extracting the trendline equation from the chart. This article introduces a simple method to implement this aim by using Spire.XLS.

For demonstration, we used a sample chart which contains a trendline equation: y=2x – 1.

How to extract the trendline equation from an Excel chart

Code snippets:

Step 1: Instantiate a Workbook object and load the Excel document.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the chart from the first worksheet.

Chart chart = workbook.Worksheets[0].Charts[0];

Step 3: Get the trendline of the chart and then extract the equation of the trendline.

IChartTrendLine trendLine = chart.Series[0].TrendLines[0];
string formula = trendLine.Formula;

Effective screenshot:

How to extract the trendline equation from an Excel chart

Full code:

[C#]
using System;
using Spire.Xls;
using Spire.Xls.Core;

namespace Extract_the_equation
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Chart chart = workbook.Worksheets[0].Charts[0];
            IChartTrendLine trendLine = chart.Series[0].TrendLines[0];
            string formula = trendLine.Formula;
            Console.WriteLine("The equation is:\n" +formula);
            Console.ReadKey();
        }
    }
}
[VB.NET]
Imports Spire.Xls
Imports Spire.Xls.Core

Namespace Extract_the_equation
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx")
			Dim chart As Chart = workbook.Worksheets(0).Charts(0)
			Dim trendLine As IChartTrendLine = chart.Series(0).TrendLines(0)
			Dim formula As String = trendLine.Formula
			Console.WriteLine(Convert.ToString("The equation is:" & vbLf) & formula)
			Console.ReadKey()
		End Sub
	End Class
End Namespace