Spread 表格控件在业内以强大的 Excel 兼容性著称,并且广泛应用于制作报表。在日常工作中,经常需要使用 excel 制作交叉报表,Excel 交叉报表的左上角单元格斜线通过 Excel 单元格斜边框制作。那么,在Spread中是否可以实现这样的效果呢?在篇文章中,我们将阐述如何在 Spread 中添加斜线实现交叉报表中的表头效果。
本文将讲阐述如何在Spread for XAML平台实现这个功能。主要思路为结合 IDrawingObjectProvider 和 Canvas 进行绘制。
以下为最终效果图:
下面我们将分布讲解实现方法。
1.IDrawingObjectProvider 接口的作用是“向 GcSpreadSheet 控件添加子控件”,首先我们需要实现该接口,在接口中判断需要绘制报表头部的单元格,进而进行绘制:
internal class MyDrawingObjectProvider : IDrawingObjectProvider
{public DrawingObject[] GetDrawingObjects(Worksheet sheet, int row, int column, int rowCount, int columnCount)
{if (row == 0 && column == 0)
{DiagonalDrawingObject dobj = new DiagonalDrawingObject(sheet, row, column);
return new DrawingObject[] { dobj };}return sheet.GetDrawingObject(row, column, rowCount, columnCount);
}}
2.CustomDrawingObject 类用于在单元格中绘制控件,其中我们使用 Canvas 来绘制复杂的交叉报表表头:
public override FrameworkElement RootElement
{get
{string cellText = this.Worksheet.GetText(this.AnchorRow, this.AnchorColumn);
string[] values = null;
if (!string.IsNullOrEmpty(cellText)){values = cellText.Split(',');
}double width = this.Worksheet.GetColumnWidth(this.AnchorColumn);
double height = this.Worksheet.GetRowHeight(this.AnchorRow);
Brush cellForeground = this.Worksheet.Cells[this.AnchorRow, this.AnchorColumn].ActualForeground;if (cellForeground == null)
{cellForeground = new SolidColorBrush(Colors.Black);
}Canvas canvas = new Canvas();
Line diagonalLine1 = new Line();
diagonalLine1.Stroke = cellForeground;diagonalLine1.StrokeThickness = 1;diagonalLine1.X1 = 0;diagonalLine1.Y1 = height / 3;diagonalLine1.X2 = width;diagonalLine1.Y2 = height;Line diagonalLine2 = new Line();
diagonalLine2.Stroke = cellForeground;diagonalLine2.StrokeThickness = 1;diagonalLine2.X1 = width / 3;diagonalLine2.Y1 = 0;diagonalLine2.X2 = width;diagonalLine2.Y2 = height;canvas.Children.Add(diagonalLine1);canvas.Children.Add(diagonalLine2);if (values != null)
{if (values.Length > 0)
{string text1 = values[0];
TextBlock t1 = new TextBlock();
t1.Text = text1;//t1.RenderTransform = new RotateTransform(30, 0.5, 0.5);
Canvas.SetLeft(t1, 10);Canvas.SetTop(t1, height - 30);canvas.Children.Add(t1);}if (values.Length > 1)
{string text2 = values[1];
TextBlock t2 = new TextBlock();
t2.Text = text2;//t2.RenderTransform = new RotateTransform(30, 0.5, 0.5);
Canvas.SetLeft(t2, 40);Canvas.SetTop(t2, height / 3);canvas.Children.Add(t2);}if (values.Length > 2)
{string text3 = values[2];
TextBlock t3 = new TextBlock();
t3.Text = text3;//t3.RenderTransform = new RotateTransform(50, 0.5, 0.5);
Canvas.SetLeft(t3, 3 * (width / 5));Canvas.SetTop(t3, 10);canvas.Children.Add(t3);}}return canvas;
}
3.使用DrawingObjectManager关联 Spread 控件和IDrawingObjectProvider实例:
DrawingObjectManager.SetDrawingObjectProvider(this.spread1, new MyDrawingObjectProvider());
Demo 下载:
VS2013 + C# + .NET4.0 + Silverlight
下载试用版体验更多更能:点击下载