Add Trendline to Excel Chart in Java

Import JAR Dependency (2 Method)

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
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("D:\\Files\\Chart.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);
trendLine.setBackward(0);

//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);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store