Spread 中给用户提供了自定义CellType的接口,用户可以定义自己所需要的单元格类型,以实现快捷的数据编辑操作和丰富的数据展示形式,不过 .NET 中提供的标准控件很有限,只能实现一些基本的功能。本文就结合 ComponentOne 所提供的功能强大的 WinForms 控件来实现更多类型的自定义单元格类型。
Spread for WinForms 在浏览状态时可以控件单元格的水平对齐和垂直对齐方式,不过在进入编辑状态时,垂直对齐方式将失效,我们就结合 C1TextBox for WinForms 控件来实现编辑状态时的垂直居中功能。
首先,需要你安装 ComponentOne Studio for WinForms 产品,下载地址:http://www.grapecity.com.cn/developer/c1_winforms_overview.htm
以下是自定义单元格类型的完整代码:
public class CTextCellType : FarPoint.Win.Spread.CellType.TextCellType { C1.Win.C1Input.C1TextBox txt = null; public CTextCellType() { txt = new C1.Win.C1Input.C1TextBox(); txt.VerticalAlign = C1.Win.C1Input.VerticalAlignEnum.Middle; txt.TextAlign = HorizontalAlignment.Center; txt.Multiline = true; txt.WordWrap = true; txt.LostFocus += new EventHandler(txt_LostFocus); } void txt_LostFocus(object sender, EventArgs e) { C1.Win.C1Input.C1TextBox txt = sender as C1.Win.C1Input.C1TextBox; FarPoint.Win.Spread.FpSpread spread = txt.Parent as FarPoint.Win.Spread.FpSpread; spread.ActiveSheet.ActiveCell.Value = txt.Text; } public override Control GetEditorControl(Control parent, FarPoint.Win.Spread.Appearance appearance, float zoomFactor) { return txt; } public override object GetEditorValue() { return txt.Text; } public override void SetEditorValue(object value) { txt.Value = value; } }
使用自定义CellType:
private void Form1_Load(object sender, EventArgs e) { CTextCellType txt = new CTextCellType(); txt.Multiline = true; txt.WordWrap = true; fpSpread1.ActiveSheet.Columns[0].CellType = txt; fpSpread1.ActiveSheet.Columns[0].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center; fpSpread1.ActiveSheet.Columns[0].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center; }
源码下载:
运行截图: