怎么样使用C#绘柱形图?

怎么样使用C#绘柱形图?

简介:
owc控件是microsoftoffice图表控件(owc10为ofiiceXP的组件、owc11为office2003的组件,组件的路径为C:/ProgramFiles/CommonFiles/MicrosoftShared/WebComponents/11/owc11,帮助文件的路径为C:/ProgramFiles/CommonFiles/MicrosoftShared/WebComponents/11/2052),它可以生成三维图、柱状图、饼状图、趋势图和误差图
--------------------------------------------------------------------------------
相关资料:
--------------------------------------------------------------------------------
怎么样使用C#绘柱形图? 引用内容
Office2003加载项:OfficeWebComponents官方下载地址(OWC11)

http://www.microsoft.com/downloads/details.aspx?FamilyID=7287252c-402e-4f72-97a5-e0fd290d4b76&DisplayLang=zh-cn

如果您机器里完全安装OFFICE2003则不需要下载

--------------------------------------------------------------------------------
怎么样使用C#绘柱形图? 引用内容
获取并安装Office2003主interop程序集(PIA)和如何对其进行引用以及疑难解答

http://www.microsoft.com/china/msdn/library/office/office/OfficePrIntopAssFAQ.mspx?mfr=true

--------------------------------------------------------------------------------
相关代码(本代码主要功能类来自博客园)
--------------------------------------------------------------------------------
usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingMicrosoft.Office.Interop.Owc11;
usingSystem.IO;
usingMicrosoft.Office.Interop;
usingOWC11=Microsoft.Office.Interop.Owc11;
usingSystem.Text;





publicclassChartFactory
{
publicChartFactory()
{
InitTypeMap();
//
//TODO:在此处添加构造函数逻辑
//
}

privatestring[]chartCategoriesArr;
privatestring[]chartValuesArr;
privateOWC11.ChartChartTypeEnumchartType=OWC11.ChartChartTypeEnum.chChartTypeColumn3D;//默认值
privatestaticHashtablechartMap=newHashtable();
privatestaticstringchartTypeCh="垂直柱状统计图";
privatestaticstringchartTitle="aaa";

privatevoidInitTypeMap()
{
chartMap.Clear();
OWC11.ChartChartTypeEnum[]chartTypes=newOWC11.ChartChartTypeEnum[]{
ChartChartTypeEnum.chChartTypeColumnClustered,
ChartChartTypeEnum.chChartTypeColumn3D,
ChartChartTypeEnum.chChartTypeBarClustered,
ChartChartTypeEnum.chChartTypeBar3D,
ChartChartTypeEnum.chChartTypeArea,
ChartChartTypeEnum.chChartTypeArea3D,
ChartChartTypeEnum.chChartTypeDoughnut,
ChartChartTypeEnum.chChartTypeLineStacked,
ChartChartTypeEnum.chChartTypeLine3D,
ChartChartTypeEnum.chChartTypeLineMarkers,
ChartChartTypeEnum.chChartTypePie,
ChartChartTypeEnum.chChartTypePie3D,
ChartChartTypeEnum.chChartTypeRadarSmoothLine,
ChartChartTypeEnum.chChartTypeSmoothLine};
string[]chartTypesCh=newstring[]{"垂直柱状统计图","3D垂直柱状统计图","水平柱状统计图","3D水平柱状统计图","区域统计图","3D区域统计图","中空饼图","折线统计图","3D折线统计图","折线带点统计图","饼图","3D饼图","网状统计图","弧线统计图"};

for(inti=0;i<chartTypes.Length;i++)
{
chartMap.Add(chartTypesCh[i],chartTypes[i]);
}
}
publicChartSpaceClassBuildCharts()
{
stringchartCategoriesStr=String.Join("/t",chartCategoriesArr);
stringchartValuesStr=String.Join("/t",chartValuesArr);

OWC11.ChartSpaceClassoChartSpace=newOWC11.ChartSpaceClass();

//------------------------------------------------------------------------
//Givepieanddoughnutchartsalegendonthebottom.Fortherestof
//themletthecontrolfigureitoutonitsown.
//------------------------------------------------------------------------

chartType=(ChartChartTypeEnum)chartMap[chartTypeCh];

if(chartType==ChartChartTypeEnum.chChartTypePie||
chartType==ChartChartTypeEnum.chChartTypePie3D||
chartType==ChartChartTypeEnum.chChartTypeDoughnut)
{
oChartSpace.HasChartSpaceLegend=true;
oChartSpace.ChartSpaceLegend.Position=ChartLegendPositionEnum.chLegendPositionBottom;
}

oChartSpace.Border.Color="blue";
oChartSpace.Charts.Add(0);
oChartSpace.Charts[0].HasTitle=true;
oChartSpace.Charts[0].Type=chartType;
oChartSpace.Charts[0].ChartDepth=125;
oChartSpace.Charts[0].AspectRatio=80;
oChartSpace.Charts[0].Title.Caption=chartTitle;
oChartSpace.Charts[0].Title.Font.Bold=true;

//绘图区背景颜色
//oChartSpace.Charts[0].PlotArea.Interior.Color="red";
//绘图区
//oChartSpace.Charts[0].PlotArea.Floor.Interior.Color="green";

oChartSpace.Charts[0].SeriesCollection.Add(0);
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection.Add();
//柱状图颜色
//oChartSpace.Charts[0].SeriesCollection[0].Interior.Color="red";

//------------------------------------------------------------------------
//Ifyou'rechartingapieoravariationthereofpercentagesmakealot
//moresensethanvalues...
//------------------------------------------------------------------------
if(chartType==ChartChartTypeEnum.chChartTypePie||
chartType==ChartChartTypeEnum.chChartTypePie3D||
chartType==ChartChartTypeEnum.chChartTypeDoughnut)
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage=true;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue=false;
}
//------------------------------------------------------------------------
//Notsoforothercharttypeswherevalueshavemoremeaningthan
//percentages.
//------------------------------------------------------------------------
else
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage=false;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue=true;
}

//------------------------------------------------------------------------
//Plugyourownvisualbellsandwhistleshere
//------------------------------------------------------------------------
oChartSpace.Charts[0].SeriesCollection[0].Caption=String.Empty;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Name="verdana";
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Size=10;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Bold=true;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Color="red";
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Position=ChartDataLabelPositionEnum.chLabelPositionCenter;

if(chartType==ChartChartTypeEnum.chChartTypeBarClustered||
chartType==ChartChartTypeEnum.chChartTypeBar3D||
chartType==ChartChartTypeEnum.chChartTypeColumnClustered||
chartType==ChartChartTypeEnum.chChartTypeColumn3D)
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Position=ChartDataLabelPositionEnum.chLabelPositionOutsideEnd;
}

oChartSpace.Charts[0].SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimCategories,
Convert.ToInt32(OWC11.ChartSpecialDataSourcesEnum.chDataLiteral),chartCategoriesStr);

oChartSpace.Charts[0].SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimValues,
Convert.ToInt32(OWC11.ChartSpecialDataSourcesEnum.chDataLiteral),chartValuesStr);

returnoChartSpace;
}

#region属性设置
publicstring[]chartCategoriesArrValue
{
get
{
returnchartCategoriesArr;
}
set
{
chartCategoriesArr=value;
}
}

publicstring[]chartValuesArrValue
{
get
{
returnchartValuesArr;
}
set
{
chartValuesArr=value;
}
}
publicstringchartTypeValue
{
get
{
returnchartTypeCh;
}
set
{
chartTypeCh=value;
}
}
publicstringchartTitleValue
{
get
{
returnchartTitle;
}
set
{
chartTitle=value;
}
}
#endregion
}





调用方法部分代码:
privatevoidForm1_Load(objectsender,System.EventArgse)
{
try
{
System.Threading.Threadthread=newSystem.Threading.Thread(newSystem.Threading.ThreadStart(aa));
thread.Start();
//ShowChart();
}
catch
{}


}

voidaa()
{

while(true)
{
ShowChart();
System.Threading.Thread.Sleep(1000);
}
}


//调用首先需要在页面上放置一个pictureBox1来显示产生的统计图

publicvoidShowChart()
{
try
{
stringConnString="DataSource=SQL服务器地址;InitialCatalog=数据库名;PersistSecurityInfo=True;UserID=用户名;Password=密码";
DB.sqlDBdb=newDB.sqlDB(ConnString);
stringsql="查询字符串";
DataTabletable=db.getTable(sql);
if(table!=null&&table.Rows.Count>0)
{

StringBuildersb=newStringBuilder();
for(inti=0;i<table.Rows.Count;i++)
{
if(i==0)
{
sb.Append(table.Rows[i]["content"].ToString());
}
else
{
sb.Append(","+table.Rows[i]["content"].ToString());
}

}
string[]CategoriesArr={sb.ToString()};

sb=newStringBuilder();


for(inti=0;i<table.Rows.Count;i++)
{
if(i==0)
{
sb.Append(table.Rows[i]["cnt"].ToString());
}
else
{
sb.Append(","+table.Rows[i]["cnt"].ToString());
}

}
string[]ValuesArr={sb.ToString()};

ChartFactorychartFactory=newChartFactory();
//初始化赋值
chartFactory.chartCategoriesArrValue=CategoriesArr;
chartFactory.chartValuesArrValue=ValuesArr;
chartFactory.chartTitleValue="“龙源夜、网通情”欢送毕生晚会节目投票";//柱形图标注名称
chartFactory.chartTypeValue="垂直柱状统计图";//图类型,在类中定义过

OWC11.ChartSpaceClassoChartSpace=chartFactory.BuildCharts();
stringpath=FileName;//产生图片并保存页可以是pnggif图片

oChartSpace.ExportPicture(path,"jpeg",this.Width-100,this.Height-100);//后面是图片的宽和高

//下面使用FileStream对象的原因是本例使用线程.每秒重新生成一个图,并将原图覆盖.
//如果不使用FileStream将会出现共享冲突.
FileStreamfs=newFileStream(FileName,FileMode.Open,FileAccess.Read);
byte[]bytes=newbyte[fs.Length];
fs.Read(bytes,0,bytes.Length);
fs.Close();
MemoryStreamms=newMemoryStream(bytes);


System.Drawing.Imageimg=System.Drawing.Image.FromStream(ms);
//本例使用pictureBox1显示图片
this.pictureBox1.Image=img;
this.pictureBox1.Refresh();


}
}
catch(Exceptione)
{//MessageBox.Show(e.ToString());
}

}











------------------------------------------------------------------------------------------
另外一处类似代码,仅供参考.

publicclassChartLine3:System.Web.UI.Page
{

publicstringtoChartLine3(DataSetmyDataSet,stringYValue,stringSeries,stringxTitle,stringyTitle,stringChartTitle)
{

//创建ChartSpace对象来放置图表

OWC11.ChartSpaceobjCSpace=newOWC11.ChartSpaceClass();

//在ChartSpace对象中添加图表,Add方法返回chart对象

OWC11.ChChartobjChart=objCSpace.Charts.Add(0);



//指定图表的类型。类型由OWC11.ChartChartTypeEnum枚举值得到

objChart.Type=OWC11.ChartChartTypeEnum.chChartTypeColumnClustered;



//给定标题

objChart.HasTitle=true;

//objChart.Title.Caption=ChartNmae;



//给定x,y轴的图示说明

objChart.Title.Caption=ChartTitle;



//给定x,y轴的图示说明

objChart.Axes[0].HasTitle=true;

objChart.Axes[0].Title.Caption=xTitle;

objChart.Axes[1].HasTitle=true;

objChart.Axes[1].Title.Caption=yTitle;



//计算数据

//objCSpace.DataSource=(msdatasrc.DataSource)dataSet;





if(Series!="")
{



//指定图表是否需要图例

objChart.HasLegend=true;

string[]Ser=Series.ToString().Split(',');

string[]Ser1=Series.ToString().Split(',');



string[]YValue_temp=YValue.ToString().Split(',');

string[]strValue=newstring[YValue_temp.Length];

string[]strCategory=newstring[YValue_temp.Length];

//循环数据集得到不重复的序列名

for(inti=0;i<=Ser.Length-1;i++)
{

//把第一行的Ser[i]列放入字符串

stringSeries1=myDataSet.Tables[0].Rows[0][Ser[i]].ToString();





//循环数据集得出与字符串内不同的Ser[i]值,放入字符串

for(intj=1;j<=myDataSet.Tables[0].Rows.Count-1;j++)
{

//将字符串分割成数组

string[]Series11=Series1.Split(',');

intk=0;

//将数据集各行的Ser[i]值与分割后的数组中的每个值循环比较,都不同的话加到字符串中

for(intw=0;w<=Series11.Length-1;w++)
{

//如果与字符串中的某个值相等k增加1

if(myDataSet.Tables[0].Rows[j][Ser[i]].ToString()==Series11[w])k++;



}

//k不等0说明没有重复的项,将该行此项添加进字符串

if(k==0)Series1+=","+myDataSet.Tables[0].Rows[j][Ser[i]].ToString();

}

//将最后得出的不重复的某序列存进数组

Ser[i]=Series1;



}

intv_num=1;

//得出动态数组的长度个序列值个数的乘积

for(inti=0;i<=Ser.Length-1;i++)
{

string[]v_str=Ser[i].Split(',');

v_num=v_num*v_str.Length;

}

string[]v_str_all=newstring[v_num];//定义存放序列的数组.

stringtemp="";

intv_j=0;



if(Ser.Length==1)
{

for(inti=0;i<=Ser.Length-1;i++)
{

string[]v_str=Ser[i].Split(',');

for(intj=0;j<=v_str.Length-1;j++)
{

for(intk=v_num-1;k>=0;k--)
{

intv_step=v_num/v_str.Length;

if((k>=j*(v_step))&&(k<(j+1)*v_step))



//if(k%v_str.Length==0)
{

v_str_all[k]=v_str_all[k]+v_str[j]+"-";

}



}

}

}

}

else
{

for(inti=1;i<=Ser.Length-1;i++)
{

if(i!=1)Ser[0]=Ser[0].Substring(0,Ser[0].Length-1);

string[]ser1=Ser[0].Split(',');

Ser[0]="";

for(intj=0;j<=ser1.Length-1;j++)
{

string[]ser2=Ser[i].Split(',');

for(intk=0;k<=ser2.Length-1;k++)
{

Ser[0]+=ser1[j]+"-"+ser2[k]+",";

}

}

}

Ser[0]=Ser[0].Substring(0,Ser[0].Length-1);

}



v_str_all=Ser[0].Split(',');

if(Ser.Length==1)
{

for(intk=0;k<v_str_all.Length;k++)
{

v_str_all[k]=v_str_all[k].Substring(0,v_str_all[k].Length-1);

}

}



stringSeriestemp="";





for(intj=0;j<=myDataSet.Tables[0].Rows.Count-1;j++)
{

Seriestemp="";

for(intw=0;w<=Ser1.Length-1;w++)
{



Seriestemp+=myDataSet.Tables[0].Rows[j][Ser1[w]].ToString()+"-";



}

Seriestemp=Seriestemp.Substring(0,Seriestemp.Length-1);

for(inti=0;i<=v_str_all.Length-1;i++)
{

if(Seriestemp==v_str_all[i])
{



for(intq=0;q<=YValue_temp.Length-1;q++)
{



strValue[q]+=myDataSet.Tables[0].Rows[j][YValue_temp[q]].ToString()+'/t';

strCategory[q]+=v_str_all[i]+'/t';

}

}

}





}









//添加一个series

string[]YValue1=YValue.ToString().Split(',');



for(inti=0;i<=strCategory.Length-1;i++)
{

objChart.SeriesCollection.Add(i);





//给定series的名字

objChart.SeriesCollection[i].SetData(OWC11.ChartDimensionsEnum.chDimSeriesNames,

+(int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral,YValue1[i]);



//给定分类

objChart.SeriesCollection[i].SetData(OWC11.ChartDimensionsEnum.chDimCategories,

+(int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral,strCategory[i]);



//给定值

objChart.SeriesCollection[i].SetData

(OWC11.ChartDimensionsEnum.chDimValues,

(int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral,strValue[i]);

}



}





//输出成GIF文件.

//stringstrAbsolutePath=(Server.MapPath("."))+"//test1.gif";

RandomvRandom=newRandom();

intvRandomInt=vRandom.Next(10000,30000);

stringvRandomStr=vRandomInt.ToString();

vRandomInt=vRandom.Next(10000,30000);

vRandomStr=vRandomStr+vRandomInt.ToString();

stringstrAbsolutePath=(Server.MapPath("."))+"//images//"+vRandomStr+".gif";

objCSpace.ExportPicture(strAbsolutePath,"GIF",640,480);



//创建GIF文件的相对路径.

stringstrRelativePath="images/"+vRandomStr+".gif";



//把图片添加到placeholder.

stringstrImageTag="<IMGSRC='"+strRelativePath+"'/>";

returnstrImageTag;

}



}



---------------------------------------------------------------------------------
调用方式举例

//调用在页面上打印一个Image来显示产生的统计图
publicvoidShowChartLine3()
{
DataSetds=newDataSet();
ds.Tables.Add("Table1");
ds.Tables[0].Columns.Add("abc");
ds.Tables[0].Columns.Add("bcd");
ds.Tables[0].Rows.Add();
for(inti=101;i<120;i++)
{
DataRowrow=ds.Tables[0].NewRow();
row["abc"]=i.ToString();
row["bcd"]=(i+5).ToString();
ds.Tables[0].Rows.Add(row);
}


ChartLine3ch=newChartLine3();
Response.Write(ch.toChartLine3(ds,"bcd,abc","abc,bcd","参赛选手","票数","在线投票系统"));
}
}