Exemplo n.º 1
0
        /// <summary>
        /// 验证重复数据
        /// </summary>
        protected void ValidateDuplicateData()
        {
            //获取设定的重复字段信息
            var checkCondition = SetDuplicatedCheck();

            if (checkCondition != null && checkCondition.Groups.Count > 0)
            {
                //生成基础Query
                var baseExp              = DC.Set <TModel>().AsQueryable();
                var modelType            = typeof(TModel);
                ParameterExpression para = Expression.Parameter(modelType, "tm");
                //循环所有重复字段组
                foreach (var group in checkCondition.Groups)
                {
                    List <Expression> conditions = new List <Expression>();
                    //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据
                    var idproperty                = typeof(TModel).GetProperties().Where(x => x.Name.ToLower() == "id").FirstOrDefault();
                    MemberExpression   idLeft     = Expression.Property(para, idproperty);
                    ConstantExpression idRight    = Expression.Constant(Entity.GetID());
                    BinaryExpression   idNotEqual = Expression.NotEqual(idLeft, idRight);
                    conditions.Add(idNotEqual);
                    List <PropertyInfo> props = new List <PropertyInfo>();
                    //在每个组中循环所有字段
                    foreach (var field in group.Fields)
                    {
                        Expression exp = field.GetExpression(Entity, para);
                        if (exp != null)
                        {
                            conditions.Add(exp);
                        }
                        //将字段名保存,为后面生成错误信息作准备
                        props.AddRange(field.GetProperties());
                    }
                    //如果要求判断id不重复,则去掉id不相等的判断,加入id相等的判断
                    if (props.Any(x => x.Name.ToLower() == "id"))
                    {
                        conditions.RemoveAt(0);
                        BinaryExpression idEqual = Expression.Equal(idLeft, idRight);
                        conditions.Insert(0, idEqual);
                    }
                    int count = 0;
                    if (conditions.Count > 1)
                    {
                        //循环添加条件并生成Where语句
                        Expression conExp = conditions[0];
                        for (int i = 1; i < conditions.Count; i++)
                        {
                            conExp = Expression.And(conExp, conditions[i]);
                        }

                        MethodCallExpression whereCallExpression = Expression.Call(
                            typeof(Queryable),
                            "Where",
                            new Type[] { modelType },
                            baseExp.Expression,
                            Expression.Lambda <Func <TModel, bool> >(conExp, new ParameterExpression[] { para }));
                        var result = baseExp.Provider.CreateQuery(whereCallExpression);

                        foreach (var res in result)
                        {
                            count++;
                        }
                    }
                    if (count > 0)
                    {
                        //循环拼接所有字段名
                        string AllName = "";
                        foreach (var prop in props)
                        {
                            string name = PropertyHelper.GetPropertyDisplayName(prop);
                            AllName += name + ",";
                        }
                        if (AllName.EndsWith(","))
                        {
                            AllName = AllName.Remove(AllName.Length - 1);
                        }
                        //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示
                        if (props.Count == 1)
                        {
                            MSD.AddModelError(GetValidationFieldName(props[0])[0], AllName + "字段重复");
                        }
                        //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示
                        else if (props.Count > 1)
                        {
                            MSD.AddModelError(GetValidationFieldName(props.First())[0], AllName + "字段组合重复");
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 创建标准动作
        /// </summary>
        /// <typeparam name="T">继承自TopBasePoco的类</typeparam>
        /// <typeparam name="V">继承自ISearcher的类</typeparam>
        /// <param name="self">self</param>
        /// <param name="controllerName">动作的Controller</param>
        /// <param name="standardType">标准动作类型</param>
        /// <param name="dialogTitle">弹出窗口的标题</param>
        /// <param name="areaName">域名</param>
        /// <param name="dialogWidth">弹出窗口的宽度</param>
        /// <param name="dialogHeight">弹出窗口的高度</param>
        /// <param name="name">动作名,默认为‘新建’</param>
        /// <param name="buttonId">Button的id  默认自动生成</param>
        /// <param name="whereStr">whereStr</param>
        /// <returns>列表动作</returns>
        /// <remarks>
        /// 根据标准动作类型,创建默认属性的标准动作
        /// </remarks>
        public static GridAction MakeStandardAction <T, V>(this IBasePagedListVM <T, V> self
                                                           , string controllerName
                                                           , GridActionStandardTypesEnum standardType
                                                           , string dialogTitle
                                                           , string areaName  = null
                                                           , int?dialogWidth  = null
                                                           , int?dialogHeight = null
                                                           , string name      = null
                                                           , string buttonId  = null
                                                           , params Expression <Func <T, object> >[] whereStr)
            where T : TopBasePoco
            where V : ISearcher
        {
            var iconcls       = string.Empty;
            var actionName    = standardType.ToString();
            var gridname      = string.Empty;
            var paraType      = GridActionParameterTypesEnum.NoId;
            var showInRow     = false;
            var hideOnToolBar = false;

            switch (standardType)
            {
            case GridActionStandardTypesEnum.Create:
                iconcls  = "icon-add";
                gridname = "新建";
                paraType = GridActionParameterTypesEnum.NoId;
                break;

            case GridActionStandardTypesEnum.AddRow:
                iconcls  = "icon-add";
                gridname = "新建";
                paraType = GridActionParameterTypesEnum.AddRow;
                break;

            case GridActionStandardTypesEnum.Edit:
                iconcls       = "icon-edit";
                gridname      = "修改";
                paraType      = GridActionParameterTypesEnum.SingleId;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.Delete:
                iconcls       = "icon-delete";
                gridname      = "删除";
                paraType      = GridActionParameterTypesEnum.SingleId;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.RemoveRow:
                iconcls       = "icon-delete";
                gridname      = "删除";
                paraType      = GridActionParameterTypesEnum.RemoveRow;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.Details:
                iconcls       = "icon-details";
                gridname      = "详细";
                paraType      = GridActionParameterTypesEnum.SingleId;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.BatchEdit:
                iconcls  = "icon-edit";
                gridname = "批量修改";
                paraType = GridActionParameterTypesEnum.MultiIds;
                break;

            case GridActionStandardTypesEnum.BatchDelete:
                iconcls  = "icon-delete";
                gridname = "批量删除";
                paraType = GridActionParameterTypesEnum.MultiIds;
                break;

            case GridActionStandardTypesEnum.Import:
                iconcls  = "icon-details";
                gridname = "导入";
                paraType = GridActionParameterTypesEnum.NoId;
                break;

            default:
                break;
            }

            var list = new List <string>();

            foreach (var item in whereStr)
            {
                list.Add(PropertyHelper.GetPropertyName(item));
            }

            return(new GridAction
            {
                ButtonId = buttonId,
                Name = (name ?? gridname),
                DialogTitle = dialogTitle,
                Area = areaName,
                ControllerName = controllerName,
                ActionName = actionName,
                ParameterType = paraType,

                IconCls = iconcls,
                DialogWidth = dialogWidth ?? 800,
                DialogHeight = dialogHeight,
                ShowInRow = showInRow,
                ShowDialog = true,
                HideOnToolBar = hideOnToolBar,
                whereStr = list.ToArray()
            });
        }
        protected void ValidateDuplicateData(DuplicatedInfo <P> checkCondition, P entity)
        {
            if (checkCondition != null && checkCondition.Groups.Count > 0)
            {
                //生成基础Query
                var baseExp              = EntityList.AsQueryable();
                var modelType            = typeof(P);
                ParameterExpression para = Expression.Parameter(modelType, "tm");
                //循环所有重复字段组
                foreach (var group in checkCondition.Groups)
                {
                    List <Expression> conditions = new List <Expression>();
                    //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据
                    MemberExpression   idLeft     = Expression.Property(para, "Id");
                    ConstantExpression idRight    = Expression.Constant(entity.ID);
                    BinaryExpression   idNotEqual = Expression.NotEqual(idLeft, idRight);
                    conditions.Add(idNotEqual);
                    List <PropertyInfo> props = new List <PropertyInfo>();
                    //在每个组中循环所有字段
                    foreach (var field in group.Fields)
                    {
                        Expression exp = field.GetExpression(entity, para);
                        if (exp != null)
                        {
                            conditions.Add(exp);
                        }
                        //将字段名保存,为后面生成错误信息作准备
                        props.AddRange(field.GetProperties());
                    }
                    int count = 0;
                    if (conditions.Count > 1)
                    {
                        //循环添加条件并生成Where语句
                        Expression conExp = conditions[0];
                        for (int i = 1; i < conditions.Count; i++)
                        {
                            conExp = Expression.And(conExp, conditions[i]);
                        }

                        MethodCallExpression whereCallExpression = Expression.Call(
                            typeof(Queryable),
                            "Where",
                            new Type[] { modelType },
                            baseExp.Expression,
                            Expression.Lambda <Func <P, bool> >(conExp, new ParameterExpression[] { para }));
                        var result = baseExp.Provider.CreateQuery(whereCallExpression);

                        foreach (var res in result)
                        {
                            count++;
                        }
                    }
                    if (count > 0)
                    {
                        //循环拼接所有字段名
                        string AllName = "";
                        foreach (var prop in props)
                        {
                            string name = PropertyHelper.GetPropertyDisplayName(prop);
                            AllName += name + ",";
                        }
                        if (AllName.EndsWith(","))
                        {
                            AllName = AllName.Remove(AllName.Length - 1);
                        }
                        //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示
                        if (props.Count == 1)
                        {
                            ErrorListVM.EntityList.Add(new ErrorMessage {
                                Message = AllName + "数据重复", Index = entity.ExcelIndex
                            });
                        }
                        //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示
                        else if (props.Count > 1)
                        {
                            ErrorListVM.EntityList.Add(new ErrorMessage {
                                Message = AllName + "组合字段重复", Index = entity.ExcelIndex
                            });
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 保存指定表中的数据
        /// </summary>
        /// <returns>成功返回True,失败返回False</returns>
        public virtual bool BatchSaveData()
        {
            //如果没有赋值,则调用赋值函数
            if (isEntityListSet == false)
            {
                SetEntityList();
            }
            //如果在复制过程中已经有错误,则直接输出错误
            if (ErrorListVM.EntityList.Count > 0)
            {
                DoReInit();
                return(false);
            }
            //进行Model层面的验证
            //找到对应的BaseCRUDVM,并初始化
            var vms = this.GetType().Assembly.GetExportedTypes().Where(x => x.IsSubclassOf(typeof(BaseCRUDVM <P>))).ToList();

            var vmtype = vms.Where(x => x.Name.ToLower() == typeof(P).Name.ToLower() + "vm").FirstOrDefault();

            if (vmtype == null)
            {
                vmtype = vms.FirstOrDefault();
            }
            IBaseCRUDVM <P>    vm    = null;
            DuplicatedInfo <P> dinfo = null;

            if (vmtype != null)
            {
                vm = vmtype.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IBaseCRUDVM <P>;
                vm.CopyContext(this);
                dinfo = (vm as dynamic).SetDuplicatedCheck();
            }
            var cinfo = this.SetDuplicatedCheck();
            DuplicatedInfo <P> finalInfo = new DuplicatedInfo <P>
            {
                Groups = new List <DuplicatedGroup <P> >()
            };

            if (dinfo == null)
            {
                dinfo = new DuplicatedInfo <P>();
            }
            if (cinfo == null)
            {
                cinfo = new DuplicatedInfo <P>();
            }
            if (dinfo.Groups != null)
            {
                foreach (var di in dinfo.Groups)
                {
                    bool found = false;
                    if (cinfo.Groups != null)
                    {
                        foreach (var ci in cinfo.Groups)
                        {
                            if (di.ToString() == ci.ToString())
                            {
                                found = true;
                                break;
                            }
                        }
                    }
                    if (found == false)
                    {
                        finalInfo.Groups.Add(di);
                    }
                }
            }
            //todo: RedoValidation
            //BaseController bc = new BaseController();
            foreach (var entity in EntityList)
            {
                //bool check = bc.RedoValidation(entity);
                //if (check == false)
                //{
                //    ErrorListVM.ErrorList.Add(new ErrorMessage { Message = bc.ModelState.Where(x => x.Value.Errors != null && x.Value.Errors.Count > 0).SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage).FirstOrDefault(), Index = entity.ExcelIndex });
                //}
                if (vm != null)
                {
                    vm.SetEntity(entity);
                    vm.ByPassBaseValidation = true;
                    vm.Validate();
                    var basevm = vm as BaseVM;
                    if (basevm?.MSD?.Count > 0)
                    {
                        foreach (var key in basevm.MSD.Keys)
                        {
                            foreach (var error in basevm.MSD[key])
                            {
                                ErrorListVM.EntityList.Add(new ErrorMessage {
                                    Message = error.ErrorMessage, Index = entity.ExcelIndex
                                });
                            }
                        }
                    }
                }
                (vm as BaseVM)?.MSD.Clear();
                //在本地EntityList中验证是否有重复
                ValidateDuplicateData(finalInfo, entity);
            }
            //如果上述验证已经有错误,则直接输出错误
            if (ErrorListVM.EntityList.Count > 0)
            {
                (vm as BaseVM)?.MSD.Clear();
                DoReInit();
                return(false);
            }

            //循环数据列表
            foreach (var item in EntityList)
            {
                //根据唯一性的设定查找数据库中是否有同样的数据
                P exist = IsDuplicateData(item, finalInfo);
                //如果有重复数据,则进行修改
                if (exist != null)
                {
                    //如果是普通字段,则直接赋值
                    var tempPros = typeof(T).GetFields();
                    foreach (var pro in tempPros)
                    {
                        var excelProp = Template.GetType().GetField(pro.Name).GetValue(Template) as ExcelPropety;
                        var proToSet  = typeof(P).GetProperty(excelProp.FieldName);
                        if (proToSet != null)
                        {
                            var val = proToSet.GetValue(item);
                            PropertyHelper.SetPropertyValue(exist, excelProp.FieldName, val, stringBasedValue: true);
                        }
                    }
                    //更新修改时间字段
                    if (tempPros.Where(x => x.Name == "UpdateTime").SingleOrDefault() == null)
                    {
                        if (typeof(BasePoco).IsAssignableFrom(exist.GetType()))
                        {
                            (exist as BasePoco).UpdateTime = DateTime.Now;
                        }
                    }
                    //更新修改人字段
                    if (tempPros.Where(x => x.Name == "UpdateBy").SingleOrDefault() == null)
                    {
                        if (typeof(BasePoco).IsAssignableFrom(exist.GetType()))
                        {
                            (exist as BasePoco).UpdateBy = LoginUserInfo.ITCode;
                        }
                    }
                    exist.ExcelIndex = item.ExcelIndex;
                    //更新字段
                    DC.UpdateEntity(exist);
                }
                //如果没有重复数据,则填加
                else
                {
                    if (typeof(BasePoco).IsAssignableFrom(item.GetType()))
                    {
                        (item as BasePoco).CreateTime = DateTime.Now;
                        (item as BasePoco).CreateBy   = LoginUserInfo?.ITCode;
                    }
                    DC.Set <P>().Add(item);
                }
            }
            //如果有错误,则返回
            if (ErrorListVM.EntityList.Count > 0)
            {
                DoReInit();
                return(false);
            }
            //如果没有错误,更新数据库
            if (EntityList.Count > 0)
            {
                try
                {
                    DC.SaveChanges();
                }
                catch (Exception e)
                {
                    SetExceptionMessage(e, null);
                    DoReInit();
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// 获取上传的结果值
        /// </summary>
        public virtual void SetEntityList()
        {
            EntityList = new List <P>();
            //获取Model类的所有属性
            var pros      = typeof(P).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            var excelPros = typeof(T).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(x => x.FieldType == typeof(ExcelPropety)).ToList();

            if (TemplateData == null)
            {
                DoMapList();
            }
            //循环Excel中的数据
            foreach (var item in TemplateData)
            {
                int  rowIndex   = 2;
                bool isMainData = false;
                //主表信息
                Dictionary <string, ExcelPropety> mainInfo = new Dictionary <string, ExcelPropety>();
                string mainValString = string.Empty;

                //子表信息
                Dictionary <Type, List <FieldInfo> > subpros      = new Dictionary <Type, List <FieldInfo> >();
                Dictionary <Type, string>            subValString = new Dictionary <Type, string>();

                //循环TemplateVM中定义的所有的列,区分出主子表
                foreach (var epro in excelPros)
                {
                    //获取本列的ExcelProperty的值
                    if (typeof(T).GetField(epro.Name).GetValue(item) is ExcelPropety ep)
                    {
                        //如果是子表的字段
                        if (ep.SubTableType != null)
                        {
                            //保存子表字段信息稍后处理
                            if (!subpros.ContainsKey(ep.SubTableType))
                            {
                                subpros[ep.SubTableType] = new List <FieldInfo>();
                            }
                            subpros[ep.SubTableType].Add(epro);
                        }
                        else
                        {
                            //PropertyHelper.SetPropertyValue(entity, epro.Name, ep.Value, stringBasedValue: true);
                            //保存子表字段信息稍后处理
                            mainInfo.Add(ep.FieldName, ep);
                            mainValString += ep.Value;
                        }
                    }
                }

                //子表信息是否为空
                foreach (var sub in subpros)
                {
                    string subVal = string.Empty;
                    foreach (var field in sub.Value)
                    {
                        ExcelPropety ep = typeof(T).GetField(field.Name).GetValue(item) as ExcelPropety;
                        subVal += ep.Value;
                    }
                    subValString.Add(sub.Key, subVal);
                }

                P entity = null;
                //说明主表信息为空
                if (string.IsNullOrEmpty(mainValString))
                {
                    entity = EntityList.LastOrDefault();
                }
                else
                {
                    //初始化一个新的Entity
                    entity     = new P();
                    isMainData = true;
                    //给主表赋值
                    foreach (var mep in mainInfo)
                    {
                        SetEntityFieldValue(entity, mep.Value, rowIndex, mep.Key, item);
                    }
                }

                //给子表赋值
                foreach (var sub in subpros)
                {
                    //循环Entity的所有属性,找到List<SubTableType>类型的字段
                    foreach (var pro in pros)
                    {
                        if (pro.PropertyType.IsGenericType)
                        {
                            var gtype = pro.PropertyType.GetGenericArguments()[0];
                            if (gtype == sub.Key)
                            {
                                //子表
                                var subList = entity.GetType().GetProperty(pro.Name).GetValue(entity);

                                //如果子表不为空
                                if (!string.IsNullOrEmpty(subValString.Where(x => x.Key == sub.Key).FirstOrDefault().Value))
                                {
                                    IList list = null;
                                    if (subList == null)
                                    {
                                        //初始化List<SubTableType>
                                        list = typeof(List <>).MakeGenericType(gtype).GetConstructor(Type.EmptyTypes).Invoke(null) as IList;
                                    }
                                    else
                                    {
                                        list = subList as IList;
                                    }

                                    //初始化一个SubTableType
                                    var obj = gtype.GetConstructor(System.Type.EmptyTypes).Invoke(null);

                                    //给SubTableType中和本ExcelProperty同名的字段赋值
                                    foreach (var field in sub.Value)
                                    {
                                        ExcelPropety ep = typeof(T).GetField(field.Name).GetValue(item) as ExcelPropety;
                                        //PropertyHelper.SetPropertyValue(obj, field.Name, ep.Value, stringBasedValue: true);
                                        SetEntityFieldValue(obj, ep, rowIndex, ep.FieldName, item);
                                    }
                                    //将付好值得SubTableType实例添加到List中
                                    list.Add(obj);
                                    PropertyHelper.SetPropertyValue(entity, pro.Name, list);
                                }
                                break;
                            }
                        }
                    }
                }
                entity.ExcelIndex = item.ExcelIndex;
                var cinfo = this.SetDuplicatedCheck();
                //if (IsUpdateRecordDuplicated(cinfo, entity) == false)
                //{
                if (isMainData)
                {
                    EntityList.Add(entity);
                }
                //}
            }
            isEntityListSet = true;
        }
Exemplo n.º 6
0
        /// <summary>
        /// 根据集合生成单个Excel
        /// </summary>
        /// <param name="List"></param>
        /// <returns></returns>
        private IWorkbook GenerateWorkBook(List <TModel> List)
        {
            IWorkbook book  = new XSSFWorkbook();
            ISheet    sheet = book.CreateSheet();
            IRow      row   = sheet.CreateRow(0);

            //创建表头样式
            ICellStyle headerStyle = book.CreateCellStyle();

            headerStyle.FillBackgroundColor = ExportTitleBackColor == null ? HSSFColor.LightBlue.Index : ExportTitleBackColor.Value;
            headerStyle.FillPattern         = FillPattern.SolidForeground;
            headerStyle.FillForegroundColor = ExportTitleBackColor == null ? HSSFColor.LightBlue.Index : ExportTitleBackColor.Value;
            IFont font = book.CreateFont();

            font.FontName           = "Calibri";
            font.FontHeightInPoints = 12;
            font.Color = ExportTitleFontColor == null ? HSSFColor.Black.Index : ExportTitleFontColor.Value;
            headerStyle.SetFont(font);

            //生成表头
            MakeExcelHeader(sheet, GridHeaders, 0, 0, headerStyle);

            //放入数据
            var ColIndex = 0;

            for (int i = 0; i < List.Count; i++)
            {
                ColIndex = 0;
                var DR = sheet.CreateRow(i + 1);
                foreach (var baseCol in GridHeaders)
                {
                    //处理枚举变量的多语言
                    bool IsEmunBoolParp = false;
                    var  proType        = baseCol.FieldType;
                    if (proType.IsEnumOrNullableEnum())
                    {
                        IsEmunBoolParp = true;
                    }

                    foreach (var col in baseCol.BottomChildren)
                    {
                        //获取数据,并过滤特殊字符
                        string text = Regex.Replace(col.GetText(List[i]).ToString(), @"<[^>]*>", String.Empty);

                        //处理枚举变量的多语言
                        if (IsEmunBoolParp)
                        {
                            if (int.TryParse(text, out int enumvalue))
                            {
                                text = PropertyHelper.GetEnumDisplayName(proType, enumvalue);
                            }
                        }

                        //建立excel单元格
                        var cell = DR.CreateCell(ColIndex);
                        cell.SetCellValue(text);
                        ColIndex++;
                    }
                }
            }
            return(book);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 获取列头内容
        /// </summary>
        /// <returns>Html内容</returns>
        protected virtual string GetHeader()
        {
            string rv = PropertyHelper.GetPropertyDisplayName(PI);

            return(rv == null ? "" : rv);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 生成Excel
        /// </summary>
        /// <returns>生成的Excel文件</returns>
        public virtual byte[] GenerateExcel()
        {
            NeedPage = false;
            if (GridHeaders == null)
            {
                GetHeaders();
            }
            if (IsSearched == false)
            {
                DoSearch();
            }
            HSSFWorkbook     workbook = new HSSFWorkbook();
            List <HSSFSheet> sheets   = new List <NPOI.HSSF.UserModel.HSSFSheet>();
            //准备好sheet,每6万行生成一个sheet
            var sheetno     = ((EntityList.Count - 1) / 60000) + 1;
            var headerStyle = workbook.CreateCellStyle();

            //设定单元格边框
            headerStyle.BorderBottom = BorderStyle.Thin;
            headerStyle.BorderLeft   = BorderStyle.Thin;
            headerStyle.BorderRight  = BorderStyle.Thin;
            headerStyle.BorderTop    = BorderStyle.Thin;
            //用灰色填充背景
            var headerbg = HSSFColor.Grey25Percent.Index;

            headerStyle.FillForegroundColor = headerbg;
            headerStyle.FillPattern         = FillPattern.SolidForeground;
            headerStyle.FillBackgroundColor = headerbg;
            //去掉 Id 列和动作列
            RemoveActionAndIdColumn();
            //循环生成所有sheet,并为每个sheet添加表头
            var headerrows = 0;

            for (int i = 1; i <= sheetno; i++)
            {
                HSSFSheet sheet = workbook.CreateSheet("Sheet" + i) as HSSFSheet;
                //生成表头
                headerrows = MakeExcelHeader(sheet, GridHeaders, 0, 0, headerStyle);
                sheets.Add(sheet);
            }

            var rowIndex = headerrows;
            var colIndex = 0;

            //Excel中用到的style,每种前景色和背景色的组合为一个style。Nopi值支持4000个style,所以同样的style要重复使用
            Dictionary <string, ICellStyle> styles = new Dictionary <string, ICellStyle>();
            //Excel中用到的font,主要是为了更改字体颜色
            Dictionary <string, IFont> fonts = new Dictionary <string, IFont>();

            //循环数据
            foreach (var row in EntityList)
            {
                var sheetindex = ((rowIndex - headerrows) / 60000);
                colIndex = 0;
                string bgColor = "";
                string fColor  = "";
                //获取设定的行背景色
                bgColor = SetFullRowBgColor(row);
                //获取设定的行前景色
                fColor = SetFullRowColor(row);
                var dr = sheets[sheetindex].CreateRow(rowIndex - sheetindex * 60000) as HSSFRow;
                foreach (var baseCol in GridHeaders)
                {
                    //处理枚举变量的多语言
                    bool IsEmunBoolParp = false;
                    var  proType        = baseCol.FieldType;
                    if (proType.IsEnumOrNullableEnum())
                    {
                        IsEmunBoolParp = true;
                    }

                    foreach (var col in baseCol.BottomChildren)
                    {
                        //获取数据,并过滤特殊字符
                        string text = Regex.Replace(col.GetText(row).ToString(), @"<[^>]*>", String.Empty);

                        //处理枚举变量的多语言

                        if (IsEmunBoolParp)
                        {
                            if (int.TryParse(text, out int enumvalue))
                            {
                                text = PropertyHelper.GetEnumDisplayName(proType, enumvalue);
                            }
                        }


                        //建立excel单元格
                        var        cell     = dr.CreateCell(colIndex);
                        ICellStyle style    = null;
                        IFont      font     = null;
                        var        styleKey = string.Empty;
                        //获取设定的单元格背景色
                        string backColor = col.GetBackGroundColor(row);
                        //获取设定的单元格前景色
                        string foreColor = col.GetForeGroundColor(row);
                        //如果行背景色或单元格背景色有值,则用颜色的ARGB的值作为style的key
                        if (bgColor != "" || backColor != "")
                        {
                            styleKey = backColor == "" ? bgColor : backColor;
                        }
                        //如果行前景色或单元格前景色有值,则用颜色的ARGB加上背景色的ARGB作为style的key
                        if (fColor != "" || foreColor != "")
                        {
                            styleKey += foreColor == "" ? foreColor : fColor;
                        }
                        //如果已经有符合条件的style,则使用
                        if (styles.ContainsKey(styleKey))
                        {
                            style = styles[styleKey];
                        }
                        //如果没有,则新建一个style
                        else
                        {
                            var newKey     = "";
                            var newFontKey = "";
                            //新建style
                            style = workbook.CreateCellStyle();
                            //设定单元格边框
                            style.BorderBottom = BorderStyle.Thin;
                            style.BorderLeft   = BorderStyle.Thin;
                            style.BorderRight  = BorderStyle.Thin;
                            style.BorderTop    = BorderStyle.Thin;
                            //如果行前景色或单元格前景色有值,则设定单元格的填充颜色
                            if (bgColor != "" || backColor != "")
                            {
                                newKey = backColor == "" ? bgColor : backColor;
                                var ci = Utils.GetExcelColor(backColor == "" ? bgColor : backColor);
                                style.FillForegroundColor = ci;
                                style.FillPattern         = FillPattern.SolidForeground;
                                style.FillBackgroundColor = ci;
                            }
                            //如果行前景色或单元格前景色有值,则设定单元格的字体的颜色
                            if (fColor != "" || foreColor != "")
                            {
                                newFontKey = foreColor == "" ? foreColor : fColor;
                                newKey    += foreColor == "" ? foreColor : fColor;
                                //如果已经有符合条件的字体,则使用
                                if (fonts.ContainsKey(newFontKey))
                                {
                                    font = fonts[newFontKey];
                                }
                                //如果没有,则新建
                                else
                                {
                                    //新建字体
                                    font = workbook.CreateFont();
                                    //设定字体颜色
                                    font.Color = Utils.GetExcelColor(foreColor == "" ? fColor : foreColor);
                                    //向集合中添加新字体
                                    fonts.Add(newFontKey, font);
                                }
                                //设定style中的字体
                                style.SetFont(font);
                            }
                            //将新建的style添加到集合中
                            styles.Add(newKey, style);
                        }
                        cell.CellStyle = style;
                        cell.SetCellValue(text);
                        colIndex++;
                    }
                }
                rowIndex++;
            }

            //获取Excel文件的二进制数据
            byte[] rv = new byte[] { };
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                rv          = ms.ToArray();
            }
            return(rv);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 创建标准动作
        /// </summary>
        /// <typeparam name="T">继承自TopBasePoco的类</typeparam>
        /// <typeparam name="V">继承自ISearcher的类</typeparam>
        /// <param name="self">self</param>
        /// <param name="controllerName">动作的Controller</param>
        /// <param name="standardType">标准动作类型</param>
        /// <param name="dialogTitle">弹出窗口的标题,可为空,代表使用默认文字</param>
        /// <param name="areaName">域名</param>
        /// <param name="dialogWidth">弹出窗口的宽度</param>
        /// <param name="dialogHeight">弹出窗口的高度</param>
        /// <param name="name">按钮显示的文字</param>
        /// <param name="buttonId">Button的id  默认自动生成</param>
        /// <param name="whereStr">whereStr</param>
        /// <returns>列表动作</returns>
        /// <remarks>
        /// 根据标准动作类型,创建默认属性的标准动作
        /// </remarks>
        public static GridAction MakeStandardAction <T, V>(this IBasePagedListVM <T, V> self
                                                           , string controllerName
                                                           , GridActionStandardTypesEnum standardType
                                                           , string dialogTitle
                                                           , string areaName  = null
                                                           , int?dialogWidth  = null
                                                           , int?dialogHeight = null
                                                           , string name      = null
                                                           , string buttonId  = null
                                                           , params Expression <Func <T, object> >[] whereStr)
            where T : TopBasePoco
            where V : ISearcher
        {
            var iconcls       = string.Empty;
            var actionName    = standardType.ToString();
            var gridname      = string.Empty;
            var paraType      = GridActionParameterTypesEnum.NoId;
            var showInRow     = false;
            var hideOnToolBar = false;
            var showDialog    = true;

            switch (standardType)
            {
            case GridActionStandardTypesEnum.Create:
                iconcls  = "layui-icon layui-icon-add-1";
                gridname = Program._localizer["Create"];
                paraType = GridActionParameterTypesEnum.NoId;
                break;

            case GridActionStandardTypesEnum.AddRow:
                iconcls  = "layui-icon layui-icon-add-1";
                gridname = Program._localizer["Create"];
                paraType = GridActionParameterTypesEnum.AddRow;
                break;

            case GridActionStandardTypesEnum.Edit:
                iconcls       = "layui-icon layui-icon-edit";
                gridname      = Program._localizer["Edit"];
                paraType      = GridActionParameterTypesEnum.SingleId;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.Delete:
                iconcls       = "layui-icon layui-icon-delete";
                gridname      = Program._localizer["Delete"];
                paraType      = GridActionParameterTypesEnum.SingleId;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.RemoveRow:
                iconcls       = "layui-icon layui-icon-delete";
                gridname      = Program._localizer["Delete"];
                paraType      = GridActionParameterTypesEnum.RemoveRow;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.Details:
                iconcls       = "layui-icon layui-icon-form";
                gridname      = Program._localizer["Details"];
                paraType      = GridActionParameterTypesEnum.SingleId;
                showInRow     = true;
                hideOnToolBar = true;
                break;

            case GridActionStandardTypesEnum.BatchEdit:
                iconcls  = "layui-icon layui-icon-edit";
                gridname = Program._localizer["BatchEdit"];
                paraType = GridActionParameterTypesEnum.MultiIds;
                break;

            case GridActionStandardTypesEnum.BatchDelete:
                iconcls  = "layui-icon layui-icon-delete";
                gridname = Program._localizer["BatchDelete"];
                paraType = GridActionParameterTypesEnum.MultiIds;
                break;

            case GridActionStandardTypesEnum.Import:
                iconcls  = "layui-icon layui-icon-templeate-1";
                gridname = Program._localizer["Import"];
                paraType = GridActionParameterTypesEnum.NoId;
                break;

            case GridActionStandardTypesEnum.ExportExcel:
                iconcls       = "layui-icon layui-icon-download-circle";
                gridname      = Program._localizer["Export"];
                paraType      = GridActionParameterTypesEnum.MultiIdWithNull;
                name          = Program._localizer["ExportExcel"];
                showInRow     = false;
                showDialog    = false;
                hideOnToolBar = false;
                break;

            default:
                break;
            }

            if (string.IsNullOrEmpty(dialogTitle))
            {
                dialogTitle = gridname;
            }

            var list = new List <string>();

            foreach (var item in whereStr)
            {
                list.Add(PropertyHelper.GetPropertyName(item));
            }

            return(new GridAction
            {
                ButtonId = buttonId,
                Name = (name ?? gridname),
                DialogTitle = dialogTitle,
                Area = areaName,
                ControllerName = controllerName,
                ActionName = actionName,
                ParameterType = paraType,

                IconCls = iconcls,
                DialogWidth = dialogWidth ?? 800,
                DialogHeight = dialogHeight,
                ShowInRow = showInRow,
                ShowDialog = showDialog,
                HideOnToolBar = hideOnToolBar,
                whereStr = list.ToArray()
            });
        }