swiftUI 统计图_swiftUI 统计图

一、封装数据(用asmx)

/// <summary>
        /// 街道编号
        /// </summary>
        private int StreetID
        {
            get
            {
                if (Session["StreetID"] != null)
                    return Convert.ToInt32(Session["StreetID"]);
                return -1;
            }
            set
            {
                Session["StreetID"] = value;
            }
        } 
        /// <summary>
        /// 管理员档案操作年度工作量折线图
        /// </summary>
        /// <param name="year"></param>
        [WebMethod(EnableSession=true)]
        public void TypeChart(string year,string username)
        {
            if (year == string.Empty)//如果时间为空,默认选择本年度
            {
                year = DateTime.Now.Year.ToString();
            }
            if (username == string.Empty)
            {
                return;
            }
            if (StreetID==-1)
            {
                Alert.Show("请先登录!");
                return;
            }//查询数据
            string SqlType1 = @"select COUNT([UserName]) as WorkType,MONTH(logTime) as MonthText,OperateType
from [dbo].[tbl_FileOperatelogs_Info]
where StreetID="+StreetID+" and YEAR(logTime)=" + year + " and [UserName]='" + username + "'  group by MONTH(logTime),OperateType"; 
//用Table封装
DataTable dt = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionString, CommandType.Text, SqlType1, null);
            dt.TableName = "table1";            //创建类型数组
            string[] lineSubTitle = new string[4];            Dictionary<string, object>[] lineDataDict = new Dictionary<string, object>[4];
            //按管理员人数来循环所有用户名的折线
            for (int i = 0; i < 4; i++)
            {
                lineSubTitle[i] = GetOpTypeName(i + 1);                //    {} (封装{}字典)
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("name", GetOpTypeName(i + 1));
                dict.Add("type", "line");
                dict.Add("stack", "总量");                //封装areaStyle字典
                Dictionary<string, object> styleDict = new Dictionary<string, object>();
                styleDict.Add("normal", "");
                dict.Add("areaStyle", styleDict);
                //封装12个月份的工作量(无工作量的月份补零)                int[] workCountArray = new int[12];
                //用datatabel循环补零

                for (int k = 0; k < 12; k++)
                {
                    DataRow[] dr = dt.Select("MonthText=" + (k + 1) + " and OperateType=" + (i + 1));//在用户行中查找月份循环12次(Y轴),档案类型循环4次(出入上下)
                    if (dr.Length == 0)//无则补零
                    {
                        workCountArray[k] = 0;
                    }
                    else//有则赋值
                    {
                        workCountArray[k] = Convert.ToInt32(dr[0]["WorkType"]);//工作量(X轴)
                    }
                }
                //添加到{}字典中
                dict.Add("data", workCountArray);
                //再讲到{}字典 封装series[]字典中
                lineDataDict[i] = dict;
            }            //将 lineSubTitle、lineDataDict字典封装到bigDict 大字典中
            Dictionary<string, object> bigDict = new Dictionary<string, object>();
            bigDict.Add("LineChartTitle", year + "年" + username + "操作分析图");
            bigDict.Add("LineSubTitle", lineSubTitle);
            bigDict.Add("LineChartData", lineDataDict);
            //将大字典转为JSON格式
            string ss = new JavaScriptSerializer().Serialize(bigDict);
            Context.Response.Write(ss);
        }        public string GetOpTypeName(int opType)
        {
            switch (opType)
            { 
                case 1:
                    return "入库";
                case 2:
                    return "上架";
                case 3:
                    return "下架";
                case 4:
                    return "出库";
                default:
                    return "";
            }        }
        /// <summary>
        /// 年度操作员工作量统计图
        /// </summary>
        /// <param name="year"></param>
        [WebMethod(EnableSession=true)]
        public void GetCharL(string year)
        {

            if (year == string.Empty)//如果时间为空,默认选择本年度
            {
                year = DateTime.Now.Year.ToString();
            }
            if (StreetID == -1)
            {
                Alert.Show("请先登录!");
                return;
            }            string sqlStr = @"select a.UserID, MONTH(a.logTime) as MonthText,COUNT(a.UserID) as WorkCount 
from [dbo].[tbl_FileOperatelogs_Info] a 
where a.StreetID="+StreetID+" and YEAR(a.logTime)=" + year + " group by a.UserID, MONTH(logTime) order by a.UserID";            DataTable dt = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionString, CommandType.Text, sqlStr, null);
            dt.TableName = "table1";
            //获取本街道所有管理员
            List<tbl_Users_Info> userInfo = tbl_Users_Info.GetList_LEVEL_ID(StreetID);
            //创建用户数组
            string[] lineSubTitle = new string[userInfo.Count];
            //    [] (封装series[]字典)            //    series : [  ——(series字典格式)
            //{
            //    name:'邮件营销',
            //    type:'line',
            //    stack: '总量',
            //    areaStyle: {normal: ''},
            //    data:[120, 132, 101, 134, 90, 230, 210]
            //}
            Dictionary<string, object>[] lineDataDict = new Dictionary<string, object>[userInfo.Count];
            //按管理员人数来循环所有用户名的折线
            for (int i = 0; i < userInfo.Count; i++)
            {
                //用户名
                lineSubTitle[i] = userInfo[i].USERNAME;
                //    {} (封装{}字典)
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("name", userInfo[i].USERNAME);
                dict.Add("type", "line");                //封装12个月份的工作量(无工作量的月份补零)
                int[] workCountArray = new int[12];
                //用datatabel循环补零
                DataView dv = new DataView();                dv.Table = dt;
                dv.RowFilter = "UserID=" + userInfo[i].USERID;//筛选用户
                DataTable dtUser = dv.ToTable();
                for (int k = 0; k < 12; k++)
                {
                    DataRow[] dr = dtUser.Select("MonthText=" + (k + 1));//在用户行中查找月份
                    if (dr.Length == 0)//无则补零
                    {
                        workCountArray[k] = 0;
                    }
                    else//有则赋值
                    {
                        workCountArray[k] = Convert.ToInt32(dr[0]["WorkCount"]);
                    }
                }
                //添加到{}字典中
                dict.Add("data", workCountArray);
                //再讲到{}字典 封装series[]字典中
                lineDataDict[i] = dict;
            }
            //将 lineSubTitle、lineDataDict字典封装到bigDict 大字典中
            Dictionary<string, object> bigDict = new Dictionary<string, object>();
            bigDict.Add("LineChartTitle", year + "年操作量分析图");
            bigDict.Add("LineSubTitle", lineSubTitle);
            bigDict.Add("LineChartData", lineDataDict);
            //将大字典转为JSON格式
            string ss = new JavaScriptSerializer().Serialize(bigDict);
            Context.Response.Write(ss);        }
