將Excel資料匯入c#的datagridview

來源:互聯網
上載者:User

標籤:excel匯入c#

//需要引入的命名空間

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);//捕捉異常

                }

            }

        }


本文出自 “無聊生活_積極面對” 部落格,請務必保留此出處http://321331.blog.51cto.com/311331/1919852

將Excel資料匯入c#的datagridview

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.