本文內容分享通過C#程序代碼給PPT文檔中的圖表添加數據趨勢線的方法。
支持趨勢線的圖表類型包括二維面積圖、條形圖、柱形圖、柱形圖、股價圖、xy (散點圖) 和氣泡圖中;不能向三維、堆積、雷達圖、餅圖、曲面圖或圓環圖的數據系列添加趨勢線。可添加的趨勢線類型包括6種,即多項式(Polynomial)趨勢線、指數(Exponential)趨勢線、線性(Linear)趨勢線、對數(Logarithmic)趨勢線、冪(Power)趨勢線、移動平均(移動平均)趨勢線。下面以柱形圖表為例,添加趨勢線。方法及步驟參考如下。
【程序環境】
- Visual Studio 2017
- .net framework 4.6.1
- Power Point 2013 (.pptx)
- PPT類庫:Spire.Presentation for .NET
1. 實現方法
通過調用Spire.Presentation.dll中Itrendline接口提供的方法AddTrendLine(TrendlinesType type)來添加趨勢線,編輯代碼前,請先按照如下第2點中的方法在程序中添加引用Spire.Presentation.dll。
2. 關於PPT類庫安裝:可直接通過Nuget搜索安裝到程序。具體方法如下:
鼠標右鍵點擊“引用”,“管理Nuget包”,然后按照下圖步驟操作;



完成安裝:

【C#】
using Spire.Presentation; using Spire.Presentation.Charts; namespace AddTrendline { class Program { static void Main(string[] args) { //創建Presentation類的實例 Presentation ppt = new Presentation(); //加載PowerPoint文檔 ppt.LoadFromFile("test.pptx"); //獲取第一張幻燈片 ISlide slide = ppt.Slides[0]; //獲取幻燈片上的第一個圖表 IChart chart = (IChart)slide.Shapes[0]; //給圖表的第一個數據系列添加線性趨勢線 ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Polynomial);//多項式趨勢線 //ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Exponential);//指數趨勢線 //ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Linear);//線性趨勢線 //ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Logarithmic);//對數趨勢線 //ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Power);//冪趨勢線 //ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.MovingAverage);//移動平均趨勢線 //顯示公式 trendLine.displayEquation = true; //顯示R平方值 trendLine.displayRSquaredValue = true; //保存結果文檔 ppt.SaveToFile("AddTrendline.pptx", FileFormat.Pptx2013); System.Diagnostics.Process.Start("AddTrendline.pptx"); } } }
趨勢線添加效果:

【vb.net】
Imports Spire.Presentation Imports Spire.Presentation.Charts Namespace AddTrendline Class Program Private Shared Sub Main(args As String()) '創建Presentation類的實例 Dim ppt As New Presentation() '加載PowerPoint文檔 ppt.LoadFromFile("test.pptx") '獲取第一張幻燈片 Dim slide As ISlide = ppt.Slides(0) '獲取幻燈片上的第一個圖表 Dim chart As IChart = DirectCast(slide.Shapes(0), IChart) '給圖表的第一個數據系列添加線性趨勢線 Dim trendLine As ITrendlines = chart.Series(0).AddTrendLine(TrendlinesType.Polynomial) '多項式趨勢線 'ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Exponential); '指數趨勢線 'ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Linear); '線性趨勢線 'ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Logarithmic); '對數趨勢線 'ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.Power); '冪趨勢線 'ITrendlines trendLine = chart.Series[0].AddTrendLine(TrendlinesType.MovingAverage); '移動平均趨勢線 '顯示公式 trendLine.displayEquation = True '顯示R平方值 trendLine.displayRSquaredValue = True '保存結果文檔 ppt.SaveToFile("AddTrendline.pptx", FileFormat.Pptx2013) System.Diagnostics.Process.Start("AddTrendline.pptx") End Sub End Class End Namespace
—End—
