Home
Manage Your Code
Snippet: Create a Chart (C#)
Title: Create a Chart Language: C#
Description: Creates a chart using Micrsosoft Office Web Components (OWC11) Views: 480
Author: Dan Kengott Date Added: 5/31/2007
Copy Code  
1using Microsoft.Office.Interop.Owc11;
2
3		private void CreateChart(string names, string totals, int chartWidth, int chartHeight) {
4			//Chart control accepts tab-delimited string of values
5			ChartSpaceClass oChartSpace = new ChartSpaceClass();
6
7			oChartSpace.Charts.Add(0);
8			//Default chart is a Bar Graph; Pie Chart is below. 
9			//oChartSpace.Charts[0].Type = ChartChartTypeEnum.chChartTypePieExploded3D;
10
11			oChartSpace.Charts[0].HasTitle = true;
12			oChartSpace.Charts[0].SeriesCollection.Add(0);
13			oChartSpace.Charts[0].SeriesCollection[0].SetData(ChartDimensionsEnum.chDimCategories,
14			Convert.ToInt32(ChartSpecialDataSourcesEnum.chDataLiteral), names);
15			oChartSpace.Charts[0].SeriesCollection[0].SetData(ChartDimensionsEnum.chDimValues,
16			Convert.ToInt32(ChartSpecialDataSourcesEnum.chDataLiteral), totals);
17
18			oChartSpace.Charts[0].SeriesCollection[0].Explosion = 20;
19			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection.Add();
20			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage = false;
21			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue = true;
22			//oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasCategoryName = true;
23			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Separator = "\n";
24			string caption = Session["ScriptName"].ToString();
25            if (txtMaxChartEntries.Visible)
26            {
27                caption += " (Top " + txtMaxChartEntries.Text + " table entries displayed)";
28            }
29            caption += " From: " + txtFromDate.Text + " To: " + txtToDate.Text;
30            oChartSpace.Charts[0].SeriesCollection[0].Caption = caption;
31			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Name = "verdana";
32			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Size = 7;
33			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Bold = true;
34			oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Color = "red";
35
36			string fileName = DateTime.Now.Ticks + ".gif";
37			string strFullPath = Server.MapPath(".\\");
38			string strFullPathAndName = Server.MapPath(fileName);
39			Session["ChartImageFilePath"] = strFullPathAndName;
40			RemoveFiles(strFullPath);
41			oChartSpace.ExportPicture(strFullPathAndName, "gif", chartWidth, chartHeight);
42			string url = "http://localhost/LogAnalysis/";
43			imgChart.ImageUrl = url + fileName;
44			Session["ChartImageUrl"] = imgChart.ImageUrl;
45			myZedChart.Visible = true;
46		}
Usage
Names and totals arguments are comma delimited strings of the things to chart.