DEV Community


Posted on • Updated on

Add Trendline to Excel Chart in Java

The trendline in Excel chart displays the changing trend of data graphically, and it can be used to forecast or analyze future data. This article will share how to programmatically add trendline to an Excel chart using Free Spire.XLS for Java.

Import Dependency (2 Method)

1# Download the free library and unzip it, then add the Spire.Xls.jar file to your project as dependency.

2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Sample Code

The XlsChartSerie.getTrendLines().add(TrendLineType type) method offered by Free Spire.XLS for Java allows you to add a trendlines in the Excel chart, and then you can set the trendline name, and decide whether to dispaly the equation and R-squared value of the trendline using the methods under IChartTrendLine interface. The comlete sample code is shown as below:

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

        //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

        //Set line type and color

        //Set forward and backward value

        //Display equation on chart

        //Display R-Squared value on chart

        //Save the result file
        workbook.saveToFile("AddTrendline.xlsx", ExcelVersion.Version2013);
Enter fullscreen mode Exit fullscreen mode


Discussion (0)