二、Web页面
1.前台
<body style="background-color: white;">
    <form id="form1" runat="server">
        <f:PageManager runat="server" ID="pg1"></f:PageManager>
        <div style="width:1000px; padding:10px 0px;">
            <%--Grid部分--%>
            <div style="float: left; width: 200px;">
                <div>
                    <div style="height: 30px; padding-left:5px;">
                        <span>年度:</span>
                        <span>
                            <asp:DropDownList ID="drpYear" runat="server" Width="80px" AutoPostBack="true" OnSelectedIndexChanged="drpYear_SelectedIndexChanged"></asp:DropDownList>
                        </span>

<%--                        <span>
                            <asp:DropDownList ID="DropDownList_month" runat="server" Width="60px" AutoPostBack="true">
                            </asp:DropDownList></span>
                        <span>月份(查看月工作量)</span>--%>
                    </div>
                    <f:Grid ID="GridTownData" runat="server" OnRowClick="GridTownData_RowClick" EnableRowClickEvent="true">
                        <Columns>
                            <f:RowNumberField Width="40px" ></f:RowNumberField>
                            <f:BoundField HeaderText="操作员" DataField="UserName" Width="80px" TextAlign="Center" />
                            <f:BoundField HeaderText="操作量" DataField="countdate" Width="80px" TextAlign="Center" />
                        </Columns>
                    </f:Grid>
                </div>
            </div>
            <div style="float: left; padding:0px 10px;">
                <div id="LineChart" style="height: 300px; width: 750px;"></div>
                <div id="TypeChart" style="height: 300px; width: 750px;"> </div>
            </div>
        </div>
        <%--图表JS部分--%>
        <script type="text/javascript">
            // 基于准备好的dom,初始化echarts实例
            var LineChart = echarts.init(document.getElementById('LineChart'));
            //鼠标移上去的提示框
            var LineOption = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    left: "right"
                },
                toolbox: {
                    show: false,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                grid: {
                    left: '3%',
                    right: '3%',
                    bottom: '6%',
                    containLabel: true
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ]
            };            // 基于准备好的dom,初始化echarts实例
            var TypeChart = echarts.init(document.getElementById('TypeChart'));
            //鼠标移上去的提示框
            var TypeOption = {
                tooltip: {
                    //坐标轴触发显示
                    trigger: 'axis'
                },
                legend: {
                    left: "right"
                },
                //工具箱
                toolbox: {
                    //是否显示工具箱
                    show: false,
                    //特效
                    feature: {
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '3%',
                    right: '3%',
                    bottom: '6%',
                    containLabel: true
                },
                //横坐标
                xAxis: [
                    {
                        //X轴为类目型
                        type: 'category',
                        //是否两端留白
                        boundaryGap: false,
                        //横坐标数据(只有类目型才有data属性)
                        data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
                    }
                ],
                //纵坐标
                yAxis: [
                    {
                        //Y轴类型为数值型
                        type: 'value'
                    }
                ]
            };            //加载方法
            var year = $("#drpYear").val();
            ShowLineChart(year);
            //选择年度加载
            $("#drpYear").change(function () {
                ShowLineChart($("#drpYear").val());//取$("#drpYear").val() 里面改变的值
            });
            //首次加载
            function ShowLineChart(_year) {
                //为echarts加载数据
                LineChart.clear();
                TypeChart.clear();
                LineChart.setOption(LineOption);
                //getJSON()方法使用接口调用JSON数据
                $.getJSON('Gender_tj.asmx/GetCharL', { year: _year }, function (jsondata) {
                    LineChart.setOption({
                        //标题
                        title: {
                            text: jsondata.LineChartTitle//调用JSON LineChartTitle
                        },
                        //图例
                        legend: {
                            data: jsondata.LineSubTitle // 调用JSON LineSubTitle
                        },
                        //图表数据
                        series: jsondata.LineChartData// 调用JSON LineChartData
                    })
                });
            } 
 
            //LineChart.on('click', function (params) {
            //    ShowTypeChart(params.name);
            //});            //首次加载
            function ShowTypeChart(_year, _username) {
                //为echarts加载数据
                TypeChart.clear();
                TypeChart.setOption(TypeOption);
                //getJSON()方法使用接口调用JSON数据
                $.getJSON('Gender_tj.asmx/TypeChart', { year: _year, username: _username }, function (jsondata) {
                    TypeChart.setOption({
                        //标题
                        title: {
                            text: jsondata.LineChartTitle//调用JSON LineChartTitle
                        },
                        //图例
                        legend: {
                            data: jsondata.LineSubTitle // 调用JSON LineSubTitle
                        },
                        //图表数据
                        series: jsondata.LineChartData// 调用JSON LineChartData
                    })
                });
            }        </script>
    </form>
</body>2.后台
public partial class Gender_tj : ChartBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Bind_Policy_Year(drpYear);
                //Bing_Month(DropDownList_month);
                drpYear.SelectedValue = DateTime.Now.Year.ToString();
                BindTotalGrid();            }
        }
        /// <summary>
        /// 根据用户ID获取用户名称
        /// </summary>
        /// <param name="StreetId"></param>
        /// <returns></returns>
        public string GetUserName(int UserId)
        {
            tbl_Users_Info GetUserName = tbl_Users_Info.GetModel(UserId);
            return GetUserName == null ? string.Empty : GetUserName.USERNAME;
        }        /// <summary>
        /// 年份
        /// </summary>
        /// <param name="ddl"></param>
        public void Bind_Policy_Year(System.Web.UI.WebControls.DropDownList ddl)
        {
            int year = DateTime.Now.Year;
            for (int i = 0; i < 10; i++)
            {
                ddl.Items.Add(new System.Web.UI.WebControls.ListItem(Convert.ToString(year - i), Convert.ToString(year - i)));
            }
        }        /// <summary>
        /// 月份
        /// </summary>
        public void Bing_Month(System.Web.UI.WebControls.DropDownList DropDownList_month)
        {
           int month = DateTime.Now.Month;
            for (int i = 0; i < 12; i++)
            {
                DropDownList_month.Items.Add(new System.Web.UI.WebControls.ListItem(Convert.ToString(month + i), Convert.ToString(month + i)));
            }
            DropDownList_month.SelectedValue = month.ToString();
        }
        /// <summary>
        /// 按年份查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///         
        protected void BindTotalGrid()
        {
            string sqlStr = @"select [UserName],COUNT(UserID) as countdate 
from [dbo].[tbl_FileOperatelogs_Info] 
where YEAR(logTime)=" + drpYear.SelectedValue + " and StreetID=" + Curr_Staff.STREETID + " group by UserName ";            DataTable dt = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionString, CommandType.Text, sqlStr, null);
            GridTownData.DataSource = dt;
            GridTownData.DataBind();
            GridTownData.Title = drpYear.SelectedValue + "年度工作量统计";
        }
        protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindTotalGrid();//Grid选择事件
        }
        /// <summary>
        /// 点击获取折线图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridTownData_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            string nameclick = GridTownData.Rows[e.RowIndex].Values[1].ToString();
            string year = drpYear.SelectedValue;
            PageContext.RegisterStartupScript("ShowTypeChart('" + year + "','" + nameclick + "');");
        }
    }

限定目的,能使人生变得简洁。