This article demonstrates how to add Trendline to an Excel chart and read the equation of the Trendline using Spire.XLS for Java.
Add Trendline
import com.spire.xls.*; import com.spire.xls.core.IChartTrendLine; import java.awt.*; public class AddTrendline { public static void main(String[] args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load the Excel file workbook.loadFromFile("test.xlsx"); //Get the first chart in the first worksheet Chart chart = workbook.getWorksheets().get(0).getCharts().get(0); //Add a Trendline to the first series of the chart IChartTrendLine trendLine = chart.getSeries().get(0).getTrendLines().add(TrendLineType.Linear); //Set Trendline name trendLine.setName("Linear(Series1)"); //Set line type and color trendLine.getBorder().setPattern(ChartLinePatternType.DashDot); trendLine.getBorder().setColor(Color.blue); //Set forward and backward value trendLine.setForward(0.5); trendLine.setBackward(0.5); //Set intercept value trendLine.setIntercept(5); //Display equation on chart trendLine.setDisplayEquation(true); //Display R-Squared value on chart trendLine.setDisplayRSquared(true); //Save the result file workbook.saveToFile("AddTrendline.xlsx", ExcelVersion.Version2013); } }
Read Trendline equation
import com.spire.xls.Chart; import com.spire.xls.Workbook; import com.spire.xls.core.IChartTrendLine; public class ReadEquationOfTrendline { public static void main(String[] args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load the Excel file workbook.loadFromFile("AddTrendline.xlsx"); //Get the first chart in the first worksheet Chart chart = workbook.getWorksheets().get(0).getCharts().get(0); //Read the equation of the first series of the chart IChartTrendLine trendLine = chart.getSeries().get(0).getTrendLines().get(0); String equation = trendLine.getFormula(); System.out.println("The equation is: " + equation); } }