C# 在PPT幻燈片中創建圖表

来源:https://www.cnblogs.com/Yesi/archive/2018/09/19/9674740.html
-Advertisement-
Play Games

圖表能夠很直觀的表現數據在某個時間段的變化趨勢,或者呈現數據的整體和局部之間的相互關係,相較於大篇幅的文本數據,圖表更增加了我們分析數據時選擇的多樣性,是我們挖掘數據背後潛在價值的一種更為有效地方式。在做數據彙報時,常用到PPT幻燈片來輔助工作,下麵的示例中將演示如何通過C#編程在PPT幻燈片中創建 ...


圖表能夠很直觀的表現數據在某個時間段的變化趨勢,或者呈現數據的整體和局部之間的相互關係,相較於大篇幅的文本數據,圖表更增加了我們分析數據時選擇的多樣性,是我們挖掘數據背後潛在價值的一種更為有效地方式。在做數據彙報時,常用到PPT幻燈片來輔助工作,下麵的示例中將演示如何通過C#編程在PPT幻燈片中創建圖表。示例中主要介紹了三種圖表的創建方法,如下:

1. 創建柱形圖表

2. 創建餅狀圖表

3. 創建混合型圖表(柱形圖、折線圖)

 

使用工具Spire.Presentation for .NET

PS:下載安裝後,註意添加引用Spire.Presentation.dll到程式,dll文件可在安裝路徑下的Bin文件夾中獲取。

【示例 1 】創建柱形圖表

步驟 1 :添加using指令

using Spire.Presentation;
using Spire.Presentation.Charts;
using System;
using System.Drawing;

步驟 2 :創建一個PowerPoint文檔

Presentation presentation = new Presentation();

步驟 3 :在幻燈片指定位置繪入指定大小和類型的圖表

RectangleF rect = new RectangleF(40, 50, 680, 500);
IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.Column3DClustered, rect);

步驟 4 :添加圖表數據

//添加圖表名
chart.ChartTitle.TextProperties.Text = "2018年上半年銷量";
chart.ChartTitle.TextProperties.IsCentered = true;
chart.ChartTitle.Height = 30;
chart.HasTitle = true;

//定義一個sting[,]數組
string[,] data = new string[,]
 {
  {"產品大類","1月","2月","3月","4月","5月","6月" },
  {"DW10","1542","1057","1223","1302","1145","1336"},
  {"ZQ13","4587","3658","2515","3154","2984","3890" },
  {"YI73","558","458","369","576","334","482" },
  {"TR11","2011","2485" ,"3010" ,"2785" ,"2225" ,"2476" }
 };

//將數據寫入圖表後臺數據表
for (int i = 0; i < data.GetLength(0); i++)
{
    for (int j = 0; j < data.GetLength(1); j++)
    {
        //將數字類型的字元串轉換為整數
        int number;
        bool result = Int32.TryParse(data[i, j], out number);
        if (result)
        {
            chart.ChartData[i, j].Value = number;
        }
        else
        {
            chart.ChartData[i, j].Value = data[i, j];
        }
    }
}

//設置系列標簽
chart.Series.SeriesLabel = chart.ChartData["B1", "G1"];

//設置類別標簽
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];

//為各個系列賦值
chart.Series[0].Values = chart.ChartData["B2", "B5"];
chart.Series[1].Values = chart.ChartData["C2", "C5"];
chart.Series[2].Values = chart.ChartData["D2", "D5"];
chart.Series[3].Values = chart.ChartData["E2", "E5"];
chart.Series[4].Values = chart.ChartData["F2", "F5"];
chart.Series[5].Values = chart.ChartData["G2", "G5"];

步驟 5 :應用圖表樣式

//應用內置圖標樣式
chart.ChartStyle = ChartStyle.Style12;
//設置系列重疊
chart.OverLap = -50;
//設置類別間距
chart.GapWidth = 200;

步驟 6 :保存文檔

presentation.SaveToFile("柱形圖.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("柱形圖.pptx");

調試運行程式後,生成圖表,如下圖:

全部代碼:

using Spire.Presentation;
using Spire.Presentation.Charts;
using System;
using System.Drawing;

namespace ColumnChart
{
    class Program
    {
        static void Main(string[] args)
        {
            //創建一個PowerPoint文檔
            Presentation presentation = new Presentation();

            //插入柱形圖
            RectangleF rect = new RectangleF(40, 50, 680, 500);
            IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.Column3DClustered, rect);

            //添加圖表名
            chart.ChartTitle.TextProperties.Text = "2018年上半年銷量";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;
            chart.HasTitle = true;

            //定義一個sting[,]數組
            string[,] data = new string[,]
             {
              {"產品大類","1月","2月","3月","4月","5月","6月" },
              {"DW10","1542","1057","1223","1302","1145","1336"},
              {"ZQ13","4587","3658","2515","3154","2984","3890" },
              {"YI73","558","458","369","576","334","482" },
              {"TR11","2011","2485" ,"3010" ,"2785" ,"2225" ,"2476" }
             };

            //將數據寫入圖表後臺數據表
            for (int i = 0; i < data.GetLength(0); i++)
            {
                for (int j = 0; j < data.GetLength(1); j++)
                {
                    //將數字類型的字元串轉換為整數
                    int number;
                    bool result = Int32.TryParse(data[i, j], out number);
                    if (result)
                    {
                        chart.ChartData[i, j].Value = number;
                    }
                    else
                    {
                        chart.ChartData[i, j].Value = data[i, j];
                    }
                }
            }

            //設置系列標簽
            chart.Series.SeriesLabel = chart.ChartData["B1", "G1"];

            //設置類別標簽
            chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];

            //為各個系列賦值
            chart.Series[0].Values = chart.ChartData["B2", "B5"];
            chart.Series[1].Values = chart.ChartData["C2", "C5"];
            chart.Series[2].Values = chart.ChartData["D2", "D5"];
            chart.Series[3].Values = chart.ChartData["E2", "E5"];
            chart.Series[4].Values = chart.ChartData["F2", "F5"];
            chart.Series[5].Values = chart.ChartData["G2", "G5"];

            //應用內置圖標樣式
            chart.ChartStyle = ChartStyle.Style12;

            //設置系列重疊
            chart.OverLap = -50;

            //設置類別間距
            chart.GapWidth = 200;

            //保存並打開文檔
            presentation.SaveToFile("柱形圖.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("柱形圖.pptx");
        }
    }
}
View Code

 

【示例 2 】創建環形圖表

步驟 1 :添加using指令

using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System.Drawing;

步驟 2 :新建一個PPT文件

Presentation presentation = new Presentation();

步驟 3 :插入圓環形圖表

RectangleF rect = new RectangleF(40, 100, 550, 320);
IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.Doughnut, rect, false);

步驟 4 :添加圖表數據內容

//設置圖表名
chart.ChartTitle.TextProperties.Text = "市場份額";
chart.ChartTitle.TextProperties.IsCentered = true;
chart.ChartTitle.Height = 30;
chart.HasTitle = true;

//定義數據
string[] countries = new string[] { "古巴", "墨西哥", "法國", "德國" };
int[] sales = new int[] { 1800, 3000, 5100, 6200 };

//將數據寫入圖表後臺數據表
chart.ChartData[0, 0].Text = "國家";
chart.ChartData[0, 1].Text = "銷售額";
for (int i = 0; i < countries.Length; ++i)
{
    chart.ChartData[i + 1, 0].Value = countries[i];
    chart.ChartData[i + 1, 1].Value = sales[i];
}

步驟 5 :應用圖表標簽

//設置系列標簽
chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];

//設置分類標簽
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];

//為系列賦值
chart.Series[0].Values = chart.ChartData["B2", "B5"];

//添加點到系列
for (int i = 0; i < chart.Series[0].Values.Count; i++)
{
    ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
    cdp.Index = i;
    chart.Series[0].DataPoints.Add(cdp);
}

//為系列里的個點添加背景顏色
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.LightBlue;
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.MediumPurple;
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.DarkGray;
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.DarkOrange;

//設置標簽顯示數值
chart.Series[0].DataLabels.LabelValueVisible = true;

//設置標簽顯示百分比
chart.Series[0].DataLabels.PercentValueVisible = true;

//設置圓環內徑大小
chart.Series[0].DoughnutHoleSize = 60;

步驟 6 :保存文檔

presentation.SaveToFile("環形圖.pptx", FileFormat.Pptx2013);
System.Diagnostics.Process.Start("環形圖.pptx");

圓環圖表創建效果:

全部代碼:

