コード例 #1
0
ファイル: LayoutController.cs プロジェクト: 15831944/EPC
        public JsonResult GetTree(string tmplCode, QueryBuilder qb)
        {
            var       listDef  = entities.Set <S_UI_Layout>().Where(c => c.Code == tmplCode).First();
            SQLHelper sqlHeler = SQLHelper.CreateSqlHelper(listDef.ConnName);

            UIFO   uiFO = FormulaHelper.CreateFO <UIFO>();
            string sql  = uiFO.ReplaceString(listDef.SQL);

            return(Json(sqlHeler.ExecuteDataTable(sql)));
        }
コード例 #2
0
        public virtual JsonResult GetTotal(string tmplCode)
        {
            var       listDef  = entities.Set <S_UI_List>().SingleOrDefault(c => c.Code == tmplCode);
            SQLHelper sqlHeler = SQLHelper.CreateSqlHelper(listDef.ConnName);

            UIFO uiFO = FormulaHelper.CreateFO <UIFO>();

            string sql = listDef.SQL;

            sql = uiFO.ReplaceString(sql);
            return(Json(sqlHeler.ExecuteDataTable(sql).Rows.Count));
        }
コード例 #3
0
        public virtual JsonResult GetSelectedList(string tmplCode, string ids)
        {
            var       listDef  = entities.Set <S_UI_List>().SingleOrDefault(c => c.Code == tmplCode);
            SQLHelper sqlHeler = SQLHelper.CreateSqlHelper(listDef.ConnName);

            UIFO uiFO = FormulaHelper.CreateFO <UIFO>();

            string sql = listDef.SQL;

            sql = uiFO.ReplaceString(sql);
            sql = string.Format("select * form ({0}) as dt0 where ID in ('{2}')", sql, ids.Replace(",", "','"));
            var dt = sqlHeler.ExecuteDataTable(sql);

            return(Json(dt));
        }
コード例 #4
0
ファイル: FormController.cs プロジェクト: Luyingjin/Qy
        private string GetSerialNumber(string formCode, string SerialNumberSettings, bool applySerialNumber, DataRow row = null, Dictionary <string, string> dic = null)
        {
            UIFO uiFO = FormulaHelper.CreateFO <UIFO>();

            var    serialNumberDic = JsonHelper.ToObject(SerialNumberSettings);
            string tmpl            = serialNumberDic["Tmpl"].ToString();
            string resetRule       = serialNumberDic["ResetRule"].ToString();
            string CategoryCode    = "";
            string SubCategoryCode = "";
            string OrderNumCode    = "";
            string PrjCode         = "";
            string OrgCode         = "";
            string UserCode        = "";

            if (serialNumberDic.ContainsKey("CategoryCode"))
            {
                CategoryCode = uiFO.ReplaceString(serialNumberDic["CategoryCode"].ToString(), row, dic);
            }
            if (serialNumberDic.ContainsKey("SubCategoryCode"))
            {
                SubCategoryCode = uiFO.ReplaceString(serialNumberDic["SubCategoryCode"].ToString(), row, dic);
            }
            if (serialNumberDic.ContainsKey("OrderNumCode"))
            {
                OrderNumCode = uiFO.ReplaceString(serialNumberDic["OrderNumCode"].ToString(), row, dic);
            }
            if (serialNumberDic.ContainsKey("PrjCode"))
            {
                PrjCode = uiFO.ReplaceString(serialNumberDic["PrjCode"].ToString(), row, dic);
            }
            if (serialNumberDic.ContainsKey("OrgCode"))
            {
                OrgCode = uiFO.ReplaceString(serialNumberDic["OrgCode"].ToString(), row, dic);
            }
            if (serialNumberDic.ContainsKey("UserCode"))
            {
                UserCode = uiFO.ReplaceString(serialNumberDic["UserCode"].ToString(), row, dic);
            }

            SerialNumberParam param = new SerialNumberParam()
            {
                Code            = formCode,
                PrjCode         = PrjCode,
                OrgCode         = OrgCode,
                UserCode        = UserCode,
                CategoryCode    = CategoryCode,
                SubCategoryCode = SubCategoryCode,
                OrderNumCode    = OrderNumCode
            };

            string SerialNumber = SerialNumberHelper.GetSerialNumberString(tmpl, param, resetRule, applySerialNumber);

            return(SerialNumber);
        }
