分享

ASP.NET+JQuery+.Ashx实现+百度Echarts 实现动态柱状图数据图形报表的统计

 陈永正的图书馆 2016-11-28

在目前的一个项目中,需要用到报表表现数据,这些数据有多个维度,需要同时表现出来,同时可能会有大量数据呈现的需求,经过几轮挑选,最终选择了百度的echarts作为报表基础类库。echarts功能强大,界面优美。要呈现的数据就用柱状图来显示了,柱状图更直观的显示出客户最想要的东西。

百度echarts简介请参考

http://echarts./doc/example.html


最终效果图如下:


JS代码:

 <!-- Charts Layout Stylesheet -->
    <link href="assets/css/echartsHome.css" rel="stylesheet"/>
    <script src="assets/js/esl.js"></script>
    <script src="assets/js/codemirror.js"></script>

HTML代码:(放在中间呈现)

  <div id="barCharts" class="main" ></div>

     <script src="assets/js/jQuery-1.8.2.min.js"></script>

    <script src="assets/js/echarts-map.js"></script>
     <script src="assets/js/EchartsJson.js"></script>


EchartsJson JS里面的代码如下:

[javascript] view plain copy
在CODE上查看代码片派生到我的代码片
  1. function needMap() {  
  2.          var href = location.href;  
  3.          return href.indexOf('map') != -1  
  4.         || href.indexOf('mix3') != -1  
  5.         || href.indexOf('mix5') != -1  
  6.         || href.indexOf('dataRange') != -1;  
  7.   
  8.      }  
  9.   
  10.      var fileLocation = needMap() ? 'assets/js/echarts-map' : 'assets/js/echarts';  
  11.      require.config({  
  12.          paths: {  
  13.              echarts: fileLocation,'echarts/assets/js/pie': fileLocation,   
  14.      'echarts/assets/js/map': fileLocation,  
  15.          }  
  16.      });  
  17.   
  18.      require(  
  19.         [  
  20.             'echarts','echarts/chart/pie',needMap() ? 'echarts/chart/map' : 'echarts'  
  21.         ],  
  22.          DrawCharts  
  23.    );  
  24.      function DrawCharts(ec) {  
  25.          FunDraw2(ec);  
  26.      }  
  27.   
  28.      function FunDraw2(ec) {  
  29.          //--- 柱状图 ---  
  30.          var myChart = ec.init(document.getElementById('barCharts'));  
  31.          myChart.showLoading({  
  32.              text: "加载中...请等待"  
  33.          });  
  34.          myChart.hideLoading();  
  35.          myChart.setOption({  
  36.              title: {  
  37.                  text: '本月每天订单数量统计(单)[周日除外]',  
  38.                  subtext: '数据来自WMS统计'  
  39.              },  
  40.              tooltip: {  
  41.                  trigger: 'item',  
  42.                  axisPointer: {  
  43.                      type: 'shadow'  
  44.                  }  
  45.              },  
  46.              legend: {  
  47.                  data: [],  
  48.                  x: 'right',  
  49.              },  
  50.              toolbox: {  
  51.                  show: true, orient: 'vertical',  
  52.                  y: 'center',  
  53.                  feature: {  
  54.                      magicType: { show: true, type: ['line', 'bar'] },  
  55.                      restore: { show: true },  
  56.                      saveAsImage: { show: true }  
  57.                  }  
  58.              },  
  59.              calculable: true,  
  60.              xAxis: { data: [], orient: 'vertical' },  
  61.              yAxis: { type: 'value' },  
  62.              series: []  
  63.          });  
  64.          // 通过Ajax获取数据  
  65.          $.ajax({  
  66.              type: "post",  
  67.              async: false, //同步执行  
  68.              url: "SearchHandler.ashx?BarType=BarChart",  
  69.              dataType: "json", //返回数据形式为json  
  70.              success: function (result) {  
  71.                  if (result) {  
  72.                      //将返回的category和series对象赋值给options对象内的category和series  
  73.                      myChart._option.xAxis.data = result.category;  
  74.                      myChart._option.series = result.series;  
  75.                      myChart._option.legend.data = result.legend;  
  76.                      myChart.hideLoading();  
  77.                      myChart.setOption(myChart._option);  
  78.                  }  
  79.              },  
  80.              error: function (errorMsg) {  
  81.                  alert("每月订单数量统计数据请求失败。");  
  82.              }  
  83.          });  
  84.   
  85.      }  

