本文将介绍如何使用Spire.XLS for Java给Excel图表添加趋势线以及读取趋势线的公式。
添加趋势线
import com.spire.xls.*;
import com.spire.xls.core.IChartTrendLine;
import java.awt.*;
public class AddTrendline {
    public static void main(String[] args){
        //加载Excel文档
        Workbook workbook = new Workbook();
        workbook.loadFromFile("test.xlsx");
        //获取第一个工作表中的第一个图表
        Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);
        //给图表的第一个数据系列添加趋势线(支持Linear、Exponential、Moving_Average等6种类型)
        IChartTrendLine trendLine = chart.getSeries().get(0).getTrendLines().add(TrendLineType.Linear);
        //设置趋势线的名称
        trendLine.setName("Linear(Series1)");
        //设置趋势线的线条类型和颜色
        trendLine.getBorder().setPattern(ChartLinePatternType.DashDot);
        trendLine.getBorder().setColor(Color.blue);
        //设置趋势线向前和向后延伸的单位数
        trendLine.setForward(0.5);
        trendLine.setBackward(0.5);
        //设置趋势线的截距
        trendLine.setIntercept(5);
        //显示公式
        trendLine.setDisplayEquation(true);
        //显示R平方值
        trendLine.setDisplayRSquared(true);
        //保存文档
        workbook.saveToFile("AddTrendline.xlsx", ExcelVersion.Version2013);
    }
}
读取趋势线公式
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){
        //加载Excel文档
        Workbook workbook = new Workbook();
        workbook.loadFromFile("AddTrendline.xlsx");
        //获取第一个工作表中的第一个图表
        Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);
        //获取图表的第一个数据系列的趋势线
        IChartTrendLine trendLine = chart.getSeries().get(0).getTrendLines().get(0);
        String equation = trendLine.getFormula();
        System.out.println("公式: " + equation);
    }
}
 



 
					