コード例 #5
0
        public JsonResult GetCustomField()
        {
            UIFO      fo    = new UIFO();
            DataTable table = new DataTable();

            table.Columns.Add("value");
            string    sql       = fo.ReplaceString(Request["SQL"]);
            string    connName  = Convert.ToString(Request["ConnName"]);
            SQLHelper sqlHelper = SQLHelper.CreateSqlHelper(connName);
            var       tb        = sqlHelper.ExecuteDataTable(sql);

            if (tb.Columns.Contains("Column1"))
            {
                throw new Exception("请为查询语名的列命名!如:select '{CurrentUserID}' as CurrentUserID");
            }

            foreach (var col in tb.Columns)
            {
                table.Rows.Add(col.ToString());
            }
            return(Json(table));
        }
コード例 #6
0
ファイル: BaseComponent.cs プロジェクト: tianzhifeng/EPC
        protected void FillDataSource(string parameters = "")
        {
            var dataSource = new Dictionary <string, DataTable>();

            if (!String.IsNullOrEmpty(this.BlockDef.GetValue("dataSource")))
            {
                var dataSourceDefList = JsonHelper.ToList(this.BlockDef.GetValue("dataSource"));
                foreach (var dataSourceDef in dataSourceDefList)
                {
                    var db  = SQLHelper.CreateSqlHelper(dataSourceDef.GetValue("ConnName"));
                    var sql = dataSourceDef.GetValue("SQL");

                    if (!string.IsNullOrEmpty(parameters))
                    {
                        var   paras = JsonHelper.ToObject <Dictionary <string, string> >(parameters);
                        Regex reg   = new Regex("\\{[0-9a-zA-Z_\\.]*\\}");
                        var   user  = FormulaHelper.GetUserInfo();
                        foreach (Match m in reg.Matches(sql))
                        {
                            string key   = m.Value.Trim('{', '}');
                            var    value = paras.GetValue(key);
                            switch (key)
                            {
                            case Formula.Constant.CurrentUserID:
                                value = user.UserID;
                                break;

                            case Formula.Constant.CurrentUserName:
                                value = user.UserName;
                                break;

                            case Formula.Constant.CurrentUserOrgID:
                                value = user.UserOrgID;
                                break;

                            case Formula.Constant.CurrentUserOrgCode:
                                value = user.UserOrgCode;
                                break;

                            case Formula.Constant.CurrentUserOrgName:
                                value = user.UserOrgName;
                                break;

                            case Formula.Constant.CurrentUserPrjID:
                                value = user.UserPrjID;
                                break;

                            case Formula.Constant.CurrentUserPrjName:
                                value = user.UserPrjName;
                                break;

                            case "CurrentUserOrgFullName":
                                value = user.UserFullOrgName;
                                break;

                            case "CurrentUserCorpID":
                                value = user.UserCompanyID;
                                break;

                            case "CurrentUserCorpName":
                                value = user.UserCompanyName;
                                break;

                            case "CurrentTime":
                                value = DateTime.Now.ToString();
                                break;

                            case "CurrentDate":
                                value = DateTime.Now.Date.ToString("yyyy-MM-dd");
                                break;

                            case "CurrentYear":
                                value = DateTime.Now.Year.ToString();
                                break;

                            case "CurrentMonth":
                                value = DateTime.Now.Month.ToString();
                                break;

                            case "CurrentQuarter":
                                value = ((DateTime.Now.Month + 2) / 3).ToString();
                                break;

                            case "CurrentUserOrgFullID":
                                value = user.UserFullOrgID;
                                break;
                            }

                            sql = sql.Replace(m.Value, value);
                        }
                    }
                    sql = fo.ReplaceString(sql);
                    var dt = db.ExecuteDataTable(sql);
                    dataSource.SetValue(dataSourceDef.GetValue("Code"), dt);
                }
            }
            this.DataSource = dataSource;
        }