using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace DoughnutChart
{
    class Program
    {
        static void Main(string[] args)
        {
            //創建一個PowerPoint文件
            Presentation presentation = new Presentation();

            //插入圓環圖
            RectangleF rect = new RectangleF(40, 100, 550, 320);
            IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.Doughnut, rect, false);

            //設置圖表名
            chart.ChartTitle.TextProperties.Text = "市場份額";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;
            chart.HasTitle = true;

            //定義數據
            string[] countries = new string[] { "古巴", "墨西哥", "法國", "德國" };
            int[] sales = new int[] { 1800, 3000, 5100, 6200 };

            //將數據寫入圖表後臺數據表
            chart.ChartData[0, 0].Text = "國家";
            chart.ChartData[0, 1].Text = "銷售額";
            for (int i = 0; i < countries.Length; ++i)
            {
                chart.ChartData[i + 1, 0].Value = countries[i];
                chart.ChartData[i + 1, 1].Value = sales[i];
            }

            //設置系列標簽
            chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];

            //設置分類標簽
            chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];

            //為系列賦值
            chart.Series[0].Values = chart.ChartData["B2", "B5"];

            //添加點到系列
            for (int i = 0; i < chart.Series[0].Values.Count; i++)
            {
                ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
                cdp.Index = i;
                chart.Series[0].DataPoints.Add(cdp);
            }

            //為系列里的個點添加背景顏色
            chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.LightBlue;
            chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.MediumPurple;
            chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.DarkGray;
            chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.DarkOrange;

            //設置標簽顯示數值
            chart.Series[0].DataLabels.LabelValueVisible = true;

            //設置標簽顯示百分比
            chart.Series[0].DataLabels.PercentValueVisible = true;

            //設置圓環內徑大小
            chart.Series[0].DoughnutHoleSize = 60;

            //保存文檔
            presentation.SaveToFile("環形圖.pptx", FileFormat.Pptx2013);
            System.Diagnostics.Process.Start("環形圖.pptx");
        }
    }
}
View Code

 

【示例 3 】創建混合型圖表

步驟 1 :添加using指令

using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System;
using System.Data;
using System.Drawing;

步驟 2 :新建文檔

Presentation presentation = new Presentation();

步驟 3 :創建圖表1:柱形圖表

//插入柱形圖
RectangleF rect = new RectangleF(40, 100, 650, 320);
IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.ColumnClustered, rec

//添加表名
chart.ChartTitle.TextProperties.Text = "2017季度銷售情況";
chart.ChartTitle.TextProperties.IsCentered = true;
chart.ChartTitle.Height = 30;
chart.HasTitle = true;

//創建一個DataTable
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("季度", Type.GetType("System.String")));
dataTable.Columns.Add(new DataColumn("銷售額", Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("同比增長率", Type.GetType("System.Decimal")));
dataTable.Rows.Add("1季度", 200, 0.6);
dataTable.Rows.Add("2季度", 250, 0.8);
dataTable.Rows.Add("3季度", 300, 0.6);
dataTable.Rows.Add("4季度", 150, 0.2);            

//將DataTable數據導入圖表後臺數據表
for (int c = 0; c < dataTable.Columns.Count; c++)
{
    chart.ChartData[0, c].Text = dataTable.Columns[c].Caption;
}
for (int r = 0; r < dataTable.Rows.Count; r++)
{
    object[] datas = dataTable.Rows[r].ItemArray;
    for (int c = 0; c < datas.Length; c++)
    {
        chart.ChartData[r + 1, c].Value = datas[c];

    }
}

//設置系列標簽
chart.Series.SeriesLabel = chart.ChartData["B1", "C1"];

//設置類別標簽      
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];

//為系列賦值
chart.Series[0].Values = chart.ChartData["B2", "B5"];
chart.Series[1].Values = chart.ChartData["C2", "C5"];

步驟 4 :添加折線圖

//將系列2的圖表類型改為折線圖
chart.Series[1].Type = ChartType.LineMarkers;

//將系列2顯示到第二根軸
chart.Series[1].UseSecondAxis = true;

//顯示百分比數據
chart.SecondaryValueAxis.NumberFormat = "0%";

//不顯示第二根軸的網格線
chart.SecondaryValueAxis.MajorGridTextLines.FillType = FillFormatType.None;

//設置系列重疊
chart.OverLap = -50;

//設置類別間距
chart.GapWidth = 200;

步驟 5 :保存文件

