|
using System ; using System.Drawing ; using System.Collections ; using System.ComponentModel ; using System.Windows.Forms ; using System.Data ; using System.Data.OleDb ; public class Form1 : Form { private Button button1 ; private System.Data.DataSet myDataSet ; private DataGrid DataGrid1 ; private System.ComponentModel.Container components = null ;
public Form1 ( ) { file://初始化窗体中的各个组件 InitializeComponent ( ) ; file://打开数据链接,得到数据集 GetConnect ( ) ; } file://清除程序中使用过的资源 protected override void Dispose ( bool disposing ) { if ( disposing ) { if ( components != null ) { components.Dispose ( ) ; } } base.Dispose ( disposing ) ; }
private void GetConnect ( ) { file://创建一个数据链接 string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = c:\\sample.xls;Extended Properties=Excel 8.0" ; OleDbConnection myConn = new OleDbConnection ( strCon ) ; string strCom = " SELECT * FROM [Sheet1$] " ; myConn.Open ( ) ; file://打开数据链接,得到一个数据集 OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ; file://创建一个 DataSet对象 myDataSet = new DataSet ( ) ; file://得到自己的DataSet对象 myCommand.Fill ( myDataSet , "[Sheet1$]" ) ; file://关闭此数据链接 myConn.Close ( ) ; } private void InitializeComponent ( ) { DataGrid1 = new DataGrid ( ) ; button1 = new Button ( ) ; SuspendLayout ( ) ; DataGrid1.Name = "DataGrid1"; DataGrid1.Size = new System.Drawing.Size ( 400 , 200 ) ;
button1.Location = new System.Drawing.Point ( 124 , 240 ) ; button1.Name = "button1" ; button1.TabIndex = 1 ; button1.Text = "读取数据" ; button1.Size = new System.Drawing.Size (84 , 24 ) ; button1.Click += new System.EventHandler ( this.button1_Click ) ;
this.AutoScaleBaseSize = new System.Drawing.Size ( 6 , 14 ) ; this.ClientSize = new System.Drawing.Size ( 400 , 280 ) ; this.Controls.Add ( button1 ) ; this.Controls.Add ( DataGrid1 ) ; this.Name = "Form1" ; this.Text = "读取Excle表格中的数据,并用DataGrid显示出来!" ; this.ResumeLayout ( false ) ;
} private void button1_Click ( object sender , System.EventArgs e ) { DataGrid1.DataMember= "[Sheet1$]" ; DataGrid1.DataSource = myDataSet ;
} static void Main ( ) { Application.Run ( new Form1 ( ) ) ; } } |