1. 程式人生 > >C#讀取Excel檔案資料

C#讀取Excel檔案資料

相當簡單,Excel就像資料庫,每個Sheet就是一個Table. Microsoft.Jet.OLEDB驅動.
之後是DataReader迴圈,或DataSet處理都非常簡單.

#region set connection
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+this.txtPath.Text+";Extended Properties=Excel 8.0;";
myDataReader = null;
craboDbConnection = new OleDbConnection(strConn);
OleDbCommand myOleDbCommand = new OleDbCommand("SELECT * FROM [Sheet1$

]", myOleDbConnection);
#endregion

try
{
myOleDbConnection.Open();
myDataReader = myOleDbCommand.ExecuteReader();
while (myDataReader.Read())
{
this.txtSeq.Text=Convert.ToString(myDataReader.GetValue(0));//列1
this.txtName.Text=Convert.ToString(myDataReader.GetValue(1));//列2
this.txtPIN.Text=Convert.ToString(myDataReader.GetValue(2));//列3
}
}
#region Catch
catch(System.Threading.ThreadAbortException e)
{
System.Threading.Thread.ResetAbort();
this.lblResult.Text = "執行緒被中斷..."+e.Message;
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
finally
{
// Always call Close when done reading.
if (myDataReader != null)
myDataReader.Close();

// Close the connection when done with it.
if (craboDbConnection!=null && craboDbConnection.State == ConnectionState.Open)
craboDbConnection.Close();

if(webResponse!=null)
webResponse.Close();
}
#endregion

引自:http://tb.blog.csdn.net/TrackBack.aspx?PostId=547149