我踏月色而来(wd900)

-只是用来记事, 而且是不重要的事.:)

博客园 首页 新随笔 联系 订阅 管理

 C#读取Excel文件数据    
相当简单,Excel就像数据库,每个Sheet就是一个Table. Microsoft.Jet.OLEDB驱动.
之后是DataReader循环,或DataSet处理都非常简单.

HTTP://BLOG.CSDN.NET/CRABO/
注意:数据类型的转换!!

#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

 

posted on 2007-11-29 12:36  wd900  阅读(1924)  评论(1编辑  收藏  举报