Excel导入DataSet

OpenFileDialog openFileDialog1 = new OpenFileDialog();
           // this.SetStyle("Table");
            string file="";
            openFileDialog1.Filter = "Excel数据文件|*.xls";
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                file = openFileDialog1.FileName;
                try
                {
                    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + ";" + "Extended Properties=Excel 8.0;";
                    OleDbConnection conn = new OleDbConnection(strConn);
                    conn.Open();
                    OleDbDataAdapter myCommand = null;
                    DataSet ds = null;
                    string strExcel = "select * from [" + "sheet1"+ "$]";
                    myCommand = new OleDbDataAdapter(strExcel, strConn);
                    ds = new DataSet();
                    myCommand.Fill(ds, "sheet1");
                    conn.Close();
                    dataGridView1.DataSource = ds.Tables[0];
                }
                catch (Exception loErr)
                {
                   MessageBox.Show(loErr.Message);
                }

            } 

你可能感兴趣的:(Excel导入DataSet)