在数据显示时,经常会遇到文本过长以至于超出了可用的显示范围,在多数需求中我们希望能够自动调整文本的字体大小,尽量在可用的范围内显示全部文本。本文就结合Spread for WinForms 中的自定义单元格类型来实现这一功能。
首先,我们需要创建一个自定义单元格类型,代码如下:
private class CTextCellType : FarPoint.Win.Spread.CellType.TextCellType { public override void PaintCell(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor) { if (value != null) { Font font = appearance.Font; while (g.MeasureString(value.ToString(),font).Width >= r.Width && font.Size >= 5) { font = new Font(font.FontFamily, font.Size - 0.2f, font.Style); } appearance.Font = font; } base.PaintCell(g, r, appearance, value, isSelected, isLocked, zoomFactor); } }
然后,将 CTextCellType 单元格类型应用到Spread中,代码如下:
private void Form1_Load(object sender, EventArgs e) { fpSpread1.ActiveSheet.DefaultStyle.CellType = new CTextCellType(); }
运行截图: