sqlServer连接Excel代码

来源:互联网 发布:汽车网络直销 编辑:程序博客网 时间:2024/05/22 05:01

                   private void button1_click()

                   {

                            try

                            {

                                     if(this.dataSet1.Tables.Count>0)

                                     {

                                               this.dataSet1.Tables[0].Rows.Clear();

                                     }

                                     string filename ="";                           

                                     DialogResult result =openFileDialog1.ShowDialog();

                                     if( result == DialogResult.OK )

                                     {

                                               filename=openFileDialog1.FileName;

                                               lbl_path.Text=filename;

                                                      

                           

                                               string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; " + "Data Source =" + filename + ";Extended Properties=Excel 8.0";

                                               OleDbConnection myConn = new OleDbConnection(strCon);

                                               myConn.Open();

                                               string strCom = "Select * FROM [Sheet1$] ";

                                               OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);

                           

                                               myCommand.Fill(dataSet1, "[Sheet1$]");

                                               myConn.Close();

   

                                               mygrid.SetDataBinding(dataSet1, "[Sheet1$]");

 

                                               this.BT_ScreenOut.Enabled = true;

                                               this.btn_Insert.Enabled = false;

                                     }

                            }

                            catch(System.Exception e)

                            {

                                     MessageBox.Show(e.Message);

                            }

                            }