天天看點

用資料庫通路的方法解決從excel大量導入資料

  要從excel裡面導入資料島程式裡面,如果用一般方法 在數量很大的情況下 可能耗費很長的時間。  在網上查詢了一些資料獲得了一個執行效率相當高的方法,現在寫下來以友善以後知識的整理。

   要用這個方法 首先得知道OLEDB。 OLEDB(Object Linking and Embedding,Database,又稱為

OLE

DB

或OLE-DB),一個基于COM的資料存儲對象,能提供對所有類型的資料的操作,甚至能在離線的情況下存取資料。

我覺得oledb主要讓我認識到所有的資料源我們都可以當做資料庫來處理, 建立連接配接 ,打開連接配接,執行語句,關閉連接配接。 

下面付下自己寫的小程式的一小段原代碼。

try
            {
                string[] res = excelFile.Split('.');
                //擷取全部資料
                //建立對excel的連接配接
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + excelFile + ";" + "Extended Properties=Excel 8.0;";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                //擷取sheet name
                string sheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();

                string strExcel = "";
                OleDbDataAdapter myAdapter = null;
                strExcel = string.Format("select * from [{0}]", sheetName);
                myAdapter = new OleDbDataAdapter(strExcel, strConn);
                myAdapter.Fill(ds);
                resLab.Text = "導入完成";
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }