將Excel數據導入c#的datagridview

//需要引入的命名空間

using System.Runtime.InteropServices;//獲取鼠標事件

using System.IO;

using System.Data.OleDb;


//核心代碼

 private void button1_Click(object sender, EventArgs e)

        {

OpenFileDialog ofd = new OpenFileDialog();//首先根據打開文件對話框,選擇要打開的文件

            ofd.Filter = "Excel表格|*.xlsx|Excel97-2003表格|*.xls|所有文件|*.*";//打開文件對話框篩選器,默認顯示文件類型

            string strPath;//定義文件路徑

            if (ofd.ShowDialog() == DialogResult.OK)

            {

                try

                {

                    strPath = ofd.FileName;

                    //string sss = ofd.SafeFileName;//獲取文件名稱

                    string fileType = System.IO.Path.GetExtension(strPath);//獲取文件的後綴

                    string strCon = "";

                    if (fileType == ".xls")//如果爲97-2003格式文件

                    {

                        strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";

                    }

                    else//如果爲2007格式文件

                    {

                        strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+strPath+";Extended Properties='Excel 12.0;HDR=YES;IEMX=1'";

                    }

                    OleDbConnection conn=new OleDbConnection(strCon);

                    Application.DoEvents();

                    string strSql = "select * from [Sheet1$]";

                    OleDbCommand Cmd= new OleDbCommand(strSql,conn);

                    OleDbDataAdapter da = new OleDbDataAdapter(Cmd);

                    DataSet ds = new DataSet();

                    da.Fill(ds,"插入表");

                    dataGridView1.DataSource=ds.Tables[0];

                    dataGridView1.AllowUserToAddRows = false;

                    dataGridView1.AllowUserToDeleteRows = false;

                    //MessageBox.Show(sss);


                }

                catch (Exception ex)

                {


                    MessageBox.Show(ex.Message);//捕捉異常

                }

            }

        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章