程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Visual C#的Excel編程(2)

Visual C#的Excel編程(2)

編輯:關於C語言
3).用Visual C#讀取Excel表格,並用DataGrid顯示出來的程序代碼(Read.cs)和程序運行的界面:

掌握了上面二點,水到渠成就可以得到以下代碼:

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 ( ) ) ;
}
}

下圖是程序編譯後,運行結果:

圖01:用Visual C#讀取"c:\sample.xls"的運行界面

(4).總結:

以上只是讀取了Excel表格中"Sheet1"中的數據,對於其他"Sheet"中的內容,可以參照讀取"Sheet1"中的程序,只作一點修改就可以了,譬如要讀取"Sheet2"中的內容,只需要把"Read.cs"程序中的"Sheet1$"改成"Sheet2$"就可以了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved