Пример #1
0
        public static ExcelItem GetValue2(dynamic item, string expression)
        {
            var result   = new ExcelItem();
            var frontStr = "{";
            var endStr   = "}";

            if (expression.Contains(frontStr) && expression.Contains(endStr))
            {
                //字符串表达式,如工资,工资-社保-公积金
                var expressionStr = GetMiddleString(expression, frontStr, endStr);

                //计算表达式
                var caculateExpression = expressionStr;

                //按属性长度倒序排序的属性集合,满足表达式的最长匹配
                var orderedPropertyList = ((IDictionary <String, Object>)item).OrderByDescending(p => p.Key.Length).ToList();

                //用数据替换属性,得到表达式
                foreach (var property in orderedPropertyList)
                {
                    caculateExpression = caculateExpression.Replace(property.Key, property.Value?.ToString());
                }

                //运算符集合
                List <string> operatorList = new List <string>()
                {
                    "+", "-", "*", "/", "%"
                };

                //判断表达式是否包含运算符
                if (operatorList.Any(p => expressionStr.Contains(p)))
                {
                    //包含运算符
                    //计算表达式
                    result.Value = Eval(caculateExpression);
                    result.IsContainsOperator = true;
                }
                else
                {
                    //不包含运算符
                    result.Value = caculateExpression;
                    result.IsContainsOperator = false;
                }
            }
            else
            {
                result = item.expression;
            }
            return(result);
        }
Пример #2
0
        /// <summary>
        /// 根据表达式计算结果
        /// </summary>
        /// <param name="item">数据源</param>
        /// <param name="expression">表达式,用大括号包含,如:工号{工号}、实发{工资-社保-公积金}</param>
        /// <returns></returns>
        public static ExcelItem GetValue(dynamic item, string expression)
        {
            var result = new ExcelItem();

            result.IsContainsOperator = expression.IndexOf("+") > -1;
            var frontStr      = "{";
            var endStr        = result.IsContainsOperator ? "+" : "}";
            var expressionStr = GetMiddleString(expression, frontStr, endStr);

            var    itemAdDict = ((IDictionary <String, Object>)item);
            object value;

            if (itemAdDict.TryGetValue(expressionStr, out value))
            {
                result.Value = value?.ToString();
            }
            return(result);
        }