コード例 #7
0
        public JsonResult GetList(string tmplCode, QueryBuilder qb)
        {
            var       listDef  = entities.Set <S_UI_List>().SingleOrDefault(c => c.Code == tmplCode);
            SQLHelper sqlHeler = SQLHelper.CreateSqlHelper(listDef.ConnName);

            UIFO   uiFO = FormulaHelper.CreateFO <UIFO>();
            string sql  = uiFO.ReplaceString(listDef.SQL);

            DataTable dtTmpl = sqlHeler.ExecuteDataTable(string.Format("select * from ({0}) as T where 1=2", sql));

            //地址栏参数作为查询条件
            foreach (string key in Request.QueryString.Keys)
            {
                if (string.IsNullOrEmpty(key))
                {
                    continue;
                }
                if ("ID,FullID,FULLID,TmplCode,IsPreView,_winid,_t".Split(',').Contains(key) || key.StartsWith("$"))
                {
                    continue;
                }
                if (dtTmpl.Columns.Contains(key))
                {
                    qb.Add(key, QueryMethod.Equal, Request[key], "Group1", null);
                }
            }

            var data = sqlHeler.ExecuteGridData(sql, qb);

            #region 计算汇总

            var           fields = JsonHelper.ToList(listDef.LayoutField);
            StringBuilder sb     = new StringBuilder();
            foreach (var field in fields)
            {
                if (field.ContainsKey("Settings") == false)
                {
                    continue;
                }
                var settings = JsonHelper.ToObject(field["Settings"].ToString());
                if (settings.ContainsKey("Collect") == false || settings["Collect"].ToString() == "")
                {
                    continue;
                }
                sb.AppendFormat(",{0}={1}({0})", field["field"], settings["Collect"]);
                if (settings["Collect"].ToString() == "sum")
                {
                    data.sumData.Add(field["field"].ToString(), null);
                }
                else
                {
                    data.avgData.Add(field["field"].ToString(), null);
                }
            }
            if (sb.Length > 0)
            {
                string collectSql = string.Format("select {0} from (select * from ({1}) as tb where 1=1 {2}) as T"
                                                  , sb.ToString().Trim(',')
                                                  , sql
                                                  , qb.GetWhereString(false) + FormulaHelper.CreateAuthDataFilter().GetWhereString(false)
                                                  );
                DataTable dtCollect = sqlHeler.ExecuteDataTable(collectSql);

                foreach (DataColumn col in dtCollect.Columns)
                {
                    if (data.sumData.ContainsKey(col.ColumnName))
                    {
                        data.sumData[col.ColumnName] = dtCollect.Rows[0][col];
                    }
                    else
                    {
                        data.avgData[col.ColumnName] = dtCollect.Rows[0][col];
                    }
                }
            }

            #endregion

            return(Json(data));
        }
