2012年12月29日土曜日

C# でExcelからチャートを作成


C# でExcelファイルからチャートを作成するサンプルです。
予め、chart1 という名前のチャートコントロールをフォームに配置しておきます。\temp.xls というExcelファイルのシート名6954の領域B1~D250に表が作成されている状態で実行します。(1行目の領域B1~D1には、hiduke,svalue,hvalue などのフィールド名が記述されています。実際の数値は領域B2~D250に記述されています。)


private void Form1_Load(object sender, EventArgs e)
{
// The Excel file name
string fileNameString = "\\temp.xls";
// Create connection object by using the preceding connection string.
string sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileNameString + ";Extended Properties=\"Excel 8.0;HDR=YES\"";
OleDbConnection myConnection = new OleDbConnection( sConn );
myConnection.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
OleDbCommand myCommand = new OleDbCommand( "Select * From [6954$B1:D250]", myConnection );
// create a database reader
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Populate the chart with data in the file
chart1.DataBindTable(myReader, "hiduke");
//chart1.Series[0].ChartType = SeriesChartType.Line;
chart1.Series["svalue"].ChartType = SeriesChartType.Line;
chart1.Series["hvalue"].ChartType = SeriesChartType.Line;
// close the reader and the connection
myReader.Close();
myConnection.Close();
}
view raw gistfile1.cs hosted with ❤ by GitHub



0 件のコメント:

コメントを投稿