presentation.SaveToFile("混合圖表.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("混合圖表.pptx");

混合型圖表生成效果:

全部代碼:

using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System;
using System.Data;
using System.Drawing;

namespace 混合圖表
{
    class Program
    {
        static void Main(string[] args)
        {
            //新建一個PowerPoint文檔
            Presentation presentation = new Presentation();

            //插入柱形圖
            RectangleF rect = new RectangleF(40, 100, 650, 320);
            IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.ColumnClustered, rect);

            //添加表名
            chart.ChartTitle.TextProperties.Text = "2017季度銷售情況";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;
            chart.HasTitle = true;

            //創建一個DataTable
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(new DataColumn("季度", Type.GetType("System.String")));
            dataTable.Columns.Add(new DataColumn("銷售額", Type.GetType("System.Int32")));
            dataTable.Columns.Add(new DataColumn("同比增長率", Type.GetType("System.Decimal")));
            dataTable.Rows.Add("1季度", 200, 0.6);
            dataTable.Rows.Add("2季度", 250, 0.8);
            dataTable.Rows.Add("3季度", 300, 0.6);
            dataTable.Rows.Add("4季度", 150, 0.2);            

            //將DataTable數據導入圖表後臺數據表
            for (int c = 0; c < dataTable.Columns.Count; c++)
            {
                chart.ChartData[0, c].Text = dataTable.Columns[c].Caption;
            }
            for (int r = 0; r < dataTable.Rows.Count; r++)
            {
                object[] datas = dataTable.Rows[r].ItemArray;
                for (int c = 0; c < datas.Length; c++)
                {
                    chart.ChartData[r + 1, c].Value = datas[c];

                }
            }

            //設置系列標簽
            chart.Series.SeriesLabel = chart.ChartData["B1", "C1"];

            //設置類別標簽      
            chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];

            //為系列賦值
            chart.Series[0].Values = chart.ChartData["B2", "B5"];
            chart.Series[1].Values = chart.ChartData["C2", "C5"];

            //將系列2的圖表類型改為折線圖
            chart.Series[1].Type = ChartType.LineMarkers;

            //將系列2顯示到第二根軸
            chart.Series[1].UseSecondAxis = true;

            //顯示百分比數據
            chart.SecondaryValueAxis.NumberFormat = "0%";

            //不顯示第二根軸的網格線
            chart.SecondaryValueAxis.MajorGridTextLines.FillType = FillFormatType.None;

            //設置系列重疊
            chart.OverLap = -50;

            //設置類別間距
            chart.GapWidth = 200;

            //保存打開文檔
            presentation.SaveToFile("混合圖表.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("混合圖表.pptx");
        }
    }
}
View Code

註:Spire.Presentation 支持創建多大73種不同的圖表樣式,如下圖

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 嚴格意義上來說,簡單工廠模式並不屬於GoF的23種設計模式,但是它是學習其他工廠模式的基礎和前提條件。理解了簡單工廠模式,學習工廠方法模式和抽象工廠模式會比較容易一些。 簡單工廠模式的定義 定義一個工廠類,他可以根據不同的參數返回不同類的實例。通常情況下,被創建的類的實例通常都具有共同的父類。 簡單 ...
  • ModelValidator主要是應用在ModelMetadata元數據的類型上或類型屬性上。它是驗證的基礎類型,所有的ModelValidatorProviders、DataAnnotationValidator、DataAnnotationValidatorProvider都是主要通過GetVa ...
  • winform 程式調用Windows.Devices.Bluetoot API 實現windows下BLE藍牙設備自動連接,收發數據功能。不需要使用win10的UWP開發。 ...
  • 文檔繼續完善整理中。。。。。。 c.DocumentFilter<SwaggerDocTag>(); /// <summary> /// Swagger註釋幫助類 /// </summary> public class SwaggerDocTag : IDocumentFilter { /// <s ...
  • 添加引用. 綁定命令. ...
  • //定義原子變數 int mituxInt = -1; //原子級別+1值,如果>=0,說明當前鎖為空,可以執行,避免重覆執行 if (Interlocked.Increment(ref mituxInt) <= 0) { if (_serverThread == null || (_serverT... ...
  • 終本案件:http://zxgk.court.gov.cn/zhongben/new_index.html 綜合執行人:http://zxgk.court.gov.cn/zhixing/new_index.html 裁判文書:http://wenshu.court.gov.cn 終本案件和執行人爬取 ...
  • 先看看為什麼要用鎖 需求:多線程處理值的加減 static int NoLockData = 0; public static void NoLockNormalTest(int threadIndex) { while (true)//這是腦殘設計,while(true) { //lock (lo ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...