コード例 #8
0
ファイル: LayoutController.cs プロジェクト: 15831944/EPC
        public JsonResult GetList(string tmplCode, QueryBuilder qb)
        {
            var       listDef  = entities.Set <S_UI_Layout>().Where(c => c.Code == tmplCode).First();
            SQLHelper sqlHeler = SQLHelper.CreateSqlHelper(listDef.ConnName);

            UIFO   uiFO = FormulaHelper.CreateFO <UIFO>();
            string sql  = uiFO.ReplaceString(listDef.SQL);

            #region 地址栏过滤

            //            string sqlTmpl = string.Format(@"SELECT  fieldCode= a.name , description= isnull(g.[value],''),fieldType=b.name,sortIndex=a.column_id
            //FROM  sys.columns a left join sys.extended_properties g on (a.object_id = g.major_id AND g.minor_id = a.column_id)
            //left join systypes b on a.user_type_id=b.xusertype
            //WHERE  object_id =(SELECT object_id FROM sys.tables WHERE name in('{0}'))", listDef.TableNames.Replace(",", "','"));
            //            if (Config.Constant.IsOracleDb)
            //            {
            //                sqlTmpl = string.Format(@"select column_name as fieldCode from user_tab_columns where table_name in('{0}')", listDef.TableNames.Replace(",", "','"));
            //            }

            //            DataTable dtTmpl = sqlHeler.ExecuteDataTable(sqlTmpl);

            //            //地址栏参数作为查询条件
            //            var queryDtTmpl = dtTmpl.AsEnumerable();
            //            foreach (string key in Request.QueryString.Keys)
            //            {
            //                if (string.IsNullOrEmpty(key))
            //                    continue;
            //                if ("ID,FullID,FULLID,TmplCode,IsPreView,_winid,_t".Split(',').Contains(key) || key.StartsWith("$"))
            //                    continue;
            //                if (queryDtTmpl.Count(c => c["fieldCode"].ToString().ToLower() == key.ToLower()) > 0)
            //                    qb.Add(key, QueryMethod.In, Request[key]);
            //            }


            DataTable dtTmpl = sqlHeler.ExecuteDataTable(sql, qb);
            foreach (string key in Request.QueryString.Keys)
            {
                if (string.IsNullOrEmpty(key))
                {
                    continue;
                }
                if ("ID,FullID,FULLID,TmplCode,IsPreView,_winid,_t".Split(',').Contains(key) || key.StartsWith("$"))
                {
                    continue;
                }
                if (dtTmpl.Columns.Contains(key))
                {
                    qb.Add(key, QueryMethod.In, Request[key]);
                }
                ;
            }


            #endregion

            GridData data = null;
            if (listDef.LayoutGrid.Contains("\"showPager\":\"false\""))
            {
                data = new GridData(sqlHeler.ExecuteDataTable(sql, (SearchCondition)qb, listDef.OrderBy));
            }
            else
            {
                data = sqlHeler.ExecuteGridData(sql, qb, listDef.OrderBy);
            }

            #region 计算汇总

            var           fields = JsonHelper.ToList(listDef.LayoutField);
            StringBuilder sb     = new StringBuilder();
            foreach (var field in fields)
            {
                if (field.ContainsKey("Settings") == false)
                {
                    continue;
                }
                var settings = JsonHelper.ToObject(field["Settings"].ToString());
                if (settings.ContainsKey("Collect") == false || settings["Collect"].ToString() == "")
                {
                    continue;
                }
                if (Config.Constant.IsOracleDb)
                {
                    sb.AppendFormat(",{1}({0}) as {0}", field["field"], settings["Collect"]);
                }
                else
                {
                    sb.AppendFormat(",{0}={1}({0})", field["field"], settings["Collect"]);
                }

                if (settings["Collect"].ToString() == "sum")
                {
                    data.sumData.Add(field["field"].ToString(), null);
                }
                else
                {
                    data.avgData.Add(field["field"].ToString(), null);
                }
            }
            if (sb.Length > 0)
            {
                string companyAuth = "";
                if (System.Configuration.ConfigurationManager.AppSettings["CorpAuthEnabled"] == "True")
                {
                    var dt = sqlHeler.ExecuteDataTable(string.Format("select * from ({0}) tempDt1 where 1=2", sql));
                    if (dt.Columns.Contains("CompanyID"))
                    {
                        companyAuth = string.Format(" and CompanyID='{0}'", FormulaHelper.GetUserInfo().UserCompanyID);
                    }
                }

                string collectSql = "";
                if (Config.Constant.IsOracleDb)
                {
                    collectSql = string.Format("select {0} from (select * from ({1}) tb where 1=1 {2}) T"
                                               , sb.ToString().Trim(',')
                                               , sql
                                               , qb.GetWhereString(false) + FormulaHelper.CreateAuthDataFilter().GetWhereString(false) + companyAuth
                                               );
                }
                else
                {
                    collectSql = string.Format("select {0} from (select * from ({1}) as tb where 1=1 {2}) as T"
                                               , sb.ToString().Trim(',')
                                               , sql
                                               , qb.GetWhereString(false) + FormulaHelper.CreateAuthDataFilter().GetWhereString(false) + companyAuth
                                               );
                }
                DataTable dtCollect = sqlHeler.ExecuteDataTable(collectSql);

                foreach (DataColumn col in dtCollect.Columns)
                {
                    if (data.sumData.ContainsKey(col.ColumnName))
                    {
                        data.sumData[col.ColumnName] = dtCollect.Rows[0][col] is DBNull ? 0 : dtCollect.Rows[0][col];
                    }
                    else
                    {
                        data.avgData[col.ColumnName] = dtCollect.Rows[0][col] is DBNull ? 0 : dtCollect.Rows[0][col];
                    }
                }
            }

            //汇总数据小数点
            foreach (var field in fields)
            {
                if (field.ContainsKey("Settings") == false)
                {
                    continue;
                }
                var settings = JsonHelper.ToObject(field["Settings"].ToString());
                if (settings.ContainsKey("Collect") == false || settings["Collect"].ToString() == "")
                {
                    continue;
                }
                int decimalPlaces = 2;
                if (settings.ContainsKey("decimalPlaces") && settings["decimalPlaces"].ToString() != "")
                {
                    decimalPlaces = Convert.ToInt32(settings["decimalPlaces"]);
                }

                string fieldCode = field["field"].ToString();

                if (data.sumData.ContainsKey(fieldCode))
                {
                    data.sumData[fieldCode] = string.Format("{0:F" + decimalPlaces + "}", Convert.ToDouble(data.sumData[fieldCode]));
                }
                else
                {
                    data.avgData[fieldCode] = string.Format("{0:F" + decimalPlaces + "}", Convert.ToDouble(data.avgData[fieldCode]));
                }
            }

            #endregion

            return(Json(data));
        }
