您的位置:首页 > 编程语言 > C#

使用C#和Excel进行报表开发(三)-生成统计图(Chart)2

2013-02-21 15:01 323 查看
好了,到此,准备工作全部已经就绪,下面要进行Chart的生成设置部分了:

生成一个统计图对象:

Excel.Chart xlChart
= (Excel.Chart)ThisWorkbook.Charts.

Add(Type.Missing,
xlSheet, Type.Missing, Type.Missing);

设定数据来源:

Excel.Range cellRange
= (Excel.Range)xlSheet.Cells[1, 1];

通过向导生成Chart:

xlChart.ChartWizard(cellRange.CurrentRegion,

Excel.XlChartType.xl3DColumn, Type.Missing,

Excel.XlRowCol.xlColumns,1,
0, true ,

"访问量比较(dahuzizyd.cnblogs.com)", "月份", "访问量",

"");

到此,Chart的生成就完成了,貌似比较简单,下面我们对其作一些设置,好更漂亮些。

设置统计图Sheet的名称:

xlChart.Name = "统计";

现在的统计图只有一个组,他们会显示成一样的颜色,我们来让12个Bar都显示不同的颜色:

Excel.ChartGroup grp
= (Excel.ChartGroup)xlChart.ChartGroups(1);

grp.GapWidth = 20;

grp.VaryByCategories = true;

现在Chart的条目的显示形状是Box,我们让它们变成圆柱形,并给它们显示加上数据标签:

Excel.Series s
= (Excel.Series)grp.SeriesCollection(1);

s.BarShape = XlBarShape.xlCylinder;

s.HasDataLabels = true;

下面再来设置统计图的标题和图例的显示:

xlChart.Legend.Position = XlLegendPosition.xlLegendPositionTop;

xlChart.ChartTitle.Font.Size = 24;

xlChart.ChartTitle.Shadow = true;

xlChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;

最后设置两个轴的属性,Excel.XlAxisType.xlValue对应的是Y轴,Excel.XlAxisType.xlCategory对应的是X轴:

Excel.Axis valueAxis
= (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,XlAxisGroup.xlPrimary);

valueAxis.AxisTitle.Orientation = -90;

Excel.Axis categoryAxis
= (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,XlAxisGroup.xlPrimary);

categoryAxis.AxisTitle.Font.Name = "MS
UI Gothic";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: