asp.net使用echarts展示圖表資料

暖楓無敵發表於2015-06-29

百度echarts開發外掛包下載地址:http://download.csdn.net/detail/taomanman/8850699





<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EchartDemo.aspx.cs" Inherits="AT.Web.Demo.EchartDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Echart圖表示例</title>
    <script src="../Themes/Scripts/jquery-1.8.2.min.js"></script>
    <link href="../Themes/Styles/Site.css" rel="stylesheet" type="text/css" />
    <script src="../Themes/Scripts/FunctionJS.js" type="text/javascript"></script>
    <script type="text/javascript">
        //初始化
        $(function () {
            $('#table2').hide();
        })
        //點選切換皮膚
        var IsFixedTableLoad = 1;
        function panel(obj) {
            if (obj == 1) {
                $('#table1').show();
                $('#table2').hide();
            } else if (obj == 2) {
                $('#table1').hide();
                $("#table2").show();
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div class="frmtop">
            <table style="padding: 0px; margin: 0px; height: 100%;" cellpadding="0" cellspacing="0">
                <tr>
                    <td id="menutab" style="vertical-align: bottom;">
                        <div id="tab0" class="Tabsel" onclick="GetTabClick(this);panel(1)">
                            能耗動態
                        </div>
                        <div id="tab1" class="Tabremovesel" onclick="GetTabClick(this);panel(2);">
                            填報動態
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div class="div-frm" style="height: 275px;">
            <%--能耗動態--%>
            <div id="table1">
                <div id="divEnergy" style="width: 610px; height: 220px;"></div>
            </div>
            <%--填報動態--%>
            <div id="table2">
                <div id="divReport" style="width: 750px; height: 250px;"></div>
            </div>
        </div>
    </form>
</body>
</html>
<script src="../Themes/Scripts/echarts/echarts.js"></script>
<script src="../Themes/Scripts/echarts/theme/macarons.js"></script>
<script type="text/javascript">
    var cityClick = '';
    function GetUnitEnergy(unitName) {
        GetCityEnergy(unitName, 2);
    }
    require.config({
        paths: {
            echarts: '../Themes/Scripts/echarts'
        }
    });
    require(
        [
            'echarts',
            'echarts/chart/bar',
            'echarts/chart/line',
            'echarts/chart/pie',
            'echarts/chart/funnel'
        ],
        DrawEChart //非同步載入的回撥函式繪製圖表
    );
    var myEnergyChart;

    var myReportChart;

    //建立ECharts圖表方法
    function DrawEChart(ec) {
        //--- 折柱 ---
        myEnergyChart = ec.init(document.getElementById('divEnergy'), macarons);
        //定義圖表options
        var options = {
            title: {
                text: "",
                subtext: ""
            },
            /*color: ['#0099FF', '#00CC00', '#008080', '#CC6600', '#CC00CC', '#0033CC','#003300', '#FF0000'],*/
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: [" "]
            },
            toolbox: {
                show: true,
                feature: {
                    mark: { show: false },
                    dataView: { show: false, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: false }
                }
            },
            grid: {
                x: 60,
                y: 30,
                x2: 5,
                y2: 30
            },
            calculable: true,
            xAxis: [
                {
                    type: 'category',
                    data: [" "]
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    axisLabel: {
                        fomatter: "."
                    },
                    splitArea: { show: true }
                }
            ],
            series: [{
                name: " ",
                type: "line",
                data: [0]
            }]
        };
        //選擇一個空圖表
        myEnergyChart.setOption(options);
        myReportChart = ec.init(document.getElementById('divReport'), macarons);
        //選擇一個空圖表
        myReportChart.setOption(options);

        // 預設載入填報
        GetReport("1");
        // 預設載入省直
        GetUnitEnergy('34');
    }


    ///點選按鈕獲取圖表資料採用ajax方式
    function GetCityEnergy(cityCode, level) {
        //獲得圖表的options物件
        var options = myEnergyChart.getOption();
        //通過Ajax獲取資料
        $.ajax({
            type: "post",
            async: false, //同步執行
            url: "GetChartData.aspx?type=energyData",
            dataType: "json", //返回資料形式為json
            success: function (result) {
                if (result) {
                    //將返回的category和series物件賦值給options物件內的category和series
                    //因為xAxis是一個陣列 這裡需要是xAxis[i]的形式
                    options.xAxis[0].data = result.category;
                    options.series = result.series;
                    options.legend.data = result.legend;
                    myEnergyChart.setOption(options);
                    myEnergyChart.refresh();
                }
            },
            error: function (errorMsg) {
                alert("圖表資料載入失敗!");
            }
        });
    }

    ///點選按鈕獲取圖表資料採用ajax方式
    function GetReport(code) {
        //獲得圖表的options物件
        var options = myReportChart.getOption();
        //通過Ajax獲取資料
        $.ajax({
            type: "post",
            async: false, //同步執行
            url: "GetChartData.aspx?type=reportData",
            dataType: "json", //返回資料形式為json
            success: function (result) {
                if (result) {
                    //將返回的category和series物件賦值給options物件內的category和series
                    //因為xAxis是一個陣列 這裡需要是xAxis[i]的形式
                    //myReportChart.clear();
                    options.xAxis[0].data = result.category;
                    options.series = result.series;
                    options.legend.data = result.legend;
                    myReportChart.setOption(options);
                }
            },
            error: function (errorMsg) {
                alert("圖表資料載入失敗!");
            }
        });
    }

    //初始載入圖表資料
    $(function () {
        GetCityEnergy("", "");
        GetUnitEnergy("");
    });
</script>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AT.Web.Demo
{
    public partial class EchartDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetChartData.aspx.cs" Inherits="AT.Web.Demo.GetChartData" %>

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AT.Web.Demo
{
    public partial class GetChartData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string type = Request["type"];
            if (!string.IsNullOrEmpty(type))
            {
                switch (type)
                {
                    case "energyData":
                        GetEnergyDataAjaxData("", "");
                        break;
                    case "reportData":
                        GetReportDataAjaxData("");
                        break;
                }
            }
        }

        /// <summary>
        /// 獲得資料且用Json格式資料返回
        /// </summary>
        private void GetEnergyDataAjaxData(string level, string code)
        {
            //考慮到圖表的category是字串陣列 這裡定義一個string的List
            List<string> categoryList = new List<string>();
            //考慮到圖表的series資料為一個物件陣列 這裡額外定義一個series的類
            List<Series> seriesList = new List<Series>();

            //考慮到Echarts圖表需要設定legend內的data陣列為series的name集合這裡需要定義一個legend陣列
            List<string> legendList = new List<string>();

            DataTable dt = null;
            using (SqlConnection con = new SqlConnection("Data Source=.;User ID=sa;Password=111111;Database=AT_DB;"))
            {
                string strSQL = "select top 12 * from T_EchartData1";
                using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, con))
                {
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    dt = ds.Tables[0];
                }
            }
            //Response.Write(dt.Rows.Count+"條資料!");
            //設定legend陣列
            legendList.Add("今年能耗"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("去年能耗"); //這裡的名稱必須和series的每一組series的name保持一致


            Series thisSeriesObj = new Series();
            thisSeriesObj.id = 0;
            thisSeriesObj.name = "今年能耗";
            thisSeriesObj.type = "line"; //線性圖呈現
            thisSeriesObj.data = new List<object>();
            thisSeriesObj.itemStyle = new itemStyle { normal = new normal { color = "#0099FF" } };
            Series lastSeriesObj = new Series();
            lastSeriesObj.id = 1;
            lastSeriesObj.name = "去年能耗";
            lastSeriesObj.type = "line"; //線性圖呈現
            lastSeriesObj.data = new List<object>();
            lastSeriesObj.itemStyle = new itemStyle { normal = new normal { color = "#00CC00" } };
            foreach (DataRow dr in dt.Rows)
            {
                categoryList.Add(dr[0].ToString() + "月");
                thisSeriesObj.data.Add(dr[1]);
                lastSeriesObj.data.Add(dr[2]);
            }
            //將sereis物件壓入sereis陣列列表內
            seriesList.Add(thisSeriesObj);
            seriesList.Add(lastSeriesObj);

            //最後呼叫相關函式將List轉換為Json
            //因為我們需要返回category和series、legend多個物件 這裡我們自己在new一個新的物件來封裝這兩個物件
            var newObj = new
            {
                category = categoryList,
                series = seriesList,
                legend = legendList
            };
            //Response返回新物件的json資料
            Response.Write(JsonConvert.SerializeObject(newObj, Formatting.None));
            Response.End();
        }

        /// <summary>
        /// 獲得資料且用Json格式資料返回
        /// </summary>
        private void GetReportDataAjaxData(string code)
        {
            //考慮到圖表的category是字串陣列 這裡定義一個string的List
            List<string> categoryList = new List<string>();
            //考慮到圖表的series資料為一個物件陣列 這裡額外定義一個series的類
            List<Series> seriesList = new List<Series>();

            //考慮到Echarts圖表需要設定legend內的data陣列為series的name集合這裡需要定義一個legend陣列
            List<string> legendList = new List<string>();

            DataTable dt = null;
            using (SqlConnection con = new SqlConnection("Data Source=.;User ID=sa;Password=111111;Database=AT_DB;"))
            {
                string strSQL = "select * from T_EchartData2";
                using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, con))
                {
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    dt = ds.Tables[0];
                }
            }
            //Response.Write(dt.Rows.Count + "條資料!");
            //設定legend陣列
            legendList.Add("電"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("水"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("燃煤"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("天然氣"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("汽油"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("柴油"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("熱力"); //這裡的名稱必須和series的每一組series的name保持一致
            legendList.Add("其他"); //這裡的名稱必須和series的每一組series的name保持一致


            Series dianSeries = new Series();
            dianSeries.id = 0;
            dianSeries.name = "電";
            dianSeries.type = "line"; //線性圖呈現
            dianSeries.data = new List<object>();
            dianSeries.itemStyle = new itemStyle { normal = new normal { color = "#0099FF" } };
            Series shuiSeries = new Series();
            shuiSeries.id = 1;
            shuiSeries.name = "水";
            shuiSeries.type = "line"; //線性圖呈現
            shuiSeries.data = new List<object>();
            shuiSeries.itemStyle = new itemStyle { normal = new normal { color = "#00CC00" } };
            Series yuanmeiSeries = new Series();
            yuanmeiSeries.id = 2;
            yuanmeiSeries.name = "燃煤";
            yuanmeiSeries.type = "line"; //線性圖呈現
            yuanmeiSeries.data = new List<object>();
            yuanmeiSeries.itemStyle = new itemStyle { normal = new normal { color = "#008080" } };
            Series tianranqiSeries = new Series();
            tianranqiSeries.id = 3;
            tianranqiSeries.name = "天然氣";
            tianranqiSeries.type = "line"; //線性圖呈現
            tianranqiSeries.data = new List<object>();
            tianranqiSeries.itemStyle = new itemStyle { normal = new normal { color = "#CC6600" } };
            Series qiyouSeries = new Series();
            qiyouSeries.id = 4;
            qiyouSeries.name = "汽油";
            qiyouSeries.type = "line"; //線性圖呈現
            qiyouSeries.data = new List<object>();
            qiyouSeries.itemStyle = new itemStyle { normal = new normal { color = "#CC00CC" } };
            Series chaiyouSeries = new Series();
            chaiyouSeries.id = 5;
            chaiyouSeries.name = "柴油";
            chaiyouSeries.type = "line"; //線性圖呈現
            chaiyouSeries.data = new List<object>();
            chaiyouSeries.itemStyle = new itemStyle { normal = new normal { color = "#0033CC" } };
            Series reliSeries = new Series();
            reliSeries.id = 6;
            reliSeries.name = "熱力";
            reliSeries.type = "line"; //線性圖呈現
            reliSeries.data = new List<object>();
            reliSeries.itemStyle = new itemStyle { normal = new normal { color = "#003300" } };
            Series qitaSeries = new Series();
            qitaSeries.id = 7;
            qitaSeries.name = "其他";
            qitaSeries.type = "line"; //線性圖呈現
            qitaSeries.data = new List<object>();
            qitaSeries.itemStyle = new itemStyle { normal = new normal { color = "#FF0000" } };
            foreach (DataRow dr in dt.Rows)
            {
                categoryList.Add(string.Format("{0}年{1}月", dr["ReportYear"], dr["ReportMonth"]));
                dianSeries.data.Add(string.IsNullOrEmpty(dr["DIAN"].ToString()) ? 0 : dr["DIAN"]);
                shuiSeries.data.Add(string.IsNullOrEmpty(dr["SHUI"].ToString()) ? 0 : dr["SHUI"]);
                yuanmeiSeries.data.Add(string.IsNullOrEmpty(dr["YUANMEI"].ToString()) ? 0 : dr["YUANMEI"]);
                tianranqiSeries.data.Add(string.IsNullOrEmpty(dr["TIANRQ"].ToString()) ? 0 : dr["TIANRQ"]);
                qiyouSeries.data.Add(string.IsNullOrEmpty(dr["QIYOU"].ToString()) ? 0 : dr["QIYOU"]);
                chaiyouSeries.data.Add(string.IsNullOrEmpty(dr["CHAIYOU"].ToString()) ? 0 : dr["CHAIYOU"]);
                reliSeries.data.Add(string.IsNullOrEmpty(dr["RELI"].ToString()) ? 0 : dr["RELI"]);
                qitaSeries.data.Add(string.IsNullOrEmpty(dr["QTNY"].ToString()) ? 0 : dr["QTNY"]);
            }
            //將sereis物件壓入sereis陣列列表內
            seriesList.Add(dianSeries);
            seriesList.Add(shuiSeries);
            seriesList.Add(yuanmeiSeries);
            seriesList.Add(tianranqiSeries);
            seriesList.Add(qiyouSeries);
            seriesList.Add(chaiyouSeries);
            seriesList.Add(reliSeries);
            seriesList.Add(qitaSeries);

            //最後呼叫相關函式將List轉換為Json
            //因為我們需要返回category和series、legend多個物件 這裡我們自己在new一個新的物件來封裝這兩個物件
            var newObj = new
            {
                category = categoryList,
                series = seriesList,
                legend = legendList
            };
            //Response返回新物件的json資料
            Response.Write(JsonConvert.SerializeObject(newObj, Formatting.None));
            Response.End();
        }
    }
    /// <summary>
    /// 定義一個Series類 設定其每一組sereis的一些基本屬性
    /// </summary>
    class Series
    {
        /// <summary>
        /// sereis序列組id
        /// </summary>
        public int id
        {
            get;
            set;
        }

        /// <summary>
        /// series序列組名稱
        /// </summary>
        public string name
        {
            get;
            set;
        }

        /// <summary>
        /// series序列組呈現圖表型別(line、column、bar等)
        /// </summary>
        public string type
        {
            get;
            set;
        }

        /// <summary>
        /// series序列組的itemstyle
        /// </summary>
        public object itemStyle
        {
            get;
            set;
        }
        /// <summary>
        /// series序列組的資料為資料型別陣列
        /// </summary>
        public List<object> data
        {
            get;
            set;
        }
    }

    class normal
    {
        /// <summary>
        /// color
        /// </summary>
        public string color
        {
            get;
            set;
        }
    }

    class itemStyle
    {
        /// <summary>
        /// normal
        /// </summary>
        public object normal
        {
            get;
            set;
        }
    }
}



相關文章