C#代码如下:

[csharp] view plain copy
在CODE上查看代码片派生到我的代码片
  1. #region // 本月每天订单数统计  
  2.  if (!string.IsNullOrEmpty(context.Request["BarType"]))  
  3.  {  
  4. //图表的category是字符串数组形式显示  
  5. List<string> categoryList = new List<string>();//{"周一","周二", "周三", "周四", "周五","周六"};  
  6. //图表的series数据为一个对象数组 需定义一个series的类  
  7. List<Series> seriesList = new List<Series>();  
  8.   
  9. //Echarts图表需要设置legend内的data数组为series的name集合这里需要定义一个legend数组  
  10. List<string> legendList = new List<string>();  
  11. //设置legend数组  
  12. legendList.Add("每天订单数(单)"); //这里的名称必须和series类里面的name保持一致  
  13.   
  14. //定义一个Series对象  
  15. Series seriesObj = new Series();  
  16. seriesObj.name = "每天订单数(单)";  
  17. seriesObj.type = "bar"; //柱状图显示,可以是其他  
  18. seriesObj.data = new List<int>(); //初始化seriesObj.data 否则data.Add(x)添加时会报错  
  19.   
  20. using (PortalSearchDataContext db = new PortalSearchDataContext())  
  21. {  
  22.      List<MonethOrdersNo> getMonthData = (from t in db.DOC_Order_Header  
  23.                                           where  
  24.                                             t.OrderTime >= startMonth.Date.Date && t.OrderTime <= DateTime.Parse(endMonth.Date.ToString("yyyy-MM-dd 23:59"))  
  25.                                           group t by new  
  26.                                           {  
  27.                                                Day = t.OrderTime.Date  
  28.                                           } into g  
  29.                                           select new MonethOrdersNo  
  30.                          {  
  31.                               Day = g.Key.Day,  
  32.                               DayOrderNo = g.Count()  
  33.                          }).OrderBy(x => x.Day).ToList<MonethOrdersNo>();  
  34.      //设置数据  
  35.      for (int i = 0; i < getMonthData.Count(); i++)  
  36.      {  
  37.           //加入category数组  
  38.           categoryList.Add(getMonthData[i].Day.Value.ToString("yyyy-MM-dd"));  
  39.           //为series序列数组中data添加数据  
  40.           seriesObj.data.Add(getMonthData[i].DayOrderNo);  
  41.      }  
  42.   
  43. }  
  44. //将sereis对象压入sereis数组列表内  
  45. seriesList.Add(seriesObj);  
  46.   
  47. //结果显示需要category和series、legend多个对象 因此new一个新的对象来封装返回的多个对象  
  48. var newObj = new  
  49. {  
  50.      category = categoryList,  
  51.      series = seriesList,  
  52.      legend = legendList  
  53. };  
  54. //将List转换为Json数据并Response返回新对象  
  55. context.Response.Write(newObj.ToJson());   context.Response.End();  
  56.  }  
  57.  #endregion  

要引用JOSN序列化代码:JsonHelper

首先去下载Newtonsoft.Json.dll 然后在项目中添加引用,(在下载附件里面有)

