C 將Excel資料表匯入SQL資料庫的兩種方法

2021-08-26 22:33:34 字數 2182 閱讀 6017

實現在c#中可高效的將excel資料匯入到sqlserver資料庫中,很多人通過迴圈來拼接sql,這樣做不但容易出錯而且效率低下,最好的辦法是使用bcp,也就是system.data.sqlclient.sqlbulkcopy 類來實現。

using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.data.oledb; namespace exceltosql private void button1_click(object sender, eventargs e) } public void transferdata(string excelfile, string sheetname, string connectionstring) $]", sheetname); mycommand = new oledbdataadapter(strexcel, strconn); mycommand.fill(ds, sheetname); //如果目標表不存在則建立,excel檔案的第一行為列標題,從第二行開始全部都是資料記錄 string strsql = string.format("if not exists(select * from sysobjects where name = '') create table (", sheetname); //以sheetname為表名 foreach (system.data.datacolumn c in ds.tables[0].columns) ] varchar(255),", c.columnname); } strsql = strsql.trim(',') + ")"; using (system.data.sqlclient.sqlconnection sqlconn = new system.data.sqlclient.sqlconnection(connectionstring)) //用bcp匯入資料 //excel檔案中列的順序必須和資料表的列順序一致,因為資料匯入時,是從excel檔案的第二行資料開始,不管資料表的結構是什麼樣的,反正就是第一列的資料會插入到資料表的第一列欄位中,第二列的資料插入到資料表的第二列欄位中,以此類推,它本身不會去判斷要插入的資料是對應資料表中哪乙個欄位的 using (system.data.sqlclient.sqlbulkcopy bcp = new system.data.sqlclient.sqlbulkcopy(connectionstring)) } catch (exception ex) } //進度顯示 void bcp_sqlrowscopied(object sender, system.data.sqlclient.sqlrowscopiedeventargs e) } }

先將excel檔案轉換成datatable,然後再迴圈將記錄插入到資料庫表中,這種方式可以任由程式設計師來選擇將哪列資料匯入到資料表的哪個欄位中

using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.data.oledb; using system.data.sqlclient; namespace exceltosql datatable dt = new datatable(); string connstring = "server = (local); uid = sa; pwd = sa; database = db_test"; sqlconnection conn; private void button1_click(object sender, eventargs e) } private void bind(string filename) catch (exception err) } //將datagridview1的記錄插入到資料庫 private void button2_click(object sender, eventargs e) conn.close(); messagebox.show("匯入成功!"); } else } private void inserttosql(datarow dr) } }

C 將Excel資料表匯入SQL資料庫的兩種方法

最近用寫個winform程式想用excel 檔案匯入資料庫中,網上尋求辦法,找到了這個經過嘗試可以使用。方法一 實現在c 中可高效的將excel資料匯入到sqlserver資料庫中,很多人通過迴圈來拼接sql,這樣做不但容易出錯而且效率低下,最好的辦法是使用bcp,也就是system.data.sq...

將excel 檔案匯入access資料表

dim conn asnew oledbconnection my.settings.connstr datawarehouse.mdb dimcomm asoledbcommand conn.createcommand comm.commandtext insert into tablename ...

sql server 匯入Excel資料表

乙個挺簡單的功能,竟然弄了一下午,現在來總結一下吧。其實最開始的問題是sql server 安裝的不完整,後面的問題是目標資料來源型別不正確。開始時用的是sql server 2005,安裝時有好多功能沒有選,但後來給忘了,一直提示沒有ssis 沒有安裝,就開始在網上查這是個什麼東西,後來知道了是s...