コード例 #9
0
        public virtual JsonResult GetList(string tmplCode, QueryBuilder qb)
        {
            var       listDef  = entities.Set <S_UI_List>().SingleOrDefault(c => c.Code == tmplCode);
            SQLHelper sqlHeler = SQLHelper.CreateSqlHelper(listDef.ConnName);

            UIFO uiFO = FormulaHelper.CreateFO <UIFO>();

            var lefSettings = JsonHelper.ToObject(listDef.LayoutGrid);

            if (lefSettings.GetValue("isTreeGrid") == true.ToString().ToLower() &&
                this.Request["IsLoadChildren"] == true.ToString().ToLower())
            {
                //异步加载树列表
                var node = String.IsNullOrEmpty(this.Request["NodeInfo"]) ? new Dictionary <string, object>() :
                           JsonHelper.ToObject <Dictionary <string, object> >(this.Request["NodeInfo"]);
                var defaultValues      = JsonHelper.ToList(listDef.DefaultValueSettings);
                var nodeTypeField      = String.IsNullOrEmpty(lefSettings.GetValue("NodeTypeField")) ? "NodeType" : lefSettings.GetValue("NodeTypeField");
                var nodeType           = String.IsNullOrEmpty(node.GetValue(nodeTypeField)) ? "Root" : node.GetValue(nodeTypeField);
                var treeGridDataSource = defaultValues.Where(c => c.GetValue("treeGridSource") == true.ToString().ToLower()).ToList();
                var dataSource         = new Dictionary <string, object>();
                if (treeGridDataSource.Count == 1)
                {
                    dataSource = treeGridDataSource.FirstOrDefault();
                }
                else
                {
                    dataSource = treeGridDataSource.FirstOrDefault(c => c.GetValue("Code").Split(',').Contains(nodeType));
                }
                if (dataSource == null)
                {
                    return(Json(new DataTable()));
                }
                var db        = SQLHelper.CreateSqlHelper(dataSource.GetValue("ConnName"));
                var sourceSQL = dataSource.GetValue("SQL");
                sourceSQL = uiFO.ReplaceDicString(sourceSQL, null, node);
                var children = db.ExecuteDataTable(sourceSQL, new SearchCondition());
                return(Json(children));
            }
            else
            {
                string sql = listDef.SQL;
                #region TAB查询
                //解决tab查询需要在sql中间的问题
                var tabData           = Request["queryTabData"];
                var fields            = JsonHelper.ToList(listDef.LayoutField);
                var tabEmbeddedFields = new Dictionary <string, string>();
                foreach (var field in fields)
                {
                    if (!field.ContainsKey("Settings"))
                    {
                        continue;
                    }
                    var settings = JsonHelper.ToObject(field["Settings"].ToString());
                    if (!settings.ContainsKey("TabSearchName") || settings["TabSearchName"].ToString() == "")
                    {
                        continue;
                    }
                    if (!settings.ContainsKey("Embedded") || settings["Embedded"].ToString() != true.ToString().ToLower())
                    {
                        continue;
                    }

                    var cnd = qb.Items.FirstOrDefault(c => c.Field == field["field"].ToString());
                    if (cnd != null)
                    {
                        qb.Items.Remove(cnd);
                        var value = cnd.Value.ToString();
                        if (value.Contains(",") && (cnd.Method == QueryMethod.InLike || cnd.Method == QueryMethod.In))
                        {
                            value = value.Replace(",", "','");
                        }
                        tabEmbeddedFields.Add(field["field"].ToString(), value);
                    }
                    else
                    {
                        if (!settings.ContainsKey("EnumKey") || settings["EnumKey"].ToString() == "")
                        {
                            continue;
                        }
                        string enumKey  = settings["EnumKey"].ToString();
                        var    enumList = new List <Dictionary <string, object> >();
                        if (enumKey.StartsWith("["))
                        {
                            enumList = JsonHelper.ToList(enumKey);
                        }
                        else
                        {
                            var enumServcie = FormulaHelper.GetService <IEnumService>();
                            var dataTable   = enumServcie.GetEnumTable(enumKey);
                            enumList = FormulaHelper.DataTableToListDic(dataTable);
                        }
                        var value = String.Join(",", enumList.Select(c => c["value"].ToString()).ToList());
                        if (value.Contains(","))
                        {
                            value = value.Replace(",", "','");
                        }
                        tabEmbeddedFields.Add(field["field"].ToString(), value);
                    }
                }
                #endregion

                sql = uiFO.ReplaceString(sql, null, tabEmbeddedFields);

                #region 地址栏过滤
                DataTable dtTmpl = sqlHeler.ExecuteDataTable(string.Format("SELECT * FROM ({0}) T WHERE 1=2", sql));
                foreach (string key in Request.QueryString.Keys)
                {
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }
                    if ("ID,FullID,FULLID,TmplCode,IsPreView,_winid,_t".Split(',').Contains(key) || key.StartsWith("$"))
                    {
                        continue;
                    }
                    if (dtTmpl.Columns.Contains(key))
                    {
                        qb.Add(key, QueryMethod.In, Request[key]);
                    }
                    ;
                }
                #endregion

                //列表定义支持加密字段
                if (System.Configuration.ConfigurationManager.AppSettings["FieldEncryption"] == "True")
                {
                    StringBuilder sbField = new StringBuilder();
                    foreach (DataColumn col in dtTmpl.Columns)
                    {
                        if (col.DataType == typeof(byte[]) && fields.Count(c => c["field"].ToString() == col.ColumnName) > 0)
                        {
                            sbField.AppendFormat(",{0}=convert(nvarchar(500), DecryptByKey({0}))", col.ColumnName);
                        }
                        else
                        {
                            sbField.AppendFormat(",{0}", col.ColumnName);
                        }
                    }
                    sql = string.Format("select {1} from ({0}) as dt0", sql, sbField.ToString().Trim(' ', ','));
                }

                GridData data = null;
                if (listDef.LayoutGrid.Contains("\"showPager\":\"false\""))
                {
                    qb.PageSize = 0;
                }
                data = sqlHeler.ExecuteGridData(sql, qb, listDef.OrderBy);

                #region 计算汇总
                StringBuilder sb = new StringBuilder();
                foreach (var field in fields)
                {
                    if (field.ContainsKey("Settings") == false)
                    {
                        continue;
                    }
                    var settings = JsonHelper.ToObject(field["Settings"].ToString());
                    if (settings.ContainsKey("Collect") == false || settings["Collect"].ToString() == "")
                    {
                        continue;
                    }
                    if (Config.Constant.IsOracleDb)
                    {
                        sb.AppendFormat(",{1}({0}) as {0}", field["field"], settings["Collect"]);
                    }
                    else
                    {
                        sb.AppendFormat(",{0}={1}({0})", field["field"], settings["Collect"]);
                    }

                    if (settings["Collect"].ToString() == "sum")
                    {
                        data.sumData.Add(field["field"].ToString(), null);
                    }
                    else
                    {
                        data.avgData.Add(field["field"].ToString(), null);
                    }
                }
                if (sb.Length > 0)
                {
                    string companyAuth = "";
                    if (System.Configuration.ConfigurationManager.AppSettings["CorpAuthEnabled"] == "True")
                    {
                        var dt = sqlHeler.ExecuteDataTable(string.Format("select * from ({0}) tempDt1 where 1=2", sql));
                        if (dt.Columns.Contains("CompanyID"))
                        {
                            companyAuth = string.Format(" and CompanyID='{0}'", FormulaHelper.GetUserInfo().UserCompanyID);
                        }
                    }

                    string          collectSql = "";
                    SearchCondition authCnd    = FormulaHelper.CreateAuthDataFilter();
                    collectSql = string.Format("select * from ({0}) sourceTable1 where 1=1 {1} {2}", sql, authCnd.GetWhereString(false), companyAuth);
                    collectSql = string.Format("select {2} from ({0}) sourceTable {1}", collectSql, qb.GetWhereString(), sb.ToString().Trim(','));
                    DataTable dtCollect = sqlHeler.ExecuteDataTable(collectSql);

                    foreach (DataColumn col in dtCollect.Columns)
                    {
                        if (data.sumData.ContainsKey(col.ColumnName))
                        {
                            data.sumData[col.ColumnName] = dtCollect.Rows[0][col] is DBNull ? 0 : dtCollect.Rows[0][col];
                        }
                        else
                        {
                            data.avgData[col.ColumnName] = dtCollect.Rows[0][col] is DBNull ? 0 : dtCollect.Rows[0][col];
                        }
                    }
                }

                //汇总数据小数点
                foreach (var field in fields)
                {
                    if (field.ContainsKey("Settings") == false)
                    {
                        continue;
                    }
                    var settings = JsonHelper.ToObject(field["Settings"].ToString());
                    if (settings.ContainsKey("Collect") == false || settings["Collect"].ToString() == "")
                    {
                        continue;
                    }
                    int decimalPlaces = 2;
                    if (settings.ContainsKey("decimalPlaces") && settings["decimalPlaces"].ToString() != "")
                    {
                        decimalPlaces = Convert.ToInt32(settings["decimalPlaces"]);
                    }

                    string fieldCode = field["field"].ToString();

                    if (data.sumData.ContainsKey(fieldCode))
                    {
                        data.sumData[fieldCode] = string.Format("{0:F" + decimalPlaces + "}", Convert.ToDouble(data.sumData[fieldCode]));
                    }
                    else
                    {
                        data.avgData[fieldCode] = string.Format("{0:F" + decimalPlaces + "}", Convert.ToDouble(data.avgData[fieldCode]));
                    }
                }

                #endregion

                return(Json(data));
            }
        }