[csharp] view plain copy
在CODE上查看代码片派生到我的代码片
  1. using System.Data;  
  2. using System.IO;  
  3. using System.Runtime.Serialization.Json;  
  4. using System.Text;  
  5. using System.Collections.Generic;  
  6. using System.Xml.Serialization;  
  7. using System;  
  8. using System.Reflection;  
  9. namespace PortalSearch.model  
  10. {  
  11.      /// <summary>  
  12.      /// 注意约束,所转化涉及到的对象必须加上 [DataContractAttribute]  [DataMember(Name = "name")]  
  13.      /// </summary>  
  14.      public static class JsonHelper  
  15.      {  
  16.           public static string XMLSerialize<T>(T t)  
  17.           {  
  18.   
  19.                using (StringWriter sw = new StringWriter())  
  20.                {  
  21.                     try  
  22.                     {  
  23.                          XmlSerializer xz = new XmlSerializer(typeof(T));  
  24.                          xz.Serialize(sw, t);  
  25.                          return sw.ToString();  
  26.                     }  
  27.                     catch (Exception e)  
  28.                     {  
  29.                          //LogHelper.Log(e.Message + e.StackTrace);  
  30.                     }  
  31.                     return "";  
  32.                }  
  33.           }  
  34.   
  35.   
  36.           public static T XMLDeserialize<T>(T t, string s)  
  37.           {  
  38.   
  39.   
  40.                using (StringReader sr = new StringReader(s))  
  41.                {  
  42.                     try  
  43.                     {  
  44.                          XmlSerializer xz = new XmlSerializer(typeof(T));  
  45.                          return (T)xz.Deserialize(sr);  
  46.                     }  
  47.                     catch (Exception e)  
  48.                     {  
  49.                          //LogHelper.Log(e.Message + e.StackTrace);  
  50.                     }  
  51.   
  52.                }  
  53.                return default(T);  
  54.           }  
  55.   
  56.   
  57.   
  58.           public static string ToJson(this object obj)  
  59.           {  
  60.                return NewtonsoftJson(obj);  
  61.           }  
  62.   
  63.           public static string NewtonsoftJson(object obj)  
  64.           {  
  65.                return Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None);  
  66.           }  
  67.           /// <summary>  
  68.           /// 将对象转化成json  
  69.           /// </summary>  
  70.           /// <param name="obj"></param>  
  71.           /// <returns></returns>  
  72.           public static string ObjectToJson(object obj)  
  73.           {  
  74.                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());  
  75.                using (MemoryStream ms = new MemoryStream())  
  76.                {  
  77.                     serializer.WriteObject(ms, obj);  
  78.                     StringBuilder sb = new StringBuilder();  
  79.                     sb.Append(Encoding.UTF8.GetString(ms.ToArray()));  
  80.                     string jsonString = sb.ToString();  
  81.                     if (!jsonString.StartsWith("[") && !jsonString.EndsWith("]"))  
  82.                     {  
  83.                          sb.Insert(0, "[");  
  84.                          sb.Append("]");  
  85.                     }  
  86.   
  87.                     return sb.ToString();  
  88.                }  
  89.           }  
  90.   
  91.   
  92.   
  93.           /// <summary>  
  94.           /// 将对象序列为Json数据格式  
  95.           /// </summary>  
  96.           /// <param name="obj"></param>  
  97.           /// <returns></returns>  
  98.           public static string Serialize<T>(T obj)  
  99.           {  
  100.                string result = Newtonsoft.Json.JsonConvert.SerializeObject(obj);  
  101.                return result;  
  102.           }  
  103.   
  104.           /// <summary>  
  105.           /// 将Json数据格式的字符串反序列化为一个对象  
  106.           /// </summary>  
  107.           /// <returns></returns>  
  108.           public static T Deserialize<T>(string josnString)  
  109.           {  
  110.   
  111.                try  
  112.                {  
  113.                     T obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(josnString);  
  114.                     return obj;  
  115.   
  116.                }  
  117.                catch (Exception e)  
  118.                {  
  119.                     string s = e.Message;  
  120.                     throw e;  
  121.                }  
  122.   
  123.           }  
  124.   
  125.           /// <summary>  
  126.           /// 将dataTable转换为json  
  127.           /// </summary>  
  128.           /// <param name="dt"></param>  
  129.           /// <returns></returns>  
  130.           public static string CreateJsonParameters(DataTable dt)  
  131.           {  
  132.                if (dt == null || dt.Rows.Count == 0)  
  133.                {  
  134.                     return string.Empty;  
  135.                }  
  136.   
  137.                StringBuilder JsonString = new StringBuilder();  
  138.                JsonString.Append("\"DataTable\":[ ");  
  139.                for (int i = 0; i < dt.Rows.Count; i++)  
  140.                {  
  141.                     JsonString.Append("{ ");  
  142.   
  143.                     for (int j = 0; j < dt.Columns.Count; j++)  
  144.                     {  
  145.                          if (j < dt.Columns.Count - 1)  
  146.                          {  
  147.                               JsonString.Append("\"" + dt.Columns[j].ColumnName + "\":" + "\"" + dt.Rows[i][j] + "\",");  
  148.                          }  
  149.                          else if (j == dt.Columns.Count - 1)  
  150.                          {  
  151.                               JsonString.Append("\"" + dt.Columns[j].ColumnName + "\":" + "\"" + dt.Rows[i][j] + "\"");  
  152.                          }  
  153.                     }  
  154.   
  155.                     if (i == dt.Rows.Count - 1)  
  156.                     {  
  157.                          JsonString.Append("} ");  
  158.                     }  
  159.                     else  
  160.                     {  
  161.                          JsonString.Append("}, ");  
  162.                     }  
  163.                }  
  164.   
  165.                JsonString.Append("]");  
  166.   
  167.                return JsonString.ToString();  
  168.           }  
  169.   
  170.           /// <summary>  
  171.           /// 列名和数据都转换为json格式  
  172.           /// </summary>  
  173.           /// <param name="dt"></param>  
  174.           /// <returns></returns>  
  175.           public static string CreateJson(DataTable dt)  
  176.           {  
  177.                if (null == dt)  
  178.                {  
  179.                     return string.Empty;  
  180.                }  
  181.   
  182.                StringBuilder JsonString = new StringBuilder();  
  183.                JsonString.Append("\"Col\":[ ");  
  184.                string coLCaption = string.Empty;  
  185.                string colName = string.Empty;  
  186.                string colInfo = string.Empty;  
  187.                for (int i = 0; i < dt.Columns.Count; i++)  
  188.                {  
  189.                     DataColumn column = dt.Columns[i];  
  190.                     colName = column.ColumnName;  
  191.                     coLCaption = column.Caption;  
  192.                     if (string.IsNullOrEmpty(coLCaption))  
  193.                     {  
  194.                          coLCaption = colName;  
  195.                     }  
  196.   
  197.                     if (i > 0)  
  198.                     {  
  199.                          JsonString.Append(",");  
  200.                     }  
  201.   
  202.                     colInfo = "{\"ColNo\":\"" + i + "\",\"ColName\":\"" + colName + "\",\"ColCaption\":\"" + coLCaption + "\",\"ColDataType\":\"" + column.DataType.Name + "\"}";  
  203.                     JsonString.Append(colInfo);  
  204.                }  
  205.   
  206.                JsonString.Append("]");  
  207.   
  208.                if (dt.Rows.Count > 0)  
  209.                {  
  210.                     JsonString.Append(",");  
  211.                     JsonString.Append(CreateJsonParameters(dt));  
  212.                }  
  213.   
  214.                return JsonString.ToString();  
  215.           }  
  216.      }  
  217.   
  218.   
  219. }  


其他参考地址: 

http://www./topic/?906

http://www./a/93673.aspx

http:///catalog.asp?tags=Echarts%E4%BD%BF%E7%94%A8

http://www./projecteactual/echarts-aspnet-ashx-demo-xiangmudaima.html

http://www./projecteactual/echarts-aspnet-ashx-demo-download-duiji-bar.html


整理好的Echarts文件地址如下:

http://files.cnblogs.com/kongwei521/Echarts%E8%A6%81%E7%94%A8%E5%88%B0%E7%9A%84js_css_dll.zip


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多