使用 Spread 时我们经常会使用其分组功能 Group,这篇文章通过实例给大家介绍 Spread 分组功能。
1.设置 Spread 相关属性
private void InitSpread() { //设置表单行列数 this.fpSpread1.Sheets[0].ColumnCount = 8; this.fpSpread1.Sheets[0].RowCount = 10; //设置表单数据。 SheetView sheet = fpSpread1.ActiveSheet; sheet.Cells.Get(0, 4).Value = 15; sheet.Cells.Get(1, 4).Value = 15; sheet.Cells.Get(2, 4).Value = 15; sheet.Cells.Get(3, 4).Value = 35; sheet.Cells.Get(4, 4).Value = 35; sheet.Cells.Get(5, 4).Value = 35; sheet.Cells.Get(6, 4).Value = 60; sheet.Cells.Get(7, 4).Value = 60; sheet.Cells.Get(8, 4).Value = 60; } 复制代码
2.开启 Spread 分组功能:
fpSpread1.AllowColumnMove = true; fpSpread1.ActiveSheet.AllowGroup = true; 复制代码
3.设置 GroupBar 可见性,GroupBar 即为分组区域
GroupBarInfo groupBarInfo = new GroupBarInfo(); groupBarInfo.BackColor = Color.LightBlue; groupBarInfo.ForeColor = Color.Red; groupBarInfo.Height = 50; groupBarInfo.Visible = true; this.fpSpread1.Sheets[0].GroupBarInfo = groupBarInfo; 复制代码
4.设置分组样式
FarPoint.Win.Spread.GroupInfo groupInfo = new FarPoint.Win.Spread.GroupInfo(); groupInfo.Indent = 10; groupInfo.IndentColor = Color.Red; fpSpread1.ActiveSheet.GroupInfos.Add(groupInfo); 复制代码
5.设置分组脚可见性。
fpSpread1.Sheets[0].GroupFooterVisible = true; 复制代码
6.添加默认分组列
-
/// <summary> /// 添加分组脚,设置分组脚中公式 /// </summary> private void CreateGroupFooter() { // 添加默认分组列 SheetView sheet = fpSpread1.ActiveSheet; GroupDataModel groupData = new GroupDataModel(sheet.Models.Data); sheet.Models.Data = groupData; //SortInfo 构造函数 SortInfo(0, true) 中第一个参数为用于分组的列索引。 SortInfo[] sort = new SortInfo[] { new SortInfo(4, true) }; groupData.Group(sort, null); //设置默认分组 DefaultGroupFooter groupFooter = fpSpread1.Sheets[0].DefaultGroupFooter[4]; ISheetDataModel dataModel = groupFooter.DataModel; //设置分组脚中公式 (dataModel as IAggregationSupport).SetCellAggregationType(0, 3, AggregationType.Count); (dataModel as IAggregationSupport).SetCellAggregationFormat(0, 3, "数量:{0}"); (dataModel as IAggregationSupport).SetCellAggregationType(0, 4, AggregationType.Sum); (dataModel as IAggregationSupport).SetCellAggregationFormat(0, 4, "合计:{0}"); fpSpread1.ActiveSheet.GroupFooterVisible = true; FarPoint.Win.Spread.FpSpread spread = this.fpSpread1; FarPoint.Win.Spread.Model.GroupDataModel gm; //更改分组 Text 内容 if (spread.ActiveSheet.Models.Data.GetType() == typeof(FarPoint.Win.Spread.Model.GroupDataModel)) { gm = (FarPoint.Win.Spread.Model.GroupDataModel)spread.Sheets[0].Models.Data; for (int i = 0; i < gm.Groups.Count; i++) { try { FarPoint.Win.Spread.Model.Group g; g = gm.Groups[i] as FarPoint.Win.Spread.Model.Group; int row = g.Rows.Count; if (g != null) { g.Text = g.GroupFooter.DataModel.GetValue(0, 4).ToString(); } } catch (Exception) { } } } } 复制代码
截图展示:
测试环境:VS 2008 && Spread for WinForm 5.0 中文版