コード例 #10
0
        public FileResult Export(string tmplCode, string id)
        {
            if (string.IsNullOrEmpty(tmplCode))
            {
                throw new Exception("缺少参数TmplCode");
            }

            SQLHelper sqlHeper   = SQLHelper.CreateSqlHelper(ConnEnum.Base);
            var       dtWordTmpl = sqlHeper.ExecuteDataTable(string.Format("select TOP 1 * from S_UI_Word where Code='{0}' ORDER BY VersionNum DESC", tmplCode));

            if (dtWordTmpl.Rows.Count == 0)
            {
                throw new Exception("Word导出定义不存在");
            }


            #region 预览时的自动ID
            if (Request["TopID"] == "true" && string.IsNullOrEmpty(id))
            {
                SQLHelper sqlHelperWord = SQLHelper.CreateSqlHelper(dtWordTmpl.Rows[0]["ConnName"].ToString());
                string    sql           = string.Format("select top 1 ID from ({0}) a", dtWordTmpl.Rows[0]["SQL"]);

                if (Config.Constant.IsOracleDb)
                {
                    sql = string.Format("select ID from({0}) a where rownum=1", dtWordTmpl.Rows[0]["SQL"]);
                }

                try
                {
                    var obj = sqlHelperWord.ExecuteScalar(sql);
                    if (obj != null)
                    {
                        id = obj.ToString();
                    }
                }
                catch
                {
                    // Response.Write("SQL错误,或者表不存在!");
                    Response.Redirect("/MvcConfig/Error.html?errMsg=SQL错误,或者表不存在!");
                    Response.End();
                    return(null);
                }

                if (string.IsNullOrEmpty(id))
                {
                    Response.Write("表中没有数据,无法导出Word。");
                    Response.End();
                    return(null);
                }
            }

            #endregion

            if (string.IsNullOrEmpty(id))
            {
                throw new Exception("缺少参数ID");
            }

            //string tmplName = dtWordTmpl.Rows[0]["Code"].ToString() + ".docx";

            //string tempPath = Server.MapPath("/") + "WordTemplate/" + tmplName;



            UIFO    uiFO = FormulaHelper.CreateFO <UIFO>();
            DataSet ds   = uiFO.GetWordDataSource(tmplCode, id);

            DataRow  wordTmplRow = dtWordTmpl.Rows[0];
            DateTime date;
            if (ds.Tables[0].Columns.Contains("CreateTime"))
            {
                date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString());
            }
            else
            {
                date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateDate"].ToString());
            }

            foreach (DataRow row in dtWordTmpl.Rows)
            {
                var _startDate = DateTime.Parse(row["VersionStartDate"].ToString());
                var _endDate   = DateTime.MaxValue;
                if (row["VersionEndDate"].ToString() != "")
                {
                    _endDate = DateTime.Parse(row["VersionEndDate"].ToString());
                }

                if (date > _startDate && date < _endDate)
                {
                    wordTmplRow = row;
                    break;
                }
            }
            int?versionNum = 1;
            if (wordTmplRow["VersionNum"].ToString() != "")
            {
                versionNum = int.Parse(wordTmplRow["VersionNum"].ToString());
            }

            string tempPath = HttpContext.Server.MapPath("/") + "WordTemplate/" + wordTmplRow["Code"].ToString() + "_" + versionNum + ".docx";
            //兼容以前没有版本时
            if (System.IO.File.Exists(tempPath) == false)
            {
                tempPath = HttpContext.Server.MapPath("/") + "WordTemplate/" + wordTmplRow["Code"].ToString() + ".docx";
            }

            AsposeWordExporter export = new AsposeWordExporter();
            byte[]             result = null;
            if (Request["pdf"] == "true")
            {
                result = export.ExportPDF(ds, tempPath, delegate(FieldMergingArgs e)
                {
                    if (e.FieldValue != null)
                    {
                        string strValues = e.FieldValue.ToString();
                        if (HtmlStringHelper.CheckHtml(strValues))
                        {
                            DocumentBuilder builder = new DocumentBuilder(e.Document);
                            builder.MoveToMergeField(e.FieldName);
                            builder.InsertHtml(strValues);
                        }
                    }
                });
            }
            else
            {
                result = export.ExportWord(ds, tempPath, delegate(FieldMergingArgs e)
                {
                    if (e.FieldValue != null)
                    {
                        string strValues = e.FieldValue.ToString();
                        if (HtmlStringHelper.CheckHtml(strValues))
                        {
                            DocumentBuilder builder = new DocumentBuilder(e.Document);
                            builder.MoveToMergeField(e.FieldName);
                            builder.InsertHtml(strValues);
                        }
                    }
                });
            }
            MemoryStream docStream = new MemoryStream(result);

            string realFileName = dtWordTmpl.Rows[0]["Name"].ToString();
            if (wordTmplRow["WordNameTmpl"].ToString() != "")
            {
                realFileName = uiFO.ReplaceString(wordTmplRow["WordNameTmpl"].ToString(), ds.Tables[0].Rows[0]);
            }


            if (!String.IsNullOrEmpty(Request["filename"]))
            {
                realFileName = Request["filename"];
            }
            var explorerName = HttpContext.Request.Browser.Browser.ToUpper();
            if (explorerName == "IE" || explorerName == "INTERNETEXPLORER" || HttpContext.Request.UserAgent.ToString().IndexOf("rv:11") > 0)
            {
                realFileName = HttpUtility.UrlEncode(realFileName, System.Text.Encoding.UTF8);
                realFileName = realFileName.Replace("+", "%20");
            }

            if (Request["pdf"] == "true")
            {
                return(base.File(docStream.ToArray(), "application/pdf", realFileName + ".pdf"));
            }
            else
            {
                return(base.File(docStream.ToArray(), "application/msword", realFileName + ".doc"));
            }
        }